Passed
Push — master ( 222e44...208bd5 )
by Alxarafe
31:22
created
dolibarr/htdocs/contrat/class/api_contracts.class.php 3 patches
Indentation   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -17,9 +17,9 @@  discard block
 block discarded – undo
17 17
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 18
  */
19 19
 
20
- use Luracast\Restler\RestException;
20
+    use Luracast\Restler\RestException;
21 21
 
22
- require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
22
+    require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
23 23
 
24 24
 /**
25 25
  * API class for contracts
@@ -35,9 +35,9 @@  discard block
 block discarded – undo
35 35
      */
36 36
     static $FIELDS = array(
37 37
         'socid',
38
-    	'date_contrat',
39
-    	'commercial_signature_id',
40
-    	'commercial_suivi_id'
38
+        'date_contrat',
39
+        'commercial_signature_id',
40
+        'commercial_suivi_id'
41 41
     );
42 42
 
43 43
     /**
@@ -50,8 +50,8 @@  discard block
 block discarded – undo
50 50
      */
51 51
     function __construct()
52 52
     {
53
-		global $db, $conf;
54
-		$this->db = $db;
53
+        global $db, $conf;
54
+        $this->db = $db;
55 55
         $this->contract = new Contrat($this->db);
56 56
     }
57 57
 
@@ -67,21 +67,21 @@  discard block
 block discarded – undo
67 67
      */
68 68
     function get($id)
69 69
     {
70
-		if(! DolibarrApiAccess::$user->rights->contrat->lire) {
71
-			throw new RestException(401);
72
-		}
70
+        if(! DolibarrApiAccess::$user->rights->contrat->lire) {
71
+            throw new RestException(401);
72
+        }
73 73
 
74 74
         $result = $this->contract->fetch($id);
75 75
         if( ! $result ) {
76 76
             throw new RestException(404, 'Contract not found');
77 77
         }
78 78
 
79
-		if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
80
-			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
81
-		}
79
+        if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
80
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
81
+        }
82 82
 
83 83
         $this->contract->fetchObjectLinked();
84
-		return $this->_cleanObjectDatas($this->contract);
84
+        return $this->_cleanObjectDatas($this->contract);
85 85
     }
86 86
 
87 87
 
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
      * @param string           $sqlfilters          Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
100 100
      * @return  array                               Array of contract objects
101 101
      *
102
-	 * @throws RestException
102
+     * @throws RestException
103 103
      */
104 104
     function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
105 105
     {
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
             {
137 137
                 throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
138 138
             }
139
-	        $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
139
+            $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
140 140
             $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
141 141
         }
142 142
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
         if( ! count($obj_ret)) {
176 176
             throw new RestException(404, 'No contract found');
177 177
         }
178
-		return $obj_ret;
178
+        return $obj_ret;
179 179
     }
180 180
 
181 181
     /**
@@ -186,9 +186,9 @@  discard block
 block discarded – undo
186 186
      */
187 187
     function post($request_data = null)
188 188
     {
189
-      if(! DolibarrApiAccess::$user->rights->contrat->creer) {
190
-			  throw new RestException(401, "Insuffisant rights");
191
-		  }
189
+        if(! DolibarrApiAccess::$user->rights->contrat->creer) {
190
+                throw new RestException(401, "Insuffisant rights");
191
+            }
192 192
         // Check mandatory fields
193 193
         $result = $this->_validate($request_data);
194 194
 
@@ -222,15 +222,15 @@  discard block
 block discarded – undo
222 222
     {
223 223
         if(! DolibarrApiAccess::$user->rights->contrat->lire) {
224 224
             throw new RestException(401);
225
-		}
225
+        }
226 226
 
227 227
         $result = $this->contract->fetch($id);
228 228
         if( ! $result ) {
229 229
             throw new RestException(404, 'Contract not found');
230 230
         }
231 231
 
232
-		if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
233
-		    throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
232
+        if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
233
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
234 234
         }
235 235
         $this->contract->getLinesArray();
236 236
         $result = array();
@@ -253,18 +253,18 @@  discard block
 block discarded – undo
253 253
     function postLine($id, $request_data = null)
254 254
     {
255 255
         if(! DolibarrApiAccess::$user->rights->contrat->creer) {
256
-			throw new RestException(401);
257
-		}
256
+            throw new RestException(401);
257
+        }
258 258
 
259 259
         $result = $this->contract->fetch($id);
260 260
         if( ! $result ) {
261 261
             throw new RestException(404, 'Contract not found');
262 262
         }
263 263
 
264
-		if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
265
-			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
264
+        if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
265
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
266 266
         }
267
-		$request_data = (object) $request_data;
267
+        $request_data = (object) $request_data;
268 268
         $updateRes = $this->contract->addline(
269 269
             $request_data->desc,
270 270
             $request_data->subprice,
@@ -277,13 +277,13 @@  discard block
 block discarded – undo
277 277
             $request_data->date_start,			// date_start = date planned start, date ouverture = date_start_real
278 278
             $request_data->date_end,			// date_end = date planned end, date_cloture = date_end_real
279 279
             $request_data->HT,
280
-      		$request_data->subprice_excl_tax,
281
-      		$request_data->info_bits,
280
+                $request_data->subprice_excl_tax,
281
+                $request_data->info_bits,
282 282
             $request_data->fk_fournprice,
283
-			$request_data->pa_ht,
284
-      		$request_data->array_options,
285
-      		$request_data->fk_unit,
286
-      		$request_data->rang
283
+            $request_data->pa_ht,
284
+                $request_data->array_options,
285
+                $request_data->fk_unit,
286
+                $request_data->rang
287 287
         );
288 288
 
289 289
         if ($updateRes > 0) {
@@ -306,17 +306,17 @@  discard block
 block discarded – undo
306 306
     function putLine($id, $lineid, $request_data = null)
307 307
     {
308 308
         if(! DolibarrApiAccess::$user->rights->contrat->creer) {
309
-			throw new RestException(401);
310
-		}
309
+            throw new RestException(401);
310
+        }
311 311
 
312 312
         $result = $this->contract->fetch($id);
313 313
         if( ! $result ) {
314 314
             throw new RestException(404, 'Contrat not found');
315 315
         }
316 316
 
317
-		if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
318
-			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
319
-		}
317
+        if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
318
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
319
+        }
320 320
 
321 321
         $request_data = (object) $request_data;
322 322
 
@@ -328,12 +328,12 @@  discard block
 block discarded – undo
328 328
             $request_data->remise_percent,
329 329
             $request_data->date_ouveture_prevue,
330 330
             $request_data->date_fin_validite,
331
-      		$request_data->tva_tx,
331
+                $request_data->tva_tx,
332 332
             $request_data->localtax1_tx,
333 333
             $request_data->localtax2_tx,
334 334
             $request_data->date_ouverture,
335 335
             $request_data->date_cloture,
336
-      		'HT',
336
+                'HT',
337 337
             $request_data->info_bits,
338 338
             $request_data->fk_fourn_price,
339 339
             $request_data->pa_ht,
@@ -365,28 +365,28 @@  discard block
 block discarded – undo
365 365
      */
366 366
     function activateLine($id, $lineid, $datestart, $dateend = null, $comment = null)
367 367
     {
368
-    	if(! DolibarrApiAccess::$user->rights->contrat->creer) {
369
-    		throw new RestException(401);
370
-    	}
368
+        if(! DolibarrApiAccess::$user->rights->contrat->creer) {
369
+            throw new RestException(401);
370
+        }
371 371
 
372
-    	$result = $this->contract->fetch($id);
373
-    	if (! $result) {
374
-    		throw new RestException(404, 'Contrat not found');
375
-    	}
372
+        $result = $this->contract->fetch($id);
373
+        if (! $result) {
374
+            throw new RestException(404, 'Contrat not found');
375
+        }
376 376
 
377
-    	if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
378
-    		throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
379
-    	}
377
+        if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
378
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
379
+        }
380 380
 
381
-    	$updateRes = $this->contract->active_line(DolibarrApiAccess::$user, $lineid, $datestart, $dateend, $comment);
381
+        $updateRes = $this->contract->active_line(DolibarrApiAccess::$user, $lineid, $datestart, $dateend, $comment);
382 382
 
383
-    	if ($updateRes > 0) {
384
-    		$result = $this->get($id);
385
-    		unset($result->line);
386
-    		return $this->_cleanObjectDatas($result);
387
-    	}
383
+        if ($updateRes > 0) {
384
+            $result = $this->get($id);
385
+            unset($result->line);
386
+            return $this->_cleanObjectDatas($result);
387
+        }
388 388
 
389
-    	return false;
389
+        return false;
390 390
     }
391 391
 
392 392
     /**
@@ -403,30 +403,30 @@  discard block
 block discarded – undo
403 403
      */
404 404
     function unactivateLine($id, $lineid, $datestart, $comment = null)
405 405
     {
406
-    	if (! DolibarrApiAccess::$user->rights->contrat->creer) {
407
-    		throw new RestException(401);
408
-    	}
406
+        if (! DolibarrApiAccess::$user->rights->contrat->creer) {
407
+            throw new RestException(401);
408
+        }
409 409
 
410
-    	$result = $this->contract->fetch($id);
411
-    	if (! $result) {
412
-    		throw new RestException(404, 'Contrat not found');
413
-    	}
410
+        $result = $this->contract->fetch($id);
411
+        if (! $result) {
412
+            throw new RestException(404, 'Contrat not found');
413
+        }
414 414
 
415
-    	if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
416
-    		throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
417
-    	}
415
+        if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
416
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
417
+        }
418 418
 
419
-    	$request_data = (object) $request_data;
419
+        $request_data = (object) $request_data;
420 420
 
421
-    	$updateRes = $this->contract->close_line(DolibarrApiAccess::$user, $lineid, $datestart, $comment);
421
+        $updateRes = $this->contract->close_line(DolibarrApiAccess::$user, $lineid, $datestart, $comment);
422 422
 
423
-    	if ($updateRes > 0) {
424
-    		$result = $this->get($id);
425
-    		unset($result->line);
426
-    		return $this->_cleanObjectDatas($result);
427
-    	}
423
+        if ($updateRes > 0) {
424
+            $result = $this->get($id);
425
+            unset($result->line);
426
+            return $this->_cleanObjectDatas($result);
427
+        }
428 428
 
429
-    	return false;
429
+        return false;
430 430
     }
431 431
 
432 432
     /**
@@ -445,16 +445,16 @@  discard block
 block discarded – undo
445 445
     function deleteLine($id, $lineid)
446 446
     {
447 447
         if (! DolibarrApiAccess::$user->rights->contrat->creer) {
448
-			throw new RestException(401);
449
-		}
448
+            throw new RestException(401);
449
+        }
450 450
 
451 451
         $result = $this->contract->fetch($id);
452 452
         if (! $result) {
453 453
             throw new RestException(404, 'Contrat not found');
454 454
         }
455 455
 
456
-		if (! DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
457
-			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
456
+        if (! DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
457
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
458 458
         }
459 459
 
460 460
         // TODO Check the lineid $lineid is a line of object
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
         }
466 466
         else
467 467
         {
468
-      	    throw new RestException(405, $this->contract->error);
468
+                throw new RestException(405, $this->contract->error);
469 469
         }
470 470
     }
471 471
 
@@ -480,17 +480,17 @@  discard block
 block discarded – undo
480 480
     function put($id, $request_data = null)
481 481
     {
482 482
         if (! DolibarrApiAccess::$user->rights->contrat->creer) {
483
-			throw new RestException(401);
484
-		}
483
+            throw new RestException(401);
484
+        }
485 485
 
486 486
         $result = $this->contract->fetch($id);
487 487
         if (! $result) {
488 488
             throw new RestException(404, 'Contrat not found');
489 489
         }
490 490
 
491
-		if (! DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
492
-			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
493
-		}
491
+        if (! DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
492
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
493
+        }
494 494
         foreach($request_data as $field => $value) {
495 495
             if ($field == 'id') continue;
496 496
             $this->contract->$field = $value;
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
         }
503 503
         else
504 504
         {
505
-        	throw new RestException(500, $this->contract->error);
505
+            throw new RestException(500, $this->contract->error);
506 506
         }
507 507
     }
508 508
 
@@ -516,16 +516,16 @@  discard block
 block discarded – undo
516 516
     function delete($id)
517 517
     {
518 518
         if (! DolibarrApiAccess::$user->rights->contrat->supprimer) {
519
-			throw new RestException(401);
520
-		}
519
+            throw new RestException(401);
520
+        }
521 521
         $result = $this->contract->fetch($id);
522 522
         if (! $result) {
523 523
             throw new RestException(404, 'Contract not found');
524 524
         }
525 525
 
526
-		if (! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
527
-			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
528
-		}
526
+        if (! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
527
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
528
+        }
529 529
 
530 530
         if (! $this->contract->delete(DolibarrApiAccess::$user)) {
531 531
             throw new RestException(500, 'Error when delete contract : '.$this->contract->error);
@@ -558,24 +558,24 @@  discard block
 block discarded – undo
558 558
     function validate($id, $notrigger=0)
559 559
     {
560 560
         if (! DolibarrApiAccess::$user->rights->contrat->creer) {
561
-			throw new RestException(401);
562
-		}
561
+            throw new RestException(401);
562
+        }
563 563
         $result = $this->contract->fetch($id);
564 564
         if (! $result) {
565 565
             throw new RestException(404, 'Contract not found');
566 566
         }
567 567
 
568
-		if (! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
569
-			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
570
-		}
568
+        if (! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
569
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
570
+        }
571 571
 
572
-		$result = $this->contract->validate(DolibarrApiAccess::$user, '', $notrigger);
573
-		if ($result == 0) {
574
-		    throw new RestException(304, 'Error nothing done. May be object is already validated');
575
-		}
576
-		if ($result < 0) {
577
-		    throw new RestException(500, 'Error when validating Contract: '.$this->contract->error);
578
-		}
572
+        $result = $this->contract->validate(DolibarrApiAccess::$user, '', $notrigger);
573
+        if ($result == 0) {
574
+            throw new RestException(304, 'Error nothing done. May be object is already validated');
575
+        }
576
+        if ($result < 0) {
577
+            throw new RestException(500, 'Error when validating Contract: '.$this->contract->error);
578
+        }
579 579
 
580 580
         return array(
581 581
             'success' => array(
@@ -603,32 +603,32 @@  discard block
 block discarded – undo
603 603
      */
604 604
     function close($id, $notrigger=0)
605 605
     {
606
-    	if (! DolibarrApiAccess::$user->rights->contrat->creer) {
607
-    		throw new RestException(401);
608
-    	}
609
-    	$result = $this->contract->fetch($id);
610
-    	if (! $result) {
611
-    		throw new RestException(404, 'Contract not found');
612
-    	}
613
-
614
-    	if (! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
615
-    		throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
616
-    	}
617
-
618
-    	$result = $this->contract->closeAll(DolibarrApiAccess::$user, $notrigger);
619
-    	if ($result == 0) {
620
-    		throw new RestException(304, 'Error nothing done. May be object is already close');
621
-    	}
622
-    	if ($result < 0) {
623
-    		throw new RestException(500, 'Error when closing Contract: '.$this->contract->error);
624
-    	}
625
-
626
-    	return array(
627
-	    	'success' => array(
628
-		    	'code' => 200,
629
-		    	'message' => 'Contract closed (Ref='.$this->contract->ref.'). All services were closed.'
630
-	    	)
631
-    	);
606
+        if (! DolibarrApiAccess::$user->rights->contrat->creer) {
607
+            throw new RestException(401);
608
+        }
609
+        $result = $this->contract->fetch($id);
610
+        if (! $result) {
611
+            throw new RestException(404, 'Contract not found');
612
+        }
613
+
614
+        if (! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
615
+            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
616
+        }
617
+
618
+        $result = $this->contract->closeAll(DolibarrApiAccess::$user, $notrigger);
619
+        if ($result == 0) {
620
+            throw new RestException(304, 'Error nothing done. May be object is already close');
621
+        }
622
+        if ($result < 0) {
623
+            throw new RestException(500, 'Error when closing Contract: '.$this->contract->error);
624
+        }
625
+
626
+        return array(
627
+            'success' => array(
628
+                'code' => 200,
629
+                'message' => 'Contract closed (Ref='.$this->contract->ref.'). All services were closed.'
630
+            )
631
+        );
632 632
     }
633 633
 
634 634
 
Please login to merge, or discard this patch.
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -67,16 +67,16 @@  discard block
 block discarded – undo
67 67
      */
68 68
     function get($id)
69 69
     {
70
-		if(! DolibarrApiAccess::$user->rights->contrat->lire) {
70
+		if (!DolibarrApiAccess::$user->rights->contrat->lire) {
71 71
 			throw new RestException(401);
72 72
 		}
73 73
 
74 74
         $result = $this->contract->fetch($id);
75
-        if( ! $result ) {
75
+        if (!$result) {
76 76
             throw new RestException(404, 'Contract not found');
77 77
         }
78 78
 
79
-		if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
79
+		if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
80 80
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
81 81
 		}
82 82
 
@@ -112,18 +112,18 @@  discard block
 block discarded – undo
112 112
 
113 113
         // If the internal user must only see his customers, force searching by him
114 114
         $search_sale = 0;
115
-        if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
115
+        if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
116 116
 
117 117
         $sql = "SELECT t.rowid";
118 118
         if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
119
-        $sql.= " FROM ".MAIN_DB_PREFIX."contrat as t";
119
+        $sql .= " FROM ".MAIN_DB_PREFIX."contrat as t";
120 120
 
121
-        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
121
+        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
122 122
 
123
-        $sql.= ' WHERE t.entity IN ('.getEntity('contrat').')';
124
-        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc";
125
-        if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")";
126
-        if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc";		// Join for the needed table to filter by sale
123
+        $sql .= ' WHERE t.entity IN ('.getEntity('contrat').')';
124
+        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
125
+        if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
126
+        if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
127 127
         // Insert sale filter
128 128
         if ($search_sale > 0)
129 129
         {
@@ -132,23 +132,23 @@  discard block
 block discarded – undo
132 132
         // Add sql filters
133 133
         if ($sqlfilters)
134 134
         {
135
-            if (! DolibarrApi::_checkFilters($sqlfilters))
135
+            if (!DolibarrApi::_checkFilters($sqlfilters))
136 136
             {
137 137
                 throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
138 138
             }
139
-	        $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
140
-            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
139
+	        $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
140
+            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
141 141
         }
142 142
 
143
-        $sql.= $db->order($sortfield, $sortorder);
144
-        if ($limit)	{
143
+        $sql .= $db->order($sortfield, $sortorder);
144
+        if ($limit) {
145 145
             if ($page < 0)
146 146
             {
147 147
                 $page = 0;
148 148
             }
149 149
             $offset = $limit * $page;
150 150
 
151
-            $sql.= $db->plimit($limit + 1, $offset);
151
+            $sql .= $db->plimit($limit + 1, $offset);
152 152
         }
153 153
 
154 154
         dol_syslog("API Rest request");
@@ -158,12 +158,12 @@  discard block
 block discarded – undo
158 158
         {
159 159
             $num = $db->num_rows($result);
160 160
             $min = min($num, ($limit <= 0 ? $num : $limit));
161
-            $i=0;
161
+            $i = 0;
162 162
             while ($i < $min)
163 163
             {
164 164
                 $obj = $db->fetch_object($result);
165 165
                 $contrat_static = new Contrat($db);
166
-                if($contrat_static->fetch($obj->rowid)) {
166
+                if ($contrat_static->fetch($obj->rowid)) {
167 167
                     $obj_ret[] = $this->_cleanObjectDatas($contrat_static);
168 168
                 }
169 169
                 $i++;
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
         else {
173 173
             throw new RestException(503, 'Error when retrieve contrat list : '.$db->lasterror());
174 174
         }
175
-        if( ! count($obj_ret)) {
175
+        if (!count($obj_ret)) {
176 176
             throw new RestException(404, 'No contract found');
177 177
         }
178 178
 		return $obj_ret;
@@ -186,13 +186,13 @@  discard block
 block discarded – undo
186 186
      */
187 187
     function post($request_data = null)
188 188
     {
189
-      if(! DolibarrApiAccess::$user->rights->contrat->creer) {
189
+      if (!DolibarrApiAccess::$user->rights->contrat->creer) {
190 190
 			  throw new RestException(401, "Insuffisant rights");
191 191
 		  }
192 192
         // Check mandatory fields
193 193
         $result = $this->_validate($request_data);
194 194
 
195
-        foreach($request_data as $field => $value) {
195
+        foreach ($request_data as $field => $value) {
196 196
             $this->contract->$field = $value;
197 197
         }
198 198
         /*if (isset($request_data["lines"])) {
@@ -220,16 +220,16 @@  discard block
 block discarded – undo
220 220
      */
221 221
     function getLines($id)
222 222
     {
223
-        if(! DolibarrApiAccess::$user->rights->contrat->lire) {
223
+        if (!DolibarrApiAccess::$user->rights->contrat->lire) {
224 224
             throw new RestException(401);
225 225
 		}
226 226
 
227 227
         $result = $this->contract->fetch($id);
228
-        if( ! $result ) {
228
+        if (!$result) {
229 229
             throw new RestException(404, 'Contract not found');
230 230
         }
231 231
 
232
-		if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
232
+		if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
233 233
 		    throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
234 234
         }
235 235
         $this->contract->getLinesArray();
@@ -252,16 +252,16 @@  discard block
 block discarded – undo
252 252
      */
253 253
     function postLine($id, $request_data = null)
254 254
     {
255
-        if(! DolibarrApiAccess::$user->rights->contrat->creer) {
255
+        if (!DolibarrApiAccess::$user->rights->contrat->creer) {
256 256
 			throw new RestException(401);
257 257
 		}
258 258
 
259 259
         $result = $this->contract->fetch($id);
260
-        if( ! $result ) {
260
+        if (!$result) {
261 261
             throw new RestException(404, 'Contract not found');
262 262
         }
263 263
 
264
-		if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
264
+		if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
265 265
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
266 266
         }
267 267
 		$request_data = (object) $request_data;
@@ -274,8 +274,8 @@  discard block
 block discarded – undo
274 274
             $request_data->localtax2_tx,
275 275
             $request_data->fk_product,
276 276
             $request_data->remise_percent,
277
-            $request_data->date_start,			// date_start = date planned start, date ouverture = date_start_real
278
-            $request_data->date_end,			// date_end = date planned end, date_cloture = date_end_real
277
+            $request_data->date_start, // date_start = date planned start, date ouverture = date_start_real
278
+            $request_data->date_end, // date_end = date planned end, date_cloture = date_end_real
279 279
             $request_data->HT,
280 280
       		$request_data->subprice_excl_tax,
281 281
       		$request_data->info_bits,
@@ -305,16 +305,16 @@  discard block
 block discarded – undo
305 305
      */
306 306
     function putLine($id, $lineid, $request_data = null)
307 307
     {
308
-        if(! DolibarrApiAccess::$user->rights->contrat->creer) {
308
+        if (!DolibarrApiAccess::$user->rights->contrat->creer) {
309 309
 			throw new RestException(401);
310 310
 		}
311 311
 
312 312
         $result = $this->contract->fetch($id);
313
-        if( ! $result ) {
313
+        if (!$result) {
314 314
             throw new RestException(404, 'Contrat not found');
315 315
         }
316 316
 
317
-		if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
317
+		if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
318 318
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
319 319
 		}
320 320
 
@@ -365,16 +365,16 @@  discard block
 block discarded – undo
365 365
      */
366 366
     function activateLine($id, $lineid, $datestart, $dateend = null, $comment = null)
367 367
     {
368
-    	if(! DolibarrApiAccess::$user->rights->contrat->creer) {
368
+    	if (!DolibarrApiAccess::$user->rights->contrat->creer) {
369 369
     		throw new RestException(401);
370 370
     	}
371 371
 
372 372
     	$result = $this->contract->fetch($id);
373
-    	if (! $result) {
373
+    	if (!$result) {
374 374
     		throw new RestException(404, 'Contrat not found');
375 375
     	}
376 376
 
377
-    	if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
377
+    	if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
378 378
     		throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
379 379
     	}
380 380
 
@@ -403,16 +403,16 @@  discard block
 block discarded – undo
403 403
      */
404 404
     function unactivateLine($id, $lineid, $datestart, $comment = null)
405 405
     {
406
-    	if (! DolibarrApiAccess::$user->rights->contrat->creer) {
406
+    	if (!DolibarrApiAccess::$user->rights->contrat->creer) {
407 407
     		throw new RestException(401);
408 408
     	}
409 409
 
410 410
     	$result = $this->contract->fetch($id);
411
-    	if (! $result) {
411
+    	if (!$result) {
412 412
     		throw new RestException(404, 'Contrat not found');
413 413
     	}
414 414
 
415
-    	if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
415
+    	if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
416 416
     		throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
417 417
     	}
418 418
 
@@ -444,16 +444,16 @@  discard block
 block discarded – undo
444 444
      */
445 445
     function deleteLine($id, $lineid)
446 446
     {
447
-        if (! DolibarrApiAccess::$user->rights->contrat->creer) {
447
+        if (!DolibarrApiAccess::$user->rights->contrat->creer) {
448 448
 			throw new RestException(401);
449 449
 		}
450 450
 
451 451
         $result = $this->contract->fetch($id);
452
-        if (! $result) {
452
+        if (!$result) {
453 453
             throw new RestException(404, 'Contrat not found');
454 454
         }
455 455
 
456
-		if (! DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
456
+		if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
457 457
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
458 458
         }
459 459
 
@@ -479,19 +479,19 @@  discard block
 block discarded – undo
479 479
      */
480 480
     function put($id, $request_data = null)
481 481
     {
482
-        if (! DolibarrApiAccess::$user->rights->contrat->creer) {
482
+        if (!DolibarrApiAccess::$user->rights->contrat->creer) {
483 483
 			throw new RestException(401);
484 484
 		}
485 485
 
486 486
         $result = $this->contract->fetch($id);
487
-        if (! $result) {
487
+        if (!$result) {
488 488
             throw new RestException(404, 'Contrat not found');
489 489
         }
490 490
 
491
-		if (! DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
491
+		if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
492 492
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
493 493
 		}
494
-        foreach($request_data as $field => $value) {
494
+        foreach ($request_data as $field => $value) {
495 495
             if ($field == 'id') continue;
496 496
             $this->contract->$field = $value;
497 497
         }
@@ -515,19 +515,19 @@  discard block
 block discarded – undo
515 515
      */
516 516
     function delete($id)
517 517
     {
518
-        if (! DolibarrApiAccess::$user->rights->contrat->supprimer) {
518
+        if (!DolibarrApiAccess::$user->rights->contrat->supprimer) {
519 519
 			throw new RestException(401);
520 520
 		}
521 521
         $result = $this->contract->fetch($id);
522
-        if (! $result) {
522
+        if (!$result) {
523 523
             throw new RestException(404, 'Contract not found');
524 524
         }
525 525
 
526
-		if (! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
526
+		if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
527 527
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
528 528
 		}
529 529
 
530
-        if (! $this->contract->delete(DolibarrApiAccess::$user)) {
530
+        if (!$this->contract->delete(DolibarrApiAccess::$user)) {
531 531
             throw new RestException(500, 'Error when delete contract : '.$this->contract->error);
532 532
         }
533 533
 
@@ -555,17 +555,17 @@  discard block
 block discarded – undo
555 555
      *   "notrigger": 0
556 556
      * }
557 557
      */
558
-    function validate($id, $notrigger=0)
558
+    function validate($id, $notrigger = 0)
559 559
     {
560
-        if (! DolibarrApiAccess::$user->rights->contrat->creer) {
560
+        if (!DolibarrApiAccess::$user->rights->contrat->creer) {
561 561
 			throw new RestException(401);
562 562
 		}
563 563
         $result = $this->contract->fetch($id);
564
-        if (! $result) {
564
+        if (!$result) {
565 565
             throw new RestException(404, 'Contract not found');
566 566
         }
567 567
 
568
-		if (! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
568
+		if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
569 569
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
570 570
 		}
571 571
 
@@ -601,17 +601,17 @@  discard block
 block discarded – undo
601 601
      *   "notrigger": 0
602 602
      * }
603 603
      */
604
-    function close($id, $notrigger=0)
604
+    function close($id, $notrigger = 0)
605 605
     {
606
-    	if (! DolibarrApiAccess::$user->rights->contrat->creer) {
606
+    	if (!DolibarrApiAccess::$user->rights->contrat->creer) {
607 607
     		throw new RestException(401);
608 608
     	}
609 609
     	$result = $this->contract->fetch($id);
610
-    	if (! $result) {
610
+    	if (!$result) {
611 611
     		throw new RestException(404, 'Contract not found');
612 612
     	}
613 613
 
614
-    	if (! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) {
614
+    	if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
615 615
     		throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
616 616
     	}
617 617
 
Please login to merge, or discard this patch.
Braces   +30 added lines, -15 removed lines patch added patch discarded remove patch
@@ -112,18 +112,33 @@  discard block
 block discarded – undo
112 112
 
113 113
         // If the internal user must only see his customers, force searching by him
114 114
         $search_sale = 0;
115
-        if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
115
+        if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
116
+            $search_sale = DolibarrApiAccess::$user->id;
117
+        }
116 118
 
117 119
         $sql = "SELECT t.rowid";
118
-        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
120
+        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
121
+            $sql .= ", sc.fk_soc, sc.fk_user";
122
+        }
123
+        // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
119 124
         $sql.= " FROM ".MAIN_DB_PREFIX."contrat as t";
120 125
 
121
-        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
126
+        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
127
+            $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
128
+        }
129
+        // We need this table joined to the select in order to filter by sale
122 130
 
123 131
         $sql.= ' WHERE t.entity IN ('.getEntity('contrat').')';
124
-        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc";
125
-        if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")";
126
-        if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc";		// Join for the needed table to filter by sale
132
+        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
133
+            $sql.= " AND t.fk_soc = sc.fk_soc";
134
+        }
135
+        if ($socids) {
136
+            $sql.= " AND t.fk_soc IN (".$socids.")";
137
+        }
138
+        if ($search_sale > 0) {
139
+            $sql.= " AND t.rowid = sc.fk_soc";
140
+        }
141
+        // Join for the needed table to filter by sale
127 142
         // Insert sale filter
128 143
         if ($search_sale > 0)
129 144
         {
@@ -168,8 +183,7 @@  discard block
 block discarded – undo
168 183
                 }
169 184
                 $i++;
170 185
             }
171
-        }
172
-        else {
186
+        } else {
173 187
             throw new RestException(503, 'Error when retrieve contrat list : '.$db->lasterror());
174 188
         }
175 189
         if( ! count($obj_ret)) {
@@ -462,8 +476,7 @@  discard block
 block discarded – undo
462 476
         $updateRes = $this->contract->deleteline($lineid, DolibarrApiAccess::$user);
463 477
         if ($updateRes > 0) {
464 478
             return $this->get($id);
465
-        }
466
-        else
479
+        } else
467 480
         {
468 481
       	    throw new RestException(405, $this->contract->error);
469 482
         }
@@ -492,15 +505,16 @@  discard block
 block discarded – undo
492 505
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
493 506
 		}
494 507
         foreach($request_data as $field => $value) {
495
-            if ($field == 'id') continue;
508
+            if ($field == 'id') {
509
+                continue;
510
+            }
496 511
             $this->contract->$field = $value;
497 512
         }
498 513
 
499 514
         if ($this->contract->update(DolibarrApiAccess::$user) > 0)
500 515
         {
501 516
             return $this->get($id);
502
-        }
503
-        else
517
+        } else
504 518
         {
505 519
         	throw new RestException(500, $this->contract->error);
506 520
         }
@@ -670,8 +684,9 @@  discard block
 block discarded – undo
670 684
     {
671 685
         $contrat = array();
672 686
         foreach (Contracts::$FIELDS as $field) {
673
-            if (!isset($data[$field]))
674
-                throw new RestException(400, "$field field missing");
687
+            if (!isset($data[$field])) {
688
+                            throw new RestException(400, "$field field missing");
689
+            }
675 690
             $contrat[$field] = $data[$field];
676 691
         }
677 692
         return $contrat;
Please login to merge, or discard this patch.
dolibarr/htdocs/contrat/class/contrat.class.php 3 patches
Indentation   +3075 added lines, -3075 removed lines patch added patch discarded remove patch
@@ -42,30 +42,30 @@  discard block
 block discarded – undo
42 42
  */
43 43
 class Contrat extends CommonObject
44 44
 {
45
-	/**
46
-	 * @var string ID to identify managed object
47
-	 */
48
-	public $element='contrat';
45
+    /**
46
+     * @var string ID to identify managed object
47
+     */
48
+    public $element='contrat';
49 49
 
50
-	/**
51
-	 * @var string Name of table without prefix where object is stored
52
-	 */
53
-	public $table_element='contrat';
50
+    /**
51
+     * @var string Name of table without prefix where object is stored
52
+     */
53
+    public $table_element='contrat';
54 54
 
55
-	/**
56
-	 * @var int    Name of subtable line
57
-	 */
58
-	public $table_element_line='contratdet';
55
+    /**
56
+     * @var int    Name of subtable line
57
+     */
58
+    public $table_element_line='contratdet';
59 59
 
60
-	/**
61
-	 * @var int Field with ID of parent key if this field has a parent
62
-	 */
63
-	public $fk_element='fk_contrat';
60
+    /**
61
+     * @var int Field with ID of parent key if this field has a parent
62
+     */
63
+    public $fk_element='fk_contrat';
64 64
 
65 65
     /**
66
-	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
67
-	 */
68
-	public $picto='contract';
66
+     * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
67
+     */
68
+    public $picto='contract';
69 69
 
70 70
     /**
71 71
      * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
@@ -79,1737 +79,1737 @@  discard block
 block discarded – undo
79 79
      */
80 80
     public $restrictiononfksoc = 1;
81 81
 
82
-	/**
83
-	 * {@inheritdoc}
84
-	 */
85
-	protected $table_ref_field = 'ref';
86
-
87
-	/**
88
-	 * Customer reference of the contract
89
-	 * @var string
90
-	 */
91
-	public $ref_customer;
92
-
93
-	/**
94
-	 * Supplier reference of the contract
95
-	 * @var string
96
-	 */
97
-	public $ref_supplier;
98
-
99
-	/**
100
-	 * Client id linked to the contract
101
-	 * @var int
102
-	 */
103
-	public $socid;
104
-
105
-	public $societe;		// Objet societe
106
-
107
-	/**
108
-	 * Status of the contract
109
-	 * @var int
110
-	 */
111
-	public $statut=0;		// 0=Draft,
112
-
113
-	public $product;
114
-
115
-	/**
116
-	 * @var int		Id of user author of the contract
117
-	 */
118
-	public $fk_user_author;
119
-
120
-	/**
121
-	 * TODO: Which is the correct one?
122
-	 * Author of the contract
123
-	 * @var int
124
-	 */
125
-	public $user_author_id;
126
-
127
-	/**
128
-	 * @var User 	Object user that create the contract. Set by the info method.
129
-	 */
130
-	public $user_creation;
131
-
132
-	/**
133
-	 * @var User 	Object user that close the contract. Set by the info method.
134
-	 */
135
-	public $user_cloture;
136
-
137
-	/**
138
-	 * @var int		Date of creation
139
-	 */
140
-	public $date_creation;
141
-
142
-	/**
143
-	 * @var int		Date of last modification. Not filled until you call ->info()
144
-	 */
145
-	public $date_modification;
146
-
147
-	/**
148
-	 * @var int		Date of validation
149
-	 */
150
-	public $date_validation;
151
-
152
-	/**
153
-	 * @var int		Date when contract was signed
154
-	 */
155
-	public $date_contrat;
156
-
157
-	/**
158
-	 * @var int		Date of contract closure
159
-	 * @deprecated we close contract lines, not a contract
160
-	 */
161
-	public $date_cloture;
162
-
163
-	public $commercial_signature_id;
164
-	public $commercial_suivi_id;
165
-
166
-	/**
167
-	 * @deprecated Use fk_project instead
168
-	 * @see fk_project
169
-	 */
170
-	public $fk_projet;
171
-
172
-	public $extraparams=array();
173
-
174
-	/**
175
-	 * @var ContratLigne[]		Contract lines
176
-	 */
177
-	public $lines=array();
178
-
179
-	/**
180
-	 * Maps ContratLigne IDs to $this->lines indexes
181
-	 * @var int[]
182
-	 */
183
-	protected $lines_id_index_mapper=array();
184
-
185
-
186
-	/**
187
-	 *	Constructor
188
-	 *
189
-	 *  @param		DoliDB		$db      Database handler
190
-	 */
191
-	function __construct($db)
192
-	{
193
-		$this->db = $db;
194
-	}
195
-
196
-	/**
197
-	 *	Return next contract ref
198
-	 *
199
-	 *	@param	Societe		$soc		Thirdparty object
200
-	 *	@return string					free reference for contract
201
-	 */
202
-	function getNextNumRef($soc)
203
-	{
204
-		global $db, $langs, $conf;
205
-		$langs->load("contracts");
206
-
207
-		if (!empty($conf->global->CONTRACT_ADDON))
208
-		{
209
-			$mybool = false;
210
-
211
-			$file = $conf->global->CONTRACT_ADDON.".php";
212
-			$classname = $conf->global->CONTRACT_ADDON;
213
-
214
-			// Include file with class
215
-			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
216
-
217
-			foreach ($dirmodels as $reldir) {
218
-
219
-				$dir = dol_buildpath($reldir."core/modules/contract/");
220
-
221
-				// Load file with numbering class (if found)
222
-				$mybool|=@include_once $dir.$file;
223
-			}
224
-
225
-			if (! $mybool)
226
-			{
227
-				dol_print_error('',"Failed to include file ".$file);
228
-				return '';
229
-			}
230
-
231
-			$obj = new $classname();
232
-			$numref = $obj->getNextValue($soc,$this);
233
-
234
-			if ( $numref != "")
235
-			{
236
-				return $numref;
237
-			}
238
-			else
239
-			{
240
-				$this->error = $obj->error;
241
-				dol_print_error($db,get_class($this)."::getNextValue ".$obj->error);
242
-				return "";
243
-			}
244
-		}
245
-		else
246
-		{
247
-			$langs->load("errors");
248
-			print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete");
249
-			return "";
250
-		}
251
-	}
82
+    /**
83
+     * {@inheritdoc}
84
+     */
85
+    protected $table_ref_field = 'ref';
86
+
87
+    /**
88
+     * Customer reference of the contract
89
+     * @var string
90
+     */
91
+    public $ref_customer;
92
+
93
+    /**
94
+     * Supplier reference of the contract
95
+     * @var string
96
+     */
97
+    public $ref_supplier;
98
+
99
+    /**
100
+     * Client id linked to the contract
101
+     * @var int
102
+     */
103
+    public $socid;
104
+
105
+    public $societe;		// Objet societe
106
+
107
+    /**
108
+     * Status of the contract
109
+     * @var int
110
+     */
111
+    public $statut=0;		// 0=Draft,
112
+
113
+    public $product;
114
+
115
+    /**
116
+     * @var int		Id of user author of the contract
117
+     */
118
+    public $fk_user_author;
119
+
120
+    /**
121
+     * TODO: Which is the correct one?
122
+     * Author of the contract
123
+     * @var int
124
+     */
125
+    public $user_author_id;
126
+
127
+    /**
128
+     * @var User 	Object user that create the contract. Set by the info method.
129
+     */
130
+    public $user_creation;
131
+
132
+    /**
133
+     * @var User 	Object user that close the contract. Set by the info method.
134
+     */
135
+    public $user_cloture;
136
+
137
+    /**
138
+     * @var int		Date of creation
139
+     */
140
+    public $date_creation;
141
+
142
+    /**
143
+     * @var int		Date of last modification. Not filled until you call ->info()
144
+     */
145
+    public $date_modification;
146
+
147
+    /**
148
+     * @var int		Date of validation
149
+     */
150
+    public $date_validation;
151
+
152
+    /**
153
+     * @var int		Date when contract was signed
154
+     */
155
+    public $date_contrat;
156
+
157
+    /**
158
+     * @var int		Date of contract closure
159
+     * @deprecated we close contract lines, not a contract
160
+     */
161
+    public $date_cloture;
162
+
163
+    public $commercial_signature_id;
164
+    public $commercial_suivi_id;
165
+
166
+    /**
167
+     * @deprecated Use fk_project instead
168
+     * @see fk_project
169
+     */
170
+    public $fk_projet;
171
+
172
+    public $extraparams=array();
173
+
174
+    /**
175
+     * @var ContratLigne[]		Contract lines
176
+     */
177
+    public $lines=array();
178
+
179
+    /**
180
+     * Maps ContratLigne IDs to $this->lines indexes
181
+     * @var int[]
182
+     */
183
+    protected $lines_id_index_mapper=array();
184
+
185
+
186
+    /**
187
+     *	Constructor
188
+     *
189
+     *  @param		DoliDB		$db      Database handler
190
+     */
191
+    function __construct($db)
192
+    {
193
+        $this->db = $db;
194
+    }
195
+
196
+    /**
197
+     *	Return next contract ref
198
+     *
199
+     *	@param	Societe		$soc		Thirdparty object
200
+     *	@return string					free reference for contract
201
+     */
202
+    function getNextNumRef($soc)
203
+    {
204
+        global $db, $langs, $conf;
205
+        $langs->load("contracts");
206
+
207
+        if (!empty($conf->global->CONTRACT_ADDON))
208
+        {
209
+            $mybool = false;
210
+
211
+            $file = $conf->global->CONTRACT_ADDON.".php";
212
+            $classname = $conf->global->CONTRACT_ADDON;
213
+
214
+            // Include file with class
215
+            $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
216
+
217
+            foreach ($dirmodels as $reldir) {
218
+
219
+                $dir = dol_buildpath($reldir."core/modules/contract/");
220
+
221
+                // Load file with numbering class (if found)
222
+                $mybool|=@include_once $dir.$file;
223
+            }
224
+
225
+            if (! $mybool)
226
+            {
227
+                dol_print_error('',"Failed to include file ".$file);
228
+                return '';
229
+            }
230
+
231
+            $obj = new $classname();
232
+            $numref = $obj->getNextValue($soc,$this);
233
+
234
+            if ( $numref != "")
235
+            {
236
+                return $numref;
237
+            }
238
+            else
239
+            {
240
+                $this->error = $obj->error;
241
+                dol_print_error($db,get_class($this)."::getNextValue ".$obj->error);
242
+                return "";
243
+            }
244
+        }
245
+        else
246
+        {
247
+            $langs->load("errors");
248
+            print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete");
249
+            return "";
250
+        }
251
+    }
252
+
253
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
254
+    /**
255
+     *  Activate a contract line
256
+     *
257
+     *  @param	User		$user       Objet User who activate contract
258
+     *  @param  int			$line_id    Id of line to activate
259
+     *  @param  int			$date       Opening date
260
+     *  @param  int|string	$date_end   Expected end date
261
+     * 	@param	string		$comment	A comment typed by user
262
+     *  @return int         			<0 if KO, >0 if OK
263
+     */
264
+    function active_line($user, $line_id, $date, $date_end='', $comment='')
265
+    {
266
+        // phpcs:enable
267
+        $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date, $date_end, $comment);
268
+        if ($result < 0)
269
+        {
270
+            $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
271
+            $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
272
+        }
273
+        return $result;
274
+    }
275
+
252 276
 
253 277
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
254
-	/**
255
-	 *  Activate a contract line
256
-	 *
257
-	 *  @param	User		$user       Objet User who activate contract
258
-	 *  @param  int			$line_id    Id of line to activate
259
-	 *  @param  int			$date       Opening date
260
-	 *  @param  int|string	$date_end   Expected end date
261
-	 * 	@param	string		$comment	A comment typed by user
262
-	 *  @return int         			<0 if KO, >0 if OK
263
-	 */
264
-	function active_line($user, $line_id, $date, $date_end='', $comment='')
265
-	{
278
+    /**
279
+     *  Close a contract line
280
+     *
281
+     *  @param	User		$user       Objet User who close contract
282
+     *  @param  int			$line_id    Id of line to close
283
+     *  @param  int			$date_end	End date
284
+     * 	@param	string		$comment	A comment typed by user
285
+     *  @return int         			<0 if KO, >0 if OK
286
+     */
287
+    function close_line($user, $line_id, $date_end, $comment='')
288
+    {
266 289
         // phpcs:enable
267
-		$result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date, $date_end, $comment);
268
-		if ($result < 0)
269
-		{
270
-			$this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
271
-			$this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
272
-		}
273
-		return $result;
274
-	}
290
+        $result=$this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
291
+        if ($result < 0)
292
+        {
293
+            $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
294
+            $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
295
+        }
296
+        return $result;
297
+    }
298
+
299
+
300
+    /**
301
+     *  Open all lines of a contract
302
+     *
303
+     *  @param	User		$user      		Object User making action
304
+     *  @param	int|string	$date_start		Date start (now if empty)
305
+     *  @param	int			$notrigger		1=Does not execute triggers, 0=Execute triggers
306
+     *  @param	string		$comment		Comment
307
+     *	@return	int							<0 if KO, >0 if OK
308
+     *  @see closeAll
309
+     */
310
+    function activateAll($user, $date_start='', $notrigger=0, $comment='')
311
+    {
312
+        if (empty($date_start)) $date_start = dol_now();
313
+
314
+        $this->db->begin();
315
+
316
+        $error=0;
317
+
318
+        // Load lines
319
+        $this->fetch_lines();
320
+
321
+        foreach($this->lines as $contratline)
322
+        {
323
+            // Open lines not already open
324
+            if ($contratline->statut != ContratLigne::STATUS_OPEN)
325
+            {
326
+                $contratline->context = $this->context;
327
+
328
+                $result = $contratline->active_line($user, $date_start, -1, $comment);
329
+                if ($result < 0)
330
+                {
331
+                    $error++;
332
+                    $this->error = $contratline->error;
333
+                    $this->errors = $contratline->errors;
334
+                    break;
335
+                }
336
+            }
337
+        }
338
+
339
+        if (! $error && $this->statut == 0)
340
+        {
341
+            $result=$this->validate($user, '', $notrigger);
342
+            if ($result < 0) $error++;
343
+        }
344
+
345
+        if (! $error)
346
+        {
347
+            $this->db->commit();
348
+            return 1;
349
+        }
350
+        else
351
+        {
352
+            $this->db->rollback();
353
+            return -1;
354
+        }
355
+    }
356
+
357
+    /**
358
+     * Close all lines of a contract
359
+     *
360
+     * @param	User		$user      		Object User making action
361
+     * @param	int			$notrigger		1=Does not execute triggers, 0=Execute triggers
362
+     * @param	string		$comment		Comment
363
+     * @return	int							<0 if KO, >0 if OK
364
+     * @see activateAll
365
+     */
366
+    function closeAll(User $user, $notrigger=0, $comment='')
367
+    {
368
+        $this->db->begin();
369
+
370
+        // Load lines
371
+        $this->fetch_lines();
372
+
373
+        $now = dol_now();
374
+
375
+        $error = 0;
376
+
377
+        foreach($this->lines as $contratline)
378
+        {
379
+            // Close lines not already closed
380
+            if ($contratline->statut != ContratLigne::STATUS_CLOSED)
381
+            {
382
+                $contratline->date_cloture=$now;
383
+                $contratline->fk_user_cloture=$user->id;
384
+                $contratline->statut=ContratLigne::STATUS_CLOSED;
385
+                $result=$contratline->close_line($user, $now, $comment, $notrigger);
386
+                if ($result < 0)
387
+                {
388
+                    $error++;
389
+                    $this->error = $contratline->error;
390
+                    $this->errors = $contratline->errors;
391
+                    break;
392
+                }
393
+            }
394
+        }
395
+
396
+        if (! $error && $this->statut == 0)
397
+        {
398
+            $result=$this->validate($user, '', $notrigger);
399
+            if ($result < 0) $error++;
400
+        }
401
+
402
+        if (! $error)
403
+        {
404
+            $this->db->commit();
405
+            return 1;
406
+        }
407
+        else
408
+        {
409
+            $this->db->rollback();
410
+            return -1;
411
+        }
412
+    }
413
+
414
+    /**
415
+     * Validate a contract
416
+     *
417
+     * @param	User	$user      		Objet User
418
+     * @param   string	$force_number	Reference to force on contract (not implemented yet)
419
+     * @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
420
+     * @return	int						<0 if KO, >0 if OK
421
+     */
422
+    function validate(User $user, $force_number='', $notrigger=0)
423
+    {
424
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
425
+        global $langs, $conf;
426
+
427
+        $now=dol_now();
428
+
429
+        $error=0;
430
+        dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
431
+
432
+
433
+        $this->db->begin();
434
+
435
+        $this->fetch_thirdparty();
436
+
437
+        // A contract is validated so we can move thirdparty to status customer
438
+        if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION))
439
+        {
440
+            $result=$this->thirdparty->set_as_client();
441
+        }
442
+
443
+        // Define new ref
444
+        if ($force_number)
445
+        {
446
+            $num = $force_number;
447
+        }
448
+        else if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
449
+        {
450
+            $num = $this->getNextNumRef($this->thirdparty);
451
+        }
452
+        else
453
+        {
454
+            $num = $this->ref;
455
+        }
456
+        $this->newref = $num;
457
+
458
+        if ($num)
459
+        {
460
+            $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$num."', statut = 1";
461
+            //$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
462
+            $sql .= " WHERE rowid = ".$this->id . " AND statut = 0";
463
+
464
+            dol_syslog(get_class($this)."::validate", LOG_DEBUG);
465
+            $resql = $this->db->query($sql);
466
+            if (! $resql)
467
+            {
468
+                dol_print_error($this->db);
469
+                $error++;
470
+                $this->error=$this->db->lasterror();
471
+            }
472
+
473
+            // Trigger calls
474
+            if (! $error && ! $notrigger)
475
+            {
476
+                // Call trigger
477
+                $result=$this->call_trigger('CONTRACT_VALIDATE',$user);
478
+                if ($result < 0) { $error++; }
479
+                // End call triggers
480
+            }
481
+
482
+            if (! $error)
483
+            {
484
+                $this->oldref = $this->ref;
485
+
486
+                // Rename directory if dir was a temporary ref
487
+                if (preg_match('/^[\(]?PROV/i', $this->ref))
488
+                {
489
+                    // Rename of object directory ($this->ref = old ref, $num = new ref)
490
+                    // to  not lose the linked files
491
+                    $oldref = dol_sanitizeFileName($this->ref);
492
+                    $newref = dol_sanitizeFileName($num);
493
+                    $dirsource = $conf->contract->dir_output.'/'.$oldref;
494
+                    $dirdest = $conf->contract->dir_output.'/'.$newref;
495
+                    if (file_exists($dirsource))
496
+                    {
497
+                        dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
498
+
499
+                        if (@rename($dirsource, $dirdest))
500
+                        {
501
+                            dol_syslog("Rename ok");
502
+                            // Rename docs starting with $oldref with $newref
503
+                            $listoffiles=dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
504
+                            foreach($listoffiles as $fileentry)
505
+                            {
506
+                                $dirsource=$fileentry['name'];
507
+                                $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
508
+                                $dirsource=$fileentry['path'].'/'.$dirsource;
509
+                                $dirdest=$fileentry['path'].'/'.$dirdest;
510
+                                @rename($dirsource, $dirdest);
511
+                            }
512
+                        }
513
+                    }
514
+                }
515
+            }
516
+
517
+            // Set new ref and define current statut
518
+            if (! $error)
519
+            {
520
+                $this->ref = $num;
521
+                $this->statut = 1;
522
+                $this->brouillon = 0;
523
+                $this->date_validation = $now;
524
+            }
525
+        }
526
+        else
527
+        {
528
+            $error++;
529
+        }
530
+
531
+        if (! $error)
532
+        {
533
+            $this->db->commit();
534
+            return 1;
535
+        }
536
+        else
537
+        {
538
+            $this->db->rollback();
539
+            return -1;
540
+        }
541
+    }
542
+
543
+    /**
544
+     * Unvalidate a contract
545
+     *
546
+     * @param	User	$user      		Object User
547
+     * @param	int		$notrigger		1=Does not execute triggers, 0=execute triggers
548
+     * @return	int						<0 if KO, >0 if OK
549
+     */
550
+    function reopen($user, $notrigger=0)
551
+    {
552
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
553
+        global $langs, $conf;
554
+
555
+        $now=dol_now();
556
+
557
+        $error=0;
558
+        dol_syslog(get_class($this).'::reopen user='.$user->id);
559
+
560
+        $this->db->begin();
561
+
562
+        $this->fetch_thirdparty();
563
+
564
+        $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
565
+        //$sql.= ", fk_user_valid = null, date_valid = null";
566
+        $sql .= " WHERE rowid = ".$this->id . " AND statut = 1";
567
+
568
+        dol_syslog(get_class($this)."::validate", LOG_DEBUG);
569
+        $resql = $this->db->query($sql);
570
+        if (! $resql)
571
+        {
572
+            dol_print_error($this->db);
573
+            $error++;
574
+            $this->error=$this->db->lasterror();
575
+        }
576
+
577
+        // Trigger calls
578
+        if (! $error && ! $notrigger)
579
+        {
580
+            // Call trigger
581
+            $result=$this->call_trigger('CONTRACT_REOPEN',$user);
582
+            if ($result < 0) {
583
+                $error++;
584
+            }
585
+            // End call triggers
586
+        }
587
+
588
+        // Set new ref and define current status
589
+        if (! $error)
590
+        {
591
+            $this->statut=0;
592
+            $this->brouillon=1;
593
+            $this->date_validation=$now;
594
+        }
595
+
596
+        if (! $error)
597
+        {
598
+            $this->db->commit();
599
+            return 1;
600
+        }
601
+        else
602
+        {
603
+            $this->db->rollback();
604
+            return -1;
605
+        }
606
+    }
607
+
608
+    /**
609
+     *    Load a contract from database
610
+     *
611
+     *    @param	int		$id     		Id of contract to load
612
+     *    @param	string	$ref			Ref
613
+     *    @param	string	$ref_customer	Customer ref
614
+     *    @param	string	$ref_supplier	Supplier ref
615
+     *    @return   int     				<0 if KO, 0 if not found, Id of contract if OK
616
+     */
617
+    function fetch($id, $ref='', $ref_customer='', $ref_supplier='')
618
+    {
619
+        $sql = "SELECT rowid, statut, ref, fk_soc, mise_en_service as datemise,";
620
+        $sql.= " ref_supplier, ref_customer,";
621
+        $sql.= " ref_ext,";
622
+        $sql.= " fk_user_mise_en_service, date_contrat as datecontrat,";
623
+        $sql.= " fk_user_author, fin_validite, date_cloture,";
624
+        $sql.= " fk_projet,";
625
+        $sql.= " fk_commercial_signature, fk_commercial_suivi,";
626
+        $sql.= " note_private, note_public, model_pdf, extraparams";
627
+        $sql.= " FROM ".MAIN_DB_PREFIX."contrat";
628
+        if (! $id) $sql.=" WHERE entity IN (".getEntity('contract').")";
629
+        else $sql.= " WHERE rowid=".$id;
630
+        if ($ref_customer)
631
+        {
632
+            $sql.= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
633
+        }
634
+        if ($ref_supplier)
635
+        {
636
+            $sql.= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
637
+        }
638
+        if ($ref)
639
+        {
640
+            $sql.= " AND ref='".$this->db->escape($ref)."'";
641
+        }
642
+
643
+        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
644
+        $resql = $this->db->query($sql);
645
+        if ($resql)
646
+        {
647
+            $obj = $this->db->fetch_object($resql);
648
+
649
+            if ($obj)
650
+            {
651
+                $this->id						= $obj->rowid;
652
+                $this->ref						= (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
653
+                $this->ref_customer				= $obj->ref_customer;
654
+                $this->ref_supplier				= $obj->ref_supplier;
655
+                $this->ref_ext					= $obj->ref_ext;
656
+                $this->statut					= $obj->statut;
657
+                $this->mise_en_service			= $this->db->jdate($obj->datemise);
658
+
659
+                $this->date_contrat				= $this->db->jdate($obj->datecontrat);
660
+                $this->date_creation			= $this->db->jdate($obj->datecontrat);
661
+
662
+                $this->fin_validite				= $this->db->jdate($obj->fin_validite);
663
+                $this->date_cloture				= $this->db->jdate($obj->date_cloture);
664
+
665
+
666
+                $this->user_author_id			= $obj->fk_user_author;
667
+
668
+                $this->commercial_signature_id	= $obj->fk_commercial_signature;
669
+                $this->commercial_suivi_id		= $obj->fk_commercial_suivi;
670
+
671
+                $this->note_private				= $obj->note_private;
672
+                $this->note_public				= $obj->note_public;
673
+                $this->modelpdf					= $obj->model_pdf;
674
+
675
+                $this->fk_projet				= $obj->fk_projet; // deprecated
676
+                $this->fk_project				= $obj->fk_projet;
677
+
678
+                $this->socid					= $obj->fk_soc;
679
+                $this->fk_soc					= $obj->fk_soc;
680
+
681
+                $this->extraparams				= (array) json_decode($obj->extraparams, true);
682
+
683
+                $this->db->free($resql);
684
+
685
+                // Retreive all extrafields
686
+                // fetch optionals attributes and labels
687
+                $this->fetch_optionals();
688
+
689
+                // Lines
690
+                $result=$this->fetch_lines();
691
+                if ($result < 0)
692
+                {
693
+                    $this->error=$this->db->lasterror();
694
+                    return -3;
695
+                }
696
+
697
+                return $this->id;
698
+            }
699
+            else
700
+            {
701
+                dol_syslog(get_class($this)."::fetch Contract not found");
702
+                $this->error="Contract not found";
703
+                return 0;
704
+            }
705
+        }
706
+        else
707
+        {
708
+            dol_syslog(get_class($this)."::fetch Error searching contract");
709
+            $this->error=$this->db->error();
710
+            return -1;
711
+        }
712
+    }
713
+
714
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
715
+    /**
716
+     *  Load lines array into this->lines.
717
+     *  This set also nbofserviceswait, nbofservicesopened, nbofservicesexpired and nbofservicesclosed
718
+     *
719
+     *  @return ContratLigne[]   Return array of contract lines
720
+     */
721
+    function fetch_lines()
722
+    {
723
+        // phpcs:enable
724
+        $this->nbofserviceswait=0;
725
+        $this->nbofservicesopened=0;
726
+        $this->nbofservicesexpired=0;
727
+        $this->nbofservicesclosed=0;
728
+
729
+        $total_ttc=0;
730
+        $total_vat=0;
731
+        $total_ht=0;
732
+
733
+        $now=dol_now();
734
+
735
+        require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
736
+        $extrafieldsline=new ExtraFields($this->db);
737
+        $line = new ContratLigne($this->db);
738
+        $extralabelsline=$extrafieldsline->fetch_name_optionals_label($line->table_element,true);
739
+
740
+        $this->lines=array();
741
+        $pos = 0;
742
+
743
+        // Selects contract lines related to a product
744
+        $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref,";
745
+        $sql.= " d.rowid, d.fk_contrat, d.statut, d.description, d.price_ht, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
746
+        $sql.= " d.total_ht,";
747
+        $sql.= " d.total_tva,";
748
+        $sql.= " d.total_localtax1,";
749
+        $sql.= " d.total_localtax2,";
750
+        $sql.= " d.total_ttc,";
751
+        $sql.= " d.info_bits, d.fk_product,";
752
+        $sql.= " d.date_ouverture_prevue, d.date_ouverture,";
753
+        $sql.= " d.date_fin_validite, d.date_cloture,";
754
+        $sql.= " d.fk_user_author,";
755
+        $sql.= " d.fk_user_ouverture,";
756
+        $sql.= " d.fk_user_cloture,";
757
+        $sql.= " d.fk_unit";
758
+        $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
759
+        $sql.= " WHERE d.fk_contrat = ".$this->id;
760
+        $sql.= " ORDER by d.rowid ASC";
761
+
762
+        dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
763
+        $result = $this->db->query($sql);
764
+        if ($result)
765
+        {
766
+            $num = $this->db->num_rows($result);
767
+            $i = 0;
768
+
769
+            while ($i < $num)
770
+            {
771
+                $objp					= $this->db->fetch_object($result);
772
+
773
+                $line					= new ContratLigne($this->db);
774
+                $line->id				= $objp->rowid;
775
+                $line->ref				= $objp->rowid;
776
+                $line->fk_contrat		= $objp->fk_contrat;
777
+                $line->desc				= $objp->description;  // Description line
778
+                $line->qty				= $objp->qty;
779
+                $line->vat_src_code 	= $objp->vat_src_code ;
780
+                $line->tva_tx			= $objp->tva_tx;
781
+                $line->localtax1_tx		= $objp->localtax1_tx;
782
+                $line->localtax2_tx		= $objp->localtax2_tx;
783
+                $line->localtax1_type	= $objp->localtax1_type;
784
+                $line->localtax2_type	= $objp->localtax2_type;
785
+                $line->subprice			= $objp->subprice;
786
+                $line->statut			= $objp->statut;
787
+                $line->remise_percent	= $objp->remise_percent;
788
+                $line->price_ht			= $objp->price_ht;
789
+                $line->price			= $objp->price_ht;	// For backward compatibility
790
+                $line->total_ht			= $objp->total_ht;
791
+                $line->total_tva		= $objp->total_tva;
792
+                $line->total_localtax1	= $objp->total_localtax1;
793
+                $line->total_localtax2	= $objp->total_localtax2;
794
+                $line->total_ttc		= $objp->total_ttc;
795
+                $line->fk_product		= (($objp->fk_product > 0)?$objp->fk_product:0);
796
+                $line->info_bits		= $objp->info_bits;
797
+
798
+                $line->fk_fournprice 	= $objp->fk_fournprice;
799
+                $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
800
+                $line->pa_ht 			= $marginInfos[0];
801
+
802
+                $line->fk_user_author	= $objp->fk_user_author;
803
+                $line->fk_user_ouverture= $objp->fk_user_ouverture;
804
+                $line->fk_user_cloture  = $objp->fk_user_cloture;
805
+                $line->fk_unit           = $objp->fk_unit;
806
+
807
+                $line->ref				= $objp->product_ref;	// deprecated
808
+                $line->product_ref		= $objp->product_ref;   // Product Ref
809
+                $line->product_desc		= $objp->product_desc;  // Product Description
810
+                $line->product_label	= $objp->product_label; // Product Label
811
+
812
+                $line->description		= $objp->description;
813
+
814
+                $line->date_start            = $this->db->jdate($objp->date_ouverture_prevue);
815
+                $line->date_start_real       = $this->db->jdate($objp->date_ouverture);
816
+                $line->date_end              = $this->db->jdate($objp->date_fin_validite);
817
+                $line->date_end_real         = $this->db->jdate($objp->date_cloture);
818
+                // For backward compatibility
819
+                $line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
820
+                $line->date_ouverture        = $this->db->jdate($objp->date_ouverture);
821
+                $line->date_fin_validite     = $this->db->jdate($objp->date_fin_validite);
822
+                $line->date_cloture          = $this->db->jdate($objp->date_cloture);
823
+                $line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
824
+                $line->date_debut_reel   = $this->db->jdate($objp->date_ouverture);
825
+                $line->date_fin_prevue   = $this->db->jdate($objp->date_fin_validite);
826
+                $line->date_fin_reel     = $this->db->jdate($objp->date_cloture);
827
+
828
+                // Retreive all extrafields for contract
829
+                // fetch optionals attributes and labels
830
+                $line->fetch_optionals();
831
+
832
+                $this->lines[$pos]			= $line;
833
+                $this->lines_id_index_mapper[$line->id] = $pos;
834
+
835
+                //dol_syslog("1 ".$line->desc);
836
+                //dol_syslog("2 ".$line->product_desc);
837
+
838
+                if ($line->statut == ContratLigne::STATUS_INITIAL) $this->nbofserviceswait++;
839
+                if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++;
840
+                if ($line->statut == ContratLigne::STATUS_OPEN && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++;
841
+                if ($line->statut == ContratLigne::STATUS_CLOSED) $this->nbofservicesclosed++;
842
+
843
+                $total_ttc+=$objp->total_ttc;   // TODO Not saved into database
844
+                $total_vat+=$objp->total_tva;
845
+                $total_ht+=$objp->total_ht;
846
+
847
+                $i++;
848
+                $pos++;
849
+            }
850
+            $this->db->free($result);
851
+        }
852
+        else
853
+        {
854
+            dol_syslog(get_class($this)."::Fetch Erreur lecture des lignes de contrats liees aux produits");
855
+            return -3;
856
+        }
857
+
858
+        $this->nbofservices=count($this->lines);
859
+        $this->total_ttc = price2num($total_ttc);   // TODO For the moment value is false as value is not stored in database for line linked to products
860
+        $this->total_vat = price2num($total_vat);   // TODO For the moment value is false as value is not stored in database for line linked to products
861
+        $this->total_ht = price2num($total_ht);     // TODO For the moment value is false as value is not stored in database for line linked to products
862
+
863
+        return $this->lines;
864
+    }
865
+
866
+    /**
867
+     *  Create a contract into database
868
+     *
869
+     *  @param	User	$user       User that create
870
+     *  @return int  				<0 if KO, id of contract if OK
871
+     */
872
+    function create($user)
873
+    {
874
+        global $conf,$langs,$mysoc;
875
+
876
+        // Check parameters
877
+        $paramsok=1;
878
+        if ($this->commercial_signature_id <= 0)
879
+        {
880
+            $langs->load("commercial");
881
+            $this->error.=$langs->trans("ErrorFieldRequired",$langs->trans("SalesRepresentativeSignature"));
882
+            $paramsok=0;
883
+        }
884
+        if ($this->commercial_suivi_id <= 0)
885
+        {
886
+            $langs->load("commercial");
887
+            $this->error.=($this->error?"<br>":'');
888
+            $this->error.=$langs->trans("ErrorFieldRequired",$langs->trans("SalesRepresentativeFollowUp"));
889
+            $paramsok=0;
890
+        }
891
+        if (! $paramsok) return -1;
892
+
893
+
894
+        $this->db->begin();
895
+
896
+        $now=dol_now();
897
+
898
+        // Insert contract
899
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
900
+        $sql.= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
901
+        $sql.= " ref, entity, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
902
+        $sql.= " VALUES ('".$this->db->idate($now)."',".$this->socid.",".$user->id;
903
+        $sql.= ", ".(dol_strlen($this->date_contrat)!=0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
904
+        $sql.= ",".($this->commercial_signature_id>0?$this->commercial_signature_id:"NULL");
905
+        $sql.= ",".($this->commercial_suivi_id>0?$this->commercial_suivi_id:"NULL");
906
+        $sql.= ",".($this->fk_project>0?$this->fk_project:"NULL");
907
+        $sql.= ", ".(dol_strlen($this->ref)<=0 ? "null" : "'".$this->db->escape($this->ref)."'");
908
+        $sql.= ", ".$conf->entity;
909
+        $sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL");
910
+        $sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL");
911
+        $sql.= ", ".(!empty($this->ref_customer)?("'".$this->db->escape($this->ref_customer)."'"):"NULL");
912
+        $sql.= ", ".(!empty($this->ref_supplier)?("'".$this->db->escape($this->ref_supplier)."'"):"NULL");
913
+        $sql.= ", ".(!empty($this->ref_ext)?("'".$this->db->escape($this->ref_ext)."'"):"NULL");
914
+        $sql.= ")";
915
+        $resql=$this->db->query($sql);
916
+        if ($resql)
917
+        {
918
+            $error=0;
919
+
920
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
921
+
922
+            // Load object modContract
923
+            $module=(! empty($conf->global->CONTRACT_ADDON)?$conf->global->CONTRACT_ADDON:'mod_contract_serpis');
924
+            if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php')
925
+            {
926
+                $module = substr($module, 0, dol_strlen($module)-4);
927
+            }
928
+            $result=dol_include_once('/core/modules/contract/'.$module.'.php');
929
+            if ($result > 0)
930
+            {
931
+                $modCodeContract = new $module();
932
+
933
+                if (!empty($modCodeContract->code_auto)) {
934
+                    // Update ref
935
+                    $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id;
936
+                    if ($this->db->query($sql))
937
+                    {
938
+                        if ($this->id)
939
+                        {
940
+                            $this->ref="(PROV".$this->id.")";
941
+                        }
942
+                    }
943
+                } else {
944
+                    $error++;
945
+                    $this->error='Failed to get PROV number';
946
+                }
947
+            }
948
+
949
+            if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))
950
+            {
951
+                $result=$this->insertExtraFields();
952
+                if ($result < 0)
953
+                {
954
+                    $error++;
955
+                }
956
+            }
957
+
958
+            // Insert business contacts ('SALESREPSIGN','contrat')
959
+            if (! $error)
960
+            {
961
+                $result=$this->add_contact($this->commercial_signature_id,'SALESREPSIGN','internal');
962
+                if ($result < 0) $error++;
963
+            }
964
+
965
+            // Insert business contacts ('SALESREPFOLL','contrat')
966
+            if (! $error)
967
+            {
968
+                $result=$this->add_contact($this->commercial_suivi_id,'SALESREPFOLL','internal');
969
+                if ($result < 0) $error++;
970
+            }
971
+
972
+            if (! $error)
973
+            {
974
+                if (! empty($this->linkedObjectsIds) && empty($this->linked_objects))	// To use new linkedObjectsIds instead of old linked_objects
975
+                {
976
+                    $this->linked_objects = $this->linkedObjectsIds;	// TODO Replace linked_objects with linkedObjectsIds
977
+                }
978
+
979
+                // Add object linked
980
+                if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
981
+                {
982
+                    foreach($this->linked_objects as $origin => $tmp_origin_id)
983
+                    {
984
+                        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, ...))
985
+                        {
986
+                            foreach($tmp_origin_id as $origin_id)
987
+                            {
988
+                                $ret = $this->add_object_linked($origin, $origin_id);
989
+                                if (! $ret)
990
+                                {
991
+                                    $this->error=$this->db->lasterror();
992
+                                    $error++;
993
+                                }
994
+                            }
995
+                        }
996
+                        else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
997
+                        {
998
+                            $origin_id = $tmp_origin_id;
999
+                            $ret = $this->add_object_linked($origin, $origin_id);
1000
+                            if (! $ret)
1001
+                            {
1002
+                                $this->error=$this->db->lasterror();
1003
+                                $error++;
1004
+                            }
1005
+                        }
1006
+                    }
1007
+                }
1008
+
1009
+                if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
1010
+                {
1011
+                    $originforcontact = $this->origin;
1012
+                    $originidforcontact = $this->origin_id;
1013
+                    if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
1014
+                    {
1015
+                        require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
1016
+                        $exp = new Expedition($db);
1017
+                        $exp->fetch($this->origin_id);
1018
+                        $exp->fetchObjectLinked();
1019
+                        if (count($exp->linkedObjectsIds['commande']) > 0)
1020
+                        {
1021
+                            foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
1022
+                            {
1023
+                                $originforcontact = 'commande';
1024
+                                $originidforcontact = $value->id;
1025
+                                break; // We take first one
1026
+                            }
1027
+                        }
1028
+                    }
1029
+
1030
+                    $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";
1031
+                    $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
1032
+
1033
+                    $resqlcontact = $this->db->query($sqlcontact);
1034
+                    if ($resqlcontact)
1035
+                    {
1036
+                        while($objcontact = $this->db->fetch_object($resqlcontact))
1037
+                        {
1038
+                            if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) continue;    // ignore this, already forced previously
1039
+
1040
+                            //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1041
+                            $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
1042
+                        }
1043
+                    }
1044
+                    else dol_print_error($resqlcontact);
1045
+                }
1046
+            }
1047
+
1048
+            if (! $error)
1049
+            {
1050
+                // Call trigger
1051
+                $result=$this->call_trigger('CONTRACT_CREATE',$user);
1052
+                if ($result < 0) { $error++; }
1053
+                // End call triggers
1054
+
1055
+                if (! $error)
1056
+                {
1057
+                    $this->db->commit();
1058
+                    return $this->id;
1059
+                }
1060
+                else
1061
+                {
1062
+                    dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR);
1063
+                    $this->db->rollback();
1064
+                    return -3;
1065
+                }
1066
+            }
1067
+            else
1068
+            {
1069
+                $this->error="Failed to add contract";
1070
+                dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1071
+                $this->db->rollback();
1072
+                return -2;
1073
+            }
1074
+        }
1075
+        else
1076
+        {
1077
+            $this->error=$langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
1078
+
1079
+            $this->db->rollback();
1080
+            return -1;
1081
+        }
1082
+    }
1083
+
1084
+
1085
+    /**
1086
+     *  Supprime l'objet de la base
1087
+     *
1088
+     *  @param	User		$user       Utilisateur qui supprime
1089
+     *  @return int         			< 0 si erreur, > 0 si ok
1090
+     */
1091
+    function delete($user)
1092
+    {
1093
+        global $conf, $langs;
1094
+        require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1095
+
1096
+        $error=0;
1097
+
1098
+        $this->db->begin();
1099
+
1100
+        // Call trigger
1101
+        $result=$this->call_trigger('CONTRACT_DELETE',$user);
1102
+        if ($result < 0) { $error++; }
1103
+        // End call triggers
1104
+
1105
+        if (! $error)
1106
+        {
1107
+            // Delete linked contacts
1108
+            $res = $this->delete_linked_contact();
1109
+            if ($res < 0)
1110
+            {
1111
+                dol_syslog(get_class($this)."::delete error", LOG_ERR);
1112
+                $error++;
1113
+            }
1114
+        }
1115
+
1116
+        if (! $error)
1117
+        {
1118
+            // Delete linked object
1119
+            $res = $this->deleteObjectLinked();
1120
+            if ($res < 0) $error++;
1121
+        }
1122
+
1123
+        if (! $error)
1124
+        {
1125
+            // Delete contratdet_log
1126
+            /*
1127
+			$sql = "DELETE cdl";
1128
+			$sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1129
+			$sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".$this->id;
1130
+			*/
1131
+            $sql = "SELECT cdl.rowid as cdlrowid ";
1132
+            $sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1133
+            $sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".$this->id;
1134
+
1135
+            dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1136
+            $resql=$this->db->query($sql);
1137
+            if (! $resql)
1138
+            {
1139
+                $this->error=$this->db->error();
1140
+                $error++;
1141
+            }
1142
+            $numressql=$this->db->num_rows($resql);
1143
+            if (! $error && $numressql )
1144
+            {
1145
+                $tab_resql=array();
1146
+                for($i=0;$i<$numressql;$i++)
1147
+                {
1148
+                    $objresql=$this->db->fetch_object($resql);
1149
+                    $tab_resql[]= $objresql->cdlrowid;
1150
+                }
1151
+                $this->db->free($resql);
1152
+
1153
+                $sql= "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log ";
1154
+                $sql.= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".implode(",",$tab_resql).")";
1155
+
1156
+                dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1157
+                $resql=$this->db->query($sql);
1158
+                if (! $resql)
1159
+                {
1160
+                    $this->error=$this->db->error();
1161
+                    $error++;
1162
+                }
1163
+            }
1164
+        }
1165
+
1166
+        if (! $error)
1167
+        {
1168
+            // Delete contratdet
1169
+            $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1170
+            $sql.= " WHERE fk_contrat=".$this->id;
1171
+
1172
+            dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1173
+            $resql=$this->db->query($sql);
1174
+            if (! $resql)
1175
+            {
1176
+                $this->error=$this->db->error();
1177
+                $error++;
1178
+            }
1179
+        }
1180
+
1181
+        if (! $error)
1182
+        {
1183
+            // Delete contrat
1184
+            $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1185
+            $sql.= " WHERE rowid=".$this->id;
1186
+
1187
+            dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1188
+            $resql=$this->db->query($sql);
1189
+            if (! $resql)
1190
+            {
1191
+                $this->error=$this->db->error();
1192
+                $error++;
1193
+            }
1194
+        }
1195
+
1196
+        // Removed extrafields
1197
+        if (! $error) {
1198
+            $result=$this->deleteExtraFields();
1199
+            if ($result < 0)
1200
+            {
1201
+                $error++;
1202
+                dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1203
+            }
1204
+        }
1205
+
1206
+        if (! $error)
1207
+        {
1208
+            // We remove directory
1209
+            $ref = dol_sanitizeFileName($this->ref);
1210
+            if ($conf->contrat->dir_output)
1211
+            {
1212
+                $dir = $conf->contrat->dir_output . "/" . $ref;
1213
+                if (file_exists($dir))
1214
+                {
1215
+                    $res=@dol_delete_dir_recursive($dir);
1216
+                    if (! $res)
1217
+                    {
1218
+                        $this->error='ErrorFailToDeleteDir';
1219
+                        $error++;
1220
+                    }
1221
+                }
1222
+            }
1223
+        }
1224
+
1225
+        if (! $error)
1226
+        {
1227
+            $this->db->commit();
1228
+            return 1;
1229
+        }
1230
+        else
1231
+        {
1232
+            $this->error=$this->db->lasterror();
1233
+            $this->db->rollback();
1234
+            return -1;
1235
+        }
1236
+    }
1237
+
1238
+    /**
1239
+     *  Update object into database
1240
+     *
1241
+     *  @param	User	$user        User that modifies
1242
+     *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
1243
+     *  @return int     		   	 <0 if KO, >0 if OK
1244
+     */
1245
+    function update($user, $notrigger=0)
1246
+    {
1247
+        global $conf, $langs;
1248
+        $error=0;
1249
+
1250
+        // Clean parameters
1251
+        if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) $this->fk_commercial_signature = $this->commercial_signature_id;
1252
+        if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) $this->fk_commercial_suivi = $this->commercial_suivi_id;
1253
+        if (empty($this->fk_soc) && $this->socid > 0) $this->fk_soc = $this->socid;
1254
+        if (empty($this->fk_project) && $this->projet > 0) $this->fk_project = $this->projet;
1255
+
1256
+        if (isset($this->ref)) $this->ref=trim($this->ref);
1257
+        if (isset($this->ref_customer)) $this->ref_customer=trim($this->ref_customer);
1258
+        if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
1259
+        if (isset($this->ref_ext)) $this->ref_ext=trim($this->ref_ext);
1260
+        if (isset($this->entity)) $this->entity=trim($this->entity);
1261
+        if (isset($this->statut)) $this->statut=(int) $this->statut;
1262
+        if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
1263
+        if (isset($this->fk_commercial_signature)) $this->fk_commercial_signature=trim($this->fk_commercial_signature);
1264
+        if (isset($this->fk_commercial_suivi)) $this->fk_commercial_suivi=trim($this->fk_commercial_suivi);
1265
+        if (isset($this->fk_user_mise_en_service)) $this->fk_user_mise_en_service=trim($this->fk_user_mise_en_service);
1266
+        if (isset($this->fk_user_cloture)) $this->fk_user_cloture=trim($this->fk_user_cloture);
1267
+        if (isset($this->note_private)) $this->note_private=trim($this->note_private);
1268
+        if (isset($this->note_public)) $this->note_public=trim($this->note_public);
1269
+        if (isset($this->import_key)) $this->import_key=trim($this->import_key);
1270
+        //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
1271
+
1272
+        // Check parameters
1273
+        // Put here code to add a control on parameters values
1274
+
1275
+        // Update request
1276
+        $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1277
+        $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
1278
+        $sql.= " ref_customer=".(isset($this->ref_customer)?"'".$this->db->escape($this->ref_customer)."'":"null").",";
1279
+        $sql.= " ref_supplier=".(isset($this->ref_supplier)?"'".$this->db->escape($this->ref_supplier)."'":"null").",";
1280
+        $sql.= " ref_ext=".(isset($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null").",";
1281
+        $sql.= " entity=".$conf->entity.",";
1282
+        $sql.= " date_contrat=".(dol_strlen($this->date_contrat)!=0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1283
+        $sql.= " statut=".(isset($this->statut)?$this->statut:"null").",";
1284
+        $sql.= " mise_en_service=".(dol_strlen($this->mise_en_service)!=0 ? "'".$this->db->idate($this->mise_en_service)."'" : 'null').",";
1285
+        $sql.= " fin_validite=".(dol_strlen($this->fin_validite)!=0 ? "'".$this->db->idate($this->fin_validite)."'" : 'null').",";
1286
+        $sql.= " date_cloture=".(dol_strlen($this->date_cloture)!=0 ? "'".$this->db->idate($this->date_cloture)."'" : 'null').",";
1287
+        $sql.= " fk_soc=".($this->fk_soc > 0 ? $this->fk_soc:"null").",";
1288
+        $sql.= " fk_projet=".($this->fk_project > 0 ? $this->fk_project:"null").",";
1289
+        $sql.= " fk_commercial_signature=".(isset($this->fk_commercial_signature)?$this->fk_commercial_signature:"null").",";
1290
+        $sql.= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi)?$this->fk_commercial_suivi:"null").",";
1291
+        $sql.= " fk_user_mise_en_service=".(isset($this->fk_user_mise_en_service)?$this->fk_user_mise_en_service:"null").",";
1292
+        $sql.= " fk_user_cloture=".(isset($this->fk_user_cloture)?$this->fk_user_cloture:"null").",";
1293
+        $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
1294
+        $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
1295
+        $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
1296
+        //$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null")."";
1297
+        $sql.= " WHERE rowid=".$this->id;
1298
+
1299
+        $this->db->begin();
1300
+
1301
+        $resql = $this->db->query($sql);
1302
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
1303
+
1304
+        if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
1305
+        {
1306
+            $result=$this->insertExtraFields();
1307
+            if ($result < 0)
1308
+            {
1309
+                $error++;
1310
+            }
1311
+        }
1312
+
1313
+        if (! $error && ! $notrigger)
1314
+        {
1315
+            // Call triggers
1316
+            $result=$this->call_trigger('CONTRACT_MODIFY',$user);
1317
+            if ($result < 0) { $error++; }
1318
+            // End call triggers
1319
+        }
1320
+
1321
+        // Commit or rollback
1322
+        if ($error)
1323
+        {
1324
+            foreach($this->errors as $errmsg)
1325
+            {
1326
+                dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1327
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
1328
+            }
1329
+            $this->db->rollback();
1330
+            return -1*$error;
1331
+        }
1332
+        else
1333
+        {
1334
+            $this->db->commit();
1335
+            return 1;
1336
+        }
1337
+    }
1338
+
1339
+
1340
+    /**
1341
+     *  Ajoute une ligne de contrat en base
1342
+     *
1343
+     *  @param	string		$desc            	Description de la ligne
1344
+     *  @param  float		$pu_ht              Prix unitaire HT
1345
+     *  @param  int			$qty             	Quantite
1346
+     *  @param  float		$txtva           	Taux tva
1347
+     *  @param  float		$txlocaltax1        Local tax 1 rate
1348
+     *  @param  float		$txlocaltax2        Local tax 2 rate
1349
+     *  @param  int			$fk_product      	Id produit
1350
+     *  @param  float		$remise_percent  	Pourcentage de remise de la ligne
1351
+     *  @param  int			$date_start      	Date de debut prevue
1352
+     *  @param  int			$date_end        	Date de fin prevue
1353
+     *	@param	string		$price_base_type	HT or TTC
1354
+     * 	@param  float		$pu_ttc             Prix unitaire TTC
1355
+     * 	@param  int			$info_bits			Bits de type de lignes
1356
+     * 	@param  int			$fk_fournprice		Fourn price id
1357
+     *  @param  int			$pa_ht				Buying price HT
1358
+     *  @param	array		$array_options		extrafields array
1359
+     * 	@param 	string		$fk_unit 			Code of the unit to use. Null to use the default one
1360
+     * 	@param 	string		$rang 				Position
1361
+     *  @return int             				<0 if KO, >0 if OK
1362
+     */
1363
+    function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null, $rang=0)
1364
+    {
1365
+        global $user, $langs, $conf, $mysoc;
1366
+        $error=0;
1367
+
1368
+        dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang");
1369
+
1370
+        // Check parameters
1371
+        if ($fk_product <= 0 && empty($desc))
1372
+        {
1373
+            $this->error="ErrorDescRequiredForFreeProductLines";
1374
+            return -1;
1375
+        }
1376
+
1377
+        if ($this->statut >= 0)
1378
+        {
1379
+            $this->db->begin();
1380
+
1381
+            // Clean parameters
1382
+            $pu_ht=price2num($pu_ht);
1383
+            $pu_ttc=price2num($pu_ttc);
1384
+            $pa_ht=price2num($pa_ht);
1385
+            if (!preg_match('/\((.*)\)/', $txtva)) {
1386
+                $txtva = price2num($txtva);               // $txtva can have format '5.0(XXX)' or '5'
1387
+            }
1388
+            $txlocaltax1=price2num($txlocaltax1);
1389
+            $txlocaltax2=price2num($txlocaltax2);
1390
+            $remise_percent=price2num($remise_percent);
1391
+            $qty=price2num($qty);
1392
+            if (empty($qty)) $qty=1;
1393
+            if (empty($info_bits)) $info_bits=0;
1394
+            if (empty($pu_ht) || ! is_numeric($pu_ht))  $pu_ht=0;
1395
+            if (empty($pu_ttc)) $pu_ttc=0;
1396
+            if (empty($txtva) || ! is_numeric($txtva)) $txtva=0;
1397
+            if (empty($txlocaltax1) || ! is_numeric($txlocaltax1)) $txlocaltax1=0;
1398
+            if (empty($txlocaltax2) || ! is_numeric($txlocaltax2)) $txlocaltax2=0;
1399
+
1400
+            if ($price_base_type=='HT')
1401
+            {
1402
+                $pu=$pu_ht;
1403
+            }
1404
+            else
1405
+            {
1406
+                $pu=$pu_ttc;
1407
+            }
1408
+
1409
+            // Check parameters
1410
+            if (empty($remise_percent)) $remise_percent=0;
1411
+
1412
+            $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->societe, $mysoc);
1413
+
1414
+            // Clean vat code
1415
+            $vat_src_code='';
1416
+            if (preg_match('/\((.*)\)/', $txtva, $reg))
1417
+            {
1418
+                $vat_src_code = $reg[1];
1419
+                $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1420
+            }
1421
+
1422
+            // Calcul du total TTC et de la TVA pour la ligne a partir de
1423
+            // qty, pu, remise_percent et txtva
1424
+            // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1425
+            // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1426
+
1427
+            $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1,$mysoc, $localtaxes_type);
1428
+            $total_ht  = $tabprice[0];
1429
+            $total_tva = $tabprice[1];
1430
+            $total_ttc = $tabprice[2];
1431
+            $total_localtax1= $tabprice[9];
1432
+            $total_localtax2= $tabprice[10];
1433
+
1434
+            $localtax1_type=$localtaxes_type[0];
1435
+            $localtax2_type=$localtaxes_type[2];
1436
+
1437
+            // TODO A virer
1438
+            // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1439
+            $remise = 0;
1440
+            $price = price2num(round($pu_ht, 2));
1441
+            if (dol_strlen($remise_percent) > 0)
1442
+            {
1443
+                $remise = round(($pu_ht * $remise_percent / 100), 2);
1444
+                $price = $pu_ht - $remise;
1445
+            }
1446
+
1447
+            if (empty($pa_ht)) $pa_ht=0;
1448
+
1449
+
1450
+            // if buy price not defined, define buyprice as configured in margin admin
1451
+            if ($this->pa_ht == 0)
1452
+            {
1453
+                if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0)
1454
+                {
1455
+                    return $result;
1456
+                }
1457
+                else
1458
+                {
1459
+                    $pa_ht = $result;
1460
+                }
1461
+            }
1462
+
1463
+            // Insertion dans la base
1464
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1465
+            $sql.= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1466
+            $sql.= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1467
+            $sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1468
+            $sql.= " info_bits,";
1469
+            $sql.= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
1470
+            if ($date_start > 0) { $sql.= ",date_ouverture_prevue"; }
1471
+            if ($date_end > 0)   { $sql.= ",date_fin_validite"; }
1472
+            $sql.= ", fk_unit";
1473
+            $sql.= ") VALUES (";
1474
+            $sql.= $this->id.", '', '" . $this->db->escape($desc) . "',";
1475
+            $sql.= ($fk_product>0 ? $fk_product : "null").",";
1476
+            $sql.= " ".$qty.",";
1477
+            $sql.= " ".$txtva.",";
1478
+            $sql.= " ".($vat_src_code?"'".$vat_src_code."'":"null").",";
1479
+            $sql.= " ".$txlocaltax1.",";
1480
+            $sql.= " ".$txlocaltax2.",";
1481
+            $sql.= " '".$localtax1_type."',";
1482
+            $sql.= " '".$localtax2_type."',";
1483
+            $sql.= " ".price2num($remise_percent).",";
1484
+            $sql.= " ".price2num($pu_ht).",";
1485
+            $sql.= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1486
+            $sql.= " '".$info_bits."',";
1487
+            $sql.= " ".price2num($price).",".price2num($remise).",";
1488
+            if (isset($fk_fournprice)) $sql.= ' '.$fk_fournprice.',';
1489
+            else $sql.= ' null,';
1490
+            if (isset($pa_ht)) $sql.= ' '.price2num($pa_ht);
1491
+            else $sql.= ' null';
1492
+            if ($date_start > 0) { $sql.= ",'".$this->db->idate($date_start)."'"; }
1493
+            if ($date_end > 0) { $sql.= ",'".$this->db->idate($date_end)."'"; }
1494
+            $sql.= ", ".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
1495
+            $sql.= ")";
1496
+
1497
+            $resql=$this->db->query($sql);
1498
+            if ($resql)
1499
+            {
1500
+                $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1501
+
1502
+                if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
1503
+                {
1504
+                    $contractline = new ContratLigne($this->db);
1505
+                    $contractline->array_options=$array_options;
1506
+                    $contractline->id=$contractlineid;
1507
+                    $result=$contractline->insertExtraFields();
1508
+                    if ($result < 0)
1509
+                    {
1510
+                        $this->error[]=$contractline->error;
1511
+                        $error++;
1512
+                    }
1513
+                }
1514
+
1515
+                if (empty($error)) {
1516
+                    // Call trigger
1517
+                    $result=$this->call_trigger('LINECONTRACT_INSERT',$user);
1518
+                    if ($result < 0)
1519
+                    {
1520
+                        $error++;
1521
+                    }
1522
+                    // End call triggers
1523
+                }
1524
+
1525
+                if ($error)
1526
+                {
1527
+                    $this->db->rollback();
1528
+                    return -1;
1529
+                }
1530
+                else
1531
+                {
1532
+                    $this->db->commit();
1533
+                    return $contractlineid;
1534
+                }
1535
+            }
1536
+            else
1537
+            {
1538
+                $this->db->rollback();
1539
+                $this->error=$this->db->error()." sql=".$sql;
1540
+                return -1;
1541
+            }
1542
+        }
1543
+        else
1544
+        {
1545
+            dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1546
+            return -2;
1547
+        }
1548
+    }
1549
+
1550
+    /**
1551
+     *  Mets a jour une ligne de contrat
1552
+     *
1553
+     *  @param	int			$rowid            	Id de la ligne de facture
1554
+     *  @param  string		$desc             	Description de la ligne
1555
+     *  @param  float		$pu               	Prix unitaire
1556
+     *  @param  int			$qty              	Quantite
1557
+     *  @param  float		$remise_percent   	Pourcentage de remise de la ligne
1558
+     *  @param  int			$date_start       	Date de debut prevue
1559
+     *  @param  int			$date_end         	Date de fin prevue
1560
+     *  @param  float		$tvatx            	Taux TVA
1561
+     *  @param  float		$localtax1tx      	Local tax 1 rate
1562
+     *  @param  float		$localtax2tx      	Local tax 2 rate
1563
+     *  @param  int|string	$date_debut_reel  	Date de debut reelle
1564
+     *  @param  int|string	$date_fin_reel    	Date de fin reelle
1565
+     *	@param	string		$price_base_type	HT or TTC
1566
+     * 	@param  int			$info_bits			Bits de type de lignes
1567
+     * 	@param  int			$fk_fournprice		Fourn price id
1568
+     *  @param  int			$pa_ht				Buying price HT
1569
+     *  @param	array		$array_options		extrafields array
1570
+     * 	@param 	string		$fk_unit 			Code of the unit to use. Null to use the default one
1571
+     *  @return int              				< 0 si erreur, > 0 si ok
1572
+     */
1573
+    function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx=0.0, $localtax2tx=0.0, $date_debut_reel='', $date_fin_reel='', $price_base_type='HT', $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null)
1574
+    {
1575
+        global $user, $conf, $langs, $mysoc;
1576
+
1577
+        $error=0;
1578
+
1579
+        // Clean parameters
1580
+        $qty=trim($qty);
1581
+        $desc=trim($desc);
1582
+        $desc=trim($desc);
1583
+        $price = price2num($pu);
1584
+        $tvatx = price2num($tvatx);
1585
+        $localtax1tx = price2num($localtax1tx);
1586
+        $localtax2tx = price2num($localtax2tx);
1587
+        $pa_ht=price2num($pa_ht);
1588
+        if (empty($fk_fournprice)) $fk_fournprice=0;
1589
+
1590
+        $subprice = $price;
1591
+        $remise = 0;
1592
+        if (dol_strlen($remise_percent) > 0)
1593
+        {
1594
+            $remise = round(($pu * $remise_percent / 100), 2);
1595
+            $price = $pu - $remise;
1596
+        }
1597
+        else
1598
+        {
1599
+            $remise_percent=0;
1600
+        }
1601
+
1602
+        dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $date_debut_reel, $date_fin_reel, $tvatx, $localtax1tx, $localtax2tx, $price_base_type, $info_bits");
1603
+
1604
+        $this->db->begin();
1605
+
1606
+        // Calcul du total TTC et de la TVA pour la ligne a partir de
1607
+        // qty, pu, remise_percent et tvatx
1608
+        // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1609
+        // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1610
+
1611
+        $localtaxes_type=getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1612
+        $tvatx = preg_replace('/\s*\(.*\)/','',$tvatx);  // Remove code into vatrate.
1613
+
1614
+        $tabprice=calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1615
+        $total_ht  = $tabprice[0];
1616
+        $total_tva = $tabprice[1];
1617
+        $total_ttc = $tabprice[2];
1618
+        $total_localtax1= $tabprice[9];
1619
+        $total_localtax2= $tabprice[10];
1620
+
1621
+        $localtax1_type=$localtaxes_type[0];
1622
+        $localtax2_type=$localtaxes_type[2];
1623
+
1624
+        // TODO A virer
1625
+        // Anciens indicateurs: $price, $remise (a ne plus utiliser)
1626
+        $remise = 0;
1627
+        $price = price2num(round($pu, 2));
1628
+        if (dol_strlen($remise_percent) > 0)
1629
+        {
1630
+            $remise = round(($pu * $remise_percent / 100), 2);
1631
+            $price = $pu - $remise;
1632
+        }
1633
+
1634
+        if (empty($pa_ht)) $pa_ht=0;
1635
+
1636
+        // if buy price not defined, define buyprice as configured in margin admin
1637
+        if ($this->pa_ht == 0)
1638
+        {
1639
+            if (($result = $this->defineBuyPrice($pu_ht, $remise_percent)) < 0)
1640
+            {
1641
+                return $result;
1642
+            }
1643
+            else
1644
+            {
1645
+                $pa_ht = $result;
1646
+            }
1647
+        }
275 1648
 
1649
+        $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description='".$this->db->escape($desc)."'";
1650
+        $sql.= ",price_ht='" .     price2num($price)."'";
1651
+        $sql.= ",subprice='" .     price2num($subprice)."'";
1652
+        $sql.= ",remise='" .       price2num($remise)."'";
1653
+        $sql.= ",remise_percent='".price2num($remise_percent)."'";
1654
+        $sql.= ",qty='".$qty."'";
1655
+        $sql.= ",tva_tx='".        price2num($tvatx)."'";
1656
+        $sql.= ",localtax1_tx='".  price2num($localtax1tx)."'";
1657
+        $sql.= ",localtax2_tx='".  price2num($localtax2tx)."'";
1658
+        $sql.= ",localtax1_type='".$localtax1_type."'";
1659
+        $sql.= ",localtax2_type='".$localtax2_type."'";
1660
+        $sql.= ", total_ht='".     price2num($total_ht)."'";
1661
+        $sql.= ", total_tva='".    price2num($total_tva)."'";
1662
+        $sql.= ", total_localtax1='".price2num($total_localtax1)."'";
1663
+        $sql.= ", total_localtax2='".price2num($total_localtax2)."'";
1664
+        $sql.= ", total_ttc='".      price2num($total_ttc)."'";
1665
+        $sql.= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1666
+        $sql.= ", buy_price_ht='".price2num($pa_ht)."'";
1667
+        if ($date_start > 0) { $sql.= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; }
1668
+        else { $sql.=",date_ouverture_prevue=null"; }
1669
+        if ($date_end > 0) { $sql.= ",date_fin_validite='".$this->db->idate($date_end)."'"; }
1670
+        else { $sql.=",date_fin_validite=null"; }
1671
+        if ($date_debut_reel > 0) { $sql.= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; }
1672
+        else { $sql.=",date_ouverture=null"; }
1673
+        if ($date_fin_reel > 0) { $sql.= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; }
1674
+        else { $sql.=",date_cloture=null"; }
1675
+        $sql .= ", fk_unit=".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
1676
+        $sql .= " WHERE rowid = ".$rowid;
1677
+
1678
+        dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1679
+        $result = $this->db->query($sql);
1680
+        if ($result)
1681
+        {
1682
+            $result=$this->update_statut($user);
1683
+            if ($result >= 0)
1684
+            {
276 1685
 
277
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
278
-	/**
279
-	 *  Close a contract line
280
-	 *
281
-	 *  @param	User		$user       Objet User who close contract
282
-	 *  @param  int			$line_id    Id of line to close
283
-	 *  @param  int			$date_end	End date
284
-	 * 	@param	string		$comment	A comment typed by user
285
-	 *  @return int         			<0 if KO, >0 if OK
286
-	 */
287
-	function close_line($user, $line_id, $date_end, $comment='')
288
-	{
289
-        // phpcs:enable
290
-		$result=$this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
291
-		if ($result < 0)
292
-		{
293
-			$this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
294
-			$this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
295
-		}
296
-		return $result;
297
-	}
298
-
299
-
300
-	/**
301
-	 *  Open all lines of a contract
302
-	 *
303
-	 *  @param	User		$user      		Object User making action
304
-	 *  @param	int|string	$date_start		Date start (now if empty)
305
-     *  @param	int			$notrigger		1=Does not execute triggers, 0=Execute triggers
306
-     *  @param	string		$comment		Comment
307
-	 *	@return	int							<0 if KO, >0 if OK
308
-	 *  @see closeAll
309
-	 */
310
-	function activateAll($user, $date_start='', $notrigger=0, $comment='')
311
-	{
312
-		if (empty($date_start)) $date_start = dol_now();
313
-
314
-		$this->db->begin();
315
-
316
-		$error=0;
317
-
318
-		// Load lines
319
-		$this->fetch_lines();
320
-
321
-		foreach($this->lines as $contratline)
322
-		{
323
-			// Open lines not already open
324
-			if ($contratline->statut != ContratLigne::STATUS_OPEN)
325
-			{
326
-				$contratline->context = $this->context;
327
-
328
-				$result = $contratline->active_line($user, $date_start, -1, $comment);
329
-				if ($result < 0)
330
-				{
331
-					$error++;
332
-					$this->error = $contratline->error;
333
-					$this->errors = $contratline->errors;
334
-					break;
335
-				}
336
-			}
337
-		}
338
-
339
-		if (! $error && $this->statut == 0)
340
-		{
341
-			$result=$this->validate($user, '', $notrigger);
342
-			if ($result < 0) $error++;
343
-		}
344
-
345
-		if (! $error)
346
-		{
347
-			$this->db->commit();
348
-			return 1;
349
-		}
350
-		else
351
-		{
352
-			$this->db->rollback();
353
-			return -1;
354
-		}
355
-	}
356
-
357
-	/**
358
-	 * Close all lines of a contract
359
-	 *
360
-	 * @param	User		$user      		Object User making action
361
-     * @param	int			$notrigger		1=Does not execute triggers, 0=Execute triggers
362
-     * @param	string		$comment		Comment
363
-	 * @return	int							<0 if KO, >0 if OK
364
-	 * @see activateAll
365
-	 */
366
-	function closeAll(User $user, $notrigger=0, $comment='')
367
-	{
368
-		$this->db->begin();
369
-
370
-		// Load lines
371
-		$this->fetch_lines();
372
-
373
-		$now = dol_now();
374
-
375
-		$error = 0;
376
-
377
-		foreach($this->lines as $contratline)
378
-		{
379
-			// Close lines not already closed
380
-			if ($contratline->statut != ContratLigne::STATUS_CLOSED)
381
-	        {
382
-				$contratline->date_cloture=$now;
383
-				$contratline->fk_user_cloture=$user->id;
384
-				$contratline->statut=ContratLigne::STATUS_CLOSED;
385
-				$result=$contratline->close_line($user, $now, $comment, $notrigger);
386
-				if ($result < 0)
387
-				{
388
-					$error++;
389
-					$this->error = $contratline->error;
390
-					$this->errors = $contratline->errors;
391
-					break;
392
-				}
393
-	        }
394
-		}
395
-
396
-		if (! $error && $this->statut == 0)
397
-		{
398
-			$result=$this->validate($user, '', $notrigger);
399
-			if ($result < 0) $error++;
400
-		}
1686
+                if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
1687
+                {
1688
+                    $contractline = new ContratLigne($this->db);
1689
+                    $contractline->array_options=$array_options;
1690
+                    $contractline->id= $rowid;
1691
+                    $result=$contractline->insertExtraFields();
1692
+                    if ($result < 0)
1693
+                    {
1694
+                        $this->error[]=$contractline->error;
1695
+                        $error++;
1696
+                    }
1697
+                }
401 1698
 
402
-        if (! $error)
403
-        {
404
-            $this->db->commit();
405
-            return 1;
1699
+                if (empty($error)) {
1700
+                    // Call trigger
1701
+                    $result=$this->call_trigger('LINECONTRACT_UPDATE',$user);
1702
+                    if ($result < 0)
1703
+                    {
1704
+                        $this->db->rollback();
1705
+                        return -3;
1706
+                    }
1707
+                    // End call triggers
1708
+
1709
+                    $this->db->commit();
1710
+                    return 1;
1711
+                }
1712
+            }
1713
+            else
1714
+            {
1715
+                $this->db->rollback();
1716
+                dol_syslog(get_class($this)."::updateline Erreur -2");
1717
+                return -2;
1718
+            }
406 1719
         }
407 1720
         else
408 1721
         {
409 1722
             $this->db->rollback();
1723
+            $this->error=$this->db->error();
1724
+            dol_syslog(get_class($this)."::updateline Erreur -1");
410 1725
             return -1;
411 1726
         }
412
-	}
413
-
414
-	/**
415
-	 * Validate a contract
416
-	 *
417
-	 * @param	User	$user      		Objet User
418
-	 * @param   string	$force_number	Reference to force on contract (not implemented yet)
419
-     * @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
420
-	 * @return	int						<0 if KO, >0 if OK
421
-	 */
422
-	function validate(User $user, $force_number='', $notrigger=0)
423
-	{
424
-		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
425
-		global $langs, $conf;
426
-
427
-		$now=dol_now();
428
-
429
-		$error=0;
430
-		dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
431
-
432
-
433
-		$this->db->begin();
434
-
435
-		$this->fetch_thirdparty();
436
-
437
-		// A contract is validated so we can move thirdparty to status customer
438
-		if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION))
439
-		{
440
-			$result=$this->thirdparty->set_as_client();
441
-		}
442
-
443
-		// Define new ref
444
-		if ($force_number)
445
-		{
446
-			$num = $force_number;
447
-		}
448
-		else if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
449
-		{
450
-			$num = $this->getNextNumRef($this->thirdparty);
451
-		}
452
-		else
453
-		{
454
-			$num = $this->ref;
455
-		}
456
-        $this->newref = $num;
457
-
458
-		if ($num)
459
-		{
460
-			$sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$num."', statut = 1";
461
-			//$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
462
-			$sql .= " WHERE rowid = ".$this->id . " AND statut = 0";
463
-
464
-			dol_syslog(get_class($this)."::validate", LOG_DEBUG);
465
-			$resql = $this->db->query($sql);
466
-			if (! $resql)
467
-			{
468
-				dol_print_error($this->db);
469
-				$error++;
470
-				$this->error=$this->db->lasterror();
471
-			}
472
-
473
-			// Trigger calls
474
-			if (! $error && ! $notrigger)
475
-			{
476
-                // Call trigger
477
-                $result=$this->call_trigger('CONTRACT_VALIDATE',$user);
478
-                if ($result < 0) { $error++; }
479
-                // End call triggers
480
-			}
481
-
482
-			if (! $error)
483
-			{
484
-            	$this->oldref = $this->ref;
485
-
486
-				// Rename directory if dir was a temporary ref
487
-				if (preg_match('/^[\(]?PROV/i', $this->ref))
488
-				{
489
-					// Rename of object directory ($this->ref = old ref, $num = new ref)
490
-					// to  not lose the linked files
491
-					$oldref = dol_sanitizeFileName($this->ref);
492
-					$newref = dol_sanitizeFileName($num);
493
-					$dirsource = $conf->contract->dir_output.'/'.$oldref;
494
-					$dirdest = $conf->contract->dir_output.'/'.$newref;
495
-					if (file_exists($dirsource))
496
-					{
497
-						dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
498
-
499
-						if (@rename($dirsource, $dirdest))
500
-						{
501
-							dol_syslog("Rename ok");
502
-						    // Rename docs starting with $oldref with $newref
503
-            				$listoffiles=dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
504
-            				foreach($listoffiles as $fileentry)
505
-            				{
506
-            					$dirsource=$fileentry['name'];
507
-            					$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
508
-            					$dirsource=$fileentry['path'].'/'.$dirsource;
509
-            					$dirdest=$fileentry['path'].'/'.$dirdest;
510
-            					@rename($dirsource, $dirdest);
511
-            				}
512
-						}
513
-					}
514
-				}
515
-			}
516
-
517
-			// Set new ref and define current statut
518
-			if (! $error)
519
-			{
520
-				$this->ref = $num;
521
-				$this->statut = 1;
522
-				$this->brouillon = 0;
523
-				$this->date_validation = $now;
524
-			}
525
-		}
526
-		else
527
-		{
528
-			$error++;
529
-		}
530
-
531
-		if (! $error)
532
-		{
533
-			$this->db->commit();
534
-			return 1;
535
-		}
536
-		else
537
-		{
538
-			$this->db->rollback();
539
-			return -1;
540
-		}
541
-	}
542
-
543
-	/**
544
-	 * Unvalidate a contract
545
-	 *
546
-	 * @param	User	$user      		Object User
547
-     * @param	int		$notrigger		1=Does not execute triggers, 0=execute triggers
548
-	 * @return	int						<0 if KO, >0 if OK
549
-	 */
550
-	function reopen($user, $notrigger=0)
551
-	{
552
-		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
553
-		global $langs, $conf;
554
-
555
-		$now=dol_now();
556
-
557
-		$error=0;
558
-		dol_syslog(get_class($this).'::reopen user='.$user->id);
559
-
560
-		$this->db->begin();
561
-
562
-		$this->fetch_thirdparty();
563
-
564
-		$sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
565
-		//$sql.= ", fk_user_valid = null, date_valid = null";
566
-		$sql .= " WHERE rowid = ".$this->id . " AND statut = 1";
567
-
568
-		dol_syslog(get_class($this)."::validate", LOG_DEBUG);
569
-		$resql = $this->db->query($sql);
570
-		if (! $resql)
571
-		{
572
-			dol_print_error($this->db);
573
-			$error++;
574
-			$this->error=$this->db->lasterror();
575
-		}
576
-
577
-		// Trigger calls
578
-		if (! $error && ! $notrigger)
579
-		{
580
-			// Call trigger
581
-			$result=$this->call_trigger('CONTRACT_REOPEN',$user);
582
-			if ($result < 0) {
583
-				$error++;
584
-			}
585
-			// End call triggers
586
-		}
587
-
588
-		// Set new ref and define current status
589
-		if (! $error)
590
-		{
591
-			$this->statut=0;
592
-			$this->brouillon=1;
593
-			$this->date_validation=$now;
594
-		}
595
-
596
-		if (! $error)
597
-		{
598
-			$this->db->commit();
599
-			return 1;
600
-		}
601
-		else
602
-		{
603
-			$this->db->rollback();
604
-			return -1;
605
-		}
606
-	}
607
-
608
-	/**
609
-	 *    Load a contract from database
610
-	 *
611
-	 *    @param	int		$id     		Id of contract to load
612
-	 *    @param	string	$ref			Ref
613
-	 *    @param	string	$ref_customer	Customer ref
614
-	 *    @param	string	$ref_supplier	Supplier ref
615
-	 *    @return   int     				<0 if KO, 0 if not found, Id of contract if OK
616
-	 */
617
-	function fetch($id, $ref='', $ref_customer='', $ref_supplier='')
618
-	{
619
-		$sql = "SELECT rowid, statut, ref, fk_soc, mise_en_service as datemise,";
620
-		$sql.= " ref_supplier, ref_customer,";
621
-		$sql.= " ref_ext,";
622
-		$sql.= " fk_user_mise_en_service, date_contrat as datecontrat,";
623
-		$sql.= " fk_user_author, fin_validite, date_cloture,";
624
-		$sql.= " fk_projet,";
625
-		$sql.= " fk_commercial_signature, fk_commercial_suivi,";
626
-		$sql.= " note_private, note_public, model_pdf, extraparams";
627
-		$sql.= " FROM ".MAIN_DB_PREFIX."contrat";
628
-		if (! $id) $sql.=" WHERE entity IN (".getEntity('contract').")";
629
-		else $sql.= " WHERE rowid=".$id;
630
-		if ($ref_customer)
631
-		{
632
-			$sql.= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
633
-		}
634
-		if ($ref_supplier)
635
-		{
636
-			$sql.= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
637
-		}
638
-		if ($ref)
639
-		{
640
-			$sql.= " AND ref='".$this->db->escape($ref)."'";
641
-		}
642
-
643
-		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
644
-		$resql = $this->db->query($sql);
645
-		if ($resql)
646
-		{
647
-			$obj = $this->db->fetch_object($resql);
648
-
649
-			if ($obj)
650
-			{
651
-				$this->id						= $obj->rowid;
652
-				$this->ref						= (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
653
-				$this->ref_customer				= $obj->ref_customer;
654
-				$this->ref_supplier				= $obj->ref_supplier;
655
-				$this->ref_ext					= $obj->ref_ext;
656
-				$this->statut					= $obj->statut;
657
-				$this->mise_en_service			= $this->db->jdate($obj->datemise);
658
-
659
-				$this->date_contrat				= $this->db->jdate($obj->datecontrat);
660
-				$this->date_creation			= $this->db->jdate($obj->datecontrat);
661
-
662
-				$this->fin_validite				= $this->db->jdate($obj->fin_validite);
663
-				$this->date_cloture				= $this->db->jdate($obj->date_cloture);
664
-
665
-
666
-				$this->user_author_id			= $obj->fk_user_author;
667
-
668
-				$this->commercial_signature_id	= $obj->fk_commercial_signature;
669
-				$this->commercial_suivi_id		= $obj->fk_commercial_suivi;
670
-
671
-				$this->note_private				= $obj->note_private;
672
-				$this->note_public				= $obj->note_public;
673
-				$this->modelpdf					= $obj->model_pdf;
674
-
675
-				$this->fk_projet				= $obj->fk_projet; // deprecated
676
-				$this->fk_project				= $obj->fk_projet;
677
-
678
-				$this->socid					= $obj->fk_soc;
679
-				$this->fk_soc					= $obj->fk_soc;
680
-
681
-				$this->extraparams				= (array) json_decode($obj->extraparams, true);
682
-
683
-				$this->db->free($resql);
684
-
685
-				// Retreive all extrafields
686
-				// fetch optionals attributes and labels
687
-				$this->fetch_optionals();
688
-
689
-				// Lines
690
-				$result=$this->fetch_lines();
691
-				if ($result < 0)
692
-				{
693
-					$this->error=$this->db->lasterror();
694
-					return -3;
695
-				}
696
-
697
-				return $this->id;
698
-			}
699
-			else
700
-			{
701
-				dol_syslog(get_class($this)."::fetch Contract not found");
702
-				$this->error="Contract not found";
703
-				return 0;
704
-			}
705
-		}
706
-		else
707
-		{
708
-			dol_syslog(get_class($this)."::fetch Error searching contract");
709
-			$this->error=$this->db->error();
710
-			return -1;
711
-		}
712
-	}
713
-
714
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
715
-	/**
716
-	 *  Load lines array into this->lines.
717
-	 *  This set also nbofserviceswait, nbofservicesopened, nbofservicesexpired and nbofservicesclosed
718
-	 *
719
-	 *  @return ContratLigne[]   Return array of contract lines
720
-	 */
721
-	function fetch_lines()
722
-	{
723
-        // phpcs:enable
724
-		$this->nbofserviceswait=0;
725
-		$this->nbofservicesopened=0;
726
-		$this->nbofservicesexpired=0;
727
-		$this->nbofservicesclosed=0;
728
-
729
-		$total_ttc=0;
730
-		$total_vat=0;
731
-		$total_ht=0;
1727
+    }
732 1728
 
733
-		$now=dol_now();
1729
+    /**
1730
+     *  Delete a contract line
1731
+     *
1732
+     *  @param	int		$idline		Id of line to delete
1733
+     *	@param  User	$user       User that delete
1734
+     *  @return int         		>0 if OK, <0 if KO
1735
+     */
1736
+    function deleteline($idline, User $user)
1737
+    {
1738
+        global $conf, $langs;
734 1739
 
735
-		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
736
-		$extrafieldsline=new ExtraFields($this->db);
737
-		$line = new ContratLigne($this->db);
738
-		$extralabelsline=$extrafieldsline->fetch_name_optionals_label($line->table_element,true);
1740
+        $error=0;
739 1741
 
740
-		$this->lines=array();
741
-        $pos = 0;
1742
+        if ($this->statut >= 0)
1743
+        {
742 1744
 
743
-		// Selects contract lines related to a product
744
-		$sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref,";
745
-		$sql.= " d.rowid, d.fk_contrat, d.statut, d.description, d.price_ht, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
746
-		$sql.= " d.total_ht,";
747
-		$sql.= " d.total_tva,";
748
-		$sql.= " d.total_localtax1,";
749
-		$sql.= " d.total_localtax2,";
750
-		$sql.= " d.total_ttc,";
751
-		$sql.= " d.info_bits, d.fk_product,";
752
-		$sql.= " d.date_ouverture_prevue, d.date_ouverture,";
753
-		$sql.= " d.date_fin_validite, d.date_cloture,";
754
-		$sql.= " d.fk_user_author,";
755
-		$sql.= " d.fk_user_ouverture,";
756
-		$sql.= " d.fk_user_cloture,";
757
-		$sql.= " d.fk_unit";
758
-		$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
759
-		$sql.= " WHERE d.fk_contrat = ".$this->id;
760
-		$sql.= " ORDER by d.rowid ASC";
761
-
762
-		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
763
-		$result = $this->db->query($sql);
764
-		if ($result)
765
-		{
766
-			$num = $this->db->num_rows($result);
767
-			$i = 0;
768
-
769
-			while ($i < $num)
770
-			{
771
-				$objp					= $this->db->fetch_object($result);
772
-
773
-				$line					= new ContratLigne($this->db);
774
-				$line->id				= $objp->rowid;
775
-				$line->ref				= $objp->rowid;
776
-				$line->fk_contrat		= $objp->fk_contrat;
777
-				$line->desc				= $objp->description;  // Description line
778
-				$line->qty				= $objp->qty;
779
-				$line->vat_src_code 	= $objp->vat_src_code ;
780
-				$line->tva_tx			= $objp->tva_tx;
781
-				$line->localtax1_tx		= $objp->localtax1_tx;
782
-				$line->localtax2_tx		= $objp->localtax2_tx;
783
-				$line->localtax1_type	= $objp->localtax1_type;
784
-				$line->localtax2_type	= $objp->localtax2_type;
785
-				$line->subprice			= $objp->subprice;
786
-				$line->statut			= $objp->statut;
787
-				$line->remise_percent	= $objp->remise_percent;
788
-				$line->price_ht			= $objp->price_ht;
789
-				$line->price			= $objp->price_ht;	// For backward compatibility
790
-				$line->total_ht			= $objp->total_ht;
791
-				$line->total_tva		= $objp->total_tva;
792
-				$line->total_localtax1	= $objp->total_localtax1;
793
-				$line->total_localtax2	= $objp->total_localtax2;
794
-				$line->total_ttc		= $objp->total_ttc;
795
-				$line->fk_product		= (($objp->fk_product > 0)?$objp->fk_product:0);
796
-				$line->info_bits		= $objp->info_bits;
797
-
798
-				$line->fk_fournprice 	= $objp->fk_fournprice;
799
-				$marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
800
-				$line->pa_ht 			= $marginInfos[0];
801
-
802
-				$line->fk_user_author	= $objp->fk_user_author;
803
-				$line->fk_user_ouverture= $objp->fk_user_ouverture;
804
-				$line->fk_user_cloture  = $objp->fk_user_cloture;
805
-				$line->fk_unit           = $objp->fk_unit;
806
-
807
-				$line->ref				= $objp->product_ref;	// deprecated
808
-				$line->product_ref		= $objp->product_ref;   // Product Ref
809
-				$line->product_desc		= $objp->product_desc;  // Product Description
810
-				$line->product_label	= $objp->product_label; // Product Label
811
-
812
-				$line->description		= $objp->description;
813
-
814
-				$line->date_start            = $this->db->jdate($objp->date_ouverture_prevue);
815
-				$line->date_start_real       = $this->db->jdate($objp->date_ouverture);
816
-				$line->date_end              = $this->db->jdate($objp->date_fin_validite);
817
-				$line->date_end_real         = $this->db->jdate($objp->date_cloture);
818
-				// For backward compatibility
819
-				$line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
820
-				$line->date_ouverture        = $this->db->jdate($objp->date_ouverture);
821
-				$line->date_fin_validite     = $this->db->jdate($objp->date_fin_validite);
822
-				$line->date_cloture          = $this->db->jdate($objp->date_cloture);
823
-				$line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
824
-				$line->date_debut_reel   = $this->db->jdate($objp->date_ouverture);
825
-				$line->date_fin_prevue   = $this->db->jdate($objp->date_fin_validite);
826
-				$line->date_fin_reel     = $this->db->jdate($objp->date_cloture);
827
-
828
-				// Retreive all extrafields for contract
829
-				// fetch optionals attributes and labels
830
-				$line->fetch_optionals();
831
-
832
-				$this->lines[$pos]			= $line;
833
-				$this->lines_id_index_mapper[$line->id] = $pos;
834
-
835
-				//dol_syslog("1 ".$line->desc);
836
-				//dol_syslog("2 ".$line->product_desc);
837
-
838
-				if ($line->statut == ContratLigne::STATUS_INITIAL) $this->nbofserviceswait++;
839
-				if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++;
840
-				if ($line->statut == ContratLigne::STATUS_OPEN && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++;
841
-				if ($line->statut == ContratLigne::STATUS_CLOSED) $this->nbofservicesclosed++;
842
-
843
-				$total_ttc+=$objp->total_ttc;   // TODO Not saved into database
844
-                $total_vat+=$objp->total_tva;
845
-                $total_ht+=$objp->total_ht;
1745
+            // Call trigger
1746
+            $result=$this->call_trigger('LINECONTRACT_DELETE',$user);
1747
+            if ($result < 0) return -1;
1748
+            // End call triggers
846 1749
 
847
-				$i++;
848
-				$pos++;
849
-			}
850
-			$this->db->free($result);
851
-		}
852
-		else
853
-		{
854
-			dol_syslog(get_class($this)."::Fetch Erreur lecture des lignes de contrats liees aux produits");
855
-			return -3;
856
-		}
857
-
858
-		$this->nbofservices=count($this->lines);
859
-        $this->total_ttc = price2num($total_ttc);   // TODO For the moment value is false as value is not stored in database for line linked to products
860
-        $this->total_vat = price2num($total_vat);   // TODO For the moment value is false as value is not stored in database for line linked to products
861
-        $this->total_ht = price2num($total_ht);     // TODO For the moment value is false as value is not stored in database for line linked to products
1750
+            $this->db->begin();
862 1751
 
863
-		return $this->lines;
864
-	}
865
-
866
-	/**
867
-	 *  Create a contract into database
868
-	 *
869
-	 *  @param	User	$user       User that create
870
-	 *  @return int  				<0 if KO, id of contract if OK
871
-	 */
872
-	function create($user)
873
-	{
874
-		global $conf,$langs,$mysoc;
875
-
876
-		// Check parameters
877
-		$paramsok=1;
878
-		if ($this->commercial_signature_id <= 0)
879
-		{
880
-			$langs->load("commercial");
881
-			$this->error.=$langs->trans("ErrorFieldRequired",$langs->trans("SalesRepresentativeSignature"));
882
-			$paramsok=0;
883
-		}
884
-		if ($this->commercial_suivi_id <= 0)
885
-		{
886
-			$langs->load("commercial");
887
-			$this->error.=($this->error?"<br>":'');
888
-			$this->error.=$langs->trans("ErrorFieldRequired",$langs->trans("SalesRepresentativeFollowUp"));
889
-			$paramsok=0;
890
-		}
891
-		if (! $paramsok) return -1;
892
-
893
-
894
-		$this->db->begin();
895
-
896
-		$now=dol_now();
897
-
898
-		// Insert contract
899
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
900
-		$sql.= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
901
-		$sql.= " ref, entity, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
902
-		$sql.= " VALUES ('".$this->db->idate($now)."',".$this->socid.",".$user->id;
903
-		$sql.= ", ".(dol_strlen($this->date_contrat)!=0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
904
-		$sql.= ",".($this->commercial_signature_id>0?$this->commercial_signature_id:"NULL");
905
-		$sql.= ",".($this->commercial_suivi_id>0?$this->commercial_suivi_id:"NULL");
906
-		$sql.= ",".($this->fk_project>0?$this->fk_project:"NULL");
907
-		$sql.= ", ".(dol_strlen($this->ref)<=0 ? "null" : "'".$this->db->escape($this->ref)."'");
908
-		$sql.= ", ".$conf->entity;
909
-		$sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL");
910
-		$sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL");
911
-		$sql.= ", ".(!empty($this->ref_customer)?("'".$this->db->escape($this->ref_customer)."'"):"NULL");
912
-		$sql.= ", ".(!empty($this->ref_supplier)?("'".$this->db->escape($this->ref_supplier)."'"):"NULL");
913
-		$sql.= ", ".(!empty($this->ref_ext)?("'".$this->db->escape($this->ref_ext)."'"):"NULL");
914
-		$sql.= ")";
915
-		$resql=$this->db->query($sql);
916
-		if ($resql)
917
-		{
918
-			$error=0;
919
-
920
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
921
-
922
-			// Load object modContract
923
-			$module=(! empty($conf->global->CONTRACT_ADDON)?$conf->global->CONTRACT_ADDON:'mod_contract_serpis');
924
-			if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php')
925
-			{
926
-				$module = substr($module, 0, dol_strlen($module)-4);
927
-			}
928
-			$result=dol_include_once('/core/modules/contract/'.$module.'.php');
929
-			if ($result > 0)
930
-			{
931
-				$modCodeContract = new $module();
932
-
933
-				if (!empty($modCodeContract->code_auto)) {
934
-					// Update ref
935
-					$sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id;
936
-					if ($this->db->query($sql))
937
-					{
938
-						if ($this->id)
939
-						{
940
-							$this->ref="(PROV".$this->id.")";
941
-						}
942
-					}
943
-				} else {
944
-					$error++;
945
-					$this->error='Failed to get PROV number';
946
-				}
947
-			}
948
-
949
-			if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))
950
-			{
951
-				$result=$this->insertExtraFields();
952
-				if ($result < 0)
953
-				{
954
-					$error++;
955
-				}
956
-			}
957
-
958
-			// Insert business contacts ('SALESREPSIGN','contrat')
959
-			if (! $error)
960
-			{
961
-    			$result=$this->add_contact($this->commercial_signature_id,'SALESREPSIGN','internal');
962
-    			if ($result < 0) $error++;
963
-			}
964
-
965
-			// Insert business contacts ('SALESREPFOLL','contrat')
966
-			if (! $error)
967
-			{
968
-                $result=$this->add_contact($this->commercial_suivi_id,'SALESREPFOLL','internal');
969
-			    if ($result < 0) $error++;
970
-			}
971
-
972
-			if (! $error)
973
-			{
974
-				if (! empty($this->linkedObjectsIds) && empty($this->linked_objects))	// To use new linkedObjectsIds instead of old linked_objects
975
-				{
976
-					$this->linked_objects = $this->linkedObjectsIds;	// TODO Replace linked_objects with linkedObjectsIds
977
-				}
978
-
979
-				// Add object linked
980
-    			if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
981
-    			{
982
-    			    foreach($this->linked_objects as $origin => $tmp_origin_id)
983
-    			    {
984
-    			        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, ...))
985
-    			        {
986
-    			            foreach($tmp_origin_id as $origin_id)
987
-    			            {
988
-    			                $ret = $this->add_object_linked($origin, $origin_id);
989
-    			                if (! $ret)
990
-    			                {
991
-    			                    $this->error=$this->db->lasterror();
992
-    			                    $error++;
993
-    			                }
994
-    			            }
995
-    			        }
996
-    			        else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
997
-    			        {
998
-    			            $origin_id = $tmp_origin_id;
999
-    			            $ret = $this->add_object_linked($origin, $origin_id);
1000
-    			            if (! $ret)
1001
-    			            {
1002
-    			                $this->error=$this->db->lasterror();
1003
-    			                $error++;
1004
-    			            }
1005
-    			        }
1006
-    			    }
1007
-    			}
1008
-
1009
-    			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
1010
-    			{
1011
-    			    $originforcontact = $this->origin;
1012
-    			    $originidforcontact = $this->origin_id;
1013
-    			    if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
1014
-    			    {
1015
-    			        require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
1016
-    			        $exp = new Expedition($db);
1017
-    			        $exp->fetch($this->origin_id);
1018
-    			        $exp->fetchObjectLinked();
1019
-    			        if (count($exp->linkedObjectsIds['commande']) > 0)
1020
-    			        {
1021
-    			            foreach ($exp->linkedObjectsIds['commande'] as $key => $value)
1022
-    			            {
1023
-    			                $originforcontact = 'commande';
1024
-    			                $originidforcontact = $value->id;
1025
-    			                break; // We take first one
1026
-    			            }
1027
-    			        }
1028
-    			    }
1029
-
1030
-    			    $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";
1031
-    			    $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
1032
-
1033
-    			    $resqlcontact = $this->db->query($sqlcontact);
1034
-    			    if ($resqlcontact)
1035
-    			    {
1036
-    			        while($objcontact = $this->db->fetch_object($resqlcontact))
1037
-    			        {
1038
-    			            if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) continue;    // ignore this, already forced previously
1039
-
1040
-    			            //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1041
-    			            $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
1042
-    			        }
1043
-    			    }
1044
-    			    else dol_print_error($resqlcontact);
1045
-    			}
1046
-			}
1047
-
1048
-			if (! $error)
1049
-			{
1050
-                // Call trigger
1051
-                $result=$this->call_trigger('CONTRACT_CREATE',$user);
1052
-                if ($result < 0) { $error++; }
1053
-                // End call triggers
1752
+            $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1753
+            $sql.= " WHERE rowid=".$idline;
1054 1754
 
1055
-				if (! $error)
1056
-				{
1057
-					$this->db->commit();
1058
-					return $this->id;
1059
-				}
1060
-				else
1061
-				{
1062
-					dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR);
1063
-					$this->db->rollback();
1064
-					return -3;
1065
-				}
1066
-			}
1067
-			else
1068
-			{
1069
-				$this->error="Failed to add contract";
1070
-				dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1071
-				$this->db->rollback();
1072
-				return -2;
1073
-			}
1074
-		}
1075
-		else
1076
-		{
1077
-			$this->error=$langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
1078
-
1079
-			$this->db->rollback();
1080
-			return -1;
1081
-		}
1082
-	}
1083
-
1084
-
1085
-	/**
1086
-	 *  Supprime l'objet de la base
1087
-	 *
1088
-	 *  @param	User		$user       Utilisateur qui supprime
1089
-	 *  @return int         			< 0 si erreur, > 0 si ok
1090
-	 */
1091
-	function delete($user)
1092
-	{
1093
-		global $conf, $langs;
1094
-		require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1095
-
1096
-		$error=0;
1097
-
1098
-		$this->db->begin();
1099
-
1100
-	    // Call trigger
1101
-	    $result=$this->call_trigger('CONTRACT_DELETE',$user);
1102
-	    if ($result < 0) { $error++; }
1103
-	    // End call triggers
1104
-
1105
-		if (! $error)
1106
-		{
1107
-			// Delete linked contacts
1108
-			$res = $this->delete_linked_contact();
1109
-			if ($res < 0)
1110
-			{
1111
-				dol_syslog(get_class($this)."::delete error", LOG_ERR);
1112
-				$error++;
1113
-			}
1114
-		}
1115
-
1116
-		if (! $error)
1117
-		{
1118
-			// Delete linked object
1119
-			$res = $this->deleteObjectLinked();
1120
-			if ($res < 0) $error++;
1121
-		}
1122
-
1123
-		if (! $error)
1124
-		{
1125
-			// Delete contratdet_log
1126
-			/*
1127
-			$sql = "DELETE cdl";
1128
-			$sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1129
-			$sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".$this->id;
1130
-			*/
1131
-			$sql = "SELECT cdl.rowid as cdlrowid ";
1132
-			$sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1133
-			$sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".$this->id;
1755
+            dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1756
+            $resql = $this->db->query($sql);
1757
+            if (! $resql)
1758
+            {
1759
+                $this->error="Error ".$this->db->lasterror();
1760
+                $error++;
1761
+            }
1134 1762
 
1135
-			dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1136
-			$resql=$this->db->query($sql);
1137
-			if (! $resql)
1138
-			{
1139
-				$this->error=$this->db->error();
1140
-				$error++;
1141
-			}
1142
-			$numressql=$this->db->num_rows($resql);
1143
-			if (! $error && $numressql )
1144
-			{
1145
-				$tab_resql=array();
1146
-				for($i=0;$i<$numressql;$i++)
1147
-				{
1148
-					$objresql=$this->db->fetch_object($resql);
1149
-					$tab_resql[]= $objresql->cdlrowid;
1150
-				}
1151
-				$this->db->free($resql);
1152
-
1153
-				$sql= "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log ";
1154
-				$sql.= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".implode(",",$tab_resql).")";
1155
-
1156
-				dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1157
-				$resql=$this->db->query($sql);
1158
-				if (! $resql)
1159
-				{
1160
-					$this->error=$this->db->error();
1161
-					$error++;
1162
-				}
1163
-			}
1164
-		}
1165
-
1166
-		if (! $error)
1167
-		{
1168
-			// Delete contratdet
1169
-			$sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1170
-			$sql.= " WHERE fk_contrat=".$this->id;
1171
-
1172
-			dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1173
-			$resql=$this->db->query($sql);
1174
-			if (! $resql)
1175
-			{
1176
-				$this->error=$this->db->error();
1177
-				$error++;
1178
-			}
1179
-		}
1180
-
1181
-		if (! $error)
1182
-		{
1183
-			// Delete contrat
1184
-			$sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1185
-			$sql.= " WHERE rowid=".$this->id;
1186
-
1187
-			dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1188
-			$resql=$this->db->query($sql);
1189
-			if (! $resql)
1190
-			{
1191
-				$this->error=$this->db->error();
1192
-				$error++;
1193
-			}
1194
-		}
1195
-
1196
-		// Removed extrafields
1197
-		if (! $error) {
1198
-			$result=$this->deleteExtraFields();
1199
-			if ($result < 0)
1200
-			{
1201
-				$error++;
1202
-				dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1203
-			}
1204
-		}
1205
-
1206
-		if (! $error)
1207
-		{
1208
-			// We remove directory
1209
-			$ref = dol_sanitizeFileName($this->ref);
1210
-			if ($conf->contrat->dir_output)
1211
-			{
1212
-				$dir = $conf->contrat->dir_output . "/" . $ref;
1213
-				if (file_exists($dir))
1214
-				{
1215
-					$res=@dol_delete_dir_recursive($dir);
1216
-					if (! $res)
1217
-					{
1218
-						$this->error='ErrorFailToDeleteDir';
1219
-						$error++;
1220
-					}
1221
-				}
1222
-			}
1223
-		}
1224
-
1225
-		if (! $error)
1226
-		{
1227
-			$this->db->commit();
1228
-			return 1;
1229
-		}
1230
-		else
1231
-		{
1232
-			$this->error=$this->db->lasterror();
1233
-			$this->db->rollback();
1234
-			return -1;
1235
-		}
1236
-	}
1237
-
1238
-	/**
1239
-	 *  Update object into database
1240
-	 *
1241
-	 *  @param	User	$user        User that modifies
1242
-	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
1243
-	 *  @return int     		   	 <0 if KO, >0 if OK
1244
-	 */
1245
-	function update($user, $notrigger=0)
1246
-	{
1247
-		global $conf, $langs;
1248
-		$error=0;
1249
-
1250
-		// Clean parameters
1251
-		if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) $this->fk_commercial_signature = $this->commercial_signature_id;
1252
-		if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) $this->fk_commercial_suivi = $this->commercial_suivi_id;
1253
-		if (empty($this->fk_soc) && $this->socid > 0) $this->fk_soc = $this->socid;
1254
-		if (empty($this->fk_project) && $this->projet > 0) $this->fk_project = $this->projet;
1255
-
1256
-		if (isset($this->ref)) $this->ref=trim($this->ref);
1257
-		if (isset($this->ref_customer)) $this->ref_customer=trim($this->ref_customer);
1258
-		if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
1259
-		if (isset($this->ref_ext)) $this->ref_ext=trim($this->ref_ext);
1260
-		if (isset($this->entity)) $this->entity=trim($this->entity);
1261
-		if (isset($this->statut)) $this->statut=(int) $this->statut;
1262
-		if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
1263
-		if (isset($this->fk_commercial_signature)) $this->fk_commercial_signature=trim($this->fk_commercial_signature);
1264
-		if (isset($this->fk_commercial_suivi)) $this->fk_commercial_suivi=trim($this->fk_commercial_suivi);
1265
-		if (isset($this->fk_user_mise_en_service)) $this->fk_user_mise_en_service=trim($this->fk_user_mise_en_service);
1266
-		if (isset($this->fk_user_cloture)) $this->fk_user_cloture=trim($this->fk_user_cloture);
1267
-		if (isset($this->note_private)) $this->note_private=trim($this->note_private);
1268
-		if (isset($this->note_public)) $this->note_public=trim($this->note_public);
1269
-		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
1270
-		//if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
1271
-
1272
-		// Check parameters
1273
-		// Put here code to add a control on parameters values
1274
-
1275
-		// Update request
1276
-    	$sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1277
-		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
1278
-		$sql.= " ref_customer=".(isset($this->ref_customer)?"'".$this->db->escape($this->ref_customer)."'":"null").",";
1279
-		$sql.= " ref_supplier=".(isset($this->ref_supplier)?"'".$this->db->escape($this->ref_supplier)."'":"null").",";
1280
-		$sql.= " ref_ext=".(isset($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null").",";
1281
-		$sql.= " entity=".$conf->entity.",";
1282
-		$sql.= " date_contrat=".(dol_strlen($this->date_contrat)!=0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1283
-		$sql.= " statut=".(isset($this->statut)?$this->statut:"null").",";
1284
-		$sql.= " mise_en_service=".(dol_strlen($this->mise_en_service)!=0 ? "'".$this->db->idate($this->mise_en_service)."'" : 'null').",";
1285
-		$sql.= " fin_validite=".(dol_strlen($this->fin_validite)!=0 ? "'".$this->db->idate($this->fin_validite)."'" : 'null').",";
1286
-		$sql.= " date_cloture=".(dol_strlen($this->date_cloture)!=0 ? "'".$this->db->idate($this->date_cloture)."'" : 'null').",";
1287
-		$sql.= " fk_soc=".($this->fk_soc > 0 ? $this->fk_soc:"null").",";
1288
-		$sql.= " fk_projet=".($this->fk_project > 0 ? $this->fk_project:"null").",";
1289
-		$sql.= " fk_commercial_signature=".(isset($this->fk_commercial_signature)?$this->fk_commercial_signature:"null").",";
1290
-		$sql.= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi)?$this->fk_commercial_suivi:"null").",";
1291
-		$sql.= " fk_user_mise_en_service=".(isset($this->fk_user_mise_en_service)?$this->fk_user_mise_en_service:"null").",";
1292
-		$sql.= " fk_user_cloture=".(isset($this->fk_user_cloture)?$this->fk_user_cloture:"null").",";
1293
-		$sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
1294
-		$sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
1295
-		$sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
1296
-		//$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null")."";
1297
-		$sql.= " WHERE rowid=".$this->id;
1298
-
1299
-		$this->db->begin();
1300
-
1301
-		$resql = $this->db->query($sql);
1302
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
1303
-
1304
-		if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
1305
-		{
1306
-			$result=$this->insertExtraFields();
1307
-			if ($result < 0)
1308
-			{
1309
-				$error++;
1310
-			}
1311
-		}
1312
-
1313
-		if (! $error && ! $notrigger)
1314
-		{
1315
-			// Call triggers
1316
-			$result=$this->call_trigger('CONTRACT_MODIFY',$user);
1317
-			if ($result < 0) { $error++; }
1318
-			// End call triggers
1319
-		}
1320
-
1321
-		// Commit or rollback
1322
-		if ($error)
1323
-		{
1324
-			foreach($this->errors as $errmsg)
1325
-			{
1326
-				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1327
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
1328
-			}
1329
-			$this->db->rollback();
1330
-			return -1*$error;
1331
-		}
1332
-		else
1333
-		{
1334
-			$this->db->commit();
1335
-			return 1;
1336
-		}
1337
-	}
1338
-
1339
-
1340
-	/**
1341
-	 *  Ajoute une ligne de contrat en base
1342
-	 *
1343
-	 *  @param	string		$desc            	Description de la ligne
1344
-	 *  @param  float		$pu_ht              Prix unitaire HT
1345
-	 *  @param  int			$qty             	Quantite
1346
-	 *  @param  float		$txtva           	Taux tva
1347
-	 *  @param  float		$txlocaltax1        Local tax 1 rate
1348
-	 *  @param  float		$txlocaltax2        Local tax 2 rate
1349
-	 *  @param  int			$fk_product      	Id produit
1350
-	 *  @param  float		$remise_percent  	Pourcentage de remise de la ligne
1351
-	 *  @param  int			$date_start      	Date de debut prevue
1352
-	 *  @param  int			$date_end        	Date de fin prevue
1353
-	 *	@param	string		$price_base_type	HT or TTC
1354
-	 * 	@param  float		$pu_ttc             Prix unitaire TTC
1355
-	 * 	@param  int			$info_bits			Bits de type de lignes
1356
-	 * 	@param  int			$fk_fournprice		Fourn price id
1357
-	 *  @param  int			$pa_ht				Buying price HT
1358
-	 *  @param	array		$array_options		extrafields array
1359
-	 * 	@param 	string		$fk_unit 			Code of the unit to use. Null to use the default one
1360
-	 * 	@param 	string		$rang 				Position
1361
-	 *  @return int             				<0 if KO, >0 if OK
1362
-	 */
1363
-	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null, $rang=0)
1364
-	{
1365
-		global $user, $langs, $conf, $mysoc;
1366
-		$error=0;
1367
-
1368
-		dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang");
1369
-
1370
-		// Check parameters
1371
-		if ($fk_product <= 0 && empty($desc))
1372
-		{
1373
-			$this->error="ErrorDescRequiredForFreeProductLines";
1374
-			return -1;
1375
-		}
1376
-
1377
-		if ($this->statut >= 0)
1378
-		{
1379
-			$this->db->begin();
1380
-
1381
-			// Clean parameters
1382
-			$pu_ht=price2num($pu_ht);
1383
-			$pu_ttc=price2num($pu_ttc);
1384
-			$pa_ht=price2num($pa_ht);
1385
-			if (!preg_match('/\((.*)\)/', $txtva)) {
1386
-				$txtva = price2num($txtva);               // $txtva can have format '5.0(XXX)' or '5'
1387
-			}
1388
-			$txlocaltax1=price2num($txlocaltax1);
1389
-			$txlocaltax2=price2num($txlocaltax2);
1390
-			$remise_percent=price2num($remise_percent);
1391
-			$qty=price2num($qty);
1392
-			if (empty($qty)) $qty=1;
1393
-			if (empty($info_bits)) $info_bits=0;
1394
-			if (empty($pu_ht) || ! is_numeric($pu_ht))  $pu_ht=0;
1395
-			if (empty($pu_ttc)) $pu_ttc=0;
1396
-			if (empty($txtva) || ! is_numeric($txtva)) $txtva=0;
1397
-			if (empty($txlocaltax1) || ! is_numeric($txlocaltax1)) $txlocaltax1=0;
1398
-            if (empty($txlocaltax2) || ! is_numeric($txlocaltax2)) $txlocaltax2=0;
1763
+            if (empty($error)) {
1764
+                // Remove extrafields
1765
+                if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1766
+                {
1767
+                    $contractline = new ContratLigne($this->db);
1768
+                    $contractline->id= $idline;
1769
+                    $result=$contractline->deleteExtraFields();
1770
+                    if ($result < 0)
1771
+                    {
1772
+                        $error++;
1773
+                        $this->error="Error ".get_class($this)."::delete deleteExtraFields error -4 ".$contractline->error;
1774
+                    }
1775
+                }
1776
+            }
1399 1777
 
1400
-			if ($price_base_type=='HT')
1401
-			{
1402
-				$pu=$pu_ht;
1403
-			}
1404
-			else
1405
-			{
1406
-				$pu=$pu_ttc;
1407
-			}
1408
-
1409
-			// Check parameters
1410
-			if (empty($remise_percent)) $remise_percent=0;
1411
-
1412
-			$localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->societe, $mysoc);
1413
-
1414
-			// Clean vat code
1415
-			$vat_src_code='';
1416
-			if (preg_match('/\((.*)\)/', $txtva, $reg))
1417
-			{
1418
-				$vat_src_code = $reg[1];
1419
-				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1420
-			}
1421
-
1422
-			// Calcul du total TTC et de la TVA pour la ligne a partir de
1423
-			// qty, pu, remise_percent et txtva
1424
-			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1425
-			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1426
-
1427
-			$tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1,$mysoc, $localtaxes_type);
1428
-			$total_ht  = $tabprice[0];
1429
-			$total_tva = $tabprice[1];
1430
-			$total_ttc = $tabprice[2];
1431
-			$total_localtax1= $tabprice[9];
1432
-			$total_localtax2= $tabprice[10];
1433
-
1434
-			$localtax1_type=$localtaxes_type[0];
1435
-			$localtax2_type=$localtaxes_type[2];
1436
-
1437
-			// TODO A virer
1438
-			// Anciens indicateurs: $price, $remise (a ne plus utiliser)
1439
-			$remise = 0;
1440
-			$price = price2num(round($pu_ht, 2));
1441
-			if (dol_strlen($remise_percent) > 0)
1442
-			{
1443
-				$remise = round(($pu_ht * $remise_percent / 100), 2);
1444
-				$price = $pu_ht - $remise;
1445
-			}
1446
-
1447
-		    if (empty($pa_ht)) $pa_ht=0;
1448
-
1449
-
1450
-			// if buy price not defined, define buyprice as configured in margin admin
1451
-			if ($this->pa_ht == 0)
1452
-			{
1453
-				if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0)
1454
-				{
1455
-					return $result;
1456
-				}
1457
-				else
1458
-				{
1459
-					$pa_ht = $result;
1460
-				}
1461
-			}
1462
-
1463
-			// Insertion dans la base
1464
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1465
-			$sql.= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1466
-			$sql.= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1467
-			$sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1468
-			$sql.= " info_bits,";
1469
-			$sql.= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
1470
-			if ($date_start > 0) { $sql.= ",date_ouverture_prevue"; }
1471
-			if ($date_end > 0)   { $sql.= ",date_fin_validite"; }
1472
-			$sql.= ", fk_unit";
1473
-			$sql.= ") VALUES (";
1474
-			$sql.= $this->id.", '', '" . $this->db->escape($desc) . "',";
1475
-			$sql.= ($fk_product>0 ? $fk_product : "null").",";
1476
-			$sql.= " ".$qty.",";
1477
-			$sql.= " ".$txtva.",";
1478
-			$sql.= " ".($vat_src_code?"'".$vat_src_code."'":"null").",";
1479
-			$sql.= " ".$txlocaltax1.",";
1480
-			$sql.= " ".$txlocaltax2.",";
1481
-			$sql.= " '".$localtax1_type."',";
1482
-			$sql.= " '".$localtax2_type."',";
1483
-			$sql.= " ".price2num($remise_percent).",";
1484
-			$sql.= " ".price2num($pu_ht).",";
1485
-			$sql.= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1486
-			$sql.= " '".$info_bits."',";
1487
-			$sql.= " ".price2num($price).",".price2num($remise).",";
1488
-			if (isset($fk_fournprice)) $sql.= ' '.$fk_fournprice.',';
1489
-			else $sql.= ' null,';
1490
-			if (isset($pa_ht)) $sql.= ' '.price2num($pa_ht);
1491
-			else $sql.= ' null';
1492
-			if ($date_start > 0) { $sql.= ",'".$this->db->idate($date_start)."'"; }
1493
-			if ($date_end > 0) { $sql.= ",'".$this->db->idate($date_end)."'"; }
1494
-			$sql.= ", ".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
1495
-			$sql.= ")";
1496
-
1497
-			$resql=$this->db->query($sql);
1498
-			if ($resql)
1499
-			{
1500
-				$contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1501
-
1502
-				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
1503
-				{
1504
-					$contractline = new ContratLigne($this->db);
1505
-					$contractline->array_options=$array_options;
1506
-					$contractline->id=$contractlineid;
1507
-					$result=$contractline->insertExtraFields();
1508
-					if ($result < 0)
1509
-					{
1510
-						$this->error[]=$contractline->error;
1511
-						$error++;
1512
-					}
1513
-				}
1514
-
1515
-				if (empty($error)) {
1516
-				    // Call trigger
1517
-				    $result=$this->call_trigger('LINECONTRACT_INSERT',$user);
1518
-				    if ($result < 0)
1519
-				    {
1520
-				    	$error++;
1521
-				    }
1522
-				    // End call triggers
1523
-				}
1524
-
1525
-				if ($error)
1526
-				{
1527
-					$this->db->rollback();
1528
-					return -1;
1529
-				}
1530
-				else
1531
-				{
1532
-					$this->db->commit();
1533
-					return $contractlineid;
1534
-				}
1535
-			}
1536
-			else
1537
-			{
1538
-				$this->db->rollback();
1539
-				$this->error=$this->db->error()." sql=".$sql;
1540
-				return -1;
1541
-			}
1542
-		}
1543
-		else
1544
-		{
1545
-			dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1546
-			return -2;
1547
-		}
1548
-	}
1549
-
1550
-	/**
1551
-	 *  Mets a jour une ligne de contrat
1552
-	 *
1553
-	 *  @param	int			$rowid            	Id de la ligne de facture
1554
-	 *  @param  string		$desc             	Description de la ligne
1555
-	 *  @param  float		$pu               	Prix unitaire
1556
-	 *  @param  int			$qty              	Quantite
1557
-	 *  @param  float		$remise_percent   	Pourcentage de remise de la ligne
1558
-	 *  @param  int			$date_start       	Date de debut prevue
1559
-	 *  @param  int			$date_end         	Date de fin prevue
1560
-	 *  @param  float		$tvatx            	Taux TVA
1561
-	 *  @param  float		$localtax1tx      	Local tax 1 rate
1562
-	 *  @param  float		$localtax2tx      	Local tax 2 rate
1563
-	 *  @param  int|string	$date_debut_reel  	Date de debut reelle
1564
-	 *  @param  int|string	$date_fin_reel    	Date de fin reelle
1565
-	 *	@param	string		$price_base_type	HT or TTC
1566
-	 * 	@param  int			$info_bits			Bits de type de lignes
1567
-	 * 	@param  int			$fk_fournprice		Fourn price id
1568
-	 *  @param  int			$pa_ht				Buying price HT
1569
-	 *  @param	array		$array_options		extrafields array
1570
-	 * 	@param 	string		$fk_unit 			Code of the unit to use. Null to use the default one
1571
-	 *  @return int              				< 0 si erreur, > 0 si ok
1572
-	 */
1573
-	function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx=0.0, $localtax2tx=0.0, $date_debut_reel='', $date_fin_reel='', $price_base_type='HT', $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null)
1574
-	{
1575
-		global $user, $conf, $langs, $mysoc;
1576
-
1577
-		$error=0;
1578
-
1579
-		// Clean parameters
1580
-		$qty=trim($qty);
1581
-		$desc=trim($desc);
1582
-		$desc=trim($desc);
1583
-		$price = price2num($pu);
1584
-		$tvatx = price2num($tvatx);
1585
-		$localtax1tx = price2num($localtax1tx);
1586
-		$localtax2tx = price2num($localtax2tx);
1587
-		$pa_ht=price2num($pa_ht);
1588
-		if (empty($fk_fournprice)) $fk_fournprice=0;
1589
-
1590
-		$subprice = $price;
1591
-		$remise = 0;
1592
-		if (dol_strlen($remise_percent) > 0)
1593
-		{
1594
-			$remise = round(($pu * $remise_percent / 100), 2);
1595
-			$price = $pu - $remise;
1596
-		}
1597
-		else
1598
-		{
1599
-			$remise_percent=0;
1600
-		}
1601
-
1602
-		dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $date_debut_reel, $date_fin_reel, $tvatx, $localtax1tx, $localtax2tx, $price_base_type, $info_bits");
1603
-
1604
-		$this->db->begin();
1605
-
1606
-		// Calcul du total TTC et de la TVA pour la ligne a partir de
1607
-		// qty, pu, remise_percent et tvatx
1608
-		// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1609
-		// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1610
-
1611
-		$localtaxes_type=getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1612
-		$tvatx = preg_replace('/\s*\(.*\)/','',$tvatx);  // Remove code into vatrate.
1613
-
1614
-		$tabprice=calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1615
-		$total_ht  = $tabprice[0];
1616
-		$total_tva = $tabprice[1];
1617
-		$total_ttc = $tabprice[2];
1618
-		$total_localtax1= $tabprice[9];
1619
-		$total_localtax2= $tabprice[10];
1620
-
1621
-		$localtax1_type=$localtaxes_type[0];
1622
-		$localtax2_type=$localtaxes_type[2];
1623
-
1624
-		// TODO A virer
1625
-		// Anciens indicateurs: $price, $remise (a ne plus utiliser)
1626
-		$remise = 0;
1627
-		$price = price2num(round($pu, 2));
1628
-		if (dol_strlen($remise_percent) > 0)
1629
-		{
1630
-		    $remise = round(($pu * $remise_percent / 100), 2);
1631
-		    $price = $pu - $remise;
1632
-		}
1633
-
1634
-	    if (empty($pa_ht)) $pa_ht=0;
1635
-
1636
-		// if buy price not defined, define buyprice as configured in margin admin
1637
-		if ($this->pa_ht == 0)
1638
-		{
1639
-			if (($result = $this->defineBuyPrice($pu_ht, $remise_percent)) < 0)
1640
-			{
1641
-				return $result;
1642
-			}
1643
-			else
1644
-			{
1645
-				$pa_ht = $result;
1646
-			}
1647
-		}
1648
-
1649
-		$sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description='".$this->db->escape($desc)."'";
1650
-		$sql.= ",price_ht='" .     price2num($price)."'";
1651
-		$sql.= ",subprice='" .     price2num($subprice)."'";
1652
-		$sql.= ",remise='" .       price2num($remise)."'";
1653
-		$sql.= ",remise_percent='".price2num($remise_percent)."'";
1654
-		$sql.= ",qty='".$qty."'";
1655
-		$sql.= ",tva_tx='".        price2num($tvatx)."'";
1656
-		$sql.= ",localtax1_tx='".  price2num($localtax1tx)."'";
1657
-		$sql.= ",localtax2_tx='".  price2num($localtax2tx)."'";
1658
-		$sql.= ",localtax1_type='".$localtax1_type."'";
1659
-		$sql.= ",localtax2_type='".$localtax2_type."'";
1660
-		$sql.= ", total_ht='".     price2num($total_ht)."'";
1661
-		$sql.= ", total_tva='".    price2num($total_tva)."'";
1662
-		$sql.= ", total_localtax1='".price2num($total_localtax1)."'";
1663
-		$sql.= ", total_localtax2='".price2num($total_localtax2)."'";
1664
-		$sql.= ", total_ttc='".      price2num($total_ttc)."'";
1665
-		$sql.= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1666
-		$sql.= ", buy_price_ht='".price2num($pa_ht)."'";
1667
-		if ($date_start > 0) { $sql.= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; }
1668
-		else { $sql.=",date_ouverture_prevue=null"; }
1669
-		if ($date_end > 0) { $sql.= ",date_fin_validite='".$this->db->idate($date_end)."'"; }
1670
-		else { $sql.=",date_fin_validite=null"; }
1671
-		if ($date_debut_reel > 0) { $sql.= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; }
1672
-		else { $sql.=",date_ouverture=null"; }
1673
-		if ($date_fin_reel > 0) { $sql.= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; }
1674
-		else { $sql.=",date_cloture=null"; }
1675
-		$sql .= ", fk_unit=".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
1676
-		$sql .= " WHERE rowid = ".$rowid;
1677
-
1678
-		dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1679
-		$result = $this->db->query($sql);
1680
-		if ($result)
1681
-		{
1682
-			$result=$this->update_statut($user);
1683
-			if ($result >= 0)
1684
-			{
1685
-
1686
-				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
1687
-				{
1688
-					$contractline = new ContratLigne($this->db);
1689
-					$contractline->array_options=$array_options;
1690
-					$contractline->id= $rowid;
1691
-					$result=$contractline->insertExtraFields();
1692
-					if ($result < 0)
1693
-					{
1694
-						$this->error[]=$contractline->error;
1695
-						$error++;
1696
-					}
1697
-				}
1698
-
1699
-				if (empty($error)) {
1700
-			        // Call trigger
1701
-			        $result=$this->call_trigger('LINECONTRACT_UPDATE',$user);
1702
-			        if ($result < 0)
1703
-			        {
1704
-			            $this->db->rollback();
1705
-			            return -3;
1706
-			        }
1707
-			        // End call triggers
1708
-
1709
-					$this->db->commit();
1710
-					return 1;
1711
-				}
1712
-			}
1713
-			else
1714
-			{
1715
-				$this->db->rollback();
1716
-				dol_syslog(get_class($this)."::updateline Erreur -2");
1717
-				return -2;
1718
-			}
1719
-		}
1720
-		else
1721
-		{
1722
-			$this->db->rollback();
1723
-			$this->error=$this->db->error();
1724
-			dol_syslog(get_class($this)."::updateline Erreur -1");
1725
-			return -1;
1726
-		}
1727
-	}
1728
-
1729
-	/**
1730
-	 *  Delete a contract line
1731
-	 *
1732
-	 *  @param	int		$idline		Id of line to delete
1733
-	 *	@param  User	$user       User that delete
1734
-	 *  @return int         		>0 if OK, <0 if KO
1735
-	 */
1736
-	function deleteline($idline, User $user)
1737
-	{
1738
-		global $conf, $langs;
1739
-
1740
-		$error=0;
1741
-
1742
-		if ($this->statut >= 0)
1743
-		{
1744
-
1745
-		    // Call trigger
1746
-		    $result=$this->call_trigger('LINECONTRACT_DELETE',$user);
1747
-		    if ($result < 0) return -1;
1748
-		    // End call triggers
1749
-
1750
-		    $this->db->begin();
1751
-
1752
-			$sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1753
-			$sql.= " WHERE rowid=".$idline;
1754
-
1755
-			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1756
-			$resql = $this->db->query($sql);
1757
-			if (! $resql)
1758
-			{
1759
-				$this->error="Error ".$this->db->lasterror();
1760
-				$error++;
1761
-			}
1762
-
1763
-			if (empty($error)) {
1764
-				// Remove extrafields
1765
-				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1766
-				{
1767
-					$contractline = new ContratLigne($this->db);
1768
-					$contractline->id= $idline;
1769
-					$result=$contractline->deleteExtraFields();
1770
-					if ($result < 0)
1771
-					{
1772
-						$error++;
1773
-						$this->error="Error ".get_class($this)."::delete deleteExtraFields error -4 ".$contractline->error;
1774
-					}
1775
-				}
1776
-			}
1777
-
1778
-			if (empty($error)) {
1779
-				$this->db->commit();
1780
-				return 1;
1781
-			} else {
1782
-				dol_syslog(get_class($this)."::delete ERROR:".$this->error, LOG_ERR);
1783
-				$this->db->rollback();
1784
-				return -1;
1785
-			}
1786
-		}
1787
-		else
1788
-		{
1789
-			$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1790
-			return -2;
1791
-		}
1792
-	}
1778
+            if (empty($error)) {
1779
+                $this->db->commit();
1780
+                return 1;
1781
+            } else {
1782
+                dol_syslog(get_class($this)."::delete ERROR:".$this->error, LOG_ERR);
1783
+                $this->db->rollback();
1784
+                return -1;
1785
+            }
1786
+        }
1787
+        else
1788
+        {
1789
+            $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1790
+            return -2;
1791
+        }
1792
+    }
1793 1793
 
1794 1794
 
1795 1795
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1796
-	/**
1797
-	 *  Update statut of contract according to services
1798
-	 *
1799
-	 *	@param	User	$user		Object user
1800
-	 *	@return int     			<0 if KO, >0 if OK
1801
-	 *  @deprecated					This function will never be used. Status of a contract is status of its lines.
1802
-	 */
1803
-	function update_statut($user)
1804
-	{
1796
+    /**
1797
+     *  Update statut of contract according to services
1798
+     *
1799
+     *	@param	User	$user		Object user
1800
+     *	@return int     			<0 if KO, >0 if OK
1801
+     *  @deprecated					This function will never be used. Status of a contract is status of its lines.
1802
+     */
1803
+    function update_statut($user)
1804
+    {
1805 1805
         // phpcs:enable
1806
-		dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
1806
+        dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
1807 1807
 
1808
-		// If draft, we keep it (should not happen)
1809
-		if ($this->statut == 0) return 1;
1808
+        // If draft, we keep it (should not happen)
1809
+        if ($this->statut == 0) return 1;
1810 1810
 
1811
-		// Load $this->lines array
1812
-		//		$this->fetch_lines();
1811
+        // Load $this->lines array
1812
+        //		$this->fetch_lines();
1813 1813
 
1814 1814
 //		$newstatut=1;
1815 1815
 //		foreach($this->lines as $key => $contractline)
@@ -1817,113 +1817,113 @@  discard block
 block discarded – undo
1817 1817
 //			//			if ($contractline)         // Loop on each service
1818 1818
 //		}
1819 1819
 
1820
-		return 1;
1821
-	}
1820
+        return 1;
1821
+    }
1822 1822
 
1823 1823
 
1824
-	/**
1825
-	 *  Return label of a contract status
1826
-	 *
1827
-	 *  @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Long label of all services, 5=Libelle court + Picto, 6=Picto of all services, 7=Same than 6 with fixed length
1828
-	 *  @return string      		Label
1829
-	 */
1830
-	function getLibStatut($mode)
1831
-	{
1832
-		return $this->LibStatut($this->statut,$mode);
1833
-	}
1824
+    /**
1825
+     *  Return label of a contract status
1826
+     *
1827
+     *  @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Long label of all services, 5=Libelle court + Picto, 6=Picto of all services, 7=Same than 6 with fixed length
1828
+     *  @return string      		Label
1829
+     */
1830
+    function getLibStatut($mode)
1831
+    {
1832
+        return $this->LibStatut($this->statut,$mode);
1833
+    }
1834 1834
 
1835 1835
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1836
-	/**
1837
-	 *  Renvoi label of a given contrat status
1838
-	 *
1839
-	 *  @param	int		$statut      	Status id
1840
-	 *  @param  int		$mode          	0=Long label, 1=Short label, 2=Picto + Libelle court, 3=Picto, 4=Picto + Long label of all services, 5=Libelle court + Picto, 6=Picto of all services, 7=Same than 6 with fixed length
1841
-	 *	@return string      			Label
1842
-	 */
1843
-	function LibStatut($statut,$mode)
1844
-	{
1836
+    /**
1837
+     *  Renvoi label of a given contrat status
1838
+     *
1839
+     *  @param	int		$statut      	Status id
1840
+     *  @param  int		$mode          	0=Long label, 1=Short label, 2=Picto + Libelle court, 3=Picto, 4=Picto + Long label of all services, 5=Libelle court + Picto, 6=Picto of all services, 7=Same than 6 with fixed length
1841
+     *	@return string      			Label
1842
+     */
1843
+    function LibStatut($statut,$mode)
1844
+    {
1845 1845
         // phpcs:enable
1846
-		global $langs;
1847
-		$langs->load("contracts");
1848
-		if ($mode == 0)
1849
-		{
1850
-			if ($statut == 0) { return $langs->trans("ContractStatusDraft"); }
1851
-			elseif ($statut == 1) { return $langs->trans("ContractStatusValidated"); }
1852
-			elseif ($statut == 2) { return $langs->trans("ContractStatusClosed"); }
1853
-		}
1854
-		elseif ($mode == 1)
1855
-		{
1856
-			if ($statut == 0) { return $langs->trans("ContractStatusDraft"); }
1857
-			elseif ($statut == 1) { return $langs->trans("ContractStatusValidated"); }
1858
-			elseif ($statut == 2) { return $langs->trans("ContractStatusClosed"); }
1859
-		}
1860
-		elseif ($mode == 2)
1861
-		{
1862
-			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0').' '.$langs->trans("ContractStatusDraft"); }
1863
-			elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4').' '.$langs->trans("ContractStatusValidated"); }
1864
-			elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6').' '.$langs->trans("ContractStatusClosed"); }
1865
-		}
1866
-		elseif ($mode == 3)
1867
-		{
1868
-			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0'); }
1869
-			elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4'); }
1870
-			elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1871
-		}
1872
-		elseif ($mode == 4 || $mode == 6 || $mode == 7)
1873
-		{
1874
-			$text='';
1875
-			if ($mode == 4)
1876
-			{
1877
-				$text ='<span class="hideonsmartphone">';
1878
-				$text.=($this->nbofserviceswait+$this->nbofservicesopened+$this->nbofservicesexpired+$this->nbofservicesclosed);
1879
-				$text.=' '.$langs->trans("Services");
1880
-				$text.=': &nbsp; &nbsp; ';
1881
-				$text.='</span>';
1882
-			}
1883
-			$text.=($mode == 7?'<div class="inline-block">':'');
1884
-			$text.=($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0,3,-1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed)?' &nbsp; ':'') : '';
1885
-			$text.=($mode == 7?'</div><div class="inline-block">':'');
1886
-			$text.=($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4,3,0,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed)?' &nbsp; ':'') : '';
1887
-			$text.=($mode == 7?'</div><div class="inline-block">':'');
1888
-			$text.=($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4,3,1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesclosed)?' &nbsp; ':'') : '';
1889
-			$text.=($mode == 7?'</div><div class="inline-block">':'');
1890
-			$text.=($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5,3,-1,'class="paddingleft2 inline-block valigntextbottom"')) : '';
1891
-			$text.=($mode == 7?'</div>':'');
1892
-			return $text;
1893
-		}
1894
-		elseif ($mode == 5)
1895
-		{
1896
-			if ($statut == 0) { return $langs->trans("ContractStatusDraft").' '.img_picto($langs->trans('ContractStatusDraft'),'statut0'); }
1897
-			elseif ($statut == 1) { return $langs->trans("ContractStatusValidated").' '.img_picto($langs->trans('ContractStatusValidated'),'statut4'); }
1898
-			elseif ($statut == 2) { return $langs->trans("ContractStatusClosed").' '.img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1899
-		}
1900
-	}
1901
-
1902
-
1903
-	/**
1904
-	 *	Return clicable name (with picto eventually)
1905
-	 *
1906
-	 *	@param	int		$withpicto					0=No picto, 1=Include picto into link, 2=Only picto
1907
-	 *	@param	int		$maxlength					Max length of ref
1846
+        global $langs;
1847
+        $langs->load("contracts");
1848
+        if ($mode == 0)
1849
+        {
1850
+            if ($statut == 0) { return $langs->trans("ContractStatusDraft"); }
1851
+            elseif ($statut == 1) { return $langs->trans("ContractStatusValidated"); }
1852
+            elseif ($statut == 2) { return $langs->trans("ContractStatusClosed"); }
1853
+        }
1854
+        elseif ($mode == 1)
1855
+        {
1856
+            if ($statut == 0) { return $langs->trans("ContractStatusDraft"); }
1857
+            elseif ($statut == 1) { return $langs->trans("ContractStatusValidated"); }
1858
+            elseif ($statut == 2) { return $langs->trans("ContractStatusClosed"); }
1859
+        }
1860
+        elseif ($mode == 2)
1861
+        {
1862
+            if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0').' '.$langs->trans("ContractStatusDraft"); }
1863
+            elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4').' '.$langs->trans("ContractStatusValidated"); }
1864
+            elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6').' '.$langs->trans("ContractStatusClosed"); }
1865
+        }
1866
+        elseif ($mode == 3)
1867
+        {
1868
+            if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0'); }
1869
+            elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4'); }
1870
+            elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1871
+        }
1872
+        elseif ($mode == 4 || $mode == 6 || $mode == 7)
1873
+        {
1874
+            $text='';
1875
+            if ($mode == 4)
1876
+            {
1877
+                $text ='<span class="hideonsmartphone">';
1878
+                $text.=($this->nbofserviceswait+$this->nbofservicesopened+$this->nbofservicesexpired+$this->nbofservicesclosed);
1879
+                $text.=' '.$langs->trans("Services");
1880
+                $text.=': &nbsp; &nbsp; ';
1881
+                $text.='</span>';
1882
+            }
1883
+            $text.=($mode == 7?'<div class="inline-block">':'');
1884
+            $text.=($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0,3,-1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed)?' &nbsp; ':'') : '';
1885
+            $text.=($mode == 7?'</div><div class="inline-block">':'');
1886
+            $text.=($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4,3,0,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed)?' &nbsp; ':'') : '';
1887
+            $text.=($mode == 7?'</div><div class="inline-block">':'');
1888
+            $text.=($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4,3,1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesclosed)?' &nbsp; ':'') : '';
1889
+            $text.=($mode == 7?'</div><div class="inline-block">':'');
1890
+            $text.=($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5,3,-1,'class="paddingleft2 inline-block valigntextbottom"')) : '';
1891
+            $text.=($mode == 7?'</div>':'');
1892
+            return $text;
1893
+        }
1894
+        elseif ($mode == 5)
1895
+        {
1896
+            if ($statut == 0) { return $langs->trans("ContractStatusDraft").' '.img_picto($langs->trans('ContractStatusDraft'),'statut0'); }
1897
+            elseif ($statut == 1) { return $langs->trans("ContractStatusValidated").' '.img_picto($langs->trans('ContractStatusValidated'),'statut4'); }
1898
+            elseif ($statut == 2) { return $langs->trans("ContractStatusClosed").' '.img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1899
+        }
1900
+    }
1901
+
1902
+
1903
+    /**
1904
+     *	Return clicable name (with picto eventually)
1905
+     *
1906
+     *	@param	int		$withpicto					0=No picto, 1=Include picto into link, 2=Only picto
1907
+     *	@param	int		$maxlength					Max length of ref
1908 1908
      *  @param	int     $notooltip					1=Disable tooltip
1909 1909
      *  @param  int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1910
-	 *	@return	string								Chaine avec URL
1911
-	 */
1912
-	function getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1)
1913
-	{
1914
-		global $conf, $langs, $user;
1910
+     *	@return	string								Chaine avec URL
1911
+     */
1912
+    function getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1)
1913
+    {
1914
+        global $conf, $langs, $user;
1915 1915
 
1916
-		$result='';
1916
+        $result='';
1917 1917
 
1918
-		$url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
1918
+        $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
1919 1919
 
1920
-		//if ($option !== 'nolink')
1921
-		//{
1922
-			// Add param to save lastsearch_values or not
1923
-			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1924
-			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1925
-			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1926
-		//}
1920
+        //if ($option !== 'nolink')
1921
+        //{
1922
+            // Add param to save lastsearch_values or not
1923
+            $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1924
+            if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1925
+            if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1926
+        //}
1927 1927
 
1928 1928
         $label = '';
1929 1929
 
@@ -1951,501 +1951,501 @@  discard block
 block discarded – undo
1951 1951
                 $label=$langs->trans("ShowOrder");
1952 1952
                 $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1953 1953
             }
1954
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1955
-            $linkclose.=' class="classfortooltip"';
1954
+            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1955
+            $linkclose.=' class="classfortooltip"';
1956
+        }
1957
+
1958
+        $linkstart = '<a href="'.$url.'"';
1959
+        $linkstart.=$linkclose.'>';
1960
+        $linkend='</a>';
1961
+
1962
+        $result .= $linkstart;
1963
+        if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
1964
+        if ($withpicto != 2) $result.= $this->ref;
1965
+        $result .= $linkend;
1966
+
1967
+        return $result;
1968
+    }
1969
+
1970
+    /**
1971
+     *  Charge les informations d'ordre info dans l'objet contrat
1972
+     *
1973
+     *  @param  int		$id     id du contrat a charger
1974
+     *  @return	void
1975
+     */
1976
+    function info($id)
1977
+    {
1978
+        $sql = "SELECT c.rowid, c.ref, c.datec, c.date_cloture,";
1979
+        $sql.= " c.tms as date_modification,";
1980
+        $sql.= " fk_user_author, fk_user_cloture";
1981
+        $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
1982
+        $sql.= " WHERE c.rowid = ".$id;
1983
+
1984
+        $result=$this->db->query($sql);
1985
+        if ($result)
1986
+        {
1987
+            if ($this->db->num_rows($result))
1988
+            {
1989
+                $obj = $this->db->fetch_object($result);
1990
+
1991
+                $this->id = $obj->rowid;
1992
+
1993
+                if ($obj->fk_user_author) {
1994
+                    $cuser = new User($this->db);
1995
+                    $cuser->fetch($obj->fk_user_author);
1996
+                    $this->user_creation     = $cuser;
1997
+                }
1998
+
1999
+                if ($obj->fk_user_cloture) {
2000
+                    $cuser = new User($this->db);
2001
+                    $cuser->fetch($obj->fk_user_cloture);
2002
+                    $this->user_cloture = $cuser;
2003
+                }
2004
+                $this->ref			     = (! $obj->ref) ? $obj->rowid : $obj->ref;
2005
+                $this->date_creation     = $this->db->jdate($obj->datec);
2006
+                $this->date_modification = $this->db->jdate($obj->date_modification);
2007
+                $this->date_cloture      = $this->db->jdate($obj->date_cloture);
2008
+            }
2009
+
2010
+            $this->db->free($result);
2011
+        }
2012
+        else
2013
+        {
2014
+            dol_print_error($this->db);
2015
+        }
2016
+    }
2017
+
2018
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2019
+    /**
2020
+     *  Return list of line rowid
2021
+     *
2022
+     *  @param	int		$statut     Status of lines to get
2023
+     *  @return array       		Array of line's rowid
2024
+     */
2025
+    function array_detail($statut=-1)
2026
+    {
2027
+        // phpcs:enable
2028
+        $tab=array();
2029
+
2030
+        $sql = "SELECT cd.rowid";
2031
+        $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2032
+        $sql.= " WHERE fk_contrat =".$this->id;
2033
+        if ($statut >= 0) $sql.= " AND statut = '$statut'";
2034
+
2035
+        dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2036
+        $resql=$this->db->query($sql);
2037
+        if ($resql)
2038
+        {
2039
+            $num=$this->db->num_rows($resql);
2040
+            $i=0;
2041
+            while ($i < $num)
2042
+            {
2043
+                $obj = $this->db->fetch_object($resql);
2044
+                $tab[$i]=$obj->rowid;
2045
+                $i++;
2046
+            }
2047
+            return $tab;
2048
+        }
2049
+        else
2050
+        {
2051
+            $this->error=$this->db->error();
2052
+            return -1;
2053
+        }
2054
+    }
2055
+
2056
+    /**
2057
+     *  Return list of other contracts for same company than current contract
2058
+     *
2059
+     *	@param	string		$option		'all' or 'others'
2060
+     *  @return array   				Array of contracts id
2061
+     */
2062
+    function getListOfContracts($option='all')
2063
+    {
2064
+        $tab=array();
2065
+
2066
+        $sql = "SELECT c.rowid, c.ref";
2067
+        $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
2068
+        $sql.= " WHERE fk_soc =".$this->socid;
2069
+        if ($option == 'others') $sql.= " AND c.rowid != ".$this->id;
2070
+
2071
+        dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2072
+        $resql=$this->db->query($sql);
2073
+        if ($resql)
2074
+        {
2075
+            $num=$this->db->num_rows($resql);
2076
+            $i=0;
2077
+            while ($i < $num)
2078
+            {
2079
+                $obj = $this->db->fetch_object($resql);
2080
+                $contrat=new Contrat($this->db);
2081
+                $contrat->fetch($obj->rowid);
2082
+                $tab[]=$contrat;
2083
+                $i++;
2084
+            }
2085
+            return $tab;
2086
+        }
2087
+        else
2088
+        {
2089
+            $this->error=$this->db->error();
2090
+            return -1;
2091
+        }
2092
+    }
2093
+
2094
+
2095
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2096
+    /**
2097
+     *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
2098
+     *
2099
+     *      @param	User	$user           Objet user
2100
+     *      @param  string	$mode           "inactive" pour services a activer, "expired" pour services expires
2101
+     *      @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
2102
+     */
2103
+    function load_board($user,$mode)
2104
+    {
2105
+        // phpcs:enable
2106
+        global $conf, $langs;
2107
+
2108
+        $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2109
+        $this->from.= ", ".MAIN_DB_PREFIX."contratdet as cd";
2110
+        $this->from.= ", ".MAIN_DB_PREFIX."societe as s";
2111
+        if (!$user->rights->societe->client->voir && !$user->societe_id) $this->from.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2112
+
2113
+        if ($mode == 'inactives')
2114
+        {
2115
+            $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2116
+            $sql.= $this->from;
2117
+            $sql.= " WHERE c.statut = 1";
2118
+            $sql.= " AND c.rowid = cd.fk_contrat";
2119
+            $sql.= " AND cd.statut = 0";
2120
+        }
2121
+        elseif ($mode == 'expired')
2122
+        {
2123
+            $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2124
+            $sql.= $this->from;
2125
+            $sql.= " WHERE c.statut = 1";
2126
+            $sql.= " AND c.rowid = cd.fk_contrat";
2127
+            $sql.= " AND cd.statut = 4";
2128
+            $sql.= " AND cd.date_fin_validite < '".$this->db->idate(time())."'";
2129
+        }
2130
+        $sql.= " AND c.fk_soc = s.rowid";
2131
+        $sql.= " AND c.entity = ".$conf->entity;
2132
+        if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
2133
+        if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id;
2134
+        $resql=$this->db->query($sql);
2135
+        if ($resql)
2136
+        {
2137
+            $langs->load("contracts");
2138
+            $now=dol_now();
2139
+
2140
+            if ($mode == 'inactives') {
2141
+                $warning_delay = $conf->contrat->services->inactifs->warning_delay;
2142
+                $label = $langs->trans("BoardNotActivatedServices");
2143
+                $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&amp;leftmenu=contracts&amp;mode=0';
2144
+            } else {
2145
+                $warning_delay = $conf->contrat->services->expires->warning_delay;
2146
+                $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&amp;leftmenu=contracts&amp;mode=4&amp;filter=expired';
2147
+                $label = $langs->trans("BoardRunningServices");
2148
+            }
2149
+
2150
+            $response = new WorkboardResponse();
2151
+            $response->warning_delay = $warning_delay/60/60/24;
2152
+            $response->label = $label;
2153
+            $response->url = $url;
2154
+            $response->img = img_object('',"contract");
2155
+
2156
+            while ($obj=$this->db->fetch_object($resql))
2157
+            {
2158
+                $response->nbtodo++;
2159
+
2160
+                if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2161
+                    $response->nbtodolate++;
2162
+                }
2163
+            }
2164
+
2165
+            return $response;
2166
+        }
2167
+        else
2168
+        {
2169
+            dol_print_error($this->db);
2170
+            $this->error=$this->db->error();
2171
+            return -1;
2172
+        }
2173
+    }
2174
+
2175
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2176
+    /**
2177
+     *   Charge indicateurs this->nb de tableau de bord
2178
+     *
2179
+     *   @return     int         <0 si ko, >0 si ok
2180
+     */
2181
+    function load_state_board()
2182
+    {
2183
+        // phpcs:enable
2184
+        global $conf, $user;
2185
+
2186
+        $this->nb=array();
2187
+        $clause = "WHERE";
2188
+
2189
+        $sql = "SELECT count(c.rowid) as nb";
2190
+        $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
2191
+        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2192
+        if (!$user->rights->societe->client->voir && !$user->societe_id)
2193
+        {
2194
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2195
+            $sql.= " WHERE sc.fk_user = " .$user->id;
2196
+            $clause = "AND";
2197
+        }
2198
+        $sql.= " ".$clause." c.entity = ".$conf->entity;
2199
+
2200
+        $resql=$this->db->query($sql);
2201
+        if ($resql)
2202
+        {
2203
+            while ($obj=$this->db->fetch_object($resql))
2204
+            {
2205
+                $this->nb["Contracts"]=$obj->nb;
2206
+            }
2207
+            $this->db->free($resql);
2208
+            return 1;
2209
+        }
2210
+        else
2211
+        {
2212
+            dol_print_error($this->db);
2213
+            $this->error=$this->db->error();
2214
+            return -1;
2215
+        }
2216
+    }
2217
+
2218
+
2219
+    /* gestion des contacts d'un contrat */
2220
+
2221
+    /**
2222
+     *  Return id des contacts clients de facturation
2223
+     *
2224
+     *  @return     array       Liste des id contacts facturation
2225
+     */
2226
+    function getIdBillingContact()
2227
+    {
2228
+        return $this->getIdContact('external','BILLING');
2229
+    }
2230
+
2231
+    /**
2232
+     *  Return id des contacts clients de prestation
2233
+     *
2234
+     *  @return     array       Liste des id contacts prestation
2235
+     */
2236
+    function getIdServiceContact()
2237
+    {
2238
+        return $this->getIdContact('external','SERVICE');
2239
+    }
2240
+
2241
+
2242
+    /**
2243
+     *  Initialise an instance with random values.
2244
+     *  Used to build previews or test instances.
2245
+     *	id must be 0 if object instance is a specimen.
2246
+     *
2247
+     *  @return	void
2248
+     */
2249
+    function initAsSpecimen()
2250
+    {
2251
+        global $user,$langs,$conf;
2252
+
2253
+        // Load array of products prodids
2254
+        $num_prods = 0;
2255
+        $prodids = array();
2256
+        $sql = "SELECT rowid";
2257
+        $sql.= " FROM ".MAIN_DB_PREFIX."product";
2258
+        $sql.= " WHERE entity IN (".getEntity('product').")";
2259
+        $sql.= " AND tosell = 1";
2260
+        $resql = $this->db->query($sql);
2261
+        if ($resql)
2262
+        {
2263
+            $num_prods = $this->db->num_rows($resql);
2264
+            $i = 0;
2265
+            while ($i < $num_prods)
2266
+            {
2267
+                $i++;
2268
+                $row = $this->db->fetch_row($resql);
2269
+                $prodids[$i] = $row[0];
2270
+            }
2271
+        }
2272
+
2273
+        // Initialise parametres
2274
+        $this->id=0;
2275
+        $this->specimen=1;
2276
+
2277
+        $this->ref = 'SPECIMEN';
2278
+        $this->ref_customer = 'SPECIMENCUST';
2279
+        $this->ref_supplier = 'SPECIMENSUPP';
2280
+        $this->socid = 1;
2281
+        $this->statut= 0;
2282
+        $this->date_creation = (dol_now() - 3600 * 24 * 7);
2283
+        $this->date_contrat = dol_now();
2284
+        $this->commercial_signature_id = 1;
2285
+        $this->commercial_suivi_id = 1;
2286
+        $this->note_private='This is a comment (private)';
2287
+        $this->note_public='This is a comment (public)';
2288
+        $this->fk_projet = 0;
2289
+        // Lines
2290
+        $nbp = 5;
2291
+        $xnbp = 0;
2292
+        while ($xnbp < $nbp)
2293
+        {
2294
+            $line=new ContratLigne($this->db);
2295
+            $line->qty=1;
2296
+            $line->subprice=100;
2297
+            $line->price=100;
2298
+            $line->tva_tx=19.6;
2299
+            $line->remise_percent=10;
2300
+            $line->total_ht=90;
2301
+            $line->total_ttc=107.64;	// 90 * 1.196
2302
+            $line->total_tva=17.64;
2303
+            $line->date_start = dol_now() - 500000;
2304
+            $line->date_start_real = dol_now() - 200000;
2305
+            $line->date_end = dol_now() + 500000;
2306
+            $line->date_end_real = dol_now() - 100000;
2307
+            if ($num_prods > 0)
2308
+            {
2309
+                $prodid = mt_rand(1, $num_prods);
2310
+                $line->fk_product=$prodids[$prodid];
2311
+            }
2312
+            $this->lines[$xnbp]=$line;
2313
+            $xnbp++;
2314
+        }
2315
+    }
2316
+
2317
+    /**
2318
+     * 	Create an array of order lines
2319
+     *
2320
+     * 	@return int		>0 if OK, <0 if KO
2321
+     */
2322
+    function getLinesArray()
2323
+    {
2324
+        return $this->fetch_lines();
2325
+    }
2326
+
2327
+
2328
+    /**
2329
+     *  Create a document onto disk according to template module.
2330
+     *
2331
+     * 	@param	    string		$modele			Force model to use ('' to not force)
2332
+     * 	@param		Translate	$outputlangs	Object langs to use for output
2333
+     *  @param      int			$hidedetails    Hide details of lines
2334
+     *  @param      int			$hidedesc       Hide description
2335
+     *  @param      int			$hideref        Hide ref
2336
+     *  @param   null|array  $moreparams     Array to provide more information
2337
+     * 	@return     int         				0 if KO, 1 if OK
2338
+     */
2339
+    public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
2340
+    {
2341
+        global $conf,$langs;
2342
+
2343
+        $langs->load("contracts");
2344
+
2345
+        if (! dol_strlen($modele)) {
2346
+
2347
+            $modele = 'strato';
2348
+
2349
+            if ($this->modelpdf) {
2350
+                $modele = $this->modelpdf;
2351
+            } elseif (! empty($conf->global->CONTRACT_ADDON_PDF)) {
2352
+                $modele = $conf->global->CONTRACT_ADDON_PDF;
2353
+            }
1956 2354
         }
1957 2355
 
1958
-		$linkstart = '<a href="'.$url.'"';
1959
-		$linkstart.=$linkclose.'>';
1960
-		$linkend='</a>';
1961
-
1962
-		$result .= $linkstart;
1963
-		if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
1964
-		if ($withpicto != 2) $result.= $this->ref;
1965
-		$result .= $linkend;
1966
-
1967
-		return $result;
1968
-	}
1969
-
1970
-	/**
1971
-	 *  Charge les informations d'ordre info dans l'objet contrat
1972
-	 *
1973
-	 *  @param  int		$id     id du contrat a charger
1974
-	 *  @return	void
1975
-	 */
1976
-	function info($id)
1977
-	{
1978
-		$sql = "SELECT c.rowid, c.ref, c.datec, c.date_cloture,";
1979
-		$sql.= " c.tms as date_modification,";
1980
-		$sql.= " fk_user_author, fk_user_cloture";
1981
-		$sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
1982
-		$sql.= " WHERE c.rowid = ".$id;
1983
-
1984
-		$result=$this->db->query($sql);
1985
-		if ($result)
1986
-		{
1987
-			if ($this->db->num_rows($result))
1988
-			{
1989
-				$obj = $this->db->fetch_object($result);
1990
-
1991
-				$this->id = $obj->rowid;
1992
-
1993
-				if ($obj->fk_user_author) {
1994
-					$cuser = new User($this->db);
1995
-					$cuser->fetch($obj->fk_user_author);
1996
-					$this->user_creation     = $cuser;
1997
-				}
1998
-
1999
-				if ($obj->fk_user_cloture) {
2000
-					$cuser = new User($this->db);
2001
-					$cuser->fetch($obj->fk_user_cloture);
2002
-					$this->user_cloture = $cuser;
2003
-				}
2004
-				$this->ref			     = (! $obj->ref) ? $obj->rowid : $obj->ref;
2005
-				$this->date_creation     = $this->db->jdate($obj->datec);
2006
-				$this->date_modification = $this->db->jdate($obj->date_modification);
2007
-				$this->date_cloture      = $this->db->jdate($obj->date_cloture);
2008
-			}
2009
-
2010
-			$this->db->free($result);
2011
-		}
2012
-		else
2013
-		{
2014
-			dol_print_error($this->db);
2015
-		}
2016
-	}
2017
-
2018
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2019
-	/**
2020
-	 *  Return list of line rowid
2021
-	 *
2022
-	 *  @param	int		$statut     Status of lines to get
2023
-	 *  @return array       		Array of line's rowid
2024
-	 */
2025
-	function array_detail($statut=-1)
2026
-	{
2027
-        // phpcs:enable
2028
-		$tab=array();
2029
-
2030
-		$sql = "SELECT cd.rowid";
2031
-		$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2032
-		$sql.= " WHERE fk_contrat =".$this->id;
2033
-		if ($statut >= 0) $sql.= " AND statut = '$statut'";
2034
-
2035
-		dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2036
-		$resql=$this->db->query($sql);
2037
-		if ($resql)
2038
-		{
2039
-			$num=$this->db->num_rows($resql);
2040
-			$i=0;
2041
-			while ($i < $num)
2042
-			{
2043
-				$obj = $this->db->fetch_object($resql);
2044
-				$tab[$i]=$obj->rowid;
2045
-				$i++;
2046
-			}
2047
-			return $tab;
2048
-		}
2049
-		else
2050
-		{
2051
-			$this->error=$this->db->error();
2052
-			return -1;
2053
-		}
2054
-	}
2055
-
2056
-	/**
2057
-	 *  Return list of other contracts for same company than current contract
2058
-	 *
2059
-	 *	@param	string		$option		'all' or 'others'
2060
-	 *  @return array   				Array of contracts id
2061
-	 */
2062
-	function getListOfContracts($option='all')
2063
-	{
2064
-		$tab=array();
2065
-
2066
-		$sql = "SELECT c.rowid, c.ref";
2067
-		$sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
2068
-		$sql.= " WHERE fk_soc =".$this->socid;
2069
-		if ($option == 'others') $sql.= " AND c.rowid != ".$this->id;
2070
-
2071
-		dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2072
-		$resql=$this->db->query($sql);
2073
-		if ($resql)
2074
-		{
2075
-			$num=$this->db->num_rows($resql);
2076
-			$i=0;
2077
-			while ($i < $num)
2078
-			{
2079
-				$obj = $this->db->fetch_object($resql);
2080
-				$contrat=new Contrat($this->db);
2081
-				$contrat->fetch($obj->rowid);
2082
-				$tab[]=$contrat;
2083
-				$i++;
2084
-			}
2085
-			return $tab;
2086
-		}
2087
-		else
2088
-		{
2089
-			$this->error=$this->db->error();
2090
-			return -1;
2091
-		}
2092
-	}
2356
+        $modelpath = "core/modules/contract/doc/";
2093 2357
 
2358
+        return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2359
+    }
2094 2360
 
2095
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2096
-	/**
2097
-     *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
2361
+    /**
2362
+     * Function used to replace a thirdparty id with another one.
2098 2363
      *
2099
-     *      @param	User	$user           Objet user
2100
-     *      @param  string	$mode           "inactive" pour services a activer, "expired" pour services expires
2101
-     *      @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
2102
-	 */
2103
-	function load_board($user,$mode)
2104
-	{
2105
-        // phpcs:enable
2106
-		global $conf, $langs;
2107
-
2108
-		$this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2109
-		$this->from.= ", ".MAIN_DB_PREFIX."contratdet as cd";
2110
-		$this->from.= ", ".MAIN_DB_PREFIX."societe as s";
2111
-		if (!$user->rights->societe->client->voir && !$user->societe_id) $this->from.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2112
-
2113
-		if ($mode == 'inactives')
2114
-		{
2115
-			$sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2116
-			$sql.= $this->from;
2117
-			$sql.= " WHERE c.statut = 1";
2118
-			$sql.= " AND c.rowid = cd.fk_contrat";
2119
-			$sql.= " AND cd.statut = 0";
2120
-		}
2121
-		elseif ($mode == 'expired')
2122
-		{
2123
-			$sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2124
-			$sql.= $this->from;
2125
-			$sql.= " WHERE c.statut = 1";
2126
-			$sql.= " AND c.rowid = cd.fk_contrat";
2127
-			$sql.= " AND cd.statut = 4";
2128
-			$sql.= " AND cd.date_fin_validite < '".$this->db->idate(time())."'";
2129
-		}
2130
-		$sql.= " AND c.fk_soc = s.rowid";
2131
-		$sql.= " AND c.entity = ".$conf->entity;
2132
-		if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
2133
-		if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id;
2134
-		$resql=$this->db->query($sql);
2135
-		if ($resql)
2136
-		{
2137
-			$langs->load("contracts");
2138
-			$now=dol_now();
2139
-
2140
-			if ($mode == 'inactives') {
2141
-				$warning_delay = $conf->contrat->services->inactifs->warning_delay;
2142
-				$label = $langs->trans("BoardNotActivatedServices");
2143
-				$url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&amp;leftmenu=contracts&amp;mode=0';
2144
-			} else {
2145
-				$warning_delay = $conf->contrat->services->expires->warning_delay;
2146
-				$url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&amp;leftmenu=contracts&amp;mode=4&amp;filter=expired';
2147
-				$label = $langs->trans("BoardRunningServices");
2148
-			}
2149
-
2150
-			$response = new WorkboardResponse();
2151
-			$response->warning_delay = $warning_delay/60/60/24;
2152
-			$response->label = $label;
2153
-			$response->url = $url;
2154
-			$response->img = img_object('',"contract");
2155
-
2156
-			while ($obj=$this->db->fetch_object($resql))
2157
-			{
2158
-				$response->nbtodo++;
2159
-
2160
-				if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
2161
-					$response->nbtodolate++;
2162
-				}
2163
-			}
2164
-
2165
-			return $response;
2166
-		}
2167
-		else
2168
-		{
2169
-			dol_print_error($this->db);
2170
-			$this->error=$this->db->error();
2171
-			return -1;
2172
-		}
2173
-	}
2364
+     * @param DoliDB $db Database handler
2365
+     * @param int $origin_id Old thirdparty id
2366
+     * @param int $dest_id New thirdparty id
2367
+     * @return bool
2368
+     */
2369
+    public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
2370
+    {
2371
+        $tables = array(
2372
+            'contrat'
2373
+        );
2174 2374
 
2175
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2176
-	/**
2177
-	 *   Charge indicateurs this->nb de tableau de bord
2178
-	 *
2179
-	 *   @return     int         <0 si ko, >0 si ok
2180
-	 */
2181
-	function load_state_board()
2182
-	{
2183
-        // phpcs:enable
2184
-		global $conf, $user;
2185
-
2186
-		$this->nb=array();
2187
-		$clause = "WHERE";
2188
-
2189
-		$sql = "SELECT count(c.rowid) as nb";
2190
-		$sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
2191
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2192
-		if (!$user->rights->societe->client->voir && !$user->societe_id)
2193
-		{
2194
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2195
-			$sql.= " WHERE sc.fk_user = " .$user->id;
2196
-			$clause = "AND";
2197
-		}
2198
-		$sql.= " ".$clause." c.entity = ".$conf->entity;
2199
-
2200
-		$resql=$this->db->query($sql);
2201
-		if ($resql)
2202
-		{
2203
-			while ($obj=$this->db->fetch_object($resql))
2204
-			{
2205
-				$this->nb["Contracts"]=$obj->nb;
2206
-			}
2207
-            $this->db->free($resql);
2208
-			return 1;
2209
-		}
2210
-		else
2211
-		{
2212
-			dol_print_error($this->db);
2213
-			$this->error=$this->db->error();
2214
-			return -1;
2215
-		}
2216
-	}
2217
-
2218
-
2219
-	/* gestion des contacts d'un contrat */
2220
-
2221
-	/**
2222
-	 *  Return id des contacts clients de facturation
2223
-	 *
2224
-	 *  @return     array       Liste des id contacts facturation
2225
-	 */
2226
-	function getIdBillingContact()
2227
-	{
2228
-		return $this->getIdContact('external','BILLING');
2229
-	}
2230
-
2231
-	/**
2232
-	 *  Return id des contacts clients de prestation
2233
-	 *
2234
-	 *  @return     array       Liste des id contacts prestation
2235
-	 */
2236
-	function getIdServiceContact()
2237
-	{
2238
-		return $this->getIdContact('external','SERVICE');
2239
-	}
2240
-
2241
-
2242
-	/**
2243
-     *  Initialise an instance with random values.
2244
-     *  Used to build previews or test instances.
2245
-     *	id must be 0 if object instance is a specimen.
2246
-     *
2247
-     *  @return	void
2248
-	 */
2249
-	function initAsSpecimen()
2250
-	{
2251
-		global $user,$langs,$conf;
2375
+        return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2376
+    }
2252 2377
 
2253
-        // Load array of products prodids
2254
-		$num_prods = 0;
2255
-		$prodids = array();
2256
-		$sql = "SELECT rowid";
2257
-		$sql.= " FROM ".MAIN_DB_PREFIX."product";
2258
-		$sql.= " WHERE entity IN (".getEntity('product').")";
2259
-		$sql.= " AND tosell = 1";
2260
-		$resql = $this->db->query($sql);
2261
-		if ($resql)
2262
-		{
2263
-			$num_prods = $this->db->num_rows($resql);
2264
-			$i = 0;
2265
-			while ($i < $num_prods)
2266
-			{
2267
-				$i++;
2268
-				$row = $this->db->fetch_row($resql);
2269
-				$prodids[$i] = $row[0];
2270
-			}
2271
-		}
2272
-
2273
-		// Initialise parametres
2274
-		$this->id=0;
2275
-		$this->specimen=1;
2276
-
2277
-		$this->ref = 'SPECIMEN';
2278
-		$this->ref_customer = 'SPECIMENCUST';
2279
-		$this->ref_supplier = 'SPECIMENSUPP';
2280
-		$this->socid = 1;
2281
-		$this->statut= 0;
2282
-		$this->date_creation = (dol_now() - 3600 * 24 * 7);
2283
-		$this->date_contrat = dol_now();
2284
-		$this->commercial_signature_id = 1;
2285
-		$this->commercial_suivi_id = 1;
2286
-		$this->note_private='This is a comment (private)';
2287
-		$this->note_public='This is a comment (public)';
2288
-		$this->fk_projet = 0;
2289
-		// Lines
2290
-		$nbp = 5;
2291
-		$xnbp = 0;
2292
-		while ($xnbp < $nbp)
2293
-		{
2294
-			$line=new ContratLigne($this->db);
2295
-			$line->qty=1;
2296
-			$line->subprice=100;
2297
-			$line->price=100;
2298
-			$line->tva_tx=19.6;
2299
-			$line->remise_percent=10;
2300
-			$line->total_ht=90;
2301
-			$line->total_ttc=107.64;	// 90 * 1.196
2302
-			$line->total_tva=17.64;
2303
-			$line->date_start = dol_now() - 500000;
2304
-			$line->date_start_real = dol_now() - 200000;
2305
-			$line->date_end = dol_now() + 500000;
2306
-			$line->date_end_real = dol_now() - 100000;
2307
-			if ($num_prods > 0)
2308
-            {
2309
-				$prodid = mt_rand(1, $num_prods);
2310
-				$line->fk_product=$prodids[$prodid];
2311
-            }
2312
-			$this->lines[$xnbp]=$line;
2313
-			$xnbp++;
2314
-		}
2315
-	}
2316
-
2317
-	/**
2318
-	 * 	Create an array of order lines
2319
-	 *
2320
-	 * 	@return int		>0 if OK, <0 if KO
2321
-	 */
2322
-	function getLinesArray()
2323
-	{
2324
-		return $this->fetch_lines();
2325
-	}
2326
-
2327
-
2328
-	/**
2329
-	 *  Create a document onto disk according to template module.
2330
-	 *
2331
-	 * 	@param	    string		$modele			Force model to use ('' to not force)
2332
-	 * 	@param		Translate	$outputlangs	Object langs to use for output
2333
-	 *  @param      int			$hidedetails    Hide details of lines
2334
-	 *  @param      int			$hidedesc       Hide description
2335
-	 *  @param      int			$hideref        Hide ref
2336
-         *  @param   null|array  $moreparams     Array to provide more information
2337
-	 * 	@return     int         				0 if KO, 1 if OK
2338
-	 */
2339
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
2340
-	{
2341
-		global $conf,$langs;
2342
-
2343
-		$langs->load("contracts");
2344
-
2345
-		if (! dol_strlen($modele)) {
2346
-
2347
-			$modele = 'strato';
2348
-
2349
-			if ($this->modelpdf) {
2350
-				$modele = $this->modelpdf;
2351
-			} elseif (! empty($conf->global->CONTRACT_ADDON_PDF)) {
2352
-				$modele = $conf->global->CONTRACT_ADDON_PDF;
2353
-			}
2354
-		}
2355
-
2356
-		$modelpath = "core/modules/contract/doc/";
2357
-
2358
-		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2359
-	}
2360
-
2361
-	/**
2362
-	 * Function used to replace a thirdparty id with another one.
2363
-	 *
2364
-	 * @param DoliDB $db Database handler
2365
-	 * @param int $origin_id Old thirdparty id
2366
-	 * @param int $dest_id New thirdparty id
2367
-	 * @return bool
2368
-	 */
2369
-	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
2370
-	{
2371
-		$tables = array(
2372
-			'contrat'
2373
-		);
2374
-
2375
-		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2376
-	}
2377
-
2378
-	/**
2379
-	 * Load an object from its id and create a new one in database
2380
-	 *
2381
-	 * @param int $socid Id of thirdparty
2382
-	 * @param int $notrigger	1=Does not execute triggers, 0= execute triggers
2383
-	 * @return int New id of clone
2384
-	 */
2378
+    /**
2379
+     * Load an object from its id and create a new one in database
2380
+     *
2381
+     * @param int $socid Id of thirdparty
2382
+     * @param int $notrigger	1=Does not execute triggers, 0= execute triggers
2383
+     * @return int New id of clone
2384
+     */
2385 2385
     function createFromClone($socid = 0, $notrigger=0)
2386 2386
     {
2387
-		global $db, $user, $langs, $conf, $hookmanager, $extrafields;
2387
+        global $db, $user, $langs, $conf, $hookmanager, $extrafields;
2388 2388
 
2389
-		dol_include_once('/projet/class/project.class.php');
2389
+        dol_include_once('/projet/class/project.class.php');
2390 2390
 
2391
-		$this->context['createfromclone'] = 'createfromclone';
2391
+        $this->context['createfromclone'] = 'createfromclone';
2392 2392
 
2393
-		$error = 0;
2393
+        $error = 0;
2394 2394
 
2395
-		$this->fetch($this->id);
2395
+        $this->fetch($this->id);
2396 2396
 
2397
-		// Load dest object
2398
-		$clonedObj = clone $this;
2397
+        // Load dest object
2398
+        $clonedObj = clone $this;
2399 2399
         $clonedObj->socid = $socid;
2400 2400
 
2401
-		$this->db->begin();
2402
-
2403
-		$objsoc = new Societe($this->db);
2404
-
2405
-		$objsoc->fetch($clonedObj->socid);
2406
-
2407
-		// Clean data
2408
-		$clonedObj->statut = 0;
2409
-		// Clean extrafields
2410
-		if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0)
2411
-		{
2412
-			$extrafields->fetch_name_optionals_label($this->element);
2413
-			foreach($clonedObj->array_options as $key => $option)
2414
-			{
2415
-				$shortkey = preg_replace('/options_/', '', $key);
2416
-				//var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2417
-				if (! empty($extrafields->attributes[$this->element]['unique'][$shortkey]))
2418
-				{
2419
-					//var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2420
-					unset($clonedObj->array_options[$key]);
2421
-				}
2422
-			}
2423
-		}
2424
-
2425
-		if (empty($conf->global->CONTRACT_ADDON) || ! is_readable(DOL_DOCUMENT_ROOT . "/core/modules/contract/" . $conf->global->CONTRACT_ADDON . ".php")) {
2426
-			$this->error = 'ErrorSetupNotComplete';
2427
-			dol_syslog($this->error);
2428
-			return - 1;
2429
-		}
2430
-
2431
-		// Set ref
2432
-		require_once DOL_DOCUMENT_ROOT . "/core/modules/contract/" . $conf->global->CONTRACT_ADDON . '.php';
2433
-		$obj = $conf->global->CONTRACT_ADDON;
2434
-		$modContract = new $obj();
2435
-		$clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2436
-
2437
-		// get extrafields so they will be clone
2438
-		foreach ($this->lines as $line) {
2439
-			$line->fetch_optionals($line->id);
2440
-		}
2441
-
2442
-		// Create clone
2443
-		$result = $clonedObj->create($user);
2444
-		if ($result < 0) {
2445
-			$error ++;
2446
-			$this->error = $clonedObj->error;
2447
-			$this->errors[] = $clonedObj->error;
2448
-		} else {
2401
+        $this->db->begin();
2402
+
2403
+        $objsoc = new Societe($this->db);
2404
+
2405
+        $objsoc->fetch($clonedObj->socid);
2406
+
2407
+        // Clean data
2408
+        $clonedObj->statut = 0;
2409
+        // Clean extrafields
2410
+        if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0)
2411
+        {
2412
+            $extrafields->fetch_name_optionals_label($this->element);
2413
+            foreach($clonedObj->array_options as $key => $option)
2414
+            {
2415
+                $shortkey = preg_replace('/options_/', '', $key);
2416
+                //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2417
+                if (! empty($extrafields->attributes[$this->element]['unique'][$shortkey]))
2418
+                {
2419
+                    //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2420
+                    unset($clonedObj->array_options[$key]);
2421
+                }
2422
+            }
2423
+        }
2424
+
2425
+        if (empty($conf->global->CONTRACT_ADDON) || ! is_readable(DOL_DOCUMENT_ROOT . "/core/modules/contract/" . $conf->global->CONTRACT_ADDON . ".php")) {
2426
+            $this->error = 'ErrorSetupNotComplete';
2427
+            dol_syslog($this->error);
2428
+            return - 1;
2429
+        }
2430
+
2431
+        // Set ref
2432
+        require_once DOL_DOCUMENT_ROOT . "/core/modules/contract/" . $conf->global->CONTRACT_ADDON . '.php';
2433
+        $obj = $conf->global->CONTRACT_ADDON;
2434
+        $modContract = new $obj();
2435
+        $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
2436
+
2437
+        // get extrafields so they will be clone
2438
+        foreach ($this->lines as $line) {
2439
+            $line->fetch_optionals($line->id);
2440
+        }
2441
+
2442
+        // Create clone
2443
+        $result = $clonedObj->create($user);
2444
+        if ($result < 0) {
2445
+            $error ++;
2446
+            $this->error = $clonedObj->error;
2447
+            $this->errors[] = $clonedObj->error;
2448
+        } else {
2449 2449
             // copy external contacts if same company
2450 2450
             if ($this->socid == $clonedObj->socid) {
2451 2451
                 if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
@@ -2454,42 +2454,42 @@  discard block
 block discarded – undo
2454 2454
             }
2455 2455
         }
2456 2456
 
2457
-		if (! $error) {
2458
-			foreach ( $this->lines as $line ) {
2459
-				$result = $clonedObj->addline($line->desc, $line->subprice, $line->qty, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->fk_product, $line->remise_percent, $line->date_ouverture, $line->date_cloture, 'HT', 0, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit);
2460
-				if ($result < 0) {
2461
-					$error ++;
2462
-					$this->error = $clonedObj->error;
2463
-					$this->errors[] = $clonedObj->error;
2464
-				}
2465
-			}
2466
-		}
2467
-
2468
-		if (! $error) {
2469
-			// Hook of thirdparty module
2470
-			if (is_object($hookmanager)) {
2471
-				$parameters = array (
2472
-						'objFrom' => $this,
2473
-						'clonedObj' => $clonedObj
2474
-				);
2475
-				$action = '';
2476
-				$reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2477
-				if ($reshook < 0)
2478
-					$error ++;
2479
-			}
2480
-		}
2481
-
2482
-		unset($this->context['createfromclone']);
2483
-
2484
-		// End
2485
-		if (! $error) {
2486
-			$this->db->commit();
2487
-			return $clonedObj->id;
2488
-		} else {
2489
-			$this->db->rollback();
2490
-			return - 1;
2491
-		}
2492
-	}
2457
+        if (! $error) {
2458
+            foreach ( $this->lines as $line ) {
2459
+                $result = $clonedObj->addline($line->desc, $line->subprice, $line->qty, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->fk_product, $line->remise_percent, $line->date_ouverture, $line->date_cloture, 'HT', 0, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit);
2460
+                if ($result < 0) {
2461
+                    $error ++;
2462
+                    $this->error = $clonedObj->error;
2463
+                    $this->errors[] = $clonedObj->error;
2464
+                }
2465
+            }
2466
+        }
2467
+
2468
+        if (! $error) {
2469
+            // Hook of thirdparty module
2470
+            if (is_object($hookmanager)) {
2471
+                $parameters = array (
2472
+                        'objFrom' => $this,
2473
+                        'clonedObj' => $clonedObj
2474
+                );
2475
+                $action = '';
2476
+                $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2477
+                if ($reshook < 0)
2478
+                    $error ++;
2479
+            }
2480
+        }
2481
+
2482
+        unset($this->context['createfromclone']);
2483
+
2484
+        // End
2485
+        if (! $error) {
2486
+            $this->db->commit();
2487
+            return $clonedObj->id;
2488
+        } else {
2489
+            $this->db->rollback();
2490
+            return - 1;
2491
+        }
2492
+    }
2493 2493
 }
2494 2494
 
2495 2495
 
@@ -2499,808 +2499,808 @@  discard block
 block discarded – undo
2499 2499
 class ContratLigne extends CommonObjectLine
2500 2500
 {
2501 2501
     /**
2502
-	 * @var string ID to identify managed object
2503
-	 */
2504
-	public $element='contratdet';
2502
+     * @var string ID to identify managed object
2503
+     */
2504
+    public $element='contratdet';
2505 2505
 
2506 2506
     /**
2507
-	 * @var string Name of table without prefix where object is stored
2508
-	 */
2509
-	public $table_element='contratdet';
2507
+     * @var string Name of table without prefix where object is stored
2508
+     */
2509
+    public $table_element='contratdet';
2510 2510
 
2511
-	/**
2512
-	 * @var int ID
2513
-	 */
2514
-	public $id;
2511
+    /**
2512
+     * @var int ID
2513
+     */
2514
+    public $id;
2515 2515
 
2516
-	/**
2517
-	 * @var string Ref
2518
-	 */
2519
-	public $ref;
2516
+    /**
2517
+     * @var string Ref
2518
+     */
2519
+    public $ref;
2520 2520
 
2521
-	public $tms;
2521
+    public $tms;
2522 2522
 
2523
-	/**
2523
+    /**
2524 2524
      * @var int ID
2525 2525
      */
2526
-	public $fk_contrat;
2526
+    public $fk_contrat;
2527 2527
 
2528
-	/**
2528
+    /**
2529 2529
      * @var int ID
2530 2530
      */
2531
-	public $fk_product;
2532
-
2533
-	public $statut;					// 0 inactive, 4 active, 5 closed
2534
-	public $type;						// 0 for product, 1 for service
2535
-
2536
-	/**
2537
-	 * @var string
2538
-	 * @deprecated
2539
-	 */
2540
-	public $label;
2541
-
2542
-	/**
2543
-	 * @var string
2544
-	 * @deprecated
2545
-	 */
2546
-	public $libelle;
2547
-
2548
-	/**
2549
-	 * @var string description
2550
-	 */
2551
-	public $description;
2552
-
2553
-	public $product_ref;
2554
-	public $product_label;
2555
-
2556
-	public $date_commande;
2557
-
2558
-	public $date_start;				// date start planned
2559
-	public $date_start_real;			// date start real
2560
-	public $date_end;					// date end planned
2561
-	public $date_end_real;				// date end real
2562
-	// For backward compatibility
2563
-	public $date_ouverture_prevue;		// date start planned
2564
-	public $date_ouverture;			// date start real
2565
-	public $date_fin_validite;			// date end planned
2566
-	public $date_cloture;				// date end real
2567
-	public $tva_tx;
2568
-	public $localtax1_tx;
2569
-	public $localtax2_tx;
2570
-	public $localtax1_type;	// Local tax 1 type
2571
-	public $localtax2_type;	// Local tax 2 type
2572
-	public $qty;
2573
-	public $remise_percent;
2574
-	public $remise;
2575
-
2576
-	/**
2531
+    public $fk_product;
2532
+
2533
+    public $statut;					// 0 inactive, 4 active, 5 closed
2534
+    public $type;						// 0 for product, 1 for service
2535
+
2536
+    /**
2537
+     * @var string
2538
+     * @deprecated
2539
+     */
2540
+    public $label;
2541
+
2542
+    /**
2543
+     * @var string
2544
+     * @deprecated
2545
+     */
2546
+    public $libelle;
2547
+
2548
+    /**
2549
+     * @var string description
2550
+     */
2551
+    public $description;
2552
+
2553
+    public $product_ref;
2554
+    public $product_label;
2555
+
2556
+    public $date_commande;
2557
+
2558
+    public $date_start;				// date start planned
2559
+    public $date_start_real;			// date start real
2560
+    public $date_end;					// date end planned
2561
+    public $date_end_real;				// date end real
2562
+    // For backward compatibility
2563
+    public $date_ouverture_prevue;		// date start planned
2564
+    public $date_ouverture;			// date start real
2565
+    public $date_fin_validite;			// date end planned
2566
+    public $date_cloture;				// date end real
2567
+    public $tva_tx;
2568
+    public $localtax1_tx;
2569
+    public $localtax2_tx;
2570
+    public $localtax1_type;	// Local tax 1 type
2571
+    public $localtax2_type;	// Local tax 2 type
2572
+    public $qty;
2573
+    public $remise_percent;
2574
+    public $remise;
2575
+
2576
+    /**
2577 2577
      * @var int ID
2578 2578
      */
2579
-	public $fk_remise_except;
2579
+    public $fk_remise_except;
2580 2580
 
2581
-	public $subprice;					// Unit price HT
2581
+    public $subprice;					// Unit price HT
2582 2582
 
2583
-	/**
2584
-	 * @var float
2585
-	 * @deprecated Use $price_ht instead
2586
-	 * @see $price_ht
2587
-	 */
2588
-	public $price;
2583
+    /**
2584
+     * @var float
2585
+     * @deprecated Use $price_ht instead
2586
+     * @see $price_ht
2587
+     */
2588
+    public $price;
2589 2589
 
2590
-	public $price_ht;
2590
+    public $price_ht;
2591 2591
 
2592
-	public $total_ht;
2593
-	public $total_tva;
2594
-	public $total_localtax1;
2595
-	public $total_localtax2;
2596
-	public $total_ttc;
2592
+    public $total_ht;
2593
+    public $total_tva;
2594
+    public $total_localtax1;
2595
+    public $total_localtax2;
2596
+    public $total_ttc;
2597 2597
 
2598
-	/**
2598
+    /**
2599 2599
      * @var int ID
2600 2600
      */
2601
-	public $fk_fournprice;
2601
+    public $fk_fournprice;
2602 2602
 
2603
-	public $pa_ht;
2603
+    public $pa_ht;
2604 2604
 
2605
-	public $info_bits;
2605
+    public $info_bits;
2606 2606
 
2607
-	/**
2607
+    /**
2608 2608
      * @var int ID
2609 2609
      */
2610
-	public $fk_user_author;
2610
+    public $fk_user_author;
2611 2611
 
2612
-	/**
2612
+    /**
2613 2613
      * @var int ID
2614 2614
      */
2615
-	public $fk_user_ouverture;
2615
+    public $fk_user_ouverture;
2616 2616
 
2617
-	/**
2617
+    /**
2618 2618
      * @var int ID
2619 2619
      */
2620
-	public $fk_user_cloture;
2620
+    public $fk_user_cloture;
2621 2621
 
2622
-	public $commentaire;
2622
+    public $commentaire;
2623 2623
 
2624
-	const STATUS_INITIAL = 0;
2625
-	const STATUS_OPEN = 4;
2626
-	const STATUS_CLOSED = 5;
2624
+    const STATUS_INITIAL = 0;
2625
+    const STATUS_OPEN = 4;
2626
+    const STATUS_CLOSED = 5;
2627 2627
 
2628 2628
 
2629 2629
 
2630
-	/**
2630
+    /**
2631 2631
      *  Constructor
2632 2632
      *
2633 2633
      *  @param      DoliDb		$db      Database handler
2634
-	 */
2635
-	function __construct($db)
2636
-	{
2637
-		$this->db = $db;
2638
-	}
2639
-
2640
-
2641
-	/**
2642
-	 *  Return label of this contract line status
2643
-	 *
2644
-	 *	@param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2645
-	 *  @return string      		Libelle
2646
-	 */
2647
-	function getLibStatut($mode)
2648
-	{
2649
-		return $this->LibStatut($this->statut,$mode,((! empty($this->date_fin_validite))?($this->date_fin_validite < dol_now()?1:0):-1));
2650
-	}
2634
+     */
2635
+    function __construct($db)
2636
+    {
2637
+        $this->db = $db;
2638
+    }
2639
+
2640
+
2641
+    /**
2642
+     *  Return label of this contract line status
2643
+     *
2644
+     *	@param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2645
+     *  @return string      		Libelle
2646
+     */
2647
+    function getLibStatut($mode)
2648
+    {
2649
+        return $this->LibStatut($this->statut,$mode,((! empty($this->date_fin_validite))?($this->date_fin_validite < dol_now()?1:0):-1));
2650
+    }
2651 2651
 
2652 2652
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2653
-	/**
2654
-	 *  Return label of a contract line status
2655
-	 *
2656
-	 *  @param	int		$statut     Id statut
2657
-	 *	@param  int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2658
-	 *	@param	int		$expired	0=Not expired, 1=Expired, -1=Both or unknown
2659
-	 *  @param	string	$moreatt	More attribute
2660
-	 *  @return string      		Libelle
2661
-	 */
2662
-	static function LibStatut($statut,$mode,$expired=-1,$moreatt='')
2663
-	{
2653
+    /**
2654
+     *  Return label of a contract line status
2655
+     *
2656
+     *  @param	int		$statut     Id statut
2657
+     *	@param  int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2658
+     *	@param	int		$expired	0=Not expired, 1=Expired, -1=Both or unknown
2659
+     *  @param	string	$moreatt	More attribute
2660
+     *  @return string      		Libelle
2661
+     */
2662
+    static function LibStatut($statut,$mode,$expired=-1,$moreatt='')
2663
+    {
2664 2664
         // phpcs:enable
2665
-		global $langs;
2666
-		$langs->load("contracts");
2667
-		if ($mode == 0)
2668
-		{
2669
-			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); }
2670
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); }
2671
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLate"); }
2672
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLate"); }
2673
-			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2674
-		}
2675
-		elseif ($mode == 1)
2676
-		{
2677
-			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); }
2678
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); }
2679
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort"); }
2680
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort"); }
2681
-			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2682
-		}
2683
-		elseif ($mode == 2)
2684
-		{
2685
-			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2686
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2687
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLateShort"); }
2688
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLateShort"); }
2689
-			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2690
-		}
2691
-		elseif ($mode == 3)
2692
-		{
2693
-			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0',$moreatt); }
2694
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4',$moreatt); }
2695
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4',$moreatt); }
2696
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3',$moreatt); }
2697
-			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6',$moreatt); }
2698
-		}
2699
-		elseif ($mode == 4)
2700
-		{
2701
-			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2702
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2703
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLate"); }
2704
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLate"); }
2705
-			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2706
-		}
2707
-		elseif ($mode == 5)
2708
-		{
2709
-			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial").' '.img_picto($langs->trans('ServiceStatusInitial'),'statut0'); }
2710
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning").' '.img_picto($langs->trans('ServiceStatusRunning'),'statut4'); }
2711
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort").' '.img_picto($langs->trans('ServiceStatusNotLateShort'),'statut4'); }
2712
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort").' '.img_picto($langs->trans('ServiceStatusLate'),'statut3'); }
2713
-			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed").' '.img_picto($langs->trans('ServiceStatusClosed'),'statut6'); }
2714
-		}
2715
-	}
2716
-
2717
-	/**
2718
-	 *	Return clicable name (with picto eventually)
2719
-	 *
2720
-	 *  @param	int		$withpicto		0=No picto, 1=Include picto into link, 2=Only picto
2721
-	 *  @param	int		$maxlength		Max length
2722
-	 *  @return	string					Chaine avec URL
2723
- 	 */
2724
-	function getNomUrl($withpicto=0,$maxlength=0)
2725
-	{
2726
-		global $langs;
2727
-
2728
-		$result='';
2665
+        global $langs;
2666
+        $langs->load("contracts");
2667
+        if ($mode == 0)
2668
+        {
2669
+            if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); }
2670
+            elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); }
2671
+            elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLate"); }
2672
+            elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLate"); }
2673
+            elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2674
+        }
2675
+        elseif ($mode == 1)
2676
+        {
2677
+            if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); }
2678
+            elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); }
2679
+            elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort"); }
2680
+            elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort"); }
2681
+            elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2682
+        }
2683
+        elseif ($mode == 2)
2684
+        {
2685
+            if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2686
+            elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2687
+            elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLateShort"); }
2688
+            elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLateShort"); }
2689
+            elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2690
+        }
2691
+        elseif ($mode == 3)
2692
+        {
2693
+            if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0',$moreatt); }
2694
+            elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4',$moreatt); }
2695
+            elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4',$moreatt); }
2696
+            elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3',$moreatt); }
2697
+            elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6',$moreatt); }
2698
+        }
2699
+        elseif ($mode == 4)
2700
+        {
2701
+            if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2702
+            elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2703
+            elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLate"); }
2704
+            elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLate"); }
2705
+            elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2706
+        }
2707
+        elseif ($mode == 5)
2708
+        {
2709
+            if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial").' '.img_picto($langs->trans('ServiceStatusInitial'),'statut0'); }
2710
+            elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning").' '.img_picto($langs->trans('ServiceStatusRunning'),'statut4'); }
2711
+            elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort").' '.img_picto($langs->trans('ServiceStatusNotLateShort'),'statut4'); }
2712
+            elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort").' '.img_picto($langs->trans('ServiceStatusLate'),'statut3'); }
2713
+            elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed").' '.img_picto($langs->trans('ServiceStatusClosed'),'statut6'); }
2714
+        }
2715
+    }
2716
+
2717
+    /**
2718
+     *	Return clicable name (with picto eventually)
2719
+     *
2720
+     *  @param	int		$withpicto		0=No picto, 1=Include picto into link, 2=Only picto
2721
+     *  @param	int		$maxlength		Max length
2722
+     *  @return	string					Chaine avec URL
2723
+     */
2724
+    function getNomUrl($withpicto=0,$maxlength=0)
2725
+    {
2726
+        global $langs;
2727
+
2728
+        $result='';
2729 2729
         $label=$langs->trans("ShowContractOfService").': '.$this->label;
2730 2730
         if (empty($label)) $label=$this->description;
2731 2731
 
2732 2732
         $link = '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$this->fk_contrat.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
2733
-		$linkend='</a>';
2733
+        $linkend='</a>';
2734 2734
 
2735
-		$picto='service';
2736
-		if ($this->type == 0) $picto='product';
2735
+        $picto='service';
2736
+        if ($this->type == 0) $picto='product';
2737 2737
 
2738 2738
         if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
2739
-		if ($withpicto && $withpicto != 2) $result.=' ';
2740
-		if ($withpicto != 2) $result.=$link.($this->product_ref?$this->product_ref.' ':'').($this->label?$this->label:$this->description).$linkend;
2741
-		return $result;
2742
-	}
2743
-
2744
-	/**
2745
-	 *    	Load object in memory from database
2746
-	 *
2747
-	 *    	@param	int		$id         Id object
2748
-	 * 		@param	string	$ref		Ref of contract
2749
-	 *    	@return int         		<0 if KO, >0 if OK
2750
-	 */
2751
-	function fetch($id, $ref='')
2752
-	{
2753
-
2754
-		// Check parameters
2755
-		if (empty($id) && empty($ref)) return -1;
2756
-
2757
-		$sql = "SELECT";
2758
-		$sql.= " t.rowid,";
2759
-
2760
-		$sql.= " t.tms,";
2761
-		$sql.= " t.fk_contrat,";
2762
-		$sql.= " t.fk_product,";
2763
-		$sql.= " t.statut,";
2764
-		$sql.= " t.label,";			// This field is not used. Only label of product
2765
-		$sql.= " p.ref as product_ref,";
2766
-		$sql.= " p.label as product_label,";
2767
-		$sql.= " p.description as product_desc,";
2768
-		$sql.= " p.fk_product_type as product_type,";
2769
-		$sql.= " t.description,";
2770
-		$sql.= " t.date_commande,";
2771
-		$sql.= " t.date_ouverture_prevue as date_ouverture_prevue,";
2772
-		$sql.= " t.date_ouverture as date_ouverture,";
2773
-		$sql.= " t.date_fin_validite as date_fin_validite,";
2774
-		$sql.= " t.date_cloture as date_cloture,";
2775
-		$sql.= " t.tva_tx,";
2776
-		$sql.= " t.vat_src_code,";
2777
-		$sql.= " t.localtax1_tx,";
2778
-		$sql.= " t.localtax2_tx,";
2779
-		$sql.= " t.localtax1_type,";
2780
-		$sql.= " t.localtax2_type,";
2781
-		$sql.= " t.qty,";
2782
-		$sql.= " t.remise_percent,";
2783
-		$sql.= " t.remise,";
2784
-		$sql.= " t.fk_remise_except,";
2785
-		$sql.= " t.subprice,";
2786
-		$sql.= " t.price_ht,";
2787
-		$sql.= " t.total_ht,";
2788
-		$sql.= " t.total_tva,";
2789
-		$sql.= " t.total_localtax1,";
2790
-		$sql.= " t.total_localtax2,";
2791
-		$sql.= " t.total_ttc,";
2792
-		$sql.= " t.fk_product_fournisseur_price as fk_fournprice,";
2793
-		$sql.= " t.buy_price_ht as pa_ht,";
2794
-		$sql.= " t.info_bits,";
2795
-		$sql.= " t.fk_user_author,";
2796
-		$sql.= " t.fk_user_ouverture,";
2797
-		$sql.= " t.fk_user_cloture,";
2798
-		$sql.= " t.commentaire,";
2799
-		$sql.= " t.fk_unit";
2800
-		$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
2801
-		if ($id)  $sql.= " WHERE t.rowid = ".$id;
2802
-		if ($ref) $sql.= " WHERE t.rowid = '".$this->db->escape($ref)."'";
2803
-
2804
-		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2805
-		$resql=$this->db->query($sql);
2806
-		if ($resql)
2807
-		{
2808
-			if ($this->db->num_rows($resql))
2809
-			{
2810
-				$obj = $this->db->fetch_object($resql);
2811
-
2812
-				$this->id    = $obj->rowid;
2813
-				$this->ref   = $obj->rowid;
2814
-
2815
-				$this->tms = $this->db->jdate($obj->tms);
2816
-				$this->fk_contrat = $obj->fk_contrat;
2817
-				$this->fk_product = $obj->fk_product;
2818
-				$this->statut = $obj->statut;
2819
-				$this->product_ref = $obj->product_ref;
2820
-				$this->product_label = $obj->product_label;
2821
-				$this->product_description = $obj->product_description;
2822
-				$this->product_type = $obj->product_type;
2823
-				$this->label = $obj->label;					// deprecated. We do not use this field. Only ref and label of product, and description of contract line
2824
-				$this->description = $obj->description;
2825
-				$this->date_commande = $this->db->jdate($obj->date_commande);
2826
-
2827
-				$this->date_start = $this->db->jdate($obj->date_ouverture_prevue);
2828
-				$this->date_start_real = $this->db->jdate($obj->date_ouverture);
2829
-				$this->date_end = $this->db->jdate($obj->date_fin_validite);
2830
-				$this->date_end_real = $this->db->jdate($obj->date_cloture);
2831
-				// For backward compatibility
2832
-				$this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue);
2833
-				$this->date_ouverture = $this->db->jdate($obj->date_ouverture);
2834
-				$this->date_fin_validite = $this->db->jdate($obj->date_fin_validite);
2835
-				$this->date_cloture = $this->db->jdate($obj->date_cloture);
2836
-
2837
-				$this->tva_tx = $obj->tva_tx;
2838
-				$this->vat_src_code = $obj->vat_src_code;
2839
-				$this->localtax1_tx = $obj->localtax1_tx;
2840
-				$this->localtax2_tx = $obj->localtax2_tx;
2841
-				$this->localtax1_type = $obj->localtax1_type;
2842
-				$this->localtax2_type = $obj->localtax2_type;
2843
-				$this->qty = $obj->qty;
2844
-				$this->remise_percent = $obj->remise_percent;
2845
-				$this->remise = $obj->remise;
2846
-				$this->fk_remise_except = $obj->fk_remise_except;
2847
-				$this->subprice = $obj->subprice;
2848
-				$this->price_ht = $obj->price_ht;
2849
-				$this->total_ht = $obj->total_ht;
2850
-				$this->total_tva = $obj->total_tva;
2851
-				$this->total_localtax1 = $obj->total_localtax1;
2852
-				$this->total_localtax2 = $obj->total_localtax2;
2853
-				$this->total_ttc = $obj->total_ttc;
2854
-				$this->info_bits = $obj->info_bits;
2855
-				$this->fk_user_author = $obj->fk_user_author;
2856
-				$this->fk_user_ouverture = $obj->fk_user_ouverture;
2857
-				$this->fk_user_cloture = $obj->fk_user_cloture;
2858
-				$this->commentaire = $obj->commentaire;
2859
-				$this->fk_fournprice = $obj->fk_fournprice;
2860
-				$marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->fk_fournprice, $obj->pa_ht);
2861
-				$this->pa_ht = $marginInfos[0];
2862
-				$this->fk_unit     = $obj->fk_unit;
2863
-			}
2864
-			$this->db->free($resql);
2865
-
2866
-			return 1;
2867
-		}
2868
-		else
2869
-		{
2870
-			$this->error="Error ".$this->db->lasterror();
2871
-			return -1;
2872
-		}
2873
-	}
2874
-
2875
-
2876
-	/**
2877
-	 *      Update database for contract line
2878
-	 *
2879
-	 *      @param	User	$user        	User that modify
2880
-	 *      @param  int		$notrigger	    0=no, 1=yes (no update trigger)
2881
-	 *      @return int         			<0 if KO, >0 if OK
2882
-	 */
2883
-	function update($user, $notrigger=0)
2884
-	{
2885
-		global $conf, $langs, $mysoc;
2886
-
2887
-		$error=0;
2888
-
2889
-		// Clean parameters
2890
-		$this->fk_contrat = (int) $this->fk_contrat;
2891
-		$this->fk_product = (int) $this->fk_product;
2892
-		$this->statut = (int) $this->statut;
2893
-		$this->label=trim($this->label);
2894
-		$this->description=trim($this->description);
2895
-		$this->vat_src_code=trim($this->vat_src_code);
2896
-		$this->tva_tx=trim($this->tva_tx);
2897
-		$this->localtax1_tx=trim($this->localtax1_tx);
2898
-		$this->localtax2_tx=trim($this->localtax2_tx);
2899
-		$this->qty=trim($this->qty);
2900
-		$this->remise_percent=trim($this->remise_percent);
2901
-		$this->remise=trim($this->remise);
2902
-		$this->fk_remise_except = (int) $this->fk_remise_except;
2903
-		$this->subprice=price2num($this->subprice);
2904
-		$this->price_ht=price2num($this->price_ht);
2905
-		$this->total_ht=trim($this->total_ht);
2906
-		$this->total_tva=trim($this->total_tva);
2907
-		$this->total_localtax1=trim($this->total_localtax1);
2908
-		$this->total_localtax2=trim($this->total_localtax2);
2909
-		$this->total_ttc=trim($this->total_ttc);
2910
-		$this->info_bits=trim($this->info_bits);
2911
-		$this->fk_user_author = (int) $this->fk_user_author;
2912
-		$this->fk_user_ouverture = (int) $this->fk_user_ouverture;
2913
-		$this->fk_user_cloture = (int) $this->fk_user_cloture;
2914
-		$this->commentaire=trim($this->commentaire);
2915
-		//if (empty($this->subprice)) $this->subprice = 0;
2916
-		if (empty($this->price_ht)) $this->price_ht = 0;
2917
-		if (empty($this->total_ht)) $this->total_ht = 0;
2918
-		if (empty($this->total_tva)) $this->total_tva = 0;
2919
-		if (empty($this->total_ttc)) $this->total_ttc = 0;
2920
-		if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
2921
-		if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
2922
-		if (empty($this->remise_percent)) $this->remise_percent = 0;
2923
-		// For backward compatibility
2924
-		if (empty($this->date_start))      $this->date_start=$this->date_ouverture_prevue;
2925
-		if (empty($this->date_start_real)) $this->date_start=$this->date_ouverture;
2926
-		if (empty($this->date_end))        $this->date_start=$this->date_fin_validite;
2927
-		if (empty($this->date_end_real))   $this->date_start=$this->date_cloture;
2928
-
2929
-
2930
-		// Check parameters
2931
-		// Put here code to add control on parameters values
2932
-
2933
-		// Calcul du total TTC et de la TVA pour la ligne a partir de
2934
-		// qty, pu, remise_percent et txtva
2935
-		// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2936
-		// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2937
-		$localtaxes_type = getLocalTaxesFromRate($this->txtva, 0, $this->societe, $mysoc);
2938
-
2939
-		$tabprice=calcul_price_total($this->qty, $this->price_ht, $this->remise_percent, $this->tva_tx, $this->localtax1_tx, $this->localtax2_tx, 0, 'HT', 0, 1, $mysoc, $localtaxes_type);
2940
-		$this->total_ht  = $tabprice[0];
2941
-		$this->total_tva = $tabprice[1];
2942
-		$this->total_ttc = $tabprice[2];
2943
-		$this->total_localtax1= $tabprice[9];
2944
-		$this->total_localtax2= $tabprice[10];
2945
-
2946
-	    if (empty($this->pa_ht)) $this->pa_ht=0;
2947
-
2948
-		// if buy price not defined, define buyprice as configured in margin admin
2949
-		if ($this->pa_ht == 0)
2950
-		{
2951
-			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
2952
-			{
2953
-				return $result;
2954
-			}
2955
-			else
2956
-			{
2957
-				$this->pa_ht = $result;
2958
-			}
2959
-		}
2960
-
2961
-
2962
-		$this->db->begin();
2963
-
2964
-		$this->oldcopy = new ContratLigne($this->db);
2965
-		$this->oldcopy->fetch($this->id);
2966
-
2967
-		// Update request
2968
-		$sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
2969
-		$sql.= " fk_contrat=".$this->fk_contrat.",";
2970
-		$sql.= " fk_product=".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":'null').",";
2971
-		$sql.= " statut=".$this->statut.",";
2972
-		$sql.= " label='".$this->db->escape($this->label)."',";
2973
-		$sql.= " description='".$this->db->escape($this->description)."',";
2974
-		$sql.= " date_commande=".($this->date_commande!=''?"'".$this->db->idate($this->date_commande)."'":"null").",";
2975
-		$sql.= " date_ouverture_prevue=".($this->date_ouverture_prevue!=''?"'".$this->db->idate($this->date_ouverture_prevue)."'":"null").",";
2976
-		$sql.= " date_ouverture=".($this->date_ouverture!=''?"'".$this->db->idate($this->date_ouverture)."'":"null").",";
2977
-		$sql.= " date_fin_validite=".($this->date_fin_validite!=''?"'".$this->db->idate($this->date_fin_validite)."'":"null").",";
2978
-		$sql.= " date_cloture=".($this->date_cloture!=''?"'".$this->db->idate($this->date_cloture)."'":"null").",";
2979
-		$sql.= " vat_src_code='".$this->db->escape($this->vat_src_code)."',";
2980
-		$sql.= " tva_tx=".price2num($this->tva_tx).",";
2981
-		$sql.= " localtax1_tx=".price2num($this->localtax1_tx).",";
2982
-		$sql.= " localtax2_tx=".price2num($this->localtax2_tx).",";
2983
-		$sql.= " qty=".price2num($this->qty).",";
2984
-		$sql.= " remise_percent=".price2num($this->remise_percent).",";
2985
-		$sql.= " remise=".($this->remise?price2num($this->remise):"null").",";
2986
-		$sql.= " fk_remise_except=".($this->fk_remise_except > 0?$this->fk_remise_except:"null").",";
2987
-		$sql.= " subprice=".($this->subprice != '' ? $this->subprice : "null").",";
2988
-		$sql.= " price_ht=".($this->price_ht != '' ? $this->price_ht : "null").",";
2989
-		$sql.= " total_ht=".$this->total_ht.",";
2990
-		$sql.= " total_tva=".$this->total_tva.",";
2991
-		$sql.= " total_localtax1=".$this->total_localtax1.",";
2992
-		$sql.= " total_localtax2=".$this->total_localtax2.",";
2993
-		$sql.= " total_ttc=".$this->total_ttc.",";
2994
-		$sql.= " fk_product_fournisseur_price=".(!empty($this->fk_fournprice)?$this->fk_fournprice:"NULL").",";
2995
-		$sql.= " buy_price_ht='".price2num($this->pa_ht)."',";
2996
-		$sql.= " info_bits='".$this->db->escape($this->info_bits)."',";
2997
-		$sql.= " fk_user_author=".($this->fk_user_author >= 0?$this->fk_user_author:"NULL").",";
2998
-		$sql.= " fk_user_ouverture=".($this->fk_user_ouverture > 0?$this->fk_user_ouverture:"NULL").",";
2999
-		$sql.= " fk_user_cloture=".($this->fk_user_cloture > 0?$this->fk_user_cloture:"NULL").",";
3000
-		$sql.= " commentaire='".$this->db->escape($this->commentaire)."',";
3001
-		$sql.= " fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
3002
-		$sql.= " WHERE rowid=".$this->id;
3003
-
3004
-		dol_syslog(get_class($this)."::update", LOG_DEBUG);
3005
-		$resql = $this->db->query($sql);
3006
-		if (! $resql)
3007
-		{
3008
-			$this->error="Error ".$this->db->lasterror();
3009
-			$error++;
3010
-		}
3011
-
3012
-		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used
3013
-		{
3014
-			$result=$this->insertExtraFields();
3015
-			if ($result < 0)
3016
-			{
3017
-				$error++;
3018
-			}
3019
-		}
3020
-
3021
-		// If we change a planned date (start or end), sync dates for all services
3022
-		if (! $error && ! empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES))
3023
-		{
3024
-			if ($this->date_ouverture_prevue != $this->oldcopy->date_ouverture_prevue)
3025
-			{
3026
-				$sql ='UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3027
-				$sql.= " date_ouverture_prevue = ".($this->date_ouverture_prevue!=''?"'".$this->db->idate($this->date_ouverture_prevue)."'":"null");
3028
-				$sql.= " WHERE fk_contrat = ".$this->fk_contrat;
3029
-
3030
-				$resql = $this->db->query($sql);
3031
-				if (! $resql)
3032
-				{
3033
-					$error++;
3034
-					$this->error="Error ".$this->db->lasterror();
3035
-				}
3036
-			}
3037
-			if ($this->date_fin_validite != $this->oldcopy->date_fin_validite)
3038
-			{
3039
-				$sql ='UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3040
-				$sql.= " date_fin_validite = ".($this->date_fin_validite!=''?"'".$this->db->idate($this->date_fin_validite)."'":"null");
3041
-				$sql.= " WHERE fk_contrat = ".$this->fk_contrat;
3042
-
3043
-				$resql = $this->db->query($sql);
3044
-				if (! $resql)
3045
-				{
3046
-					$error++;
3047
-					$this->error="Error ".$this->db->lasterror();
3048
-				}
3049
-			}
3050
-		}
3051
-
3052
-		if (! $error && ! $notrigger) {
3053
-	        // Call trigger
3054
-	        $result=$this->call_trigger('LINECONTRACT_UPDATE', $user);
3055
-	        if ($result < 0) {
2739
+        if ($withpicto && $withpicto != 2) $result.=' ';
2740
+        if ($withpicto != 2) $result.=$link.($this->product_ref?$this->product_ref.' ':'').($this->label?$this->label:$this->description).$linkend;
2741
+        return $result;
2742
+    }
2743
+
2744
+    /**
2745
+     *    	Load object in memory from database
2746
+     *
2747
+     *    	@param	int		$id         Id object
2748
+     * 		@param	string	$ref		Ref of contract
2749
+     *    	@return int         		<0 if KO, >0 if OK
2750
+     */
2751
+    function fetch($id, $ref='')
2752
+    {
2753
+
2754
+        // Check parameters
2755
+        if (empty($id) && empty($ref)) return -1;
2756
+
2757
+        $sql = "SELECT";
2758
+        $sql.= " t.rowid,";
2759
+
2760
+        $sql.= " t.tms,";
2761
+        $sql.= " t.fk_contrat,";
2762
+        $sql.= " t.fk_product,";
2763
+        $sql.= " t.statut,";
2764
+        $sql.= " t.label,";			// This field is not used. Only label of product
2765
+        $sql.= " p.ref as product_ref,";
2766
+        $sql.= " p.label as product_label,";
2767
+        $sql.= " p.description as product_desc,";
2768
+        $sql.= " p.fk_product_type as product_type,";
2769
+        $sql.= " t.description,";
2770
+        $sql.= " t.date_commande,";
2771
+        $sql.= " t.date_ouverture_prevue as date_ouverture_prevue,";
2772
+        $sql.= " t.date_ouverture as date_ouverture,";
2773
+        $sql.= " t.date_fin_validite as date_fin_validite,";
2774
+        $sql.= " t.date_cloture as date_cloture,";
2775
+        $sql.= " t.tva_tx,";
2776
+        $sql.= " t.vat_src_code,";
2777
+        $sql.= " t.localtax1_tx,";
2778
+        $sql.= " t.localtax2_tx,";
2779
+        $sql.= " t.localtax1_type,";
2780
+        $sql.= " t.localtax2_type,";
2781
+        $sql.= " t.qty,";
2782
+        $sql.= " t.remise_percent,";
2783
+        $sql.= " t.remise,";
2784
+        $sql.= " t.fk_remise_except,";
2785
+        $sql.= " t.subprice,";
2786
+        $sql.= " t.price_ht,";
2787
+        $sql.= " t.total_ht,";
2788
+        $sql.= " t.total_tva,";
2789
+        $sql.= " t.total_localtax1,";
2790
+        $sql.= " t.total_localtax2,";
2791
+        $sql.= " t.total_ttc,";
2792
+        $sql.= " t.fk_product_fournisseur_price as fk_fournprice,";
2793
+        $sql.= " t.buy_price_ht as pa_ht,";
2794
+        $sql.= " t.info_bits,";
2795
+        $sql.= " t.fk_user_author,";
2796
+        $sql.= " t.fk_user_ouverture,";
2797
+        $sql.= " t.fk_user_cloture,";
2798
+        $sql.= " t.commentaire,";
2799
+        $sql.= " t.fk_unit";
2800
+        $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
2801
+        if ($id)  $sql.= " WHERE t.rowid = ".$id;
2802
+        if ($ref) $sql.= " WHERE t.rowid = '".$this->db->escape($ref)."'";
2803
+
2804
+        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2805
+        $resql=$this->db->query($sql);
2806
+        if ($resql)
2807
+        {
2808
+            if ($this->db->num_rows($resql))
2809
+            {
2810
+                $obj = $this->db->fetch_object($resql);
2811
+
2812
+                $this->id    = $obj->rowid;
2813
+                $this->ref   = $obj->rowid;
2814
+
2815
+                $this->tms = $this->db->jdate($obj->tms);
2816
+                $this->fk_contrat = $obj->fk_contrat;
2817
+                $this->fk_product = $obj->fk_product;
2818
+                $this->statut = $obj->statut;
2819
+                $this->product_ref = $obj->product_ref;
2820
+                $this->product_label = $obj->product_label;
2821
+                $this->product_description = $obj->product_description;
2822
+                $this->product_type = $obj->product_type;
2823
+                $this->label = $obj->label;					// deprecated. We do not use this field. Only ref and label of product, and description of contract line
2824
+                $this->description = $obj->description;
2825
+                $this->date_commande = $this->db->jdate($obj->date_commande);
2826
+
2827
+                $this->date_start = $this->db->jdate($obj->date_ouverture_prevue);
2828
+                $this->date_start_real = $this->db->jdate($obj->date_ouverture);
2829
+                $this->date_end = $this->db->jdate($obj->date_fin_validite);
2830
+                $this->date_end_real = $this->db->jdate($obj->date_cloture);
2831
+                // For backward compatibility
2832
+                $this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue);
2833
+                $this->date_ouverture = $this->db->jdate($obj->date_ouverture);
2834
+                $this->date_fin_validite = $this->db->jdate($obj->date_fin_validite);
2835
+                $this->date_cloture = $this->db->jdate($obj->date_cloture);
2836
+
2837
+                $this->tva_tx = $obj->tva_tx;
2838
+                $this->vat_src_code = $obj->vat_src_code;
2839
+                $this->localtax1_tx = $obj->localtax1_tx;
2840
+                $this->localtax2_tx = $obj->localtax2_tx;
2841
+                $this->localtax1_type = $obj->localtax1_type;
2842
+                $this->localtax2_type = $obj->localtax2_type;
2843
+                $this->qty = $obj->qty;
2844
+                $this->remise_percent = $obj->remise_percent;
2845
+                $this->remise = $obj->remise;
2846
+                $this->fk_remise_except = $obj->fk_remise_except;
2847
+                $this->subprice = $obj->subprice;
2848
+                $this->price_ht = $obj->price_ht;
2849
+                $this->total_ht = $obj->total_ht;
2850
+                $this->total_tva = $obj->total_tva;
2851
+                $this->total_localtax1 = $obj->total_localtax1;
2852
+                $this->total_localtax2 = $obj->total_localtax2;
2853
+                $this->total_ttc = $obj->total_ttc;
2854
+                $this->info_bits = $obj->info_bits;
2855
+                $this->fk_user_author = $obj->fk_user_author;
2856
+                $this->fk_user_ouverture = $obj->fk_user_ouverture;
2857
+                $this->fk_user_cloture = $obj->fk_user_cloture;
2858
+                $this->commentaire = $obj->commentaire;
2859
+                $this->fk_fournprice = $obj->fk_fournprice;
2860
+                $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->fk_fournprice, $obj->pa_ht);
2861
+                $this->pa_ht = $marginInfos[0];
2862
+                $this->fk_unit     = $obj->fk_unit;
2863
+            }
2864
+            $this->db->free($resql);
2865
+
2866
+            return 1;
2867
+        }
2868
+        else
2869
+        {
2870
+            $this->error="Error ".$this->db->lasterror();
2871
+            return -1;
2872
+        }
2873
+    }
2874
+
2875
+
2876
+    /**
2877
+     *      Update database for contract line
2878
+     *
2879
+     *      @param	User	$user        	User that modify
2880
+     *      @param  int		$notrigger	    0=no, 1=yes (no update trigger)
2881
+     *      @return int         			<0 if KO, >0 if OK
2882
+     */
2883
+    function update($user, $notrigger=0)
2884
+    {
2885
+        global $conf, $langs, $mysoc;
2886
+
2887
+        $error=0;
2888
+
2889
+        // Clean parameters
2890
+        $this->fk_contrat = (int) $this->fk_contrat;
2891
+        $this->fk_product = (int) $this->fk_product;
2892
+        $this->statut = (int) $this->statut;
2893
+        $this->label=trim($this->label);
2894
+        $this->description=trim($this->description);
2895
+        $this->vat_src_code=trim($this->vat_src_code);
2896
+        $this->tva_tx=trim($this->tva_tx);
2897
+        $this->localtax1_tx=trim($this->localtax1_tx);
2898
+        $this->localtax2_tx=trim($this->localtax2_tx);
2899
+        $this->qty=trim($this->qty);
2900
+        $this->remise_percent=trim($this->remise_percent);
2901
+        $this->remise=trim($this->remise);
2902
+        $this->fk_remise_except = (int) $this->fk_remise_except;
2903
+        $this->subprice=price2num($this->subprice);
2904
+        $this->price_ht=price2num($this->price_ht);
2905
+        $this->total_ht=trim($this->total_ht);
2906
+        $this->total_tva=trim($this->total_tva);
2907
+        $this->total_localtax1=trim($this->total_localtax1);
2908
+        $this->total_localtax2=trim($this->total_localtax2);
2909
+        $this->total_ttc=trim($this->total_ttc);
2910
+        $this->info_bits=trim($this->info_bits);
2911
+        $this->fk_user_author = (int) $this->fk_user_author;
2912
+        $this->fk_user_ouverture = (int) $this->fk_user_ouverture;
2913
+        $this->fk_user_cloture = (int) $this->fk_user_cloture;
2914
+        $this->commentaire=trim($this->commentaire);
2915
+        //if (empty($this->subprice)) $this->subprice = 0;
2916
+        if (empty($this->price_ht)) $this->price_ht = 0;
2917
+        if (empty($this->total_ht)) $this->total_ht = 0;
2918
+        if (empty($this->total_tva)) $this->total_tva = 0;
2919
+        if (empty($this->total_ttc)) $this->total_ttc = 0;
2920
+        if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
2921
+        if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
2922
+        if (empty($this->remise_percent)) $this->remise_percent = 0;
2923
+        // For backward compatibility
2924
+        if (empty($this->date_start))      $this->date_start=$this->date_ouverture_prevue;
2925
+        if (empty($this->date_start_real)) $this->date_start=$this->date_ouverture;
2926
+        if (empty($this->date_end))        $this->date_start=$this->date_fin_validite;
2927
+        if (empty($this->date_end_real))   $this->date_start=$this->date_cloture;
2928
+
2929
+
2930
+        // Check parameters
2931
+        // Put here code to add control on parameters values
2932
+
2933
+        // Calcul du total TTC et de la TVA pour la ligne a partir de
2934
+        // qty, pu, remise_percent et txtva
2935
+        // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
2936
+        // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2937
+        $localtaxes_type = getLocalTaxesFromRate($this->txtva, 0, $this->societe, $mysoc);
2938
+
2939
+        $tabprice=calcul_price_total($this->qty, $this->price_ht, $this->remise_percent, $this->tva_tx, $this->localtax1_tx, $this->localtax2_tx, 0, 'HT', 0, 1, $mysoc, $localtaxes_type);
2940
+        $this->total_ht  = $tabprice[0];
2941
+        $this->total_tva = $tabprice[1];
2942
+        $this->total_ttc = $tabprice[2];
2943
+        $this->total_localtax1= $tabprice[9];
2944
+        $this->total_localtax2= $tabprice[10];
2945
+
2946
+        if (empty($this->pa_ht)) $this->pa_ht=0;
2947
+
2948
+        // if buy price not defined, define buyprice as configured in margin admin
2949
+        if ($this->pa_ht == 0)
2950
+        {
2951
+            if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
2952
+            {
2953
+                return $result;
2954
+            }
2955
+            else
2956
+            {
2957
+                $this->pa_ht = $result;
2958
+            }
2959
+        }
2960
+
2961
+
2962
+        $this->db->begin();
2963
+
2964
+        $this->oldcopy = new ContratLigne($this->db);
2965
+        $this->oldcopy->fetch($this->id);
2966
+
2967
+        // Update request
2968
+        $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
2969
+        $sql.= " fk_contrat=".$this->fk_contrat.",";
2970
+        $sql.= " fk_product=".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":'null').",";
2971
+        $sql.= " statut=".$this->statut.",";
2972
+        $sql.= " label='".$this->db->escape($this->label)."',";
2973
+        $sql.= " description='".$this->db->escape($this->description)."',";
2974
+        $sql.= " date_commande=".($this->date_commande!=''?"'".$this->db->idate($this->date_commande)."'":"null").",";
2975
+        $sql.= " date_ouverture_prevue=".($this->date_ouverture_prevue!=''?"'".$this->db->idate($this->date_ouverture_prevue)."'":"null").",";
2976
+        $sql.= " date_ouverture=".($this->date_ouverture!=''?"'".$this->db->idate($this->date_ouverture)."'":"null").",";
2977
+        $sql.= " date_fin_validite=".($this->date_fin_validite!=''?"'".$this->db->idate($this->date_fin_validite)."'":"null").",";
2978
+        $sql.= " date_cloture=".($this->date_cloture!=''?"'".$this->db->idate($this->date_cloture)."'":"null").",";
2979
+        $sql.= " vat_src_code='".$this->db->escape($this->vat_src_code)."',";
2980
+        $sql.= " tva_tx=".price2num($this->tva_tx).",";
2981
+        $sql.= " localtax1_tx=".price2num($this->localtax1_tx).",";
2982
+        $sql.= " localtax2_tx=".price2num($this->localtax2_tx).",";
2983
+        $sql.= " qty=".price2num($this->qty).",";
2984
+        $sql.= " remise_percent=".price2num($this->remise_percent).",";
2985
+        $sql.= " remise=".($this->remise?price2num($this->remise):"null").",";
2986
+        $sql.= " fk_remise_except=".($this->fk_remise_except > 0?$this->fk_remise_except:"null").",";
2987
+        $sql.= " subprice=".($this->subprice != '' ? $this->subprice : "null").",";
2988
+        $sql.= " price_ht=".($this->price_ht != '' ? $this->price_ht : "null").",";
2989
+        $sql.= " total_ht=".$this->total_ht.",";
2990
+        $sql.= " total_tva=".$this->total_tva.",";
2991
+        $sql.= " total_localtax1=".$this->total_localtax1.",";
2992
+        $sql.= " total_localtax2=".$this->total_localtax2.",";
2993
+        $sql.= " total_ttc=".$this->total_ttc.",";
2994
+        $sql.= " fk_product_fournisseur_price=".(!empty($this->fk_fournprice)?$this->fk_fournprice:"NULL").",";
2995
+        $sql.= " buy_price_ht='".price2num($this->pa_ht)."',";
2996
+        $sql.= " info_bits='".$this->db->escape($this->info_bits)."',";
2997
+        $sql.= " fk_user_author=".($this->fk_user_author >= 0?$this->fk_user_author:"NULL").",";
2998
+        $sql.= " fk_user_ouverture=".($this->fk_user_ouverture > 0?$this->fk_user_ouverture:"NULL").",";
2999
+        $sql.= " fk_user_cloture=".($this->fk_user_cloture > 0?$this->fk_user_cloture:"NULL").",";
3000
+        $sql.= " commentaire='".$this->db->escape($this->commentaire)."',";
3001
+        $sql.= " fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
3002
+        $sql.= " WHERE rowid=".$this->id;
3003
+
3004
+        dol_syslog(get_class($this)."::update", LOG_DEBUG);
3005
+        $resql = $this->db->query($sql);
3006
+        if (! $resql)
3007
+        {
3008
+            $this->error="Error ".$this->db->lasterror();
3009
+            $error++;
3010
+        }
3011
+
3012
+        if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used
3013
+        {
3014
+            $result=$this->insertExtraFields();
3015
+            if ($result < 0)
3016
+            {
3017
+                $error++;
3018
+            }
3019
+        }
3020
+
3021
+        // If we change a planned date (start or end), sync dates for all services
3022
+        if (! $error && ! empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES))
3023
+        {
3024
+            if ($this->date_ouverture_prevue != $this->oldcopy->date_ouverture_prevue)
3025
+            {
3026
+                $sql ='UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3027
+                $sql.= " date_ouverture_prevue = ".($this->date_ouverture_prevue!=''?"'".$this->db->idate($this->date_ouverture_prevue)."'":"null");
3028
+                $sql.= " WHERE fk_contrat = ".$this->fk_contrat;
3029
+
3030
+                $resql = $this->db->query($sql);
3031
+                if (! $resql)
3032
+                {
3033
+                    $error++;
3034
+                    $this->error="Error ".$this->db->lasterror();
3035
+                }
3036
+            }
3037
+            if ($this->date_fin_validite != $this->oldcopy->date_fin_validite)
3038
+            {
3039
+                $sql ='UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3040
+                $sql.= " date_fin_validite = ".($this->date_fin_validite!=''?"'".$this->db->idate($this->date_fin_validite)."'":"null");
3041
+                $sql.= " WHERE fk_contrat = ".$this->fk_contrat;
3042
+
3043
+                $resql = $this->db->query($sql);
3044
+                if (! $resql)
3045
+                {
3046
+                    $error++;
3047
+                    $this->error="Error ".$this->db->lasterror();
3048
+                }
3049
+            }
3050
+        }
3051
+
3052
+        if (! $error && ! $notrigger) {
3053
+            // Call trigger
3054
+            $result=$this->call_trigger('LINECONTRACT_UPDATE', $user);
3055
+            if ($result < 0) {
3056 3056
                 $error++;
3057 3057
                 $this->db->rollback();
3058 3058
             }
3059
-	        // End call triggers
3060
-		}
3059
+            // End call triggers
3060
+        }
3061 3061
 
3062
-		if (! $error)
3063
-		{
3064
-        	$this->db->commit();
3065
-			return 1;
3066
-		} else {
3067
-			$this->db->rollback();
3068
-			$this->errors[]=$this->error;
3069
-			return -1;
3070
-		}
3071
-	}
3062
+        if (! $error)
3063
+        {
3064
+            $this->db->commit();
3065
+            return 1;
3066
+        } else {
3067
+            $this->db->rollback();
3068
+            $this->errors[]=$this->error;
3069
+            return -1;
3070
+        }
3071
+    }
3072 3072
 
3073 3073
 
3074 3074
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3075
-	/**
3076
-	 *      Mise a jour en base des champs total_xxx de ligne
3077
-	 *		Used by migration process
3078
-	 *
3079
-	 *		@return		int		<0 if KO, >0 if OK
3080
-	 */
3081
-	function update_total()
3082
-	{
3075
+    /**
3076
+     *      Mise a jour en base des champs total_xxx de ligne
3077
+     *		Used by migration process
3078
+     *
3079
+     *		@return		int		<0 if KO, >0 if OK
3080
+     */
3081
+    function update_total()
3082
+    {
3083 3083
         // phpcs:enable
3084
-		$this->db->begin();
3085
-
3086
-		// Mise a jour ligne en base
3087
-		$sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3088
-		$sql.= " total_ht=".price2num($this->total_ht,'MT')."";
3089
-		$sql.= ",total_tva=".price2num($this->total_tva,'MT')."";
3090
-		$sql.= ",total_localtax1=".price2num($this->total_localtax1,'MT')."";
3091
-		$sql.= ",total_localtax2=".price2num($this->total_localtax2,'MT')."";
3092
-		$sql.= ",total_ttc=".price2num($this->total_ttc,'MT')."";
3093
-		$sql.= " WHERE rowid = ".$this->id;
3094
-
3095
-		dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
3096
-
3097
-		$resql=$this->db->query($sql);
3098
-		if ($resql)
3099
-		{
3100
-			$this->db->commit();
3101
-			return 1;
3102
-		}
3103
-		else
3104
-		{
3105
-			$this->error=$this->db->error();
3106
-			$this->db->rollback();
3107
-			return -2;
3108
-		}
3109
-	}
3110
-
3111
-
3112
-	/**
3113
-	 * Inserts a contrat line into database
3114
-	 *
3115
-	 * @param int $notrigger Set to 1 if you don't want triggers to be fired
3116
-	 * @return int <0 if KO, >0 if OK
3117
-	 */
3118
-	public function insert($notrigger = 0)
3119
-	{
3120
-		global $conf, $user;
3121
-
3122
-		// Insertion dans la base
3123
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
3124
-		$sql.= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
3125
-		$sql.= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
3126
-		$sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
3127
-		$sql.= " info_bits,";
3128
-		$sql.= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
3129
-		if ($this->date_ouverture_prevue > 0) { $sql.= ",date_ouverture_prevue"; }
3130
-		if ($this->date_fin_validite > 0)     { $sql.= ",date_fin_validite"; }
3131
-		$sql.= ") VALUES ($this->fk_contrat, '', '" . $this->db->escape($this->description) . "',";
3132
-		$sql.= ($this->fk_product>0 ? $this->fk_product : "null").",";
3133
-		$sql.= " '".$this->db->escape($this->qty)."',";
3134
-		$sql.= " '".$this->db->escape($this->vat_src_code)."',";
3135
-		$sql.= " '".$this->db->escape($this->tva_tx)."',";
3136
-		$sql.= " '".$this->db->escape($this->localtax1_tx)."',";
3137
-		$sql.= " '".$this->db->escape($this->localtax2_tx)."',";
3138
-		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
3139
-		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
3140
-		$sql.= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
3141
-		$sql.= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3142
-		$sql.= " '".$this->db->escape($this->info_bits)."',";
3143
-		$sql.= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3144
-		if ($this->fk_fournprice > 0) $sql.= ' '.$this->fk_fournprice.',';
3145
-		else $sql.= ' null,';
3146
-		if ($this->pa_ht > 0) $sql.= ' '.price2num($this->pa_ht);
3147
-		else $sql.= ' null';
3148
-		if ($this->date_ouverture > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture)."'"; }
3149
-		if ($this->date_cloture > 0)   { $sql.= ",'".$this->db->idate($this->date_cloture)."'"; }
3150
-		$sql.= ")";
3151
-
3152
-		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3153
-
3154
-		$resql=$this->db->query($sql);
3155
-		if ($resql)
3156
-		{
3157
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
3158
-
3159
-			// Insert of extrafields
3160
-			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used
3161
-			{
3162
-				$result = $this->insertExtraFields();
3163
-				if ($result < 0)
3164
-				{
3165
-					$this->db->rollback();
3166
-					return -1;
3167
-				}
3168
-			}
3169
-
3170
-			if (!$notrigger)
3171
-			{
3172
-				// Call trigger
3173
-				$result = $this->call_trigger('LINECONTRACT_INSERT', $user);
3174
-				if ($result < 0) {
3175
-					$this->db->rollback();
3176
-					return -1;
3177
-				}
3178
-				// End call triggers
3179
-			}
3180
-
3181
-			$this->db->commit();
3182
-			return 1;
3183
-		}
3184
-		else
3185
-		{
3186
-			$this->db->rollback();
3187
-			$this->error=$this->db->error()." sql=".$sql;
3188
-			return -1;
3189
-		}
3190
-	}
3084
+        $this->db->begin();
3085
+
3086
+        // Mise a jour ligne en base
3087
+        $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3088
+        $sql.= " total_ht=".price2num($this->total_ht,'MT')."";
3089
+        $sql.= ",total_tva=".price2num($this->total_tva,'MT')."";
3090
+        $sql.= ",total_localtax1=".price2num($this->total_localtax1,'MT')."";
3091
+        $sql.= ",total_localtax2=".price2num($this->total_localtax2,'MT')."";
3092
+        $sql.= ",total_ttc=".price2num($this->total_ttc,'MT')."";
3093
+        $sql.= " WHERE rowid = ".$this->id;
3094
+
3095
+        dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
3096
+
3097
+        $resql=$this->db->query($sql);
3098
+        if ($resql)
3099
+        {
3100
+            $this->db->commit();
3101
+            return 1;
3102
+        }
3103
+        else
3104
+        {
3105
+            $this->error=$this->db->error();
3106
+            $this->db->rollback();
3107
+            return -2;
3108
+        }
3109
+    }
3110
+
3111
+
3112
+    /**
3113
+     * Inserts a contrat line into database
3114
+     *
3115
+     * @param int $notrigger Set to 1 if you don't want triggers to be fired
3116
+     * @return int <0 if KO, >0 if OK
3117
+     */
3118
+    public function insert($notrigger = 0)
3119
+    {
3120
+        global $conf, $user;
3121
+
3122
+        // Insertion dans la base
3123
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
3124
+        $sql.= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
3125
+        $sql.= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
3126
+        $sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
3127
+        $sql.= " info_bits,";
3128
+        $sql.= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
3129
+        if ($this->date_ouverture_prevue > 0) { $sql.= ",date_ouverture_prevue"; }
3130
+        if ($this->date_fin_validite > 0)     { $sql.= ",date_fin_validite"; }
3131
+        $sql.= ") VALUES ($this->fk_contrat, '', '" . $this->db->escape($this->description) . "',";
3132
+        $sql.= ($this->fk_product>0 ? $this->fk_product : "null").",";
3133
+        $sql.= " '".$this->db->escape($this->qty)."',";
3134
+        $sql.= " '".$this->db->escape($this->vat_src_code)."',";
3135
+        $sql.= " '".$this->db->escape($this->tva_tx)."',";
3136
+        $sql.= " '".$this->db->escape($this->localtax1_tx)."',";
3137
+        $sql.= " '".$this->db->escape($this->localtax2_tx)."',";
3138
+        $sql.= " '".$this->db->escape($this->localtax1_type)."',";
3139
+        $sql.= " '".$this->db->escape($this->localtax2_type)."',";
3140
+        $sql.= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
3141
+        $sql.= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3142
+        $sql.= " '".$this->db->escape($this->info_bits)."',";
3143
+        $sql.= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3144
+        if ($this->fk_fournprice > 0) $sql.= ' '.$this->fk_fournprice.',';
3145
+        else $sql.= ' null,';
3146
+        if ($this->pa_ht > 0) $sql.= ' '.price2num($this->pa_ht);
3147
+        else $sql.= ' null';
3148
+        if ($this->date_ouverture > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture)."'"; }
3149
+        if ($this->date_cloture > 0)   { $sql.= ",'".$this->db->idate($this->date_cloture)."'"; }
3150
+        $sql.= ")";
3151
+
3152
+        dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3153
+
3154
+        $resql=$this->db->query($sql);
3155
+        if ($resql)
3156
+        {
3157
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
3158
+
3159
+            // Insert of extrafields
3160
+            if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used
3161
+            {
3162
+                $result = $this->insertExtraFields();
3163
+                if ($result < 0)
3164
+                {
3165
+                    $this->db->rollback();
3166
+                    return -1;
3167
+                }
3168
+            }
3169
+
3170
+            if (!$notrigger)
3171
+            {
3172
+                // Call trigger
3173
+                $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
3174
+                if ($result < 0) {
3175
+                    $this->db->rollback();
3176
+                    return -1;
3177
+                }
3178
+                // End call triggers
3179
+            }
3180
+
3181
+            $this->db->commit();
3182
+            return 1;
3183
+        }
3184
+        else
3185
+        {
3186
+            $this->db->rollback();
3187
+            $this->error=$this->db->error()." sql=".$sql;
3188
+            return -1;
3189
+        }
3190
+    }
3191 3191
 
3192 3192
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3193
-	/**
3194
-	 *  Activate a contract line
3195
-	 *
3196
-	 * @param   User 		$user 		Objet User who activate contract
3197
-	 * @param  	int 		$date 		Date activation
3198
-	 * @param  	int|string 	$date_end 	Date planned end. Use '-1' to keep it unchanged.
3199
-	 * @param   string 		$comment 	A comment typed by user
3200
-	 * @return 	int                    	<0 if KO, >0 if OK
3201
-	 */
3202
-	function active_line($user, $date, $date_end = '', $comment = '')
3203
-	{
3193
+    /**
3194
+     *  Activate a contract line
3195
+     *
3196
+     * @param   User 		$user 		Objet User who activate contract
3197
+     * @param  	int 		$date 		Date activation
3198
+     * @param  	int|string 	$date_end 	Date planned end. Use '-1' to keep it unchanged.
3199
+     * @param   string 		$comment 	A comment typed by user
3200
+     * @return 	int                    	<0 if KO, >0 if OK
3201
+     */
3202
+    function active_line($user, $date, $date_end = '', $comment = '')
3203
+    {
3204 3204
         // phpcs:enable
3205
-		global $langs, $conf;
3206
-
3207
-		$error = 0;
3208
-
3209
-		$this->db->begin();
3210
-
3211
-		$sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = ".ContratLigne::STATUS_OPEN.",";
3212
-		$sql .= " date_ouverture = " . (dol_strlen($date) != 0 ? "'" . $this->db->idate($date) . "'" : "null") . ",";
3213
-		if ($date_end >= 0) $sql .= " date_fin_validite = " . (dol_strlen($date_end) != 0 ? "'" . $this->db->idate($date_end) . "'" : "null") . ",";
3214
-		$sql .= " fk_user_ouverture = " . $user->id . ",";
3215
-		$sql .= " date_cloture = null,";
3216
-		$sql .= " commentaire = '" . $this->db->escape($comment) . "'";
3217
-		$sql .= " WHERE rowid = " . $this->id . " AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
3218
-
3219
-		dol_syslog(get_class($this) . "::active_line", LOG_DEBUG);
3220
-		$resql = $this->db->query($sql);
3221
-		if ($resql) {
3222
-			// Call trigger
3223
-			$result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user);
3224
-			if ($result < 0) $error++;
3225
-			// End call triggers
3226
-
3227
-			if (! $error)
3228
-			{
3229
-				$this->statut = ContratLigne::STATUS_OPEN;
3230
-				$this->date_ouverture = $date;
3231
-				$this->date_fin_validite = $date_end;
3232
-				$this->fk_user_ouverture = $user->id;
3233
-				$this->date_cloture = null;
3234
-				$this->commentaire = $comment;
3235
-
3236
-				$this->db->commit();
3237
-				return 1;
3238
-			}
3239
-			else
3240
-			{
3241
-				$this->db->rollback();
3242
-				return -1;
3243
-			}
3244
-		} else {
3245
-			$this->error = $this->db->lasterror();
3246
-			$this->db->rollback();
3247
-			return -1;
3248
-		}
3249
-	}
3205
+        global $langs, $conf;
3206
+
3207
+        $error = 0;
3208
+
3209
+        $this->db->begin();
3210
+
3211
+        $sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = ".ContratLigne::STATUS_OPEN.",";
3212
+        $sql .= " date_ouverture = " . (dol_strlen($date) != 0 ? "'" . $this->db->idate($date) . "'" : "null") . ",";
3213
+        if ($date_end >= 0) $sql .= " date_fin_validite = " . (dol_strlen($date_end) != 0 ? "'" . $this->db->idate($date_end) . "'" : "null") . ",";
3214
+        $sql .= " fk_user_ouverture = " . $user->id . ",";
3215
+        $sql .= " date_cloture = null,";
3216
+        $sql .= " commentaire = '" . $this->db->escape($comment) . "'";
3217
+        $sql .= " WHERE rowid = " . $this->id . " AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
3218
+
3219
+        dol_syslog(get_class($this) . "::active_line", LOG_DEBUG);
3220
+        $resql = $this->db->query($sql);
3221
+        if ($resql) {
3222
+            // Call trigger
3223
+            $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user);
3224
+            if ($result < 0) $error++;
3225
+            // End call triggers
3226
+
3227
+            if (! $error)
3228
+            {
3229
+                $this->statut = ContratLigne::STATUS_OPEN;
3230
+                $this->date_ouverture = $date;
3231
+                $this->date_fin_validite = $date_end;
3232
+                $this->fk_user_ouverture = $user->id;
3233
+                $this->date_cloture = null;
3234
+                $this->commentaire = $comment;
3235
+
3236
+                $this->db->commit();
3237
+                return 1;
3238
+            }
3239
+            else
3240
+            {
3241
+                $this->db->rollback();
3242
+                return -1;
3243
+            }
3244
+        } else {
3245
+            $this->error = $this->db->lasterror();
3246
+            $this->db->rollback();
3247
+            return -1;
3248
+        }
3249
+    }
3250 3250
 
3251 3251
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3252
-	/**
3253
-	 *  Close a contract line
3254
-	 *
3255
-	 * @param    User 	$user 			Objet User who close contract
3256
-	 * @param  	 int 	$date_end 		Date end
3257
-	 * @param    string $comment 		A comment typed by user
3252
+    /**
3253
+     *  Close a contract line
3254
+     *
3255
+     * @param    User 	$user 			Objet User who close contract
3256
+     * @param  	 int 	$date_end 		Date end
3257
+     * @param    string $comment 		A comment typed by user
3258 3258
      * @param    int	$notrigger		1=Does not execute triggers, 0=Execute triggers
3259
-	 * @return int                    	<0 if KO, >0 if OK
3260
-	 */
3261
-	function close_line($user, $date_end, $comment = '', $notrigger=0)
3262
-	{
3259
+     * @return int                    	<0 if KO, >0 if OK
3260
+     */
3261
+    function close_line($user, $date_end, $comment = '', $notrigger=0)
3262
+    {
3263 3263
         // phpcs:enable
3264
-		global $langs, $conf;
3265
-
3266
-		// Update object
3267
-		$this->date_cloture = $date_end;
3268
-		$this->fk_user_cloture = $user->id;
3269
-		$this->commentaire = $comment;
3270
-
3271
-		$error = 0;
3272
-
3273
-		// statut actif : 4
3274
-
3275
-		$this->db->begin();
3276
-
3277
-		$sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = ".ContratLigne::STATUS_CLOSED.",";
3278
-		$sql .= " date_cloture = '" . $this->db->idate($date_end) . "',";
3279
-		$sql .= " fk_user_cloture = " . $user->id . ",";
3280
-		$sql .= " commentaire = '" . $this->db->escape($comment) . "'";
3281
-		$sql .= " WHERE rowid = " . $this->id . " AND statut = ".ContratLigne::STATUS_OPEN;
3282
-
3283
-		$resql = $this->db->query($sql);
3284
-		if ($resql)
3285
-		{
3286
-			if (! $notrigger)
3287
-			{
3288
-				// Call trigger
3289
-				$result = $this->call_trigger('LINECONTRACT_CLOSE', $user);
3290
-				if ($result < 0) {
3291
-					$error++;
3292
-					$this->db->rollback();
3293
-					return -1;
3294
-				}
3295
-				// End call triggers
3296
-			}
3297
-
3298
-			$this->db->commit();
3299
-			return 1;
3300
-		} else {
3301
-			$this->error = $this->db->lasterror();
3302
-			$this->db->rollback();
3303
-			return -1;
3304
-		}
3305
-	}
3264
+        global $langs, $conf;
3265
+
3266
+        // Update object
3267
+        $this->date_cloture = $date_end;
3268
+        $this->fk_user_cloture = $user->id;
3269
+        $this->commentaire = $comment;
3270
+
3271
+        $error = 0;
3272
+
3273
+        // statut actif : 4
3274
+
3275
+        $this->db->begin();
3276
+
3277
+        $sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = ".ContratLigne::STATUS_CLOSED.",";
3278
+        $sql .= " date_cloture = '" . $this->db->idate($date_end) . "',";
3279
+        $sql .= " fk_user_cloture = " . $user->id . ",";
3280
+        $sql .= " commentaire = '" . $this->db->escape($comment) . "'";
3281
+        $sql .= " WHERE rowid = " . $this->id . " AND statut = ".ContratLigne::STATUS_OPEN;
3282
+
3283
+        $resql = $this->db->query($sql);
3284
+        if ($resql)
3285
+        {
3286
+            if (! $notrigger)
3287
+            {
3288
+                // Call trigger
3289
+                $result = $this->call_trigger('LINECONTRACT_CLOSE', $user);
3290
+                if ($result < 0) {
3291
+                    $error++;
3292
+                    $this->db->rollback();
3293
+                    return -1;
3294
+                }
3295
+                // End call triggers
3296
+            }
3297
+
3298
+            $this->db->commit();
3299
+            return 1;
3300
+        } else {
3301
+            $this->error = $this->db->lasterror();
3302
+            $this->db->rollback();
3303
+            return -1;
3304
+        }
3305
+    }
3306 3306
 }
Please login to merge, or discard this patch.
Spacing   +812 added lines, -812 removed lines patch added patch discarded remove patch
@@ -32,10 +32,10 @@  discard block
 block discarded – undo
32 32
  *	\brief      File of class to manage contracts
33 33
  */
34 34
 
35
-require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
35
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
36 36
 require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
37
-require_once DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php';
38
-require_once DOL_DOCUMENT_ROOT . '/margin/lib/margins.lib.php';
37
+require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
38
+require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
39 39
 
40 40
 /**
41 41
  *	Class to manage contracts
@@ -45,27 +45,27 @@  discard block
 block discarded – undo
45 45
 	/**
46 46
 	 * @var string ID to identify managed object
47 47
 	 */
48
-	public $element='contrat';
48
+	public $element = 'contrat';
49 49
 
50 50
 	/**
51 51
 	 * @var string Name of table without prefix where object is stored
52 52
 	 */
53
-	public $table_element='contrat';
53
+	public $table_element = 'contrat';
54 54
 
55 55
 	/**
56 56
 	 * @var int    Name of subtable line
57 57
 	 */
58
-	public $table_element_line='contratdet';
58
+	public $table_element_line = 'contratdet';
59 59
 
60 60
 	/**
61 61
 	 * @var int Field with ID of parent key if this field has a parent
62 62
 	 */
63
-	public $fk_element='fk_contrat';
63
+	public $fk_element = 'fk_contrat';
64 64
 
65 65
     /**
66 66
 	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
67 67
 	 */
68
-	public $picto='contract';
68
+	public $picto = 'contract';
69 69
 
70 70
     /**
71 71
      * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
@@ -102,13 +102,13 @@  discard block
 block discarded – undo
102 102
 	 */
103 103
 	public $socid;
104 104
 
105
-	public $societe;		// Objet societe
105
+	public $societe; // Objet societe
106 106
 
107 107
 	/**
108 108
 	 * Status of the contract
109 109
 	 * @var int
110 110
 	 */
111
-	public $statut=0;		// 0=Draft,
111
+	public $statut = 0; // 0=Draft,
112 112
 
113 113
 	public $product;
114 114
 
@@ -169,18 +169,18 @@  discard block
 block discarded – undo
169 169
 	 */
170 170
 	public $fk_projet;
171 171
 
172
-	public $extraparams=array();
172
+	public $extraparams = array();
173 173
 
174 174
 	/**
175 175
 	 * @var ContratLigne[]		Contract lines
176 176
 	 */
177
-	public $lines=array();
177
+	public $lines = array();
178 178
 
179 179
 	/**
180 180
 	 * Maps ContratLigne IDs to $this->lines indexes
181 181
 	 * @var int[]
182 182
 	 */
183
-	protected $lines_id_index_mapper=array();
183
+	protected $lines_id_index_mapper = array();
184 184
 
185 185
 
186 186
 	/**
@@ -219,26 +219,26 @@  discard block
 block discarded – undo
219 219
 				$dir = dol_buildpath($reldir."core/modules/contract/");
220 220
 
221 221
 				// Load file with numbering class (if found)
222
-				$mybool|=@include_once $dir.$file;
222
+				$mybool |= @include_once $dir.$file;
223 223
 			}
224 224
 
225
-			if (! $mybool)
225
+			if (!$mybool)
226 226
 			{
227
-				dol_print_error('',"Failed to include file ".$file);
227
+				dol_print_error('', "Failed to include file ".$file);
228 228
 				return '';
229 229
 			}
230 230
 
231 231
 			$obj = new $classname();
232
-			$numref = $obj->getNextValue($soc,$this);
232
+			$numref = $obj->getNextValue($soc, $this);
233 233
 
234
-			if ( $numref != "")
234
+			if ($numref != "")
235 235
 			{
236 236
 				return $numref;
237 237
 			}
238 238
 			else
239 239
 			{
240 240
 				$this->error = $obj->error;
241
-				dol_print_error($db,get_class($this)."::getNextValue ".$obj->error);
241
+				dol_print_error($db, get_class($this)."::getNextValue ".$obj->error);
242 242
 				return "";
243 243
 			}
244 244
 		}
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 * 	@param	string		$comment	A comment typed by user
262 262
 	 *  @return int         			<0 if KO, >0 if OK
263 263
 	 */
264
-	function active_line($user, $line_id, $date, $date_end='', $comment='')
264
+	function active_line($user, $line_id, $date, $date_end = '', $comment = '')
265 265
 	{
266 266
         // phpcs:enable
267 267
 		$result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date, $date_end, $comment);
@@ -284,10 +284,10 @@  discard block
 block discarded – undo
284 284
 	 * 	@param	string		$comment	A comment typed by user
285 285
 	 *  @return int         			<0 if KO, >0 if OK
286 286
 	 */
287
-	function close_line($user, $line_id, $date_end, $comment='')
287
+	function close_line($user, $line_id, $date_end, $comment = '')
288 288
 	{
289 289
         // phpcs:enable
290
-		$result=$this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
290
+		$result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
291 291
 		if ($result < 0)
292 292
 		{
293 293
 			$this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
@@ -307,18 +307,18 @@  discard block
 block discarded – undo
307 307
 	 *	@return	int							<0 if KO, >0 if OK
308 308
 	 *  @see closeAll
309 309
 	 */
310
-	function activateAll($user, $date_start='', $notrigger=0, $comment='')
310
+	function activateAll($user, $date_start = '', $notrigger = 0, $comment = '')
311 311
 	{
312 312
 		if (empty($date_start)) $date_start = dol_now();
313 313
 
314 314
 		$this->db->begin();
315 315
 
316
-		$error=0;
316
+		$error = 0;
317 317
 
318 318
 		// Load lines
319 319
 		$this->fetch_lines();
320 320
 
321
-		foreach($this->lines as $contratline)
321
+		foreach ($this->lines as $contratline)
322 322
 		{
323 323
 			// Open lines not already open
324 324
 			if ($contratline->statut != ContratLigne::STATUS_OPEN)
@@ -336,13 +336,13 @@  discard block
 block discarded – undo
336 336
 			}
337 337
 		}
338 338
 
339
-		if (! $error && $this->statut == 0)
339
+		if (!$error && $this->statut == 0)
340 340
 		{
341
-			$result=$this->validate($user, '', $notrigger);
341
+			$result = $this->validate($user, '', $notrigger);
342 342
 			if ($result < 0) $error++;
343 343
 		}
344 344
 
345
-		if (! $error)
345
+		if (!$error)
346 346
 		{
347 347
 			$this->db->commit();
348 348
 			return 1;
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
 	 * @return	int							<0 if KO, >0 if OK
364 364
 	 * @see activateAll
365 365
 	 */
366
-	function closeAll(User $user, $notrigger=0, $comment='')
366
+	function closeAll(User $user, $notrigger = 0, $comment = '')
367 367
 	{
368 368
 		$this->db->begin();
369 369
 
@@ -374,15 +374,15 @@  discard block
 block discarded – undo
374 374
 
375 375
 		$error = 0;
376 376
 
377
-		foreach($this->lines as $contratline)
377
+		foreach ($this->lines as $contratline)
378 378
 		{
379 379
 			// Close lines not already closed
380 380
 			if ($contratline->statut != ContratLigne::STATUS_CLOSED)
381 381
 	        {
382
-				$contratline->date_cloture=$now;
383
-				$contratline->fk_user_cloture=$user->id;
384
-				$contratline->statut=ContratLigne::STATUS_CLOSED;
385
-				$result=$contratline->close_line($user, $now, $comment, $notrigger);
382
+				$contratline->date_cloture = $now;
383
+				$contratline->fk_user_cloture = $user->id;
384
+				$contratline->statut = ContratLigne::STATUS_CLOSED;
385
+				$result = $contratline->close_line($user, $now, $comment, $notrigger);
386 386
 				if ($result < 0)
387 387
 				{
388 388
 					$error++;
@@ -393,13 +393,13 @@  discard block
 block discarded – undo
393 393
 	        }
394 394
 		}
395 395
 
396
-		if (! $error && $this->statut == 0)
396
+		if (!$error && $this->statut == 0)
397 397
 		{
398
-			$result=$this->validate($user, '', $notrigger);
398
+			$result = $this->validate($user, '', $notrigger);
399 399
 			if ($result < 0) $error++;
400 400
 		}
401 401
 
402
-        if (! $error)
402
+        if (!$error)
403 403
         {
404 404
             $this->db->commit();
405 405
             return 1;
@@ -419,14 +419,14 @@  discard block
 block discarded – undo
419 419
      * @param	int		$notrigger		1=Does not execute triggers, 0= execute triggers
420 420
 	 * @return	int						<0 if KO, >0 if OK
421 421
 	 */
422
-	function validate(User $user, $force_number='', $notrigger=0)
422
+	function validate(User $user, $force_number = '', $notrigger = 0)
423 423
 	{
424 424
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
425 425
 		global $langs, $conf;
426 426
 
427
-		$now=dol_now();
427
+		$now = dol_now();
428 428
 
429
-		$error=0;
429
+		$error = 0;
430 430
 		dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
431 431
 
432 432
 
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
 		// A contract is validated so we can move thirdparty to status customer
438 438
 		if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION))
439 439
 		{
440
-			$result=$this->thirdparty->set_as_client();
440
+			$result = $this->thirdparty->set_as_client();
441 441
 		}
442 442
 
443 443
 		// Define new ref
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
 		{
446 446
 			$num = $force_number;
447 447
 		}
448
-		else if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
448
+		else if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
449 449
 		{
450 450
 			$num = $this->getNextNumRef($this->thirdparty);
451 451
 		}
@@ -459,27 +459,27 @@  discard block
 block discarded – undo
459 459
 		{
460 460
 			$sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$num."', statut = 1";
461 461
 			//$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
462
-			$sql .= " WHERE rowid = ".$this->id . " AND statut = 0";
462
+			$sql .= " WHERE rowid = ".$this->id." AND statut = 0";
463 463
 
464 464
 			dol_syslog(get_class($this)."::validate", LOG_DEBUG);
465 465
 			$resql = $this->db->query($sql);
466
-			if (! $resql)
466
+			if (!$resql)
467 467
 			{
468 468
 				dol_print_error($this->db);
469 469
 				$error++;
470
-				$this->error=$this->db->lasterror();
470
+				$this->error = $this->db->lasterror();
471 471
 			}
472 472
 
473 473
 			// Trigger calls
474
-			if (! $error && ! $notrigger)
474
+			if (!$error && !$notrigger)
475 475
 			{
476 476
                 // Call trigger
477
-                $result=$this->call_trigger('CONTRACT_VALIDATE',$user);
477
+                $result = $this->call_trigger('CONTRACT_VALIDATE', $user);
478 478
                 if ($result < 0) { $error++; }
479 479
                 // End call triggers
480 480
 			}
481 481
 
482
-			if (! $error)
482
+			if (!$error)
483 483
 			{
484 484
             	$this->oldref = $this->ref;
485 485
 
@@ -500,13 +500,13 @@  discard block
 block discarded – undo
500 500
 						{
501 501
 							dol_syslog("Rename ok");
502 502
 						    // Rename docs starting with $oldref with $newref
503
-            				$listoffiles=dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
504
-            				foreach($listoffiles as $fileentry)
503
+            				$listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
504
+            				foreach ($listoffiles as $fileentry)
505 505
             				{
506
-            					$dirsource=$fileentry['name'];
507
-            					$dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
508
-            					$dirsource=$fileentry['path'].'/'.$dirsource;
509
-            					$dirdest=$fileentry['path'].'/'.$dirdest;
506
+            					$dirsource = $fileentry['name'];
507
+            					$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
508
+            					$dirsource = $fileentry['path'].'/'.$dirsource;
509
+            					$dirdest = $fileentry['path'].'/'.$dirdest;
510 510
             					@rename($dirsource, $dirdest);
511 511
             				}
512 512
 						}
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
 			}
516 516
 
517 517
 			// Set new ref and define current statut
518
-			if (! $error)
518
+			if (!$error)
519 519
 			{
520 520
 				$this->ref = $num;
521 521
 				$this->statut = 1;
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
 			$error++;
529 529
 		}
530 530
 
531
-		if (! $error)
531
+		if (!$error)
532 532
 		{
533 533
 			$this->db->commit();
534 534
 			return 1;
@@ -547,14 +547,14 @@  discard block
 block discarded – undo
547 547
      * @param	int		$notrigger		1=Does not execute triggers, 0=execute triggers
548 548
 	 * @return	int						<0 if KO, >0 if OK
549 549
 	 */
550
-	function reopen($user, $notrigger=0)
550
+	function reopen($user, $notrigger = 0)
551 551
 	{
552 552
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
553 553
 		global $langs, $conf;
554 554
 
555
-		$now=dol_now();
555
+		$now = dol_now();
556 556
 
557
-		$error=0;
557
+		$error = 0;
558 558
 		dol_syslog(get_class($this).'::reopen user='.$user->id);
559 559
 
560 560
 		$this->db->begin();
@@ -563,22 +563,22 @@  discard block
 block discarded – undo
563 563
 
564 564
 		$sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
565 565
 		//$sql.= ", fk_user_valid = null, date_valid = null";
566
-		$sql .= " WHERE rowid = ".$this->id . " AND statut = 1";
566
+		$sql .= " WHERE rowid = ".$this->id." AND statut = 1";
567 567
 
568 568
 		dol_syslog(get_class($this)."::validate", LOG_DEBUG);
569 569
 		$resql = $this->db->query($sql);
570
-		if (! $resql)
570
+		if (!$resql)
571 571
 		{
572 572
 			dol_print_error($this->db);
573 573
 			$error++;
574
-			$this->error=$this->db->lasterror();
574
+			$this->error = $this->db->lasterror();
575 575
 		}
576 576
 
577 577
 		// Trigger calls
578
-		if (! $error && ! $notrigger)
578
+		if (!$error && !$notrigger)
579 579
 		{
580 580
 			// Call trigger
581
-			$result=$this->call_trigger('CONTRACT_REOPEN',$user);
581
+			$result = $this->call_trigger('CONTRACT_REOPEN', $user);
582 582
 			if ($result < 0) {
583 583
 				$error++;
584 584
 			}
@@ -586,14 +586,14 @@  discard block
 block discarded – undo
586 586
 		}
587 587
 
588 588
 		// Set new ref and define current status
589
-		if (! $error)
589
+		if (!$error)
590 590
 		{
591
-			$this->statut=0;
592
-			$this->brouillon=1;
593
-			$this->date_validation=$now;
591
+			$this->statut = 0;
592
+			$this->brouillon = 1;
593
+			$this->date_validation = $now;
594 594
 		}
595 595
 
596
-		if (! $error)
596
+		if (!$error)
597 597
 		{
598 598
 			$this->db->commit();
599 599
 			return 1;
@@ -614,30 +614,30 @@  discard block
 block discarded – undo
614 614
 	 *    @param	string	$ref_supplier	Supplier ref
615 615
 	 *    @return   int     				<0 if KO, 0 if not found, Id of contract if OK
616 616
 	 */
617
-	function fetch($id, $ref='', $ref_customer='', $ref_supplier='')
617
+	function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '')
618 618
 	{
619 619
 		$sql = "SELECT rowid, statut, ref, fk_soc, mise_en_service as datemise,";
620
-		$sql.= " ref_supplier, ref_customer,";
621
-		$sql.= " ref_ext,";
622
-		$sql.= " fk_user_mise_en_service, date_contrat as datecontrat,";
623
-		$sql.= " fk_user_author, fin_validite, date_cloture,";
624
-		$sql.= " fk_projet,";
625
-		$sql.= " fk_commercial_signature, fk_commercial_suivi,";
626
-		$sql.= " note_private, note_public, model_pdf, extraparams";
627
-		$sql.= " FROM ".MAIN_DB_PREFIX."contrat";
628
-		if (! $id) $sql.=" WHERE entity IN (".getEntity('contract').")";
629
-		else $sql.= " WHERE rowid=".$id;
620
+		$sql .= " ref_supplier, ref_customer,";
621
+		$sql .= " ref_ext,";
622
+		$sql .= " fk_user_mise_en_service, date_contrat as datecontrat,";
623
+		$sql .= " fk_user_author, fin_validite, date_cloture,";
624
+		$sql .= " fk_projet,";
625
+		$sql .= " fk_commercial_signature, fk_commercial_suivi,";
626
+		$sql .= " note_private, note_public, model_pdf, extraparams";
627
+		$sql .= " FROM ".MAIN_DB_PREFIX."contrat";
628
+		if (!$id) $sql .= " WHERE entity IN (".getEntity('contract').")";
629
+		else $sql .= " WHERE rowid=".$id;
630 630
 		if ($ref_customer)
631 631
 		{
632
-			$sql.= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
632
+			$sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
633 633
 		}
634 634
 		if ($ref_supplier)
635 635
 		{
636
-			$sql.= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
636
+			$sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
637 637
 		}
638 638
 		if ($ref)
639 639
 		{
640
-			$sql.= " AND ref='".$this->db->escape($ref)."'";
640
+			$sql .= " AND ref='".$this->db->escape($ref)."'";
641 641
 		}
642 642
 
643 643
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
@@ -648,13 +648,13 @@  discard block
 block discarded – undo
648 648
 
649 649
 			if ($obj)
650 650
 			{
651
-				$this->id						= $obj->rowid;
652
-				$this->ref						= (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
651
+				$this->id = $obj->rowid;
652
+				$this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
653 653
 				$this->ref_customer				= $obj->ref_customer;
654 654
 				$this->ref_supplier				= $obj->ref_supplier;
655
-				$this->ref_ext					= $obj->ref_ext;
656
-				$this->statut					= $obj->statut;
657
-				$this->mise_en_service			= $this->db->jdate($obj->datemise);
655
+				$this->ref_ext = $obj->ref_ext;
656
+				$this->statut = $obj->statut;
657
+				$this->mise_en_service = $this->db->jdate($obj->datemise);
658 658
 
659 659
 				$this->date_contrat				= $this->db->jdate($obj->datecontrat);
660 660
 				$this->date_creation			= $this->db->jdate($obj->datecontrat);
@@ -663,22 +663,22 @@  discard block
 block discarded – undo
663 663
 				$this->date_cloture				= $this->db->jdate($obj->date_cloture);
664 664
 
665 665
 
666
-				$this->user_author_id			= $obj->fk_user_author;
666
+				$this->user_author_id = $obj->fk_user_author;
667 667
 
668
-				$this->commercial_signature_id	= $obj->fk_commercial_signature;
669
-				$this->commercial_suivi_id		= $obj->fk_commercial_suivi;
668
+				$this->commercial_signature_id = $obj->fk_commercial_signature;
669
+				$this->commercial_suivi_id = $obj->fk_commercial_suivi;
670 670
 
671
-				$this->note_private				= $obj->note_private;
672
-				$this->note_public				= $obj->note_public;
671
+				$this->note_private = $obj->note_private;
672
+				$this->note_public = $obj->note_public;
673 673
 				$this->modelpdf					= $obj->model_pdf;
674 674
 
675 675
 				$this->fk_projet				= $obj->fk_projet; // deprecated
676
-				$this->fk_project				= $obj->fk_projet;
676
+				$this->fk_project = $obj->fk_projet;
677 677
 
678
-				$this->socid					= $obj->fk_soc;
679
-				$this->fk_soc					= $obj->fk_soc;
678
+				$this->socid = $obj->fk_soc;
679
+				$this->fk_soc = $obj->fk_soc;
680 680
 
681
-				$this->extraparams				= (array) json_decode($obj->extraparams, true);
681
+				$this->extraparams = (array) json_decode($obj->extraparams, true);
682 682
 
683 683
 				$this->db->free($resql);
684 684
 
@@ -687,10 +687,10 @@  discard block
 block discarded – undo
687 687
 				$this->fetch_optionals();
688 688
 
689 689
 				// Lines
690
-				$result=$this->fetch_lines();
690
+				$result = $this->fetch_lines();
691 691
 				if ($result < 0)
692 692
 				{
693
-					$this->error=$this->db->lasterror();
693
+					$this->error = $this->db->lasterror();
694 694
 					return -3;
695 695
 				}
696 696
 
@@ -699,14 +699,14 @@  discard block
 block discarded – undo
699 699
 			else
700 700
 			{
701 701
 				dol_syslog(get_class($this)."::fetch Contract not found");
702
-				$this->error="Contract not found";
702
+				$this->error = "Contract not found";
703 703
 				return 0;
704 704
 			}
705 705
 		}
706 706
 		else
707 707
 		{
708 708
 			dol_syslog(get_class($this)."::fetch Error searching contract");
709
-			$this->error=$this->db->error();
709
+			$this->error = $this->db->error();
710 710
 			return -1;
711 711
 		}
712 712
 	}
@@ -721,43 +721,43 @@  discard block
 block discarded – undo
721 721
 	function fetch_lines()
722 722
 	{
723 723
         // phpcs:enable
724
-		$this->nbofserviceswait=0;
725
-		$this->nbofservicesopened=0;
726
-		$this->nbofservicesexpired=0;
727
-		$this->nbofservicesclosed=0;
724
+		$this->nbofserviceswait = 0;
725
+		$this->nbofservicesopened = 0;
726
+		$this->nbofservicesexpired = 0;
727
+		$this->nbofservicesclosed = 0;
728 728
 
729
-		$total_ttc=0;
730
-		$total_vat=0;
731
-		$total_ht=0;
729
+		$total_ttc = 0;
730
+		$total_vat = 0;
731
+		$total_ht = 0;
732 732
 
733
-		$now=dol_now();
733
+		$now = dol_now();
734 734
 
735 735
 		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
736
-		$extrafieldsline=new ExtraFields($this->db);
736
+		$extrafieldsline = new ExtraFields($this->db);
737 737
 		$line = new ContratLigne($this->db);
738
-		$extralabelsline=$extrafieldsline->fetch_name_optionals_label($line->table_element,true);
738
+		$extralabelsline = $extrafieldsline->fetch_name_optionals_label($line->table_element, true);
739 739
 
740
-		$this->lines=array();
740
+		$this->lines = array();
741 741
         $pos = 0;
742 742
 
743 743
 		// Selects contract lines related to a product
744 744
 		$sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref,";
745
-		$sql.= " d.rowid, d.fk_contrat, d.statut, d.description, d.price_ht, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
746
-		$sql.= " d.total_ht,";
747
-		$sql.= " d.total_tva,";
748
-		$sql.= " d.total_localtax1,";
749
-		$sql.= " d.total_localtax2,";
750
-		$sql.= " d.total_ttc,";
751
-		$sql.= " d.info_bits, d.fk_product,";
752
-		$sql.= " d.date_ouverture_prevue, d.date_ouverture,";
753
-		$sql.= " d.date_fin_validite, d.date_cloture,";
754
-		$sql.= " d.fk_user_author,";
755
-		$sql.= " d.fk_user_ouverture,";
756
-		$sql.= " d.fk_user_cloture,";
757
-		$sql.= " d.fk_unit";
758
-		$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
759
-		$sql.= " WHERE d.fk_contrat = ".$this->id;
760
-		$sql.= " ORDER by d.rowid ASC";
745
+		$sql .= " d.rowid, d.fk_contrat, d.statut, d.description, d.price_ht, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
746
+		$sql .= " d.total_ht,";
747
+		$sql .= " d.total_tva,";
748
+		$sql .= " d.total_localtax1,";
749
+		$sql .= " d.total_localtax2,";
750
+		$sql .= " d.total_ttc,";
751
+		$sql .= " d.info_bits, d.fk_product,";
752
+		$sql .= " d.date_ouverture_prevue, d.date_ouverture,";
753
+		$sql .= " d.date_fin_validite, d.date_cloture,";
754
+		$sql .= " d.fk_user_author,";
755
+		$sql .= " d.fk_user_ouverture,";
756
+		$sql .= " d.fk_user_cloture,";
757
+		$sql .= " d.fk_unit";
758
+		$sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
759
+		$sql .= " WHERE d.fk_contrat = ".$this->id;
760
+		$sql .= " ORDER by d.rowid ASC";
761 761
 
762 762
 		dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
763 763
 		$result = $this->db->query($sql);
@@ -771,45 +771,45 @@  discard block
 block discarded – undo
771 771
 				$objp					= $this->db->fetch_object($result);
772 772
 
773 773
 				$line					= new ContratLigne($this->db);
774
-				$line->id				= $objp->rowid;
774
+				$line->id = $objp->rowid;
775 775
 				$line->ref				= $objp->rowid;
776
-				$line->fk_contrat		= $objp->fk_contrat;
777
-				$line->desc				= $objp->description;  // Description line
776
+				$line->fk_contrat = $objp->fk_contrat;
777
+				$line->desc = $objp->description; // Description line
778 778
 				$line->qty				= $objp->qty;
779
-				$line->vat_src_code 	= $objp->vat_src_code ;
780
-				$line->tva_tx			= $objp->tva_tx;
779
+				$line->vat_src_code 	= $objp->vat_src_code;
780
+				$line->tva_tx = $objp->tva_tx;
781 781
 				$line->localtax1_tx		= $objp->localtax1_tx;
782 782
 				$line->localtax2_tx		= $objp->localtax2_tx;
783 783
 				$line->localtax1_type	= $objp->localtax1_type;
784 784
 				$line->localtax2_type	= $objp->localtax2_type;
785 785
 				$line->subprice			= $objp->subprice;
786
-				$line->statut			= $objp->statut;
786
+				$line->statut = $objp->statut;
787 787
 				$line->remise_percent	= $objp->remise_percent;
788 788
 				$line->price_ht			= $objp->price_ht;
789
-				$line->price			= $objp->price_ht;	// For backward compatibility
789
+				$line->price = $objp->price_ht; // For backward compatibility
790 790
 				$line->total_ht			= $objp->total_ht;
791 791
 				$line->total_tva		= $objp->total_tva;
792 792
 				$line->total_localtax1	= $objp->total_localtax1;
793 793
 				$line->total_localtax2	= $objp->total_localtax2;
794 794
 				$line->total_ttc		= $objp->total_ttc;
795
-				$line->fk_product		= (($objp->fk_product > 0)?$objp->fk_product:0);
795
+				$line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
796 796
 				$line->info_bits		= $objp->info_bits;
797 797
 
798
-				$line->fk_fournprice 	= $objp->fk_fournprice;
798
+				$line->fk_fournprice = $objp->fk_fournprice;
799 799
 				$marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
800
-				$line->pa_ht 			= $marginInfos[0];
800
+				$line->pa_ht = $marginInfos[0];
801 801
 
802
-				$line->fk_user_author	= $objp->fk_user_author;
803
-				$line->fk_user_ouverture= $objp->fk_user_ouverture;
802
+				$line->fk_user_author = $objp->fk_user_author;
803
+				$line->fk_user_ouverture = $objp->fk_user_ouverture;
804 804
 				$line->fk_user_cloture  = $objp->fk_user_cloture;
805
-				$line->fk_unit           = $objp->fk_unit;
805
+				$line->fk_unit = $objp->fk_unit;
806 806
 
807
-				$line->ref				= $objp->product_ref;	// deprecated
808
-				$line->product_ref		= $objp->product_ref;   // Product Ref
809
-				$line->product_desc		= $objp->product_desc;  // Product Description
807
+				$line->ref = $objp->product_ref; // deprecated
808
+				$line->product_ref = $objp->product_ref; // Product Ref
809
+				$line->product_desc		= $objp->product_desc; // Product Description
810 810
 				$line->product_label	= $objp->product_label; // Product Label
811 811
 
812
-				$line->description		= $objp->description;
812
+				$line->description = $objp->description;
813 813
 
814 814
 				$line->date_start            = $this->db->jdate($objp->date_ouverture_prevue);
815 815
 				$line->date_start_real       = $this->db->jdate($objp->date_ouverture);
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
 				// fetch optionals attributes and labels
830 830
 				$line->fetch_optionals();
831 831
 
832
-				$this->lines[$pos]			= $line;
832
+				$this->lines[$pos] = $line;
833 833
 				$this->lines_id_index_mapper[$line->id] = $pos;
834 834
 
835 835
 				//dol_syslog("1 ".$line->desc);
@@ -837,12 +837,12 @@  discard block
 block discarded – undo
837 837
 
838 838
 				if ($line->statut == ContratLigne::STATUS_INITIAL) $this->nbofserviceswait++;
839 839
 				if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++;
840
-				if ($line->statut == ContratLigne::STATUS_OPEN && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++;
840
+				if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++;
841 841
 				if ($line->statut == ContratLigne::STATUS_CLOSED) $this->nbofservicesclosed++;
842 842
 
843
-				$total_ttc+=$objp->total_ttc;   // TODO Not saved into database
844
-                $total_vat+=$objp->total_tva;
845
-                $total_ht+=$objp->total_ht;
843
+				$total_ttc += $objp->total_ttc; // TODO Not saved into database
844
+                $total_vat += $objp->total_tva;
845
+                $total_ht += $objp->total_ht;
846 846
 
847 847
 				$i++;
848 848
 				$pos++;
@@ -855,10 +855,10 @@  discard block
 block discarded – undo
855 855
 			return -3;
856 856
 		}
857 857
 
858
-		$this->nbofservices=count($this->lines);
859
-        $this->total_ttc = price2num($total_ttc);   // TODO For the moment value is false as value is not stored in database for line linked to products
860
-        $this->total_vat = price2num($total_vat);   // TODO For the moment value is false as value is not stored in database for line linked to products
861
-        $this->total_ht = price2num($total_ht);     // TODO For the moment value is false as value is not stored in database for line linked to products
858
+		$this->nbofservices = count($this->lines);
859
+        $this->total_ttc = price2num($total_ttc); // TODO For the moment value is false as value is not stored in database for line linked to products
860
+        $this->total_vat = price2num($total_vat); // TODO For the moment value is false as value is not stored in database for line linked to products
861
+        $this->total_ht = price2num($total_ht); // TODO For the moment value is false as value is not stored in database for line linked to products
862 862
 
863 863
 		return $this->lines;
864 864
 	}
@@ -871,61 +871,61 @@  discard block
 block discarded – undo
871 871
 	 */
872 872
 	function create($user)
873 873
 	{
874
-		global $conf,$langs,$mysoc;
874
+		global $conf, $langs, $mysoc;
875 875
 
876 876
 		// Check parameters
877
-		$paramsok=1;
877
+		$paramsok = 1;
878 878
 		if ($this->commercial_signature_id <= 0)
879 879
 		{
880 880
 			$langs->load("commercial");
881
-			$this->error.=$langs->trans("ErrorFieldRequired",$langs->trans("SalesRepresentativeSignature"));
882
-			$paramsok=0;
881
+			$this->error .= $langs->trans("ErrorFieldRequired", $langs->trans("SalesRepresentativeSignature"));
882
+			$paramsok = 0;
883 883
 		}
884 884
 		if ($this->commercial_suivi_id <= 0)
885 885
 		{
886 886
 			$langs->load("commercial");
887
-			$this->error.=($this->error?"<br>":'');
888
-			$this->error.=$langs->trans("ErrorFieldRequired",$langs->trans("SalesRepresentativeFollowUp"));
889
-			$paramsok=0;
887
+			$this->error .= ($this->error ? "<br>" : '');
888
+			$this->error .= $langs->trans("ErrorFieldRequired", $langs->trans("SalesRepresentativeFollowUp"));
889
+			$paramsok = 0;
890 890
 		}
891
-		if (! $paramsok) return -1;
891
+		if (!$paramsok) return -1;
892 892
 
893 893
 
894 894
 		$this->db->begin();
895 895
 
896
-		$now=dol_now();
896
+		$now = dol_now();
897 897
 
898 898
 		// Insert contract
899 899
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
900
-		$sql.= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
901
-		$sql.= " ref, entity, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
902
-		$sql.= " VALUES ('".$this->db->idate($now)."',".$this->socid.",".$user->id;
903
-		$sql.= ", ".(dol_strlen($this->date_contrat)!=0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
904
-		$sql.= ",".($this->commercial_signature_id>0?$this->commercial_signature_id:"NULL");
905
-		$sql.= ",".($this->commercial_suivi_id>0?$this->commercial_suivi_id:"NULL");
906
-		$sql.= ",".($this->fk_project>0?$this->fk_project:"NULL");
907
-		$sql.= ", ".(dol_strlen($this->ref)<=0 ? "null" : "'".$this->db->escape($this->ref)."'");
908
-		$sql.= ", ".$conf->entity;
909
-		$sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL");
910
-		$sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL");
911
-		$sql.= ", ".(!empty($this->ref_customer)?("'".$this->db->escape($this->ref_customer)."'"):"NULL");
912
-		$sql.= ", ".(!empty($this->ref_supplier)?("'".$this->db->escape($this->ref_supplier)."'"):"NULL");
913
-		$sql.= ", ".(!empty($this->ref_ext)?("'".$this->db->escape($this->ref_ext)."'"):"NULL");
914
-		$sql.= ")";
915
-		$resql=$this->db->query($sql);
900
+		$sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
901
+		$sql .= " ref, entity, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
902
+		$sql .= " VALUES ('".$this->db->idate($now)."',".$this->socid.",".$user->id;
903
+		$sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
904
+		$sql .= ",".($this->commercial_signature_id > 0 ? $this->commercial_signature_id : "NULL");
905
+		$sql .= ",".($this->commercial_suivi_id > 0 ? $this->commercial_suivi_id : "NULL");
906
+		$sql .= ",".($this->fk_project > 0 ? $this->fk_project : "NULL");
907
+		$sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
908
+		$sql .= ", ".$conf->entity;
909
+		$sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
910
+		$sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
911
+		$sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
912
+		$sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
913
+		$sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
914
+		$sql .= ")";
915
+		$resql = $this->db->query($sql);
916 916
 		if ($resql)
917 917
 		{
918
-			$error=0;
918
+			$error = 0;
919 919
 
920 920
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
921 921
 
922 922
 			// Load object modContract
923
-			$module=(! empty($conf->global->CONTRACT_ADDON)?$conf->global->CONTRACT_ADDON:'mod_contract_serpis');
923
+			$module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
924 924
 			if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php')
925 925
 			{
926
-				$module = substr($module, 0, dol_strlen($module)-4);
926
+				$module = substr($module, 0, dol_strlen($module) - 4);
927 927
 			}
928
-			$result=dol_include_once('/core/modules/contract/'.$module.'.php');
928
+			$result = dol_include_once('/core/modules/contract/'.$module.'.php');
929 929
 			if ($result > 0)
930 930
 			{
931 931
 				$modCodeContract = new $module();
@@ -937,18 +937,18 @@  discard block
 block discarded – undo
937 937
 					{
938 938
 						if ($this->id)
939 939
 						{
940
-							$this->ref="(PROV".$this->id.")";
940
+							$this->ref = "(PROV".$this->id.")";
941 941
 						}
942 942
 					}
943 943
 				} else {
944 944
 					$error++;
945
-					$this->error='Failed to get PROV number';
945
+					$this->error = 'Failed to get PROV number';
946 946
 				}
947 947
 			}
948 948
 
949
-			if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))
949
+			if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))
950 950
 			{
951
-				$result=$this->insertExtraFields();
951
+				$result = $this->insertExtraFields();
952 952
 				if ($result < 0)
953 953
 				{
954 954
 					$error++;
@@ -956,39 +956,39 @@  discard block
 block discarded – undo
956 956
 			}
957 957
 
958 958
 			// Insert business contacts ('SALESREPSIGN','contrat')
959
-			if (! $error)
959
+			if (!$error)
960 960
 			{
961
-    			$result=$this->add_contact($this->commercial_signature_id,'SALESREPSIGN','internal');
961
+    			$result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
962 962
     			if ($result < 0) $error++;
963 963
 			}
964 964
 
965 965
 			// Insert business contacts ('SALESREPFOLL','contrat')
966
-			if (! $error)
966
+			if (!$error)
967 967
 			{
968
-                $result=$this->add_contact($this->commercial_suivi_id,'SALESREPFOLL','internal');
968
+                $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
969 969
 			    if ($result < 0) $error++;
970 970
 			}
971 971
 
972
-			if (! $error)
972
+			if (!$error)
973 973
 			{
974
-				if (! empty($this->linkedObjectsIds) && empty($this->linked_objects))	// To use new linkedObjectsIds instead of old linked_objects
974
+				if (!empty($this->linkedObjectsIds) && empty($this->linked_objects))	// To use new linkedObjectsIds instead of old linked_objects
975 975
 				{
976
-					$this->linked_objects = $this->linkedObjectsIds;	// TODO Replace linked_objects with linkedObjectsIds
976
+					$this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
977 977
 				}
978 978
 
979 979
 				// Add object linked
980
-    			if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
980
+    			if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects))
981 981
     			{
982
-    			    foreach($this->linked_objects as $origin => $tmp_origin_id)
982
+    			    foreach ($this->linked_objects as $origin => $tmp_origin_id)
983 983
     			    {
984 984
     			        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, ...))
985 985
     			        {
986
-    			            foreach($tmp_origin_id as $origin_id)
986
+    			            foreach ($tmp_origin_id as $origin_id)
987 987
     			            {
988 988
     			                $ret = $this->add_object_linked($origin, $origin_id);
989
-    			                if (! $ret)
989
+    			                if (!$ret)
990 990
     			                {
991
-    			                    $this->error=$this->db->lasterror();
991
+    			                    $this->error = $this->db->lasterror();
992 992
     			                    $error++;
993 993
     			                }
994 994
     			            }
@@ -997,22 +997,22 @@  discard block
 block discarded – undo
997 997
     			        {
998 998
     			            $origin_id = $tmp_origin_id;
999 999
     			            $ret = $this->add_object_linked($origin, $origin_id);
1000
-    			            if (! $ret)
1000
+    			            if (!$ret)
1001 1001
     			            {
1002
-    			                $this->error=$this->db->lasterror();
1002
+    			                $this->error = $this->db->lasterror();
1003 1003
     			                $error++;
1004 1004
     			            }
1005 1005
     			        }
1006 1006
     			    }
1007 1007
     			}
1008 1008
 
1009
-    			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
1009
+    			if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id))   // Get contact from origin object
1010 1010
     			{
1011 1011
     			    $originforcontact = $this->origin;
1012 1012
     			    $originidforcontact = $this->origin_id;
1013 1013
     			    if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
1014 1014
     			    {
1015
-    			        require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
1015
+    			        require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1016 1016
     			        $exp = new Expedition($db);
1017 1017
     			        $exp->fetch($this->origin_id);
1018 1018
     			        $exp->fetchObjectLinked();
@@ -1028,31 +1028,31 @@  discard block
 block discarded – undo
1028 1028
     			    }
1029 1029
 
1030 1030
     			    $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";
1031
-    			    $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
1031
+    			    $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'";
1032 1032
 
1033 1033
     			    $resqlcontact = $this->db->query($sqlcontact);
1034 1034
     			    if ($resqlcontact)
1035 1035
     			    {
1036
-    			        while($objcontact = $this->db->fetch_object($resqlcontact))
1036
+    			        while ($objcontact = $this->db->fetch_object($resqlcontact))
1037 1037
     			        {
1038
-    			            if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) continue;    // ignore this, already forced previously
1038
+    			            if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) continue; // ignore this, already forced previously
1039 1039
 
1040 1040
     			            //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1041
-    			            $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
1041
+    			            $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
1042 1042
     			        }
1043 1043
     			    }
1044 1044
     			    else dol_print_error($resqlcontact);
1045 1045
     			}
1046 1046
 			}
1047 1047
 
1048
-			if (! $error)
1048
+			if (!$error)
1049 1049
 			{
1050 1050
                 // Call trigger
1051
-                $result=$this->call_trigger('CONTRACT_CREATE',$user);
1051
+                $result = $this->call_trigger('CONTRACT_CREATE', $user);
1052 1052
                 if ($result < 0) { $error++; }
1053 1053
                 // End call triggers
1054 1054
 
1055
-				if (! $error)
1055
+				if (!$error)
1056 1056
 				{
1057 1057
 					$this->db->commit();
1058 1058
 					return $this->id;
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
 			}
1067 1067
 			else
1068 1068
 			{
1069
-				$this->error="Failed to add contract";
1069
+				$this->error = "Failed to add contract";
1070 1070
 				dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1071 1071
 				$this->db->rollback();
1072 1072
 				return -2;
@@ -1074,7 +1074,7 @@  discard block
 block discarded – undo
1074 1074
 		}
1075 1075
 		else
1076 1076
 		{
1077
-			$this->error=$langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
1077
+			$this->error = $langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
1078 1078
 
1079 1079
 			$this->db->rollback();
1080 1080
 			return -1;
@@ -1091,18 +1091,18 @@  discard block
 block discarded – undo
1091 1091
 	function delete($user)
1092 1092
 	{
1093 1093
 		global $conf, $langs;
1094
-		require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1094
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1095 1095
 
1096
-		$error=0;
1096
+		$error = 0;
1097 1097
 
1098 1098
 		$this->db->begin();
1099 1099
 
1100 1100
 	    // Call trigger
1101
-	    $result=$this->call_trigger('CONTRACT_DELETE',$user);
1101
+	    $result = $this->call_trigger('CONTRACT_DELETE', $user);
1102 1102
 	    if ($result < 0) { $error++; }
1103 1103
 	    // End call triggers
1104 1104
 
1105
-		if (! $error)
1105
+		if (!$error)
1106 1106
 		{
1107 1107
 			// Delete linked contacts
1108 1108
 			$res = $this->delete_linked_contact();
@@ -1113,14 +1113,14 @@  discard block
 block discarded – undo
1113 1113
 			}
1114 1114
 		}
1115 1115
 
1116
-		if (! $error)
1116
+		if (!$error)
1117 1117
 		{
1118 1118
 			// Delete linked object
1119 1119
 			$res = $this->deleteObjectLinked();
1120 1120
 			if ($res < 0) $error++;
1121 1121
 		}
1122 1122
 
1123
-		if (! $error)
1123
+		if (!$error)
1124 1124
 		{
1125 1125
 			// Delete contratdet_log
1126 1126
 			/*
@@ -1129,73 +1129,73 @@  discard block
 block discarded – undo
1129 1129
 			$sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".$this->id;
1130 1130
 			*/
1131 1131
 			$sql = "SELECT cdl.rowid as cdlrowid ";
1132
-			$sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1133
-			$sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".$this->id;
1132
+			$sql .= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
1133
+			$sql .= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".$this->id;
1134 1134
 
1135 1135
 			dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1136
-			$resql=$this->db->query($sql);
1137
-			if (! $resql)
1136
+			$resql = $this->db->query($sql);
1137
+			if (!$resql)
1138 1138
 			{
1139
-				$this->error=$this->db->error();
1139
+				$this->error = $this->db->error();
1140 1140
 				$error++;
1141 1141
 			}
1142
-			$numressql=$this->db->num_rows($resql);
1143
-			if (! $error && $numressql )
1142
+			$numressql = $this->db->num_rows($resql);
1143
+			if (!$error && $numressql)
1144 1144
 			{
1145
-				$tab_resql=array();
1146
-				for($i=0;$i<$numressql;$i++)
1145
+				$tab_resql = array();
1146
+				for ($i = 0; $i < $numressql; $i++)
1147 1147
 				{
1148
-					$objresql=$this->db->fetch_object($resql);
1149
-					$tab_resql[]= $objresql->cdlrowid;
1148
+					$objresql = $this->db->fetch_object($resql);
1149
+					$tab_resql[] = $objresql->cdlrowid;
1150 1150
 				}
1151 1151
 				$this->db->free($resql);
1152 1152
 
1153
-				$sql= "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log ";
1154
-				$sql.= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".implode(",",$tab_resql).")";
1153
+				$sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log ";
1154
+				$sql .= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".implode(",", $tab_resql).")";
1155 1155
 
1156 1156
 				dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
1157
-				$resql=$this->db->query($sql);
1158
-				if (! $resql)
1157
+				$resql = $this->db->query($sql);
1158
+				if (!$resql)
1159 1159
 				{
1160
-					$this->error=$this->db->error();
1160
+					$this->error = $this->db->error();
1161 1161
 					$error++;
1162 1162
 				}
1163 1163
 			}
1164 1164
 		}
1165 1165
 
1166
-		if (! $error)
1166
+		if (!$error)
1167 1167
 		{
1168 1168
 			// Delete contratdet
1169 1169
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1170
-			$sql.= " WHERE fk_contrat=".$this->id;
1170
+			$sql .= " WHERE fk_contrat=".$this->id;
1171 1171
 
1172 1172
 			dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
1173
-			$resql=$this->db->query($sql);
1174
-			if (! $resql)
1173
+			$resql = $this->db->query($sql);
1174
+			if (!$resql)
1175 1175
 			{
1176
-				$this->error=$this->db->error();
1176
+				$this->error = $this->db->error();
1177 1177
 				$error++;
1178 1178
 			}
1179 1179
 		}
1180 1180
 
1181
-		if (! $error)
1181
+		if (!$error)
1182 1182
 		{
1183 1183
 			// Delete contrat
1184 1184
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
1185
-			$sql.= " WHERE rowid=".$this->id;
1185
+			$sql .= " WHERE rowid=".$this->id;
1186 1186
 
1187 1187
 			dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
1188
-			$resql=$this->db->query($sql);
1189
-			if (! $resql)
1188
+			$resql = $this->db->query($sql);
1189
+			if (!$resql)
1190 1190
 			{
1191
-				$this->error=$this->db->error();
1191
+				$this->error = $this->db->error();
1192 1192
 				$error++;
1193 1193
 			}
1194 1194
 		}
1195 1195
 
1196 1196
 		// Removed extrafields
1197
-		if (! $error) {
1198
-			$result=$this->deleteExtraFields();
1197
+		if (!$error) {
1198
+			$result = $this->deleteExtraFields();
1199 1199
 			if ($result < 0)
1200 1200
 			{
1201 1201
 				$error++;
@@ -1203,33 +1203,33 @@  discard block
 block discarded – undo
1203 1203
 			}
1204 1204
 		}
1205 1205
 
1206
-		if (! $error)
1206
+		if (!$error)
1207 1207
 		{
1208 1208
 			// We remove directory
1209 1209
 			$ref = dol_sanitizeFileName($this->ref);
1210 1210
 			if ($conf->contrat->dir_output)
1211 1211
 			{
1212
-				$dir = $conf->contrat->dir_output . "/" . $ref;
1212
+				$dir = $conf->contrat->dir_output."/".$ref;
1213 1213
 				if (file_exists($dir))
1214 1214
 				{
1215
-					$res=@dol_delete_dir_recursive($dir);
1216
-					if (! $res)
1215
+					$res = @dol_delete_dir_recursive($dir);
1216
+					if (!$res)
1217 1217
 					{
1218
-						$this->error='ErrorFailToDeleteDir';
1218
+						$this->error = 'ErrorFailToDeleteDir';
1219 1219
 						$error++;
1220 1220
 					}
1221 1221
 				}
1222 1222
 			}
1223 1223
 		}
1224 1224
 
1225
-		if (! $error)
1225
+		if (!$error)
1226 1226
 		{
1227 1227
 			$this->db->commit();
1228 1228
 			return 1;
1229 1229
 		}
1230 1230
 		else
1231 1231
 		{
1232
-			$this->error=$this->db->lasterror();
1232
+			$this->error = $this->db->lasterror();
1233 1233
 			$this->db->rollback();
1234 1234
 			return -1;
1235 1235
 		}
@@ -1242,10 +1242,10 @@  discard block
 block discarded – undo
1242 1242
 	 *  @param  int		$notrigger	 0=launch triggers after, 1=disable triggers
1243 1243
 	 *  @return int     		   	 <0 if KO, >0 if OK
1244 1244
 	 */
1245
-	function update($user, $notrigger=0)
1245
+	function update($user, $notrigger = 0)
1246 1246
 	{
1247 1247
 		global $conf, $langs;
1248
-		$error=0;
1248
+		$error = 0;
1249 1249
 
1250 1250
 		// Clean parameters
1251 1251
 		if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) $this->fk_commercial_signature = $this->commercial_signature_id;
@@ -1253,20 +1253,20 @@  discard block
 block discarded – undo
1253 1253
 		if (empty($this->fk_soc) && $this->socid > 0) $this->fk_soc = $this->socid;
1254 1254
 		if (empty($this->fk_project) && $this->projet > 0) $this->fk_project = $this->projet;
1255 1255
 
1256
-		if (isset($this->ref)) $this->ref=trim($this->ref);
1257
-		if (isset($this->ref_customer)) $this->ref_customer=trim($this->ref_customer);
1258
-		if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
1259
-		if (isset($this->ref_ext)) $this->ref_ext=trim($this->ref_ext);
1260
-		if (isset($this->entity)) $this->entity=trim($this->entity);
1261
-		if (isset($this->statut)) $this->statut=(int) $this->statut;
1262
-		if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
1263
-		if (isset($this->fk_commercial_signature)) $this->fk_commercial_signature=trim($this->fk_commercial_signature);
1264
-		if (isset($this->fk_commercial_suivi)) $this->fk_commercial_suivi=trim($this->fk_commercial_suivi);
1265
-		if (isset($this->fk_user_mise_en_service)) $this->fk_user_mise_en_service=trim($this->fk_user_mise_en_service);
1266
-		if (isset($this->fk_user_cloture)) $this->fk_user_cloture=trim($this->fk_user_cloture);
1267
-		if (isset($this->note_private)) $this->note_private=trim($this->note_private);
1268
-		if (isset($this->note_public)) $this->note_public=trim($this->note_public);
1269
-		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
1256
+		if (isset($this->ref)) $this->ref = trim($this->ref);
1257
+		if (isset($this->ref_customer)) $this->ref_customer = trim($this->ref_customer);
1258
+		if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier);
1259
+		if (isset($this->ref_ext)) $this->ref_ext = trim($this->ref_ext);
1260
+		if (isset($this->entity)) $this->entity = trim($this->entity);
1261
+		if (isset($this->statut)) $this->statut = (int) $this->statut;
1262
+		if (isset($this->fk_soc)) $this->fk_soc = trim($this->fk_soc);
1263
+		if (isset($this->fk_commercial_signature)) $this->fk_commercial_signature = trim($this->fk_commercial_signature);
1264
+		if (isset($this->fk_commercial_suivi)) $this->fk_commercial_suivi = trim($this->fk_commercial_suivi);
1265
+		if (isset($this->fk_user_mise_en_service)) $this->fk_user_mise_en_service = trim($this->fk_user_mise_en_service);
1266
+		if (isset($this->fk_user_cloture)) $this->fk_user_cloture = trim($this->fk_user_cloture);
1267
+		if (isset($this->note_private)) $this->note_private = trim($this->note_private);
1268
+		if (isset($this->note_public)) $this->note_public = trim($this->note_public);
1269
+		if (isset($this->import_key)) $this->import_key = trim($this->import_key);
1270 1270
 		//if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
1271 1271
 
1272 1272
 		// Check parameters
@@ -1274,46 +1274,46 @@  discard block
 block discarded – undo
1274 1274
 
1275 1275
 		// Update request
1276 1276
     	$sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
1277
-		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
1278
-		$sql.= " ref_customer=".(isset($this->ref_customer)?"'".$this->db->escape($this->ref_customer)."'":"null").",";
1279
-		$sql.= " ref_supplier=".(isset($this->ref_supplier)?"'".$this->db->escape($this->ref_supplier)."'":"null").",";
1280
-		$sql.= " ref_ext=".(isset($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null").",";
1281
-		$sql.= " entity=".$conf->entity.",";
1282
-		$sql.= " date_contrat=".(dol_strlen($this->date_contrat)!=0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1283
-		$sql.= " statut=".(isset($this->statut)?$this->statut:"null").",";
1284
-		$sql.= " mise_en_service=".(dol_strlen($this->mise_en_service)!=0 ? "'".$this->db->idate($this->mise_en_service)."'" : 'null').",";
1285
-		$sql.= " fin_validite=".(dol_strlen($this->fin_validite)!=0 ? "'".$this->db->idate($this->fin_validite)."'" : 'null').",";
1286
-		$sql.= " date_cloture=".(dol_strlen($this->date_cloture)!=0 ? "'".$this->db->idate($this->date_cloture)."'" : 'null').",";
1287
-		$sql.= " fk_soc=".($this->fk_soc > 0 ? $this->fk_soc:"null").",";
1288
-		$sql.= " fk_projet=".($this->fk_project > 0 ? $this->fk_project:"null").",";
1289
-		$sql.= " fk_commercial_signature=".(isset($this->fk_commercial_signature)?$this->fk_commercial_signature:"null").",";
1290
-		$sql.= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi)?$this->fk_commercial_suivi:"null").",";
1291
-		$sql.= " fk_user_mise_en_service=".(isset($this->fk_user_mise_en_service)?$this->fk_user_mise_en_service:"null").",";
1292
-		$sql.= " fk_user_cloture=".(isset($this->fk_user_cloture)?$this->fk_user_cloture:"null").",";
1293
-		$sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
1294
-		$sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
1295
-		$sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
1277
+		$sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
1278
+		$sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
1279
+		$sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
1280
+		$sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
1281
+		$sql .= " entity=".$conf->entity.",";
1282
+		$sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
1283
+		$sql .= " statut=".(isset($this->statut) ? $this->statut : "null").",";
1284
+		$sql .= " mise_en_service=".(dol_strlen($this->mise_en_service) != 0 ? "'".$this->db->idate($this->mise_en_service)."'" : 'null').",";
1285
+		$sql .= " fin_validite=".(dol_strlen($this->fin_validite) != 0 ? "'".$this->db->idate($this->fin_validite)."'" : 'null').",";
1286
+		$sql .= " date_cloture=".(dol_strlen($this->date_cloture) != 0 ? "'".$this->db->idate($this->date_cloture)."'" : 'null').",";
1287
+		$sql .= " fk_soc=".($this->fk_soc > 0 ? $this->fk_soc : "null").",";
1288
+		$sql .= " fk_projet=".($this->fk_project > 0 ? $this->fk_project : "null").",";
1289
+		$sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? $this->fk_commercial_signature : "null").",";
1290
+		$sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? $this->fk_commercial_suivi : "null").",";
1291
+		$sql .= " fk_user_mise_en_service=".(isset($this->fk_user_mise_en_service) ? $this->fk_user_mise_en_service : "null").",";
1292
+		$sql .= " fk_user_cloture=".(isset($this->fk_user_cloture) ? $this->fk_user_cloture : "null").",";
1293
+		$sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
1294
+		$sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
1295
+		$sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
1296 1296
 		//$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null")."";
1297
-		$sql.= " WHERE rowid=".$this->id;
1297
+		$sql .= " WHERE rowid=".$this->id;
1298 1298
 
1299 1299
 		$this->db->begin();
1300 1300
 
1301 1301
 		$resql = $this->db->query($sql);
1302
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
1302
+		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
1303 1303
 
1304
-		if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
1304
+		if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0)
1305 1305
 		{
1306
-			$result=$this->insertExtraFields();
1306
+			$result = $this->insertExtraFields();
1307 1307
 			if ($result < 0)
1308 1308
 			{
1309 1309
 				$error++;
1310 1310
 			}
1311 1311
 		}
1312 1312
 
1313
-		if (! $error && ! $notrigger)
1313
+		if (!$error && !$notrigger)
1314 1314
 		{
1315 1315
 			// Call triggers
1316
-			$result=$this->call_trigger('CONTRACT_MODIFY',$user);
1316
+			$result = $this->call_trigger('CONTRACT_MODIFY', $user);
1317 1317
 			if ($result < 0) { $error++; }
1318 1318
 			// End call triggers
1319 1319
 		}
@@ -1321,13 +1321,13 @@  discard block
 block discarded – undo
1321 1321
 		// Commit or rollback
1322 1322
 		if ($error)
1323 1323
 		{
1324
-			foreach($this->errors as $errmsg)
1324
+			foreach ($this->errors as $errmsg)
1325 1325
 			{
1326 1326
 				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1327
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
1327
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1328 1328
 			}
1329 1329
 			$this->db->rollback();
1330
-			return -1*$error;
1330
+			return -1 * $error;
1331 1331
 		}
1332 1332
 		else
1333 1333
 		{
@@ -1360,17 +1360,17 @@  discard block
 block discarded – undo
1360 1360
 	 * 	@param 	string		$rang 				Position
1361 1361
 	 *  @return int             				<0 if KO, >0 if OK
1362 1362
 	 */
1363
-	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null, $rang=0)
1363
+	function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = 0, $fk_unit = null, $rang = 0)
1364 1364
 	{
1365 1365
 		global $user, $langs, $conf, $mysoc;
1366
-		$error=0;
1366
+		$error = 0;
1367 1367
 
1368 1368
 		dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang");
1369 1369
 
1370 1370
 		// Check parameters
1371 1371
 		if ($fk_product <= 0 && empty($desc))
1372 1372
 		{
1373
-			$this->error="ErrorDescRequiredForFreeProductLines";
1373
+			$this->error = "ErrorDescRequiredForFreeProductLines";
1374 1374
 			return -1;
1375 1375
 		}
1376 1376
 
@@ -1379,44 +1379,44 @@  discard block
 block discarded – undo
1379 1379
 			$this->db->begin();
1380 1380
 
1381 1381
 			// Clean parameters
1382
-			$pu_ht=price2num($pu_ht);
1383
-			$pu_ttc=price2num($pu_ttc);
1384
-			$pa_ht=price2num($pa_ht);
1382
+			$pu_ht = price2num($pu_ht);
1383
+			$pu_ttc = price2num($pu_ttc);
1384
+			$pa_ht = price2num($pa_ht);
1385 1385
 			if (!preg_match('/\((.*)\)/', $txtva)) {
1386
-				$txtva = price2num($txtva);               // $txtva can have format '5.0(XXX)' or '5'
1387
-			}
1388
-			$txlocaltax1=price2num($txlocaltax1);
1389
-			$txlocaltax2=price2num($txlocaltax2);
1390
-			$remise_percent=price2num($remise_percent);
1391
-			$qty=price2num($qty);
1392
-			if (empty($qty)) $qty=1;
1393
-			if (empty($info_bits)) $info_bits=0;
1394
-			if (empty($pu_ht) || ! is_numeric($pu_ht))  $pu_ht=0;
1395
-			if (empty($pu_ttc)) $pu_ttc=0;
1396
-			if (empty($txtva) || ! is_numeric($txtva)) $txtva=0;
1397
-			if (empty($txlocaltax1) || ! is_numeric($txlocaltax1)) $txlocaltax1=0;
1398
-            if (empty($txlocaltax2) || ! is_numeric($txlocaltax2)) $txlocaltax2=0;
1399
-
1400
-			if ($price_base_type=='HT')
1386
+				$txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
1387
+			}
1388
+			$txlocaltax1 = price2num($txlocaltax1);
1389
+			$txlocaltax2 = price2num($txlocaltax2);
1390
+			$remise_percent = price2num($remise_percent);
1391
+			$qty = price2num($qty);
1392
+			if (empty($qty)) $qty = 1;
1393
+			if (empty($info_bits)) $info_bits = 0;
1394
+			if (empty($pu_ht) || !is_numeric($pu_ht))  $pu_ht = 0;
1395
+			if (empty($pu_ttc)) $pu_ttc = 0;
1396
+			if (empty($txtva) || !is_numeric($txtva)) $txtva = 0;
1397
+			if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) $txlocaltax1 = 0;
1398
+            if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) $txlocaltax2 = 0;
1399
+
1400
+			if ($price_base_type == 'HT')
1401 1401
 			{
1402
-				$pu=$pu_ht;
1402
+				$pu = $pu_ht;
1403 1403
 			}
1404 1404
 			else
1405 1405
 			{
1406
-				$pu=$pu_ttc;
1406
+				$pu = $pu_ttc;
1407 1407
 			}
1408 1408
 
1409 1409
 			// Check parameters
1410
-			if (empty($remise_percent)) $remise_percent=0;
1410
+			if (empty($remise_percent)) $remise_percent = 0;
1411 1411
 
1412
-			$localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->societe, $mysoc);
1412
+			$localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->societe, $mysoc);
1413 1413
 
1414 1414
 			// Clean vat code
1415
-			$vat_src_code='';
1415
+			$vat_src_code = '';
1416 1416
 			if (preg_match('/\((.*)\)/', $txtva, $reg))
1417 1417
 			{
1418 1418
 				$vat_src_code = $reg[1];
1419
-				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
1419
+				$txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
1420 1420
 			}
1421 1421
 
1422 1422
 			// Calcul du total TTC et de la TVA pour la ligne a partir de
@@ -1424,15 +1424,15 @@  discard block
 block discarded – undo
1424 1424
 			// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1425 1425
 			// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1426 1426
 
1427
-			$tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1,$mysoc, $localtaxes_type);
1427
+			$tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1428 1428
 			$total_ht  = $tabprice[0];
1429 1429
 			$total_tva = $tabprice[1];
1430 1430
 			$total_ttc = $tabprice[2];
1431
-			$total_localtax1= $tabprice[9];
1432
-			$total_localtax2= $tabprice[10];
1431
+			$total_localtax1 = $tabprice[9];
1432
+			$total_localtax2 = $tabprice[10];
1433 1433
 
1434
-			$localtax1_type=$localtaxes_type[0];
1435
-			$localtax2_type=$localtaxes_type[2];
1434
+			$localtax1_type = $localtaxes_type[0];
1435
+			$localtax2_type = $localtaxes_type[2];
1436 1436
 
1437 1437
 			// TODO A virer
1438 1438
 			// Anciens indicateurs: $price, $remise (a ne plus utiliser)
@@ -1444,7 +1444,7 @@  discard block
 block discarded – undo
1444 1444
 				$price = $pu_ht - $remise;
1445 1445
 			}
1446 1446
 
1447
-		    if (empty($pa_ht)) $pa_ht=0;
1447
+		    if (empty($pa_ht)) $pa_ht = 0;
1448 1448
 
1449 1449
 
1450 1450
 			// if buy price not defined, define buyprice as configured in margin admin
@@ -1462,59 +1462,59 @@  discard block
 block discarded – undo
1462 1462
 
1463 1463
 			// Insertion dans la base
1464 1464
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
1465
-			$sql.= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1466
-			$sql.= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1467
-			$sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1468
-			$sql.= " info_bits,";
1469
-			$sql.= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
1470
-			if ($date_start > 0) { $sql.= ",date_ouverture_prevue"; }
1471
-			if ($date_end > 0)   { $sql.= ",date_fin_validite"; }
1472
-			$sql.= ", fk_unit";
1473
-			$sql.= ") VALUES (";
1474
-			$sql.= $this->id.", '', '" . $this->db->escape($desc) . "',";
1475
-			$sql.= ($fk_product>0 ? $fk_product : "null").",";
1476
-			$sql.= " ".$qty.",";
1477
-			$sql.= " ".$txtva.",";
1478
-			$sql.= " ".($vat_src_code?"'".$vat_src_code."'":"null").",";
1479
-			$sql.= " ".$txlocaltax1.",";
1480
-			$sql.= " ".$txlocaltax2.",";
1481
-			$sql.= " '".$localtax1_type."',";
1482
-			$sql.= " '".$localtax2_type."',";
1483
-			$sql.= " ".price2num($remise_percent).",";
1484
-			$sql.= " ".price2num($pu_ht).",";
1485
-			$sql.= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1486
-			$sql.= " '".$info_bits."',";
1487
-			$sql.= " ".price2num($price).",".price2num($remise).",";
1488
-			if (isset($fk_fournprice)) $sql.= ' '.$fk_fournprice.',';
1489
-			else $sql.= ' null,';
1490
-			if (isset($pa_ht)) $sql.= ' '.price2num($pa_ht);
1491
-			else $sql.= ' null';
1492
-			if ($date_start > 0) { $sql.= ",'".$this->db->idate($date_start)."'"; }
1493
-			if ($date_end > 0) { $sql.= ",'".$this->db->idate($date_end)."'"; }
1494
-			$sql.= ", ".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
1495
-			$sql.= ")";
1496
-
1497
-			$resql=$this->db->query($sql);
1465
+			$sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
1466
+			$sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
1467
+			$sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
1468
+			$sql .= " info_bits,";
1469
+			$sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
1470
+			if ($date_start > 0) { $sql .= ",date_ouverture_prevue"; }
1471
+			if ($date_end > 0) { $sql .= ",date_fin_validite"; }
1472
+			$sql .= ", fk_unit";
1473
+			$sql .= ") VALUES (";
1474
+			$sql .= $this->id.", '', '".$this->db->escape($desc)."',";
1475
+			$sql .= ($fk_product > 0 ? $fk_product : "null").",";
1476
+			$sql .= " ".$qty.",";
1477
+			$sql .= " ".$txtva.",";
1478
+			$sql .= " ".($vat_src_code ? "'".$vat_src_code."'" : "null").",";
1479
+			$sql .= " ".$txlocaltax1.",";
1480
+			$sql .= " ".$txlocaltax2.",";
1481
+			$sql .= " '".$localtax1_type."',";
1482
+			$sql .= " '".$localtax2_type."',";
1483
+			$sql .= " ".price2num($remise_percent).",";
1484
+			$sql .= " ".price2num($pu_ht).",";
1485
+			$sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1486
+			$sql .= " '".$info_bits."',";
1487
+			$sql .= " ".price2num($price).",".price2num($remise).",";
1488
+			if (isset($fk_fournprice)) $sql .= ' '.$fk_fournprice.',';
1489
+			else $sql .= ' null,';
1490
+			if (isset($pa_ht)) $sql .= ' '.price2num($pa_ht);
1491
+			else $sql .= ' null';
1492
+			if ($date_start > 0) { $sql .= ",'".$this->db->idate($date_start)."'"; }
1493
+			if ($date_end > 0) { $sql .= ",'".$this->db->idate($date_end)."'"; }
1494
+			$sql .= ", ".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
1495
+			$sql .= ")";
1496
+
1497
+			$resql = $this->db->query($sql);
1498 1498
 			if ($resql)
1499 1499
 			{
1500 1500
 				$contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1501 1501
 
1502
-				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
1502
+				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used
1503 1503
 				{
1504 1504
 					$contractline = new ContratLigne($this->db);
1505
-					$contractline->array_options=$array_options;
1506
-					$contractline->id=$contractlineid;
1507
-					$result=$contractline->insertExtraFields();
1505
+					$contractline->array_options = $array_options;
1506
+					$contractline->id = $contractlineid;
1507
+					$result = $contractline->insertExtraFields();
1508 1508
 					if ($result < 0)
1509 1509
 					{
1510
-						$this->error[]=$contractline->error;
1510
+						$this->error[] = $contractline->error;
1511 1511
 						$error++;
1512 1512
 					}
1513 1513
 				}
1514 1514
 
1515 1515
 				if (empty($error)) {
1516 1516
 				    // Call trigger
1517
-				    $result=$this->call_trigger('LINECONTRACT_INSERT',$user);
1517
+				    $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
1518 1518
 				    if ($result < 0)
1519 1519
 				    {
1520 1520
 				    	$error++;
@@ -1536,7 +1536,7 @@  discard block
 block discarded – undo
1536 1536
 			else
1537 1537
 			{
1538 1538
 				$this->db->rollback();
1539
-				$this->error=$this->db->error()." sql=".$sql;
1539
+				$this->error = $this->db->error()." sql=".$sql;
1540 1540
 				return -1;
1541 1541
 			}
1542 1542
 		}
@@ -1570,22 +1570,22 @@  discard block
 block discarded – undo
1570 1570
 	 * 	@param 	string		$fk_unit 			Code of the unit to use. Null to use the default one
1571 1571
 	 *  @return int              				< 0 si erreur, > 0 si ok
1572 1572
 	 */
1573
-	function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx=0.0, $localtax2tx=0.0, $date_debut_reel='', $date_fin_reel='', $price_base_type='HT', $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null)
1573
+	function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx = 0.0, $localtax2tx = 0.0, $date_debut_reel = '', $date_fin_reel = '', $price_base_type = 'HT', $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = 0, $fk_unit = null)
1574 1574
 	{
1575 1575
 		global $user, $conf, $langs, $mysoc;
1576 1576
 
1577
-		$error=0;
1577
+		$error = 0;
1578 1578
 
1579 1579
 		// Clean parameters
1580
-		$qty=trim($qty);
1581
-		$desc=trim($desc);
1582
-		$desc=trim($desc);
1580
+		$qty = trim($qty);
1581
+		$desc = trim($desc);
1582
+		$desc = trim($desc);
1583 1583
 		$price = price2num($pu);
1584 1584
 		$tvatx = price2num($tvatx);
1585 1585
 		$localtax1tx = price2num($localtax1tx);
1586 1586
 		$localtax2tx = price2num($localtax2tx);
1587
-		$pa_ht=price2num($pa_ht);
1588
-		if (empty($fk_fournprice)) $fk_fournprice=0;
1587
+		$pa_ht = price2num($pa_ht);
1588
+		if (empty($fk_fournprice)) $fk_fournprice = 0;
1589 1589
 
1590 1590
 		$subprice = $price;
1591 1591
 		$remise = 0;
@@ -1596,7 +1596,7 @@  discard block
 block discarded – undo
1596 1596
 		}
1597 1597
 		else
1598 1598
 		{
1599
-			$remise_percent=0;
1599
+			$remise_percent = 0;
1600 1600
 		}
1601 1601
 
1602 1602
 		dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $date_debut_reel, $date_fin_reel, $tvatx, $localtax1tx, $localtax2tx, $price_base_type, $info_bits");
@@ -1608,18 +1608,18 @@  discard block
 block discarded – undo
1608 1608
 		// TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
1609 1609
 		// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
1610 1610
 
1611
-		$localtaxes_type=getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1612
-		$tvatx = preg_replace('/\s*\(.*\)/','',$tvatx);  // Remove code into vatrate.
1611
+		$localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
1612
+		$tvatx = preg_replace('/\s*\(.*\)/', '', $tvatx); // Remove code into vatrate.
1613 1613
 
1614
-		$tabprice=calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1614
+		$tabprice = calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
1615 1615
 		$total_ht  = $tabprice[0];
1616 1616
 		$total_tva = $tabprice[1];
1617 1617
 		$total_ttc = $tabprice[2];
1618
-		$total_localtax1= $tabprice[9];
1619
-		$total_localtax2= $tabprice[10];
1618
+		$total_localtax1 = $tabprice[9];
1619
+		$total_localtax2 = $tabprice[10];
1620 1620
 
1621
-		$localtax1_type=$localtaxes_type[0];
1622
-		$localtax2_type=$localtaxes_type[2];
1621
+		$localtax1_type = $localtaxes_type[0];
1622
+		$localtax2_type = $localtaxes_type[2];
1623 1623
 
1624 1624
 		// TODO A virer
1625 1625
 		// Anciens indicateurs: $price, $remise (a ne plus utiliser)
@@ -1631,7 +1631,7 @@  discard block
 block discarded – undo
1631 1631
 		    $price = $pu - $remise;
1632 1632
 		}
1633 1633
 
1634
-	    if (empty($pa_ht)) $pa_ht=0;
1634
+	    if (empty($pa_ht)) $pa_ht = 0;
1635 1635
 
1636 1636
 		// if buy price not defined, define buyprice as configured in margin admin
1637 1637
 		if ($this->pa_ht == 0)
@@ -1647,58 +1647,58 @@  discard block
 block discarded – undo
1647 1647
 		}
1648 1648
 
1649 1649
 		$sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description='".$this->db->escape($desc)."'";
1650
-		$sql.= ",price_ht='" .     price2num($price)."'";
1651
-		$sql.= ",subprice='" .     price2num($subprice)."'";
1652
-		$sql.= ",remise='" .       price2num($remise)."'";
1653
-		$sql.= ",remise_percent='".price2num($remise_percent)."'";
1654
-		$sql.= ",qty='".$qty."'";
1655
-		$sql.= ",tva_tx='".        price2num($tvatx)."'";
1656
-		$sql.= ",localtax1_tx='".  price2num($localtax1tx)."'";
1657
-		$sql.= ",localtax2_tx='".  price2num($localtax2tx)."'";
1658
-		$sql.= ",localtax1_type='".$localtax1_type."'";
1659
-		$sql.= ",localtax2_type='".$localtax2_type."'";
1660
-		$sql.= ", total_ht='".     price2num($total_ht)."'";
1661
-		$sql.= ", total_tva='".    price2num($total_tva)."'";
1662
-		$sql.= ", total_localtax1='".price2num($total_localtax1)."'";
1663
-		$sql.= ", total_localtax2='".price2num($total_localtax2)."'";
1664
-		$sql.= ", total_ttc='".      price2num($total_ttc)."'";
1665
-		$sql.= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1666
-		$sql.= ", buy_price_ht='".price2num($pa_ht)."'";
1667
-		if ($date_start > 0) { $sql.= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; }
1668
-		else { $sql.=",date_ouverture_prevue=null"; }
1669
-		if ($date_end > 0) { $sql.= ",date_fin_validite='".$this->db->idate($date_end)."'"; }
1670
-		else { $sql.=",date_fin_validite=null"; }
1671
-		if ($date_debut_reel > 0) { $sql.= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; }
1672
-		else { $sql.=",date_ouverture=null"; }
1673
-		if ($date_fin_reel > 0) { $sql.= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; }
1674
-		else { $sql.=",date_cloture=null"; }
1675
-		$sql .= ", fk_unit=".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
1650
+		$sql .= ",price_ht='".price2num($price)."'";
1651
+		$sql .= ",subprice='".price2num($subprice)."'";
1652
+		$sql .= ",remise='".price2num($remise)."'";
1653
+		$sql .= ",remise_percent='".price2num($remise_percent)."'";
1654
+		$sql .= ",qty='".$qty."'";
1655
+		$sql .= ",tva_tx='".price2num($tvatx)."'";
1656
+		$sql .= ",localtax1_tx='".price2num($localtax1tx)."'";
1657
+		$sql .= ",localtax2_tx='".price2num($localtax2tx)."'";
1658
+		$sql .= ",localtax1_type='".$localtax1_type."'";
1659
+		$sql .= ",localtax2_type='".$localtax2_type."'";
1660
+		$sql .= ", total_ht='".price2num($total_ht)."'";
1661
+		$sql .= ", total_tva='".price2num($total_tva)."'";
1662
+		$sql .= ", total_localtax1='".price2num($total_localtax1)."'";
1663
+		$sql .= ", total_localtax2='".price2num($total_localtax2)."'";
1664
+		$sql .= ", total_ttc='".price2num($total_ttc)."'";
1665
+		$sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1666
+		$sql .= ", buy_price_ht='".price2num($pa_ht)."'";
1667
+		if ($date_start > 0) { $sql .= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; }
1668
+		else { $sql .= ",date_ouverture_prevue=null"; }
1669
+		if ($date_end > 0) { $sql .= ",date_fin_validite='".$this->db->idate($date_end)."'"; }
1670
+		else { $sql .= ",date_fin_validite=null"; }
1671
+		if ($date_debut_reel > 0) { $sql .= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; }
1672
+		else { $sql .= ",date_ouverture=null"; }
1673
+		if ($date_fin_reel > 0) { $sql .= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; }
1674
+		else { $sql .= ",date_cloture=null"; }
1675
+		$sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
1676 1676
 		$sql .= " WHERE rowid = ".$rowid;
1677 1677
 
1678 1678
 		dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
1679 1679
 		$result = $this->db->query($sql);
1680 1680
 		if ($result)
1681 1681
 		{
1682
-			$result=$this->update_statut($user);
1682
+			$result = $this->update_statut($user);
1683 1683
 			if ($result >= 0)
1684 1684
 			{
1685 1685
 
1686
-				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
1686
+				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used
1687 1687
 				{
1688 1688
 					$contractline = new ContratLigne($this->db);
1689
-					$contractline->array_options=$array_options;
1690
-					$contractline->id= $rowid;
1691
-					$result=$contractline->insertExtraFields();
1689
+					$contractline->array_options = $array_options;
1690
+					$contractline->id = $rowid;
1691
+					$result = $contractline->insertExtraFields();
1692 1692
 					if ($result < 0)
1693 1693
 					{
1694
-						$this->error[]=$contractline->error;
1694
+						$this->error[] = $contractline->error;
1695 1695
 						$error++;
1696 1696
 					}
1697 1697
 				}
1698 1698
 
1699 1699
 				if (empty($error)) {
1700 1700
 			        // Call trigger
1701
-			        $result=$this->call_trigger('LINECONTRACT_UPDATE',$user);
1701
+			        $result = $this->call_trigger('LINECONTRACT_UPDATE', $user);
1702 1702
 			        if ($result < 0)
1703 1703
 			        {
1704 1704
 			            $this->db->rollback();
@@ -1720,7 +1720,7 @@  discard block
 block discarded – undo
1720 1720
 		else
1721 1721
 		{
1722 1722
 			$this->db->rollback();
1723
-			$this->error=$this->db->error();
1723
+			$this->error = $this->db->error();
1724 1724
 			dol_syslog(get_class($this)."::updateline Erreur -1");
1725 1725
 			return -1;
1726 1726
 		}
@@ -1737,26 +1737,26 @@  discard block
 block discarded – undo
1737 1737
 	{
1738 1738
 		global $conf, $langs;
1739 1739
 
1740
-		$error=0;
1740
+		$error = 0;
1741 1741
 
1742 1742
 		if ($this->statut >= 0)
1743 1743
 		{
1744 1744
 
1745 1745
 		    // Call trigger
1746
-		    $result=$this->call_trigger('LINECONTRACT_DELETE',$user);
1746
+		    $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
1747 1747
 		    if ($result < 0) return -1;
1748 1748
 		    // End call triggers
1749 1749
 
1750 1750
 		    $this->db->begin();
1751 1751
 
1752 1752
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
1753
-			$sql.= " WHERE rowid=".$idline;
1753
+			$sql .= " WHERE rowid=".$idline;
1754 1754
 
1755 1755
 			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1756 1756
 			$resql = $this->db->query($sql);
1757
-			if (! $resql)
1757
+			if (!$resql)
1758 1758
 			{
1759
-				$this->error="Error ".$this->db->lasterror();
1759
+				$this->error = "Error ".$this->db->lasterror();
1760 1760
 				$error++;
1761 1761
 			}
1762 1762
 
@@ -1765,12 +1765,12 @@  discard block
 block discarded – undo
1765 1765
 				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1766 1766
 				{
1767 1767
 					$contractline = new ContratLigne($this->db);
1768
-					$contractline->id= $idline;
1769
-					$result=$contractline->deleteExtraFields();
1768
+					$contractline->id = $idline;
1769
+					$result = $contractline->deleteExtraFields();
1770 1770
 					if ($result < 0)
1771 1771
 					{
1772 1772
 						$error++;
1773
-						$this->error="Error ".get_class($this)."::delete deleteExtraFields error -4 ".$contractline->error;
1773
+						$this->error = "Error ".get_class($this)."::delete deleteExtraFields error -4 ".$contractline->error;
1774 1774
 					}
1775 1775
 				}
1776 1776
 			}
@@ -1803,7 +1803,7 @@  discard block
 block discarded – undo
1803 1803
 	function update_statut($user)
1804 1804
 	{
1805 1805
         // phpcs:enable
1806
-		dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
1806
+		dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
1807 1807
 
1808 1808
 		// If draft, we keep it (should not happen)
1809 1809
 		if ($this->statut == 0) return 1;
@@ -1829,7 +1829,7 @@  discard block
 block discarded – undo
1829 1829
 	 */
1830 1830
 	function getLibStatut($mode)
1831 1831
 	{
1832
-		return $this->LibStatut($this->statut,$mode);
1832
+		return $this->LibStatut($this->statut, $mode);
1833 1833
 	}
1834 1834
 
1835 1835
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
 	 *  @param  int		$mode          	0=Long label, 1=Short label, 2=Picto + Libelle court, 3=Picto, 4=Picto + Long label of all services, 5=Libelle court + Picto, 6=Picto of all services, 7=Same than 6 with fixed length
1841 1841
 	 *	@return string      			Label
1842 1842
 	 */
1843
-	function LibStatut($statut,$mode)
1843
+	function LibStatut($statut, $mode)
1844 1844
 	{
1845 1845
         // phpcs:enable
1846 1846
 		global $langs;
@@ -1859,43 +1859,43 @@  discard block
 block discarded – undo
1859 1859
 		}
1860 1860
 		elseif ($mode == 2)
1861 1861
 		{
1862
-			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0').' '.$langs->trans("ContractStatusDraft"); }
1863
-			elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4').' '.$langs->trans("ContractStatusValidated"); }
1864
-			elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6').' '.$langs->trans("ContractStatusClosed"); }
1862
+			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'), 'statut0').' '.$langs->trans("ContractStatusDraft"); }
1863
+			elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'), 'statut4').' '.$langs->trans("ContractStatusValidated"); }
1864
+			elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'), 'statut6').' '.$langs->trans("ContractStatusClosed"); }
1865 1865
 		}
1866 1866
 		elseif ($mode == 3)
1867 1867
 		{
1868
-			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0'); }
1869
-			elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4'); }
1870
-			elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1868
+			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'), 'statut0'); }
1869
+			elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'), 'statut4'); }
1870
+			elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'), 'statut6'); }
1871 1871
 		}
1872 1872
 		elseif ($mode == 4 || $mode == 6 || $mode == 7)
1873 1873
 		{
1874
-			$text='';
1874
+			$text = '';
1875 1875
 			if ($mode == 4)
1876 1876
 			{
1877
-				$text ='<span class="hideonsmartphone">';
1878
-				$text.=($this->nbofserviceswait+$this->nbofservicesopened+$this->nbofservicesexpired+$this->nbofservicesclosed);
1879
-				$text.=' '.$langs->trans("Services");
1880
-				$text.=': &nbsp; &nbsp; ';
1881
-				$text.='</span>';
1882
-			}
1883
-			$text.=($mode == 7?'<div class="inline-block">':'');
1884
-			$text.=($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0,3,-1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed)?' &nbsp; ':'') : '';
1885
-			$text.=($mode == 7?'</div><div class="inline-block">':'');
1886
-			$text.=($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4,3,0,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed)?' &nbsp; ':'') : '';
1887
-			$text.=($mode == 7?'</div><div class="inline-block">':'');
1888
-			$text.=($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4,3,1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesclosed)?' &nbsp; ':'') : '';
1889
-			$text.=($mode == 7?'</div><div class="inline-block">':'');
1890
-			$text.=($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5,3,-1,'class="paddingleft2 inline-block valigntextbottom"')) : '';
1891
-			$text.=($mode == 7?'</div>':'');
1877
+				$text = '<span class="hideonsmartphone">';
1878
+				$text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
1879
+				$text .= ' '.$langs->trans("Services");
1880
+				$text .= ': &nbsp; &nbsp; ';
1881
+				$text .= '</span>';
1882
+			}
1883
+			$text .= ($mode == 7 ? '<div class="inline-block">' : '');
1884
+			$text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1885
+			$text .= ($mode == 7 ? '</div><div class="inline-block">' : '');
1886
+			$text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1887
+			$text .= ($mode == 7 ? '</div><div class="inline-block">' : '');
1888
+			$text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
1889
+			$text .= ($mode == 7 ? '</div><div class="inline-block">' : '');
1890
+			$text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="paddingleft2 inline-block valigntextbottom"')) : '';
1891
+			$text .= ($mode == 7 ? '</div>' : '');
1892 1892
 			return $text;
1893 1893
 		}
1894 1894
 		elseif ($mode == 5)
1895 1895
 		{
1896
-			if ($statut == 0) { return $langs->trans("ContractStatusDraft").' '.img_picto($langs->trans('ContractStatusDraft'),'statut0'); }
1897
-			elseif ($statut == 1) { return $langs->trans("ContractStatusValidated").' '.img_picto($langs->trans('ContractStatusValidated'),'statut4'); }
1898
-			elseif ($statut == 2) { return $langs->trans("ContractStatusClosed").' '.img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1896
+			if ($statut == 0) { return $langs->trans("ContractStatusDraft").' '.img_picto($langs->trans('ContractStatusDraft'), 'statut0'); }
1897
+			elseif ($statut == 1) { return $langs->trans("ContractStatusValidated").' '.img_picto($langs->trans('ContractStatusValidated'), 'statut4'); }
1898
+			elseif ($statut == 2) { return $langs->trans("ContractStatusClosed").' '.img_picto($langs->trans('ContractStatusClosed'), 'statut6'); }
1899 1899
 		}
1900 1900
 	}
1901 1901
 
@@ -1909,20 +1909,20 @@  discard block
 block discarded – undo
1909 1909
      *  @param  int     $save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1910 1910
 	 *	@return	string								Chaine avec URL
1911 1911
 	 */
1912
-	function getNomUrl($withpicto=0, $maxlength=0, $notooltip=0, $save_lastsearch_value=-1)
1912
+	function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
1913 1913
 	{
1914 1914
 		global $conf, $langs, $user;
1915 1915
 
1916
-		$result='';
1916
+		$result = '';
1917 1917
 
1918 1918
 		$url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
1919 1919
 
1920 1920
 		//if ($option !== 'nolink')
1921 1921
 		//{
1922 1922
 			// Add param to save lastsearch_values or not
1923
-			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1924
-			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1925
-			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1923
+			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1924
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1925
+			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1926 1926
 		//}
1927 1927
 
1928 1928
         $label = '';
@@ -1936,32 +1936,32 @@  discard block
 block discarded – undo
1936 1936
                 $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
1937 1937
             }
1938 1938
             if (!empty($this->total_tva)) {
1939
-                $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1,	$conf->currency);
1939
+                $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
1940 1940
             }
1941 1941
             if (!empty($this->total_ttc)) {
1942 1942
                 $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
1943 1943
             }
1944 1944
         }
1945 1945
 
1946
-        $linkclose='';
1946
+        $linkclose = '';
1947 1947
         if (empty($notooltip) && $user->rights->contrat->lire)
1948 1948
         {
1949
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1949
+            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1950 1950
             {
1951
-                $label=$langs->trans("ShowOrder");
1952
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
1951
+                $label = $langs->trans("ShowOrder");
1952
+                $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1953 1953
             }
1954
-            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
1955
-            $linkclose.=' class="classfortooltip"';
1954
+            $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1955
+            $linkclose .= ' class="classfortooltip"';
1956 1956
         }
1957 1957
 
1958 1958
 		$linkstart = '<a href="'.$url.'"';
1959
-		$linkstart.=$linkclose.'>';
1960
-		$linkend='</a>';
1959
+		$linkstart .= $linkclose.'>';
1960
+		$linkend = '</a>';
1961 1961
 
1962 1962
 		$result .= $linkstart;
1963
-		if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
1964
-		if ($withpicto != 2) $result.= $this->ref;
1963
+		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1964
+		if ($withpicto != 2) $result .= $this->ref;
1965 1965
 		$result .= $linkend;
1966 1966
 
1967 1967
 		return $result;
@@ -1976,12 +1976,12 @@  discard block
 block discarded – undo
1976 1976
 	function info($id)
1977 1977
 	{
1978 1978
 		$sql = "SELECT c.rowid, c.ref, c.datec, c.date_cloture,";
1979
-		$sql.= " c.tms as date_modification,";
1980
-		$sql.= " fk_user_author, fk_user_cloture";
1981
-		$sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
1982
-		$sql.= " WHERE c.rowid = ".$id;
1979
+		$sql .= " c.tms as date_modification,";
1980
+		$sql .= " fk_user_author, fk_user_cloture";
1981
+		$sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
1982
+		$sql .= " WHERE c.rowid = ".$id;
1983 1983
 
1984
-		$result=$this->db->query($sql);
1984
+		$result = $this->db->query($sql);
1985 1985
 		if ($result)
1986 1986
 		{
1987 1987
 			if ($this->db->num_rows($result))
@@ -1993,7 +1993,7 @@  discard block
 block discarded – undo
1993 1993
 				if ($obj->fk_user_author) {
1994 1994
 					$cuser = new User($this->db);
1995 1995
 					$cuser->fetch($obj->fk_user_author);
1996
-					$this->user_creation     = $cuser;
1996
+					$this->user_creation = $cuser;
1997 1997
 				}
1998 1998
 
1999 1999
 				if ($obj->fk_user_cloture) {
@@ -2001,7 +2001,7 @@  discard block
 block discarded – undo
2001 2001
 					$cuser->fetch($obj->fk_user_cloture);
2002 2002
 					$this->user_cloture = $cuser;
2003 2003
 				}
2004
-				$this->ref			     = (! $obj->ref) ? $obj->rowid : $obj->ref;
2004
+				$this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
2005 2005
 				$this->date_creation     = $this->db->jdate($obj->datec);
2006 2006
 				$this->date_modification = $this->db->jdate($obj->date_modification);
2007 2007
 				$this->date_cloture      = $this->db->jdate($obj->date_cloture);
@@ -2022,33 +2022,33 @@  discard block
 block discarded – undo
2022 2022
 	 *  @param	int		$statut     Status of lines to get
2023 2023
 	 *  @return array       		Array of line's rowid
2024 2024
 	 */
2025
-	function array_detail($statut=-1)
2025
+	function array_detail($statut = -1)
2026 2026
 	{
2027 2027
         // phpcs:enable
2028
-		$tab=array();
2028
+		$tab = array();
2029 2029
 
2030 2030
 		$sql = "SELECT cd.rowid";
2031
-		$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2032
-		$sql.= " WHERE fk_contrat =".$this->id;
2033
-		if ($statut >= 0) $sql.= " AND statut = '$statut'";
2031
+		$sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2032
+		$sql .= " WHERE fk_contrat =".$this->id;
2033
+		if ($statut >= 0) $sql .= " AND statut = '$statut'";
2034 2034
 
2035 2035
 		dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2036
-		$resql=$this->db->query($sql);
2036
+		$resql = $this->db->query($sql);
2037 2037
 		if ($resql)
2038 2038
 		{
2039
-			$num=$this->db->num_rows($resql);
2040
-			$i=0;
2039
+			$num = $this->db->num_rows($resql);
2040
+			$i = 0;
2041 2041
 			while ($i < $num)
2042 2042
 			{
2043 2043
 				$obj = $this->db->fetch_object($resql);
2044
-				$tab[$i]=$obj->rowid;
2044
+				$tab[$i] = $obj->rowid;
2045 2045
 				$i++;
2046 2046
 			}
2047 2047
 			return $tab;
2048 2048
 		}
2049 2049
 		else
2050 2050
 		{
2051
-			$this->error=$this->db->error();
2051
+			$this->error = $this->db->error();
2052 2052
 			return -1;
2053 2053
 		}
2054 2054
 	}
@@ -2059,34 +2059,34 @@  discard block
 block discarded – undo
2059 2059
 	 *	@param	string		$option		'all' or 'others'
2060 2060
 	 *  @return array   				Array of contracts id
2061 2061
 	 */
2062
-	function getListOfContracts($option='all')
2062
+	function getListOfContracts($option = 'all')
2063 2063
 	{
2064
-		$tab=array();
2064
+		$tab = array();
2065 2065
 
2066 2066
 		$sql = "SELECT c.rowid, c.ref";
2067
-		$sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
2068
-		$sql.= " WHERE fk_soc =".$this->socid;
2069
-		if ($option == 'others') $sql.= " AND c.rowid != ".$this->id;
2067
+		$sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2068
+		$sql .= " WHERE fk_soc =".$this->socid;
2069
+		if ($option == 'others') $sql .= " AND c.rowid != ".$this->id;
2070 2070
 
2071 2071
 		dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2072
-		$resql=$this->db->query($sql);
2072
+		$resql = $this->db->query($sql);
2073 2073
 		if ($resql)
2074 2074
 		{
2075
-			$num=$this->db->num_rows($resql);
2076
-			$i=0;
2075
+			$num = $this->db->num_rows($resql);
2076
+			$i = 0;
2077 2077
 			while ($i < $num)
2078 2078
 			{
2079 2079
 				$obj = $this->db->fetch_object($resql);
2080
-				$contrat=new Contrat($this->db);
2080
+				$contrat = new Contrat($this->db);
2081 2081
 				$contrat->fetch($obj->rowid);
2082
-				$tab[]=$contrat;
2082
+				$tab[] = $contrat;
2083 2083
 				$i++;
2084 2084
 			}
2085 2085
 			return $tab;
2086 2086
 		}
2087 2087
 		else
2088 2088
 		{
2089
-			$this->error=$this->db->error();
2089
+			$this->error = $this->db->error();
2090 2090
 			return -1;
2091 2091
 		}
2092 2092
 	}
@@ -2100,42 +2100,42 @@  discard block
 block discarded – undo
2100 2100
      *      @param  string	$mode           "inactive" pour services a activer, "expired" pour services expires
2101 2101
      *      @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
2102 2102
 	 */
2103
-	function load_board($user,$mode)
2103
+	function load_board($user, $mode)
2104 2104
 	{
2105 2105
         // phpcs:enable
2106 2106
 		global $conf, $langs;
2107 2107
 
2108 2108
 		$this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2109
-		$this->from.= ", ".MAIN_DB_PREFIX."contratdet as cd";
2110
-		$this->from.= ", ".MAIN_DB_PREFIX."societe as s";
2111
-		if (!$user->rights->societe->client->voir && !$user->societe_id) $this->from.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2109
+		$this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
2110
+		$this->from .= ", ".MAIN_DB_PREFIX."societe as s";
2111
+		if (!$user->rights->societe->client->voir && !$user->societe_id) $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2112 2112
 
2113 2113
 		if ($mode == 'inactives')
2114 2114
 		{
2115 2115
 			$sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
2116
-			$sql.= $this->from;
2117
-			$sql.= " WHERE c.statut = 1";
2118
-			$sql.= " AND c.rowid = cd.fk_contrat";
2119
-			$sql.= " AND cd.statut = 0";
2116
+			$sql .= $this->from;
2117
+			$sql .= " WHERE c.statut = 1";
2118
+			$sql .= " AND c.rowid = cd.fk_contrat";
2119
+			$sql .= " AND cd.statut = 0";
2120 2120
 		}
2121 2121
 		elseif ($mode == 'expired')
2122 2122
 		{
2123 2123
 			$sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2124
-			$sql.= $this->from;
2125
-			$sql.= " WHERE c.statut = 1";
2126
-			$sql.= " AND c.rowid = cd.fk_contrat";
2127
-			$sql.= " AND cd.statut = 4";
2128
-			$sql.= " AND cd.date_fin_validite < '".$this->db->idate(time())."'";
2129
-		}
2130
-		$sql.= " AND c.fk_soc = s.rowid";
2131
-		$sql.= " AND c.entity = ".$conf->entity;
2132
-		if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
2133
-		if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id;
2134
-		$resql=$this->db->query($sql);
2124
+			$sql .= $this->from;
2125
+			$sql .= " WHERE c.statut = 1";
2126
+			$sql .= " AND c.rowid = cd.fk_contrat";
2127
+			$sql .= " AND cd.statut = 4";
2128
+			$sql .= " AND cd.date_fin_validite < '".$this->db->idate(time())."'";
2129
+		}
2130
+		$sql .= " AND c.fk_soc = s.rowid";
2131
+		$sql .= " AND c.entity = ".$conf->entity;
2132
+		if ($user->societe_id) $sql .= " AND c.fk_soc = ".$user->societe_id;
2133
+		if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
2134
+		$resql = $this->db->query($sql);
2135 2135
 		if ($resql)
2136 2136
 		{
2137 2137
 			$langs->load("contracts");
2138
-			$now=dol_now();
2138
+			$now = dol_now();
2139 2139
 
2140 2140
 			if ($mode == 'inactives') {
2141 2141
 				$warning_delay = $conf->contrat->services->inactifs->warning_delay;
@@ -2148,12 +2148,12 @@  discard block
 block discarded – undo
2148 2148
 			}
2149 2149
 
2150 2150
 			$response = new WorkboardResponse();
2151
-			$response->warning_delay = $warning_delay/60/60/24;
2151
+			$response->warning_delay = $warning_delay / 60 / 60 / 24;
2152 2152
 			$response->label = $label;
2153 2153
 			$response->url = $url;
2154
-			$response->img = img_object('',"contract");
2154
+			$response->img = img_object('', "contract");
2155 2155
 
2156
-			while ($obj=$this->db->fetch_object($resql))
2156
+			while ($obj = $this->db->fetch_object($resql))
2157 2157
 			{
2158 2158
 				$response->nbtodo++;
2159 2159
 
@@ -2167,7 +2167,7 @@  discard block
 block discarded – undo
2167 2167
 		else
2168 2168
 		{
2169 2169
 			dol_print_error($this->db);
2170
-			$this->error=$this->db->error();
2170
+			$this->error = $this->db->error();
2171 2171
 			return -1;
2172 2172
 		}
2173 2173
 	}
@@ -2183,26 +2183,26 @@  discard block
 block discarded – undo
2183 2183
         // phpcs:enable
2184 2184
 		global $conf, $user;
2185 2185
 
2186
-		$this->nb=array();
2186
+		$this->nb = array();
2187 2187
 		$clause = "WHERE";
2188 2188
 
2189 2189
 		$sql = "SELECT count(c.rowid) as nb";
2190
-		$sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
2191
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2190
+		$sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
2191
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
2192 2192
 		if (!$user->rights->societe->client->voir && !$user->societe_id)
2193 2193
 		{
2194
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2195
-			$sql.= " WHERE sc.fk_user = " .$user->id;
2194
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
2195
+			$sql .= " WHERE sc.fk_user = ".$user->id;
2196 2196
 			$clause = "AND";
2197 2197
 		}
2198
-		$sql.= " ".$clause." c.entity = ".$conf->entity;
2198
+		$sql .= " ".$clause." c.entity = ".$conf->entity;
2199 2199
 
2200
-		$resql=$this->db->query($sql);
2200
+		$resql = $this->db->query($sql);
2201 2201
 		if ($resql)
2202 2202
 		{
2203
-			while ($obj=$this->db->fetch_object($resql))
2203
+			while ($obj = $this->db->fetch_object($resql))
2204 2204
 			{
2205
-				$this->nb["Contracts"]=$obj->nb;
2205
+				$this->nb["Contracts"] = $obj->nb;
2206 2206
 			}
2207 2207
             $this->db->free($resql);
2208 2208
 			return 1;
@@ -2210,7 +2210,7 @@  discard block
 block discarded – undo
2210 2210
 		else
2211 2211
 		{
2212 2212
 			dol_print_error($this->db);
2213
-			$this->error=$this->db->error();
2213
+			$this->error = $this->db->error();
2214 2214
 			return -1;
2215 2215
 		}
2216 2216
 	}
@@ -2225,7 +2225,7 @@  discard block
 block discarded – undo
2225 2225
 	 */
2226 2226
 	function getIdBillingContact()
2227 2227
 	{
2228
-		return $this->getIdContact('external','BILLING');
2228
+		return $this->getIdContact('external', 'BILLING');
2229 2229
 	}
2230 2230
 
2231 2231
 	/**
@@ -2235,7 +2235,7 @@  discard block
 block discarded – undo
2235 2235
 	 */
2236 2236
 	function getIdServiceContact()
2237 2237
 	{
2238
-		return $this->getIdContact('external','SERVICE');
2238
+		return $this->getIdContact('external', 'SERVICE');
2239 2239
 	}
2240 2240
 
2241 2241
 
@@ -2248,15 +2248,15 @@  discard block
 block discarded – undo
2248 2248
 	 */
2249 2249
 	function initAsSpecimen()
2250 2250
 	{
2251
-		global $user,$langs,$conf;
2251
+		global $user, $langs, $conf;
2252 2252
 
2253 2253
         // Load array of products prodids
2254 2254
 		$num_prods = 0;
2255 2255
 		$prodids = array();
2256 2256
 		$sql = "SELECT rowid";
2257
-		$sql.= " FROM ".MAIN_DB_PREFIX."product";
2258
-		$sql.= " WHERE entity IN (".getEntity('product').")";
2259
-		$sql.= " AND tosell = 1";
2257
+		$sql .= " FROM ".MAIN_DB_PREFIX."product";
2258
+		$sql .= " WHERE entity IN (".getEntity('product').")";
2259
+		$sql .= " AND tosell = 1";
2260 2260
 		$resql = $this->db->query($sql);
2261 2261
 		if ($resql)
2262 2262
 		{
@@ -2271,35 +2271,35 @@  discard block
 block discarded – undo
2271 2271
 		}
2272 2272
 
2273 2273
 		// Initialise parametres
2274
-		$this->id=0;
2275
-		$this->specimen=1;
2274
+		$this->id = 0;
2275
+		$this->specimen = 1;
2276 2276
 
2277 2277
 		$this->ref = 'SPECIMEN';
2278 2278
 		$this->ref_customer = 'SPECIMENCUST';
2279 2279
 		$this->ref_supplier = 'SPECIMENSUPP';
2280 2280
 		$this->socid = 1;
2281
-		$this->statut= 0;
2281
+		$this->statut = 0;
2282 2282
 		$this->date_creation = (dol_now() - 3600 * 24 * 7);
2283 2283
 		$this->date_contrat = dol_now();
2284 2284
 		$this->commercial_signature_id = 1;
2285 2285
 		$this->commercial_suivi_id = 1;
2286
-		$this->note_private='This is a comment (private)';
2287
-		$this->note_public='This is a comment (public)';
2286
+		$this->note_private = 'This is a comment (private)';
2287
+		$this->note_public = 'This is a comment (public)';
2288 2288
 		$this->fk_projet = 0;
2289 2289
 		// Lines
2290 2290
 		$nbp = 5;
2291 2291
 		$xnbp = 0;
2292 2292
 		while ($xnbp < $nbp)
2293 2293
 		{
2294
-			$line=new ContratLigne($this->db);
2295
-			$line->qty=1;
2296
-			$line->subprice=100;
2297
-			$line->price=100;
2298
-			$line->tva_tx=19.6;
2299
-			$line->remise_percent=10;
2300
-			$line->total_ht=90;
2301
-			$line->total_ttc=107.64;	// 90 * 1.196
2302
-			$line->total_tva=17.64;
2294
+			$line = new ContratLigne($this->db);
2295
+			$line->qty = 1;
2296
+			$line->subprice = 100;
2297
+			$line->price = 100;
2298
+			$line->tva_tx = 19.6;
2299
+			$line->remise_percent = 10;
2300
+			$line->total_ht = 90;
2301
+			$line->total_ttc = 107.64; // 90 * 1.196
2302
+			$line->total_tva = 17.64;
2303 2303
 			$line->date_start = dol_now() - 500000;
2304 2304
 			$line->date_start_real = dol_now() - 200000;
2305 2305
 			$line->date_end = dol_now() + 500000;
@@ -2307,9 +2307,9 @@  discard block
 block discarded – undo
2307 2307
 			if ($num_prods > 0)
2308 2308
             {
2309 2309
 				$prodid = mt_rand(1, $num_prods);
2310
-				$line->fk_product=$prodids[$prodid];
2310
+				$line->fk_product = $prodids[$prodid];
2311 2311
             }
2312
-			$this->lines[$xnbp]=$line;
2312
+			$this->lines[$xnbp] = $line;
2313 2313
 			$xnbp++;
2314 2314
 		}
2315 2315
 	}
@@ -2336,19 +2336,19 @@  discard block
 block discarded – undo
2336 2336
          *  @param   null|array  $moreparams     Array to provide more information
2337 2337
 	 * 	@return     int         				0 if KO, 1 if OK
2338 2338
 	 */
2339
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
2339
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2340 2340
 	{
2341
-		global $conf,$langs;
2341
+		global $conf, $langs;
2342 2342
 
2343 2343
 		$langs->load("contracts");
2344 2344
 
2345
-		if (! dol_strlen($modele)) {
2345
+		if (!dol_strlen($modele)) {
2346 2346
 
2347 2347
 			$modele = 'strato';
2348 2348
 
2349 2349
 			if ($this->modelpdf) {
2350 2350
 				$modele = $this->modelpdf;
2351
-			} elseif (! empty($conf->global->CONTRACT_ADDON_PDF)) {
2351
+			} elseif (!empty($conf->global->CONTRACT_ADDON_PDF)) {
2352 2352
 				$modele = $conf->global->CONTRACT_ADDON_PDF;
2353 2353
 			}
2354 2354
 		}
@@ -2382,7 +2382,7 @@  discard block
 block discarded – undo
2382 2382
 	 * @param int $notrigger	1=Does not execute triggers, 0= execute triggers
2383 2383
 	 * @return int New id of clone
2384 2384
 	 */
2385
-    function createFromClone($socid = 0, $notrigger=0)
2385
+    function createFromClone($socid = 0, $notrigger = 0)
2386 2386
     {
2387 2387
 		global $db, $user, $langs, $conf, $hookmanager, $extrafields;
2388 2388
 
@@ -2410,11 +2410,11 @@  discard block
 block discarded – undo
2410 2410
 		if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0)
2411 2411
 		{
2412 2412
 			$extrafields->fetch_name_optionals_label($this->element);
2413
-			foreach($clonedObj->array_options as $key => $option)
2413
+			foreach ($clonedObj->array_options as $key => $option)
2414 2414
 			{
2415 2415
 				$shortkey = preg_replace('/options_/', '', $key);
2416 2416
 				//var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
2417
-				if (! empty($extrafields->attributes[$this->element]['unique'][$shortkey]))
2417
+				if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey]))
2418 2418
 				{
2419 2419
 					//var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
2420 2420
 					unset($clonedObj->array_options[$key]);
@@ -2422,14 +2422,14 @@  discard block
 block discarded – undo
2422 2422
 			}
2423 2423
 		}
2424 2424
 
2425
-		if (empty($conf->global->CONTRACT_ADDON) || ! is_readable(DOL_DOCUMENT_ROOT . "/core/modules/contract/" . $conf->global->CONTRACT_ADDON . ".php")) {
2425
+		if (empty($conf->global->CONTRACT_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.".php")) {
2426 2426
 			$this->error = 'ErrorSetupNotComplete';
2427 2427
 			dol_syslog($this->error);
2428
-			return - 1;
2428
+			return -1;
2429 2429
 		}
2430 2430
 
2431 2431
 		// Set ref
2432
-		require_once DOL_DOCUMENT_ROOT . "/core/modules/contract/" . $conf->global->CONTRACT_ADDON . '.php';
2432
+		require_once DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.'.php';
2433 2433
 		$obj = $conf->global->CONTRACT_ADDON;
2434 2434
 		$modContract = new $obj();
2435 2435
 		$clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
@@ -2442,7 +2442,7 @@  discard block
 block discarded – undo
2442 2442
 		// Create clone
2443 2443
 		$result = $clonedObj->create($user);
2444 2444
 		if ($result < 0) {
2445
-			$error ++;
2445
+			$error++;
2446 2446
 			$this->error = $clonedObj->error;
2447 2447
 			$this->errors[] = $clonedObj->error;
2448 2448
 		} else {
@@ -2454,40 +2454,40 @@  discard block
 block discarded – undo
2454 2454
             }
2455 2455
         }
2456 2456
 
2457
-		if (! $error) {
2458
-			foreach ( $this->lines as $line ) {
2457
+		if (!$error) {
2458
+			foreach ($this->lines as $line) {
2459 2459
 				$result = $clonedObj->addline($line->desc, $line->subprice, $line->qty, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->fk_product, $line->remise_percent, $line->date_ouverture, $line->date_cloture, 'HT', 0, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit);
2460 2460
 				if ($result < 0) {
2461
-					$error ++;
2461
+					$error++;
2462 2462
 					$this->error = $clonedObj->error;
2463 2463
 					$this->errors[] = $clonedObj->error;
2464 2464
 				}
2465 2465
 			}
2466 2466
 		}
2467 2467
 
2468
-		if (! $error) {
2468
+		if (!$error) {
2469 2469
 			// Hook of thirdparty module
2470 2470
 			if (is_object($hookmanager)) {
2471
-				$parameters = array (
2471
+				$parameters = array(
2472 2472
 						'objFrom' => $this,
2473 2473
 						'clonedObj' => $clonedObj
2474 2474
 				);
2475 2475
 				$action = '';
2476 2476
 				$reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2477 2477
 				if ($reshook < 0)
2478
-					$error ++;
2478
+					$error++;
2479 2479
 			}
2480 2480
 		}
2481 2481
 
2482 2482
 		unset($this->context['createfromclone']);
2483 2483
 
2484 2484
 		// End
2485
-		if (! $error) {
2485
+		if (!$error) {
2486 2486
 			$this->db->commit();
2487 2487
 			return $clonedObj->id;
2488 2488
 		} else {
2489 2489
 			$this->db->rollback();
2490
-			return - 1;
2490
+			return -1;
2491 2491
 		}
2492 2492
 	}
2493 2493
 }
@@ -2501,12 +2501,12 @@  discard block
 block discarded – undo
2501 2501
     /**
2502 2502
 	 * @var string ID to identify managed object
2503 2503
 	 */
2504
-	public $element='contratdet';
2504
+	public $element = 'contratdet';
2505 2505
 
2506 2506
     /**
2507 2507
 	 * @var string Name of table without prefix where object is stored
2508 2508
 	 */
2509
-	public $table_element='contratdet';
2509
+	public $table_element = 'contratdet';
2510 2510
 
2511 2511
 	/**
2512 2512
 	 * @var int ID
@@ -2530,8 +2530,8 @@  discard block
 block discarded – undo
2530 2530
      */
2531 2531
 	public $fk_product;
2532 2532
 
2533
-	public $statut;					// 0 inactive, 4 active, 5 closed
2534
-	public $type;						// 0 for product, 1 for service
2533
+	public $statut; // 0 inactive, 4 active, 5 closed
2534
+	public $type; // 0 for product, 1 for service
2535 2535
 
2536 2536
 	/**
2537 2537
 	 * @var string
@@ -2555,20 +2555,20 @@  discard block
 block discarded – undo
2555 2555
 
2556 2556
 	public $date_commande;
2557 2557
 
2558
-	public $date_start;				// date start planned
2559
-	public $date_start_real;			// date start real
2560
-	public $date_end;					// date end planned
2561
-	public $date_end_real;				// date end real
2558
+	public $date_start; // date start planned
2559
+	public $date_start_real; // date start real
2560
+	public $date_end; // date end planned
2561
+	public $date_end_real; // date end real
2562 2562
 	// For backward compatibility
2563
-	public $date_ouverture_prevue;		// date start planned
2564
-	public $date_ouverture;			// date start real
2565
-	public $date_fin_validite;			// date end planned
2566
-	public $date_cloture;				// date end real
2563
+	public $date_ouverture_prevue; // date start planned
2564
+	public $date_ouverture; // date start real
2565
+	public $date_fin_validite; // date end planned
2566
+	public $date_cloture; // date end real
2567 2567
 	public $tva_tx;
2568 2568
 	public $localtax1_tx;
2569 2569
 	public $localtax2_tx;
2570
-	public $localtax1_type;	// Local tax 1 type
2571
-	public $localtax2_type;	// Local tax 2 type
2570
+	public $localtax1_type; // Local tax 1 type
2571
+	public $localtax2_type; // Local tax 2 type
2572 2572
 	public $qty;
2573 2573
 	public $remise_percent;
2574 2574
 	public $remise;
@@ -2578,7 +2578,7 @@  discard block
 block discarded – undo
2578 2578
      */
2579 2579
 	public $fk_remise_except;
2580 2580
 
2581
-	public $subprice;					// Unit price HT
2581
+	public $subprice; // Unit price HT
2582 2582
 
2583 2583
 	/**
2584 2584
 	 * @var float
@@ -2646,7 +2646,7 @@  discard block
 block discarded – undo
2646 2646
 	 */
2647 2647
 	function getLibStatut($mode)
2648 2648
 	{
2649
-		return $this->LibStatut($this->statut,$mode,((! empty($this->date_fin_validite))?($this->date_fin_validite < dol_now()?1:0):-1));
2649
+		return $this->LibStatut($this->statut, $mode, ((!empty($this->date_fin_validite)) ? ($this->date_fin_validite < dol_now() ? 1 : 0) : -1));
2650 2650
 	}
2651 2651
 
2652 2652
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -2659,7 +2659,7 @@  discard block
 block discarded – undo
2659 2659
 	 *  @param	string	$moreatt	More attribute
2660 2660
 	 *  @return string      		Libelle
2661 2661
 	 */
2662
-	static function LibStatut($statut,$mode,$expired=-1,$moreatt='')
2662
+	static function LibStatut($statut, $mode, $expired = -1, $moreatt = '')
2663 2663
 	{
2664 2664
         // phpcs:enable
2665 2665
 		global $langs;
@@ -2668,49 +2668,49 @@  discard block
 block discarded – undo
2668 2668
 		{
2669 2669
 			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); }
2670 2670
 			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); }
2671
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLate"); }
2672
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLate"); }
2673
-			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2671
+			elseif ($statut == self::STATUS_OPEN && $expired == 0) { return $langs->trans("ServiceStatusNotLate"); }
2672
+			elseif ($statut == self::STATUS_OPEN && $expired == 1) { return $langs->trans("ServiceStatusLate"); }
2673
+			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed"); }
2674 2674
 		}
2675 2675
 		elseif ($mode == 1)
2676 2676
 		{
2677 2677
 			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); }
2678 2678
 			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); }
2679
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort"); }
2680
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort"); }
2681
-			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2679
+			elseif ($statut == self::STATUS_OPEN && $expired == 0) { return $langs->trans("ServiceStatusNotLateShort"); }
2680
+			elseif ($statut == self::STATUS_OPEN && $expired == 1) { return $langs->trans("ServiceStatusLateShort"); }
2681
+			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed"); }
2682 2682
 		}
2683 2683
 		elseif ($mode == 2)
2684 2684
 		{
2685
-			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2686
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2687
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLateShort"); }
2688
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLateShort"); }
2689
-			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2685
+			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'), 'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2686
+			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'), 'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2687
+			elseif ($statut == self::STATUS_OPEN && $expired == 0) { return img_picto($langs->trans('ServiceStatusNotLate'), 'statut4').' '.$langs->trans("ServiceStatusNotLateShort"); }
2688
+			elseif ($statut == self::STATUS_OPEN && $expired == 1) { return img_picto($langs->trans('ServiceStatusLate'), 'statut3').' '.$langs->trans("ServiceStatusLateShort"); }
2689
+			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'), 'statut6').' '.$langs->trans("ServiceStatusClosed"); }
2690 2690
 		}
2691 2691
 		elseif ($mode == 3)
2692 2692
 		{
2693
-			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0',$moreatt); }
2694
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4',$moreatt); }
2695
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4',$moreatt); }
2696
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3',$moreatt); }
2697
-			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6',$moreatt); }
2693
+			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'), 'statut0', $moreatt); }
2694
+			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'), 'statut4', $moreatt); }
2695
+			elseif ($statut == self::STATUS_OPEN && $expired == 0) { return img_picto($langs->trans('ServiceStatusNotLate'), 'statut4', $moreatt); }
2696
+			elseif ($statut == self::STATUS_OPEN && $expired == 1) { return img_picto($langs->trans('ServiceStatusLate'), 'statut3', $moreatt); }
2697
+			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'), 'statut6', $moreatt); }
2698 2698
 		}
2699 2699
 		elseif ($mode == 4)
2700 2700
 		{
2701
-			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2702
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2703
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLate"); }
2704
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLate"); }
2705
-			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2701
+			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'), 'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2702
+			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'), 'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2703
+			elseif ($statut == self::STATUS_OPEN && $expired == 0) { return img_picto($langs->trans('ServiceStatusNotLate'), 'statut4').' '.$langs->trans("ServiceStatusNotLate"); }
2704
+			elseif ($statut == self::STATUS_OPEN && $expired == 1) { return img_picto($langs->trans('ServiceStatusLate'), 'statut3').' '.$langs->trans("ServiceStatusLate"); }
2705
+			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'), 'statut6').' '.$langs->trans("ServiceStatusClosed"); }
2706 2706
 		}
2707 2707
 		elseif ($mode == 5)
2708 2708
 		{
2709
-			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial").' '.img_picto($langs->trans('ServiceStatusInitial'),'statut0'); }
2710
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning").' '.img_picto($langs->trans('ServiceStatusRunning'),'statut4'); }
2711
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort").' '.img_picto($langs->trans('ServiceStatusNotLateShort'),'statut4'); }
2712
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort").' '.img_picto($langs->trans('ServiceStatusLate'),'statut3'); }
2713
-			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed").' '.img_picto($langs->trans('ServiceStatusClosed'),'statut6'); }
2709
+			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial").' '.img_picto($langs->trans('ServiceStatusInitial'), 'statut0'); }
2710
+			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning").' '.img_picto($langs->trans('ServiceStatusRunning'), 'statut4'); }
2711
+			elseif ($statut == self::STATUS_OPEN && $expired == 0) { return $langs->trans("ServiceStatusNotLateShort").' '.img_picto($langs->trans('ServiceStatusNotLateShort'), 'statut4'); }
2712
+			elseif ($statut == self::STATUS_OPEN && $expired == 1) { return $langs->trans("ServiceStatusLateShort").' '.img_picto($langs->trans('ServiceStatusLate'), 'statut3'); }
2713
+			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed").' '.img_picto($langs->trans('ServiceStatusClosed'), 'statut6'); }
2714 2714
 		}
2715 2715
 	}
2716 2716
 
@@ -2721,23 +2721,23 @@  discard block
 block discarded – undo
2721 2721
 	 *  @param	int		$maxlength		Max length
2722 2722
 	 *  @return	string					Chaine avec URL
2723 2723
  	 */
2724
-	function getNomUrl($withpicto=0,$maxlength=0)
2724
+	function getNomUrl($withpicto = 0, $maxlength = 0)
2725 2725
 	{
2726 2726
 		global $langs;
2727 2727
 
2728
-		$result='';
2729
-        $label=$langs->trans("ShowContractOfService").': '.$this->label;
2730
-        if (empty($label)) $label=$this->description;
2728
+		$result = '';
2729
+        $label = $langs->trans("ShowContractOfService").': '.$this->label;
2730
+        if (empty($label)) $label = $this->description;
2731 2731
 
2732 2732
         $link = '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$this->fk_contrat.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
2733
-		$linkend='</a>';
2733
+		$linkend = '</a>';
2734 2734
 
2735
-		$picto='service';
2736
-		if ($this->type == 0) $picto='product';
2735
+		$picto = 'service';
2736
+		if ($this->type == 0) $picto = 'product';
2737 2737
 
2738
-        if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
2739
-		if ($withpicto && $withpicto != 2) $result.=' ';
2740
-		if ($withpicto != 2) $result.=$link.($this->product_ref?$this->product_ref.' ':'').($this->label?$this->label:$this->description).$linkend;
2738
+        if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
2739
+		if ($withpicto && $withpicto != 2) $result .= ' ';
2740
+		if ($withpicto != 2) $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend;
2741 2741
 		return $result;
2742 2742
 	}
2743 2743
 
@@ -2748,61 +2748,61 @@  discard block
 block discarded – undo
2748 2748
 	 * 		@param	string	$ref		Ref of contract
2749 2749
 	 *    	@return int         		<0 if KO, >0 if OK
2750 2750
 	 */
2751
-	function fetch($id, $ref='')
2751
+	function fetch($id, $ref = '')
2752 2752
 	{
2753 2753
 
2754 2754
 		// Check parameters
2755 2755
 		if (empty($id) && empty($ref)) return -1;
2756 2756
 
2757 2757
 		$sql = "SELECT";
2758
-		$sql.= " t.rowid,";
2759
-
2760
-		$sql.= " t.tms,";
2761
-		$sql.= " t.fk_contrat,";
2762
-		$sql.= " t.fk_product,";
2763
-		$sql.= " t.statut,";
2764
-		$sql.= " t.label,";			// This field is not used. Only label of product
2765
-		$sql.= " p.ref as product_ref,";
2766
-		$sql.= " p.label as product_label,";
2767
-		$sql.= " p.description as product_desc,";
2768
-		$sql.= " p.fk_product_type as product_type,";
2769
-		$sql.= " t.description,";
2770
-		$sql.= " t.date_commande,";
2771
-		$sql.= " t.date_ouverture_prevue as date_ouverture_prevue,";
2772
-		$sql.= " t.date_ouverture as date_ouverture,";
2773
-		$sql.= " t.date_fin_validite as date_fin_validite,";
2774
-		$sql.= " t.date_cloture as date_cloture,";
2775
-		$sql.= " t.tva_tx,";
2776
-		$sql.= " t.vat_src_code,";
2777
-		$sql.= " t.localtax1_tx,";
2778
-		$sql.= " t.localtax2_tx,";
2779
-		$sql.= " t.localtax1_type,";
2780
-		$sql.= " t.localtax2_type,";
2781
-		$sql.= " t.qty,";
2782
-		$sql.= " t.remise_percent,";
2783
-		$sql.= " t.remise,";
2784
-		$sql.= " t.fk_remise_except,";
2785
-		$sql.= " t.subprice,";
2786
-		$sql.= " t.price_ht,";
2787
-		$sql.= " t.total_ht,";
2788
-		$sql.= " t.total_tva,";
2789
-		$sql.= " t.total_localtax1,";
2790
-		$sql.= " t.total_localtax2,";
2791
-		$sql.= " t.total_ttc,";
2792
-		$sql.= " t.fk_product_fournisseur_price as fk_fournprice,";
2793
-		$sql.= " t.buy_price_ht as pa_ht,";
2794
-		$sql.= " t.info_bits,";
2795
-		$sql.= " t.fk_user_author,";
2796
-		$sql.= " t.fk_user_ouverture,";
2797
-		$sql.= " t.fk_user_cloture,";
2798
-		$sql.= " t.commentaire,";
2799
-		$sql.= " t.fk_unit";
2800
-		$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
2801
-		if ($id)  $sql.= " WHERE t.rowid = ".$id;
2802
-		if ($ref) $sql.= " WHERE t.rowid = '".$this->db->escape($ref)."'";
2758
+		$sql .= " t.rowid,";
2759
+
2760
+		$sql .= " t.tms,";
2761
+		$sql .= " t.fk_contrat,";
2762
+		$sql .= " t.fk_product,";
2763
+		$sql .= " t.statut,";
2764
+		$sql .= " t.label,"; // This field is not used. Only label of product
2765
+		$sql .= " p.ref as product_ref,";
2766
+		$sql .= " p.label as product_label,";
2767
+		$sql .= " p.description as product_desc,";
2768
+		$sql .= " p.fk_product_type as product_type,";
2769
+		$sql .= " t.description,";
2770
+		$sql .= " t.date_commande,";
2771
+		$sql .= " t.date_ouverture_prevue as date_ouverture_prevue,";
2772
+		$sql .= " t.date_ouverture as date_ouverture,";
2773
+		$sql .= " t.date_fin_validite as date_fin_validite,";
2774
+		$sql .= " t.date_cloture as date_cloture,";
2775
+		$sql .= " t.tva_tx,";
2776
+		$sql .= " t.vat_src_code,";
2777
+		$sql .= " t.localtax1_tx,";
2778
+		$sql .= " t.localtax2_tx,";
2779
+		$sql .= " t.localtax1_type,";
2780
+		$sql .= " t.localtax2_type,";
2781
+		$sql .= " t.qty,";
2782
+		$sql .= " t.remise_percent,";
2783
+		$sql .= " t.remise,";
2784
+		$sql .= " t.fk_remise_except,";
2785
+		$sql .= " t.subprice,";
2786
+		$sql .= " t.price_ht,";
2787
+		$sql .= " t.total_ht,";
2788
+		$sql .= " t.total_tva,";
2789
+		$sql .= " t.total_localtax1,";
2790
+		$sql .= " t.total_localtax2,";
2791
+		$sql .= " t.total_ttc,";
2792
+		$sql .= " t.fk_product_fournisseur_price as fk_fournprice,";
2793
+		$sql .= " t.buy_price_ht as pa_ht,";
2794
+		$sql .= " t.info_bits,";
2795
+		$sql .= " t.fk_user_author,";
2796
+		$sql .= " t.fk_user_ouverture,";
2797
+		$sql .= " t.fk_user_cloture,";
2798
+		$sql .= " t.commentaire,";
2799
+		$sql .= " t.fk_unit";
2800
+		$sql .= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
2801
+		if ($id)  $sql .= " WHERE t.rowid = ".$id;
2802
+		if ($ref) $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'";
2803 2803
 
2804 2804
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2805
-		$resql=$this->db->query($sql);
2805
+		$resql = $this->db->query($sql);
2806 2806
 		if ($resql)
2807 2807
 		{
2808 2808
 			if ($this->db->num_rows($resql))
@@ -2820,7 +2820,7 @@  discard block
 block discarded – undo
2820 2820
 				$this->product_label = $obj->product_label;
2821 2821
 				$this->product_description = $obj->product_description;
2822 2822
 				$this->product_type = $obj->product_type;
2823
-				$this->label = $obj->label;					// deprecated. We do not use this field. Only ref and label of product, and description of contract line
2823
+				$this->label = $obj->label; // deprecated. We do not use this field. Only ref and label of product, and description of contract line
2824 2824
 				$this->description = $obj->description;
2825 2825
 				$this->date_commande = $this->db->jdate($obj->date_commande);
2826 2826
 
@@ -2859,7 +2859,7 @@  discard block
 block discarded – undo
2859 2859
 				$this->fk_fournprice = $obj->fk_fournprice;
2860 2860
 				$marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->fk_fournprice, $obj->pa_ht);
2861 2861
 				$this->pa_ht = $marginInfos[0];
2862
-				$this->fk_unit     = $obj->fk_unit;
2862
+				$this->fk_unit = $obj->fk_unit;
2863 2863
 			}
2864 2864
 			$this->db->free($resql);
2865 2865
 
@@ -2867,7 +2867,7 @@  discard block
 block discarded – undo
2867 2867
 		}
2868 2868
 		else
2869 2869
 		{
2870
-			$this->error="Error ".$this->db->lasterror();
2870
+			$this->error = "Error ".$this->db->lasterror();
2871 2871
 			return -1;
2872 2872
 		}
2873 2873
 	}
@@ -2880,38 +2880,38 @@  discard block
 block discarded – undo
2880 2880
 	 *      @param  int		$notrigger	    0=no, 1=yes (no update trigger)
2881 2881
 	 *      @return int         			<0 if KO, >0 if OK
2882 2882
 	 */
2883
-	function update($user, $notrigger=0)
2883
+	function update($user, $notrigger = 0)
2884 2884
 	{
2885 2885
 		global $conf, $langs, $mysoc;
2886 2886
 
2887
-		$error=0;
2887
+		$error = 0;
2888 2888
 
2889 2889
 		// Clean parameters
2890 2890
 		$this->fk_contrat = (int) $this->fk_contrat;
2891 2891
 		$this->fk_product = (int) $this->fk_product;
2892 2892
 		$this->statut = (int) $this->statut;
2893
-		$this->label=trim($this->label);
2894
-		$this->description=trim($this->description);
2895
-		$this->vat_src_code=trim($this->vat_src_code);
2896
-		$this->tva_tx=trim($this->tva_tx);
2897
-		$this->localtax1_tx=trim($this->localtax1_tx);
2898
-		$this->localtax2_tx=trim($this->localtax2_tx);
2899
-		$this->qty=trim($this->qty);
2900
-		$this->remise_percent=trim($this->remise_percent);
2901
-		$this->remise=trim($this->remise);
2893
+		$this->label = trim($this->label);
2894
+		$this->description = trim($this->description);
2895
+		$this->vat_src_code = trim($this->vat_src_code);
2896
+		$this->tva_tx = trim($this->tva_tx);
2897
+		$this->localtax1_tx = trim($this->localtax1_tx);
2898
+		$this->localtax2_tx = trim($this->localtax2_tx);
2899
+		$this->qty = trim($this->qty);
2900
+		$this->remise_percent = trim($this->remise_percent);
2901
+		$this->remise = trim($this->remise);
2902 2902
 		$this->fk_remise_except = (int) $this->fk_remise_except;
2903
-		$this->subprice=price2num($this->subprice);
2904
-		$this->price_ht=price2num($this->price_ht);
2905
-		$this->total_ht=trim($this->total_ht);
2906
-		$this->total_tva=trim($this->total_tva);
2907
-		$this->total_localtax1=trim($this->total_localtax1);
2908
-		$this->total_localtax2=trim($this->total_localtax2);
2909
-		$this->total_ttc=trim($this->total_ttc);
2910
-		$this->info_bits=trim($this->info_bits);
2903
+		$this->subprice = price2num($this->subprice);
2904
+		$this->price_ht = price2num($this->price_ht);
2905
+		$this->total_ht = trim($this->total_ht);
2906
+		$this->total_tva = trim($this->total_tva);
2907
+		$this->total_localtax1 = trim($this->total_localtax1);
2908
+		$this->total_localtax2 = trim($this->total_localtax2);
2909
+		$this->total_ttc = trim($this->total_ttc);
2910
+		$this->info_bits = trim($this->info_bits);
2911 2911
 		$this->fk_user_author = (int) $this->fk_user_author;
2912 2912
 		$this->fk_user_ouverture = (int) $this->fk_user_ouverture;
2913 2913
 		$this->fk_user_cloture = (int) $this->fk_user_cloture;
2914
-		$this->commentaire=trim($this->commentaire);
2914
+		$this->commentaire = trim($this->commentaire);
2915 2915
 		//if (empty($this->subprice)) $this->subprice = 0;
2916 2916
 		if (empty($this->price_ht)) $this->price_ht = 0;
2917 2917
 		if (empty($this->total_ht)) $this->total_ht = 0;
@@ -2921,10 +2921,10 @@  discard block
 block discarded – undo
2921 2921
 		if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
2922 2922
 		if (empty($this->remise_percent)) $this->remise_percent = 0;
2923 2923
 		// For backward compatibility
2924
-		if (empty($this->date_start))      $this->date_start=$this->date_ouverture_prevue;
2925
-		if (empty($this->date_start_real)) $this->date_start=$this->date_ouverture;
2926
-		if (empty($this->date_end))        $this->date_start=$this->date_fin_validite;
2927
-		if (empty($this->date_end_real))   $this->date_start=$this->date_cloture;
2924
+		if (empty($this->date_start))      $this->date_start = $this->date_ouverture_prevue;
2925
+		if (empty($this->date_start_real)) $this->date_start = $this->date_ouverture;
2926
+		if (empty($this->date_end))        $this->date_start = $this->date_fin_validite;
2927
+		if (empty($this->date_end_real))   $this->date_start = $this->date_cloture;
2928 2928
 
2929 2929
 
2930 2930
 		// Check parameters
@@ -2936,14 +2936,14 @@  discard block
 block discarded – undo
2936 2936
 		// la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
2937 2937
 		$localtaxes_type = getLocalTaxesFromRate($this->txtva, 0, $this->societe, $mysoc);
2938 2938
 
2939
-		$tabprice=calcul_price_total($this->qty, $this->price_ht, $this->remise_percent, $this->tva_tx, $this->localtax1_tx, $this->localtax2_tx, 0, 'HT', 0, 1, $mysoc, $localtaxes_type);
2939
+		$tabprice = calcul_price_total($this->qty, $this->price_ht, $this->remise_percent, $this->tva_tx, $this->localtax1_tx, $this->localtax2_tx, 0, 'HT', 0, 1, $mysoc, $localtaxes_type);
2940 2940
 		$this->total_ht  = $tabprice[0];
2941 2941
 		$this->total_tva = $tabprice[1];
2942 2942
 		$this->total_ttc = $tabprice[2];
2943
-		$this->total_localtax1= $tabprice[9];
2944
-		$this->total_localtax2= $tabprice[10];
2943
+		$this->total_localtax1 = $tabprice[9];
2944
+		$this->total_localtax2 = $tabprice[10];
2945 2945
 
2946
-	    if (empty($this->pa_ht)) $this->pa_ht=0;
2946
+	    if (empty($this->pa_ht)) $this->pa_ht = 0;
2947 2947
 
2948 2948
 		// if buy price not defined, define buyprice as configured in margin admin
2949 2949
 		if ($this->pa_ht == 0)
@@ -2966,52 +2966,52 @@  discard block
 block discarded – undo
2966 2966
 
2967 2967
 		// Update request
2968 2968
 		$sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
2969
-		$sql.= " fk_contrat=".$this->fk_contrat.",";
2970
-		$sql.= " fk_product=".($this->fk_product?"'".$this->db->escape($this->fk_product)."'":'null').",";
2971
-		$sql.= " statut=".$this->statut.",";
2972
-		$sql.= " label='".$this->db->escape($this->label)."',";
2973
-		$sql.= " description='".$this->db->escape($this->description)."',";
2974
-		$sql.= " date_commande=".($this->date_commande!=''?"'".$this->db->idate($this->date_commande)."'":"null").",";
2975
-		$sql.= " date_ouverture_prevue=".($this->date_ouverture_prevue!=''?"'".$this->db->idate($this->date_ouverture_prevue)."'":"null").",";
2976
-		$sql.= " date_ouverture=".($this->date_ouverture!=''?"'".$this->db->idate($this->date_ouverture)."'":"null").",";
2977
-		$sql.= " date_fin_validite=".($this->date_fin_validite!=''?"'".$this->db->idate($this->date_fin_validite)."'":"null").",";
2978
-		$sql.= " date_cloture=".($this->date_cloture!=''?"'".$this->db->idate($this->date_cloture)."'":"null").",";
2979
-		$sql.= " vat_src_code='".$this->db->escape($this->vat_src_code)."',";
2980
-		$sql.= " tva_tx=".price2num($this->tva_tx).",";
2981
-		$sql.= " localtax1_tx=".price2num($this->localtax1_tx).",";
2982
-		$sql.= " localtax2_tx=".price2num($this->localtax2_tx).",";
2983
-		$sql.= " qty=".price2num($this->qty).",";
2984
-		$sql.= " remise_percent=".price2num($this->remise_percent).",";
2985
-		$sql.= " remise=".($this->remise?price2num($this->remise):"null").",";
2986
-		$sql.= " fk_remise_except=".($this->fk_remise_except > 0?$this->fk_remise_except:"null").",";
2987
-		$sql.= " subprice=".($this->subprice != '' ? $this->subprice : "null").",";
2988
-		$sql.= " price_ht=".($this->price_ht != '' ? $this->price_ht : "null").",";
2989
-		$sql.= " total_ht=".$this->total_ht.",";
2990
-		$sql.= " total_tva=".$this->total_tva.",";
2991
-		$sql.= " total_localtax1=".$this->total_localtax1.",";
2992
-		$sql.= " total_localtax2=".$this->total_localtax2.",";
2993
-		$sql.= " total_ttc=".$this->total_ttc.",";
2994
-		$sql.= " fk_product_fournisseur_price=".(!empty($this->fk_fournprice)?$this->fk_fournprice:"NULL").",";
2995
-		$sql.= " buy_price_ht='".price2num($this->pa_ht)."',";
2996
-		$sql.= " info_bits='".$this->db->escape($this->info_bits)."',";
2997
-		$sql.= " fk_user_author=".($this->fk_user_author >= 0?$this->fk_user_author:"NULL").",";
2998
-		$sql.= " fk_user_ouverture=".($this->fk_user_ouverture > 0?$this->fk_user_ouverture:"NULL").",";
2999
-		$sql.= " fk_user_cloture=".($this->fk_user_cloture > 0?$this->fk_user_cloture:"NULL").",";
3000
-		$sql.= " commentaire='".$this->db->escape($this->commentaire)."',";
3001
-		$sql.= " fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
3002
-		$sql.= " WHERE rowid=".$this->id;
2969
+		$sql .= " fk_contrat=".$this->fk_contrat.",";
2970
+		$sql .= " fk_product=".($this->fk_product ? "'".$this->db->escape($this->fk_product)."'" : 'null').",";
2971
+		$sql .= " statut=".$this->statut.",";
2972
+		$sql .= " label='".$this->db->escape($this->label)."',";
2973
+		$sql .= " description='".$this->db->escape($this->description)."',";
2974
+		$sql .= " date_commande=".($this->date_commande != '' ? "'".$this->db->idate($this->date_commande)."'" : "null").",";
2975
+		$sql .= " date_ouverture_prevue=".($this->date_ouverture_prevue != '' ? "'".$this->db->idate($this->date_ouverture_prevue)."'" : "null").",";
2976
+		$sql .= " date_ouverture=".($this->date_ouverture != '' ? "'".$this->db->idate($this->date_ouverture)."'" : "null").",";
2977
+		$sql .= " date_fin_validite=".($this->date_fin_validite != '' ? "'".$this->db->idate($this->date_fin_validite)."'" : "null").",";
2978
+		$sql .= " date_cloture=".($this->date_cloture != '' ? "'".$this->db->idate($this->date_cloture)."'" : "null").",";
2979
+		$sql .= " vat_src_code='".$this->db->escape($this->vat_src_code)."',";
2980
+		$sql .= " tva_tx=".price2num($this->tva_tx).",";
2981
+		$sql .= " localtax1_tx=".price2num($this->localtax1_tx).",";
2982
+		$sql .= " localtax2_tx=".price2num($this->localtax2_tx).",";
2983
+		$sql .= " qty=".price2num($this->qty).",";
2984
+		$sql .= " remise_percent=".price2num($this->remise_percent).",";
2985
+		$sql .= " remise=".($this->remise ?price2num($this->remise) : "null").",";
2986
+		$sql .= " fk_remise_except=".($this->fk_remise_except > 0 ? $this->fk_remise_except : "null").",";
2987
+		$sql .= " subprice=".($this->subprice != '' ? $this->subprice : "null").",";
2988
+		$sql .= " price_ht=".($this->price_ht != '' ? $this->price_ht : "null").",";
2989
+		$sql .= " total_ht=".$this->total_ht.",";
2990
+		$sql .= " total_tva=".$this->total_tva.",";
2991
+		$sql .= " total_localtax1=".$this->total_localtax1.",";
2992
+		$sql .= " total_localtax2=".$this->total_localtax2.",";
2993
+		$sql .= " total_ttc=".$this->total_ttc.",";
2994
+		$sql .= " fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "NULL").",";
2995
+		$sql .= " buy_price_ht='".price2num($this->pa_ht)."',";
2996
+		$sql .= " info_bits='".$this->db->escape($this->info_bits)."',";
2997
+		$sql .= " fk_user_author=".($this->fk_user_author >= 0 ? $this->fk_user_author : "NULL").",";
2998
+		$sql .= " fk_user_ouverture=".($this->fk_user_ouverture > 0 ? $this->fk_user_ouverture : "NULL").",";
2999
+		$sql .= " fk_user_cloture=".($this->fk_user_cloture > 0 ? $this->fk_user_cloture : "NULL").",";
3000
+		$sql .= " commentaire='".$this->db->escape($this->commentaire)."',";
3001
+		$sql .= " fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
3002
+		$sql .= " WHERE rowid=".$this->id;
3003 3003
 
3004 3004
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
3005 3005
 		$resql = $this->db->query($sql);
3006
-		if (! $resql)
3006
+		if (!$resql)
3007 3007
 		{
3008
-			$this->error="Error ".$this->db->lasterror();
3008
+			$this->error = "Error ".$this->db->lasterror();
3009 3009
 			$error++;
3010 3010
 		}
3011 3011
 
3012
-		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used
3012
+		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) // For avoid conflicts if trigger used
3013 3013
 		{
3014
-			$result=$this->insertExtraFields();
3014
+			$result = $this->insertExtraFields();
3015 3015
 			if ($result < 0)
3016 3016
 			{
3017 3017
 				$error++;
@@ -3019,39 +3019,39 @@  discard block
 block discarded – undo
3019 3019
 		}
3020 3020
 
3021 3021
 		// If we change a planned date (start or end), sync dates for all services
3022
-		if (! $error && ! empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES))
3022
+		if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES))
3023 3023
 		{
3024 3024
 			if ($this->date_ouverture_prevue != $this->oldcopy->date_ouverture_prevue)
3025 3025
 			{
3026
-				$sql ='UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3027
-				$sql.= " date_ouverture_prevue = ".($this->date_ouverture_prevue!=''?"'".$this->db->idate($this->date_ouverture_prevue)."'":"null");
3028
-				$sql.= " WHERE fk_contrat = ".$this->fk_contrat;
3026
+				$sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3027
+				$sql .= " date_ouverture_prevue = ".($this->date_ouverture_prevue != '' ? "'".$this->db->idate($this->date_ouverture_prevue)."'" : "null");
3028
+				$sql .= " WHERE fk_contrat = ".$this->fk_contrat;
3029 3029
 
3030 3030
 				$resql = $this->db->query($sql);
3031
-				if (! $resql)
3031
+				if (!$resql)
3032 3032
 				{
3033 3033
 					$error++;
3034
-					$this->error="Error ".$this->db->lasterror();
3034
+					$this->error = "Error ".$this->db->lasterror();
3035 3035
 				}
3036 3036
 			}
3037 3037
 			if ($this->date_fin_validite != $this->oldcopy->date_fin_validite)
3038 3038
 			{
3039
-				$sql ='UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3040
-				$sql.= " date_fin_validite = ".($this->date_fin_validite!=''?"'".$this->db->idate($this->date_fin_validite)."'":"null");
3041
-				$sql.= " WHERE fk_contrat = ".$this->fk_contrat;
3039
+				$sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
3040
+				$sql .= " date_fin_validite = ".($this->date_fin_validite != '' ? "'".$this->db->idate($this->date_fin_validite)."'" : "null");
3041
+				$sql .= " WHERE fk_contrat = ".$this->fk_contrat;
3042 3042
 
3043 3043
 				$resql = $this->db->query($sql);
3044
-				if (! $resql)
3044
+				if (!$resql)
3045 3045
 				{
3046 3046
 					$error++;
3047
-					$this->error="Error ".$this->db->lasterror();
3047
+					$this->error = "Error ".$this->db->lasterror();
3048 3048
 				}
3049 3049
 			}
3050 3050
 		}
3051 3051
 
3052
-		if (! $error && ! $notrigger) {
3052
+		if (!$error && !$notrigger) {
3053 3053
 	        // Call trigger
3054
-	        $result=$this->call_trigger('LINECONTRACT_UPDATE', $user);
3054
+	        $result = $this->call_trigger('LINECONTRACT_UPDATE', $user);
3055 3055
 	        if ($result < 0) {
3056 3056
                 $error++;
3057 3057
                 $this->db->rollback();
@@ -3059,13 +3059,13 @@  discard block
 block discarded – undo
3059 3059
 	        // End call triggers
3060 3060
 		}
3061 3061
 
3062
-		if (! $error)
3062
+		if (!$error)
3063 3063
 		{
3064 3064
         	$this->db->commit();
3065 3065
 			return 1;
3066 3066
 		} else {
3067 3067
 			$this->db->rollback();
3068
-			$this->errors[]=$this->error;
3068
+			$this->errors[] = $this->error;
3069 3069
 			return -1;
3070 3070
 		}
3071 3071
 	}
@@ -3085,16 +3085,16 @@  discard block
 block discarded – undo
3085 3085
 
3086 3086
 		// Mise a jour ligne en base
3087 3087
 		$sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
3088
-		$sql.= " total_ht=".price2num($this->total_ht,'MT')."";
3089
-		$sql.= ",total_tva=".price2num($this->total_tva,'MT')."";
3090
-		$sql.= ",total_localtax1=".price2num($this->total_localtax1,'MT')."";
3091
-		$sql.= ",total_localtax2=".price2num($this->total_localtax2,'MT')."";
3092
-		$sql.= ",total_ttc=".price2num($this->total_ttc,'MT')."";
3093
-		$sql.= " WHERE rowid = ".$this->id;
3088
+		$sql .= " total_ht=".price2num($this->total_ht, 'MT')."";
3089
+		$sql .= ",total_tva=".price2num($this->total_tva, 'MT')."";
3090
+		$sql .= ",total_localtax1=".price2num($this->total_localtax1, 'MT')."";
3091
+		$sql .= ",total_localtax2=".price2num($this->total_localtax2, 'MT')."";
3092
+		$sql .= ",total_ttc=".price2num($this->total_ttc, 'MT')."";
3093
+		$sql .= " WHERE rowid = ".$this->id;
3094 3094
 
3095 3095
 		dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
3096 3096
 
3097
-		$resql=$this->db->query($sql);
3097
+		$resql = $this->db->query($sql);
3098 3098
 		if ($resql)
3099 3099
 		{
3100 3100
 			$this->db->commit();
@@ -3102,7 +3102,7 @@  discard block
 block discarded – undo
3102 3102
 		}
3103 3103
 		else
3104 3104
 		{
3105
-			$this->error=$this->db->error();
3105
+			$this->error = $this->db->error();
3106 3106
 			$this->db->rollback();
3107 3107
 			return -2;
3108 3108
 		}
@@ -3121,43 +3121,43 @@  discard block
 block discarded – undo
3121 3121
 
3122 3122
 		// Insertion dans la base
3123 3123
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
3124
-		$sql.= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
3125
-		$sql.= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
3126
-		$sql.= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
3127
-		$sql.= " info_bits,";
3128
-		$sql.= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
3129
-		if ($this->date_ouverture_prevue > 0) { $sql.= ",date_ouverture_prevue"; }
3130
-		if ($this->date_fin_validite > 0)     { $sql.= ",date_fin_validite"; }
3131
-		$sql.= ") VALUES ($this->fk_contrat, '', '" . $this->db->escape($this->description) . "',";
3132
-		$sql.= ($this->fk_product>0 ? $this->fk_product : "null").",";
3133
-		$sql.= " '".$this->db->escape($this->qty)."',";
3134
-		$sql.= " '".$this->db->escape($this->vat_src_code)."',";
3135
-		$sql.= " '".$this->db->escape($this->tva_tx)."',";
3136
-		$sql.= " '".$this->db->escape($this->localtax1_tx)."',";
3137
-		$sql.= " '".$this->db->escape($this->localtax2_tx)."',";
3138
-		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
3139
-		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
3140
-		$sql.= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
3141
-		$sql.= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3142
-		$sql.= " '".$this->db->escape($this->info_bits)."',";
3143
-		$sql.= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3144
-		if ($this->fk_fournprice > 0) $sql.= ' '.$this->fk_fournprice.',';
3145
-		else $sql.= ' null,';
3146
-		if ($this->pa_ht > 0) $sql.= ' '.price2num($this->pa_ht);
3147
-		else $sql.= ' null';
3148
-		if ($this->date_ouverture > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture)."'"; }
3149
-		if ($this->date_cloture > 0)   { $sql.= ",'".$this->db->idate($this->date_cloture)."'"; }
3150
-		$sql.= ")";
3124
+		$sql .= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
3125
+		$sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
3126
+		$sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
3127
+		$sql .= " info_bits,";
3128
+		$sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
3129
+		if ($this->date_ouverture_prevue > 0) { $sql .= ",date_ouverture_prevue"; }
3130
+		if ($this->date_fin_validite > 0) { $sql .= ",date_fin_validite"; }
3131
+		$sql .= ") VALUES ($this->fk_contrat, '', '".$this->db->escape($this->description)."',";
3132
+		$sql .= ($this->fk_product > 0 ? $this->fk_product : "null").",";
3133
+		$sql .= " '".$this->db->escape($this->qty)."',";
3134
+		$sql .= " '".$this->db->escape($this->vat_src_code)."',";
3135
+		$sql .= " '".$this->db->escape($this->tva_tx)."',";
3136
+		$sql .= " '".$this->db->escape($this->localtax1_tx)."',";
3137
+		$sql .= " '".$this->db->escape($this->localtax2_tx)."',";
3138
+		$sql .= " '".$this->db->escape($this->localtax1_type)."',";
3139
+		$sql .= " '".$this->db->escape($this->localtax2_type)."',";
3140
+		$sql .= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
3141
+		$sql .= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3142
+		$sql .= " '".$this->db->escape($this->info_bits)."',";
3143
+		$sql .= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3144
+		if ($this->fk_fournprice > 0) $sql .= ' '.$this->fk_fournprice.',';
3145
+		else $sql .= ' null,';
3146
+		if ($this->pa_ht > 0) $sql .= ' '.price2num($this->pa_ht);
3147
+		else $sql .= ' null';
3148
+		if ($this->date_ouverture > 0) { $sql .= ",'".$this->db->idate($this->date_ouverture)."'"; }
3149
+		if ($this->date_cloture > 0) { $sql .= ",'".$this->db->idate($this->date_cloture)."'"; }
3150
+		$sql .= ")";
3151 3151
 
3152 3152
 		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
3153 3153
 
3154
-		$resql=$this->db->query($sql);
3154
+		$resql = $this->db->query($sql);
3155 3155
 		if ($resql)
3156 3156
 		{
3157 3157
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
3158 3158
 
3159 3159
 			// Insert of extrafields
3160
-			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used
3160
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) // For avoid conflicts if trigger used
3161 3161
 			{
3162 3162
 				$result = $this->insertExtraFields();
3163 3163
 				if ($result < 0)
@@ -3184,7 +3184,7 @@  discard block
 block discarded – undo
3184 3184
 		else
3185 3185
 		{
3186 3186
 			$this->db->rollback();
3187
-			$this->error=$this->db->error()." sql=".$sql;
3187
+			$this->error = $this->db->error()." sql=".$sql;
3188 3188
 			return -1;
3189 3189
 		}
3190 3190
 	}
@@ -3208,15 +3208,15 @@  discard block
 block discarded – undo
3208 3208
 
3209 3209
 		$this->db->begin();
3210 3210
 
3211
-		$sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = ".ContratLigne::STATUS_OPEN.",";
3212
-		$sql .= " date_ouverture = " . (dol_strlen($date) != 0 ? "'" . $this->db->idate($date) . "'" : "null") . ",";
3213
-		if ($date_end >= 0) $sql .= " date_fin_validite = " . (dol_strlen($date_end) != 0 ? "'" . $this->db->idate($date_end) . "'" : "null") . ",";
3214
-		$sql .= " fk_user_ouverture = " . $user->id . ",";
3211
+		$sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".ContratLigne::STATUS_OPEN.",";
3212
+		$sql .= " date_ouverture = ".(dol_strlen($date) != 0 ? "'".$this->db->idate($date)."'" : "null").",";
3213
+		if ($date_end >= 0) $sql .= " date_fin_validite = ".(dol_strlen($date_end) != 0 ? "'".$this->db->idate($date_end)."'" : "null").",";
3214
+		$sql .= " fk_user_ouverture = ".$user->id.",";
3215 3215
 		$sql .= " date_cloture = null,";
3216
-		$sql .= " commentaire = '" . $this->db->escape($comment) . "'";
3217
-		$sql .= " WHERE rowid = " . $this->id . " AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
3216
+		$sql .= " commentaire = '".$this->db->escape($comment)."'";
3217
+		$sql .= " WHERE rowid = ".$this->id." AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
3218 3218
 
3219
-		dol_syslog(get_class($this) . "::active_line", LOG_DEBUG);
3219
+		dol_syslog(get_class($this)."::active_line", LOG_DEBUG);
3220 3220
 		$resql = $this->db->query($sql);
3221 3221
 		if ($resql) {
3222 3222
 			// Call trigger
@@ -3224,7 +3224,7 @@  discard block
 block discarded – undo
3224 3224
 			if ($result < 0) $error++;
3225 3225
 			// End call triggers
3226 3226
 
3227
-			if (! $error)
3227
+			if (!$error)
3228 3228
 			{
3229 3229
 				$this->statut = ContratLigne::STATUS_OPEN;
3230 3230
 				$this->date_ouverture = $date;
@@ -3258,7 +3258,7 @@  discard block
 block discarded – undo
3258 3258
      * @param    int	$notrigger		1=Does not execute triggers, 0=Execute triggers
3259 3259
 	 * @return int                    	<0 if KO, >0 if OK
3260 3260
 	 */
3261
-	function close_line($user, $date_end, $comment = '', $notrigger=0)
3261
+	function close_line($user, $date_end, $comment = '', $notrigger = 0)
3262 3262
 	{
3263 3263
         // phpcs:enable
3264 3264
 		global $langs, $conf;
@@ -3274,16 +3274,16 @@  discard block
 block discarded – undo
3274 3274
 
3275 3275
 		$this->db->begin();
3276 3276
 
3277
-		$sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = ".ContratLigne::STATUS_CLOSED.",";
3278
-		$sql .= " date_cloture = '" . $this->db->idate($date_end) . "',";
3279
-		$sql .= " fk_user_cloture = " . $user->id . ",";
3280
-		$sql .= " commentaire = '" . $this->db->escape($comment) . "'";
3281
-		$sql .= " WHERE rowid = " . $this->id . " AND statut = ".ContratLigne::STATUS_OPEN;
3277
+		$sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".ContratLigne::STATUS_CLOSED.",";
3278
+		$sql .= " date_cloture = '".$this->db->idate($date_end)."',";
3279
+		$sql .= " fk_user_cloture = ".$user->id.",";
3280
+		$sql .= " commentaire = '".$this->db->escape($comment)."'";
3281
+		$sql .= " WHERE rowid = ".$this->id." AND statut = ".ContratLigne::STATUS_OPEN;
3282 3282
 
3283 3283
 		$resql = $this->db->query($sql);
3284 3284
 		if ($resql)
3285 3285
 		{
3286
-			if (! $notrigger)
3286
+			if (!$notrigger)
3287 3287
 			{
3288 3288
 				// Call trigger
3289 3289
 				$result = $this->call_trigger('LINECONTRACT_CLOSE', $user);
Please login to merge, or discard this patch.
Braces   +348 added lines, -248 removed lines patch added patch discarded remove patch
@@ -234,15 +234,13 @@  discard block
 block discarded – undo
234 234
 			if ( $numref != "")
235 235
 			{
236 236
 				return $numref;
237
-			}
238
-			else
237
+			} else
239 238
 			{
240 239
 				$this->error = $obj->error;
241 240
 				dol_print_error($db,get_class($this)."::getNextValue ".$obj->error);
242 241
 				return "";
243 242
 			}
244
-		}
245
-		else
243
+		} else
246 244
 		{
247 245
 			$langs->load("errors");
248 246
 			print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete");
@@ -309,7 +307,9 @@  discard block
 block discarded – undo
309 307
 	 */
310 308
 	function activateAll($user, $date_start='', $notrigger=0, $comment='')
311 309
 	{
312
-		if (empty($date_start)) $date_start = dol_now();
310
+		if (empty($date_start)) {
311
+		    $date_start = dol_now();
312
+		}
313 313
 
314 314
 		$this->db->begin();
315 315
 
@@ -339,15 +339,16 @@  discard block
 block discarded – undo
339 339
 		if (! $error && $this->statut == 0)
340 340
 		{
341 341
 			$result=$this->validate($user, '', $notrigger);
342
-			if ($result < 0) $error++;
342
+			if ($result < 0) {
343
+			    $error++;
344
+			}
343 345
 		}
344 346
 
345 347
 		if (! $error)
346 348
 		{
347 349
 			$this->db->commit();
348 350
 			return 1;
349
-		}
350
-		else
351
+		} else
351 352
 		{
352 353
 			$this->db->rollback();
353 354
 			return -1;
@@ -396,15 +397,16 @@  discard block
 block discarded – undo
396 397
 		if (! $error && $this->statut == 0)
397 398
 		{
398 399
 			$result=$this->validate($user, '', $notrigger);
399
-			if ($result < 0) $error++;
400
+			if ($result < 0) {
401
+			    $error++;
402
+			}
400 403
 		}
401 404
 
402 405
         if (! $error)
403 406
         {
404 407
             $this->db->commit();
405 408
             return 1;
406
-        }
407
-        else
409
+        } else
408 410
         {
409 411
             $this->db->rollback();
410 412
             return -1;
@@ -444,12 +446,12 @@  discard block
 block discarded – undo
444 446
 		if ($force_number)
445 447
 		{
446 448
 			$num = $force_number;
447
-		}
448
-		else if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
449
+		} else if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) {
450
+		    // empty should not happened, but when it occurs, the test save life
449 451
 		{
450 452
 			$num = $this->getNextNumRef($this->thirdparty);
451 453
 		}
452
-		else
454
+		} else
453 455
 		{
454 456
 			$num = $this->ref;
455 457
 		}
@@ -522,8 +524,7 @@  discard block
 block discarded – undo
522 524
 				$this->brouillon = 0;
523 525
 				$this->date_validation = $now;
524 526
 			}
525
-		}
526
-		else
527
+		} else
527 528
 		{
528 529
 			$error++;
529 530
 		}
@@ -532,8 +533,7 @@  discard block
 block discarded – undo
532 533
 		{
533 534
 			$this->db->commit();
534 535
 			return 1;
535
-		}
536
-		else
536
+		} else
537 537
 		{
538 538
 			$this->db->rollback();
539 539
 			return -1;
@@ -597,8 +597,7 @@  discard block
 block discarded – undo
597 597
 		{
598 598
 			$this->db->commit();
599 599
 			return 1;
600
-		}
601
-		else
600
+		} else
602 601
 		{
603 602
 			$this->db->rollback();
604 603
 			return -1;
@@ -625,8 +624,11 @@  discard block
 block discarded – undo
625 624
 		$sql.= " fk_commercial_signature, fk_commercial_suivi,";
626 625
 		$sql.= " note_private, note_public, model_pdf, extraparams";
627 626
 		$sql.= " FROM ".MAIN_DB_PREFIX."contrat";
628
-		if (! $id) $sql.=" WHERE entity IN (".getEntity('contract').")";
629
-		else $sql.= " WHERE rowid=".$id;
627
+		if (! $id) {
628
+		    $sql.=" WHERE entity IN (".getEntity('contract').")";
629
+		} else {
630
+		    $sql.= " WHERE rowid=".$id;
631
+		}
630 632
 		if ($ref_customer)
631 633
 		{
632 634
 			$sql.= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
@@ -695,15 +697,13 @@  discard block
 block discarded – undo
695 697
 				}
696 698
 
697 699
 				return $this->id;
698
-			}
699
-			else
700
+			} else
700 701
 			{
701 702
 				dol_syslog(get_class($this)."::fetch Contract not found");
702 703
 				$this->error="Contract not found";
703 704
 				return 0;
704 705
 			}
705
-		}
706
-		else
706
+		} else
707 707
 		{
708 708
 			dol_syslog(get_class($this)."::fetch Error searching contract");
709 709
 			$this->error=$this->db->error();
@@ -835,10 +835,18 @@  discard block
 block discarded – undo
835 835
 				//dol_syslog("1 ".$line->desc);
836 836
 				//dol_syslog("2 ".$line->product_desc);
837 837
 
838
-				if ($line->statut == ContratLigne::STATUS_INITIAL) $this->nbofserviceswait++;
839
-				if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++;
840
-				if ($line->statut == ContratLigne::STATUS_OPEN && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++;
841
-				if ($line->statut == ContratLigne::STATUS_CLOSED) $this->nbofservicesclosed++;
838
+				if ($line->statut == ContratLigne::STATUS_INITIAL) {
839
+				    $this->nbofserviceswait++;
840
+				}
841
+				if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) {
842
+				    $this->nbofservicesopened++;
843
+				}
844
+				if ($line->statut == ContratLigne::STATUS_OPEN && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) {
845
+				    $this->nbofservicesexpired++;
846
+				}
847
+				if ($line->statut == ContratLigne::STATUS_CLOSED) {
848
+				    $this->nbofservicesclosed++;
849
+				}
842 850
 
843 851
 				$total_ttc+=$objp->total_ttc;   // TODO Not saved into database
844 852
                 $total_vat+=$objp->total_tva;
@@ -848,8 +856,7 @@  discard block
 block discarded – undo
848 856
 				$pos++;
849 857
 			}
850 858
 			$this->db->free($result);
851
-		}
852
-		else
859
+		} else
853 860
 		{
854 861
 			dol_syslog(get_class($this)."::Fetch Erreur lecture des lignes de contrats liees aux produits");
855 862
 			return -3;
@@ -888,7 +895,9 @@  discard block
 block discarded – undo
888 895
 			$this->error.=$langs->trans("ErrorFieldRequired",$langs->trans("SalesRepresentativeFollowUp"));
889 896
 			$paramsok=0;
890 897
 		}
891
-		if (! $paramsok) return -1;
898
+		if (! $paramsok) {
899
+		    return -1;
900
+		}
892 901
 
893 902
 
894 903
 		$this->db->begin();
@@ -959,21 +968,28 @@  discard block
 block discarded – undo
959 968
 			if (! $error)
960 969
 			{
961 970
     			$result=$this->add_contact($this->commercial_signature_id,'SALESREPSIGN','internal');
962
-    			if ($result < 0) $error++;
971
+    			if ($result < 0) {
972
+    			    $error++;
973
+    			}
963 974
 			}
964 975
 
965 976
 			// Insert business contacts ('SALESREPFOLL','contrat')
966 977
 			if (! $error)
967 978
 			{
968 979
                 $result=$this->add_contact($this->commercial_suivi_id,'SALESREPFOLL','internal');
969
-			    if ($result < 0) $error++;
980
+			    if ($result < 0) {
981
+			        $error++;
982
+			    }
970 983
 			}
971 984
 
972 985
 			if (! $error)
973 986
 			{
974
-				if (! empty($this->linkedObjectsIds) && empty($this->linked_objects))	// To use new linkedObjectsIds instead of old linked_objects
987
+				if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) {
988
+				    // To use new linkedObjectsIds instead of old linked_objects
975 989
 				{
976
-					$this->linked_objects = $this->linkedObjectsIds;	// TODO Replace linked_objects with linkedObjectsIds
990
+					$this->linked_objects = $this->linkedObjectsIds;
991
+				}
992
+				// TODO Replace linked_objects with linkedObjectsIds
977 993
 				}
978 994
 
979 995
 				// Add object linked
@@ -981,19 +997,20 @@  discard block
 block discarded – undo
981 997
     			{
982 998
     			    foreach($this->linked_objects as $origin => $tmp_origin_id)
983 999
     			    {
984
-    			        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, ...))
1000
+    			        if (is_array($tmp_origin_id)) {
1001
+    			            // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
985 1002
     			        {
986 1003
     			            foreach($tmp_origin_id as $origin_id)
987 1004
     			            {
988 1005
     			                $ret = $this->add_object_linked($origin, $origin_id);
1006
+    			        }
989 1007
     			                if (! $ret)
990 1008
     			                {
991 1009
     			                    $this->error=$this->db->lasterror();
992 1010
     			                    $error++;
993 1011
     			                }
994 1012
     			            }
995
-    			        }
996
-    			        else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
1013
+    			        } else                                // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
997 1014
     			        {
998 1015
     			            $origin_id = $tmp_origin_id;
999 1016
     			            $ret = $this->add_object_linked($origin, $origin_id);
@@ -1006,13 +1023,17 @@  discard block
 block discarded – undo
1006 1023
     			    }
1007 1024
     			}
1008 1025
 
1009
-    			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id))   // Get contact from origin object
1026
+    			if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id)) {
1027
+    			    // Get contact from origin object
1010 1028
     			{
1011 1029
     			    $originforcontact = $this->origin;
1030
+    			}
1012 1031
     			    $originidforcontact = $this->origin_id;
1013
-    			    if ($originforcontact == 'shipping')     // shipment and order share the same contacts. If creating from shipment we take data of order
1032
+    			    if ($originforcontact == 'shipping') {
1033
+    			        // shipment and order share the same contacts. If creating from shipment we take data of order
1014 1034
     			    {
1015 1035
     			        require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
1036
+    			    }
1016 1037
     			        $exp = new Expedition($db);
1017 1038
     			        $exp->fetch($this->origin_id);
1018 1039
     			        $exp->fetchObjectLinked();
@@ -1035,13 +1056,17 @@  discard block
 block discarded – undo
1035 1056
     			    {
1036 1057
     			        while($objcontact = $this->db->fetch_object($resqlcontact))
1037 1058
     			        {
1038
-    			            if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) continue;    // ignore this, already forced previously
1059
+    			            if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
1060
+    			                continue;
1061
+    			            }
1062
+    			            // ignore this, already forced previously
1039 1063
 
1040 1064
     			            //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
1041 1065
     			            $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
1042 1066
     			        }
1067
+    			    } else {
1068
+    			        dol_print_error($resqlcontact);
1043 1069
     			    }
1044
-    			    else dol_print_error($resqlcontact);
1045 1070
     			}
1046 1071
 			}
1047 1072
 
@@ -1056,23 +1081,20 @@  discard block
 block discarded – undo
1056 1081
 				{
1057 1082
 					$this->db->commit();
1058 1083
 					return $this->id;
1059
-				}
1060
-				else
1084
+				} else
1061 1085
 				{
1062 1086
 					dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR);
1063 1087
 					$this->db->rollback();
1064 1088
 					return -3;
1065 1089
 				}
1066
-			}
1067
-			else
1090
+			} else
1068 1091
 			{
1069 1092
 				$this->error="Failed to add contract";
1070 1093
 				dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
1071 1094
 				$this->db->rollback();
1072 1095
 				return -2;
1073 1096
 			}
1074
-		}
1075
-		else
1097
+		} else
1076 1098
 		{
1077 1099
 			$this->error=$langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
1078 1100
 
@@ -1117,7 +1139,9 @@  discard block
 block discarded – undo
1117 1139
 		{
1118 1140
 			// Delete linked object
1119 1141
 			$res = $this->deleteObjectLinked();
1120
-			if ($res < 0) $error++;
1142
+			if ($res < 0) {
1143
+			    $error++;
1144
+			}
1121 1145
 		}
1122 1146
 
1123 1147
 		if (! $error)
@@ -1226,8 +1250,7 @@  discard block
 block discarded – undo
1226 1250
 		{
1227 1251
 			$this->db->commit();
1228 1252
 			return 1;
1229
-		}
1230
-		else
1253
+		} else
1231 1254
 		{
1232 1255
 			$this->error=$this->db->lasterror();
1233 1256
 			$this->db->rollback();
@@ -1248,25 +1271,61 @@  discard block
 block discarded – undo
1248 1271
 		$error=0;
1249 1272
 
1250 1273
 		// Clean parameters
1251
-		if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) $this->fk_commercial_signature = $this->commercial_signature_id;
1252
-		if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) $this->fk_commercial_suivi = $this->commercial_suivi_id;
1253
-		if (empty($this->fk_soc) && $this->socid > 0) $this->fk_soc = $this->socid;
1254
-		if (empty($this->fk_project) && $this->projet > 0) $this->fk_project = $this->projet;
1255
-
1256
-		if (isset($this->ref)) $this->ref=trim($this->ref);
1257
-		if (isset($this->ref_customer)) $this->ref_customer=trim($this->ref_customer);
1258
-		if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier);
1259
-		if (isset($this->ref_ext)) $this->ref_ext=trim($this->ref_ext);
1260
-		if (isset($this->entity)) $this->entity=trim($this->entity);
1261
-		if (isset($this->statut)) $this->statut=(int) $this->statut;
1262
-		if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc);
1263
-		if (isset($this->fk_commercial_signature)) $this->fk_commercial_signature=trim($this->fk_commercial_signature);
1264
-		if (isset($this->fk_commercial_suivi)) $this->fk_commercial_suivi=trim($this->fk_commercial_suivi);
1265
-		if (isset($this->fk_user_mise_en_service)) $this->fk_user_mise_en_service=trim($this->fk_user_mise_en_service);
1266
-		if (isset($this->fk_user_cloture)) $this->fk_user_cloture=trim($this->fk_user_cloture);
1267
-		if (isset($this->note_private)) $this->note_private=trim($this->note_private);
1268
-		if (isset($this->note_public)) $this->note_public=trim($this->note_public);
1269
-		if (isset($this->import_key)) $this->import_key=trim($this->import_key);
1274
+		if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
1275
+		    $this->fk_commercial_signature = $this->commercial_signature_id;
1276
+		}
1277
+		if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
1278
+		    $this->fk_commercial_suivi = $this->commercial_suivi_id;
1279
+		}
1280
+		if (empty($this->fk_soc) && $this->socid > 0) {
1281
+		    $this->fk_soc = $this->socid;
1282
+		}
1283
+		if (empty($this->fk_project) && $this->projet > 0) {
1284
+		    $this->fk_project = $this->projet;
1285
+		}
1286
+
1287
+		if (isset($this->ref)) {
1288
+		    $this->ref=trim($this->ref);
1289
+		}
1290
+		if (isset($this->ref_customer)) {
1291
+		    $this->ref_customer=trim($this->ref_customer);
1292
+		}
1293
+		if (isset($this->ref_supplier)) {
1294
+		    $this->ref_supplier=trim($this->ref_supplier);
1295
+		}
1296
+		if (isset($this->ref_ext)) {
1297
+		    $this->ref_ext=trim($this->ref_ext);
1298
+		}
1299
+		if (isset($this->entity)) {
1300
+		    $this->entity=trim($this->entity);
1301
+		}
1302
+		if (isset($this->statut)) {
1303
+		    $this->statut=(int) $this->statut;
1304
+		}
1305
+		if (isset($this->fk_soc)) {
1306
+		    $this->fk_soc=trim($this->fk_soc);
1307
+		}
1308
+		if (isset($this->fk_commercial_signature)) {
1309
+		    $this->fk_commercial_signature=trim($this->fk_commercial_signature);
1310
+		}
1311
+		if (isset($this->fk_commercial_suivi)) {
1312
+		    $this->fk_commercial_suivi=trim($this->fk_commercial_suivi);
1313
+		}
1314
+		if (isset($this->fk_user_mise_en_service)) {
1315
+		    $this->fk_user_mise_en_service=trim($this->fk_user_mise_en_service);
1316
+		}
1317
+		if (isset($this->fk_user_cloture)) {
1318
+		    $this->fk_user_cloture=trim($this->fk_user_cloture);
1319
+		}
1320
+		if (isset($this->note_private)) {
1321
+		    $this->note_private=trim($this->note_private);
1322
+		}
1323
+		if (isset($this->note_public)) {
1324
+		    $this->note_public=trim($this->note_public);
1325
+		}
1326
+		if (isset($this->import_key)) {
1327
+		    $this->import_key=trim($this->import_key);
1328
+		}
1270 1329
 		//if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
1271 1330
 
1272 1331
 		// Check parameters
@@ -1328,8 +1387,7 @@  discard block
 block discarded – undo
1328 1387
 			}
1329 1388
 			$this->db->rollback();
1330 1389
 			return -1*$error;
1331
-		}
1332
-		else
1390
+		} else
1333 1391
 		{
1334 1392
 			$this->db->commit();
1335 1393
 			return 1;
@@ -1389,25 +1447,40 @@  discard block
 block discarded – undo
1389 1447
 			$txlocaltax2=price2num($txlocaltax2);
1390 1448
 			$remise_percent=price2num($remise_percent);
1391 1449
 			$qty=price2num($qty);
1392
-			if (empty($qty)) $qty=1;
1393
-			if (empty($info_bits)) $info_bits=0;
1394
-			if (empty($pu_ht) || ! is_numeric($pu_ht))  $pu_ht=0;
1395
-			if (empty($pu_ttc)) $pu_ttc=0;
1396
-			if (empty($txtva) || ! is_numeric($txtva)) $txtva=0;
1397
-			if (empty($txlocaltax1) || ! is_numeric($txlocaltax1)) $txlocaltax1=0;
1398
-            if (empty($txlocaltax2) || ! is_numeric($txlocaltax2)) $txlocaltax2=0;
1450
+			if (empty($qty)) {
1451
+			    $qty=1;
1452
+			}
1453
+			if (empty($info_bits)) {
1454
+			    $info_bits=0;
1455
+			}
1456
+			if (empty($pu_ht) || ! is_numeric($pu_ht)) {
1457
+			    $pu_ht=0;
1458
+			}
1459
+			if (empty($pu_ttc)) {
1460
+			    $pu_ttc=0;
1461
+			}
1462
+			if (empty($txtva) || ! is_numeric($txtva)) {
1463
+			    $txtva=0;
1464
+			}
1465
+			if (empty($txlocaltax1) || ! is_numeric($txlocaltax1)) {
1466
+			    $txlocaltax1=0;
1467
+			}
1468
+            if (empty($txlocaltax2) || ! is_numeric($txlocaltax2)) {
1469
+                $txlocaltax2=0;
1470
+            }
1399 1471
 
1400 1472
 			if ($price_base_type=='HT')
1401 1473
 			{
1402 1474
 				$pu=$pu_ht;
1403
-			}
1404
-			else
1475
+			} else
1405 1476
 			{
1406 1477
 				$pu=$pu_ttc;
1407 1478
 			}
1408 1479
 
1409 1480
 			// Check parameters
1410
-			if (empty($remise_percent)) $remise_percent=0;
1481
+			if (empty($remise_percent)) {
1482
+			    $remise_percent=0;
1483
+			}
1411 1484
 
1412 1485
 			$localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->societe, $mysoc);
1413 1486
 
@@ -1444,7 +1517,9 @@  discard block
 block discarded – undo
1444 1517
 				$price = $pu_ht - $remise;
1445 1518
 			}
1446 1519
 
1447
-		    if (empty($pa_ht)) $pa_ht=0;
1520
+		    if (empty($pa_ht)) {
1521
+		        $pa_ht=0;
1522
+		    }
1448 1523
 
1449 1524
 
1450 1525
 			// if buy price not defined, define buyprice as configured in margin admin
@@ -1453,8 +1528,7 @@  discard block
 block discarded – undo
1453 1528
 				if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0)
1454 1529
 				{
1455 1530
 					return $result;
1456
-				}
1457
-				else
1531
+				} else
1458 1532
 				{
1459 1533
 					$pa_ht = $result;
1460 1534
 				}
@@ -1485,10 +1559,16 @@  discard block
 block discarded – undo
1485 1559
 			$sql.= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
1486 1560
 			$sql.= " '".$info_bits."',";
1487 1561
 			$sql.= " ".price2num($price).",".price2num($remise).",";
1488
-			if (isset($fk_fournprice)) $sql.= ' '.$fk_fournprice.',';
1489
-			else $sql.= ' null,';
1490
-			if (isset($pa_ht)) $sql.= ' '.price2num($pa_ht);
1491
-			else $sql.= ' null';
1562
+			if (isset($fk_fournprice)) {
1563
+			    $sql.= ' '.$fk_fournprice.',';
1564
+			} else {
1565
+			    $sql.= ' null,';
1566
+			}
1567
+			if (isset($pa_ht)) {
1568
+			    $sql.= ' '.price2num($pa_ht);
1569
+			} else {
1570
+			    $sql.= ' null';
1571
+			}
1492 1572
 			if ($date_start > 0) { $sql.= ",'".$this->db->idate($date_start)."'"; }
1493 1573
 			if ($date_end > 0) { $sql.= ",'".$this->db->idate($date_end)."'"; }
1494 1574
 			$sql.= ", ".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
@@ -1499,9 +1579,11 @@  discard block
 block discarded – undo
1499 1579
 			{
1500 1580
 				$contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
1501 1581
 
1502
-				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
1582
+				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) {
1583
+				    // For avoid conflicts if trigger used
1503 1584
 				{
1504 1585
 					$contractline = new ContratLigne($this->db);
1586
+				}
1505 1587
 					$contractline->array_options=$array_options;
1506 1588
 					$contractline->id=$contractlineid;
1507 1589
 					$result=$contractline->insertExtraFields();
@@ -1526,21 +1608,18 @@  discard block
 block discarded – undo
1526 1608
 				{
1527 1609
 					$this->db->rollback();
1528 1610
 					return -1;
1529
-				}
1530
-				else
1611
+				} else
1531 1612
 				{
1532 1613
 					$this->db->commit();
1533 1614
 					return $contractlineid;
1534 1615
 				}
1535
-			}
1536
-			else
1616
+			} else
1537 1617
 			{
1538 1618
 				$this->db->rollback();
1539 1619
 				$this->error=$this->db->error()." sql=".$sql;
1540 1620
 				return -1;
1541 1621
 			}
1542
-		}
1543
-		else
1622
+		} else
1544 1623
 		{
1545 1624
 			dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
1546 1625
 			return -2;
@@ -1585,7 +1664,9 @@  discard block
 block discarded – undo
1585 1664
 		$localtax1tx = price2num($localtax1tx);
1586 1665
 		$localtax2tx = price2num($localtax2tx);
1587 1666
 		$pa_ht=price2num($pa_ht);
1588
-		if (empty($fk_fournprice)) $fk_fournprice=0;
1667
+		if (empty($fk_fournprice)) {
1668
+		    $fk_fournprice=0;
1669
+		}
1589 1670
 
1590 1671
 		$subprice = $price;
1591 1672
 		$remise = 0;
@@ -1593,8 +1674,7 @@  discard block
 block discarded – undo
1593 1674
 		{
1594 1675
 			$remise = round(($pu * $remise_percent / 100), 2);
1595 1676
 			$price = $pu - $remise;
1596
-		}
1597
-		else
1677
+		} else
1598 1678
 		{
1599 1679
 			$remise_percent=0;
1600 1680
 		}
@@ -1631,7 +1711,9 @@  discard block
 block discarded – undo
1631 1711
 		    $price = $pu - $remise;
1632 1712
 		}
1633 1713
 
1634
-	    if (empty($pa_ht)) $pa_ht=0;
1714
+	    if (empty($pa_ht)) {
1715
+	        $pa_ht=0;
1716
+	    }
1635 1717
 
1636 1718
 		// if buy price not defined, define buyprice as configured in margin admin
1637 1719
 		if ($this->pa_ht == 0)
@@ -1639,8 +1721,7 @@  discard block
 block discarded – undo
1639 1721
 			if (($result = $this->defineBuyPrice($pu_ht, $remise_percent)) < 0)
1640 1722
 			{
1641 1723
 				return $result;
1642
-			}
1643
-			else
1724
+			} else
1644 1725
 			{
1645 1726
 				$pa_ht = $result;
1646 1727
 			}
@@ -1664,14 +1745,10 @@  discard block
 block discarded – undo
1664 1745
 		$sql.= ", total_ttc='".      price2num($total_ttc)."'";
1665 1746
 		$sql.= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
1666 1747
 		$sql.= ", buy_price_ht='".price2num($pa_ht)."'";
1667
-		if ($date_start > 0) { $sql.= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; }
1668
-		else { $sql.=",date_ouverture_prevue=null"; }
1669
-		if ($date_end > 0) { $sql.= ",date_fin_validite='".$this->db->idate($date_end)."'"; }
1670
-		else { $sql.=",date_fin_validite=null"; }
1671
-		if ($date_debut_reel > 0) { $sql.= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; }
1672
-		else { $sql.=",date_ouverture=null"; }
1673
-		if ($date_fin_reel > 0) { $sql.= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; }
1674
-		else { $sql.=",date_cloture=null"; }
1748
+		if ($date_start > 0) { $sql.= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; } else { $sql.=",date_ouverture_prevue=null"; }
1749
+		if ($date_end > 0) { $sql.= ",date_fin_validite='".$this->db->idate($date_end)."'"; } else { $sql.=",date_fin_validite=null"; }
1750
+		if ($date_debut_reel > 0) { $sql.= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; } else { $sql.=",date_ouverture=null"; }
1751
+		if ($date_fin_reel > 0) { $sql.= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; } else { $sql.=",date_cloture=null"; }
1675 1752
 		$sql .= ", fk_unit=".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
1676 1753
 		$sql .= " WHERE rowid = ".$rowid;
1677 1754
 
@@ -1683,9 +1760,11 @@  discard block
 block discarded – undo
1683 1760
 			if ($result >= 0)
1684 1761
 			{
1685 1762
 
1686
-				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
1763
+				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) {
1764
+				    // For avoid conflicts if trigger used
1687 1765
 				{
1688 1766
 					$contractline = new ContratLigne($this->db);
1767
+				}
1689 1768
 					$contractline->array_options=$array_options;
1690 1769
 					$contractline->id= $rowid;
1691 1770
 					$result=$contractline->insertExtraFields();
@@ -1709,15 +1788,13 @@  discard block
 block discarded – undo
1709 1788
 					$this->db->commit();
1710 1789
 					return 1;
1711 1790
 				}
1712
-			}
1713
-			else
1791
+			} else
1714 1792
 			{
1715 1793
 				$this->db->rollback();
1716 1794
 				dol_syslog(get_class($this)."::updateline Erreur -2");
1717 1795
 				return -2;
1718 1796
 			}
1719
-		}
1720
-		else
1797
+		} else
1721 1798
 		{
1722 1799
 			$this->db->rollback();
1723 1800
 			$this->error=$this->db->error();
@@ -1744,7 +1821,9 @@  discard block
 block discarded – undo
1744 1821
 
1745 1822
 		    // Call trigger
1746 1823
 		    $result=$this->call_trigger('LINECONTRACT_DELETE',$user);
1747
-		    if ($result < 0) return -1;
1824
+		    if ($result < 0) {
1825
+		        return -1;
1826
+		    }
1748 1827
 		    // End call triggers
1749 1828
 
1750 1829
 		    $this->db->begin();
@@ -1762,9 +1841,11 @@  discard block
 block discarded – undo
1762 1841
 
1763 1842
 			if (empty($error)) {
1764 1843
 				// Remove extrafields
1765
-				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1844
+				if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
1845
+				    // For avoid conflicts if trigger used
1766 1846
 				{
1767 1847
 					$contractline = new ContratLigne($this->db);
1848
+				}
1768 1849
 					$contractline->id= $idline;
1769 1850
 					$result=$contractline->deleteExtraFields();
1770 1851
 					if ($result < 0)
@@ -1783,8 +1864,7 @@  discard block
 block discarded – undo
1783 1864
 				$this->db->rollback();
1784 1865
 				return -1;
1785 1866
 			}
1786
-		}
1787
-		else
1867
+		} else
1788 1868
 		{
1789 1869
 			$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1790 1870
 			return -2;
@@ -1806,7 +1886,9 @@  discard block
 block discarded – undo
1806 1886
 		dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING);
1807 1887
 
1808 1888
 		// If draft, we keep it (should not happen)
1809
-		if ($this->statut == 0) return 1;
1889
+		if ($this->statut == 0) {
1890
+		    return 1;
1891
+		}
1810 1892
 
1811 1893
 		// Load $this->lines array
1812 1894
 		//		$this->fetch_lines();
@@ -1847,29 +1929,17 @@  discard block
 block discarded – undo
1847 1929
 		$langs->load("contracts");
1848 1930
 		if ($mode == 0)
1849 1931
 		{
1850
-			if ($statut == 0) { return $langs->trans("ContractStatusDraft"); }
1851
-			elseif ($statut == 1) { return $langs->trans("ContractStatusValidated"); }
1852
-			elseif ($statut == 2) { return $langs->trans("ContractStatusClosed"); }
1853
-		}
1854
-		elseif ($mode == 1)
1932
+			if ($statut == 0) { return $langs->trans("ContractStatusDraft"); } elseif ($statut == 1) { return $langs->trans("ContractStatusValidated"); } elseif ($statut == 2) { return $langs->trans("ContractStatusClosed"); }
1933
+		} elseif ($mode == 1)
1855 1934
 		{
1856
-			if ($statut == 0) { return $langs->trans("ContractStatusDraft"); }
1857
-			elseif ($statut == 1) { return $langs->trans("ContractStatusValidated"); }
1858
-			elseif ($statut == 2) { return $langs->trans("ContractStatusClosed"); }
1859
-		}
1860
-		elseif ($mode == 2)
1935
+			if ($statut == 0) { return $langs->trans("ContractStatusDraft"); } elseif ($statut == 1) { return $langs->trans("ContractStatusValidated"); } elseif ($statut == 2) { return $langs->trans("ContractStatusClosed"); }
1936
+		} elseif ($mode == 2)
1861 1937
 		{
1862
-			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0').' '.$langs->trans("ContractStatusDraft"); }
1863
-			elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4').' '.$langs->trans("ContractStatusValidated"); }
1864
-			elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6').' '.$langs->trans("ContractStatusClosed"); }
1865
-		}
1866
-		elseif ($mode == 3)
1938
+			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0').' '.$langs->trans("ContractStatusDraft"); } elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4').' '.$langs->trans("ContractStatusValidated"); } elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6').' '.$langs->trans("ContractStatusClosed"); }
1939
+		} elseif ($mode == 3)
1867 1940
 		{
1868
-			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0'); }
1869
-			elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4'); }
1870
-			elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1871
-		}
1872
-		elseif ($mode == 4 || $mode == 6 || $mode == 7)
1941
+			if ($statut == 0) { return img_picto($langs->trans('ContractStatusDraft'),'statut0'); } elseif ($statut == 1) { return img_picto($langs->trans('ContractStatusValidated'),'statut4'); } elseif ($statut == 2) { return img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1942
+		} elseif ($mode == 4 || $mode == 6 || $mode == 7)
1873 1943
 		{
1874 1944
 			$text='';
1875 1945
 			if ($mode == 4)
@@ -1890,12 +1960,9 @@  discard block
 block discarded – undo
1890 1960
 			$text.=($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5,3,-1,'class="paddingleft2 inline-block valigntextbottom"')) : '';
1891 1961
 			$text.=($mode == 7?'</div>':'');
1892 1962
 			return $text;
1893
-		}
1894
-		elseif ($mode == 5)
1963
+		} elseif ($mode == 5)
1895 1964
 		{
1896
-			if ($statut == 0) { return $langs->trans("ContractStatusDraft").' '.img_picto($langs->trans('ContractStatusDraft'),'statut0'); }
1897
-			elseif ($statut == 1) { return $langs->trans("ContractStatusValidated").' '.img_picto($langs->trans('ContractStatusValidated'),'statut4'); }
1898
-			elseif ($statut == 2) { return $langs->trans("ContractStatusClosed").' '.img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1965
+			if ($statut == 0) { return $langs->trans("ContractStatusDraft").' '.img_picto($langs->trans('ContractStatusDraft'),'statut0'); } elseif ($statut == 1) { return $langs->trans("ContractStatusValidated").' '.img_picto($langs->trans('ContractStatusValidated'),'statut4'); } elseif ($statut == 2) { return $langs->trans("ContractStatusClosed").' '.img_picto($langs->trans('ContractStatusClosed'),'statut6'); }
1899 1966
 		}
1900 1967
 	}
1901 1968
 
@@ -1921,8 +1988,12 @@  discard block
 block discarded – undo
1921 1988
 		//{
1922 1989
 			// Add param to save lastsearch_values or not
1923 1990
 			$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
1924
-			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
1925
-			if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
1991
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) {
1992
+			    $add_save_lastsearch_values=1;
1993
+			}
1994
+			if ($add_save_lastsearch_values) {
1995
+			    $url.='&save_lastsearch_values=1';
1996
+			}
1926 1997
 		//}
1927 1998
 
1928 1999
         $label = '';
@@ -1960,8 +2031,12 @@  discard block
 block discarded – undo
1960 2031
 		$linkend='</a>';
1961 2032
 
1962 2033
 		$result .= $linkstart;
1963
-		if ($withpicto) $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
1964
-		if ($withpicto != 2) $result.= $this->ref;
2034
+		if ($withpicto) {
2035
+		    $result.=img_object(($notooltip?'':$label), $this->picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
2036
+		}
2037
+		if ($withpicto != 2) {
2038
+		    $result.= $this->ref;
2039
+		}
1965 2040
 		$result .= $linkend;
1966 2041
 
1967 2042
 		return $result;
@@ -2008,8 +2083,7 @@  discard block
 block discarded – undo
2008 2083
 			}
2009 2084
 
2010 2085
 			$this->db->free($result);
2011
-		}
2012
-		else
2086
+		} else
2013 2087
 		{
2014 2088
 			dol_print_error($this->db);
2015 2089
 		}
@@ -2030,7 +2104,9 @@  discard block
 block discarded – undo
2030 2104
 		$sql = "SELECT cd.rowid";
2031 2105
 		$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
2032 2106
 		$sql.= " WHERE fk_contrat =".$this->id;
2033
-		if ($statut >= 0) $sql.= " AND statut = '$statut'";
2107
+		if ($statut >= 0) {
2108
+		    $sql.= " AND statut = '$statut'";
2109
+		}
2034 2110
 
2035 2111
 		dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
2036 2112
 		$resql=$this->db->query($sql);
@@ -2045,8 +2121,7 @@  discard block
 block discarded – undo
2045 2121
 				$i++;
2046 2122
 			}
2047 2123
 			return $tab;
2048
-		}
2049
-		else
2124
+		} else
2050 2125
 		{
2051 2126
 			$this->error=$this->db->error();
2052 2127
 			return -1;
@@ -2066,7 +2141,9 @@  discard block
 block discarded – undo
2066 2141
 		$sql = "SELECT c.rowid, c.ref";
2067 2142
 		$sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
2068 2143
 		$sql.= " WHERE fk_soc =".$this->socid;
2069
-		if ($option == 'others') $sql.= " AND c.rowid != ".$this->id;
2144
+		if ($option == 'others') {
2145
+		    $sql.= " AND c.rowid != ".$this->id;
2146
+		}
2070 2147
 
2071 2148
 		dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
2072 2149
 		$resql=$this->db->query($sql);
@@ -2083,8 +2160,7 @@  discard block
 block discarded – undo
2083 2160
 				$i++;
2084 2161
 			}
2085 2162
 			return $tab;
2086
-		}
2087
-		else
2163
+		} else
2088 2164
 		{
2089 2165
 			$this->error=$this->db->error();
2090 2166
 			return -1;
@@ -2108,7 +2184,9 @@  discard block
 block discarded – undo
2108 2184
 		$this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
2109 2185
 		$this->from.= ", ".MAIN_DB_PREFIX."contratdet as cd";
2110 2186
 		$this->from.= ", ".MAIN_DB_PREFIX."societe as s";
2111
-		if (!$user->rights->societe->client->voir && !$user->societe_id) $this->from.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2187
+		if (!$user->rights->societe->client->voir && !$user->societe_id) {
2188
+		    $this->from.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
2189
+		}
2112 2190
 
2113 2191
 		if ($mode == 'inactives')
2114 2192
 		{
@@ -2117,8 +2195,7 @@  discard block
 block discarded – undo
2117 2195
 			$sql.= " WHERE c.statut = 1";
2118 2196
 			$sql.= " AND c.rowid = cd.fk_contrat";
2119 2197
 			$sql.= " AND cd.statut = 0";
2120
-		}
2121
-		elseif ($mode == 'expired')
2198
+		} elseif ($mode == 'expired')
2122 2199
 		{
2123 2200
 			$sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
2124 2201
 			$sql.= $this->from;
@@ -2129,8 +2206,12 @@  discard block
 block discarded – undo
2129 2206
 		}
2130 2207
 		$sql.= " AND c.fk_soc = s.rowid";
2131 2208
 		$sql.= " AND c.entity = ".$conf->entity;
2132
-		if ($user->societe_id) $sql.=" AND c.fk_soc = ".$user->societe_id;
2133
-		if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id;
2209
+		if ($user->societe_id) {
2210
+		    $sql.=" AND c.fk_soc = ".$user->societe_id;
2211
+		}
2212
+		if (!$user->rights->societe->client->voir && !$user->societe_id) {
2213
+		    $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id;
2214
+		}
2134 2215
 		$resql=$this->db->query($sql);
2135 2216
 		if ($resql)
2136 2217
 		{
@@ -2163,8 +2244,7 @@  discard block
 block discarded – undo
2163 2244
 			}
2164 2245
 
2165 2246
 			return $response;
2166
-		}
2167
-		else
2247
+		} else
2168 2248
 		{
2169 2249
 			dol_print_error($this->db);
2170 2250
 			$this->error=$this->db->error();
@@ -2206,8 +2286,7 @@  discard block
 block discarded – undo
2206 2286
 			}
2207 2287
             $this->db->free($resql);
2208 2288
 			return 1;
2209
-		}
2210
-		else
2289
+		} else
2211 2290
 		{
2212 2291
 			dol_print_error($this->db);
2213 2292
 			$this->error=$this->db->error();
@@ -2474,8 +2553,9 @@  discard block
 block discarded – undo
2474 2553
 				);
2475 2554
 				$action = '';
2476 2555
 				$reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
2477
-				if ($reshook < 0)
2478
-					$error ++;
2556
+				if ($reshook < 0) {
2557
+									$error ++;
2558
+				}
2479 2559
 			}
2480 2560
 		}
2481 2561
 
@@ -2666,51 +2746,22 @@  discard block
 block discarded – undo
2666 2746
 		$langs->load("contracts");
2667 2747
 		if ($mode == 0)
2668 2748
 		{
2669
-			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); }
2670
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); }
2671
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLate"); }
2672
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLate"); }
2673
-			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2674
-		}
2675
-		elseif ($mode == 1)
2749
+			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); } elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); } elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLate"); } elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLate"); } elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2750
+		} elseif ($mode == 1)
2676 2751
 		{
2677
-			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); }
2678
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); }
2679
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort"); }
2680
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort"); }
2681
-			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2682
-		}
2683
-		elseif ($mode == 2)
2752
+			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); } elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); } elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort"); } elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort"); } elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed");  }
2753
+		} elseif ($mode == 2)
2684 2754
 		{
2685
-			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2686
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2687
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLateShort"); }
2688
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLateShort"); }
2689
-			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2690
-		}
2691
-		elseif ($mode == 3)
2755
+			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); } elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); } elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLateShort"); } elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLateShort"); } elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2756
+		} elseif ($mode == 3)
2692 2757
 		{
2693
-			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0',$moreatt); }
2694
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4',$moreatt); }
2695
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4',$moreatt); }
2696
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3',$moreatt); }
2697
-			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6',$moreatt); }
2698
-		}
2699
-		elseif ($mode == 4)
2758
+			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0',$moreatt); } elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4',$moreatt); } elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4',$moreatt); } elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3',$moreatt); } elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6',$moreatt); }
2759
+		} elseif ($mode == 4)
2700 2760
 		{
2701
-			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); }
2702
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); }
2703
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLate"); }
2704
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLate"); }
2705
-			elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2706
-		}
2707
-		elseif ($mode == 5)
2761
+			if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); } elseif ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); } elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLate"); } elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLate"); } elseif ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); }
2762
+		} elseif ($mode == 5)
2708 2763
 		{
2709
-			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial").' '.img_picto($langs->trans('ServiceStatusInitial'),'statut0'); }
2710
-			elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning").' '.img_picto($langs->trans('ServiceStatusRunning'),'statut4'); }
2711
-			elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort").' '.img_picto($langs->trans('ServiceStatusNotLateShort'),'statut4'); }
2712
-			elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort").' '.img_picto($langs->trans('ServiceStatusLate'),'statut3'); }
2713
-			elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed").' '.img_picto($langs->trans('ServiceStatusClosed'),'statut6'); }
2764
+			if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial").' '.img_picto($langs->trans('ServiceStatusInitial'),'statut0'); } elseif ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning").' '.img_picto($langs->trans('ServiceStatusRunning'),'statut4'); } elseif ($statut == self::STATUS_OPEN && $expired == 0)  { return $langs->trans("ServiceStatusNotLateShort").' '.img_picto($langs->trans('ServiceStatusNotLateShort'),'statut4'); } elseif ($statut == self::STATUS_OPEN && $expired == 1)  { return $langs->trans("ServiceStatusLateShort").' '.img_picto($langs->trans('ServiceStatusLate'),'statut3'); } elseif ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed").' '.img_picto($langs->trans('ServiceStatusClosed'),'statut6'); }
2714 2765
 		}
2715 2766
 	}
2716 2767
 
@@ -2727,17 +2778,27 @@  discard block
 block discarded – undo
2727 2778
 
2728 2779
 		$result='';
2729 2780
         $label=$langs->trans("ShowContractOfService").': '.$this->label;
2730
-        if (empty($label)) $label=$this->description;
2781
+        if (empty($label)) {
2782
+            $label=$this->description;
2783
+        }
2731 2784
 
2732 2785
         $link = '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$this->fk_contrat.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
2733 2786
 		$linkend='</a>';
2734 2787
 
2735 2788
 		$picto='service';
2736
-		if ($this->type == 0) $picto='product';
2789
+		if ($this->type == 0) {
2790
+		    $picto='product';
2791
+		}
2737 2792
 
2738
-        if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
2739
-		if ($withpicto && $withpicto != 2) $result.=' ';
2740
-		if ($withpicto != 2) $result.=$link.($this->product_ref?$this->product_ref.' ':'').($this->label?$this->label:$this->description).$linkend;
2793
+        if ($withpicto) {
2794
+            $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
2795
+        }
2796
+		if ($withpicto && $withpicto != 2) {
2797
+		    $result.=' ';
2798
+		}
2799
+		if ($withpicto != 2) {
2800
+		    $result.=$link.($this->product_ref?$this->product_ref.' ':'').($this->label?$this->label:$this->description).$linkend;
2801
+		}
2741 2802
 		return $result;
2742 2803
 	}
2743 2804
 
@@ -2752,7 +2813,9 @@  discard block
 block discarded – undo
2752 2813
 	{
2753 2814
 
2754 2815
 		// Check parameters
2755
-		if (empty($id) && empty($ref)) return -1;
2816
+		if (empty($id) && empty($ref)) {
2817
+		    return -1;
2818
+		}
2756 2819
 
2757 2820
 		$sql = "SELECT";
2758 2821
 		$sql.= " t.rowid,";
@@ -2798,8 +2861,12 @@  discard block
 block discarded – undo
2798 2861
 		$sql.= " t.commentaire,";
2799 2862
 		$sql.= " t.fk_unit";
2800 2863
 		$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
2801
-		if ($id)  $sql.= " WHERE t.rowid = ".$id;
2802
-		if ($ref) $sql.= " WHERE t.rowid = '".$this->db->escape($ref)."'";
2864
+		if ($id) {
2865
+		    $sql.= " WHERE t.rowid = ".$id;
2866
+		}
2867
+		if ($ref) {
2868
+		    $sql.= " WHERE t.rowid = '".$this->db->escape($ref)."'";
2869
+		}
2803 2870
 
2804 2871
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
2805 2872
 		$resql=$this->db->query($sql);
@@ -2864,8 +2931,7 @@  discard block
 block discarded – undo
2864 2931
 			$this->db->free($resql);
2865 2932
 
2866 2933
 			return 1;
2867
-		}
2868
-		else
2934
+		} else
2869 2935
 		{
2870 2936
 			$this->error="Error ".$this->db->lasterror();
2871 2937
 			return -1;
@@ -2913,18 +2979,40 @@  discard block
 block discarded – undo
2913 2979
 		$this->fk_user_cloture = (int) $this->fk_user_cloture;
2914 2980
 		$this->commentaire=trim($this->commentaire);
2915 2981
 		//if (empty($this->subprice)) $this->subprice = 0;
2916
-		if (empty($this->price_ht)) $this->price_ht = 0;
2917
-		if (empty($this->total_ht)) $this->total_ht = 0;
2918
-		if (empty($this->total_tva)) $this->total_tva = 0;
2919
-		if (empty($this->total_ttc)) $this->total_ttc = 0;
2920
-		if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
2921
-		if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
2922
-		if (empty($this->remise_percent)) $this->remise_percent = 0;
2982
+		if (empty($this->price_ht)) {
2983
+		    $this->price_ht = 0;
2984
+		}
2985
+		if (empty($this->total_ht)) {
2986
+		    $this->total_ht = 0;
2987
+		}
2988
+		if (empty($this->total_tva)) {
2989
+		    $this->total_tva = 0;
2990
+		}
2991
+		if (empty($this->total_ttc)) {
2992
+		    $this->total_ttc = 0;
2993
+		}
2994
+		if (empty($this->localtax1_tx)) {
2995
+		    $this->localtax1_tx = 0;
2996
+		}
2997
+		if (empty($this->localtax2_tx)) {
2998
+		    $this->localtax2_tx = 0;
2999
+		}
3000
+		if (empty($this->remise_percent)) {
3001
+		    $this->remise_percent = 0;
3002
+		}
2923 3003
 		// For backward compatibility
2924
-		if (empty($this->date_start))      $this->date_start=$this->date_ouverture_prevue;
2925
-		if (empty($this->date_start_real)) $this->date_start=$this->date_ouverture;
2926
-		if (empty($this->date_end))        $this->date_start=$this->date_fin_validite;
2927
-		if (empty($this->date_end_real))   $this->date_start=$this->date_cloture;
3004
+		if (empty($this->date_start)) {
3005
+		    $this->date_start=$this->date_ouverture_prevue;
3006
+		}
3007
+		if (empty($this->date_start_real)) {
3008
+		    $this->date_start=$this->date_ouverture;
3009
+		}
3010
+		if (empty($this->date_end)) {
3011
+		    $this->date_start=$this->date_fin_validite;
3012
+		}
3013
+		if (empty($this->date_end_real)) {
3014
+		    $this->date_start=$this->date_cloture;
3015
+		}
2928 3016
 
2929 3017
 
2930 3018
 		// Check parameters
@@ -2943,7 +3031,9 @@  discard block
 block discarded – undo
2943 3031
 		$this->total_localtax1= $tabprice[9];
2944 3032
 		$this->total_localtax2= $tabprice[10];
2945 3033
 
2946
-	    if (empty($this->pa_ht)) $this->pa_ht=0;
3034
+	    if (empty($this->pa_ht)) {
3035
+	        $this->pa_ht=0;
3036
+	    }
2947 3037
 
2948 3038
 		// if buy price not defined, define buyprice as configured in margin admin
2949 3039
 		if ($this->pa_ht == 0)
@@ -2951,8 +3041,7 @@  discard block
 block discarded – undo
2951 3041
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
2952 3042
 			{
2953 3043
 				return $result;
2954
-			}
2955
-			else
3044
+			} else
2956 3045
 			{
2957 3046
 				$this->pa_ht = $result;
2958 3047
 			}
@@ -3009,9 +3098,11 @@  discard block
 block discarded – undo
3009 3098
 			$error++;
3010 3099
 		}
3011 3100
 
3012
-		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used
3101
+		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) {
3102
+		    // For avoid conflicts if trigger used
3013 3103
 		{
3014 3104
 			$result=$this->insertExtraFields();
3105
+		}
3015 3106
 			if ($result < 0)
3016 3107
 			{
3017 3108
 				$error++;
@@ -3099,8 +3190,7 @@  discard block
 block discarded – undo
3099 3190
 		{
3100 3191
 			$this->db->commit();
3101 3192
 			return 1;
3102
-		}
3103
-		else
3193
+		} else
3104 3194
 		{
3105 3195
 			$this->error=$this->db->error();
3106 3196
 			$this->db->rollback();
@@ -3141,10 +3231,16 @@  discard block
 block discarded – undo
3141 3231
 		$sql.= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
3142 3232
 		$sql.= " '".$this->db->escape($this->info_bits)."',";
3143 3233
 		$sql.= " ".price2num($this->price_ht).",".price2num($this->remise).",";
3144
-		if ($this->fk_fournprice > 0) $sql.= ' '.$this->fk_fournprice.',';
3145
-		else $sql.= ' null,';
3146
-		if ($this->pa_ht > 0) $sql.= ' '.price2num($this->pa_ht);
3147
-		else $sql.= ' null';
3234
+		if ($this->fk_fournprice > 0) {
3235
+		    $sql.= ' '.$this->fk_fournprice.',';
3236
+		} else {
3237
+		    $sql.= ' null,';
3238
+		}
3239
+		if ($this->pa_ht > 0) {
3240
+		    $sql.= ' '.price2num($this->pa_ht);
3241
+		} else {
3242
+		    $sql.= ' null';
3243
+		}
3148 3244
 		if ($this->date_ouverture > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture)."'"; }
3149 3245
 		if ($this->date_cloture > 0)   { $sql.= ",'".$this->db->idate($this->date_cloture)."'"; }
3150 3246
 		$sql.= ")";
@@ -3157,9 +3253,11 @@  discard block
 block discarded – undo
3157 3253
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
3158 3254
 
3159 3255
 			// Insert of extrafields
3160
-			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used
3256
+			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) {
3257
+			    // For avoid conflicts if trigger used
3161 3258
 			{
3162 3259
 				$result = $this->insertExtraFields();
3260
+			}
3163 3261
 				if ($result < 0)
3164 3262
 				{
3165 3263
 					$this->db->rollback();
@@ -3180,8 +3278,7 @@  discard block
 block discarded – undo
3180 3278
 
3181 3279
 			$this->db->commit();
3182 3280
 			return 1;
3183
-		}
3184
-		else
3281
+		} else
3185 3282
 		{
3186 3283
 			$this->db->rollback();
3187 3284
 			$this->error=$this->db->error()." sql=".$sql;
@@ -3210,7 +3307,9 @@  discard block
 block discarded – undo
3210 3307
 
3211 3308
 		$sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = ".ContratLigne::STATUS_OPEN.",";
3212 3309
 		$sql .= " date_ouverture = " . (dol_strlen($date) != 0 ? "'" . $this->db->idate($date) . "'" : "null") . ",";
3213
-		if ($date_end >= 0) $sql .= " date_fin_validite = " . (dol_strlen($date_end) != 0 ? "'" . $this->db->idate($date_end) . "'" : "null") . ",";
3310
+		if ($date_end >= 0) {
3311
+		    $sql .= " date_fin_validite = " . (dol_strlen($date_end) != 0 ? "'" . $this->db->idate($date_end) . "'" : "null") . ",";
3312
+		}
3214 3313
 		$sql .= " fk_user_ouverture = " . $user->id . ",";
3215 3314
 		$sql .= " date_cloture = null,";
3216 3315
 		$sql .= " commentaire = '" . $this->db->escape($comment) . "'";
@@ -3221,7 +3320,9 @@  discard block
 block discarded – undo
3221 3320
 		if ($resql) {
3222 3321
 			// Call trigger
3223 3322
 			$result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user);
3224
-			if ($result < 0) $error++;
3323
+			if ($result < 0) {
3324
+			    $error++;
3325
+			}
3225 3326
 			// End call triggers
3226 3327
 
3227 3328
 			if (! $error)
@@ -3235,8 +3336,7 @@  discard block
 block discarded – undo
3235 3336
 
3236 3337
 				$this->db->commit();
3237 3338
 				return 1;
3238
-			}
3239
-			else
3339
+			} else
3240 3340
 			{
3241 3341
 				$this->db->rollback();
3242 3342
 				return -1;
Please login to merge, or discard this patch.
dolibarr/htdocs/contrat/card.php 3 patches
Indentation   +1957 added lines, -1957 removed lines patch added patch discarded remove patch
@@ -42,8 +42,8 @@  discard block
 block discarded – undo
42 42
 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
43 43
 if (! empty($conf->propal->enabled))  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
44 44
 if (! empty($conf->projet->enabled)) {
45
-	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
46
-	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
45
+    require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
46
+    require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
47 47
 }
48 48
 require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
49 49
 
@@ -73,11 +73,11 @@  discard block
 block discarded – undo
73 73
 
74 74
 // Load object
75 75
 if ($id > 0 || ! empty($ref) && $action!='add') {
76
-	$ret = $object->fetch($id, $ref);
77
-	if ($ret > 0)
78
-		$ret = $object->fetch_thirdparty();
79
-	if ($ret < 0)
80
-		dol_print_error('', $object->error);
76
+    $ret = $object->fetch($id, $ref);
77
+    if ($ret > 0)
78
+        $ret = $object->fetch_thirdparty();
79
+    if ($ret < 0)
80
+        dol_print_error('', $object->error);
81 81
 }
82 82
 
83 83
 // fetch optionals attributes and labels
@@ -101,989 +101,989 @@  discard block
 block discarded – undo
101 101
 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
102 102
 if (empty($reshook))
103 103
 {
104
-	include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include, not includ_once
105
-
106
-	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';		// Must be include, not include_once
107
-
108
-	if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer)
109
-	{
110
-		$result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment'));
111
-
112
-		if ($result > 0)
113
-		{
114
-			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
115
-			exit;
116
-		}
117
-		else {
118
-			setEventMessages($object->error, $object->errors, 'errors');
119
-		}
120
-	}
104
+    include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include, not includ_once
121 105
 
122
-	else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer)
123
-	{
124
-		if (! GETPOST('dateend'))
125
-		{
126
-			$error++;
127
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
128
-		}
129
-		if (! $error)
130
-		{
131
-			$result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment')));
132
-			if ($result > 0)
133
-			{
134
-				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
135
-				exit;
136
-			}
137
-			else
138
-			{
139
-				setEventMessages($object->error, $object->errors, 'errors');
140
-			}
141
-		}
142
-	}
106
+    include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';		// Must be include, not include_once
143 107
 
144
-	// Si ajout champ produit predefini
145
-	if (GETPOST('mode')=='predefined')
146
-	{
147
-		$date_start='';
148
-		$date_end='';
149
-		if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear'))
150
-		{
151
-			$date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
152
-		}
153
-		if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear'))
154
-		{
155
-			$date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
156
-		}
157
-	}
108
+    if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer)
109
+    {
110
+        $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment'));
158 111
 
159
-	// Si ajout champ produit libre
160
-	if (GETPOST('mode')=='libre')
161
-	{
162
-		$date_start_sl='';
163
-		$date_end_sl='';
164
-		if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear'))
165
-		{
166
-			$date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear'));
167
-		}
168
-		if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear'))
169
-		{
170
-			$date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear'));
171
-		}
172
-	}
112
+        if ($result > 0)
113
+        {
114
+            header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
115
+            exit;
116
+        }
117
+        else {
118
+            setEventMessages($object->error, $object->errors, 'errors');
119
+        }
120
+    }
173 121
 
174
-	// Param dates
175
-	$date_contrat='';
176
-	$date_start_update='';
177
-	$date_end_update='';
178
-	$date_start_real_update='';
179
-	$date_end_real_update='';
180
-	if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear'))
181
-	{
182
-		$date_start_update=dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear'));
183
-	}
184
-	if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear'))
185
-	{
186
-		$date_end_update=dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear'));
187
-	}
188
-	if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear'))
189
-	{
190
-		$date_start_real_update=dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear'));
191
-	}
192
-	if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear'))
193
-	{
194
-		$date_end_real_update=dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear'));
195
-	}
196
-	if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear'))
197
-	{
198
-		$datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
199
-	}
122
+    else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer)
123
+    {
124
+        if (! GETPOST('dateend'))
125
+        {
126
+            $error++;
127
+            setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
128
+        }
129
+        if (! $error)
130
+        {
131
+            $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment')));
132
+            if ($result > 0)
133
+            {
134
+                header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
135
+                exit;
136
+            }
137
+            else
138
+            {
139
+                setEventMessages($object->error, $object->errors, 'errors');
140
+            }
141
+        }
142
+    }
200 143
 
201
-	// Add contract
202
-	if ($action == 'add' && $user->rights->contrat->creer)
203
-	{
204
-		// Check
205
-		if (empty($datecontrat))
206
-		{
207
-			$error++;
208
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
209
-			$action='create';
210
-		}
211
-
212
-		if ($socid<1)
213
-		{
214
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors');
215
-			$action='create';
216
-			$error++;
217
-		}
218
-
219
-		// Fill array 'array_options' with data from add form
220
-		$ret = $extrafields->setOptionalsFromPost($extralabels, $object);
221
-		if ($ret < 0) {
222
-			$error ++;
223
-			$action = 'create';
224
-		}
225
-
226
-		if (! $error)
227
-		{
228
-			$object->socid						= $socid;
229
-			$object->date_contrat				= $datecontrat;
230
-
231
-			$object->commercial_suivi_id		= GETPOST('commercial_suivi_id','int');
232
-			$object->commercial_signature_id	= GETPOST('commercial_signature_id','int');
233
-
234
-			$object->note_private				= GETPOST('note_private','alpha');
235
-			$object->note_public				= GETPOST('note_public','alpha');
236
-			$object->fk_project					= GETPOST('projectid','int');
237
-			$object->remise_percent				= GETPOST('remise_percent','alpha');
238
-			$object->ref						= GETPOST('ref','alpha');
239
-			$object->ref_customer				= GETPOST('ref_customer','alpha');
240
-			$object->ref_supplier				= GETPOST('ref_supplier','alpha');
241
-
242
-			// If creation from another object of another module (Example: origin=propal, originid=1)
243
-			if (! empty($origin) && ! empty($originid))
244
-			{
245
-				// Parse element/subelement (ex: project_task)
246
-				$element = $subelement = $origin;
247
-				if (preg_match('/^([^_]+)_([^_]+)/i',$origin,$regs))
248
-				{
249
-					$element = $regs[1];
250
-					$subelement = $regs[2];
251
-				}
252
-
253
-				// For compatibility
254
-				if ($element == 'order')    { $element = $subelement = 'commande'; }
255
-				if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
256
-
257
-				$object->origin    = $origin;
258
-				$object->origin_id = $originid;
259
-
260
-				// Possibility to add external linked objects with hooks
261
-				$object->linked_objects[$object->origin] = $object->origin_id;
262
-				if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects']))
263
-				{
264
-					$object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
265
-				}
266
-
267
-				$id = $object->create($user);
268
-				if ($id < 0) {
269
-					setEventMessages($object->error, $object->errors, 'errors');
270
-				}
271
-
272
-				if ($id > 0)
273
-				{
274
-					dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
275
-
276
-					$classname = ucfirst($subelement);
277
-					$srcobject = new $classname($db);
278
-
279
-					dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
280
-					$result=$srcobject->fetch($object->origin_id);
281
-					if ($result > 0)
282
-					{
283
-						$srcobject->fetch_thirdparty();
284
-						$lines = $srcobject->lines;
285
-						if (empty($lines) && method_exists($srcobject,'fetch_lines'))
286
-						{
287
-							$srcobject->fetch_lines();
288
-							$lines = $srcobject->lines;
289
-						}
290
-
291
-						$fk_parent_line=0;
292
-						$num=count($lines);
293
-
294
-						for ($i=0;$i<$num;$i++)
295
-						{
296
-							$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
297
-
298
-							if ($product_type == 1 || (! empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0,1)))) { 	// TODO Exclude also deee
299
-								// service prédéfini
300
-								if ($lines[$i]->fk_product > 0)
301
-								{
302
-									$product_static = new Product($db);
303
-
304
-									// Define output language
305
-									if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE))
306
-									{
307
-										$prod = new Product($db);
308
-										$prod->id=$lines[$i]->fk_product;
309
-										$prod->getMultiLangs();
310
-
311
-										$outputlangs = $langs;
312
-										$newlang='';
313
-										if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
314
-										if (empty($newlang)) $newlang=$srcobject->thirdparty->default_lang;
315
-										if (! empty($newlang))
316
-										{
317
-											$outputlangs = new Translate("",$conf);
318
-											$outputlangs->setDefaultLang($newlang);
319
-										}
320
-
321
-										$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
322
-									}
323
-									else
324
-									{
325
-										$label = $lines[$i]->product_label;
326
-									}
327
-									$desc = ($lines[$i]->desc && $lines[$i]->desc!=$lines[$i]->libelle)?dol_htmlentitiesbr($lines[$i]->desc):'';
328
-								}
329
-								else {
330
-									$desc = dol_htmlentitiesbr($lines[$i]->desc);
331
-								}
332
-
333
-								// Extrafields
334
-								$array_options = array();
335
-								if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) 							// For avoid conflicts if
336
-								// trigger used
337
-								{
338
-									$lines[$i]->fetch_optionals($lines[$i]->rowid);
339
-									$array_options = $lines[$i]->array_options;
340
-								}
341
-
342
-								$txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx . ' (' .  $lines[$i]->vat_src_code . ')' : $lines[$i]->tva_tx;
343
-
344
-								// View third's localtaxes for now
345
-								$localtax1_tx = get_localtax($txtva, 1, $object->thirdparty);
346
-								$localtax2_tx = get_localtax($txtva, 2, $object->thirdparty);
347
-
348
-								$result = $object->addline(
349
-									$desc,
350
-									$lines[$i]->subprice,
351
-									$lines[$i]->qty,
352
-									$txtva,
353
-									$localtax1_tx,
354
-									$localtax2_tx,
355
-									$lines[$i]->fk_product,
356
-									$lines[$i]->remise_percent,
357
-									$lines[$i]->date_start,
358
-									$lines[$i]->date_end,
359
-									'HT',
360
-									0,
361
-									$lines[$i]->info_bits,
362
-									$lines[$i]->fk_fournprice,
363
-									$lines[$i]->pa_ht,
364
-									$array_options,
365
-									$lines[$i]->fk_unit
366
-								);
367
-
368
-								if ($result < 0)
369
-								{
370
-									$error++;
371
-									break;
372
-								}
373
-							}
374
-						}
375
-					}
376
-					else
377
-					{
378
-						setEventMessages($srcobject->error, $srcobject->errors, 'errors');
379
-						$error++;
380
-					}
381
-
382
-					// Hooks
383
-					$parameters = array('objFrom' => $srcobject);
384
-					$reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
385
-					// modified by hook
386
-					if ($reshook < 0)
387
-						$error++;
388
-				}
389
-				else
390
-				{
391
-					setEventMessages($object->error, $object->errors, 'errors');
392
-					$error++;
393
-				}
394
-			}
395
-			else
396
-			{
397
-				$result = $object->create($user);
398
-				if ($result > 0)
399
-				{
400
-					header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
401
-					exit;
402
-				}
403
-				else {
404
-					setEventMessages($object->error, $object->errors, 'errors');
405
-				}
406
-				$action='create';
407
-			}
408
-		}
409
-	}
144
+    // Si ajout champ produit predefini
145
+    if (GETPOST('mode')=='predefined')
146
+    {
147
+        $date_start='';
148
+        $date_end='';
149
+        if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear'))
150
+        {
151
+            $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
152
+        }
153
+        if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear'))
154
+        {
155
+            $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
156
+        }
157
+    }
410 158
 
411
-	else if ($action == 'classin' && $user->rights->contrat->creer)
412
-	{
413
-		$object->setProject(GETPOST('projectid'));
414
-	}
159
+    // Si ajout champ produit libre
160
+    if (GETPOST('mode')=='libre')
161
+    {
162
+        $date_start_sl='';
163
+        $date_end_sl='';
164
+        if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear'))
165
+        {
166
+            $date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear'));
167
+        }
168
+        if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear'))
169
+        {
170
+            $date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear'));
171
+        }
172
+    }
415 173
 
416
-	// Add a new line
417
-	else if ($action == 'addline' && $user->rights->contrat->creer)
418
-	{
419
-		// Set if we used free entry or predefined product
420
-		$predef='';
421
-		$product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
422
-		$price_ht = GETPOST('price_ht');
423
-		$price_ht_devise = GETPOST('multicurrency_price_ht');
424
-		if (GETPOST('prod_entry_mode') == 'free')
425
-		{
426
-			$idprod=0;
427
-			$tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
428
-		}
429
-		else
430
-		{
431
-			$idprod=GETPOST('idprod', 'int');
432
-			$tva_tx = '';
433
-		}
434
-
435
-		$qty = GETPOST('qty'.$predef);
436
-		$remise_percent = GETPOST('remise_percent'.$predef);
437
-
438
-		if ($qty == '')
439
-		{
440
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors');
441
-			$error++;
442
-		}
443
-		if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc))
444
-		{
445
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors');
446
-			$error++;
447
-		}
448
-
449
-	  $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year'));
450
-	  $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year'));
451
-	  if (!empty($date_start) && !empty($date_end) && $date_start > $date_end)
452
-	  {
453
-		  setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
454
-		  $error++;
455
-	  }
456
-
457
-		// Extrafields
458
-		$extrafieldsline = new ExtraFields($db);
459
-		$extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
460
-		$array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
461
-		// Unset extrafield
462
-		if (is_array($extralabelsline)) {
463
-			// Get extra fields
464
-			foreach ($extralabelsline as $key => $value) {
465
-				unset($_POST["options_" . $key]);
466
-			}
467
-		}
468
-
469
-		if (! $error)
470
-		{
471
-			// Clean parameters
472
-			$date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
473
-			$date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
474
-			$price_base_type = (GETPOST('price_base_type', 'alpha')?GETPOST('price_base_type', 'alpha'):'HT');
475
-
476
-			// Ecrase $pu par celui du produit
477
-			// Ecrase $desc par celui du produit
478
-			// Ecrase $tva_tx par celui du produit
479
-			// Ecrase $base_price_type par celui du produit
480
-			if ($idprod > 0)
481
-			{
482
-				$prod = new Product($db);
483
-				$prod->fetch($idprod);
484
-
485
-				// Update if prices fields are defined
486
-				$tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id);
487
-				$tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id);
488
-				if (empty($tva_tx)) $tva_npr=0;
489
-
490
-				$pu_ht = $prod->price;
491
-				$pu_ttc = $prod->price_ttc;
492
-				$price_min = $prod->price_min;
493
-				$price_base_type = $prod->price_base_type;
494
-
495
-				// On defini prix unitaire
496
-				if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level)
497
-				{
498
-					$pu_ht = $prod->multiprices[$object->thirdparty->price_level];
499
-					$pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
500
-					$price_min = $prod->multiprices_min[$object->thirdparty->price_level];
501
-					$price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
502
-				}
503
-				elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
504
-				{
505
-					require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
506
-
507
-					$prodcustprice = new Productcustomerprice($db);
508
-
509
-					$filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id);
510
-
511
-					$result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
512
-					if ($result) {
513
-						if (count($prodcustprice->lines) > 0) {
514
-							$pu_ht = price($prodcustprice->lines [0]->price);
515
-							$pu_ttc = price($prodcustprice->lines [0]->price_ttc);
516
-							$price_base_type = $prodcustprice->lines [0]->price_base_type;
517
-							$tva_tx = $prodcustprice->lines [0]->tva_tx;
518
-							if ($prodcustprice->lines[0]->default_vat_code && ! preg_match('/\(.*\)/', $tva_tx)) $tva_tx.= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
519
-							$tva_npr = $prodcustprice->lines[0]->recuperableonly;
520
-							if (empty($tva_tx)) $tva_npr=0;
521
-						}
522
-					}
523
-				}
524
-
525
-				$tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
526
-				$tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
527
-
528
-				// On reevalue prix selon taux tva car taux tva transaction peut etre different
529
-				// de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
530
-				if ($tmpvat != $tmpprodvat)
531
-				{
532
-					if ($price_base_type != 'HT')
533
-					{
534
-						$pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU');
535
-					}
536
-					else
537
-				  {
538
-						$pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU');
539
-					}
540
-				}
541
-
542
-			   	$desc=$prod->description;
543
-			   	$desc=dol_concatdesc($desc,$product_desc, '', !empty($conf->global->CHANGE_ORDER_CONCAT_DESCRIPTION));
544
-				$fk_unit = $prod->fk_unit;
545
-			}
546
-			else
547
-			{
548
-				$pu_ht=GETPOST('price_ht');
549
-				$price_base_type = 'HT';
550
-				$tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0;		// tva_tx field may be disabled, so we use vat rate 0
551
-				$tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0;
552
-				$desc=$product_desc;
553
-				$fk_unit= GETPOST('units', 'alpha');
554
-			}
555
-
556
-			$localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty,$mysoc,$tva_npr);
557
-			$localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty,$mysoc,$tva_npr);
558
-
559
-			// ajout prix achat
560
-			$fk_fournprice = $_POST['fournprice'];
561
-			if ( ! empty($_POST['buying_price']) )
562
-			  $pa_ht = $_POST['buying_price'];
563
-			else
564
-			  $pa_ht = null;
565
-
566
-			$info_bits=0;
567
-			if ($tva_npr) $info_bits |= 0x01;
568
-
569
-			if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS) )&& ($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))))
570
-			{
571
-				$object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency));
572
-				$result = -1 ;
573
-			}
574
-			else
575
-			{
576
-				// Insert line
577
-				$result = $object->addline(
578
-					$desc,
579
-					$pu_ht,
580
-					$qty,
581
-					$tva_tx,
582
-					$localtax1_tx,
583
-					$localtax2_tx,
584
-					$idprod,
585
-					$remise_percent,
586
-					$date_start,
587
-					$date_end,
588
-					$price_base_type,
589
-					$pu_ttc,
590
-					$info_bits,
591
-		  			$fk_fournprice,
592
-		  			$pa_ht,
593
-					$array_options,
594
-					$fk_unit
595
-				);
596
-			}
597
-
598
-			if ($result > 0)
599
-			{
600
-				// Define output language
601
-				if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && ! empty($conf->global->CONTRACT_ADDON_PDF))    // No generation if default type not defined
602
-				{
603
-					$outputlangs = $langs;
604
-					$newlang = '';
605
-					if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
606
-					if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
607
-					if (! empty($newlang)) {
608
-						$outputlangs = new Translate("", $conf);
609
-						$outputlangs->setDefaultLang($newlang);
610
-					}
611
-
612
-					$ret = $object->fetch($id); // Reload to get new records
613
-
614
-					$object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
615
-				}
616
-
617
-				unset($_POST ['prod_entry_mode']);
618
-
619
-				unset($_POST['qty']);
620
-				unset($_POST['type']);
621
-				unset($_POST['remise_percent']);
622
-				unset($_POST['price_ht']);
623
-				unset($_POST['multicurrency_price_ht']);
624
-				unset($_POST['price_ttc']);
625
-				unset($_POST['tva_tx']);
626
-				unset($_POST['product_ref']);
627
-				unset($_POST['product_label']);
628
-				unset($_POST['product_desc']);
629
-				unset($_POST['fournprice']);
630
-				unset($_POST['buying_price']);
631
-				unset($_POST ['np_marginRate']);
632
-				unset($_POST ['np_markRate']);
633
-				unset($_POST['dp_desc']);
634
-				unset($_POST['idprod']);
635
-
636
-				unset($_POST['date_starthour']);
637
-				unset($_POST['date_startmin']);
638
-				unset($_POST['date_startsec']);
639
-				unset($_POST['date_startday']);
640
-				unset($_POST['date_startmonth']);
641
-				unset($_POST['date_startyear']);
642
-				unset($_POST['date_endhour']);
643
-				unset($_POST['date_endmin']);
644
-				unset($_POST['date_endsec']);
645
-				unset($_POST['date_endday']);
646
-				unset($_POST['date_endmonth']);
647
-				unset($_POST['date_endyear']);
648
-			}
649
-			else
650
-			{
651
-				setEventMessages($object->error, $object->errors, 'errors');
652
-			}
653
-		}
654
-	}
174
+    // Param dates
175
+    $date_contrat='';
176
+    $date_start_update='';
177
+    $date_end_update='';
178
+    $date_start_real_update='';
179
+    $date_end_real_update='';
180
+    if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear'))
181
+    {
182
+        $date_start_update=dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear'));
183
+    }
184
+    if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear'))
185
+    {
186
+        $date_end_update=dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear'));
187
+    }
188
+    if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear'))
189
+    {
190
+        $date_start_real_update=dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear'));
191
+    }
192
+    if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear'))
193
+    {
194
+        $date_end_real_update=dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear'));
195
+    }
196
+    if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear'))
197
+    {
198
+        $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
199
+    }
655 200
 
656
-	else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel','alpha'))
657
-	{
658
-		$error = 0;
659
-
660
-		if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update)
661
-		{
662
-			setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
663
-			$action = 'editline';
664
-			$_GET['rowid'] = GETPOST('elrowid');
665
-			$error++;
666
-		}
667
-
668
-		if (! $error)
669
-		{
670
-			$objectline = new ContratLigne($db);
671
-			if ($objectline->fetch(GETPOST('elrowid')) < 0)
672
-			{
673
-				setEventMessages($objectline->error, $objectline->errors, 'errors');
674
-				$error++;
675
-			}
676
-		}
677
-
678
-		$db->begin();
679
-
680
-		if (! $error)
681
-		{
682
-			if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture;
683
-			if ($date_end_real_update == '')   $date_end_real_update=$objectline->date_cloture;
684
-
685
-			$vat_rate = GETPOST('eltva_tx');
686
-			// Define info_bits
687
-			$info_bits = 0;
688
-			if (preg_match('/\*/', $vat_rate))
689
-				  $info_bits |= 0x01;
690
-
691
-			// Define vat_rate
692
-			$vat_rate = str_replace('*', '', $vat_rate);
693
-			$localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
694
-			$localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
695
-
696
-			$txtva = $vat_rate;
697
-
698
-			// Clean vat code
699
-			$vat_src_code='';
700
-			if (preg_match('/\((.*)\)/', $txtva, $reg))
701
-			{
702
-				  $vat_src_code = $reg[1];
703
-				  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
704
-			}
705
-
706
-			// ajout prix d'achat
707
-			$fk_fournprice = $_POST['fournprice'];
708
-			if ( ! empty($_POST['buying_price']) )
709
-			  $pa_ht = $_POST['buying_price'];
710
-			else
711
-			  $pa_ht = null;
712
-
713
-			$fk_unit = GETPOST('unit', 'alpha');
714
-
715
-			$objectline->description=GETPOST('product_desc','none');
716
-			$objectline->price_ht=GETPOST('elprice');
717
-			$objectline->subprice=GETPOST('elprice');
718
-			$objectline->qty=GETPOST('elqty');
719
-			$objectline->remise_percent=GETPOST('elremise_percent');
720
-			$objectline->tva_tx=($txtva?$txtva:0);	// Field may be disabled, so we use vat rate 0
721
-			$objectline->vat_src_code=$vat_src_code;
722
-			$objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0;
723
-			$objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0;
724
-			$objectline->date_ouverture_prevue=$date_start_update;
725
-			$objectline->date_ouverture=$date_start_real_update;
726
-			$objectline->date_fin_validite=$date_end_update;
727
-			$objectline->date_cloture=$date_end_real_update;
728
-			$objectline->fk_user_cloture=$user->id;
729
-			$objectline->fk_fournprice=$fk_fournprice;
730
-			$objectline->pa_ht=$pa_ht;
731
-
732
-			if ($fk_unit > 0) {
733
-			  $objectline->fk_unit = GETPOST('unit');
734
-			} else {
735
-			  $objectline->fk_unit = null;
736
-			}
737
-
738
-			// Extrafields
739
-			$extrafieldsline = new ExtraFields($db);
740
-			$extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element);
741
-			$array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
742
-			$objectline->array_options=$array_options;
743
-
744
-			// TODO verifier price_min si fk_product et multiprix
745
-
746
-			$result=$objectline->update($user);
747
-			if ($result < 0)
748
-			{
749
-				$error++;
750
-				setEventMessages($objectline->error, $objectline->errors, 'errors');
751
-			}
752
-		}
753
-
754
-		if (! $error)
755
-		{
756
-			$db->commit();
757
-		}
758
-		else
759
-		{
760
-			$db->rollback();
761
-		}
762
-	}
201
+    // Add contract
202
+    if ($action == 'add' && $user->rights->contrat->creer)
203
+    {
204
+        // Check
205
+        if (empty($datecontrat))
206
+        {
207
+            $error++;
208
+            setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
209
+            $action='create';
210
+        }
763 211
 
764
-	else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer)
765
-	{
766
-		$result = $object->deleteline(GETPOST('lineid'),$user);
767
-
768
-		if ($result >= 0)
769
-		{
770
-			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
771
-			exit;
772
-		}
773
-		else
774
-		{
775
-			setEventMessages($object->error, $object->errors, 'errors');
776
-		}
777
-	}
212
+        if ($socid<1)
213
+        {
214
+            setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors');
215
+            $action='create';
216
+            $error++;
217
+        }
778 218
 
779
-	else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer)
780
-	{
781
-		$result = $object->validate($user);
782
-
783
-		if ($result > 0)
784
-		{
785
-			// Define output language
786
-			if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
787
-			{
788
-				$outputlangs = $langs;
789
-				$newlang = '';
790
-				if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
791
-				if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
792
-				if (! empty($newlang)) {
793
-					$outputlangs = new Translate("", $conf);
794
-					$outputlangs->setDefaultLang($newlang);
795
-				}
796
-				$model=$object->modelpdf;
797
-				$ret = $object->fetch($id); // Reload to get new records
798
-
799
-				$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
800
-			}
801
-		}
802
-		else
803
-		{
804
-			setEventMessages($object->error, $object->errors, 'errors');
805
-		}
806
-	}
219
+        // Fill array 'array_options' with data from add form
220
+        $ret = $extrafields->setOptionalsFromPost($extralabels, $object);
221
+        if ($ret < 0) {
222
+            $error ++;
223
+            $action = 'create';
224
+        }
807 225
 
808
-	else if ($action == 'reopen' && $user->rights->contrat->creer)
809
-	{
810
-		$result = $object->reopen($user);
811
-		if ($result < 0)
812
-		{
813
-			setEventMessages($object->error, $object->errors, 'errors');
814
-		}
815
-	}
226
+        if (! $error)
227
+        {
228
+            $object->socid						= $socid;
229
+            $object->date_contrat				= $datecontrat;
230
+
231
+            $object->commercial_suivi_id		= GETPOST('commercial_suivi_id','int');
232
+            $object->commercial_signature_id	= GETPOST('commercial_signature_id','int');
233
+
234
+            $object->note_private				= GETPOST('note_private','alpha');
235
+            $object->note_public				= GETPOST('note_public','alpha');
236
+            $object->fk_project					= GETPOST('projectid','int');
237
+            $object->remise_percent				= GETPOST('remise_percent','alpha');
238
+            $object->ref						= GETPOST('ref','alpha');
239
+            $object->ref_customer				= GETPOST('ref_customer','alpha');
240
+            $object->ref_supplier				= GETPOST('ref_supplier','alpha');
241
+
242
+            // If creation from another object of another module (Example: origin=propal, originid=1)
243
+            if (! empty($origin) && ! empty($originid))
244
+            {
245
+                // Parse element/subelement (ex: project_task)
246
+                $element = $subelement = $origin;
247
+                if (preg_match('/^([^_]+)_([^_]+)/i',$origin,$regs))
248
+                {
249
+                    $element = $regs[1];
250
+                    $subelement = $regs[2];
251
+                }
252
+
253
+                // For compatibility
254
+                if ($element == 'order')    { $element = $subelement = 'commande'; }
255
+                if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
256
+
257
+                $object->origin    = $origin;
258
+                $object->origin_id = $originid;
259
+
260
+                // Possibility to add external linked objects with hooks
261
+                $object->linked_objects[$object->origin] = $object->origin_id;
262
+                if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects']))
263
+                {
264
+                    $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
265
+                }
266
+
267
+                $id = $object->create($user);
268
+                if ($id < 0) {
269
+                    setEventMessages($object->error, $object->errors, 'errors');
270
+                }
271
+
272
+                if ($id > 0)
273
+                {
274
+                    dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
275
+
276
+                    $classname = ucfirst($subelement);
277
+                    $srcobject = new $classname($db);
278
+
279
+                    dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
280
+                    $result=$srcobject->fetch($object->origin_id);
281
+                    if ($result > 0)
282
+                    {
283
+                        $srcobject->fetch_thirdparty();
284
+                        $lines = $srcobject->lines;
285
+                        if (empty($lines) && method_exists($srcobject,'fetch_lines'))
286
+                        {
287
+                            $srcobject->fetch_lines();
288
+                            $lines = $srcobject->lines;
289
+                        }
290
+
291
+                        $fk_parent_line=0;
292
+                        $num=count($lines);
293
+
294
+                        for ($i=0;$i<$num;$i++)
295
+                        {
296
+                            $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
297
+
298
+                            if ($product_type == 1 || (! empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0,1)))) { 	// TODO Exclude also deee
299
+                                // service prédéfini
300
+                                if ($lines[$i]->fk_product > 0)
301
+                                {
302
+                                    $product_static = new Product($db);
303
+
304
+                                    // Define output language
305
+                                    if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE))
306
+                                    {
307
+                                        $prod = new Product($db);
308
+                                        $prod->id=$lines[$i]->fk_product;
309
+                                        $prod->getMultiLangs();
310
+
311
+                                        $outputlangs = $langs;
312
+                                        $newlang='';
313
+                                        if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
314
+                                        if (empty($newlang)) $newlang=$srcobject->thirdparty->default_lang;
315
+                                        if (! empty($newlang))
316
+                                        {
317
+                                            $outputlangs = new Translate("",$conf);
318
+                                            $outputlangs->setDefaultLang($newlang);
319
+                                        }
320
+
321
+                                        $label = (! empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
322
+                                    }
323
+                                    else
324
+                                    {
325
+                                        $label = $lines[$i]->product_label;
326
+                                    }
327
+                                    $desc = ($lines[$i]->desc && $lines[$i]->desc!=$lines[$i]->libelle)?dol_htmlentitiesbr($lines[$i]->desc):'';
328
+                                }
329
+                                else {
330
+                                    $desc = dol_htmlentitiesbr($lines[$i]->desc);
331
+                                }
332
+
333
+                                // Extrafields
334
+                                $array_options = array();
335
+                                if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) 							// For avoid conflicts if
336
+                                // trigger used
337
+                                {
338
+                                    $lines[$i]->fetch_optionals($lines[$i]->rowid);
339
+                                    $array_options = $lines[$i]->array_options;
340
+                                }
341
+
342
+                                $txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx . ' (' .  $lines[$i]->vat_src_code . ')' : $lines[$i]->tva_tx;
343
+
344
+                                // View third's localtaxes for now
345
+                                $localtax1_tx = get_localtax($txtva, 1, $object->thirdparty);
346
+                                $localtax2_tx = get_localtax($txtva, 2, $object->thirdparty);
347
+
348
+                                $result = $object->addline(
349
+                                    $desc,
350
+                                    $lines[$i]->subprice,
351
+                                    $lines[$i]->qty,
352
+                                    $txtva,
353
+                                    $localtax1_tx,
354
+                                    $localtax2_tx,
355
+                                    $lines[$i]->fk_product,
356
+                                    $lines[$i]->remise_percent,
357
+                                    $lines[$i]->date_start,
358
+                                    $lines[$i]->date_end,
359
+                                    'HT',
360
+                                    0,
361
+                                    $lines[$i]->info_bits,
362
+                                    $lines[$i]->fk_fournprice,
363
+                                    $lines[$i]->pa_ht,
364
+                                    $array_options,
365
+                                    $lines[$i]->fk_unit
366
+                                );
367
+
368
+                                if ($result < 0)
369
+                                {
370
+                                    $error++;
371
+                                    break;
372
+                                }
373
+                            }
374
+                        }
375
+                    }
376
+                    else
377
+                    {
378
+                        setEventMessages($srcobject->error, $srcobject->errors, 'errors');
379
+                        $error++;
380
+                    }
381
+
382
+                    // Hooks
383
+                    $parameters = array('objFrom' => $srcobject);
384
+                    $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
385
+                    // modified by hook
386
+                    if ($reshook < 0)
387
+                        $error++;
388
+                }
389
+                else
390
+                {
391
+                    setEventMessages($object->error, $object->errors, 'errors');
392
+                    $error++;
393
+                }
394
+            }
395
+            else
396
+            {
397
+                $result = $object->create($user);
398
+                if ($result > 0)
399
+                {
400
+                    header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
401
+                    exit;
402
+                }
403
+                else {
404
+                    setEventMessages($object->error, $object->errors, 'errors');
405
+                }
406
+                $action='create';
407
+            }
408
+        }
409
+    }
816 410
 
817
-	// Close all lines
818
-	else if ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer)
819
-	{
820
-		$result = $object->closeAll($user);
821
-		if ($result < 0)
822
-		{
823
-			setEventMessages($object->error, $object->errors, 'errors');
824
-		}
825
-	}
411
+    else if ($action == 'classin' && $user->rights->contrat->creer)
412
+    {
413
+        $object->setProject(GETPOST('projectid'));
414
+    }
826 415
 
827
-	// Close all lines
828
-	else if ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer)
829
-	{
830
-		$result = $object->activateAll($user);
831
-		if ($result < 0)
832
-		{
833
-			setEventMessages($object->error, $object->errors, 'errors');
834
-		}
835
-	}
416
+    // Add a new line
417
+    else if ($action == 'addline' && $user->rights->contrat->creer)
418
+    {
419
+        // Set if we used free entry or predefined product
420
+        $predef='';
421
+        $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
422
+        $price_ht = GETPOST('price_ht');
423
+        $price_ht_devise = GETPOST('multicurrency_price_ht');
424
+        if (GETPOST('prod_entry_mode') == 'free')
425
+        {
426
+            $idprod=0;
427
+            $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
428
+        }
429
+        else
430
+        {
431
+            $idprod=GETPOST('idprod', 'int');
432
+            $tva_tx = '';
433
+        }
836 434
 
837
-	else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer)
838
-	{
839
-		$result=$object->delete($user);
840
-		if ($result >= 0)
841
-		{
842
-			header("Location: list.php?restore_lastsearch_values=1");
843
-			return;
844
-		}
845
-		else
846
-		{
847
-			setEventMessages($object->error, $object->errors, 'errors');
848
-		}
849
-	}
435
+        $qty = GETPOST('qty'.$predef);
436
+        $remise_percent = GETPOST('remise_percent'.$predef);
850 437
 
851
-	else if ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer)
852
-	{
853
-		if (GETPOST('newcid') > 0)
854
-		{
855
-			$contractline = new ContratLigne($db);
856
-			$result=$contractline->fetch(GETPOST('lineid'));
857
-			$contractline->fk_contrat = GETPOST('newcid');
858
-			$result=$contractline->update($user,1);
859
-			if ($result >= 0)
860
-			{
861
-				header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
862
-				return;
863
-			}
864
-			else
865
-			{
866
-				setEventMessages($object->error, $object->errors, 'errors');
867
-			}
868
-		}
869
-		else
870
-		{
871
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefNewContract")), null, 'errors');
872
-		}
873
-	}
874
-	else if ($action == 'update_extras')
875
-	{
876
-		$object->oldcopy = dol_clone($object);
877
-
878
-		// Fill array 'array_options' with data from update form
879
-		$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
880
-		$ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none'));
881
-		if ($ret < 0) $error++;
882
-
883
-		if (! $error) {
884
-			$result = $object->insertExtraFields('CONTRACT_MODIFY');
885
-			if ($result < 0)
886
-			{
887
-				setEventMessages($object->error, $object->errors, 'errors');
888
-				$error++;
889
-			}
890
-		}
891
-
892
-		if ($error) {
893
-			$action = 'edit_extras';
894
-		}
895
-	}
896
-	elseif ($action=='setref_supplier')
897
-	{
898
-		$cancelbutton = GETPOST('cancel','alpha');
899
-		if (!$cancelbutton) {
900
-
901
-			$object->oldcopy = dol_clone($object);
902
-
903
-			$result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
904
-			if ($result < 0) {
905
-				setEventMessages($object->error, $object->errors, 'errors');
906
-				$action = 'editref_supplier';
907
-			} else {
908
-				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
909
-				exit;
910
-			}
911
-		}
912
-		else {
913
-			header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
914
-			exit;
915
-		}
916
-	}
917
-	elseif ($action=='setref_customer')
918
-	{
919
-		$cancelbutton = GETPOST('cancel','alpha');
920
-
921
-		if (!$cancelbutton)
922
-		{
923
-			$object->oldcopy = dol_clone($object);
924
-
925
-			$result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
926
-			if ($result < 0) {
927
-				setEventMessages($object->error, $object->errors, 'errors');
928
-				$action = 'editref_customer';
929
-			} else {
930
-				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
931
-				exit;
932
-			}
933
-		}
934
-		else {
935
-			header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
936
-			exit;
937
-		}
938
-	}
939
-	elseif ($action=='setref')
940
-	{
941
-		$cancelbutton = GETPOST('cancel','alpha');
942
-
943
-		if (!$cancelbutton) {
944
-			$result = $object->fetch($id);
945
-			if ($result < 0) {
946
-				setEventMessages($object->error, $object->errors, 'errors');
947
-			}
948
-
949
-			$old_ref = $object->ref;
950
-
951
-	        $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
952
-	        if ($result < 0) {
953
-	            setEventMessages($object->error, $object->errors, 'errors');
954
-	            $action = 'editref';
955
-	        } else {
956
-				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
957
-				$old_filedir = $conf->contrat->dir_output . '/' . dol_sanitizeFileName($old_ref);
958
-				$new_filedir = $conf->contrat->dir_output . '/' . dol_sanitizeFileName($object->ref);
959
-
960
-				$files = dol_dir_list($old_filedir);
961
-				if (!empty($files))
962
-				{
963
-					if (!is_dir($new_filedir)) dol_mkdir($new_filedir);
964
-					foreach ($files as $file)
965
-					{
966
-						dol_move($file['fullname'], $new_filedir.'/'.$file['name']);
967
-					}
968
-				}
969
-
970
-	            header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
971
-	            exit;
972
-	        }
973
-	    }
974
-	    else {
975
-	        header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
976
-	        exit;
977
-	    }
978
-	}
979
-	elseif ($action=='setdate_contrat')
980
-	{
981
-		$cancelbutton = GETPOST('cancel','alpha');
982
-
983
-		if (!$cancelbutton) {
984
-			$result = $object->fetch($id);
985
-			if ($result < 0) {
986
-				setEventMessages($object->error, $object->errors, 'errors');
987
-			}
988
-			$datacontrat=dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear'));
989
-			$result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY');
990
-			if ($result < 0) {
991
-				setEventMessages($object->error, $object->errors, 'errors');
992
-				$action = 'editdate_contrat';
993
-			} else {
994
-				header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
995
-				exit;
996
-			}
997
-		}
998
-		else {
999
-			header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
1000
-			exit;
1001
-		}
1002
-	}
438
+        if ($qty == '')
439
+        {
440
+            setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors');
441
+            $error++;
442
+        }
443
+        if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc))
444
+        {
445
+            setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors');
446
+            $error++;
447
+        }
1003 448
 
449
+        $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year'));
450
+        $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year'));
451
+        if (!empty($date_start) && !empty($date_end) && $date_start > $date_end)
452
+        {
453
+            setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
454
+            $error++;
455
+        }
1004 456
 
1005
-	// Actions to build doc
1006
-	$upload_dir = $conf->contrat->dir_output;
1007
-	$permissioncreate = $user->rights->contrat->creer;
1008
-	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
1009
-
1010
-	// Actions to send emails
1011
-	$trigger_name='CONTRACT_SENTBYMAIL';
1012
-	$paramname='id';
1013
-	$mode='emailfromcontract';
1014
-	$trackid='con'.$object->id;
1015
-	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
1016
-
1017
-
1018
-	if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer)
1019
-	{
1020
-		if ($action == 'addcontact')
1021
-		{
1022
-			$contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
1023
-			$result = $object->add_contact($contactid, GETPOST('type'), GETPOST('source'));
1024
-
1025
-			if ($result >= 0)
1026
-			{
1027
-				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1028
-				exit;
1029
-			}
1030
-			else
1031
-			{
1032
-				if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1033
-				{
1034
-					$langs->load("errors");
1035
-					setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
1036
-				}
1037
-				else
1038
-				{
1039
-					setEventMessages($object->error, $object->errors, 'errors');
1040
-				}
1041
-			}
1042
-		}
1043
-
1044
-		// bascule du statut d'un contact
1045
-		else if ($action == 'swapstatut')
1046
-		{
1047
-			$result=$object->swapContactStatus(GETPOST('ligne'));
1048
-		}
1049
-
1050
-		// Efface un contact
1051
-		else if ($action == 'deletecontact')
1052
-		{
1053
-			$result = $object->delete_contact(GETPOST('lineid'));
1054
-
1055
-			if ($result >= 0)
1056
-			{
1057
-				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1058
-				exit;
1059
-			}
1060
-			else {
1061
-				setEventMessages($object->error, $object->errors, 'errors');
1062
-			}
1063
-		}
1064
-	}
457
+        // Extrafields
458
+        $extrafieldsline = new ExtraFields($db);
459
+        $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
460
+        $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
461
+        // Unset extrafield
462
+        if (is_array($extralabelsline)) {
463
+            // Get extra fields
464
+            foreach ($extralabelsline as $key => $value) {
465
+                unset($_POST["options_" . $key]);
466
+            }
467
+        }
1065 468
 
1066
-	// Action clone object
1067
-	if ($action == 'confirm_clone' && $confirm == 'yes')
1068
-	{
1069
-		if (! GETPOST('socid', 3))
1070
-		{
1071
-			setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
1072
-		}
1073
-		else
1074
-		{
1075
-			if ($object->id > 0) {
1076
-				$result = $object->createFromClone($socid);
1077
-				if ($result > 0) {
1078
-					header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result);
1079
-					exit();
1080
-				} else {
1081
-					if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors');
1082
-					$action = '';
1083
-				}
1084
-			}
1085
-		}
1086
-	}
469
+        if (! $error)
470
+        {
471
+            // Clean parameters
472
+            $date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
473
+            $date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
474
+            $price_base_type = (GETPOST('price_base_type', 'alpha')?GETPOST('price_base_type', 'alpha'):'HT');
475
+
476
+            // Ecrase $pu par celui du produit
477
+            // Ecrase $desc par celui du produit
478
+            // Ecrase $tva_tx par celui du produit
479
+            // Ecrase $base_price_type par celui du produit
480
+            if ($idprod > 0)
481
+            {
482
+                $prod = new Product($db);
483
+                $prod->fetch($idprod);
484
+
485
+                // Update if prices fields are defined
486
+                $tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id);
487
+                $tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id);
488
+                if (empty($tva_tx)) $tva_npr=0;
489
+
490
+                $pu_ht = $prod->price;
491
+                $pu_ttc = $prod->price_ttc;
492
+                $price_min = $prod->price_min;
493
+                $price_base_type = $prod->price_base_type;
494
+
495
+                // On defini prix unitaire
496
+                if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level)
497
+                {
498
+                    $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
499
+                    $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
500
+                    $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
501
+                    $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
502
+                }
503
+                elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
504
+                {
505
+                    require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
506
+
507
+                    $prodcustprice = new Productcustomerprice($db);
508
+
509
+                    $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id);
510
+
511
+                    $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
512
+                    if ($result) {
513
+                        if (count($prodcustprice->lines) > 0) {
514
+                            $pu_ht = price($prodcustprice->lines [0]->price);
515
+                            $pu_ttc = price($prodcustprice->lines [0]->price_ttc);
516
+                            $price_base_type = $prodcustprice->lines [0]->price_base_type;
517
+                            $tva_tx = $prodcustprice->lines [0]->tva_tx;
518
+                            if ($prodcustprice->lines[0]->default_vat_code && ! preg_match('/\(.*\)/', $tva_tx)) $tva_tx.= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
519
+                            $tva_npr = $prodcustprice->lines[0]->recuperableonly;
520
+                            if (empty($tva_tx)) $tva_npr=0;
521
+                        }
522
+                    }
523
+                }
524
+
525
+                $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
526
+                $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
527
+
528
+                // On reevalue prix selon taux tva car taux tva transaction peut etre different
529
+                // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
530
+                if ($tmpvat != $tmpprodvat)
531
+                {
532
+                    if ($price_base_type != 'HT')
533
+                    {
534
+                        $pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU');
535
+                    }
536
+                    else
537
+                    {
538
+                        $pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU');
539
+                    }
540
+                }
541
+
542
+                    $desc=$prod->description;
543
+                    $desc=dol_concatdesc($desc,$product_desc, '', !empty($conf->global->CHANGE_ORDER_CONCAT_DESCRIPTION));
544
+                $fk_unit = $prod->fk_unit;
545
+            }
546
+            else
547
+            {
548
+                $pu_ht=GETPOST('price_ht');
549
+                $price_base_type = 'HT';
550
+                $tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0;		// tva_tx field may be disabled, so we use vat rate 0
551
+                $tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0;
552
+                $desc=$product_desc;
553
+                $fk_unit= GETPOST('units', 'alpha');
554
+            }
555
+
556
+            $localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty,$mysoc,$tva_npr);
557
+            $localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty,$mysoc,$tva_npr);
558
+
559
+            // ajout prix achat
560
+            $fk_fournprice = $_POST['fournprice'];
561
+            if ( ! empty($_POST['buying_price']) )
562
+                $pa_ht = $_POST['buying_price'];
563
+            else
564
+                $pa_ht = null;
565
+
566
+            $info_bits=0;
567
+            if ($tva_npr) $info_bits |= 0x01;
568
+
569
+            if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS) )&& ($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))))
570
+            {
571
+                $object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency));
572
+                $result = -1 ;
573
+            }
574
+            else
575
+            {
576
+                // Insert line
577
+                $result = $object->addline(
578
+                    $desc,
579
+                    $pu_ht,
580
+                    $qty,
581
+                    $tva_tx,
582
+                    $localtax1_tx,
583
+                    $localtax2_tx,
584
+                    $idprod,
585
+                    $remise_percent,
586
+                    $date_start,
587
+                    $date_end,
588
+                    $price_base_type,
589
+                    $pu_ttc,
590
+                    $info_bits,
591
+                        $fk_fournprice,
592
+                        $pa_ht,
593
+                    $array_options,
594
+                    $fk_unit
595
+                );
596
+            }
597
+
598
+            if ($result > 0)
599
+            {
600
+                // Define output language
601
+                if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && ! empty($conf->global->CONTRACT_ADDON_PDF))    // No generation if default type not defined
602
+                {
603
+                    $outputlangs = $langs;
604
+                    $newlang = '';
605
+                    if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
606
+                    if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
607
+                    if (! empty($newlang)) {
608
+                        $outputlangs = new Translate("", $conf);
609
+                        $outputlangs->setDefaultLang($newlang);
610
+                    }
611
+
612
+                    $ret = $object->fetch($id); // Reload to get new records
613
+
614
+                    $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
615
+                }
616
+
617
+                unset($_POST ['prod_entry_mode']);
618
+
619
+                unset($_POST['qty']);
620
+                unset($_POST['type']);
621
+                unset($_POST['remise_percent']);
622
+                unset($_POST['price_ht']);
623
+                unset($_POST['multicurrency_price_ht']);
624
+                unset($_POST['price_ttc']);
625
+                unset($_POST['tva_tx']);
626
+                unset($_POST['product_ref']);
627
+                unset($_POST['product_label']);
628
+                unset($_POST['product_desc']);
629
+                unset($_POST['fournprice']);
630
+                unset($_POST['buying_price']);
631
+                unset($_POST ['np_marginRate']);
632
+                unset($_POST ['np_markRate']);
633
+                unset($_POST['dp_desc']);
634
+                unset($_POST['idprod']);
635
+
636
+                unset($_POST['date_starthour']);
637
+                unset($_POST['date_startmin']);
638
+                unset($_POST['date_startsec']);
639
+                unset($_POST['date_startday']);
640
+                unset($_POST['date_startmonth']);
641
+                unset($_POST['date_startyear']);
642
+                unset($_POST['date_endhour']);
643
+                unset($_POST['date_endmin']);
644
+                unset($_POST['date_endsec']);
645
+                unset($_POST['date_endday']);
646
+                unset($_POST['date_endmonth']);
647
+                unset($_POST['date_endyear']);
648
+            }
649
+            else
650
+            {
651
+                setEventMessages($object->error, $object->errors, 'errors');
652
+            }
653
+        }
654
+    }
655
+
656
+    else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel','alpha'))
657
+    {
658
+        $error = 0;
659
+
660
+        if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update)
661
+        {
662
+            setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
663
+            $action = 'editline';
664
+            $_GET['rowid'] = GETPOST('elrowid');
665
+            $error++;
666
+        }
667
+
668
+        if (! $error)
669
+        {
670
+            $objectline = new ContratLigne($db);
671
+            if ($objectline->fetch(GETPOST('elrowid')) < 0)
672
+            {
673
+                setEventMessages($objectline->error, $objectline->errors, 'errors');
674
+                $error++;
675
+            }
676
+        }
677
+
678
+        $db->begin();
679
+
680
+        if (! $error)
681
+        {
682
+            if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture;
683
+            if ($date_end_real_update == '')   $date_end_real_update=$objectline->date_cloture;
684
+
685
+            $vat_rate = GETPOST('eltva_tx');
686
+            // Define info_bits
687
+            $info_bits = 0;
688
+            if (preg_match('/\*/', $vat_rate))
689
+                    $info_bits |= 0x01;
690
+
691
+            // Define vat_rate
692
+            $vat_rate = str_replace('*', '', $vat_rate);
693
+            $localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
694
+            $localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
695
+
696
+            $txtva = $vat_rate;
697
+
698
+            // Clean vat code
699
+            $vat_src_code='';
700
+            if (preg_match('/\((.*)\)/', $txtva, $reg))
701
+            {
702
+                    $vat_src_code = $reg[1];
703
+                    $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
704
+            }
705
+
706
+            // ajout prix d'achat
707
+            $fk_fournprice = $_POST['fournprice'];
708
+            if ( ! empty($_POST['buying_price']) )
709
+                $pa_ht = $_POST['buying_price'];
710
+            else
711
+                $pa_ht = null;
712
+
713
+            $fk_unit = GETPOST('unit', 'alpha');
714
+
715
+            $objectline->description=GETPOST('product_desc','none');
716
+            $objectline->price_ht=GETPOST('elprice');
717
+            $objectline->subprice=GETPOST('elprice');
718
+            $objectline->qty=GETPOST('elqty');
719
+            $objectline->remise_percent=GETPOST('elremise_percent');
720
+            $objectline->tva_tx=($txtva?$txtva:0);	// Field may be disabled, so we use vat rate 0
721
+            $objectline->vat_src_code=$vat_src_code;
722
+            $objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0;
723
+            $objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0;
724
+            $objectline->date_ouverture_prevue=$date_start_update;
725
+            $objectline->date_ouverture=$date_start_real_update;
726
+            $objectline->date_fin_validite=$date_end_update;
727
+            $objectline->date_cloture=$date_end_real_update;
728
+            $objectline->fk_user_cloture=$user->id;
729
+            $objectline->fk_fournprice=$fk_fournprice;
730
+            $objectline->pa_ht=$pa_ht;
731
+
732
+            if ($fk_unit > 0) {
733
+                $objectline->fk_unit = GETPOST('unit');
734
+            } else {
735
+                $objectline->fk_unit = null;
736
+            }
737
+
738
+            // Extrafields
739
+            $extrafieldsline = new ExtraFields($db);
740
+            $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element);
741
+            $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
742
+            $objectline->array_options=$array_options;
743
+
744
+            // TODO verifier price_min si fk_product et multiprix
745
+
746
+            $result=$objectline->update($user);
747
+            if ($result < 0)
748
+            {
749
+                $error++;
750
+                setEventMessages($objectline->error, $objectline->errors, 'errors');
751
+            }
752
+        }
753
+
754
+        if (! $error)
755
+        {
756
+            $db->commit();
757
+        }
758
+        else
759
+        {
760
+            $db->rollback();
761
+        }
762
+    }
763
+
764
+    else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer)
765
+    {
766
+        $result = $object->deleteline(GETPOST('lineid'),$user);
767
+
768
+        if ($result >= 0)
769
+        {
770
+            header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
771
+            exit;
772
+        }
773
+        else
774
+        {
775
+            setEventMessages($object->error, $object->errors, 'errors');
776
+        }
777
+    }
778
+
779
+    else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer)
780
+    {
781
+        $result = $object->validate($user);
782
+
783
+        if ($result > 0)
784
+        {
785
+            // Define output language
786
+            if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
787
+            {
788
+                $outputlangs = $langs;
789
+                $newlang = '';
790
+                if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
791
+                if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
792
+                if (! empty($newlang)) {
793
+                    $outputlangs = new Translate("", $conf);
794
+                    $outputlangs->setDefaultLang($newlang);
795
+                }
796
+                $model=$object->modelpdf;
797
+                $ret = $object->fetch($id); // Reload to get new records
798
+
799
+                $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
800
+            }
801
+        }
802
+        else
803
+        {
804
+            setEventMessages($object->error, $object->errors, 'errors');
805
+        }
806
+    }
807
+
808
+    else if ($action == 'reopen' && $user->rights->contrat->creer)
809
+    {
810
+        $result = $object->reopen($user);
811
+        if ($result < 0)
812
+        {
813
+            setEventMessages($object->error, $object->errors, 'errors');
814
+        }
815
+    }
816
+
817
+    // Close all lines
818
+    else if ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer)
819
+    {
820
+        $result = $object->closeAll($user);
821
+        if ($result < 0)
822
+        {
823
+            setEventMessages($object->error, $object->errors, 'errors');
824
+        }
825
+    }
826
+
827
+    // Close all lines
828
+    else if ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer)
829
+    {
830
+        $result = $object->activateAll($user);
831
+        if ($result < 0)
832
+        {
833
+            setEventMessages($object->error, $object->errors, 'errors');
834
+        }
835
+    }
836
+
837
+    else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer)
838
+    {
839
+        $result=$object->delete($user);
840
+        if ($result >= 0)
841
+        {
842
+            header("Location: list.php?restore_lastsearch_values=1");
843
+            return;
844
+        }
845
+        else
846
+        {
847
+            setEventMessages($object->error, $object->errors, 'errors');
848
+        }
849
+    }
850
+
851
+    else if ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer)
852
+    {
853
+        if (GETPOST('newcid') > 0)
854
+        {
855
+            $contractline = new ContratLigne($db);
856
+            $result=$contractline->fetch(GETPOST('lineid'));
857
+            $contractline->fk_contrat = GETPOST('newcid');
858
+            $result=$contractline->update($user,1);
859
+            if ($result >= 0)
860
+            {
861
+                header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
862
+                return;
863
+            }
864
+            else
865
+            {
866
+                setEventMessages($object->error, $object->errors, 'errors');
867
+            }
868
+        }
869
+        else
870
+        {
871
+            setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefNewContract")), null, 'errors');
872
+        }
873
+    }
874
+    else if ($action == 'update_extras')
875
+    {
876
+        $object->oldcopy = dol_clone($object);
877
+
878
+        // Fill array 'array_options' with data from update form
879
+        $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
880
+        $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none'));
881
+        if ($ret < 0) $error++;
882
+
883
+        if (! $error) {
884
+            $result = $object->insertExtraFields('CONTRACT_MODIFY');
885
+            if ($result < 0)
886
+            {
887
+                setEventMessages($object->error, $object->errors, 'errors');
888
+                $error++;
889
+            }
890
+        }
891
+
892
+        if ($error) {
893
+            $action = 'edit_extras';
894
+        }
895
+    }
896
+    elseif ($action=='setref_supplier')
897
+    {
898
+        $cancelbutton = GETPOST('cancel','alpha');
899
+        if (!$cancelbutton) {
900
+
901
+            $object->oldcopy = dol_clone($object);
902
+
903
+            $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
904
+            if ($result < 0) {
905
+                setEventMessages($object->error, $object->errors, 'errors');
906
+                $action = 'editref_supplier';
907
+            } else {
908
+                header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
909
+                exit;
910
+            }
911
+        }
912
+        else {
913
+            header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
914
+            exit;
915
+        }
916
+    }
917
+    elseif ($action=='setref_customer')
918
+    {
919
+        $cancelbutton = GETPOST('cancel','alpha');
920
+
921
+        if (!$cancelbutton)
922
+        {
923
+            $object->oldcopy = dol_clone($object);
924
+
925
+            $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
926
+            if ($result < 0) {
927
+                setEventMessages($object->error, $object->errors, 'errors');
928
+                $action = 'editref_customer';
929
+            } else {
930
+                header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
931
+                exit;
932
+            }
933
+        }
934
+        else {
935
+            header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
936
+            exit;
937
+        }
938
+    }
939
+    elseif ($action=='setref')
940
+    {
941
+        $cancelbutton = GETPOST('cancel','alpha');
942
+
943
+        if (!$cancelbutton) {
944
+            $result = $object->fetch($id);
945
+            if ($result < 0) {
946
+                setEventMessages($object->error, $object->errors, 'errors');
947
+            }
948
+
949
+            $old_ref = $object->ref;
950
+
951
+            $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
952
+            if ($result < 0) {
953
+                setEventMessages($object->error, $object->errors, 'errors');
954
+                $action = 'editref';
955
+            } else {
956
+                require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
957
+                $old_filedir = $conf->contrat->dir_output . '/' . dol_sanitizeFileName($old_ref);
958
+                $new_filedir = $conf->contrat->dir_output . '/' . dol_sanitizeFileName($object->ref);
959
+
960
+                $files = dol_dir_list($old_filedir);
961
+                if (!empty($files))
962
+                {
963
+                    if (!is_dir($new_filedir)) dol_mkdir($new_filedir);
964
+                    foreach ($files as $file)
965
+                    {
966
+                        dol_move($file['fullname'], $new_filedir.'/'.$file['name']);
967
+                    }
968
+                }
969
+
970
+                header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
971
+                exit;
972
+            }
973
+        }
974
+        else {
975
+            header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
976
+            exit;
977
+        }
978
+    }
979
+    elseif ($action=='setdate_contrat')
980
+    {
981
+        $cancelbutton = GETPOST('cancel','alpha');
982
+
983
+        if (!$cancelbutton) {
984
+            $result = $object->fetch($id);
985
+            if ($result < 0) {
986
+                setEventMessages($object->error, $object->errors, 'errors');
987
+            }
988
+            $datacontrat=dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear'));
989
+            $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY');
990
+            if ($result < 0) {
991
+                setEventMessages($object->error, $object->errors, 'errors');
992
+                $action = 'editdate_contrat';
993
+            } else {
994
+                header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
995
+                exit;
996
+            }
997
+        }
998
+        else {
999
+            header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
1000
+            exit;
1001
+        }
1002
+    }
1003
+
1004
+
1005
+    // Actions to build doc
1006
+    $upload_dir = $conf->contrat->dir_output;
1007
+    $permissioncreate = $user->rights->contrat->creer;
1008
+    include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
1009
+
1010
+    // Actions to send emails
1011
+    $trigger_name='CONTRACT_SENTBYMAIL';
1012
+    $paramname='id';
1013
+    $mode='emailfromcontract';
1014
+    $trackid='con'.$object->id;
1015
+    include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
1016
+
1017
+
1018
+    if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer)
1019
+    {
1020
+        if ($action == 'addcontact')
1021
+        {
1022
+            $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
1023
+            $result = $object->add_contact($contactid, GETPOST('type'), GETPOST('source'));
1024
+
1025
+            if ($result >= 0)
1026
+            {
1027
+                header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1028
+                exit;
1029
+            }
1030
+            else
1031
+            {
1032
+                if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1033
+                {
1034
+                    $langs->load("errors");
1035
+                    setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
1036
+                }
1037
+                else
1038
+                {
1039
+                    setEventMessages($object->error, $object->errors, 'errors');
1040
+                }
1041
+            }
1042
+        }
1043
+
1044
+        // bascule du statut d'un contact
1045
+        else if ($action == 'swapstatut')
1046
+        {
1047
+            $result=$object->swapContactStatus(GETPOST('ligne'));
1048
+        }
1049
+
1050
+        // Efface un contact
1051
+        else if ($action == 'deletecontact')
1052
+        {
1053
+            $result = $object->delete_contact(GETPOST('lineid'));
1054
+
1055
+            if ($result >= 0)
1056
+            {
1057
+                header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1058
+                exit;
1059
+            }
1060
+            else {
1061
+                setEventMessages($object->error, $object->errors, 'errors');
1062
+            }
1063
+        }
1064
+    }
1065
+
1066
+    // Action clone object
1067
+    if ($action == 'confirm_clone' && $confirm == 'yes')
1068
+    {
1069
+        if (! GETPOST('socid', 3))
1070
+        {
1071
+            setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
1072
+        }
1073
+        else
1074
+        {
1075
+            if ($object->id > 0) {
1076
+                $result = $object->createFromClone($socid);
1077
+                if ($result > 0) {
1078
+                    header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result);
1079
+                    exit();
1080
+                } else {
1081
+                    if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors');
1082
+                    $action = '';
1083
+                }
1084
+            }
1085
+        }
1086
+    }
1087 1087
 }
1088 1088
 
1089 1089
 
@@ -1103,207 +1103,207 @@  discard block
 block discarded – undo
1103 1103
 $module=(! empty($conf->global->CONTRACT_ADDON)?$conf->global->CONTRACT_ADDON:'mod_contract_serpis');
1104 1104
 if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php')
1105 1105
 {
1106
-	$module = substr($module, 0, dol_strlen($module)-4);
1106
+    $module = substr($module, 0, dol_strlen($module)-4);
1107 1107
 }
1108 1108
 $result=dol_include_once('/core/modules/contract/'.$module.'.php');
1109 1109
 if ($result > 0)
1110 1110
 {
1111
-	$modCodeContract = new $module();
1111
+    $modCodeContract = new $module();
1112 1112
 }
1113 1113
 
1114 1114
 // Create
1115 1115
 if ($action == 'create')
1116 1116
 {
1117
-	print load_fiche_titre($langs->trans('AddContract'),'','title_commercial.png');
1118
-
1119
-	$soc = new Societe($db);
1120
-	if ($socid>0) $soc->fetch($socid);
1121
-
1122
-	if (GETPOST('origin') && GETPOST('originid'))
1123
-	{
1124
-		// Parse element/subelement (ex: project_task)
1125
-		$element = $subelement = GETPOST('origin');
1126
-		if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs))
1127
-		{
1128
-			$element = $regs[1];
1129
-			$subelement = $regs[2];
1130
-		}
1131
-
1132
-		if ($element == 'project')
1133
-		{
1134
-			$projectid=GETPOST('originid');
1135
-		}
1136
-		else
1137
-		{
1138
-			// For compatibility
1139
-			if ($element == 'order' || $element == 'commande')    { $element = $subelement = 'commande'; }
1140
-			if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
1141
-
1142
-			dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1143
-
1144
-			$classname = ucfirst($subelement);
1145
-			$objectsrc = new $classname($db);
1146
-			$objectsrc->fetch(GETPOST('originid'));
1147
-			if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines'))  $objectsrc->fetch_lines();
1148
-			$objectsrc->fetch_thirdparty();
1149
-
1150
-			// Replicate extrafields
1151
-			$objectsrc->fetch_optionals($originid);
1152
-			$object->array_options = $objectsrc->array_options;
1153
-
1154
-			$projectid          = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:'');
1155
-
1156
-			$soc = $objectsrc->thirdparty;
1157
-
1158
-			$note_private		= (! empty($objectsrc->note_private) ? $objectsrc->note_private : '');
1159
-			$note_public		= (! empty($objectsrc->note_public) ? $objectsrc->note_public : '');
1160
-
1161
-			// Object source contacts list
1162
-			$srccontactslist = $objectsrc->liste_contact(-1,'external',1);
1163
-		}
1164
-	}
1165
-	else {
1166
-		$projectid = GETPOST('projectid','int');
1167
-		$note_private = GETPOST("note_private");
1168
-		$note_public = GETPOST("note_public");
1169
-	}
1117
+    print load_fiche_titre($langs->trans('AddContract'),'','title_commercial.png');
1118
+
1119
+    $soc = new Societe($db);
1120
+    if ($socid>0) $soc->fetch($socid);
1121
+
1122
+    if (GETPOST('origin') && GETPOST('originid'))
1123
+    {
1124
+        // Parse element/subelement (ex: project_task)
1125
+        $element = $subelement = GETPOST('origin');
1126
+        if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs))
1127
+        {
1128
+            $element = $regs[1];
1129
+            $subelement = $regs[2];
1130
+        }
1170 1131
 
1171
-	$object->date_contrat = dol_now();
1132
+        if ($element == 'project')
1133
+        {
1134
+            $projectid=GETPOST('originid');
1135
+        }
1136
+        else
1137
+        {
1138
+            // For compatibility
1139
+            if ($element == 'order' || $element == 'commande')    { $element = $subelement = 'commande'; }
1140
+            if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
1172 1141
 
1173
-	print '<form name="form_contract" action="'.$_SERVER["PHP_SELF"].'" method="post">';
1174
-	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1142
+            dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1175 1143
 
1176
-	print '<input type="hidden" name="action" value="add">';
1177
-	print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
1178
-	print '<input type="hidden" name="remise_percent" value="0">';
1144
+            $classname = ucfirst($subelement);
1145
+            $objectsrc = new $classname($db);
1146
+            $objectsrc->fetch(GETPOST('originid'));
1147
+            if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines'))  $objectsrc->fetch_lines();
1148
+            $objectsrc->fetch_thirdparty();
1179 1149
 
1180
-	dol_fiche_head();
1150
+            // Replicate extrafields
1151
+            $objectsrc->fetch_optionals($originid);
1152
+            $object->array_options = $objectsrc->array_options;
1181 1153
 
1182
-	print '<table class="border" width="100%">';
1154
+            $projectid          = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:'');
1183 1155
 
1184
-	// Ref
1185
-	print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td>';
1186
-	if (! empty($modCodeContract->code_auto)) {
1187
-		$tmpcode=$langs->trans("Draft");
1188
-	} else {
1189
-		$tmpcode='<input name="ref" class="maxwidth100" maxlength="128" value="'.dol_escape_htmltag(GETPOST('ref')?GETPOST('ref'):$tmpcode).'">';
1190
-	}
1191
-	print $tmpcode;
1192
-	print '</td></tr>';
1193
-
1194
-	// Ref customer
1195
-	print '<tr><td>'.$langs->trans('RefCustomer').'</td>';
1196
-	print '<td><input type="text" class="maxwidth150" name="ref_customer" id="ref_customer" value="'.dol_escape_htmltag(GETPOST('ref_customer','alpha')).'"></td></tr>';
1197
-
1198
-	// Ref supplier
1199
-	print '<tr><td>'.$langs->trans('RefSupplier').'</td>';
1200
-	print '<td><input type="text" class="maxwidth150" name="ref_supplier" id="ref_supplier" value="'.dol_escape_htmltag(GETPOST('ref_supplier','alpha')).'"></td></tr>';
1201
-
1202
-	// Thirdparty
1203
-	print '<tr>';
1204
-	print '<td class="fieldrequired">'.$langs->trans('ThirdParty').'</td>';
1205
-	if ($socid>0)
1206
-	{
1207
-		print '<td>';
1208
-		print $soc->getNomUrl(1);
1209
-		print '<input type="hidden" name="socid" value="'.$soc->id.'">';
1210
-		print '</td>';
1211
-	}
1212
-	else
1213
-	{
1214
-		print '<td>';
1215
-		print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300');
1216
-		print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'">'.$langs->trans("AddThirdParty").'</a>';
1217
-		print '</td>';
1218
-	}
1219
-	print '</tr>'."\n";
1220
-
1221
-	if($socid>0)
1222
-	{
1223
-		// Ligne info remises tiers
1224
-		print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
1225
-		if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent);
1226
-		else print $langs->trans("CompanyHasNoRelativeDiscount");
1227
-		print '. ';
1228
-		$absolute_discount=$soc->getAvailableDiscounts();
1229
-		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1230
-		else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1231
-		print '.';
1232
-		print '</td></tr>';
1233
-	}
1156
+            $soc = $objectsrc->thirdparty;
1234 1157
 
1235
-	// Commercial suivi
1236
-	print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").'</span></td><td>';
1237
-	print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,'');
1238
-	print '</td></tr>';
1158
+            $note_private		= (! empty($objectsrc->note_private) ? $objectsrc->note_private : '');
1159
+            $note_public		= (! empty($objectsrc->note_public) ? $objectsrc->note_public : '');
1239 1160
 
1240
-	// Commercial signature
1241
-	print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").'</span></td><td>';
1242
-	print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,'');
1243
-	print '</td></tr>';
1161
+            // Object source contacts list
1162
+            $srccontactslist = $objectsrc->liste_contact(-1,'external',1);
1163
+        }
1164
+    }
1165
+    else {
1166
+        $projectid = GETPOST('projectid','int');
1167
+        $note_private = GETPOST("note_private");
1168
+        $note_public = GETPOST("note_public");
1169
+    }
1244 1170
 
1245
-	print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td>';
1246
-	print $form->selectDate($datecontrat, '', 0, 0, '', "contrat");
1247
-	print "</td></tr>";
1171
+    $object->date_contrat = dol_now();
1248 1172
 
1249
-	// Project
1250
-	if (! empty($conf->projet->enabled))
1251
-	{
1252
-		$langs->load('projects');
1173
+    print '<form name="form_contract" action="'.$_SERVER["PHP_SELF"].'" method="post">';
1174
+    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1253 1175
 
1254
-		$formproject=new FormProjets($db);
1176
+    print '<input type="hidden" name="action" value="add">';
1177
+    print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
1178
+    print '<input type="hidden" name="remise_percent" value="0">';
1255 1179
 
1256
-		print '<tr><td>'.$langs->trans("Project").'</td><td>';
1257
-		$formproject->select_projects(($soc->id>0?$soc->id:-1),$projectid,"projectid",0,0,1,1);
1258
-		print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid=' . $soc->id . '&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id).'">' . $langs->trans("AddProject") . '</a>';
1259
-		print "</td></tr>";
1260
-	}
1180
+    dol_fiche_head();
1261 1181
 
1262
-	print '<tr><td>'.$langs->trans("NotePublic").'</td><td class="tdtop">';
1263
-	$doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1264
-	print $doleditor->Create(1);
1265
-	print '</td></tr>';
1266
-
1267
-	if (empty($user->societe_id))
1268
-	{
1269
-		print '<tr><td>'.$langs->trans("NotePrivate").'</td><td class="tdtop">';
1270
-		$doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1271
-		print $doleditor->Create(1);
1272
-		print '</td></tr>';
1273
-	}
1182
+    print '<table class="border" width="100%">';
1274 1183
 
1275
-	// Other attributes
1276
-	$parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"', 'cols'=>3);
1277
-	$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
1278
-	print $hookmanager->resPrint;
1184
+    // Ref
1185
+    print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td>';
1186
+    if (! empty($modCodeContract->code_auto)) {
1187
+        $tmpcode=$langs->trans("Draft");
1188
+    } else {
1189
+        $tmpcode='<input name="ref" class="maxwidth100" maxlength="128" value="'.dol_escape_htmltag(GETPOST('ref')?GETPOST('ref'):$tmpcode).'">';
1190
+    }
1191
+    print $tmpcode;
1192
+    print '</td></tr>';
1193
+
1194
+    // Ref customer
1195
+    print '<tr><td>'.$langs->trans('RefCustomer').'</td>';
1196
+    print '<td><input type="text" class="maxwidth150" name="ref_customer" id="ref_customer" value="'.dol_escape_htmltag(GETPOST('ref_customer','alpha')).'"></td></tr>';
1197
+
1198
+    // Ref supplier
1199
+    print '<tr><td>'.$langs->trans('RefSupplier').'</td>';
1200
+    print '<td><input type="text" class="maxwidth150" name="ref_supplier" id="ref_supplier" value="'.dol_escape_htmltag(GETPOST('ref_supplier','alpha')).'"></td></tr>';
1201
+
1202
+    // Thirdparty
1203
+    print '<tr>';
1204
+    print '<td class="fieldrequired">'.$langs->trans('ThirdParty').'</td>';
1205
+    if ($socid>0)
1206
+    {
1207
+        print '<td>';
1208
+        print $soc->getNomUrl(1);
1209
+        print '<input type="hidden" name="socid" value="'.$soc->id.'">';
1210
+        print '</td>';
1211
+    }
1212
+    else
1213
+    {
1214
+        print '<td>';
1215
+        print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300');
1216
+        print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'">'.$langs->trans("AddThirdParty").'</a>';
1217
+        print '</td>';
1218
+    }
1219
+    print '</tr>'."\n";
1220
+
1221
+    if($socid>0)
1222
+    {
1223
+        // Ligne info remises tiers
1224
+        print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
1225
+        if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent);
1226
+        else print $langs->trans("CompanyHasNoRelativeDiscount");
1227
+        print '. ';
1228
+        $absolute_discount=$soc->getAvailableDiscounts();
1229
+        if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1230
+        else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1231
+        print '.';
1232
+        print '</td></tr>';
1233
+    }
1279 1234
 
1280
-	// Other attributes
1281
-	if (empty($reshook)) {
1282
-		print $object->showOptionals($extrafields, 'edit');
1283
-	}
1235
+    // Commercial suivi
1236
+    print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").'</span></td><td>';
1237
+    print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,'');
1238
+    print '</td></tr>';
1284 1239
 
1285
-	print "</table>\n";
1240
+    // Commercial signature
1241
+    print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").'</span></td><td>';
1242
+    print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,'');
1243
+    print '</td></tr>';
1286 1244
 
1287
-	dol_fiche_end();
1245
+    print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td>';
1246
+    print $form->selectDate($datecontrat, '', 0, 0, '', "contrat");
1247
+    print "</td></tr>";
1288 1248
 
1289
-	print '<div class="center">';
1290
-	print '<input type="submit" class="button" value="'.$langs->trans("Create").'">';
1291
-	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1292
-	print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
1293
-	print '</div>';
1249
+    // Project
1250
+    if (! empty($conf->projet->enabled))
1251
+    {
1252
+        $langs->load('projects');
1294 1253
 
1295
-	if (is_object($objectsrc))
1296
-	{
1297
-		print '<input type="hidden" name="origin"         value="'.$objectsrc->element.'">';
1298
-		print '<input type="hidden" name="originid"       value="'.$objectsrc->id.'">';
1254
+        $formproject=new FormProjets($db);
1299 1255
 
1300
-		if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS))
1301
-		{
1302
-			print '<br>'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed");
1303
-		}
1304
-	}
1256
+        print '<tr><td>'.$langs->trans("Project").'</td><td>';
1257
+        $formproject->select_projects(($soc->id>0?$soc->id:-1),$projectid,"projectid",0,0,1,1);
1258
+        print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid=' . $soc->id . '&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id).'">' . $langs->trans("AddProject") . '</a>';
1259
+        print "</td></tr>";
1260
+    }
1261
+
1262
+    print '<tr><td>'.$langs->trans("NotePublic").'</td><td class="tdtop">';
1263
+    $doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1264
+    print $doleditor->Create(1);
1265
+    print '</td></tr>';
1266
+
1267
+    if (empty($user->societe_id))
1268
+    {
1269
+        print '<tr><td>'.$langs->trans("NotePrivate").'</td><td class="tdtop">';
1270
+        $doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1271
+        print $doleditor->Create(1);
1272
+        print '</td></tr>';
1273
+    }
1274
+
1275
+    // Other attributes
1276
+    $parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"', 'cols'=>3);
1277
+    $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
1278
+    print $hookmanager->resPrint;
1279
+
1280
+    // Other attributes
1281
+    if (empty($reshook)) {
1282
+        print $object->showOptionals($extrafields, 'edit');
1283
+    }
1284
+
1285
+    print "</table>\n";
1286
+
1287
+    dol_fiche_end();
1288
+
1289
+    print '<div class="center">';
1290
+    print '<input type="submit" class="button" value="'.$langs->trans("Create").'">';
1291
+    print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1292
+    print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
1293
+    print '</div>';
1294
+
1295
+    if (is_object($objectsrc))
1296
+    {
1297
+        print '<input type="hidden" name="origin"         value="'.$objectsrc->element.'">';
1298
+        print '<input type="hidden" name="originid"       value="'.$objectsrc->id.'">';
1299
+
1300
+        if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS))
1301
+        {
1302
+            print '<br>'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed");
1303
+        }
1304
+    }
1305 1305
 
1306
-	print "</form>\n";
1306
+    print "</form>\n";
1307 1307
 }
1308 1308
 else
1309 1309
 /* *************************************************************************** */
@@ -1312,29 +1312,29 @@  discard block
 block discarded – undo
1312 1312
 /*                                                                             */
1313 1313
 /* *************************************************************************** */
1314 1314
 {
1315
-	$now=dol_now();
1315
+    $now=dol_now();
1316 1316
 
1317
-	if ($object->id > 0)
1318
-	{
1319
-		$object->fetch_thirdparty();
1317
+    if ($object->id > 0)
1318
+    {
1319
+        $object->fetch_thirdparty();
1320 1320
 
1321
-		$result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed
1322
-		if ($result < 0) {
1321
+        $result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed
1322
+        if ($result < 0) {
1323 1323
             dol_print_error($db,$object->error);
1324 1324
         }
1325 1325
 
1326
-		$nbofservices=count($object->lines);
1326
+        $nbofservices=count($object->lines);
1327 1327
 
1328
-		$author = new User($db);
1329
-		$author->fetch($object->user_author_id);
1328
+        $author = new User($db);
1329
+        $author->fetch($object->user_author_id);
1330 1330
 
1331
-		$commercial_signature = new User($db);
1332
-		$commercial_signature->fetch($object->commercial_signature_id);
1331
+        $commercial_signature = new User($db);
1332
+        $commercial_signature->fetch($object->commercial_signature_id);
1333 1333
 
1334
-		$commercial_suivi = new User($db);
1335
-		$commercial_suivi->fetch($object->commercial_suivi_id);
1334
+        $commercial_suivi = new User($db);
1335
+        $commercial_suivi->fetch($object->commercial_suivi_id);
1336 1336
 
1337
-		$head = contract_prepare_head($object);
1337
+        $head = contract_prepare_head($object);
1338 1338
 
1339 1339
         $hselected = 0;
1340 1340
         $formconfirm = '';
@@ -1386,847 +1386,847 @@  discard block
 block discarded – undo
1386 1386
         /*
1387 1387
          *   Contrat
1388 1388
          */
1389
-		if (! empty($object->brouillon) && $user->rights->contrat->creer)
1390
-		{
1391
-			print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="POST">';
1392
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1393
-			print '<input type="hidden" name="action" value="setremise">';
1394
-		}
1395
-
1396
-		// Contract card
1397
-
1398
-		$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
1399
-
1400
-
1401
-		$morehtmlref='';
1402
-		if (! empty($modCodeContract->code_auto)) {
1403
-			$morehtmlref.=$object->ref;
1404
-		} else {
1405
-			$morehtmlref.=$form->editfieldkey("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,3);
1406
-			$morehtmlref.=$form->editfieldval("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,2);
1407
-		}
1408
-
1409
-		$morehtmlref.='<div class="refidno">';
1410
-		// Ref customer
1411
-		$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1412
-		$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1);
1413
-		// Ref supplier
1414
-		$morehtmlref.='<br>';
1415
-		$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1416
-		$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1);
1417
-		// Thirdparty
1418
-		$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
1419
-		if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
1420
-		// Project
1421
-		if (! empty($conf->projet->enabled))
1422
-		{
1423
-			$langs->load("projects");
1424
-			$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
1425
-			if ($user->rights->contrat->creer)
1426
-			{
1427
-				if ($action != 'classify')
1428
-					$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
1429
-					if ($action == 'classify') {
1430
-						//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
1431
-						$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
1432
-						$morehtmlref.='<input type="hidden" name="action" value="classin">';
1433
-						$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1434
-						$morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
1435
-						$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
1436
-						$morehtmlref.='</form>';
1437
-					} else {
1438
-						$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
1439
-					}
1440
-			} else {
1441
-				if (! empty($object->fk_project)) {
1442
-					$proj = new Project($db);
1443
-					$proj->fetch($object->fk_project);
1444
-					$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
1445
-					$morehtmlref.=$proj->ref;
1446
-					$morehtmlref.='</a>';
1447
-				} else {
1448
-					$morehtmlref.='';
1449
-				}
1450
-			}
1451
-		}
1452
-		$morehtmlref.='</div>';
1453
-
1454
-
1455
-		dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
1456
-
1457
-
1458
-		print '<div class="fichecenter">';
1459
-		print '<div class="underbanner clearboth"></div>';
1460
-
1461
-
1462
-		print '<table class="border" width="100%">';
1463
-
1464
-		// Ligne info remises tiers
1465
-		print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">';
1466
-		if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent);
1467
-		else print $langs->trans("CompanyHasNoRelativeDiscount");
1468
-		$absolute_discount=$object->thirdparty->getAvailableDiscounts();
1469
-		print '. ';
1470
-		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1471
-		else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1472
-		print '.';
1473
-		print '</td></tr>';
1474
-
1475
-		// Date
1476
-		print '<tr>';
1477
-		print '<td class="titlefield">';
1478
-		print $form->editfieldkey("Date",'date_contrat',$object->date_contrat,$object,$user->rights->contrat->creer);
1479
-		print '</td><td>';
1480
-		print $form->editfieldval("Date",'date_contrat',$object->date_contrat,$object,$user->rights->contrat->creer,'datehourpicker');
1481
-		print '</td>';
1482
-		print '</tr>';
1483
-
1484
-		// Other attributes
1485
-		$cols = 3;
1486
-		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
1487
-
1488
-		print "</table>";
1489
-
1490
-		print '</div>';
1491
-
1492
-		if (! empty($object->brouillon) && $user->rights->contrat->creer)
1493
-		{
1494
-			print '</form>';
1495
-		}
1496
-
1497
-		echo '<br>';
1498
-
1499
-		if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
1500
-		{
1501
-			$blocname = 'contacts';
1502
-			$title = $langs->trans('ContactsAddresses');
1503
-			include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1504
-		}
1505
-
1506
-		if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
1507
-		{
1508
-			$blocname = 'notes';
1509
-			$title = $langs->trans('Notes');
1510
-			include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1511
-		}
1512
-
1513
-
1514
-		$colorb = '666666';
1515
-
1516
-		$arrayothercontracts=$object->getListOfContracts('others');
1517
-
1518
-		/*
1389
+        if (! empty($object->brouillon) && $user->rights->contrat->creer)
1390
+        {
1391
+            print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="POST">';
1392
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1393
+            print '<input type="hidden" name="action" value="setremise">';
1394
+        }
1395
+
1396
+        // Contract card
1397
+
1398
+        $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
1399
+
1400
+
1401
+        $morehtmlref='';
1402
+        if (! empty($modCodeContract->code_auto)) {
1403
+            $morehtmlref.=$object->ref;
1404
+        } else {
1405
+            $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,3);
1406
+            $morehtmlref.=$form->editfieldval("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,2);
1407
+        }
1408
+
1409
+        $morehtmlref.='<div class="refidno">';
1410
+        // Ref customer
1411
+        $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1412
+        $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1);
1413
+        // Ref supplier
1414
+        $morehtmlref.='<br>';
1415
+        $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1416
+        $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1);
1417
+        // Thirdparty
1418
+        $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
1419
+        if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
1420
+        // Project
1421
+        if (! empty($conf->projet->enabled))
1422
+        {
1423
+            $langs->load("projects");
1424
+            $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
1425
+            if ($user->rights->contrat->creer)
1426
+            {
1427
+                if ($action != 'classify')
1428
+                    $morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
1429
+                    if ($action == 'classify') {
1430
+                        //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
1431
+                        $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
1432
+                        $morehtmlref.='<input type="hidden" name="action" value="classin">';
1433
+                        $morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1434
+                        $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
1435
+                        $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
1436
+                        $morehtmlref.='</form>';
1437
+                    } else {
1438
+                        $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
1439
+                    }
1440
+            } else {
1441
+                if (! empty($object->fk_project)) {
1442
+                    $proj = new Project($db);
1443
+                    $proj->fetch($object->fk_project);
1444
+                    $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
1445
+                    $morehtmlref.=$proj->ref;
1446
+                    $morehtmlref.='</a>';
1447
+                } else {
1448
+                    $morehtmlref.='';
1449
+                }
1450
+            }
1451
+        }
1452
+        $morehtmlref.='</div>';
1453
+
1454
+
1455
+        dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
1456
+
1457
+
1458
+        print '<div class="fichecenter">';
1459
+        print '<div class="underbanner clearboth"></div>';
1460
+
1461
+
1462
+        print '<table class="border" width="100%">';
1463
+
1464
+        // Ligne info remises tiers
1465
+        print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">';
1466
+        if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent);
1467
+        else print $langs->trans("CompanyHasNoRelativeDiscount");
1468
+        $absolute_discount=$object->thirdparty->getAvailableDiscounts();
1469
+        print '. ';
1470
+        if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1471
+        else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1472
+        print '.';
1473
+        print '</td></tr>';
1474
+
1475
+        // Date
1476
+        print '<tr>';
1477
+        print '<td class="titlefield">';
1478
+        print $form->editfieldkey("Date",'date_contrat',$object->date_contrat,$object,$user->rights->contrat->creer);
1479
+        print '</td><td>';
1480
+        print $form->editfieldval("Date",'date_contrat',$object->date_contrat,$object,$user->rights->contrat->creer,'datehourpicker');
1481
+        print '</td>';
1482
+        print '</tr>';
1483
+
1484
+        // Other attributes
1485
+        $cols = 3;
1486
+        include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
1487
+
1488
+        print "</table>";
1489
+
1490
+        print '</div>';
1491
+
1492
+        if (! empty($object->brouillon) && $user->rights->contrat->creer)
1493
+        {
1494
+            print '</form>';
1495
+        }
1496
+
1497
+        echo '<br>';
1498
+
1499
+        if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
1500
+        {
1501
+            $blocname = 'contacts';
1502
+            $title = $langs->trans('ContactsAddresses');
1503
+            include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1504
+        }
1505
+
1506
+        if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
1507
+        {
1508
+            $blocname = 'notes';
1509
+            $title = $langs->trans('Notes');
1510
+            include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1511
+        }
1512
+
1513
+
1514
+        $colorb = '666666';
1515
+
1516
+        $arrayothercontracts=$object->getListOfContracts('others');
1517
+
1518
+        /*
1519 1519
          * Lines of contracts
1520 1520
          */
1521 1521
 
1522
-		$productstatic=new Product($db);
1523
-
1524
-		$usemargins=0;
1525
-		if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1;
1526
-
1527
-		$var=false;
1528
-
1529
-		// Title line for service
1530
-		$cursorline=1;
1531
-		print '<div id="contrat-lines-container" data-contractid="'.$object->id.'"  data-element="'.$object->element.'" >';
1532
-		while ($cursorline <= $nbofservices)
1533
-		{
1534
-			print '<div id="contrat-line-container'.$object->lines[$cursorline-1]->id.'" data-contratlineid = "'.$object->lines[$cursorline-1]->id.'" data-element="'.$object->lines[$cursorline-1]->element.'" >';
1535
-			print '<form name="update" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="post">';
1536
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1537
-			print '<input type="hidden" name="action" value="updateline">';
1538
-			print '<input type="hidden" name="elrowid" value="'.$object->lines[$cursorline-1]->id.'">';
1539
-			print '<input type="hidden" name="idprod" value="'.(!empty($object->lines[$cursorline-1]->fk_product) ? $object->lines[$cursorline-1]->fk_product : 0).'">';
1540
-			print '<input type="hidden" name="fournprice" value="'.(!empty($object->lines[$cursorline-1]->fk_fournprice) ? $object->lines[$cursorline-1]->fk_fournprice : 0).'">';
1541
-
1542
-			// Area with common detail of line
1543
-			print '<div class="div-table-responsive-no-min">';
1544
-			print '<table class="notopnoleftnoright allwidth tableforservicepart1" width="100%">';
1545
-
1546
-			$sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,";
1547
-			$sql.= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,";
1548
-			$sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,";
1549
-			$sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,";
1550
-			$sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,";
1551
-			$sql.= " cd.fk_unit,";
1552
-			$sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity";
1553
-			$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
1554
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
1555
-			$sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id;
1556
-
1557
-			$result = $db->query($sql);
1558
-			if ($result)
1559
-			{
1560
-				$total = 0;
1561
-
1562
-				print '<tr class="liste_titre'.($cursorline?' liste_titre_add':'').'">';
1563
-				print '<td>'.$langs->trans("ServiceNb",$cursorline).'</td>';
1564
-				print '<td width="80" align="center">'.$langs->trans("VAT").'</td>';
1565
-				print '<td width="80" align="right">'.$langs->trans("PriceUHT").'</td>';
1566
-				if (!empty($conf->multicurrency->enabled)) {
1567
-					print '<td width="80" align="right">'.$langs->trans("PriceUHTCurrency").'</td>';
1568
-				}
1569
-				print '<td width="30" align="center">'.$langs->trans("Qty").'</td>';
1570
-				if ($conf->global->PRODUCT_USE_UNITS) print '<td width="30" align="left">'.$langs->trans("Unit").'</td>';
1571
-				print '<td width="50" align="right">'.$langs->trans("ReductionShort").'</td>';
1572
-				if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td width="50" align="right">'.$langs->trans("BuyingPrice").'</td>';
1573
-				print '<td width="30">&nbsp;</td>';
1574
-				print "</tr>\n";
1575
-
1576
-				$objp = $db->fetch_object($result);
1577
-
1578
-				//
1579
-
1580
-				if ($action != 'editline' || GETPOST('rowid') != $objp->rowid)
1581
-				{
1582
-					print '<tr class="tdtop oddeven">';
1583
-					// Label
1584
-					if ($objp->fk_product > 0)
1585
-					{
1586
-						print '<td>';
1587
-						$productstatic->id=$objp->fk_product;
1588
-						$productstatic->type=$objp->ptype;
1589
-						$productstatic->ref=$objp->pref;
1590
-						$productstatic->entity=$objp->pentity;
1591
-						$productstatic->label=$objp->plabel;
1592
-						$text = $productstatic->getNomUrl(1,'',32);
1593
-						if ($objp->plabel)
1594
-						{
1595
-							$text .= ' - ';
1596
-							$text .= $objp->plabel;
1597
-						}
1598
-						$description = $objp->description;
1599
-
1600
-						// Add description in form
1601
-						if (! empty($conf->global->PRODUIT_DESC_IN_FORM))
1602
-						{
1603
-							$text .= (! empty($objp->description) && $objp->description!=$objp->plabel)?'<br>'.dol_htmlentitiesbr($objp->description):'';
1604
-							$description = '';	// Already added into main visible desc
1605
-						}
1606
-
1607
-						echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):''));
1608
-
1609
-						print '</td>';
1610
-					}
1611
-					else
1612
-					{
1613
-						print '<td>'.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."</td>\n";
1614
-					}
1615
-					// TVA
1616
-					print '<td align="center">';
1617
-					print vatrate($objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), '%', $objp->info_bits);
1618
-					print '</td>';
1619
-					// Price
1620
-					print '<td align="right">'.($objp->subprice != '' ? price($objp->subprice) : '')."</td>\n";
1621
-					// Price multicurrency
1622
-					if (!empty($conf->multicurrency->enabled)) {
1623
-						print '<td align="right" class="linecoluht_currency nowrap">'.price($objp->multicurrency_subprice).'</td>';
1624
-					}
1625
-					// Quantite
1626
-					print '<td align="center">'.$objp->qty.'</td>';
1627
-					// Unit
1628
-					if($conf->global->PRODUCT_USE_UNITS) print '<td align="left">'.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).'</td>';
1629
-					// Remise
1630
-					if ($objp->remise_percent > 0)
1631
-					{
1632
-						print '<td align="right">'.$objp->remise_percent."%</td>\n";
1633
-					}
1634
-					else
1635
-					{
1636
-						print '<td>&nbsp;</td>';
1637
-					}
1638
-
1639
-					// Margin
1640
-					if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td align="right" class="nowrap">'.price($objp->pa_ht).'</td>';
1641
-
1642
-					// Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme)
1643
-					print '<td align="right" class="nowrap">';
1644
-					if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0))
1645
-					{
1646
-						print '<!-- link to move service line into another contract -->';
1647
-						print '<a class="reposition" style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=move&amp;rowid='.$objp->rowid.'">';
1648
-						print img_picto($langs->trans("MoveToAnotherContract"),'uparrow');
1649
-						print '</a>';
1650
-					}
1651
-					if ($user->rights->contrat->creer && ($object->statut >= 0))
1652
-					{
1653
-						print '<a class="reposition" style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=editline&amp;rowid='.$objp->rowid.'">';
1654
-						print img_edit();
1655
-						print '</a>';
1656
-					}
1657
-					if ( $user->rights->contrat->creer && ($object->statut >= 0))
1658
-					{
1659
-						print '<a style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=deleteline&amp;rowid='.$objp->rowid.'">';
1660
-						print img_delete();
1661
-						print '</a>';
1662
-					}
1663
-					print '</td>';
1664
-
1665
-					print "</tr>\n";
1666
-
1667
-					// Dates of service planed and real
1668
-					if ($objp->subprice >= 0)
1669
-					{
1670
-						$colspan = 6;
1671
-
1672
-						if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) {
1673
-							$colspan = 8;
1674
-						} elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) {
1675
-							$colspan = 7;
1676
-						}
1677
-
1678
-						print '<tr class="oddeven">';
1679
-						print '<td colspan="'.$colspan.'">';
1680
-
1681
-						// Date planned
1682
-						print $langs->trans("DateStartPlanned").': ';
1683
-						if ($objp->date_debut)
1684
-						{
1685
-							print dol_print_date($db->jdate($objp->date_debut), 'day');
1686
-							// Warning si date prevu passee et pas en service
1687
-							if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) {
1688
-								$warning_delay=$conf->contrat->services->inactifs->warning_delay / 3600 / 24;
1689
-								$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1690
-								print " ".img_warning($textlate);
1691
-							}
1692
-						}
1693
-						else print $langs->trans("Unknown");
1694
-						print ' &nbsp;-&nbsp; ';
1695
-						print $langs->trans("DateEndPlanned").': ';
1696
-						if ($objp->date_fin)
1697
-						{
1698
-							print dol_print_date($db->jdate($objp->date_fin), 'day');
1699
-							if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) {
1700
-								$warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24;
1701
-								$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1702
-								print " ".img_warning($textlate);
1703
-							}
1704
-						}
1705
-						else print $langs->trans("Unknown");
1706
-
1707
-						print '</td>';
1708
-						print '</tr>';
1709
-					}
1710
-
1711
-					// Display lines extrafields
1712
-					if (is_array($extralabelslines) && count($extralabelslines)>0) {
1713
-						$line = new ContratLigne($db);
1714
-						$line->fetch_optionals($objp->rowid);
1715
-						print $line->showOptionals($extrafieldsline, 'view', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
1716
-					}
1717
-				}
1718
-				// Ligne en mode update
1719
-				else
1720
-				{
1721
-					// Ligne carac
1722
-					print '<tr class="oddeven">';
1723
-					print '<td>';
1724
-					if ($objp->fk_product)
1725
-					{
1726
-						$productstatic->id=$objp->fk_product;
1727
-						$productstatic->type=$objp->ptype;
1728
-						$productstatic->ref=$objp->pref;
1729
-						$productstatic->entity=$objp->pentity;
1730
-						print $productstatic->getNomUrl(1,'',32);
1731
-						print $objp->label?' - '.dol_trunc($objp->label,32):'';
1732
-						print '<br>';
1733
-					}
1734
-					else
1735
-					{
1736
-						print $objp->label?$objp->label.'<br>':'';
1737
-					}
1738
-
1739
-					// editeur wysiwyg
1740
-					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1741
-					$nbrows=ROWS_2;
1742
-					if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
1743
-					$enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0);
1744
-					$doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%');
1745
-					$doleditor->Create();
1746
-
1747
-					print '</td>';
1748
-					print '<td align="right">';
1749
-					print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1);
1750
-					print '</td>';
1751
-					print '<td align="right"><input size="5" type="text" name="elprice" value="'.price($objp->subprice).'"></td>';
1752
-					print '<td align="center"><input size="2" type="text" name="elqty" value="'.$objp->qty.'"></td>';
1753
-					if ($conf->global->PRODUCT_USE_UNITS)
1754
-					{
1755
-						print '<td align="left">';
1756
-						print $form->selectUnits($objp->fk_unit, "unit");
1757
-						print '</td>';
1758
-					}
1759
-					print '<td align="right" class="nowrap"><input size="1" type="text" name="elremise_percent" value="'.$objp->remise_percent.'">%</td>';
1760
-					if (! empty($usemargins))
1761
-					{
1762
-						print '<td align="right">';
1763
-						if ($objp->fk_product) print '<select id="fournprice" name="fournprice"></select>';
1764
-						print '<input id="buying_price" type="text" size="5" name="buying_price" value="'.price($objp->pa_ht,0,'',0).'"></td>';
1765
-					}
1766
-					print '<td align="center">';
1767
-					print '<input type="submit" class="button" name="save" value="'.$langs->trans("Modify").'">';
1768
-					print '<br><input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
1769
-					print '</td>';
1770
-					print '</tr>';
1771
-
1772
-					$colspan=6;
1773
-					if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++;
1774
-					if($conf->global->PRODUCT_USE_UNITS) $colspan++;
1775
-
1776
-					// Ligne dates prevues
1777
-					print '<tr class="oddeven">';
1778
-					print '<td colspan="'.$colspan.'">';
1779
-					print $langs->trans("DateStartPlanned").' ';
1780
-					print $form->selectDate($db->jdate($objp->date_debut), "date_start_update", $usehm, $usehm, ($db->jdate($objp->date_debut)>0?0:1), "update");
1781
-					print ' &nbsp;&nbsp;'.$langs->trans("DateEndPlanned").' ';
1782
-					print $form->selectDate($db->jdate($objp->date_fin), "date_end_update", $usehm, $usehm, ($db->jdate($objp->date_fin)>0?0:1), "update");
1783
-					print '</td>';
1784
-					print '</tr>';
1785
-
1786
-					if (is_array($extralabelslines) && count($extralabelslines)>0) {
1787
-						$line = new ContratLigne($db);
1788
-						$line->fetch_optionals($objp->rowid);
1789
-						print $line->showOptionals($extrafieldsline, 'edit', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
1790
-					}
1791
-				}
1792
-
1793
-				$db->free($result);
1794
-			}
1795
-			else
1796
-			{
1797
-				dol_print_error($db);
1798
-			}
1799
-
1800
-			if ($object->statut > 0)
1801
-			{
1802
-				print '<tr class="oddeven">';
1803
-				print '<td class="tdhrthin" colspan="'.($conf->margin->enabled?7:6).'"><hr class="opacitymedium tdhrthin"></td>';
1804
-				print "</tr>\n";
1805
-			}
1806
-
1807
-			print "</table>";
1808
-			print '</div>';
1809
-
1810
-			print "</form>\n";
1811
-
1812
-
1813
-			/*
1522
+        $productstatic=new Product($db);
1523
+
1524
+        $usemargins=0;
1525
+        if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1;
1526
+
1527
+        $var=false;
1528
+
1529
+        // Title line for service
1530
+        $cursorline=1;
1531
+        print '<div id="contrat-lines-container" data-contractid="'.$object->id.'"  data-element="'.$object->element.'" >';
1532
+        while ($cursorline <= $nbofservices)
1533
+        {
1534
+            print '<div id="contrat-line-container'.$object->lines[$cursorline-1]->id.'" data-contratlineid = "'.$object->lines[$cursorline-1]->id.'" data-element="'.$object->lines[$cursorline-1]->element.'" >';
1535
+            print '<form name="update" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="post">';
1536
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1537
+            print '<input type="hidden" name="action" value="updateline">';
1538
+            print '<input type="hidden" name="elrowid" value="'.$object->lines[$cursorline-1]->id.'">';
1539
+            print '<input type="hidden" name="idprod" value="'.(!empty($object->lines[$cursorline-1]->fk_product) ? $object->lines[$cursorline-1]->fk_product : 0).'">';
1540
+            print '<input type="hidden" name="fournprice" value="'.(!empty($object->lines[$cursorline-1]->fk_fournprice) ? $object->lines[$cursorline-1]->fk_fournprice : 0).'">';
1541
+
1542
+            // Area with common detail of line
1543
+            print '<div class="div-table-responsive-no-min">';
1544
+            print '<table class="notopnoleftnoright allwidth tableforservicepart1" width="100%">';
1545
+
1546
+            $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,";
1547
+            $sql.= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,";
1548
+            $sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,";
1549
+            $sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,";
1550
+            $sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,";
1551
+            $sql.= " cd.fk_unit,";
1552
+            $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity";
1553
+            $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
1554
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
1555
+            $sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id;
1556
+
1557
+            $result = $db->query($sql);
1558
+            if ($result)
1559
+            {
1560
+                $total = 0;
1561
+
1562
+                print '<tr class="liste_titre'.($cursorline?' liste_titre_add':'').'">';
1563
+                print '<td>'.$langs->trans("ServiceNb",$cursorline).'</td>';
1564
+                print '<td width="80" align="center">'.$langs->trans("VAT").'</td>';
1565
+                print '<td width="80" align="right">'.$langs->trans("PriceUHT").'</td>';
1566
+                if (!empty($conf->multicurrency->enabled)) {
1567
+                    print '<td width="80" align="right">'.$langs->trans("PriceUHTCurrency").'</td>';
1568
+                }
1569
+                print '<td width="30" align="center">'.$langs->trans("Qty").'</td>';
1570
+                if ($conf->global->PRODUCT_USE_UNITS) print '<td width="30" align="left">'.$langs->trans("Unit").'</td>';
1571
+                print '<td width="50" align="right">'.$langs->trans("ReductionShort").'</td>';
1572
+                if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td width="50" align="right">'.$langs->trans("BuyingPrice").'</td>';
1573
+                print '<td width="30">&nbsp;</td>';
1574
+                print "</tr>\n";
1575
+
1576
+                $objp = $db->fetch_object($result);
1577
+
1578
+                //
1579
+
1580
+                if ($action != 'editline' || GETPOST('rowid') != $objp->rowid)
1581
+                {
1582
+                    print '<tr class="tdtop oddeven">';
1583
+                    // Label
1584
+                    if ($objp->fk_product > 0)
1585
+                    {
1586
+                        print '<td>';
1587
+                        $productstatic->id=$objp->fk_product;
1588
+                        $productstatic->type=$objp->ptype;
1589
+                        $productstatic->ref=$objp->pref;
1590
+                        $productstatic->entity=$objp->pentity;
1591
+                        $productstatic->label=$objp->plabel;
1592
+                        $text = $productstatic->getNomUrl(1,'',32);
1593
+                        if ($objp->plabel)
1594
+                        {
1595
+                            $text .= ' - ';
1596
+                            $text .= $objp->plabel;
1597
+                        }
1598
+                        $description = $objp->description;
1599
+
1600
+                        // Add description in form
1601
+                        if (! empty($conf->global->PRODUIT_DESC_IN_FORM))
1602
+                        {
1603
+                            $text .= (! empty($objp->description) && $objp->description!=$objp->plabel)?'<br>'.dol_htmlentitiesbr($objp->description):'';
1604
+                            $description = '';	// Already added into main visible desc
1605
+                        }
1606
+
1607
+                        echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):''));
1608
+
1609
+                        print '</td>';
1610
+                    }
1611
+                    else
1612
+                    {
1613
+                        print '<td>'.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."</td>\n";
1614
+                    }
1615
+                    // TVA
1616
+                    print '<td align="center">';
1617
+                    print vatrate($objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), '%', $objp->info_bits);
1618
+                    print '</td>';
1619
+                    // Price
1620
+                    print '<td align="right">'.($objp->subprice != '' ? price($objp->subprice) : '')."</td>\n";
1621
+                    // Price multicurrency
1622
+                    if (!empty($conf->multicurrency->enabled)) {
1623
+                        print '<td align="right" class="linecoluht_currency nowrap">'.price($objp->multicurrency_subprice).'</td>';
1624
+                    }
1625
+                    // Quantite
1626
+                    print '<td align="center">'.$objp->qty.'</td>';
1627
+                    // Unit
1628
+                    if($conf->global->PRODUCT_USE_UNITS) print '<td align="left">'.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).'</td>';
1629
+                    // Remise
1630
+                    if ($objp->remise_percent > 0)
1631
+                    {
1632
+                        print '<td align="right">'.$objp->remise_percent."%</td>\n";
1633
+                    }
1634
+                    else
1635
+                    {
1636
+                        print '<td>&nbsp;</td>';
1637
+                    }
1638
+
1639
+                    // Margin
1640
+                    if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td align="right" class="nowrap">'.price($objp->pa_ht).'</td>';
1641
+
1642
+                    // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme)
1643
+                    print '<td align="right" class="nowrap">';
1644
+                    if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0))
1645
+                    {
1646
+                        print '<!-- link to move service line into another contract -->';
1647
+                        print '<a class="reposition" style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=move&amp;rowid='.$objp->rowid.'">';
1648
+                        print img_picto($langs->trans("MoveToAnotherContract"),'uparrow');
1649
+                        print '</a>';
1650
+                    }
1651
+                    if ($user->rights->contrat->creer && ($object->statut >= 0))
1652
+                    {
1653
+                        print '<a class="reposition" style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=editline&amp;rowid='.$objp->rowid.'">';
1654
+                        print img_edit();
1655
+                        print '</a>';
1656
+                    }
1657
+                    if ( $user->rights->contrat->creer && ($object->statut >= 0))
1658
+                    {
1659
+                        print '<a style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=deleteline&amp;rowid='.$objp->rowid.'">';
1660
+                        print img_delete();
1661
+                        print '</a>';
1662
+                    }
1663
+                    print '</td>';
1664
+
1665
+                    print "</tr>\n";
1666
+
1667
+                    // Dates of service planed and real
1668
+                    if ($objp->subprice >= 0)
1669
+                    {
1670
+                        $colspan = 6;
1671
+
1672
+                        if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) {
1673
+                            $colspan = 8;
1674
+                        } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) {
1675
+                            $colspan = 7;
1676
+                        }
1677
+
1678
+                        print '<tr class="oddeven">';
1679
+                        print '<td colspan="'.$colspan.'">';
1680
+
1681
+                        // Date planned
1682
+                        print $langs->trans("DateStartPlanned").': ';
1683
+                        if ($objp->date_debut)
1684
+                        {
1685
+                            print dol_print_date($db->jdate($objp->date_debut), 'day');
1686
+                            // Warning si date prevu passee et pas en service
1687
+                            if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) {
1688
+                                $warning_delay=$conf->contrat->services->inactifs->warning_delay / 3600 / 24;
1689
+                                $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1690
+                                print " ".img_warning($textlate);
1691
+                            }
1692
+                        }
1693
+                        else print $langs->trans("Unknown");
1694
+                        print ' &nbsp;-&nbsp; ';
1695
+                        print $langs->trans("DateEndPlanned").': ';
1696
+                        if ($objp->date_fin)
1697
+                        {
1698
+                            print dol_print_date($db->jdate($objp->date_fin), 'day');
1699
+                            if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) {
1700
+                                $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24;
1701
+                                $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1702
+                                print " ".img_warning($textlate);
1703
+                            }
1704
+                        }
1705
+                        else print $langs->trans("Unknown");
1706
+
1707
+                        print '</td>';
1708
+                        print '</tr>';
1709
+                    }
1710
+
1711
+                    // Display lines extrafields
1712
+                    if (is_array($extralabelslines) && count($extralabelslines)>0) {
1713
+                        $line = new ContratLigne($db);
1714
+                        $line->fetch_optionals($objp->rowid);
1715
+                        print $line->showOptionals($extrafieldsline, 'view', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
1716
+                    }
1717
+                }
1718
+                // Ligne en mode update
1719
+                else
1720
+                {
1721
+                    // Ligne carac
1722
+                    print '<tr class="oddeven">';
1723
+                    print '<td>';
1724
+                    if ($objp->fk_product)
1725
+                    {
1726
+                        $productstatic->id=$objp->fk_product;
1727
+                        $productstatic->type=$objp->ptype;
1728
+                        $productstatic->ref=$objp->pref;
1729
+                        $productstatic->entity=$objp->pentity;
1730
+                        print $productstatic->getNomUrl(1,'',32);
1731
+                        print $objp->label?' - '.dol_trunc($objp->label,32):'';
1732
+                        print '<br>';
1733
+                    }
1734
+                    else
1735
+                    {
1736
+                        print $objp->label?$objp->label.'<br>':'';
1737
+                    }
1738
+
1739
+                    // editeur wysiwyg
1740
+                    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1741
+                    $nbrows=ROWS_2;
1742
+                    if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
1743
+                    $enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0);
1744
+                    $doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%');
1745
+                    $doleditor->Create();
1746
+
1747
+                    print '</td>';
1748
+                    print '<td align="right">';
1749
+                    print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1);
1750
+                    print '</td>';
1751
+                    print '<td align="right"><input size="5" type="text" name="elprice" value="'.price($objp->subprice).'"></td>';
1752
+                    print '<td align="center"><input size="2" type="text" name="elqty" value="'.$objp->qty.'"></td>';
1753
+                    if ($conf->global->PRODUCT_USE_UNITS)
1754
+                    {
1755
+                        print '<td align="left">';
1756
+                        print $form->selectUnits($objp->fk_unit, "unit");
1757
+                        print '</td>';
1758
+                    }
1759
+                    print '<td align="right" class="nowrap"><input size="1" type="text" name="elremise_percent" value="'.$objp->remise_percent.'">%</td>';
1760
+                    if (! empty($usemargins))
1761
+                    {
1762
+                        print '<td align="right">';
1763
+                        if ($objp->fk_product) print '<select id="fournprice" name="fournprice"></select>';
1764
+                        print '<input id="buying_price" type="text" size="5" name="buying_price" value="'.price($objp->pa_ht,0,'',0).'"></td>';
1765
+                    }
1766
+                    print '<td align="center">';
1767
+                    print '<input type="submit" class="button" name="save" value="'.$langs->trans("Modify").'">';
1768
+                    print '<br><input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
1769
+                    print '</td>';
1770
+                    print '</tr>';
1771
+
1772
+                    $colspan=6;
1773
+                    if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++;
1774
+                    if($conf->global->PRODUCT_USE_UNITS) $colspan++;
1775
+
1776
+                    // Ligne dates prevues
1777
+                    print '<tr class="oddeven">';
1778
+                    print '<td colspan="'.$colspan.'">';
1779
+                    print $langs->trans("DateStartPlanned").' ';
1780
+                    print $form->selectDate($db->jdate($objp->date_debut), "date_start_update", $usehm, $usehm, ($db->jdate($objp->date_debut)>0?0:1), "update");
1781
+                    print ' &nbsp;&nbsp;'.$langs->trans("DateEndPlanned").' ';
1782
+                    print $form->selectDate($db->jdate($objp->date_fin), "date_end_update", $usehm, $usehm, ($db->jdate($objp->date_fin)>0?0:1), "update");
1783
+                    print '</td>';
1784
+                    print '</tr>';
1785
+
1786
+                    if (is_array($extralabelslines) && count($extralabelslines)>0) {
1787
+                        $line = new ContratLigne($db);
1788
+                        $line->fetch_optionals($objp->rowid);
1789
+                        print $line->showOptionals($extrafieldsline, 'edit', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
1790
+                    }
1791
+                }
1792
+
1793
+                $db->free($result);
1794
+            }
1795
+            else
1796
+            {
1797
+                dol_print_error($db);
1798
+            }
1799
+
1800
+            if ($object->statut > 0)
1801
+            {
1802
+                print '<tr class="oddeven">';
1803
+                print '<td class="tdhrthin" colspan="'.($conf->margin->enabled?7:6).'"><hr class="opacitymedium tdhrthin"></td>';
1804
+                print "</tr>\n";
1805
+            }
1806
+
1807
+            print "</table>";
1808
+            print '</div>';
1809
+
1810
+            print "</form>\n";
1811
+
1812
+
1813
+            /*
1814 1814
              * Confirmation to delete service line of contract
1815 1815
              */
1816
-			if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid'))
1817
-			{
1818
-				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1);
1819
-				if ($ret == 'html') print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1820
-			}
1816
+            if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid'))
1817
+            {
1818
+                print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1);
1819
+                if ($ret == 'html') print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1820
+            }
1821 1821
 
1822
-			/*
1822
+            /*
1823 1823
              * Confirmation to move service toward another contract
1824 1824
              */
1825
-			if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid'))
1826
-			{
1827
-				$arraycontractid=array();
1828
-				foreach($arrayothercontracts as $contractcursor)
1829
-				{
1830
-					$arraycontractid[$contractcursor->id]=$contractcursor->ref;
1831
-				}
1832
-				//var_dump($arraycontractid);
1833
-				// Cree un tableau formulaire
1834
-				$formquestion=array(
1835
-				'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"),
1836
-				array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid));
1837
-
1838
-				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion);
1839
-				print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1840
-			}
1841
-
1842
-			/*
1825
+            if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid'))
1826
+            {
1827
+                $arraycontractid=array();
1828
+                foreach($arrayothercontracts as $contractcursor)
1829
+                {
1830
+                    $arraycontractid[$contractcursor->id]=$contractcursor->ref;
1831
+                }
1832
+                //var_dump($arraycontractid);
1833
+                // Cree un tableau formulaire
1834
+                $formquestion=array(
1835
+                'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"),
1836
+                array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid));
1837
+
1838
+                print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion);
1839
+                print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1840
+            }
1841
+
1842
+            /*
1843 1843
              * Confirmation de la validation activation
1844 1844
              */
1845
-			if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1846
-			{
1847
-				$dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1848
-				$dateactend   = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1849
-				$comment      = GETPOST('comment','alpha');
1850
-				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1);
1851
-				print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1852
-			}
1853
-
1854
-			/*
1845
+            if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1846
+            {
1847
+                $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1848
+                $dateactend   = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1849
+                $comment      = GETPOST('comment','alpha');
1850
+                print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1);
1851
+                print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1852
+            }
1853
+
1854
+            /*
1855 1855
              * Confirmation de la validation fermeture
1856 1856
              */
1857
-			if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1858
-			{
1859
-				$dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1860
-				$dateactend   = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1861
-				$comment      = GETPOST('comment','alpha');
1862
-
1863
-				if (empty($dateactend))
1864
-				{
1865
-					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors');
1866
-				}
1867
-				else
1868
-				{
1869
-					print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1);
1870
-				}
1871
-				print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1872
-			}
1873
-
1874
-
1875
-			// Area with status and activation info of line
1876
-			if ($object->statut > 0)
1877
-			{
1878
-				print '<table class="notopnoleftnoright tableforservicepart2'.($cursorline < $nbofservices ?' boxtablenobottom':'').'" width="100%">';
1879
-
1880
-				print '<tr class="oddeven">';
1881
-				print '<td>'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).'</td>';
1882
-				print '<td width="30" align="right">';
1883
-				if ($user->societe_id == 0)
1884
-				{
1885
-					if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline')
1886
-					{
1887
-						$tmpaction='activateline';
1888
-						$tmpactionpicto='play';
1889
-						$tmpactiontext=$langs->trans("Activate");
1890
-						if ($objp->statut == 4)
1891
-						{
1892
-							$tmpaction='unactivateline';
1893
-							$tmpactionpicto='playstop';
1894
-							$tmpactiontext=$langs->trans("Disable");
1895
-						}
1896
-						if (($tmpaction=='activateline' && $user->rights->contrat->activer) || ($tmpaction=='unactivateline' && $user->rights->contrat->desactiver))
1897
-						{
1898
-							print '<a class="reposition" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;ligne=' . $object->lines[$cursorline - 1]->id . '&amp;action=' . $tmpaction . '">';
1899
-							print img_picto($tmpactiontext, $tmpactionpicto);
1900
-							print '</a>';
1901
-						}
1902
-					}
1903
-				}
1904
-				print '</td>';
1905
-				print "</tr>\n";
1906
-
1907
-				print '<tr class="oddeven">';
1908
-
1909
-				print '<td>';
1910
-				// Si pas encore active
1911
-				if (! $objp->date_debut_reelle) {
1912
-					print $langs->trans("DateStartReal").': ';
1913
-					if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle, 'day');
1914
-					else print $langs->trans("ContractStatusNotRunning");
1915
-				}
1916
-				// Si active et en cours
1917
-				if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) {
1918
-					print $langs->trans("DateStartReal").': ';
1919
-					print dol_print_date($objp->date_debut_reelle, 'day');
1920
-				}
1921
-				// Si desactive
1922
-				if ($objp->date_debut_reelle && $objp->date_fin_reelle) {
1923
-					print $langs->trans("DateStartReal").': ';
1924
-					print dol_print_date($objp->date_debut_reelle, 'day');
1925
-					print ' &nbsp;-&nbsp; ';
1926
-					print $langs->trans("DateEndReal").': ';
1927
-					print dol_print_date($objp->date_fin_reelle, 'day');
1928
-				}
1929
-				if (! empty($objp->comment)) print " &nbsp;-&nbsp; ".$objp->comment;
1930
-				print '</td>';
1931
-
1932
-				print '<td align="center">&nbsp;</td>';
1933
-
1934
-				print '</tr>';
1935
-				print '</table>';
1936
-			}
1937
-
1938
-			// Form to activate line
1939
-			if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1940
-			{
1941
-				print '<form name="active" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.GETPOST('ligne').'&amp;action=active" method="post">';
1942
-				print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1943
-
1944
-				print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ?' boxtablenobottom':'').'" width="100%">';
1945
-
1946
-				// Definie date debut et fin par defaut
1947
-				$dateactstart = $objp->date_debut;
1948
-				if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1949
-				elseif (! $dateactstart) $dateactstart = time();
1950
-
1951
-				$dateactend = $objp->date_fin;
1952
-				if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1953
-				elseif (! $dateactend)
1954
-				{
1955
-					if ($objp->fk_product > 0)
1956
-					{
1957
-						$product=new Product($db);
1958
-						$product->fetch($objp->fk_product);
1959
-						$dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
1960
-					}
1961
-				}
1962
-
1963
-				print '<tr class="oddeven">';
1964
-				print '<td class="nohover">'.$langs->trans("DateServiceActivate").'</td><td class="nohover">';
1965
-				print $form->selectDate($dateactstart, '', $usehm, $usehm, '', "active", 1, 0);
1966
-				print '</td>';
1967
-				print '<td class="nohover">'.$langs->trans("DateEndPlanned").'</td><td class="nohover">';
1968
-				print $form->selectDate($dateactend, "end", $usehm, $usehm, '', "active", 1, 0);
1969
-				print '</td>';
1970
-				print '<td class="center nohover">';
1971
-				print '</td>';
1972
-
1973
-				print '</tr>';
1974
-
1975
-				print '<tr class="oddeven">';
1976
-				print '<td class="nohover">'.$langs->trans("Comment").'</td><td colspan="3" class="nohover" colspan="'.($conf->margin->enabled?4:3).'"><input size="80" type="text" name="comment" value="'.$_POST["comment"].'"></td>';
1977
-				print '<td class="nohover right">';
1978
-				print '<input type="submit" class="button" name="activate" value="'.$langs->trans("Activate").'"> &nbsp; ';
1979
-				print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
1980
-				print '</td>';
1981
-				print '</tr>';
1982
-
1983
-				print '</table>';
1984
-
1985
-				print '</form>';
1986
-			}
1987
-
1988
-			if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1989
-			{
1990
-				/**
1991
-				 * Disable a contract line
1992
-				 */
1993
-				print '<!-- Form to disabled a line -->'."\n";
1994
-				print '<form name="closeline" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline-1]->id.'" method="post">';
1995
-
1996
-				print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1997
-				print '<input type="hidden" name="action" value="closeline">';
1998
-
1999
-				print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ?' boxtablenobottom':'').'" width="100%">';
2000
-
2001
-				// Definie date debut et fin par defaut
2002
-				$dateactstart = $objp->date_debut_reelle;
2003
-				if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
2004
-				elseif (! $dateactstart) $dateactstart = time();
2005
-
2006
-				$dateactend = $objp->date_fin_reelle;
2007
-				if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
2008
-				elseif (! $dateactend)
2009
-				{
2010
-					if ($objp->fk_product > 0)
2011
-					{
2012
-						$product=new Product($db);
2013
-						$product->fetch($objp->fk_product);
2014
-						$dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
2015
-					}
2016
-				}
2017
-				$now=dol_now();
2018
-				if ($dateactend > $now) $dateactend=$now;
2019
-
2020
-				print '<tr class="oddeven"><td colspan="2" class="nohover">';
2021
-				if ($objp->statut >= 4)
2022
-				{
2023
-					if ($objp->statut == 4)
2024
-					{
2025
-						print $langs->trans("DateEndReal").' ';
2026
-						print $form->selectDate($dateactend, "end", $usehm, $usehm, ($objp->date_fin_reelle>0?0:1), "closeline", 1, 1);
2027
-					}
2028
-				}
2029
-				print '</td>';
2030
-				print '<td class="center nohover">';
2031
-				print '</td></tr>';
2032
-
2033
-				print '<tr class="oddeven">';
2034
-				print '<td class="nohover">'.$langs->trans("Comment").'</td><td class="nohover"><input size="70" type="text" class="flat" name="comment" value="'.dol_escape_htmltag(GETPOST('comment', 'alpha')).'"></td>';
2035
-				print '<td class="nohover right">';
2036
-				print '<input type="submit" class="button" name="close" value="'.$langs->trans("Disable").'"> &nbsp; ';
2037
-				print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
2038
-				print '</td>';
2039
-				print '</tr>';
2040
-
2041
-				print '</table>';
2042
-
2043
-				print '</form>';
2044
-			}
2045
-			print '</div>';
2046
-			$cursorline++;
2047
-		}
2048
-		print '</div>';
2049
-
2050
-		// Form to add new line
2051
-		if ($user->rights->contrat->creer && ($object->statut == 0))
2052
-		{
2053
-			$dateSelector=1;
2054
-
2055
-			print "\n";
2056
-			print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline')?'#add':'#line_'.GETPOST('lineid')).'" method="POST">
1857
+            if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1858
+            {
1859
+                $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1860
+                $dateactend   = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1861
+                $comment      = GETPOST('comment','alpha');
1862
+
1863
+                if (empty($dateactend))
1864
+                {
1865
+                    setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors');
1866
+                }
1867
+                else
1868
+                {
1869
+                    print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1);
1870
+                }
1871
+                print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1872
+            }
1873
+
1874
+
1875
+            // Area with status and activation info of line
1876
+            if ($object->statut > 0)
1877
+            {
1878
+                print '<table class="notopnoleftnoright tableforservicepart2'.($cursorline < $nbofservices ?' boxtablenobottom':'').'" width="100%">';
1879
+
1880
+                print '<tr class="oddeven">';
1881
+                print '<td>'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).'</td>';
1882
+                print '<td width="30" align="right">';
1883
+                if ($user->societe_id == 0)
1884
+                {
1885
+                    if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline')
1886
+                    {
1887
+                        $tmpaction='activateline';
1888
+                        $tmpactionpicto='play';
1889
+                        $tmpactiontext=$langs->trans("Activate");
1890
+                        if ($objp->statut == 4)
1891
+                        {
1892
+                            $tmpaction='unactivateline';
1893
+                            $tmpactionpicto='playstop';
1894
+                            $tmpactiontext=$langs->trans("Disable");
1895
+                        }
1896
+                        if (($tmpaction=='activateline' && $user->rights->contrat->activer) || ($tmpaction=='unactivateline' && $user->rights->contrat->desactiver))
1897
+                        {
1898
+                            print '<a class="reposition" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;ligne=' . $object->lines[$cursorline - 1]->id . '&amp;action=' . $tmpaction . '">';
1899
+                            print img_picto($tmpactiontext, $tmpactionpicto);
1900
+                            print '</a>';
1901
+                        }
1902
+                    }
1903
+                }
1904
+                print '</td>';
1905
+                print "</tr>\n";
1906
+
1907
+                print '<tr class="oddeven">';
1908
+
1909
+                print '<td>';
1910
+                // Si pas encore active
1911
+                if (! $objp->date_debut_reelle) {
1912
+                    print $langs->trans("DateStartReal").': ';
1913
+                    if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle, 'day');
1914
+                    else print $langs->trans("ContractStatusNotRunning");
1915
+                }
1916
+                // Si active et en cours
1917
+                if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) {
1918
+                    print $langs->trans("DateStartReal").': ';
1919
+                    print dol_print_date($objp->date_debut_reelle, 'day');
1920
+                }
1921
+                // Si desactive
1922
+                if ($objp->date_debut_reelle && $objp->date_fin_reelle) {
1923
+                    print $langs->trans("DateStartReal").': ';
1924
+                    print dol_print_date($objp->date_debut_reelle, 'day');
1925
+                    print ' &nbsp;-&nbsp; ';
1926
+                    print $langs->trans("DateEndReal").': ';
1927
+                    print dol_print_date($objp->date_fin_reelle, 'day');
1928
+                }
1929
+                if (! empty($objp->comment)) print " &nbsp;-&nbsp; ".$objp->comment;
1930
+                print '</td>';
1931
+
1932
+                print '<td align="center">&nbsp;</td>';
1933
+
1934
+                print '</tr>';
1935
+                print '</table>';
1936
+            }
1937
+
1938
+            // Form to activate line
1939
+            if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1940
+            {
1941
+                print '<form name="active" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.GETPOST('ligne').'&amp;action=active" method="post">';
1942
+                print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1943
+
1944
+                print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ?' boxtablenobottom':'').'" width="100%">';
1945
+
1946
+                // Definie date debut et fin par defaut
1947
+                $dateactstart = $objp->date_debut;
1948
+                if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1949
+                elseif (! $dateactstart) $dateactstart = time();
1950
+
1951
+                $dateactend = $objp->date_fin;
1952
+                if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1953
+                elseif (! $dateactend)
1954
+                {
1955
+                    if ($objp->fk_product > 0)
1956
+                    {
1957
+                        $product=new Product($db);
1958
+                        $product->fetch($objp->fk_product);
1959
+                        $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
1960
+                    }
1961
+                }
1962
+
1963
+                print '<tr class="oddeven">';
1964
+                print '<td class="nohover">'.$langs->trans("DateServiceActivate").'</td><td class="nohover">';
1965
+                print $form->selectDate($dateactstart, '', $usehm, $usehm, '', "active", 1, 0);
1966
+                print '</td>';
1967
+                print '<td class="nohover">'.$langs->trans("DateEndPlanned").'</td><td class="nohover">';
1968
+                print $form->selectDate($dateactend, "end", $usehm, $usehm, '', "active", 1, 0);
1969
+                print '</td>';
1970
+                print '<td class="center nohover">';
1971
+                print '</td>';
1972
+
1973
+                print '</tr>';
1974
+
1975
+                print '<tr class="oddeven">';
1976
+                print '<td class="nohover">'.$langs->trans("Comment").'</td><td colspan="3" class="nohover" colspan="'.($conf->margin->enabled?4:3).'"><input size="80" type="text" name="comment" value="'.$_POST["comment"].'"></td>';
1977
+                print '<td class="nohover right">';
1978
+                print '<input type="submit" class="button" name="activate" value="'.$langs->trans("Activate").'"> &nbsp; ';
1979
+                print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
1980
+                print '</td>';
1981
+                print '</tr>';
1982
+
1983
+                print '</table>';
1984
+
1985
+                print '</form>';
1986
+            }
1987
+
1988
+            if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1989
+            {
1990
+                /**
1991
+                 * Disable a contract line
1992
+                 */
1993
+                print '<!-- Form to disabled a line -->'."\n";
1994
+                print '<form name="closeline" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline-1]->id.'" method="post">';
1995
+
1996
+                print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1997
+                print '<input type="hidden" name="action" value="closeline">';
1998
+
1999
+                print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ?' boxtablenobottom':'').'" width="100%">';
2000
+
2001
+                // Definie date debut et fin par defaut
2002
+                $dateactstart = $objp->date_debut_reelle;
2003
+                if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
2004
+                elseif (! $dateactstart) $dateactstart = time();
2005
+
2006
+                $dateactend = $objp->date_fin_reelle;
2007
+                if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
2008
+                elseif (! $dateactend)
2009
+                {
2010
+                    if ($objp->fk_product > 0)
2011
+                    {
2012
+                        $product=new Product($db);
2013
+                        $product->fetch($objp->fk_product);
2014
+                        $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
2015
+                    }
2016
+                }
2017
+                $now=dol_now();
2018
+                if ($dateactend > $now) $dateactend=$now;
2019
+
2020
+                print '<tr class="oddeven"><td colspan="2" class="nohover">';
2021
+                if ($objp->statut >= 4)
2022
+                {
2023
+                    if ($objp->statut == 4)
2024
+                    {
2025
+                        print $langs->trans("DateEndReal").' ';
2026
+                        print $form->selectDate($dateactend, "end", $usehm, $usehm, ($objp->date_fin_reelle>0?0:1), "closeline", 1, 1);
2027
+                    }
2028
+                }
2029
+                print '</td>';
2030
+                print '<td class="center nohover">';
2031
+                print '</td></tr>';
2032
+
2033
+                print '<tr class="oddeven">';
2034
+                print '<td class="nohover">'.$langs->trans("Comment").'</td><td class="nohover"><input size="70" type="text" class="flat" name="comment" value="'.dol_escape_htmltag(GETPOST('comment', 'alpha')).'"></td>';
2035
+                print '<td class="nohover right">';
2036
+                print '<input type="submit" class="button" name="close" value="'.$langs->trans("Disable").'"> &nbsp; ';
2037
+                print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
2038
+                print '</td>';
2039
+                print '</tr>';
2040
+
2041
+                print '</table>';
2042
+
2043
+                print '</form>';
2044
+            }
2045
+            print '</div>';
2046
+            $cursorline++;
2047
+        }
2048
+        print '</div>';
2049
+
2050
+        // Form to add new line
2051
+        if ($user->rights->contrat->creer && ($object->statut == 0))
2052
+        {
2053
+            $dateSelector=1;
2054
+
2055
+            print "\n";
2056
+            print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline')?'#add':'#line_'.GETPOST('lineid')).'" method="POST">
2057 2057
 			<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">
2058 2058
 			<input type="hidden" name="action" value="'.(($action != 'editline')?'addline':'updateline').'">
2059 2059
 			<input type="hidden" name="mode" value="">
2060 2060
 			<input type="hidden" name="id" value="'.$object->id.'">
2061 2061
 			';
2062 2062
 
2063
-			print '<div class="div-table-responsive-no-min">';
2064
-			print '<table id="tablelines" class="noborder noshadow" width="100%">';	// Array with (n*2)+1 lines
2063
+            print '<div class="div-table-responsive-no-min">';
2064
+            print '<table id="tablelines" class="noborder noshadow" width="100%">';	// Array with (n*2)+1 lines
2065 2065
 
2066
-			// Form to add new line
2067
-	   		if ($action != 'editline')
2068
-			{
2069
-				$forcetoshowtitlelines=1;
2066
+            // Form to add new line
2067
+                if ($action != 'editline')
2068
+            {
2069
+                $forcetoshowtitlelines=1;
2070 2070
 
2071
-				// Add free products/services
2072
-				$object->formAddObjectLine(1, $mysoc, $soc);
2071
+                // Add free products/services
2072
+                $object->formAddObjectLine(1, $mysoc, $soc);
2073 2073
 
2074
-				$parameters = array();
2075
-				$reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2076
-			}
2074
+                $parameters = array();
2075
+                $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2076
+            }
2077 2077
 
2078
-			print '</table>';
2079
-			print '</div>';
2080
-			print '</form>';
2081
-		}
2078
+            print '</table>';
2079
+            print '</div>';
2080
+            print '</form>';
2081
+        }
2082 2082
 
2083
-		dol_fiche_end();
2083
+        dol_fiche_end();
2084 2084
 
2085 2085
 
2086
-		/*
2086
+        /*
2087 2087
          * Buttons
2088 2088
          */
2089 2089
 
2090
-		if ($user->societe_id == 0)
2091
-		{
2092
-			print '<div class="tabsAction">';
2093
-
2094
-			$parameters=array();
2095
-			$reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
2096
-
2097
-			if (empty($reshook))
2098
-			{
2099
-				// Send
2100
-				if ($object->statut == 1) {
2101
-					if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) {
2102
-						print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a></div>';
2103
-					} else
2104
-						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">' . $langs->trans('SendMail') . '</a></div>';
2105
-				}
2106
-
2107
-				if ($object->statut == 0 && $nbofservices)
2108
-				{
2109
-					if ($user->rights->contrat->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">'.$langs->trans("Validate").'</a></div>';
2110
-					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Validate").'</a></div>';
2111
-				}
2112
-				if ($object->statut == 1)
2113
-				{
2114
-					if ($user->rights->contrat->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Modify").'</a></div>';
2115
-					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Modify").'</a></div>';
2116
-				}
2117
-
2118
-				if (! empty($conf->facture->enabled) && $object->statut > 0)
2119
-				{
2120
-					$langs->load("bills");
2121
-					if ($user->rights->facture->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateBill").'</a></div>';
2122
-					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateBill").'</a></div>';
2123
-				}
2124
-
2125
-				if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices)
2126
-				{
2127
-					$langs->load("orders");
2128
-					if ($user->rights->commande->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateOrder").'</a></div>';
2129
-					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateOrder").'</a></div>';
2130
-				}
2131
-
2132
-				// Clone
2133
-				if ($user->rights->contrat->creer) {
2134
-					print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&amp;socid=' . $object->socid . '&amp;action=clone&amp;object=' . $object->element . '">' . $langs->trans("ToClone") . '</a></div>';
2135
-				}
2136
-
2137
-				if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0)
2138
-				{
2139
-					if ($user->rights->contrat->activer)
2140
-					{
2141
-						print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=activate">'.$langs->trans("ActivateAllContracts").'</a></div>';
2142
-					}
2143
-					else
2144
-					{
2145
-						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("ActivateAllContracts").'</a></div>';
2146
-					}
2147
-				}
2148
-				if ($object->nbofservicesclosed < $nbofservices)
2149
-				{
2150
-					if ($user->rights->contrat->desactiver)
2151
-					{
2152
-						print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=close">'.$langs->trans("CloseAllContracts").'</a></div>';
2153
-					}
2154
-					else
2155
-					{
2156
-						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("CloseAllContracts").'</a></div>';
2157
-					}
2158
-
2159
-					//if (! $numactive)
2160
-					//{
2161
-					//}
2162
-					//else
2163
-					//{
2164
-					//	print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("CloseRefusedBecauseOneServiceActive").'">'.$langs->trans("Close").'</a></div>';
2165
-					//}
2166
-				}
2167
-
2168
-				// On peut supprimer entite si
2169
-				// - Droit de creer + mode brouillon (erreur creation)
2170
-				// - Droit de supprimer
2171
-				if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer)
2172
-				{
2173
-					print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete">'.$langs->trans("Delete").'</a></div>';
2174
-				}
2175
-				else
2176
-				{
2177
-					print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("Delete").'</a></div>';
2178
-				}
2179
-			}
2180
-
2181
-			print "</div>";
2182
-		}
2183
-
2184
-		// Select mail models is same action as presend
2185
-		if (GETPOST('modelselected')) {
2186
-			$action = 'presend';
2187
-		}
2188
-
2189
-		if ($action != 'presend')
2190
-		{
2191
-			print '<div class="fichecenter"><div class="fichehalfleft">';
2192
-
2193
-			/*
2090
+        if ($user->societe_id == 0)
2091
+        {
2092
+            print '<div class="tabsAction">';
2093
+
2094
+            $parameters=array();
2095
+            $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
2096
+
2097
+            if (empty($reshook))
2098
+            {
2099
+                // Send
2100
+                if ($object->statut == 1) {
2101
+                    if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) {
2102
+                        print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a></div>';
2103
+                    } else
2104
+                        print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">' . $langs->trans('SendMail') . '</a></div>';
2105
+                }
2106
+
2107
+                if ($object->statut == 0 && $nbofservices)
2108
+                {
2109
+                    if ($user->rights->contrat->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">'.$langs->trans("Validate").'</a></div>';
2110
+                    else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Validate").'</a></div>';
2111
+                }
2112
+                if ($object->statut == 1)
2113
+                {
2114
+                    if ($user->rights->contrat->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Modify").'</a></div>';
2115
+                    else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Modify").'</a></div>';
2116
+                }
2117
+
2118
+                if (! empty($conf->facture->enabled) && $object->statut > 0)
2119
+                {
2120
+                    $langs->load("bills");
2121
+                    if ($user->rights->facture->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateBill").'</a></div>';
2122
+                    else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateBill").'</a></div>';
2123
+                }
2124
+
2125
+                if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices)
2126
+                {
2127
+                    $langs->load("orders");
2128
+                    if ($user->rights->commande->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateOrder").'</a></div>';
2129
+                    else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateOrder").'</a></div>';
2130
+                }
2131
+
2132
+                // Clone
2133
+                if ($user->rights->contrat->creer) {
2134
+                    print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&amp;socid=' . $object->socid . '&amp;action=clone&amp;object=' . $object->element . '">' . $langs->trans("ToClone") . '</a></div>';
2135
+                }
2136
+
2137
+                if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0)
2138
+                {
2139
+                    if ($user->rights->contrat->activer)
2140
+                    {
2141
+                        print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=activate">'.$langs->trans("ActivateAllContracts").'</a></div>';
2142
+                    }
2143
+                    else
2144
+                    {
2145
+                        print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("ActivateAllContracts").'</a></div>';
2146
+                    }
2147
+                }
2148
+                if ($object->nbofservicesclosed < $nbofservices)
2149
+                {
2150
+                    if ($user->rights->contrat->desactiver)
2151
+                    {
2152
+                        print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=close">'.$langs->trans("CloseAllContracts").'</a></div>';
2153
+                    }
2154
+                    else
2155
+                    {
2156
+                        print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("CloseAllContracts").'</a></div>';
2157
+                    }
2158
+
2159
+                    //if (! $numactive)
2160
+                    //{
2161
+                    //}
2162
+                    //else
2163
+                    //{
2164
+                    //	print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("CloseRefusedBecauseOneServiceActive").'">'.$langs->trans("Close").'</a></div>';
2165
+                    //}
2166
+                }
2167
+
2168
+                // On peut supprimer entite si
2169
+                // - Droit de creer + mode brouillon (erreur creation)
2170
+                // - Droit de supprimer
2171
+                if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer)
2172
+                {
2173
+                    print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete">'.$langs->trans("Delete").'</a></div>';
2174
+                }
2175
+                else
2176
+                {
2177
+                    print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("Delete").'</a></div>';
2178
+                }
2179
+            }
2180
+
2181
+            print "</div>";
2182
+        }
2183
+
2184
+        // Select mail models is same action as presend
2185
+        if (GETPOST('modelselected')) {
2186
+            $action = 'presend';
2187
+        }
2188
+
2189
+        if ($action != 'presend')
2190
+        {
2191
+            print '<div class="fichecenter"><div class="fichehalfleft">';
2192
+
2193
+            /*
2194 2194
     		 * Documents generes
2195 2195
     		*/
2196
-			$filename = dol_sanitizeFileName($object->ref);
2197
-			$filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref);
2198
-			$urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
2199
-			$genallowed = $user->rights->contrat->lire;
2200
-			$delallowed = $user->rights->contrat->creer;
2196
+            $filename = dol_sanitizeFileName($object->ref);
2197
+            $filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref);
2198
+            $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
2199
+            $genallowed = $user->rights->contrat->lire;
2200
+            $delallowed = $user->rights->contrat->creer;
2201 2201
 
2202 2202
 
2203
-			print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
2203
+            print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
2204 2204
 
2205 2205
 
2206
-			// Show links to link elements
2207
-			$linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat'));
2208
-			$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
2206
+            // Show links to link elements
2207
+            $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat'));
2208
+            $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
2209 2209
 
2210 2210
 
2211
-			print '</div><div class="fichehalfright"><div class="ficheaddleft">';
2211
+            print '</div><div class="fichehalfright"><div class="ficheaddleft">';
2212 2212
 
2213
-			// List of actions on element
2214
-			include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
2215
-			$formactions = new FormActions($db);
2216
-			$somethingshown = $formactions->showactions($object, 'contract', $socid, 1);
2213
+            // List of actions on element
2214
+            include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
2215
+            $formactions = new FormActions($db);
2216
+            $somethingshown = $formactions->showactions($object, 'contract', $socid, 1);
2217 2217
 
2218 2218
 
2219
-			print '</div></div></div>';
2220
-		}
2219
+            print '</div></div></div>';
2220
+        }
2221 2221
 
2222
-		// Presend form
2223
-		$modelmail='contract';
2224
-		$defaulttopic='SendContractRef';
2225
-		$diroutput = $conf->contrat->dir_output;
2226
-		$trackid = 'con'.$object->id;
2222
+        // Presend form
2223
+        $modelmail='contract';
2224
+        $defaulttopic='SendContractRef';
2225
+        $diroutput = $conf->contrat->dir_output;
2226
+        $trackid = 'con'.$object->id;
2227 2227
 
2228
-		include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2229
-	}
2228
+        include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2229
+    }
2230 2230
 }
2231 2231
 
2232 2232
 
Please login to merge, or discard this patch.
Spacing   +399 added lines, -399 removed lines patch added patch discarded remove patch
@@ -40,39 +40,39 @@  discard block
 block discarded – undo
40 40
 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
41 41
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
42 42
 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
43
-if (! empty($conf->propal->enabled))  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
44
-if (! empty($conf->projet->enabled)) {
43
+if (!empty($conf->propal->enabled))  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
44
+if (!empty($conf->projet->enabled)) {
45 45
 	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
46 46
 	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
47 47
 }
48
-require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
48
+require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
49 49
 
50 50
 // Load translation files required by the page
51
-$langs->loadLangs(array("contracts","orders","companies","bills","products",'compta'));
51
+$langs->loadLangs(array("contracts", "orders", "companies", "bills", "products", 'compta'));
52 52
 
53
-$action=GETPOST('action','alpha');
54
-$confirm=GETPOST('confirm','alpha');
55
-$socid = GETPOST('socid','int');
56
-$id = GETPOST('id','int');
57
-$ref=GETPOST('ref','alpha');
58
-$origin=GETPOST('origin','alpha');
59
-$originid=GETPOST('originid','int');
53
+$action = GETPOST('action', 'alpha');
54
+$confirm = GETPOST('confirm', 'alpha');
55
+$socid = GETPOST('socid', 'int');
56
+$id = GETPOST('id', 'int');
57
+$ref = GETPOST('ref', 'alpha');
58
+$origin = GETPOST('origin', 'alpha');
59
+$originid = GETPOST('originid', 'int');
60 60
 
61
-$datecontrat='';
62
-$usehm=(! empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE)?$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE:0);
61
+$datecontrat = '';
62
+$usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
63 63
 
64 64
 // Security check
65
-if ($user->societe_id) $socid=$user->societe_id;
66
-$result=restrictedArea($user,'contrat',$id);
65
+if ($user->societe_id) $socid = $user->societe_id;
66
+$result = restrictedArea($user, 'contrat', $id);
67 67
 
68 68
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
69
-$hookmanager->initHooks(array('contractcard','globalcard'));
69
+$hookmanager->initHooks(array('contractcard', 'globalcard'));
70 70
 
71 71
 $object = new Contrat($db);
72 72
 $extrafields = new ExtraFields($db);
73 73
 
74 74
 // Load object
75
-if ($id > 0 || ! empty($ref) && $action!='add') {
75
+if ($id > 0 || !empty($ref) && $action != 'add') {
76 76
 	$ret = $object->fetch($id, $ref);
77 77
 	if ($ret > 0)
78 78
 		$ret = $object->fetch_thirdparty();
@@ -85,10 +85,10 @@  discard block
 block discarded – undo
85 85
 
86 86
 // fetch optionals attributes lines and labels
87 87
 $extrafieldsline = new ExtraFields($db);
88
-$extralabelslines=$extrafieldsline->fetch_name_optionals_label($object->table_element_line);
88
+$extralabelslines = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
89 89
 
90
-$permissionnote=$user->rights->contrat->creer;	// Used by the include of actions_setnotes.inc.php
91
-$permissiondellink=$user->rights->contrat->creer;	// Used by the include of actions_dellink.inc.php
90
+$permissionnote = $user->rights->contrat->creer; // Used by the include of actions_setnotes.inc.php
91
+$permissiondellink = $user->rights->contrat->creer; // Used by the include of actions_dellink.inc.php
92 92
 
93 93
 
94 94
 
@@ -101,9 +101,9 @@  discard block
 block discarded – undo
101 101
 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
102 102
 if (empty($reshook))
103 103
 {
104
-	include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include, not includ_once
104
+	include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once
105 105
 
106
-	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';		// Must be include, not include_once
106
+	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
107 107
 
108 108
 	if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer)
109 109
 	{
@@ -121,12 +121,12 @@  discard block
 block discarded – undo
121 121
 
122 122
 	else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer)
123 123
 	{
124
-		if (! GETPOST('dateend'))
124
+		if (!GETPOST('dateend'))
125 125
 		{
126 126
 			$error++;
127 127
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
128 128
 		}
129
-		if (! $error)
129
+		if (!$error)
130 130
 		{
131 131
 			$result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment')));
132 132
 			if ($result > 0)
@@ -142,56 +142,56 @@  discard block
 block discarded – undo
142 142
 	}
143 143
 
144 144
 	// Si ajout champ produit predefini
145
-	if (GETPOST('mode')=='predefined')
145
+	if (GETPOST('mode') == 'predefined')
146 146
 	{
147
-		$date_start='';
148
-		$date_end='';
147
+		$date_start = '';
148
+		$date_end = '';
149 149
 		if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear'))
150 150
 		{
151
-			$date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
151
+			$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
152 152
 		}
153 153
 		if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear'))
154 154
 		{
155
-			$date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
155
+			$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
156 156
 		}
157 157
 	}
158 158
 
159 159
 	// Si ajout champ produit libre
160
-	if (GETPOST('mode')=='libre')
160
+	if (GETPOST('mode') == 'libre')
161 161
 	{
162
-		$date_start_sl='';
163
-		$date_end_sl='';
162
+		$date_start_sl = '';
163
+		$date_end_sl = '';
164 164
 		if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear'))
165 165
 		{
166
-			$date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear'));
166
+			$date_start_sl = dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear'));
167 167
 		}
168 168
 		if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear'))
169 169
 		{
170
-			$date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear'));
170
+			$date_end_sl = dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear'));
171 171
 		}
172 172
 	}
173 173
 
174 174
 	// Param dates
175
-	$date_contrat='';
176
-	$date_start_update='';
177
-	$date_end_update='';
178
-	$date_start_real_update='';
179
-	$date_end_real_update='';
175
+	$date_contrat = '';
176
+	$date_start_update = '';
177
+	$date_end_update = '';
178
+	$date_start_real_update = '';
179
+	$date_end_real_update = '';
180 180
 	if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear'))
181 181
 	{
182
-		$date_start_update=dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear'));
182
+		$date_start_update = dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear'));
183 183
 	}
184 184
 	if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear'))
185 185
 	{
186
-		$date_end_update=dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear'));
186
+		$date_end_update = dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear'));
187 187
 	}
188 188
 	if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear'))
189 189
 	{
190
-		$date_start_real_update=dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear'));
190
+		$date_start_real_update = dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear'));
191 191
 	}
192 192
 	if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear'))
193 193
 	{
194
-		$date_end_real_update=dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear'));
194
+		$date_end_real_update = dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear'));
195 195
 	}
196 196
 	if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear'))
197 197
 	{
@@ -206,60 +206,60 @@  discard block
 block discarded – undo
206 206
 		{
207 207
 			$error++;
208 208
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
209
-			$action='create';
209
+			$action = 'create';
210 210
 		}
211 211
 
212
-		if ($socid<1)
212
+		if ($socid < 1)
213 213
 		{
214 214
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors');
215
-			$action='create';
215
+			$action = 'create';
216 216
 			$error++;
217 217
 		}
218 218
 
219 219
 		// Fill array 'array_options' with data from add form
220 220
 		$ret = $extrafields->setOptionalsFromPost($extralabels, $object);
221 221
 		if ($ret < 0) {
222
-			$error ++;
222
+			$error++;
223 223
 			$action = 'create';
224 224
 		}
225 225
 
226
-		if (! $error)
226
+		if (!$error)
227 227
 		{
228
-			$object->socid						= $socid;
229
-			$object->date_contrat				= $datecontrat;
228
+			$object->socid = $socid;
229
+			$object->date_contrat = $datecontrat;
230 230
 
231
-			$object->commercial_suivi_id		= GETPOST('commercial_suivi_id','int');
232
-			$object->commercial_signature_id	= GETPOST('commercial_signature_id','int');
231
+			$object->commercial_suivi_id = GETPOST('commercial_suivi_id', 'int');
232
+			$object->commercial_signature_id = GETPOST('commercial_signature_id', 'int');
233 233
 
234
-			$object->note_private				= GETPOST('note_private','alpha');
235
-			$object->note_public				= GETPOST('note_public','alpha');
236
-			$object->fk_project					= GETPOST('projectid','int');
237
-			$object->remise_percent				= GETPOST('remise_percent','alpha');
238
-			$object->ref						= GETPOST('ref','alpha');
239
-			$object->ref_customer				= GETPOST('ref_customer','alpha');
240
-			$object->ref_supplier				= GETPOST('ref_supplier','alpha');
234
+			$object->note_private = GETPOST('note_private', 'alpha');
235
+			$object->note_public				= GETPOST('note_public', 'alpha');
236
+			$object->fk_project					= GETPOST('projectid', 'int');
237
+			$object->remise_percent = GETPOST('remise_percent', 'alpha');
238
+			$object->ref = GETPOST('ref', 'alpha');
239
+			$object->ref_customer				= GETPOST('ref_customer', 'alpha');
240
+			$object->ref_supplier				= GETPOST('ref_supplier', 'alpha');
241 241
 
242 242
 			// If creation from another object of another module (Example: origin=propal, originid=1)
243
-			if (! empty($origin) && ! empty($originid))
243
+			if (!empty($origin) && !empty($originid))
244 244
 			{
245 245
 				// Parse element/subelement (ex: project_task)
246 246
 				$element = $subelement = $origin;
247
-				if (preg_match('/^([^_]+)_([^_]+)/i',$origin,$regs))
247
+				if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs))
248 248
 				{
249 249
 					$element = $regs[1];
250 250
 					$subelement = $regs[2];
251 251
 				}
252 252
 
253 253
 				// For compatibility
254
-				if ($element == 'order')    { $element = $subelement = 'commande'; }
255
-				if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
254
+				if ($element == 'order') { $element = $subelement = 'commande'; }
255
+				if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; }
256 256
 
257 257
 				$object->origin    = $origin;
258 258
 				$object->origin_id = $originid;
259 259
 
260 260
 				// Possibility to add external linked objects with hooks
261 261
 				$object->linked_objects[$object->origin] = $object->origin_id;
262
-				if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects']))
262
+				if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects']))
263 263
 				{
264 264
 					$object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
265 265
 				}
@@ -277,54 +277,54 @@  discard block
 block discarded – undo
277 277
 					$srcobject = new $classname($db);
278 278
 
279 279
 					dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
280
-					$result=$srcobject->fetch($object->origin_id);
280
+					$result = $srcobject->fetch($object->origin_id);
281 281
 					if ($result > 0)
282 282
 					{
283 283
 						$srcobject->fetch_thirdparty();
284 284
 						$lines = $srcobject->lines;
285
-						if (empty($lines) && method_exists($srcobject,'fetch_lines'))
285
+						if (empty($lines) && method_exists($srcobject, 'fetch_lines'))
286 286
 						{
287 287
 							$srcobject->fetch_lines();
288 288
 							$lines = $srcobject->lines;
289 289
 						}
290 290
 
291
-						$fk_parent_line=0;
292
-						$num=count($lines);
291
+						$fk_parent_line = 0;
292
+						$num = count($lines);
293 293
 
294
-						for ($i=0;$i<$num;$i++)
294
+						for ($i = 0; $i < $num; $i++)
295 295
 						{
296
-							$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
296
+							$product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
297 297
 
298
-							if ($product_type == 1 || (! empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0,1)))) { 	// TODO Exclude also deee
298
+							if ($product_type == 1 || (!empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0, 1)))) { 	// TODO Exclude also deee
299 299
 								// service prédéfini
300 300
 								if ($lines[$i]->fk_product > 0)
301 301
 								{
302 302
 									$product_static = new Product($db);
303 303
 
304 304
 									// Define output language
305
-									if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE))
305
+									if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE))
306 306
 									{
307 307
 										$prod = new Product($db);
308
-										$prod->id=$lines[$i]->fk_product;
308
+										$prod->id = $lines[$i]->fk_product;
309 309
 										$prod->getMultiLangs();
310 310
 
311 311
 										$outputlangs = $langs;
312
-										$newlang='';
313
-										if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
314
-										if (empty($newlang)) $newlang=$srcobject->thirdparty->default_lang;
315
-										if (! empty($newlang))
312
+										$newlang = '';
313
+										if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
314
+										if (empty($newlang)) $newlang = $srcobject->thirdparty->default_lang;
315
+										if (!empty($newlang))
316 316
 										{
317
-											$outputlangs = new Translate("",$conf);
317
+											$outputlangs = new Translate("", $conf);
318 318
 											$outputlangs->setDefaultLang($newlang);
319 319
 										}
320 320
 
321
-										$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
321
+										$label = (!empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
322 322
 									}
323 323
 									else
324 324
 									{
325 325
 										$label = $lines[$i]->product_label;
326 326
 									}
327
-									$desc = ($lines[$i]->desc && $lines[$i]->desc!=$lines[$i]->libelle)?dol_htmlentitiesbr($lines[$i]->desc):'';
327
+									$desc = ($lines[$i]->desc && $lines[$i]->desc != $lines[$i]->libelle) ?dol_htmlentitiesbr($lines[$i]->desc) : '';
328 328
 								}
329 329
 								else {
330 330
 									$desc = dol_htmlentitiesbr($lines[$i]->desc);
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 									$array_options = $lines[$i]->array_options;
340 340
 								}
341 341
 
342
-								$txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx . ' (' .  $lines[$i]->vat_src_code . ')' : $lines[$i]->tva_tx;
342
+								$txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx.' ('.$lines[$i]->vat_src_code.')' : $lines[$i]->tva_tx;
343 343
 
344 344
 								// View third's localtaxes for now
345 345
 								$localtax1_tx = get_localtax($txtva, 1, $object->thirdparty);
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
 				else {
404 404
 					setEventMessages($object->error, $object->errors, 'errors');
405 405
 				}
406
-				$action='create';
406
+				$action = 'create';
407 407
 			}
408 408
 		}
409 409
 	}
@@ -417,18 +417,18 @@  discard block
 block discarded – undo
417 417
 	else if ($action == 'addline' && $user->rights->contrat->creer)
418 418
 	{
419 419
 		// Set if we used free entry or predefined product
420
-		$predef='';
421
-		$product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
420
+		$predef = '';
421
+		$product_desc = (GETPOST('dp_desc') ?GETPOST('dp_desc') : '');
422 422
 		$price_ht = GETPOST('price_ht');
423 423
 		$price_ht_devise = GETPOST('multicurrency_price_ht');
424 424
 		if (GETPOST('prod_entry_mode') == 'free')
425 425
 		{
426
-			$idprod=0;
426
+			$idprod = 0;
427 427
 			$tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
428 428
 		}
429 429
 		else
430 430
 		{
431
-			$idprod=GETPOST('idprod', 'int');
431
+			$idprod = GETPOST('idprod', 'int');
432 432
 			$tva_tx = '';
433 433
 		}
434 434
 
@@ -446,8 +446,8 @@  discard block
 block discarded – undo
446 446
 			$error++;
447 447
 		}
448 448
 
449
-	  $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year'));
450
-	  $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year'));
449
+	  $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
450
+	  $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
451 451
 	  if (!empty($date_start) && !empty($date_end) && $date_start > $date_end)
452 452
 	  {
453 453
 		  setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
@@ -462,16 +462,16 @@  discard block
 block discarded – undo
462 462
 		if (is_array($extralabelsline)) {
463 463
 			// Get extra fields
464 464
 			foreach ($extralabelsline as $key => $value) {
465
-				unset($_POST["options_" . $key]);
465
+				unset($_POST["options_".$key]);
466 466
 			}
467 467
 		}
468 468
 
469
-		if (! $error)
469
+		if (!$error)
470 470
 		{
471 471
 			// Clean parameters
472
-			$date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
473
-			$date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
474
-			$price_base_type = (GETPOST('price_base_type', 'alpha')?GETPOST('price_base_type', 'alpha'):'HT');
472
+			$date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
473
+			$date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
474
+			$price_base_type = (GETPOST('price_base_type', 'alpha') ?GETPOST('price_base_type', 'alpha') : 'HT');
475 475
 
476 476
 			// Ecrase $pu par celui du produit
477 477
 			// Ecrase $desc par celui du produit
@@ -483,9 +483,9 @@  discard block
 block discarded – undo
483 483
 				$prod->fetch($idprod);
484 484
 
485 485
 				// Update if prices fields are defined
486
-				$tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id);
487
-				$tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id);
488
-				if (empty($tva_tx)) $tva_npr=0;
486
+				$tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
487
+				$tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
488
+				if (empty($tva_tx)) $tva_npr = 0;
489 489
 
490 490
 				$pu_ht = $prod->price;
491 491
 				$pu_ttc = $prod->price_ttc;
@@ -500,13 +500,13 @@  discard block
 block discarded – undo
500 500
 					$price_min = $prod->multiprices_min[$object->thirdparty->price_level];
501 501
 					$price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
502 502
 				}
503
-				elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
503
+				elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES))
504 504
 				{
505
-					require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
505
+					require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
506 506
 
507 507
 					$prodcustprice = new Productcustomerprice($db);
508 508
 
509
-					$filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id);
509
+					$filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id);
510 510
 
511 511
 					$result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
512 512
 					if ($result) {
@@ -515,9 +515,9 @@  discard block
 block discarded – undo
515 515
 							$pu_ttc = price($prodcustprice->lines [0]->price_ttc);
516 516
 							$price_base_type = $prodcustprice->lines [0]->price_base_type;
517 517
 							$tva_tx = $prodcustprice->lines [0]->tva_tx;
518
-							if ($prodcustprice->lines[0]->default_vat_code && ! preg_match('/\(.*\)/', $tva_tx)) $tva_tx.= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
518
+							if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
519 519
 							$tva_npr = $prodcustprice->lines[0]->recuperableonly;
520
-							if (empty($tva_tx)) $tva_npr=0;
520
+							if (empty($tva_tx)) $tva_npr = 0;
521 521
 						}
522 522
 					}
523 523
 				}
@@ -531,45 +531,45 @@  discard block
 block discarded – undo
531 531
 				{
532 532
 					if ($price_base_type != 'HT')
533 533
 					{
534
-						$pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU');
534
+						$pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
535 535
 					}
536 536
 					else
537 537
 				  {
538
-						$pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU');
538
+						$pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
539 539
 					}
540 540
 				}
541 541
 
542
-			   	$desc=$prod->description;
543
-			   	$desc=dol_concatdesc($desc,$product_desc, '', !empty($conf->global->CHANGE_ORDER_CONCAT_DESCRIPTION));
542
+			   	$desc = $prod->description;
543
+			   	$desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->CHANGE_ORDER_CONCAT_DESCRIPTION));
544 544
 				$fk_unit = $prod->fk_unit;
545 545
 			}
546 546
 			else
547 547
 			{
548
-				$pu_ht=GETPOST('price_ht');
548
+				$pu_ht = GETPOST('price_ht');
549 549
 				$price_base_type = 'HT';
550
-				$tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0;		// tva_tx field may be disabled, so we use vat rate 0
551
-				$tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0;
552
-				$desc=$product_desc;
553
-				$fk_unit= GETPOST('units', 'alpha');
550
+				$tva_tx = GETPOST('tva_tx') ?str_replace('*', '', GETPOST('tva_tx')) : 0; // tva_tx field may be disabled, so we use vat rate 0
551
+				$tva_npr = preg_match('/\*/', GETPOST('tva_tx')) ? 1 : 0;
552
+				$desc = $product_desc;
553
+				$fk_unit = GETPOST('units', 'alpha');
554 554
 			}
555 555
 
556
-			$localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty,$mysoc,$tva_npr);
557
-			$localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty,$mysoc,$tva_npr);
556
+			$localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
557
+			$localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
558 558
 
559 559
 			// ajout prix achat
560 560
 			$fk_fournprice = $_POST['fournprice'];
561
-			if ( ! empty($_POST['buying_price']) )
561
+			if (!empty($_POST['buying_price']))
562 562
 			  $pa_ht = $_POST['buying_price'];
563 563
 			else
564 564
 			  $pa_ht = null;
565 565
 
566
-			$info_bits=0;
566
+			$info_bits = 0;
567 567
 			if ($tva_npr) $info_bits |= 0x01;
568 568
 
569
-			if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS) )&& ($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))))
569
+			if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && ($price_min && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))))
570 570
 			{
571
-				$object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency));
572
-				$result = -1 ;
571
+				$object->error = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
572
+				$result = -1;
573 573
 			}
574 574
 			else
575 575
 			{
@@ -598,13 +598,13 @@  discard block
 block discarded – undo
598 598
 			if ($result > 0)
599 599
 			{
600 600
 				// Define output language
601
-				if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && ! empty($conf->global->CONTRACT_ADDON_PDF))    // No generation if default type not defined
601
+				if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && !empty($conf->global->CONTRACT_ADDON_PDF))    // No generation if default type not defined
602 602
 				{
603 603
 					$outputlangs = $langs;
604 604
 					$newlang = '';
605
-					if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
605
+					if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
606 606
 					if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
607
-					if (! empty($newlang)) {
607
+					if (!empty($newlang)) {
608 608
 						$outputlangs = new Translate("", $conf);
609 609
 						$outputlangs->setDefaultLang($newlang);
610 610
 					}
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
 		}
654 654
 	}
655 655
 
656
-	else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel','alpha'))
656
+	else if ($action == 'updateline' && $user->rights->contrat->creer && !GETPOST('cancel', 'alpha'))
657 657
 	{
658 658
 		$error = 0;
659 659
 
@@ -665,7 +665,7 @@  discard block
 block discarded – undo
665 665
 			$error++;
666 666
 		}
667 667
 
668
-		if (! $error)
668
+		if (!$error)
669 669
 		{
670 670
 			$objectline = new ContratLigne($db);
671 671
 			if ($objectline->fetch(GETPOST('elrowid')) < 0)
@@ -677,10 +677,10 @@  discard block
 block discarded – undo
677 677
 
678 678
 		$db->begin();
679 679
 
680
-		if (! $error)
680
+		if (!$error)
681 681
 		{
682
-			if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture;
683
-			if ($date_end_real_update == '')   $date_end_real_update=$objectline->date_cloture;
682
+			if ($date_start_real_update == '') $date_start_real_update = $objectline->date_ouverture;
683
+			if ($date_end_real_update == '')   $date_end_real_update = $objectline->date_cloture;
684 684
 
685 685
 			$vat_rate = GETPOST('eltva_tx');
686 686
 			// Define info_bits
@@ -690,44 +690,44 @@  discard block
 block discarded – undo
690 690
 
691 691
 			// Define vat_rate
692 692
 			$vat_rate = str_replace('*', '', $vat_rate);
693
-			$localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
694
-			$localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
693
+			$localtax1_tx = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
694
+			$localtax2_tx = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
695 695
 
696 696
 			$txtva = $vat_rate;
697 697
 
698 698
 			// Clean vat code
699
-			$vat_src_code='';
699
+			$vat_src_code = '';
700 700
 			if (preg_match('/\((.*)\)/', $txtva, $reg))
701 701
 			{
702 702
 				  $vat_src_code = $reg[1];
703
-				  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva);    // Remove code into vatrate.
703
+				  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
704 704
 			}
705 705
 
706 706
 			// ajout prix d'achat
707 707
 			$fk_fournprice = $_POST['fournprice'];
708
-			if ( ! empty($_POST['buying_price']) )
708
+			if (!empty($_POST['buying_price']))
709 709
 			  $pa_ht = $_POST['buying_price'];
710 710
 			else
711 711
 			  $pa_ht = null;
712 712
 
713 713
 			$fk_unit = GETPOST('unit', 'alpha');
714 714
 
715
-			$objectline->description=GETPOST('product_desc','none');
716
-			$objectline->price_ht=GETPOST('elprice');
717
-			$objectline->subprice=GETPOST('elprice');
718
-			$objectline->qty=GETPOST('elqty');
719
-			$objectline->remise_percent=GETPOST('elremise_percent');
720
-			$objectline->tva_tx=($txtva?$txtva:0);	// Field may be disabled, so we use vat rate 0
721
-			$objectline->vat_src_code=$vat_src_code;
722
-			$objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0;
723
-			$objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0;
724
-			$objectline->date_ouverture_prevue=$date_start_update;
725
-			$objectline->date_ouverture=$date_start_real_update;
726
-			$objectline->date_fin_validite=$date_end_update;
727
-			$objectline->date_cloture=$date_end_real_update;
728
-			$objectline->fk_user_cloture=$user->id;
729
-			$objectline->fk_fournprice=$fk_fournprice;
730
-			$objectline->pa_ht=$pa_ht;
715
+			$objectline->description = GETPOST('product_desc', 'none');
716
+			$objectline->price_ht = GETPOST('elprice');
717
+			$objectline->subprice = GETPOST('elprice');
718
+			$objectline->qty = GETPOST('elqty');
719
+			$objectline->remise_percent = GETPOST('elremise_percent');
720
+			$objectline->tva_tx = ($txtva ? $txtva : 0); // Field may be disabled, so we use vat rate 0
721
+			$objectline->vat_src_code = $vat_src_code;
722
+			$objectline->localtax1_tx = is_numeric($localtax1_tx) ? $localtax1_tx : 0;
723
+			$objectline->localtax2_tx = is_numeric($localtax2_tx) ? $localtax2_tx : 0;
724
+			$objectline->date_ouverture_prevue = $date_start_update;
725
+			$objectline->date_ouverture = $date_start_real_update;
726
+			$objectline->date_fin_validite = $date_end_update;
727
+			$objectline->date_cloture = $date_end_real_update;
728
+			$objectline->fk_user_cloture = $user->id;
729
+			$objectline->fk_fournprice = $fk_fournprice;
730
+			$objectline->pa_ht = $pa_ht;
731 731
 
732 732
 			if ($fk_unit > 0) {
733 733
 			  $objectline->fk_unit = GETPOST('unit');
@@ -739,11 +739,11 @@  discard block
 block discarded – undo
739 739
 			$extrafieldsline = new ExtraFields($db);
740 740
 			$extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element);
741 741
 			$array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
742
-			$objectline->array_options=$array_options;
742
+			$objectline->array_options = $array_options;
743 743
 
744 744
 			// TODO verifier price_min si fk_product et multiprix
745 745
 
746
-			$result=$objectline->update($user);
746
+			$result = $objectline->update($user);
747 747
 			if ($result < 0)
748 748
 			{
749 749
 				$error++;
@@ -751,7 +751,7 @@  discard block
 block discarded – undo
751 751
 			}
752 752
 		}
753 753
 
754
-		if (! $error)
754
+		if (!$error)
755 755
 		{
756 756
 			$db->commit();
757 757
 		}
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
 
764 764
 	else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer)
765 765
 	{
766
-		$result = $object->deleteline(GETPOST('lineid'),$user);
766
+		$result = $object->deleteline(GETPOST('lineid'), $user);
767 767
 
768 768
 		if ($result >= 0)
769 769
 		{
@@ -787,13 +787,13 @@  discard block
 block discarded – undo
787 787
 			{
788 788
 				$outputlangs = $langs;
789 789
 				$newlang = '';
790
-				if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
790
+				if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
791 791
 				if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
792
-				if (! empty($newlang)) {
792
+				if (!empty($newlang)) {
793 793
 					$outputlangs = new Translate("", $conf);
794 794
 					$outputlangs->setDefaultLang($newlang);
795 795
 				}
796
-				$model=$object->modelpdf;
796
+				$model = $object->modelpdf;
797 797
 				$ret = $object->fetch($id); // Reload to get new records
798 798
 
799 799
 				$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -836,7 +836,7 @@  discard block
 block discarded – undo
836 836
 
837 837
 	else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer)
838 838
 	{
839
-		$result=$object->delete($user);
839
+		$result = $object->delete($user);
840 840
 		if ($result >= 0)
841 841
 		{
842 842
 			header("Location: list.php?restore_lastsearch_values=1");
@@ -853,9 +853,9 @@  discard block
 block discarded – undo
853 853
 		if (GETPOST('newcid') > 0)
854 854
 		{
855 855
 			$contractline = new ContratLigne($db);
856
-			$result=$contractline->fetch(GETPOST('lineid'));
856
+			$result = $contractline->fetch(GETPOST('lineid'));
857 857
 			$contractline->fk_contrat = GETPOST('newcid');
858
-			$result=$contractline->update($user,1);
858
+			$result = $contractline->update($user, 1);
859 859
 			if ($result >= 0)
860 860
 			{
861 861
 				header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
@@ -877,10 +877,10 @@  discard block
 block discarded – undo
877 877
 
878 878
 		// Fill array 'array_options' with data from update form
879 879
 		$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
880
-		$ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none'));
880
+		$ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute', 'none'));
881 881
 		if ($ret < 0) $error++;
882 882
 
883
-		if (! $error) {
883
+		if (!$error) {
884 884
 			$result = $object->insertExtraFields('CONTRACT_MODIFY');
885 885
 			if ($result < 0)
886 886
 			{
@@ -893,14 +893,14 @@  discard block
 block discarded – undo
893 893
 			$action = 'edit_extras';
894 894
 		}
895 895
 	}
896
-	elseif ($action=='setref_supplier')
896
+	elseif ($action == 'setref_supplier')
897 897
 	{
898
-		$cancelbutton = GETPOST('cancel','alpha');
898
+		$cancelbutton = GETPOST('cancel', 'alpha');
899 899
 		if (!$cancelbutton) {
900 900
 
901 901
 			$object->oldcopy = dol_clone($object);
902 902
 
903
-			$result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
903
+			$result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
904 904
 			if ($result < 0) {
905 905
 				setEventMessages($object->error, $object->errors, 'errors');
906 906
 				$action = 'editref_supplier';
@@ -910,19 +910,19 @@  discard block
 block discarded – undo
910 910
 			}
911 911
 		}
912 912
 		else {
913
-			header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
913
+			header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
914 914
 			exit;
915 915
 		}
916 916
 	}
917
-	elseif ($action=='setref_customer')
917
+	elseif ($action == 'setref_customer')
918 918
 	{
919
-		$cancelbutton = GETPOST('cancel','alpha');
919
+		$cancelbutton = GETPOST('cancel', 'alpha');
920 920
 
921 921
 		if (!$cancelbutton)
922 922
 		{
923 923
 			$object->oldcopy = dol_clone($object);
924 924
 
925
-			$result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
925
+			$result = $object->setValueFrom('ref_customer', GETPOST('ref_customer', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
926 926
 			if ($result < 0) {
927 927
 				setEventMessages($object->error, $object->errors, 'errors');
928 928
 				$action = 'editref_customer';
@@ -932,13 +932,13 @@  discard block
 block discarded – undo
932 932
 			}
933 933
 		}
934 934
 		else {
935
-			header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
935
+			header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
936 936
 			exit;
937 937
 		}
938 938
 	}
939
-	elseif ($action=='setref')
939
+	elseif ($action == 'setref')
940 940
 	{
941
-		$cancelbutton = GETPOST('cancel','alpha');
941
+		$cancelbutton = GETPOST('cancel', 'alpha');
942 942
 
943 943
 		if (!$cancelbutton) {
944 944
 			$result = $object->fetch($id);
@@ -948,14 +948,14 @@  discard block
 block discarded – undo
948 948
 
949 949
 			$old_ref = $object->ref;
950 950
 
951
-	        $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
951
+	        $result = $object->setValueFrom('ref', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
952 952
 	        if ($result < 0) {
953 953
 	            setEventMessages($object->error, $object->errors, 'errors');
954 954
 	            $action = 'editref';
955 955
 	        } else {
956 956
 				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
957
-				$old_filedir = $conf->contrat->dir_output . '/' . dol_sanitizeFileName($old_ref);
958
-				$new_filedir = $conf->contrat->dir_output . '/' . dol_sanitizeFileName($object->ref);
957
+				$old_filedir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($old_ref);
958
+				$new_filedir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($object->ref);
959 959
 
960 960
 				$files = dol_dir_list($old_filedir);
961 961
 				if (!empty($files))
@@ -967,36 +967,36 @@  discard block
 block discarded – undo
967 967
 					}
968 968
 				}
969 969
 
970
-	            header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
970
+	            header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
971 971
 	            exit;
972 972
 	        }
973 973
 	    }
974 974
 	    else {
975
-	        header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
975
+	        header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
976 976
 	        exit;
977 977
 	    }
978 978
 	}
979
-	elseif ($action=='setdate_contrat')
979
+	elseif ($action == 'setdate_contrat')
980 980
 	{
981
-		$cancelbutton = GETPOST('cancel','alpha');
981
+		$cancelbutton = GETPOST('cancel', 'alpha');
982 982
 
983 983
 		if (!$cancelbutton) {
984 984
 			$result = $object->fetch($id);
985 985
 			if ($result < 0) {
986 986
 				setEventMessages($object->error, $object->errors, 'errors');
987 987
 			}
988
-			$datacontrat=dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear'));
988
+			$datacontrat = dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear'));
989 989
 			$result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY');
990 990
 			if ($result < 0) {
991 991
 				setEventMessages($object->error, $object->errors, 'errors');
992 992
 				$action = 'editdate_contrat';
993 993
 			} else {
994
-				header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
994
+				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
995 995
 				exit;
996 996
 			}
997 997
 		}
998 998
 		else {
999
-			header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
999
+			header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
1000 1000
 			exit;
1001 1001
 		}
1002 1002
 	}
@@ -1008,14 +1008,14 @@  discard block
 block discarded – undo
1008 1008
 	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
1009 1009
 
1010 1010
 	// Actions to send emails
1011
-	$trigger_name='CONTRACT_SENTBYMAIL';
1012
-	$paramname='id';
1013
-	$mode='emailfromcontract';
1014
-	$trackid='con'.$object->id;
1011
+	$trigger_name = 'CONTRACT_SENTBYMAIL';
1012
+	$paramname = 'id';
1013
+	$mode = 'emailfromcontract';
1014
+	$trackid = 'con'.$object->id;
1015 1015
 	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
1016 1016
 
1017 1017
 
1018
-	if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer)
1018
+	if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer)
1019 1019
 	{
1020 1020
 		if ($action == 'addcontact')
1021 1021
 		{
@@ -1044,7 +1044,7 @@  discard block
 block discarded – undo
1044 1044
 		// bascule du statut d'un contact
1045 1045
 		else if ($action == 'swapstatut')
1046 1046
 		{
1047
-			$result=$object->swapContactStatus(GETPOST('ligne'));
1047
+			$result = $object->swapContactStatus(GETPOST('ligne'));
1048 1048
 		}
1049 1049
 
1050 1050
 		// Efface un contact
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
 	// Action clone object
1067 1067
 	if ($action == 'confirm_clone' && $confirm == 'yes')
1068 1068
 	{
1069
-		if (! GETPOST('socid', 3))
1069
+		if (!GETPOST('socid', 3))
1070 1070
 		{
1071 1071
 			setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
1072 1072
 		}
@@ -1075,7 +1075,7 @@  discard block
 block discarded – undo
1075 1075
 			if ($object->id > 0) {
1076 1076
 				$result = $object->createFromClone($socid);
1077 1077
 				if ($result > 0) {
1078
-					header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result);
1078
+					header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
1079 1079
 					exit();
1080 1080
 				} else {
1081 1081
 					if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors');
@@ -1091,21 +1091,21 @@  discard block
 block discarded – undo
1091 1091
  * View
1092 1092
  */
1093 1093
 
1094
-llxHeader('',$langs->trans("Contract"),"");
1094
+llxHeader('', $langs->trans("Contract"), "");
1095 1095
 
1096 1096
 $form = new Form($db);
1097 1097
 $formfile = new FormFile($db);
1098
-if (! empty($conf->projet->enabled)) $formproject = new FormProjets($db);
1098
+if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db);
1099 1099
 
1100
-$objectlignestatic=new ContratLigne($db);
1100
+$objectlignestatic = new ContratLigne($db);
1101 1101
 
1102 1102
 // Load object modContract
1103
-$module=(! empty($conf->global->CONTRACT_ADDON)?$conf->global->CONTRACT_ADDON:'mod_contract_serpis');
1103
+$module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
1104 1104
 if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php')
1105 1105
 {
1106
-	$module = substr($module, 0, dol_strlen($module)-4);
1106
+	$module = substr($module, 0, dol_strlen($module) - 4);
1107 1107
 }
1108
-$result=dol_include_once('/core/modules/contract/'.$module.'.php');
1108
+$result = dol_include_once('/core/modules/contract/'.$module.'.php');
1109 1109
 if ($result > 0)
1110 1110
 {
1111 1111
 	$modCodeContract = new $module();
@@ -1114,16 +1114,16 @@  discard block
 block discarded – undo
1114 1114
 // Create
1115 1115
 if ($action == 'create')
1116 1116
 {
1117
-	print load_fiche_titre($langs->trans('AddContract'),'','title_commercial.png');
1117
+	print load_fiche_titre($langs->trans('AddContract'), '', 'title_commercial.png');
1118 1118
 
1119 1119
 	$soc = new Societe($db);
1120
-	if ($socid>0) $soc->fetch($socid);
1120
+	if ($socid > 0) $soc->fetch($socid);
1121 1121
 
1122 1122
 	if (GETPOST('origin') && GETPOST('originid'))
1123 1123
 	{
1124 1124
 		// Parse element/subelement (ex: project_task)
1125 1125
 		$element = $subelement = GETPOST('origin');
1126
-		if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs))
1126
+		if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs))
1127 1127
 		{
1128 1128
 			$element = $regs[1];
1129 1129
 			$subelement = $regs[2];
@@ -1131,39 +1131,39 @@  discard block
 block discarded – undo
1131 1131
 
1132 1132
 		if ($element == 'project')
1133 1133
 		{
1134
-			$projectid=GETPOST('originid');
1134
+			$projectid = GETPOST('originid');
1135 1135
 		}
1136 1136
 		else
1137 1137
 		{
1138 1138
 			// For compatibility
1139
-			if ($element == 'order' || $element == 'commande')    { $element = $subelement = 'commande'; }
1140
-			if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
1139
+			if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; }
1140
+			if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; }
1141 1141
 
1142 1142
 			dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1143 1143
 
1144 1144
 			$classname = ucfirst($subelement);
1145 1145
 			$objectsrc = new $classname($db);
1146 1146
 			$objectsrc->fetch(GETPOST('originid'));
1147
-			if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines'))  $objectsrc->fetch_lines();
1147
+			if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines'))  $objectsrc->fetch_lines();
1148 1148
 			$objectsrc->fetch_thirdparty();
1149 1149
 
1150 1150
 			// Replicate extrafields
1151 1151
 			$objectsrc->fetch_optionals($originid);
1152 1152
 			$object->array_options = $objectsrc->array_options;
1153 1153
 
1154
-			$projectid          = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:'');
1154
+			$projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
1155 1155
 
1156 1156
 			$soc = $objectsrc->thirdparty;
1157 1157
 
1158
-			$note_private		= (! empty($objectsrc->note_private) ? $objectsrc->note_private : '');
1159
-			$note_public		= (! empty($objectsrc->note_public) ? $objectsrc->note_public : '');
1158
+			$note_private = (!empty($objectsrc->note_private) ? $objectsrc->note_private : '');
1159
+			$note_public = (!empty($objectsrc->note_public) ? $objectsrc->note_public : '');
1160 1160
 
1161 1161
 			// Object source contacts list
1162
-			$srccontactslist = $objectsrc->liste_contact(-1,'external',1);
1162
+			$srccontactslist = $objectsrc->liste_contact(-1, 'external', 1);
1163 1163
 		}
1164 1164
 	}
1165 1165
 	else {
1166
-		$projectid = GETPOST('projectid','int');
1166
+		$projectid = GETPOST('projectid', 'int');
1167 1167
 		$note_private = GETPOST("note_private");
1168 1168
 		$note_public = GETPOST("note_public");
1169 1169
 	}
@@ -1183,26 +1183,26 @@  discard block
 block discarded – undo
1183 1183
 
1184 1184
 	// Ref
1185 1185
 	print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td>';
1186
-	if (! empty($modCodeContract->code_auto)) {
1187
-		$tmpcode=$langs->trans("Draft");
1186
+	if (!empty($modCodeContract->code_auto)) {
1187
+		$tmpcode = $langs->trans("Draft");
1188 1188
 	} else {
1189
-		$tmpcode='<input name="ref" class="maxwidth100" maxlength="128" value="'.dol_escape_htmltag(GETPOST('ref')?GETPOST('ref'):$tmpcode).'">';
1189
+		$tmpcode = '<input name="ref" class="maxwidth100" maxlength="128" value="'.dol_escape_htmltag(GETPOST('ref') ?GETPOST('ref') : $tmpcode).'">';
1190 1190
 	}
1191 1191
 	print $tmpcode;
1192 1192
 	print '</td></tr>';
1193 1193
 
1194 1194
 	// Ref customer
1195 1195
 	print '<tr><td>'.$langs->trans('RefCustomer').'</td>';
1196
-	print '<td><input type="text" class="maxwidth150" name="ref_customer" id="ref_customer" value="'.dol_escape_htmltag(GETPOST('ref_customer','alpha')).'"></td></tr>';
1196
+	print '<td><input type="text" class="maxwidth150" name="ref_customer" id="ref_customer" value="'.dol_escape_htmltag(GETPOST('ref_customer', 'alpha')).'"></td></tr>';
1197 1197
 
1198 1198
 	// Ref supplier
1199 1199
 	print '<tr><td>'.$langs->trans('RefSupplier').'</td>';
1200
-	print '<td><input type="text" class="maxwidth150" name="ref_supplier" id="ref_supplier" value="'.dol_escape_htmltag(GETPOST('ref_supplier','alpha')).'"></td></tr>';
1200
+	print '<td><input type="text" class="maxwidth150" name="ref_supplier" id="ref_supplier" value="'.dol_escape_htmltag(GETPOST('ref_supplier', 'alpha')).'"></td></tr>';
1201 1201
 
1202 1202
 	// Thirdparty
1203 1203
 	print '<tr>';
1204 1204
 	print '<td class="fieldrequired">'.$langs->trans('ThirdParty').'</td>';
1205
-	if ($socid>0)
1205
+	if ($socid > 0)
1206 1206
 	{
1207 1207
 		print '<td>';
1208 1208
 		print $soc->getNomUrl(1);
@@ -1218,15 +1218,15 @@  discard block
 block discarded – undo
1218 1218
 	}
1219 1219
 	print '</tr>'."\n";
1220 1220
 
1221
-	if($socid>0)
1221
+	if ($socid > 0)
1222 1222
 	{
1223 1223
 		// Ligne info remises tiers
1224 1224
 		print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
1225
-		if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent);
1225
+		if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent);
1226 1226
 		else print $langs->trans("CompanyHasNoRelativeDiscount");
1227 1227
 		print '. ';
1228
-		$absolute_discount=$soc->getAvailableDiscounts();
1229
-		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1228
+		$absolute_discount = $soc->getAvailableDiscounts();
1229
+		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency));
1230 1230
 		else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1231 1231
 		print '.';
1232 1232
 		print '</td></tr>';
@@ -1234,12 +1234,12 @@  discard block
 block discarded – undo
1234 1234
 
1235 1235
 	// Commercial suivi
1236 1236
 	print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").'</span></td><td>';
1237
-	print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,'');
1237
+	print $form->select_dolusers(GETPOST("commercial_suivi_id") ?GETPOST("commercial_suivi_id") : $user->id, 'commercial_suivi_id', 1, '');
1238 1238
 	print '</td></tr>';
1239 1239
 
1240 1240
 	// Commercial signature
1241 1241
 	print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").'</span></td><td>';
1242
-	print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,'');
1242
+	print $form->select_dolusers(GETPOST("commercial_signature_id") ?GETPOST("commercial_signature_id") : $user->id, 'commercial_signature_id', 1, '');
1243 1243
 	print '</td></tr>';
1244 1244
 
1245 1245
 	print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td>';
@@ -1247,34 +1247,34 @@  discard block
 block discarded – undo
1247 1247
 	print "</td></tr>";
1248 1248
 
1249 1249
 	// Project
1250
-	if (! empty($conf->projet->enabled))
1250
+	if (!empty($conf->projet->enabled))
1251 1251
 	{
1252 1252
 		$langs->load('projects');
1253 1253
 
1254
-		$formproject=new FormProjets($db);
1254
+		$formproject = new FormProjets($db);
1255 1255
 
1256 1256
 		print '<tr><td>'.$langs->trans("Project").'</td><td>';
1257
-		$formproject->select_projects(($soc->id>0?$soc->id:-1),$projectid,"projectid",0,0,1,1);
1258
-		print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid=' . $soc->id . '&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id).'">' . $langs->trans("AddProject") . '</a>';
1257
+		$formproject->select_projects(($soc->id > 0 ? $soc->id : -1), $projectid, "projectid", 0, 0, 1, 1);
1258
+		print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id).'">'.$langs->trans("AddProject").'</a>';
1259 1259
 		print "</td></tr>";
1260 1260
 	}
1261 1261
 
1262 1262
 	print '<tr><td>'.$langs->trans("NotePublic").'</td><td class="tdtop">';
1263
-	$doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1263
+	$doleditor = new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1264 1264
 	print $doleditor->Create(1);
1265 1265
 	print '</td></tr>';
1266 1266
 
1267 1267
 	if (empty($user->societe_id))
1268 1268
 	{
1269 1269
 		print '<tr><td>'.$langs->trans("NotePrivate").'</td><td class="tdtop">';
1270
-		$doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1270
+		$doleditor = new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1271 1271
 		print $doleditor->Create(1);
1272 1272
 		print '</td></tr>';
1273 1273
 	}
1274 1274
 
1275 1275
 	// Other attributes
1276
-	$parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"', 'cols'=>3);
1277
-	$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
1276
+	$parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"', 'cols'=>3);
1277
+	$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1278 1278
 	print $hookmanager->resPrint;
1279 1279
 
1280 1280
 	// Other attributes
@@ -1289,7 +1289,7 @@  discard block
 block discarded – undo
1289 1289
 	print '<div class="center">';
1290 1290
 	print '<input type="submit" class="button" value="'.$langs->trans("Create").'">';
1291 1291
 	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1292
-	print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
1292
+	print '<input type="button" class="button" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
1293 1293
 	print '</div>';
1294 1294
 
1295 1295
 	if (is_object($objectsrc))
@@ -1312,18 +1312,18 @@  discard block
 block discarded – undo
1312 1312
 /*                                                                             */
1313 1313
 /* *************************************************************************** */
1314 1314
 {
1315
-	$now=dol_now();
1315
+	$now = dol_now();
1316 1316
 
1317 1317
 	if ($object->id > 0)
1318 1318
 	{
1319 1319
 		$object->fetch_thirdparty();
1320 1320
 
1321
-		$result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed
1321
+		$result = $object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed
1322 1322
 		if ($result < 0) {
1323
-            dol_print_error($db,$object->error);
1323
+            dol_print_error($db, $object->error);
1324 1324
         }
1325 1325
 
1326
-		$nbofservices=count($object->lines);
1326
+		$nbofservices = count($object->lines);
1327 1327
 
1328 1328
 		$author = new User($db);
1329 1329
 		$author->fetch($object->user_author_id);
@@ -1344,7 +1344,7 @@  discard block
 block discarded – undo
1344 1344
 
1345 1345
         if ($action == 'delete') {
1346 1346
             //Confirmation de la suppression du contrat
1347
-            $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("DeleteAContract"),$langs->trans("ConfirmDeleteAContract"),"confirm_delete",'',0,1);
1347
+            $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("DeleteAContract"), $langs->trans("ConfirmDeleteAContract"), "confirm_delete", '', 0, 1);
1348 1348
         } elseif ($action == 'valid') {
1349 1349
             //Confirmation de la validation
1350 1350
             $ref = substr($object->ref, 1, 4);
@@ -1353,17 +1353,17 @@  discard block
 block discarded – undo
1353 1353
             } else {
1354 1354
                 $numref = $object->ref;
1355 1355
             }
1356
-            $text = $langs->trans('ConfirmValidateContract',$numref);
1357
-            $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ValidateAContract"),$text,"confirm_valid",'',0,1);
1356
+            $text = $langs->trans('ConfirmValidateContract', $numref);
1357
+            $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ValidateAContract"), $text, "confirm_valid", '', 0, 1);
1358 1358
         } elseif ($action == 'close') {
1359 1359
             // Confirmation de la fermeture
1360
-            $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("CloseAContract"),$langs->trans("ConfirmCloseContract"),"confirm_close",'',0,1);
1360
+            $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("CloseAContract"), $langs->trans("ConfirmCloseContract"), "confirm_close", '', 0, 1);
1361 1361
         } elseif ($action == 'activate') {
1362
-            $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ActivateAllOnContract"),$langs->trans("ConfirmActivateAllOnContract"),"confirm_activate",'',0,1);
1362
+            $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ActivateAllOnContract"), $langs->trans("ConfirmActivateAllOnContract"), "confirm_activate", '', 0, 1);
1363 1363
         } elseif ($action == 'clone') {
1364 1364
             // Clone confirmation
1365
-            $formquestion = array(array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)')));
1366
-            $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloneContract'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
1365
+            $formquestion = array(array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)')));
1366
+            $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('CloneContract'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
1367 1367
         }
1368 1368
 
1369 1369
 
@@ -1386,7 +1386,7 @@  discard block
 block discarded – undo
1386 1386
         /*
1387 1387
          *   Contrat
1388 1388
          */
1389
-		if (! empty($object->brouillon) && $user->rights->contrat->creer)
1389
+		if (!empty($object->brouillon) && $user->rights->contrat->creer)
1390 1390
 		{
1391 1391
 			print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="POST">';
1392 1392
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
@@ -1395,61 +1395,61 @@  discard block
 block discarded – undo
1395 1395
 
1396 1396
 		// Contract card
1397 1397
 
1398
-		$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
1398
+		$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
1399 1399
 
1400 1400
 
1401
-		$morehtmlref='';
1402
-		if (! empty($modCodeContract->code_auto)) {
1403
-			$morehtmlref.=$object->ref;
1401
+		$morehtmlref = '';
1402
+		if (!empty($modCodeContract->code_auto)) {
1403
+			$morehtmlref .= $object->ref;
1404 1404
 		} else {
1405
-			$morehtmlref.=$form->editfieldkey("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,3);
1406
-			$morehtmlref.=$form->editfieldval("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,2);
1405
+			$morehtmlref .= $form->editfieldkey("", 'ref', $object->ref, $object, $user->rights->contrat->creer, 'string', '', 0, 3);
1406
+			$morehtmlref .= $form->editfieldval("", 'ref', $object->ref, $object, $user->rights->contrat->creer, 'string', '', 0, 2);
1407 1407
 		}
1408 1408
 
1409
-		$morehtmlref.='<div class="refidno">';
1409
+		$morehtmlref .= '<div class="refidno">';
1410 1410
 		// Ref customer
1411
-		$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1412
-		$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1);
1411
+		$morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1412
+		$morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1);
1413 1413
 		// Ref supplier
1414
-		$morehtmlref.='<br>';
1415
-		$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1416
-		$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1);
1414
+		$morehtmlref .= '<br>';
1415
+		$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1416
+		$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1);
1417 1417
 		// Thirdparty
1418
-		$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
1419
-		if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
1418
+		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
1419
+		if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
1420 1420
 		// Project
1421
-		if (! empty($conf->projet->enabled))
1421
+		if (!empty($conf->projet->enabled))
1422 1422
 		{
1423 1423
 			$langs->load("projects");
1424
-			$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
1424
+			$morehtmlref .= '<br>'.$langs->trans('Project').' ';
1425 1425
 			if ($user->rights->contrat->creer)
1426 1426
 			{
1427 1427
 				if ($action != 'classify')
1428
-					$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
1428
+					$morehtmlref .= '<a href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
1429 1429
 					if ($action == 'classify') {
1430 1430
 						//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
1431
-						$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
1432
-						$morehtmlref.='<input type="hidden" name="action" value="classin">';
1433
-						$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1434
-						$morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
1435
-						$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
1436
-						$morehtmlref.='</form>';
1431
+						$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
1432
+						$morehtmlref .= '<input type="hidden" name="action" value="classin">';
1433
+						$morehtmlref .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1434
+						$morehtmlref .= $formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
1435
+						$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
1436
+						$morehtmlref .= '</form>';
1437 1437
 					} else {
1438
-						$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
1438
+						$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
1439 1439
 					}
1440 1440
 			} else {
1441
-				if (! empty($object->fk_project)) {
1441
+				if (!empty($object->fk_project)) {
1442 1442
 					$proj = new Project($db);
1443 1443
 					$proj->fetch($object->fk_project);
1444
-					$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
1445
-					$morehtmlref.=$proj->ref;
1446
-					$morehtmlref.='</a>';
1444
+					$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
1445
+					$morehtmlref .= $proj->ref;
1446
+					$morehtmlref .= '</a>';
1447 1447
 				} else {
1448
-					$morehtmlref.='';
1448
+					$morehtmlref .= '';
1449 1449
 				}
1450 1450
 			}
1451 1451
 		}
1452
-		$morehtmlref.='</div>';
1452
+		$morehtmlref .= '</div>';
1453 1453
 
1454 1454
 
1455 1455
 		dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
@@ -1463,11 +1463,11 @@  discard block
 block discarded – undo
1463 1463
 
1464 1464
 		// Ligne info remises tiers
1465 1465
 		print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">';
1466
-		if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent);
1466
+		if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent);
1467 1467
 		else print $langs->trans("CompanyHasNoRelativeDiscount");
1468
-		$absolute_discount=$object->thirdparty->getAvailableDiscounts();
1468
+		$absolute_discount = $object->thirdparty->getAvailableDiscounts();
1469 1469
 		print '. ';
1470
-		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1470
+		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency));
1471 1471
 		else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1472 1472
 		print '.';
1473 1473
 		print '</td></tr>';
@@ -1475,35 +1475,35 @@  discard block
 block discarded – undo
1475 1475
 		// Date
1476 1476
 		print '<tr>';
1477 1477
 		print '<td class="titlefield">';
1478
-		print $form->editfieldkey("Date",'date_contrat',$object->date_contrat,$object,$user->rights->contrat->creer);
1478
+		print $form->editfieldkey("Date", 'date_contrat', $object->date_contrat, $object, $user->rights->contrat->creer);
1479 1479
 		print '</td><td>';
1480
-		print $form->editfieldval("Date",'date_contrat',$object->date_contrat,$object,$user->rights->contrat->creer,'datehourpicker');
1480
+		print $form->editfieldval("Date", 'date_contrat', $object->date_contrat, $object, $user->rights->contrat->creer, 'datehourpicker');
1481 1481
 		print '</td>';
1482 1482
 		print '</tr>';
1483 1483
 
1484 1484
 		// Other attributes
1485 1485
 		$cols = 3;
1486
-		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
1486
+		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
1487 1487
 
1488 1488
 		print "</table>";
1489 1489
 
1490 1490
 		print '</div>';
1491 1491
 
1492
-		if (! empty($object->brouillon) && $user->rights->contrat->creer)
1492
+		if (!empty($object->brouillon) && $user->rights->contrat->creer)
1493 1493
 		{
1494 1494
 			print '</form>';
1495 1495
 		}
1496 1496
 
1497 1497
 		echo '<br>';
1498 1498
 
1499
-		if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
1499
+		if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
1500 1500
 		{
1501 1501
 			$blocname = 'contacts';
1502 1502
 			$title = $langs->trans('ContactsAddresses');
1503 1503
 			include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1504 1504
 		}
1505 1505
 
1506
-		if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
1506
+		if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB))
1507 1507
 		{
1508 1508
 			$blocname = 'notes';
1509 1509
 			$title = $langs->trans('Notes');
@@ -1513,54 +1513,54 @@  discard block
 block discarded – undo
1513 1513
 
1514 1514
 		$colorb = '666666';
1515 1515
 
1516
-		$arrayothercontracts=$object->getListOfContracts('others');
1516
+		$arrayothercontracts = $object->getListOfContracts('others');
1517 1517
 
1518 1518
 		/*
1519 1519
          * Lines of contracts
1520 1520
          */
1521 1521
 
1522
-		$productstatic=new Product($db);
1522
+		$productstatic = new Product($db);
1523 1523
 
1524
-		$usemargins=0;
1525
-		if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1;
1524
+		$usemargins = 0;
1525
+		if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'propal', 'commande'))) $usemargins = 1;
1526 1526
 
1527
-		$var=false;
1527
+		$var = false;
1528 1528
 
1529 1529
 		// Title line for service
1530
-		$cursorline=1;
1530
+		$cursorline = 1;
1531 1531
 		print '<div id="contrat-lines-container" data-contractid="'.$object->id.'"  data-element="'.$object->element.'" >';
1532 1532
 		while ($cursorline <= $nbofservices)
1533 1533
 		{
1534
-			print '<div id="contrat-line-container'.$object->lines[$cursorline-1]->id.'" data-contratlineid = "'.$object->lines[$cursorline-1]->id.'" data-element="'.$object->lines[$cursorline-1]->element.'" >';
1534
+			print '<div id="contrat-line-container'.$object->lines[$cursorline - 1]->id.'" data-contratlineid = "'.$object->lines[$cursorline - 1]->id.'" data-element="'.$object->lines[$cursorline - 1]->element.'" >';
1535 1535
 			print '<form name="update" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="post">';
1536 1536
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1537 1537
 			print '<input type="hidden" name="action" value="updateline">';
1538
-			print '<input type="hidden" name="elrowid" value="'.$object->lines[$cursorline-1]->id.'">';
1539
-			print '<input type="hidden" name="idprod" value="'.(!empty($object->lines[$cursorline-1]->fk_product) ? $object->lines[$cursorline-1]->fk_product : 0).'">';
1540
-			print '<input type="hidden" name="fournprice" value="'.(!empty($object->lines[$cursorline-1]->fk_fournprice) ? $object->lines[$cursorline-1]->fk_fournprice : 0).'">';
1538
+			print '<input type="hidden" name="elrowid" value="'.$object->lines[$cursorline - 1]->id.'">';
1539
+			print '<input type="hidden" name="idprod" value="'.(!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0).'">';
1540
+			print '<input type="hidden" name="fournprice" value="'.(!empty($object->lines[$cursorline - 1]->fk_fournprice) ? $object->lines[$cursorline - 1]->fk_fournprice : 0).'">';
1541 1541
 
1542 1542
 			// Area with common detail of line
1543 1543
 			print '<div class="div-table-responsive-no-min">';
1544 1544
 			print '<table class="notopnoleftnoright allwidth tableforservicepart1" width="100%">';
1545 1545
 
1546 1546
 			$sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,";
1547
-			$sql.= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,";
1548
-			$sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,";
1549
-			$sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,";
1550
-			$sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,";
1551
-			$sql.= " cd.fk_unit,";
1552
-			$sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity";
1553
-			$sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
1554
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
1555
-			$sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id;
1547
+			$sql .= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,";
1548
+			$sql .= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,";
1549
+			$sql .= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,";
1550
+			$sql .= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,";
1551
+			$sql .= " cd.fk_unit,";
1552
+			$sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity";
1553
+			$sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
1554
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
1555
+			$sql .= " WHERE cd.rowid = ".$object->lines[$cursorline - 1]->id;
1556 1556
 
1557 1557
 			$result = $db->query($sql);
1558 1558
 			if ($result)
1559 1559
 			{
1560 1560
 				$total = 0;
1561 1561
 
1562
-				print '<tr class="liste_titre'.($cursorline?' liste_titre_add':'').'">';
1563
-				print '<td>'.$langs->trans("ServiceNb",$cursorline).'</td>';
1562
+				print '<tr class="liste_titre'.($cursorline ? ' liste_titre_add' : '').'">';
1563
+				print '<td>'.$langs->trans("ServiceNb", $cursorline).'</td>';
1564 1564
 				print '<td width="80" align="center">'.$langs->trans("VAT").'</td>';
1565 1565
 				print '<td width="80" align="right">'.$langs->trans("PriceUHT").'</td>';
1566 1566
 				if (!empty($conf->multicurrency->enabled)) {
@@ -1569,7 +1569,7 @@  discard block
 block discarded – undo
1569 1569
 				print '<td width="30" align="center">'.$langs->trans("Qty").'</td>';
1570 1570
 				if ($conf->global->PRODUCT_USE_UNITS) print '<td width="30" align="left">'.$langs->trans("Unit").'</td>';
1571 1571
 				print '<td width="50" align="right">'.$langs->trans("ReductionShort").'</td>';
1572
-				if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td width="50" align="right">'.$langs->trans("BuyingPrice").'</td>';
1572
+				if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td width="50" align="right">'.$langs->trans("BuyingPrice").'</td>';
1573 1573
 				print '<td width="30">&nbsp;</td>';
1574 1574
 				print "</tr>\n";
1575 1575
 
@@ -1584,12 +1584,12 @@  discard block
 block discarded – undo
1584 1584
 					if ($objp->fk_product > 0)
1585 1585
 					{
1586 1586
 						print '<td>';
1587
-						$productstatic->id=$objp->fk_product;
1588
-						$productstatic->type=$objp->ptype;
1589
-						$productstatic->ref=$objp->pref;
1590
-						$productstatic->entity=$objp->pentity;
1591
-						$productstatic->label=$objp->plabel;
1592
-						$text = $productstatic->getNomUrl(1,'',32);
1587
+						$productstatic->id = $objp->fk_product;
1588
+						$productstatic->type = $objp->ptype;
1589
+						$productstatic->ref = $objp->pref;
1590
+						$productstatic->entity = $objp->pentity;
1591
+						$productstatic->label = $objp->plabel;
1592
+						$text = $productstatic->getNomUrl(1, '', 32);
1593 1593
 						if ($objp->plabel)
1594 1594
 						{
1595 1595
 							$text .= ' - ';
@@ -1598,13 +1598,13 @@  discard block
 block discarded – undo
1598 1598
 						$description = $objp->description;
1599 1599
 
1600 1600
 						// Add description in form
1601
-						if (! empty($conf->global->PRODUIT_DESC_IN_FORM))
1601
+						if (!empty($conf->global->PRODUIT_DESC_IN_FORM))
1602 1602
 						{
1603
-							$text .= (! empty($objp->description) && $objp->description!=$objp->plabel)?'<br>'.dol_htmlentitiesbr($objp->description):'';
1604
-							$description = '';	// Already added into main visible desc
1603
+							$text .= (!empty($objp->description) && $objp->description != $objp->plabel) ? '<br>'.dol_htmlentitiesbr($objp->description) : '';
1604
+							$description = ''; // Already added into main visible desc
1605 1605
 						}
1606 1606
 
1607
-						echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):''));
1607
+						echo $form->textwithtooltip($text, $description, 3, '', '', $cursorline, 0, (!empty($line->fk_parent_line) ?img_picto('', 'rightarrow') : ''));
1608 1608
 
1609 1609
 						print '</td>';
1610 1610
 					}
@@ -1614,7 +1614,7 @@  discard block
 block discarded – undo
1614 1614
 					}
1615 1615
 					// TVA
1616 1616
 					print '<td align="center">';
1617
-					print vatrate($objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), '%', $objp->info_bits);
1617
+					print vatrate($objp->tva_tx.($objp->vat_src_code ? (' ('.$objp->vat_src_code.')') : ''), '%', $objp->info_bits);
1618 1618
 					print '</td>';
1619 1619
 					// Price
1620 1620
 					print '<td align="right">'.($objp->subprice != '' ? price($objp->subprice) : '')."</td>\n";
@@ -1625,7 +1625,7 @@  discard block
 block discarded – undo
1625 1625
 					// Quantite
1626 1626
 					print '<td align="center">'.$objp->qty.'</td>';
1627 1627
 					// Unit
1628
-					if($conf->global->PRODUCT_USE_UNITS) print '<td align="left">'.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).'</td>';
1628
+					if ($conf->global->PRODUCT_USE_UNITS) print '<td align="left">'.$langs->trans($object->lines[$cursorline - 1]->getLabelOfUnit()).'</td>';
1629 1629
 					// Remise
1630 1630
 					if ($objp->remise_percent > 0)
1631 1631
 					{
@@ -1637,7 +1637,7 @@  discard block
 block discarded – undo
1637 1637
 					}
1638 1638
 
1639 1639
 					// Margin
1640
-					if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td align="right" class="nowrap">'.price($objp->pa_ht).'</td>';
1640
+					if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td align="right" class="nowrap">'.price($objp->pa_ht).'</td>';
1641 1641
 
1642 1642
 					// Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme)
1643 1643
 					print '<td align="right" class="nowrap">';
@@ -1645,7 +1645,7 @@  discard block
 block discarded – undo
1645 1645
 					{
1646 1646
 						print '<!-- link to move service line into another contract -->';
1647 1647
 						print '<a class="reposition" style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=move&amp;rowid='.$objp->rowid.'">';
1648
-						print img_picto($langs->trans("MoveToAnotherContract"),'uparrow');
1648
+						print img_picto($langs->trans("MoveToAnotherContract"), 'uparrow');
1649 1649
 						print '</a>';
1650 1650
 					}
1651 1651
 					if ($user->rights->contrat->creer && ($object->statut >= 0))
@@ -1654,7 +1654,7 @@  discard block
 block discarded – undo
1654 1654
 						print img_edit();
1655 1655
 						print '</a>';
1656 1656
 					}
1657
-					if ( $user->rights->contrat->creer && ($object->statut >= 0))
1657
+					if ($user->rights->contrat->creer && ($object->statut >= 0))
1658 1658
 					{
1659 1659
 						print '<a style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=deleteline&amp;rowid='.$objp->rowid.'">';
1660 1660
 						print img_delete();
@@ -1685,7 +1685,7 @@  discard block
 block discarded – undo
1685 1685
 							print dol_print_date($db->jdate($objp->date_debut), 'day');
1686 1686
 							// Warning si date prevu passee et pas en service
1687 1687
 							if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) {
1688
-								$warning_delay=$conf->contrat->services->inactifs->warning_delay / 3600 / 24;
1688
+								$warning_delay = $conf->contrat->services->inactifs->warning_delay / 3600 / 24;
1689 1689
 								$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1690 1690
 								print " ".img_warning($textlate);
1691 1691
 							}
@@ -1697,7 +1697,7 @@  discard block
 block discarded – undo
1697 1697
 						{
1698 1698
 							print dol_print_date($db->jdate($objp->date_fin), 'day');
1699 1699
 							if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) {
1700
-								$warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24;
1700
+								$warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24;
1701 1701
 								$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1702 1702
 								print " ".img_warning($textlate);
1703 1703
 							}
@@ -1709,10 +1709,10 @@  discard block
 block discarded – undo
1709 1709
 					}
1710 1710
 
1711 1711
 					// Display lines extrafields
1712
-					if (is_array($extralabelslines) && count($extralabelslines)>0) {
1712
+					if (is_array($extralabelslines) && count($extralabelslines) > 0) {
1713 1713
 						$line = new ContratLigne($db);
1714 1714
 						$line->fetch_optionals($objp->rowid);
1715
-						print $line->showOptionals($extrafieldsline, 'view', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
1715
+						print $line->showOptionals($extrafieldsline, 'view', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1);
1716 1716
 					}
1717 1717
 				}
1718 1718
 				// Ligne en mode update
@@ -1723,30 +1723,30 @@  discard block
 block discarded – undo
1723 1723
 					print '<td>';
1724 1724
 					if ($objp->fk_product)
1725 1725
 					{
1726
-						$productstatic->id=$objp->fk_product;
1727
-						$productstatic->type=$objp->ptype;
1728
-						$productstatic->ref=$objp->pref;
1729
-						$productstatic->entity=$objp->pentity;
1730
-						print $productstatic->getNomUrl(1,'',32);
1731
-						print $objp->label?' - '.dol_trunc($objp->label,32):'';
1726
+						$productstatic->id = $objp->fk_product;
1727
+						$productstatic->type = $objp->ptype;
1728
+						$productstatic->ref = $objp->pref;
1729
+						$productstatic->entity = $objp->pentity;
1730
+						print $productstatic->getNomUrl(1, '', 32);
1731
+						print $objp->label ? ' - '.dol_trunc($objp->label, 32) : '';
1732 1732
 						print '<br>';
1733 1733
 					}
1734 1734
 					else
1735 1735
 					{
1736
-						print $objp->label?$objp->label.'<br>':'';
1736
+						print $objp->label ? $objp->label.'<br>' : '';
1737 1737
 					}
1738 1738
 
1739 1739
 					// editeur wysiwyg
1740 1740
 					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1741
-					$nbrows=ROWS_2;
1742
-					if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
1743
-					$enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0);
1744
-					$doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%');
1741
+					$nbrows = ROWS_2;
1742
+					if (!empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows = $conf->global->MAIN_INPUT_DESC_HEIGHT;
1743
+					$enable = (isset($conf->global->FCKEDITOR_ENABLE_DETAILS) ? $conf->global->FCKEDITOR_ENABLE_DETAILS : 0);
1744
+					$doleditor = new DolEditor('product_desc', $objp->description, '', 92, 'dolibarr_details', '', false, true, $enable, $nbrows, '90%');
1745 1745
 					$doleditor->Create();
1746 1746
 
1747 1747
 					print '</td>';
1748 1748
 					print '<td align="right">';
1749
-					print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1);
1749
+					print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code ? (' ('.$objp->vat_src_code.')') : ''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1);
1750 1750
 					print '</td>';
1751 1751
 					print '<td align="right"><input size="5" type="text" name="elprice" value="'.price($objp->subprice).'"></td>';
1752 1752
 					print '<td align="center"><input size="2" type="text" name="elqty" value="'.$objp->qty.'"></td>';
@@ -1757,11 +1757,11 @@  discard block
 block discarded – undo
1757 1757
 						print '</td>';
1758 1758
 					}
1759 1759
 					print '<td align="right" class="nowrap"><input size="1" type="text" name="elremise_percent" value="'.$objp->remise_percent.'">%</td>';
1760
-					if (! empty($usemargins))
1760
+					if (!empty($usemargins))
1761 1761
 					{
1762 1762
 						print '<td align="right">';
1763 1763
 						if ($objp->fk_product) print '<select id="fournprice" name="fournprice"></select>';
1764
-						print '<input id="buying_price" type="text" size="5" name="buying_price" value="'.price($objp->pa_ht,0,'',0).'"></td>';
1764
+						print '<input id="buying_price" type="text" size="5" name="buying_price" value="'.price($objp->pa_ht, 0, '', 0).'"></td>';
1765 1765
 					}
1766 1766
 					print '<td align="center">';
1767 1767
 					print '<input type="submit" class="button" name="save" value="'.$langs->trans("Modify").'">';
@@ -1769,24 +1769,24 @@  discard block
 block discarded – undo
1769 1769
 					print '</td>';
1770 1770
 					print '</tr>';
1771 1771
 
1772
-					$colspan=6;
1773
-					if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++;
1774
-					if($conf->global->PRODUCT_USE_UNITS) $colspan++;
1772
+					$colspan = 6;
1773
+					if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++;
1774
+					if ($conf->global->PRODUCT_USE_UNITS) $colspan++;
1775 1775
 
1776 1776
 					// Ligne dates prevues
1777 1777
 					print '<tr class="oddeven">';
1778 1778
 					print '<td colspan="'.$colspan.'">';
1779 1779
 					print $langs->trans("DateStartPlanned").' ';
1780
-					print $form->selectDate($db->jdate($objp->date_debut), "date_start_update", $usehm, $usehm, ($db->jdate($objp->date_debut)>0?0:1), "update");
1780
+					print $form->selectDate($db->jdate($objp->date_debut), "date_start_update", $usehm, $usehm, ($db->jdate($objp->date_debut) > 0 ? 0 : 1), "update");
1781 1781
 					print ' &nbsp;&nbsp;'.$langs->trans("DateEndPlanned").' ';
1782
-					print $form->selectDate($db->jdate($objp->date_fin), "date_end_update", $usehm, $usehm, ($db->jdate($objp->date_fin)>0?0:1), "update");
1782
+					print $form->selectDate($db->jdate($objp->date_fin), "date_end_update", $usehm, $usehm, ($db->jdate($objp->date_fin) > 0 ? 0 : 1), "update");
1783 1783
 					print '</td>';
1784 1784
 					print '</tr>';
1785 1785
 
1786
-					if (is_array($extralabelslines) && count($extralabelslines)>0) {
1786
+					if (is_array($extralabelslines) && count($extralabelslines) > 0) {
1787 1787
 						$line = new ContratLigne($db);
1788 1788
 						$line->fetch_optionals($objp->rowid);
1789
-						print $line->showOptionals($extrafieldsline, 'edit', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
1789
+						print $line->showOptionals($extrafieldsline, 'edit', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1);
1790 1790
 					}
1791 1791
 				}
1792 1792
 
@@ -1800,7 +1800,7 @@  discard block
 block discarded – undo
1800 1800
 			if ($object->statut > 0)
1801 1801
 			{
1802 1802
 				print '<tr class="oddeven">';
1803
-				print '<td class="tdhrthin" colspan="'.($conf->margin->enabled?7:6).'"><hr class="opacitymedium tdhrthin"></td>';
1803
+				print '<td class="tdhrthin" colspan="'.($conf->margin->enabled ? 7 : 6).'"><hr class="opacitymedium tdhrthin"></td>';
1804 1804
 				print "</tr>\n";
1805 1805
 			}
1806 1806
 
@@ -1813,52 +1813,52 @@  discard block
 block discarded – undo
1813 1813
 			/*
1814 1814
              * Confirmation to delete service line of contract
1815 1815
              */
1816
-			if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid'))
1816
+			if ($action == 'deleteline' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid'))
1817 1817
 			{
1818
-				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1);
1818
+				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'), $langs->trans("DeleteContractLine"), $langs->trans("ConfirmDeleteContractLine"), "confirm_deleteline", '', 0, 1);
1819 1819
 				if ($ret == 'html') print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1820 1820
 			}
1821 1821
 
1822 1822
 			/*
1823 1823
              * Confirmation to move service toward another contract
1824 1824
              */
1825
-			if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid'))
1825
+			if ($action == 'move' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid'))
1826 1826
 			{
1827
-				$arraycontractid=array();
1828
-				foreach($arrayothercontracts as $contractcursor)
1827
+				$arraycontractid = array();
1828
+				foreach ($arrayothercontracts as $contractcursor)
1829 1829
 				{
1830
-					$arraycontractid[$contractcursor->id]=$contractcursor->ref;
1830
+					$arraycontractid[$contractcursor->id] = $contractcursor->ref;
1831 1831
 				}
1832 1832
 				//var_dump($arraycontractid);
1833 1833
 				// Cree un tableau formulaire
1834
-				$formquestion=array(
1834
+				$formquestion = array(
1835 1835
 				'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"),
1836 1836
 				array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid));
1837 1837
 
1838
-				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion);
1838
+				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'), $langs->trans("MoveToAnotherContract"), $langs->trans("ConfirmMoveToAnotherContract"), "confirm_move", $formquestion);
1839 1839
 				print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1840 1840
 			}
1841 1841
 
1842 1842
 			/*
1843 1843
              * Confirmation de la validation activation
1844 1844
              */
1845
-			if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1845
+			if ($action == 'active' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne'))
1846 1846
 			{
1847 1847
 				$dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1848 1848
 				$dateactend   = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1849
-				$comment      = GETPOST('comment','alpha');
1850
-				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1);
1849
+				$comment      = GETPOST('comment', 'alpha');
1850
+				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("ActivateService"), $langs->trans("ConfirmActivateService", dol_print_date($dateactstart, "%A %d %B %Y")), "confirm_active", '', 0, 1);
1851 1851
 				print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1852 1852
 			}
1853 1853
 
1854 1854
 			/*
1855 1855
              * Confirmation de la validation fermeture
1856 1856
              */
1857
-			if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1857
+			if ($action == 'closeline' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne'))
1858 1858
 			{
1859 1859
 				$dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1860 1860
 				$dateactend   = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1861
-				$comment      = GETPOST('comment','alpha');
1861
+				$comment      = GETPOST('comment', 'alpha');
1862 1862
 
1863 1863
 				if (empty($dateactend))
1864 1864
 				{
@@ -1866,7 +1866,7 @@  discard block
 block discarded – undo
1866 1866
 				}
1867 1867
 				else
1868 1868
 				{
1869
-					print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1);
1869
+					print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne', 'int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService", dol_print_date($dateactend, "%A %d %B %Y")), "confirm_closeline", '', 0, 1);
1870 1870
 				}
1871 1871
 				print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1872 1872
 			}
@@ -1875,27 +1875,27 @@  discard block
 block discarded – undo
1875 1875
 			// Area with status and activation info of line
1876 1876
 			if ($object->statut > 0)
1877 1877
 			{
1878
-				print '<table class="notopnoleftnoright tableforservicepart2'.($cursorline < $nbofservices ?' boxtablenobottom':'').'" width="100%">';
1878
+				print '<table class="notopnoleftnoright tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').'" width="100%">';
1879 1879
 
1880 1880
 				print '<tr class="oddeven">';
1881
-				print '<td>'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).'</td>';
1881
+				print '<td>'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline - 1]->getLibStatut(4).'</td>';
1882 1882
 				print '<td width="30" align="right">';
1883 1883
 				if ($user->societe_id == 0)
1884 1884
 				{
1885 1885
 					if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline')
1886 1886
 					{
1887
-						$tmpaction='activateline';
1888
-						$tmpactionpicto='play';
1889
-						$tmpactiontext=$langs->trans("Activate");
1887
+						$tmpaction = 'activateline';
1888
+						$tmpactionpicto = 'play';
1889
+						$tmpactiontext = $langs->trans("Activate");
1890 1890
 						if ($objp->statut == 4)
1891 1891
 						{
1892
-							$tmpaction='unactivateline';
1893
-							$tmpactionpicto='playstop';
1894
-							$tmpactiontext=$langs->trans("Disable");
1892
+							$tmpaction = 'unactivateline';
1893
+							$tmpactionpicto = 'playstop';
1894
+							$tmpactiontext = $langs->trans("Disable");
1895 1895
 						}
1896
-						if (($tmpaction=='activateline' && $user->rights->contrat->activer) || ($tmpaction=='unactivateline' && $user->rights->contrat->desactiver))
1896
+						if (($tmpaction == 'activateline' && $user->rights->contrat->activer) || ($tmpaction == 'unactivateline' && $user->rights->contrat->desactiver))
1897 1897
 						{
1898
-							print '<a class="reposition" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&amp;ligne=' . $object->lines[$cursorline - 1]->id . '&amp;action=' . $tmpaction . '">';
1898
+							print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline - 1]->id.'&amp;action='.$tmpaction.'">';
1899 1899
 							print img_picto($tmpactiontext, $tmpactionpicto);
1900 1900
 							print '</a>';
1901 1901
 						}
@@ -1908,13 +1908,13 @@  discard block
 block discarded – undo
1908 1908
 
1909 1909
 				print '<td>';
1910 1910
 				// Si pas encore active
1911
-				if (! $objp->date_debut_reelle) {
1911
+				if (!$objp->date_debut_reelle) {
1912 1912
 					print $langs->trans("DateStartReal").': ';
1913 1913
 					if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle, 'day');
1914 1914
 					else print $langs->trans("ContractStatusNotRunning");
1915 1915
 				}
1916 1916
 				// Si active et en cours
1917
-				if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) {
1917
+				if ($objp->date_debut_reelle && !$objp->date_fin_reelle) {
1918 1918
 					print $langs->trans("DateStartReal").': ';
1919 1919
 					print dol_print_date($objp->date_debut_reelle, 'day');
1920 1920
 				}
@@ -1926,7 +1926,7 @@  discard block
 block discarded – undo
1926 1926
 					print $langs->trans("DateEndReal").': ';
1927 1927
 					print dol_print_date($objp->date_fin_reelle, 'day');
1928 1928
 				}
1929
-				if (! empty($objp->comment)) print " &nbsp;-&nbsp; ".$objp->comment;
1929
+				if (!empty($objp->comment)) print " &nbsp;-&nbsp; ".$objp->comment;
1930 1930
 				print '</td>';
1931 1931
 
1932 1932
 				print '<td align="center">&nbsp;</td>';
@@ -1936,25 +1936,25 @@  discard block
 block discarded – undo
1936 1936
 			}
1937 1937
 
1938 1938
 			// Form to activate line
1939
-			if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1939
+			if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne'))
1940 1940
 			{
1941 1941
 				print '<form name="active" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.GETPOST('ligne').'&amp;action=active" method="post">';
1942 1942
 				print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1943 1943
 
1944
-				print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ?' boxtablenobottom':'').'" width="100%">';
1944
+				print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').'" width="100%">';
1945 1945
 
1946 1946
 				// Definie date debut et fin par defaut
1947 1947
 				$dateactstart = $objp->date_debut;
1948 1948
 				if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1949
-				elseif (! $dateactstart) $dateactstart = time();
1949
+				elseif (!$dateactstart) $dateactstart = time();
1950 1950
 
1951 1951
 				$dateactend = $objp->date_fin;
1952 1952
 				if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1953
-				elseif (! $dateactend)
1953
+				elseif (!$dateactend)
1954 1954
 				{
1955 1955
 					if ($objp->fk_product > 0)
1956 1956
 					{
1957
-						$product=new Product($db);
1957
+						$product = new Product($db);
1958 1958
 						$product->fetch($objp->fk_product);
1959 1959
 						$dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
1960 1960
 					}
@@ -1973,7 +1973,7 @@  discard block
 block discarded – undo
1973 1973
 				print '</tr>';
1974 1974
 
1975 1975
 				print '<tr class="oddeven">';
1976
-				print '<td class="nohover">'.$langs->trans("Comment").'</td><td colspan="3" class="nohover" colspan="'.($conf->margin->enabled?4:3).'"><input size="80" type="text" name="comment" value="'.$_POST["comment"].'"></td>';
1976
+				print '<td class="nohover">'.$langs->trans("Comment").'</td><td colspan="3" class="nohover" colspan="'.($conf->margin->enabled ? 4 : 3).'"><input size="80" type="text" name="comment" value="'.$_POST["comment"].'"></td>';
1977 1977
 				print '<td class="nohover right">';
1978 1978
 				print '<input type="submit" class="button" name="activate" value="'.$langs->trans("Activate").'"> &nbsp; ';
1979 1979
 				print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
@@ -1985,37 +1985,37 @@  discard block
 block discarded – undo
1985 1985
 				print '</form>';
1986 1986
 			}
1987 1987
 
1988
-			if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1988
+			if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne'))
1989 1989
 			{
1990 1990
 				/**
1991 1991
 				 * Disable a contract line
1992 1992
 				 */
1993 1993
 				print '<!-- Form to disabled a line -->'."\n";
1994
-				print '<form name="closeline" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline-1]->id.'" method="post">';
1994
+				print '<form name="closeline" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline - 1]->id.'" method="post">';
1995 1995
 
1996 1996
 				print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1997 1997
 				print '<input type="hidden" name="action" value="closeline">';
1998 1998
 
1999
-				print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ?' boxtablenobottom':'').'" width="100%">';
1999
+				print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').'" width="100%">';
2000 2000
 
2001 2001
 				// Definie date debut et fin par defaut
2002 2002
 				$dateactstart = $objp->date_debut_reelle;
2003 2003
 				if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
2004
-				elseif (! $dateactstart) $dateactstart = time();
2004
+				elseif (!$dateactstart) $dateactstart = time();
2005 2005
 
2006 2006
 				$dateactend = $objp->date_fin_reelle;
2007 2007
 				if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
2008
-				elseif (! $dateactend)
2008
+				elseif (!$dateactend)
2009 2009
 				{
2010 2010
 					if ($objp->fk_product > 0)
2011 2011
 					{
2012
-						$product=new Product($db);
2012
+						$product = new Product($db);
2013 2013
 						$product->fetch($objp->fk_product);
2014 2014
 						$dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
2015 2015
 					}
2016 2016
 				}
2017
-				$now=dol_now();
2018
-				if ($dateactend > $now) $dateactend=$now;
2017
+				$now = dol_now();
2018
+				if ($dateactend > $now) $dateactend = $now;
2019 2019
 
2020 2020
 				print '<tr class="oddeven"><td colspan="2" class="nohover">';
2021 2021
 				if ($objp->statut >= 4)
@@ -2023,7 +2023,7 @@  discard block
 block discarded – undo
2023 2023
 					if ($objp->statut == 4)
2024 2024
 					{
2025 2025
 						print $langs->trans("DateEndReal").' ';
2026
-						print $form->selectDate($dateactend, "end", $usehm, $usehm, ($objp->date_fin_reelle>0?0:1), "closeline", 1, 1);
2026
+						print $form->selectDate($dateactend, "end", $usehm, $usehm, ($objp->date_fin_reelle > 0 ? 0 : 1), "closeline", 1, 1);
2027 2027
 					}
2028 2028
 				}
2029 2029
 				print '</td>';
@@ -2050,23 +2050,23 @@  discard block
 block discarded – undo
2050 2050
 		// Form to add new line
2051 2051
 		if ($user->rights->contrat->creer && ($object->statut == 0))
2052 2052
 		{
2053
-			$dateSelector=1;
2053
+			$dateSelector = 1;
2054 2054
 
2055 2055
 			print "\n";
2056
-			print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline')?'#add':'#line_'.GETPOST('lineid')).'" method="POST">
2056
+			print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#add' : '#line_'.GETPOST('lineid')).'" method="POST">
2057 2057
 			<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">
2058
-			<input type="hidden" name="action" value="'.(($action != 'editline')?'addline':'updateline').'">
2058
+			<input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">
2059 2059
 			<input type="hidden" name="mode" value="">
2060 2060
 			<input type="hidden" name="id" value="'.$object->id.'">
2061 2061
 			';
2062 2062
 
2063 2063
 			print '<div class="div-table-responsive-no-min">';
2064
-			print '<table id="tablelines" class="noborder noshadow" width="100%">';	// Array with (n*2)+1 lines
2064
+			print '<table id="tablelines" class="noborder noshadow" width="100%">'; // Array with (n*2)+1 lines
2065 2065
 
2066 2066
 			// Form to add new line
2067 2067
 	   		if ($action != 'editline')
2068 2068
 			{
2069
-				$forcetoshowtitlelines=1;
2069
+				$forcetoshowtitlelines = 1;
2070 2070
 
2071 2071
 				// Add free products/services
2072 2072
 				$object->formAddObjectLine(1, $mysoc, $soc);
@@ -2091,17 +2091,17 @@  discard block
 block discarded – undo
2091 2091
 		{
2092 2092
 			print '<div class="tabsAction">';
2093 2093
 
2094
-			$parameters=array();
2095
-			$reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
2094
+			$parameters = array();
2095
+			$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2096 2096
 
2097 2097
 			if (empty($reshook))
2098 2098
 			{
2099 2099
 				// Send
2100 2100
 				if ($object->statut == 1) {
2101 2101
 					if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) {
2102
-						print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a></div>';
2102
+						print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>';
2103 2103
 					} else
2104
-						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">' . $langs->trans('SendMail') . '</a></div>';
2104
+						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a></div>';
2105 2105
 				}
2106 2106
 
2107 2107
 				if ($object->statut == 0 && $nbofservices)
@@ -2115,14 +2115,14 @@  discard block
 block discarded – undo
2115 2115
 					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Modify").'</a></div>';
2116 2116
 				}
2117 2117
 
2118
-				if (! empty($conf->facture->enabled) && $object->statut > 0)
2118
+				if (!empty($conf->facture->enabled) && $object->statut > 0)
2119 2119
 				{
2120 2120
 					$langs->load("bills");
2121 2121
 					if ($user->rights->facture->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateBill").'</a></div>';
2122 2122
 					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateBill").'</a></div>';
2123 2123
 				}
2124 2124
 
2125
-				if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices)
2125
+				if (!empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices)
2126 2126
 				{
2127 2127
 					$langs->load("orders");
2128 2128
 					if ($user->rights->commande->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateOrder").'</a></div>';
@@ -2131,7 +2131,7 @@  discard block
 block discarded – undo
2131 2131
 
2132 2132
 				// Clone
2133 2133
 				if ($user->rights->contrat->creer) {
2134
-					print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&amp;socid=' . $object->socid . '&amp;action=clone&amp;object=' . $object->element . '">' . $langs->trans("ToClone") . '</a></div>';
2134
+					print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object='.$object->element.'">'.$langs->trans("ToClone").'</a></div>';
2135 2135
 				}
2136 2136
 
2137 2137
 				if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0)
@@ -2194,8 +2194,8 @@  discard block
 block discarded – undo
2194 2194
     		 * Documents generes
2195 2195
     		*/
2196 2196
 			$filename = dol_sanitizeFileName($object->ref);
2197
-			$filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref);
2198
-			$urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
2197
+			$filedir = $conf->contrat->dir_output."/".dol_sanitizeFileName($object->ref);
2198
+			$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
2199 2199
 			$genallowed = $user->rights->contrat->lire;
2200 2200
 			$delallowed = $user->rights->contrat->creer;
2201 2201
 
@@ -2211,7 +2211,7 @@  discard block
 block discarded – undo
2211 2211
 			print '</div><div class="fichehalfright"><div class="ficheaddleft">';
2212 2212
 
2213 2213
 			// List of actions on element
2214
-			include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
2214
+			include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
2215 2215
 			$formactions = new FormActions($db);
2216 2216
 			$somethingshown = $formactions->showactions($object, 'contract', $socid, 1);
2217 2217
 
@@ -2220,8 +2220,8 @@  discard block
 block discarded – undo
2220 2220
 		}
2221 2221
 
2222 2222
 		// Presend form
2223
-		$modelmail='contract';
2224
-		$defaulttopic='SendContractRef';
2223
+		$modelmail = 'contract';
2224
+		$defaulttopic = 'SendContractRef';
2225 2225
 		$diroutput = $conf->contrat->dir_output;
2226 2226
 		$trackid = 'con'.$object->id;
2227 2227
 
@@ -2236,7 +2236,7 @@  discard block
 block discarded – undo
2236 2236
 ?>
2237 2237
 
2238 2238
 <?php
2239
-if (! empty($conf->margin->enabled) && $action == 'editline')
2239
+if (!empty($conf->margin->enabled) && $action == 'editline')
2240 2240
 {
2241 2241
 ?>
2242 2242
 
Please login to merge, or discard this patch.
Braces   +255 added lines, -199 removed lines patch added patch discarded remove patch
@@ -40,7 +40,9 @@  discard block
 block discarded – undo
40 40
 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
41 41
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
42 42
 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
43
-if (! empty($conf->propal->enabled))  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
43
+if (! empty($conf->propal->enabled)) {
44
+    require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
45
+}
44 46
 if (! empty($conf->projet->enabled)) {
45 47
 	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
46 48
 	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
@@ -62,7 +64,9 @@  discard block
 block discarded – undo
62 64
 $usehm=(! empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE)?$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE:0);
63 65
 
64 66
 // Security check
65
-if ($user->societe_id) $socid=$user->societe_id;
67
+if ($user->societe_id) {
68
+    $socid=$user->societe_id;
69
+}
66 70
 $result=restrictedArea($user,'contrat',$id);
67 71
 
68 72
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@@ -74,11 +78,13 @@  discard block
 block discarded – undo
74 78
 // Load object
75 79
 if ($id > 0 || ! empty($ref) && $action!='add') {
76 80
 	$ret = $object->fetch($id, $ref);
77
-	if ($ret > 0)
78
-		$ret = $object->fetch_thirdparty();
79
-	if ($ret < 0)
80
-		dol_print_error('', $object->error);
81
-}
81
+	if ($ret > 0) {
82
+			$ret = $object->fetch_thirdparty();
83
+	}
84
+	if ($ret < 0) {
85
+			dol_print_error('', $object->error);
86
+	}
87
+	}
82 88
 
83 89
 // fetch optionals attributes and labels
84 90
 $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
@@ -98,7 +104,9 @@  discard block
 block discarded – undo
98 104
 
99 105
 $parameters = array('socid' => $socid);
100 106
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
101
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
107
+if ($reshook < 0) {
108
+    setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
109
+}
102 110
 if (empty($reshook))
103 111
 {
104 112
 	include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include, not includ_once
@@ -113,13 +121,10 @@  discard block
 block discarded – undo
113 121
 		{
114 122
 			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
115 123
 			exit;
116
-		}
117
-		else {
124
+		} else {
118 125
 			setEventMessages($object->error, $object->errors, 'errors');
119 126
 		}
120
-	}
121
-
122
-	else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer)
127
+	} else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer)
123 128
 	{
124 129
 		if (! GETPOST('dateend'))
125 130
 		{
@@ -133,8 +138,7 @@  discard block
 block discarded – undo
133 138
 			{
134 139
 				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
135 140
 				exit;
136
-			}
137
-			else
141
+			} else
138 142
 			{
139 143
 				setEventMessages($object->error, $object->errors, 'errors');
140 144
 			}
@@ -310,8 +314,12 @@  discard block
 block discarded – undo
310 314
 
311 315
 										$outputlangs = $langs;
312 316
 										$newlang='';
313
-										if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
314
-										if (empty($newlang)) $newlang=$srcobject->thirdparty->default_lang;
317
+										if (empty($newlang) && GETPOST('lang_id','aZ09')) {
318
+										    $newlang=GETPOST('lang_id','aZ09');
319
+										}
320
+										if (empty($newlang)) {
321
+										    $newlang=$srcobject->thirdparty->default_lang;
322
+										}
315 323
 										if (! empty($newlang))
316 324
 										{
317 325
 											$outputlangs = new Translate("",$conf);
@@ -319,23 +327,23 @@  discard block
 block discarded – undo
319 327
 										}
320 328
 
321 329
 										$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
322
-									}
323
-									else
330
+									} else
324 331
 									{
325 332
 										$label = $lines[$i]->product_label;
326 333
 									}
327 334
 									$desc = ($lines[$i]->desc && $lines[$i]->desc!=$lines[$i]->libelle)?dol_htmlentitiesbr($lines[$i]->desc):'';
328
-								}
329
-								else {
335
+								} else {
330 336
 									$desc = dol_htmlentitiesbr($lines[$i]->desc);
331 337
 								}
332 338
 
333 339
 								// Extrafields
334 340
 								$array_options = array();
335
-								if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) 							// For avoid conflicts if
341
+								if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
342
+								    // For avoid conflicts if
336 343
 								// trigger used
337 344
 								{
338 345
 									$lines[$i]->fetch_optionals($lines[$i]->rowid);
346
+								}
339 347
 									$array_options = $lines[$i]->array_options;
340 348
 								}
341 349
 
@@ -372,8 +380,7 @@  discard block
 block discarded – undo
372 380
 								}
373 381
 							}
374 382
 						}
375
-					}
376
-					else
383
+					} else
377 384
 					{
378 385
 						setEventMessages($srcobject->error, $srcobject->errors, 'errors');
379 386
 						$error++;
@@ -383,32 +390,28 @@  discard block
 block discarded – undo
383 390
 					$parameters = array('objFrom' => $srcobject);
384 391
 					$reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
385 392
 					// modified by hook
386
-					if ($reshook < 0)
387
-						$error++;
388
-				}
389
-				else
393
+					if ($reshook < 0) {
394
+											$error++;
395
+					}
396
+				} else
390 397
 				{
391 398
 					setEventMessages($object->error, $object->errors, 'errors');
392 399
 					$error++;
393 400
 				}
394
-			}
395
-			else
401
+			} else
396 402
 			{
397 403
 				$result = $object->create($user);
398 404
 				if ($result > 0)
399 405
 				{
400 406
 					header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
401 407
 					exit;
402
-				}
403
-				else {
408
+				} else {
404 409
 					setEventMessages($object->error, $object->errors, 'errors');
405 410
 				}
406 411
 				$action='create';
407 412
 			}
408 413
 		}
409
-	}
410
-
411
-	else if ($action == 'classin' && $user->rights->contrat->creer)
414
+	} else if ($action == 'classin' && $user->rights->contrat->creer)
412 415
 	{
413 416
 		$object->setProject(GETPOST('projectid'));
414 417
 	}
@@ -425,8 +428,7 @@  discard block
 block discarded – undo
425 428
 		{
426 429
 			$idprod=0;
427 430
 			$tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
428
-		}
429
-		else
431
+		} else
430 432
 		{
431 433
 			$idprod=GETPOST('idprod', 'int');
432 434
 			$tva_tx = '';
@@ -485,7 +487,9 @@  discard block
 block discarded – undo
485 487
 				// Update if prices fields are defined
486 488
 				$tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id);
487 489
 				$tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id);
488
-				if (empty($tva_tx)) $tva_npr=0;
490
+				if (empty($tva_tx)) {
491
+				    $tva_npr=0;
492
+				}
489 493
 
490 494
 				$pu_ht = $prod->price;
491 495
 				$pu_ttc = $prod->price_ttc;
@@ -499,8 +503,7 @@  discard block
 block discarded – undo
499 503
 					$pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
500 504
 					$price_min = $prod->multiprices_min[$object->thirdparty->price_level];
501 505
 					$price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
502
-				}
503
-				elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
506
+				} elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
504 507
 				{
505 508
 					require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
506 509
 
@@ -515,9 +518,13 @@  discard block
 block discarded – undo
515 518
 							$pu_ttc = price($prodcustprice->lines [0]->price_ttc);
516 519
 							$price_base_type = $prodcustprice->lines [0]->price_base_type;
517 520
 							$tva_tx = $prodcustprice->lines [0]->tva_tx;
518
-							if ($prodcustprice->lines[0]->default_vat_code && ! preg_match('/\(.*\)/', $tva_tx)) $tva_tx.= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
521
+							if ($prodcustprice->lines[0]->default_vat_code && ! preg_match('/\(.*\)/', $tva_tx)) {
522
+							    $tva_tx.= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
523
+							}
519 524
 							$tva_npr = $prodcustprice->lines[0]->recuperableonly;
520
-							if (empty($tva_tx)) $tva_npr=0;
525
+							if (empty($tva_tx)) {
526
+							    $tva_npr=0;
527
+							}
521 528
 						}
522 529
 					}
523 530
 				}
@@ -532,8 +539,7 @@  discard block
 block discarded – undo
532 539
 					if ($price_base_type != 'HT')
533 540
 					{
534 541
 						$pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU');
535
-					}
536
-					else
542
+					} else
537 543
 				  {
538 544
 						$pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU');
539 545
 					}
@@ -542,8 +548,7 @@  discard block
 block discarded – undo
542 548
 			   	$desc=$prod->description;
543 549
 			   	$desc=dol_concatdesc($desc,$product_desc, '', !empty($conf->global->CHANGE_ORDER_CONCAT_DESCRIPTION));
544 550
 				$fk_unit = $prod->fk_unit;
545
-			}
546
-			else
551
+			} else
547 552
 			{
548 553
 				$pu_ht=GETPOST('price_ht');
549 554
 				$price_base_type = 'HT';
@@ -558,20 +563,22 @@  discard block
 block discarded – undo
558 563
 
559 564
 			// ajout prix achat
560 565
 			$fk_fournprice = $_POST['fournprice'];
561
-			if ( ! empty($_POST['buying_price']) )
562
-			  $pa_ht = $_POST['buying_price'];
563
-			else
564
-			  $pa_ht = null;
566
+			if ( ! empty($_POST['buying_price']) ) {
567
+						  $pa_ht = $_POST['buying_price'];
568
+			} else {
569
+						  $pa_ht = null;
570
+			}
565 571
 
566 572
 			$info_bits=0;
567
-			if ($tva_npr) $info_bits |= 0x01;
573
+			if ($tva_npr) {
574
+			    $info_bits |= 0x01;
575
+			}
568 576
 
569 577
 			if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS) )&& ($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))))
570 578
 			{
571 579
 				$object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency));
572 580
 				$result = -1 ;
573
-			}
574
-			else
581
+			} else
575 582
 			{
576 583
 				// Insert line
577 584
 				$result = $object->addline(
@@ -598,12 +605,18 @@  discard block
 block discarded – undo
598 605
 			if ($result > 0)
599 606
 			{
600 607
 				// Define output language
601
-				if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && ! empty($conf->global->CONTRACT_ADDON_PDF))    // No generation if default type not defined
608
+				if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && ! empty($conf->global->CONTRACT_ADDON_PDF)) {
609
+				    // No generation if default type not defined
602 610
 				{
603 611
 					$outputlangs = $langs;
612
+				}
604 613
 					$newlang = '';
605
-					if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
606
-					if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
614
+					if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) {
615
+					    $newlang = GETPOST('lang_id','aZ09');
616
+					}
617
+					if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
618
+					    $newlang = $object->thirdparty->default_lang;
619
+					}
607 620
 					if (! empty($newlang)) {
608 621
 						$outputlangs = new Translate("", $conf);
609 622
 						$outputlangs->setDefaultLang($newlang);
@@ -645,15 +658,12 @@  discard block
 block discarded – undo
645 658
 				unset($_POST['date_endday']);
646 659
 				unset($_POST['date_endmonth']);
647 660
 				unset($_POST['date_endyear']);
648
-			}
649
-			else
661
+			} else
650 662
 			{
651 663
 				setEventMessages($object->error, $object->errors, 'errors');
652 664
 			}
653 665
 		}
654
-	}
655
-
656
-	else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel','alpha'))
666
+	} else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel','alpha'))
657 667
 	{
658 668
 		$error = 0;
659 669
 
@@ -679,14 +689,19 @@  discard block
 block discarded – undo
679 689
 
680 690
 		if (! $error)
681 691
 		{
682
-			if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture;
683
-			if ($date_end_real_update == '')   $date_end_real_update=$objectline->date_cloture;
692
+			if ($date_start_real_update == '') {
693
+			    $date_start_real_update=$objectline->date_ouverture;
694
+			}
695
+			if ($date_end_real_update == '') {
696
+			    $date_end_real_update=$objectline->date_cloture;
697
+			}
684 698
 
685 699
 			$vat_rate = GETPOST('eltva_tx');
686 700
 			// Define info_bits
687 701
 			$info_bits = 0;
688
-			if (preg_match('/\*/', $vat_rate))
689
-				  $info_bits |= 0x01;
702
+			if (preg_match('/\*/', $vat_rate)) {
703
+							  $info_bits |= 0x01;
704
+			}
690 705
 
691 706
 			// Define vat_rate
692 707
 			$vat_rate = str_replace('*', '', $vat_rate);
@@ -705,10 +720,11 @@  discard block
 block discarded – undo
705 720
 
706 721
 			// ajout prix d'achat
707 722
 			$fk_fournprice = $_POST['fournprice'];
708
-			if ( ! empty($_POST['buying_price']) )
709
-			  $pa_ht = $_POST['buying_price'];
710
-			else
711
-			  $pa_ht = null;
723
+			if ( ! empty($_POST['buying_price']) ) {
724
+						  $pa_ht = $_POST['buying_price'];
725
+			} else {
726
+						  $pa_ht = null;
727
+			}
712 728
 
713 729
 			$fk_unit = GETPOST('unit', 'alpha');
714 730
 
@@ -754,14 +770,11 @@  discard block
 block discarded – undo
754 770
 		if (! $error)
755 771
 		{
756 772
 			$db->commit();
757
-		}
758
-		else
773
+		} else
759 774
 		{
760 775
 			$db->rollback();
761 776
 		}
762
-	}
763
-
764
-	else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer)
777
+	} else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer)
765 778
 	{
766 779
 		$result = $object->deleteline(GETPOST('lineid'),$user);
767 780
 
@@ -769,14 +782,11 @@  discard block
 block discarded – undo
769 782
 		{
770 783
 			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
771 784
 			exit;
772
-		}
773
-		else
785
+		} else
774 786
 		{
775 787
 			setEventMessages($object->error, $object->errors, 'errors');
776 788
 		}
777
-	}
778
-
779
-	else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer)
789
+	} else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer)
780 790
 	{
781 791
 		$result = $object->validate($user);
782 792
 
@@ -787,8 +797,12 @@  discard block
 block discarded – undo
787 797
 			{
788 798
 				$outputlangs = $langs;
789 799
 				$newlang = '';
790
-				if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
791
-				if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
800
+				if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) {
801
+				    $newlang = GETPOST('lang_id','aZ09');
802
+				}
803
+				if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
804
+				    $newlang = $object->thirdparty->default_lang;
805
+				}
792 806
 				if (! empty($newlang)) {
793 807
 					$outputlangs = new Translate("", $conf);
794 808
 					$outputlangs->setDefaultLang($newlang);
@@ -798,14 +812,11 @@  discard block
 block discarded – undo
798 812
 
799 813
 				$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
800 814
 			}
801
-		}
802
-		else
815
+		} else
803 816
 		{
804 817
 			setEventMessages($object->error, $object->errors, 'errors');
805 818
 		}
806
-	}
807
-
808
-	else if ($action == 'reopen' && $user->rights->contrat->creer)
819
+	} else if ($action == 'reopen' && $user->rights->contrat->creer)
809 820
 	{
810 821
 		$result = $object->reopen($user);
811 822
 		if ($result < 0)
@@ -832,23 +843,18 @@  discard block
 block discarded – undo
832 843
 		{
833 844
 			setEventMessages($object->error, $object->errors, 'errors');
834 845
 		}
835
-	}
836
-
837
-	else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer)
846
+	} else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer)
838 847
 	{
839 848
 		$result=$object->delete($user);
840 849
 		if ($result >= 0)
841 850
 		{
842 851
 			header("Location: list.php?restore_lastsearch_values=1");
843 852
 			return;
844
-		}
845
-		else
853
+		} else
846 854
 		{
847 855
 			setEventMessages($object->error, $object->errors, 'errors');
848 856
 		}
849
-	}
850
-
851
-	else if ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer)
857
+	} else if ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer)
852 858
 	{
853 859
 		if (GETPOST('newcid') > 0)
854 860
 		{
@@ -860,25 +866,24 @@  discard block
 block discarded – undo
860 866
 			{
861 867
 				header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
862 868
 				return;
863
-			}
864
-			else
869
+			} else
865 870
 			{
866 871
 				setEventMessages($object->error, $object->errors, 'errors');
867 872
 			}
868
-		}
869
-		else
873
+		} else
870 874
 		{
871 875
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefNewContract")), null, 'errors');
872 876
 		}
873
-	}
874
-	else if ($action == 'update_extras')
877
+	} else if ($action == 'update_extras')
875 878
 	{
876 879
 		$object->oldcopy = dol_clone($object);
877 880
 
878 881
 		// Fill array 'array_options' with data from update form
879 882
 		$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
880 883
 		$ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none'));
881
-		if ($ret < 0) $error++;
884
+		if ($ret < 0) {
885
+		    $error++;
886
+		}
882 887
 
883 888
 		if (! $error) {
884 889
 			$result = $object->insertExtraFields('CONTRACT_MODIFY');
@@ -892,8 +897,7 @@  discard block
 block discarded – undo
892 897
 		if ($error) {
893 898
 			$action = 'edit_extras';
894 899
 		}
895
-	}
896
-	elseif ($action=='setref_supplier')
900
+	} elseif ($action=='setref_supplier')
897 901
 	{
898 902
 		$cancelbutton = GETPOST('cancel','alpha');
899 903
 		if (!$cancelbutton) {
@@ -908,13 +912,11 @@  discard block
 block discarded – undo
908 912
 				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
909 913
 				exit;
910 914
 			}
911
-		}
912
-		else {
915
+		} else {
913 916
 			header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
914 917
 			exit;
915 918
 		}
916
-	}
917
-	elseif ($action=='setref_customer')
919
+	} elseif ($action=='setref_customer')
918 920
 	{
919 921
 		$cancelbutton = GETPOST('cancel','alpha');
920 922
 
@@ -930,13 +932,11 @@  discard block
 block discarded – undo
930 932
 				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
931 933
 				exit;
932 934
 			}
933
-		}
934
-		else {
935
+		} else {
935 936
 			header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
936 937
 			exit;
937 938
 		}
938
-	}
939
-	elseif ($action=='setref')
939
+	} elseif ($action=='setref')
940 940
 	{
941 941
 		$cancelbutton = GETPOST('cancel','alpha');
942 942
 
@@ -960,7 +960,9 @@  discard block
 block discarded – undo
960 960
 				$files = dol_dir_list($old_filedir);
961 961
 				if (!empty($files))
962 962
 				{
963
-					if (!is_dir($new_filedir)) dol_mkdir($new_filedir);
963
+					if (!is_dir($new_filedir)) {
964
+					    dol_mkdir($new_filedir);
965
+					}
964 966
 					foreach ($files as $file)
965 967
 					{
966 968
 						dol_move($file['fullname'], $new_filedir.'/'.$file['name']);
@@ -970,13 +972,11 @@  discard block
 block discarded – undo
970 972
 	            header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
971 973
 	            exit;
972 974
 	        }
973
-	    }
974
-	    else {
975
+	    } else {
975 976
 	        header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
976 977
 	        exit;
977 978
 	    }
978
-	}
979
-	elseif ($action=='setdate_contrat')
979
+	} elseif ($action=='setdate_contrat')
980 980
 	{
981 981
 		$cancelbutton = GETPOST('cancel','alpha');
982 982
 
@@ -994,8 +994,7 @@  discard block
 block discarded – undo
994 994
 				header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
995 995
 				exit;
996 996
 			}
997
-		}
998
-		else {
997
+		} else {
999 998
 			header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id);
1000 999
 			exit;
1001 1000
 		}
@@ -1026,15 +1025,13 @@  discard block
 block discarded – undo
1026 1025
 			{
1027 1026
 				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1028 1027
 				exit;
1029
-			}
1030
-			else
1028
+			} else
1031 1029
 			{
1032 1030
 				if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1033 1031
 				{
1034 1032
 					$langs->load("errors");
1035 1033
 					setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
1036
-				}
1037
-				else
1034
+				} else
1038 1035
 				{
1039 1036
 					setEventMessages($object->error, $object->errors, 'errors');
1040 1037
 				}
@@ -1056,8 +1053,7 @@  discard block
 block discarded – undo
1056 1053
 			{
1057 1054
 				header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1058 1055
 				exit;
1059
-			}
1060
-			else {
1056
+			} else {
1061 1057
 				setEventMessages($object->error, $object->errors, 'errors');
1062 1058
 			}
1063 1059
 		}
@@ -1069,8 +1065,7 @@  discard block
 block discarded – undo
1069 1065
 		if (! GETPOST('socid', 3))
1070 1066
 		{
1071 1067
 			setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
1072
-		}
1073
-		else
1068
+		} else
1074 1069
 		{
1075 1070
 			if ($object->id > 0) {
1076 1071
 				$result = $object->createFromClone($socid);
@@ -1078,7 +1073,9 @@  discard block
 block discarded – undo
1078 1073
 					header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result);
1079 1074
 					exit();
1080 1075
 				} else {
1081
-					if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors');
1076
+					if (count($object->errors) > 0) {
1077
+					    setEventMessages($object->error, $object->errors, 'errors');
1078
+					}
1082 1079
 					$action = '';
1083 1080
 				}
1084 1081
 			}
@@ -1095,7 +1092,9 @@  discard block
 block discarded – undo
1095 1092
 
1096 1093
 $form = new Form($db);
1097 1094
 $formfile = new FormFile($db);
1098
-if (! empty($conf->projet->enabled)) $formproject = new FormProjets($db);
1095
+if (! empty($conf->projet->enabled)) {
1096
+    $formproject = new FormProjets($db);
1097
+}
1099 1098
 
1100 1099
 $objectlignestatic=new ContratLigne($db);
1101 1100
 
@@ -1117,7 +1116,9 @@  discard block
 block discarded – undo
1117 1116
 	print load_fiche_titre($langs->trans('AddContract'),'','title_commercial.png');
1118 1117
 
1119 1118
 	$soc = new Societe($db);
1120
-	if ($socid>0) $soc->fetch($socid);
1119
+	if ($socid>0) {
1120
+	    $soc->fetch($socid);
1121
+	}
1121 1122
 
1122 1123
 	if (GETPOST('origin') && GETPOST('originid'))
1123 1124
 	{
@@ -1132,8 +1133,7 @@  discard block
 block discarded – undo
1132 1133
 		if ($element == 'project')
1133 1134
 		{
1134 1135
 			$projectid=GETPOST('originid');
1135
-		}
1136
-		else
1136
+		} else
1137 1137
 		{
1138 1138
 			// For compatibility
1139 1139
 			if ($element == 'order' || $element == 'commande')    { $element = $subelement = 'commande'; }
@@ -1144,7 +1144,9 @@  discard block
 block discarded – undo
1144 1144
 			$classname = ucfirst($subelement);
1145 1145
 			$objectsrc = new $classname($db);
1146 1146
 			$objectsrc->fetch(GETPOST('originid'));
1147
-			if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines'))  $objectsrc->fetch_lines();
1147
+			if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines')) {
1148
+			    $objectsrc->fetch_lines();
1149
+			}
1148 1150
 			$objectsrc->fetch_thirdparty();
1149 1151
 
1150 1152
 			// Replicate extrafields
@@ -1161,8 +1163,7 @@  discard block
 block discarded – undo
1161 1163
 			// Object source contacts list
1162 1164
 			$srccontactslist = $objectsrc->liste_contact(-1,'external',1);
1163 1165
 		}
1164
-	}
1165
-	else {
1166
+	} else {
1166 1167
 		$projectid = GETPOST('projectid','int');
1167 1168
 		$note_private = GETPOST("note_private");
1168 1169
 		$note_public = GETPOST("note_public");
@@ -1208,8 +1209,7 @@  discard block
 block discarded – undo
1208 1209
 		print $soc->getNomUrl(1);
1209 1210
 		print '<input type="hidden" name="socid" value="'.$soc->id.'">';
1210 1211
 		print '</td>';
1211
-	}
1212
-	else
1212
+	} else
1213 1213
 	{
1214 1214
 		print '<td>';
1215 1215
 		print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300');
@@ -1222,12 +1222,18 @@  discard block
 block discarded – undo
1222 1222
 	{
1223 1223
 		// Ligne info remises tiers
1224 1224
 		print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
1225
-		if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent);
1226
-		else print $langs->trans("CompanyHasNoRelativeDiscount");
1225
+		if ($soc->remise_percent) {
1226
+		    print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent);
1227
+		} else {
1228
+		    print $langs->trans("CompanyHasNoRelativeDiscount");
1229
+		}
1227 1230
 		print '. ';
1228 1231
 		$absolute_discount=$soc->getAvailableDiscounts();
1229
-		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1230
-		else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1232
+		if ($absolute_discount) {
1233
+		    print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1234
+		} else {
1235
+		    print $langs->trans("CompanyHasNoAbsoluteDiscount");
1236
+		}
1231 1237
 		print '.';
1232 1238
 		print '</td></tr>';
1233 1239
 	}
@@ -1304,8 +1310,7 @@  discard block
 block discarded – undo
1304 1310
 	}
1305 1311
 
1306 1312
 	print "</form>\n";
1307
-}
1308
-else
1313
+} else
1309 1314
 /* *************************************************************************** */
1310 1315
 /*                                                                             */
1311 1316
 /* Mode vue et edition                                                         */
@@ -1416,7 +1421,9 @@  discard block
 block discarded – undo
1416 1421
 		$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1);
1417 1422
 		// Thirdparty
1418 1423
 		$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
1419
-		if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
1424
+		if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
1425
+		    $morehtmlref.=' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
1426
+		}
1420 1427
 		// Project
1421 1428
 		if (! empty($conf->projet->enabled))
1422 1429
 		{
@@ -1424,8 +1431,9 @@  discard block
 block discarded – undo
1424 1431
 			$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
1425 1432
 			if ($user->rights->contrat->creer)
1426 1433
 			{
1427
-				if ($action != 'classify')
1428
-					$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
1434
+				if ($action != 'classify') {
1435
+									$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
1436
+				}
1429 1437
 					if ($action == 'classify') {
1430 1438
 						//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
1431 1439
 						$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
@@ -1463,12 +1471,18 @@  discard block
 block discarded – undo
1463 1471
 
1464 1472
 		// Ligne info remises tiers
1465 1473
 		print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">';
1466
-		if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent);
1467
-		else print $langs->trans("CompanyHasNoRelativeDiscount");
1474
+		if ($object->thirdparty->remise_percent) {
1475
+		    print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent);
1476
+		} else {
1477
+		    print $langs->trans("CompanyHasNoRelativeDiscount");
1478
+		}
1468 1479
 		$absolute_discount=$object->thirdparty->getAvailableDiscounts();
1469 1480
 		print '. ';
1470
-		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1471
-		else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1481
+		if ($absolute_discount) {
1482
+		    print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1483
+		} else {
1484
+		    print $langs->trans("CompanyHasNoAbsoluteDiscount");
1485
+		}
1472 1486
 		print '.';
1473 1487
 		print '</td></tr>';
1474 1488
 
@@ -1522,7 +1536,9 @@  discard block
 block discarded – undo
1522 1536
 		$productstatic=new Product($db);
1523 1537
 
1524 1538
 		$usemargins=0;
1525
-		if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1;
1539
+		if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) {
1540
+		    $usemargins=1;
1541
+		}
1526 1542
 
1527 1543
 		$var=false;
1528 1544
 
@@ -1567,9 +1583,13 @@  discard block
 block discarded – undo
1567 1583
 					print '<td width="80" align="right">'.$langs->trans("PriceUHTCurrency").'</td>';
1568 1584
 				}
1569 1585
 				print '<td width="30" align="center">'.$langs->trans("Qty").'</td>';
1570
-				if ($conf->global->PRODUCT_USE_UNITS) print '<td width="30" align="left">'.$langs->trans("Unit").'</td>';
1586
+				if ($conf->global->PRODUCT_USE_UNITS) {
1587
+				    print '<td width="30" align="left">'.$langs->trans("Unit").'</td>';
1588
+				}
1571 1589
 				print '<td width="50" align="right">'.$langs->trans("ReductionShort").'</td>';
1572
-				if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td width="50" align="right">'.$langs->trans("BuyingPrice").'</td>';
1590
+				if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) {
1591
+				    print '<td width="50" align="right">'.$langs->trans("BuyingPrice").'</td>';
1592
+				}
1573 1593
 				print '<td width="30">&nbsp;</td>';
1574 1594
 				print "</tr>\n";
1575 1595
 
@@ -1607,8 +1627,7 @@  discard block
 block discarded – undo
1607 1627
 						echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):''));
1608 1628
 
1609 1629
 						print '</td>';
1610
-					}
1611
-					else
1630
+					} else
1612 1631
 					{
1613 1632
 						print '<td>'.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."</td>\n";
1614 1633
 					}
@@ -1625,19 +1644,22 @@  discard block
 block discarded – undo
1625 1644
 					// Quantite
1626 1645
 					print '<td align="center">'.$objp->qty.'</td>';
1627 1646
 					// Unit
1628
-					if($conf->global->PRODUCT_USE_UNITS) print '<td align="left">'.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).'</td>';
1647
+					if($conf->global->PRODUCT_USE_UNITS) {
1648
+					    print '<td align="left">'.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).'</td>';
1649
+					}
1629 1650
 					// Remise
1630 1651
 					if ($objp->remise_percent > 0)
1631 1652
 					{
1632 1653
 						print '<td align="right">'.$objp->remise_percent."%</td>\n";
1633
-					}
1634
-					else
1654
+					} else
1635 1655
 					{
1636 1656
 						print '<td>&nbsp;</td>';
1637 1657
 					}
1638 1658
 
1639 1659
 					// Margin
1640
-					if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td align="right" class="nowrap">'.price($objp->pa_ht).'</td>';
1660
+					if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) {
1661
+					    print '<td align="right" class="nowrap">'.price($objp->pa_ht).'</td>';
1662
+					}
1641 1663
 
1642 1664
 					// Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme)
1643 1665
 					print '<td align="right" class="nowrap">';
@@ -1689,8 +1711,9 @@  discard block
 block discarded – undo
1689 1711
 								$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1690 1712
 								print " ".img_warning($textlate);
1691 1713
 							}
1714
+						} else {
1715
+						    print $langs->trans("Unknown");
1692 1716
 						}
1693
-						else print $langs->trans("Unknown");
1694 1717
 						print ' &nbsp;-&nbsp; ';
1695 1718
 						print $langs->trans("DateEndPlanned").': ';
1696 1719
 						if ($objp->date_fin)
@@ -1701,8 +1724,9 @@  discard block
 block discarded – undo
1701 1724
 								$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1702 1725
 								print " ".img_warning($textlate);
1703 1726
 							}
1727
+						} else {
1728
+						    print $langs->trans("Unknown");
1704 1729
 						}
1705
-						else print $langs->trans("Unknown");
1706 1730
 
1707 1731
 						print '</td>';
1708 1732
 						print '</tr>';
@@ -1730,8 +1754,7 @@  discard block
 block discarded – undo
1730 1754
 						print $productstatic->getNomUrl(1,'',32);
1731 1755
 						print $objp->label?' - '.dol_trunc($objp->label,32):'';
1732 1756
 						print '<br>';
1733
-					}
1734
-					else
1757
+					} else
1735 1758
 					{
1736 1759
 						print $objp->label?$objp->label.'<br>':'';
1737 1760
 					}
@@ -1739,7 +1762,9 @@  discard block
 block discarded – undo
1739 1762
 					// editeur wysiwyg
1740 1763
 					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1741 1764
 					$nbrows=ROWS_2;
1742
-					if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
1765
+					if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) {
1766
+					    $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
1767
+					}
1743 1768
 					$enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0);
1744 1769
 					$doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%');
1745 1770
 					$doleditor->Create();
@@ -1760,7 +1785,9 @@  discard block
 block discarded – undo
1760 1785
 					if (! empty($usemargins))
1761 1786
 					{
1762 1787
 						print '<td align="right">';
1763
-						if ($objp->fk_product) print '<select id="fournprice" name="fournprice"></select>';
1788
+						if ($objp->fk_product) {
1789
+						    print '<select id="fournprice" name="fournprice"></select>';
1790
+						}
1764 1791
 						print '<input id="buying_price" type="text" size="5" name="buying_price" value="'.price($objp->pa_ht,0,'',0).'"></td>';
1765 1792
 					}
1766 1793
 					print '<td align="center">';
@@ -1770,8 +1797,12 @@  discard block
 block discarded – undo
1770 1797
 					print '</tr>';
1771 1798
 
1772 1799
 					$colspan=6;
1773
-					if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++;
1774
-					if($conf->global->PRODUCT_USE_UNITS) $colspan++;
1800
+					if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) {
1801
+					    $colspan++;
1802
+					}
1803
+					if($conf->global->PRODUCT_USE_UNITS) {
1804
+					    $colspan++;
1805
+					}
1775 1806
 
1776 1807
 					// Ligne dates prevues
1777 1808
 					print '<tr class="oddeven">';
@@ -1791,8 +1822,7 @@  discard block
 block discarded – undo
1791 1822
 				}
1792 1823
 
1793 1824
 				$db->free($result);
1794
-			}
1795
-			else
1825
+			} else
1796 1826
 			{
1797 1827
 				dol_print_error($db);
1798 1828
 			}
@@ -1816,7 +1846,9 @@  discard block
 block discarded – undo
1816 1846
 			if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid'))
1817 1847
 			{
1818 1848
 				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1);
1819
-				if ($ret == 'html') print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1849
+				if ($ret == 'html') {
1850
+				    print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1851
+				}
1820 1852
 			}
1821 1853
 
1822 1854
 			/*
@@ -1863,8 +1895,7 @@  discard block
 block discarded – undo
1863 1895
 				if (empty($dateactend))
1864 1896
 				{
1865 1897
 					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors');
1866
-				}
1867
-				else
1898
+				} else
1868 1899
 				{
1869 1900
 					print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1);
1870 1901
 				}
@@ -1910,8 +1941,11 @@  discard block
 block discarded – undo
1910 1941
 				// Si pas encore active
1911 1942
 				if (! $objp->date_debut_reelle) {
1912 1943
 					print $langs->trans("DateStartReal").': ';
1913
-					if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle, 'day');
1914
-					else print $langs->trans("ContractStatusNotRunning");
1944
+					if ($objp->date_debut_reelle) {
1945
+					    print dol_print_date($objp->date_debut_reelle, 'day');
1946
+					} else {
1947
+					    print $langs->trans("ContractStatusNotRunning");
1948
+					}
1915 1949
 				}
1916 1950
 				// Si active et en cours
1917 1951
 				if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) {
@@ -1926,7 +1960,9 @@  discard block
 block discarded – undo
1926 1960
 					print $langs->trans("DateEndReal").': ';
1927 1961
 					print dol_print_date($objp->date_fin_reelle, 'day');
1928 1962
 				}
1929
-				if (! empty($objp->comment)) print " &nbsp;-&nbsp; ".$objp->comment;
1963
+				if (! empty($objp->comment)) {
1964
+				    print " &nbsp;-&nbsp; ".$objp->comment;
1965
+				}
1930 1966
 				print '</td>';
1931 1967
 
1932 1968
 				print '<td align="center">&nbsp;</td>';
@@ -1945,12 +1981,16 @@  discard block
 block discarded – undo
1945 1981
 
1946 1982
 				// Definie date debut et fin par defaut
1947 1983
 				$dateactstart = $objp->date_debut;
1948
-				if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1949
-				elseif (! $dateactstart) $dateactstart = time();
1984
+				if (GETPOST('remonth')) {
1985
+				    $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1986
+				} elseif (! $dateactstart) {
1987
+				    $dateactstart = time();
1988
+				}
1950 1989
 
1951 1990
 				$dateactend = $objp->date_fin;
1952
-				if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1953
-				elseif (! $dateactend)
1991
+				if (GETPOST('endmonth')) {
1992
+				    $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1993
+				} elseif (! $dateactend)
1954 1994
 				{
1955 1995
 					if ($objp->fk_product > 0)
1956 1996
 					{
@@ -2000,12 +2040,16 @@  discard block
 block discarded – undo
2000 2040
 
2001 2041
 				// Definie date debut et fin par defaut
2002 2042
 				$dateactstart = $objp->date_debut_reelle;
2003
-				if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
2004
-				elseif (! $dateactstart) $dateactstart = time();
2043
+				if (GETPOST('remonth')) {
2044
+				    $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
2045
+				} elseif (! $dateactstart) {
2046
+				    $dateactstart = time();
2047
+				}
2005 2048
 
2006 2049
 				$dateactend = $objp->date_fin_reelle;
2007
-				if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
2008
-				elseif (! $dateactend)
2050
+				if (GETPOST('endmonth')) {
2051
+				    $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
2052
+				} elseif (! $dateactend)
2009 2053
 				{
2010 2054
 					if ($objp->fk_product > 0)
2011 2055
 					{
@@ -2015,7 +2059,9 @@  discard block
 block discarded – undo
2015 2059
 					}
2016 2060
 				}
2017 2061
 				$now=dol_now();
2018
-				if ($dateactend > $now) $dateactend=$now;
2062
+				if ($dateactend > $now) {
2063
+				    $dateactend=$now;
2064
+				}
2019 2065
 
2020 2066
 				print '<tr class="oddeven"><td colspan="2" class="nohover">';
2021 2067
 				if ($objp->statut >= 4)
@@ -2100,33 +2146,46 @@  discard block
 block discarded – undo
2100 2146
 				if ($object->statut == 1) {
2101 2147
 					if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) {
2102 2148
 						print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a></div>';
2103
-					} else
2104
-						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">' . $langs->trans('SendMail') . '</a></div>';
2149
+					} else {
2150
+											print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">' . $langs->trans('SendMail') . '</a></div>';
2151
+					}
2105 2152
 				}
2106 2153
 
2107 2154
 				if ($object->statut == 0 && $nbofservices)
2108 2155
 				{
2109
-					if ($user->rights->contrat->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">'.$langs->trans("Validate").'</a></div>';
2110
-					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Validate").'</a></div>';
2156
+					if ($user->rights->contrat->creer) {
2157
+					    print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">'.$langs->trans("Validate").'</a></div>';
2158
+					} else {
2159
+					    print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Validate").'</a></div>';
2160
+					}
2111 2161
 				}
2112 2162
 				if ($object->statut == 1)
2113 2163
 				{
2114
-					if ($user->rights->contrat->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Modify").'</a></div>';
2115
-					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Modify").'</a></div>';
2164
+					if ($user->rights->contrat->creer) {
2165
+					    print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Modify").'</a></div>';
2166
+					} else {
2167
+					    print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Modify").'</a></div>';
2168
+					}
2116 2169
 				}
2117 2170
 
2118 2171
 				if (! empty($conf->facture->enabled) && $object->statut > 0)
2119 2172
 				{
2120 2173
 					$langs->load("bills");
2121
-					if ($user->rights->facture->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateBill").'</a></div>';
2122
-					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateBill").'</a></div>';
2174
+					if ($user->rights->facture->creer) {
2175
+					    print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateBill").'</a></div>';
2176
+					} else {
2177
+					    print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateBill").'</a></div>';
2178
+					}
2123 2179
 				}
2124 2180
 
2125 2181
 				if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices)
2126 2182
 				{
2127 2183
 					$langs->load("orders");
2128
-					if ($user->rights->commande->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateOrder").'</a></div>';
2129
-					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateOrder").'</a></div>';
2184
+					if ($user->rights->commande->creer) {
2185
+					    print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateOrder").'</a></div>';
2186
+					} else {
2187
+					    print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateOrder").'</a></div>';
2188
+					}
2130 2189
 				}
2131 2190
 
2132 2191
 				// Clone
@@ -2139,8 +2198,7 @@  discard block
 block discarded – undo
2139 2198
 					if ($user->rights->contrat->activer)
2140 2199
 					{
2141 2200
 						print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=activate">'.$langs->trans("ActivateAllContracts").'</a></div>';
2142
-					}
2143
-					else
2201
+					} else
2144 2202
 					{
2145 2203
 						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("ActivateAllContracts").'</a></div>';
2146 2204
 					}
@@ -2150,8 +2208,7 @@  discard block
 block discarded – undo
2150 2208
 					if ($user->rights->contrat->desactiver)
2151 2209
 					{
2152 2210
 						print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=close">'.$langs->trans("CloseAllContracts").'</a></div>';
2153
-					}
2154
-					else
2211
+					} else
2155 2212
 					{
2156 2213
 						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("CloseAllContracts").'</a></div>';
2157 2214
 					}
@@ -2171,8 +2228,7 @@  discard block
 block discarded – undo
2171 2228
 				if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer)
2172 2229
 				{
2173 2230
 					print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete">'.$langs->trans("Delete").'</a></div>';
2174
-				}
2175
-				else
2231
+				} else
2176 2232
 				{
2177 2233
 					print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("Delete").'</a></div>';
2178 2234
 				}
Please login to merge, or discard this patch.
dolibarr/htdocs/contrat/tpl/linkedobjectblock.tpl.php 3 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -19,8 +19,8 @@  discard block
 block discarded – undo
19 19
 // Protection to avoid direct call of template
20 20
 if (empty($conf) || ! is_object($conf))
21 21
 {
22
-	print "Error, template page can't be called as URL";
23
-	exit;
22
+    print "Error, template page can't be called as URL";
23
+    exit;
24 24
 }
25 25
 
26 26
 ?>
@@ -52,18 +52,18 @@  discard block
 block discarded – undo
52 52
     <td></td>
53 53
 	<td align="center"><?php echo dol_print_date($objectlink->date_contrat,'day'); ?></td>
54 54
     <td align="right"><?php
55
-		// Price of contract is not shown by default because a contract is a list of service with
56
-		// start and end date that change with time andd that may be different that the period of reference for price.
57
-		// So price of a contract does often means nothing. Prices is on the different invoices done on same contract.
58
-		if ($user->rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE))
59
-		{
60
-			$totalcontrat = 0;
61
-			foreach ($objectlink->lines as $linecontrat) {
62
-				$totalcontrat = $totalcontrat + $linecontrat->total_ht;
63
-			    $total = $total + $linecontrat->total_ht;
64
-			}
65
-			echo price($totalcontrat);
66
-		} ?></td>
55
+        // Price of contract is not shown by default because a contract is a list of service with
56
+        // start and end date that change with time andd that may be different that the period of reference for price.
57
+        // So price of a contract does often means nothing. Prices is on the different invoices done on same contract.
58
+        if ($user->rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE))
59
+        {
60
+            $totalcontrat = 0;
61
+            foreach ($objectlink->lines as $linecontrat) {
62
+                $totalcontrat = $totalcontrat + $linecontrat->total_ht;
63
+                $total = $total + $linecontrat->total_ht;
64
+            }
65
+            echo price($totalcontrat);
66
+        } ?></td>
67 67
 	<td align="right"><?php echo $objectlink->getLibStatut(7); ?></td>
68 68
 	<td align="right"><a href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td>
69 69
 </tr>
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
  */
18 18
 
19 19
 // Protection to avoid direct call of template
20
-if (empty($conf) || ! is_object($conf))
20
+if (empty($conf) || !is_object($conf))
21 21
 {
22 22
 	print "Error, template page can't be called as URL";
23 23
 	exit;
@@ -38,19 +38,19 @@  discard block
 block discarded – undo
38 38
 // Load translation files required by the page
39 39
 $langs->load("contracts");
40 40
 
41
-$total=0; $ilink=0;
42
-foreach($linkedObjectBlock as $key => $objectlink)
41
+$total = 0; $ilink = 0;
42
+foreach ($linkedObjectBlock as $key => $objectlink)
43 43
 {
44 44
     $ilink++;
45 45
 
46
-    $trclass='oddeven';
47
-    if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total';
46
+    $trclass = 'oddeven';
47
+    if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total';
48 48
 ?>
49 49
 <tr class="<?php echo $trclass; ?>">
50 50
     <td><?php echo $langs->trans("Contract"); ?></td>
51 51
     <td><?php echo $objectlink->getNomUrl(1); ?></td>
52 52
     <td></td>
53
-	<td align="center"><?php echo dol_print_date($objectlink->date_contrat,'day'); ?></td>
53
+	<td align="center"><?php echo dol_print_date($objectlink->date_contrat, 'day'); ?></td>
54 54
     <td align="right"><?php
55 55
 		// Price of contract is not shown by default because a contract is a list of service with
56 56
 		// start and end date that change with time andd that may be different that the period of reference for price.
Please login to merge, or discard this patch.
Braces   +4 added lines, -2 removed lines patch added patch discarded remove patch
@@ -44,8 +44,10 @@
 block discarded – undo
44 44
     $ilink++;
45 45
 
46 46
     $trclass='oddeven';
47
-    if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total';
48
-?>
47
+    if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) {
48
+        $trclass.=' liste_sub_total';
49
+    }
50
+    ?>
49 51
 <tr class="<?php echo $trclass; ?>">
50 52
     <td><?php echo $langs->trans("Contract"); ?></td>
51 53
     <td><?php echo $objectlink->getNomUrl(1); ?></td>
Please login to merge, or discard this patch.
dolibarr/htdocs/contrat/info.php 3 patches
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
 require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
28 28
 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
29 29
 if (! empty($conf->projet->enabled)) {
30
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
30
+    require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
31 31
 }
32 32
 
33 33
 // Load translation files required by the page
@@ -102,35 +102,35 @@  discard block
 block discarded – undo
102 102
 // Project
103 103
 if (! empty($conf->projet->enabled))
104 104
 {
105
-	$langs->load("projects");
106
-	$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
107
-	if ($user->rights->contrat->creer)
108
-	{
109
-		if ($action != 'classify')
110
-			//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
111
-			$morehtmlref.=' : ';
112
-		if ($action == 'classify') {
113
-			//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
114
-			$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
115
-			$morehtmlref.='<input type="hidden" name="action" value="classin">';
116
-			$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
117
-			$morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
118
-			$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
119
-			$morehtmlref.='</form>';
120
-		} else {
121
-			$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
122
-		}
123
-	} else {
124
-		if (! empty($object->fk_project)) {
125
-			$proj = new Project($db);
126
-			$proj->fetch($object->fk_project);
127
-			$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
128
-			$morehtmlref.=$proj->ref;
129
-			$morehtmlref.='</a>';
130
-		} else {
131
-			$morehtmlref.='';
132
-		}
133
-	}
105
+    $langs->load("projects");
106
+    $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
107
+    if ($user->rights->contrat->creer)
108
+    {
109
+        if ($action != 'classify')
110
+            //$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
111
+            $morehtmlref.=' : ';
112
+        if ($action == 'classify') {
113
+            //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
114
+            $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
115
+            $morehtmlref.='<input type="hidden" name="action" value="classin">';
116
+            $morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
117
+            $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
118
+            $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
119
+            $morehtmlref.='</form>';
120
+        } else {
121
+            $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
122
+        }
123
+    } else {
124
+        if (! empty($object->fk_project)) {
125
+            $proj = new Project($db);
126
+            $proj->fetch($object->fk_project);
127
+            $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
128
+            $morehtmlref.=$proj->ref;
129
+            $morehtmlref.='</a>';
130
+        } else {
131
+            $morehtmlref.='';
132
+        }
133
+    }
134 134
 }
135 135
 $morehtmlref.='</div>';
136 136
 
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -26,24 +26,24 @@  discard block
 block discarded – undo
26 26
 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
27 27
 require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
28 28
 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
29
-if (! empty($conf->projet->enabled)) {
30
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
29
+if (!empty($conf->projet->enabled)) {
30
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
31 31
 }
32 32
 
33 33
 // Load translation files required by the page
34 34
 $langs->load("contracts");
35 35
 
36
-$action		= GETPOST('action','alpha');
37
-$confirm	= GETPOST('confirm','alpha');
38
-$id			= GETPOST('id','int');
39
-$ref		= GETPOST('ref','alpha');
36
+$action		= GETPOST('action', 'alpha');
37
+$confirm	= GETPOST('confirm', 'alpha');
38
+$id			= GETPOST('id', 'int');
39
+$ref		= GETPOST('ref', 'alpha');
40 40
 
41 41
 // Security check
42
-if ($user->societe_id) $socid=$user->societe_id;
42
+if ($user->societe_id) $socid = $user->societe_id;
43 43
 $result = restrictedArea($user, 'contrat', $id, '');
44 44
 
45 45
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
46
-$hookmanager->initHooks(array('contractcard','globalcard'));
46
+$hookmanager->initHooks(array('contractcard', 'globalcard'));
47 47
 
48 48
 
49 49
 /*
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 
61 61
 $form = new Form($db);
62 62
 
63
-llxHeader('',$langs->trans("Contract"),"");
63
+llxHeader('', $langs->trans("Contract"), "");
64 64
 
65 65
 $object = new Contrat($db);
66 66
 $object->fetch($id, $ref);
@@ -78,61 +78,61 @@  discard block
 block discarded – undo
78 78
 
79 79
 // Contract card
80 80
 
81
-$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
81
+$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
82 82
 
83 83
 
84
-$morehtmlref='';
84
+$morehtmlref = '';
85 85
 //if (! empty($modCodeContract->code_auto)) {
86
-$morehtmlref.=$object->ref;
86
+$morehtmlref .= $object->ref;
87 87
 /*} else {
88 88
  $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3);
89 89
 $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2);
90 90
 }*/
91 91
 
92
-$morehtmlref.='<div class="refidno">';
92
+$morehtmlref .= '<div class="refidno">';
93 93
 // Ref customer
94
-$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
95
-$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1);
94
+$morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
95
+$morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1);
96 96
 // Ref supplier
97
-$morehtmlref.='<br>';
98
-$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
99
-$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1);
97
+$morehtmlref .= '<br>';
98
+$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
99
+$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1);
100 100
 // Thirdparty
101
-$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
101
+$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
102 102
 // Project
103
-if (! empty($conf->projet->enabled))
103
+if (!empty($conf->projet->enabled))
104 104
 {
105 105
 	$langs->load("projects");
106
-	$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
106
+	$morehtmlref .= '<br>'.$langs->trans('Project').' ';
107 107
 	if ($user->rights->contrat->creer)
108 108
 	{
109 109
 		if ($action != 'classify')
110 110
 			//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
111
-			$morehtmlref.=' : ';
111
+			$morehtmlref .= ' : ';
112 112
 		if ($action == 'classify') {
113 113
 			//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
114
-			$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
115
-			$morehtmlref.='<input type="hidden" name="action" value="classin">';
116
-			$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
117
-			$morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
118
-			$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
119
-			$morehtmlref.='</form>';
114
+			$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
115
+			$morehtmlref .= '<input type="hidden" name="action" value="classin">';
116
+			$morehtmlref .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
117
+			$morehtmlref .= $formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
118
+			$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
119
+			$morehtmlref .= '</form>';
120 120
 		} else {
121
-			$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
121
+			$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
122 122
 		}
123 123
 	} else {
124
-		if (! empty($object->fk_project)) {
124
+		if (!empty($object->fk_project)) {
125 125
 			$proj = new Project($db);
126 126
 			$proj->fetch($object->fk_project);
127
-			$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
128
-			$morehtmlref.=$proj->ref;
129
-			$morehtmlref.='</a>';
127
+			$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
128
+			$morehtmlref .= $proj->ref;
129
+			$morehtmlref .= '</a>';
130 130
 		} else {
131
-			$morehtmlref.='';
131
+			$morehtmlref .= '';
132 132
 		}
133 133
 	}
134 134
 }
135
-$morehtmlref.='</div>';
135
+$morehtmlref .= '</div>';
136 136
 
137 137
 
138 138
 dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
Please login to merge, or discard this patch.
Braces   +6 added lines, -3 removed lines patch added patch discarded remove patch
@@ -39,7 +39,9 @@  discard block
 block discarded – undo
39 39
 $ref		= GETPOST('ref','alpha');
40 40
 
41 41
 // Security check
42
-if ($user->societe_id) $socid=$user->societe_id;
42
+if ($user->societe_id) {
43
+    $socid=$user->societe_id;
44
+}
43 45
 $result = restrictedArea($user, 'contrat', $id, '');
44 46
 
45 47
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@@ -106,9 +108,10 @@  discard block
 block discarded – undo
106 108
 	$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
107 109
 	if ($user->rights->contrat->creer)
108 110
 	{
109
-		if ($action != 'classify')
110
-			//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
111
+		if ($action != 'classify') {
112
+					//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
111 113
 			$morehtmlref.=' : ';
114
+		}
112 115
 		if ($action == 'classify') {
113 116
 			//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
114 117
 			$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
Please login to merge, or discard this patch.
dolibarr/htdocs/contrat/document.php 3 patches
Indentation   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
35 35
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
36 36
 if (! empty($conf->projet->enabled)) {
37
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
37
+    require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
38 38
 }
39 39
 
40 40
 // Load translation files required by the page
@@ -48,9 +48,9 @@  discard block
 block discarded – undo
48 48
 // Security check
49 49
 if ($user->societe_id > 0)
50 50
 {
51
-	unset($_GET["action"]);
52
-	$action='';
53
-	$socid = $user->societe_id;
51
+    unset($_GET["action"]);
52
+    $action='';
53
+    $socid = $user->societe_id;
54 54
 }
55 55
 $result = restrictedArea($user, 'contrat', $id);
56 56
 
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 $object->fetch($id, $ref);
71 71
 if ($object->id > 0)
72 72
 {
73
-	$object->fetch_thirdparty();
73
+    $object->fetch_thirdparty();
74 74
 }
75 75
 
76 76
 $upload_dir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($object->ref);
@@ -98,84 +98,84 @@  discard block
 block discarded – undo
98 98
 
99 99
 if ($object->id)
100 100
 {
101
-	$head=contract_prepare_head($object);
101
+    $head=contract_prepare_head($object);
102 102
 
103
-	dol_fiche_head($head, 'documents', $langs->trans("Contract"), -1, 'contract');
103
+    dol_fiche_head($head, 'documents', $langs->trans("Contract"), -1, 'contract');
104 104
 
105 105
 
106
-	// Build file list
107
-	$filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
108
-	$totalsize=0;
109
-	foreach($filearray as $key => $file)
110
-	{
111
-		$totalsize+=$file['size'];
112
-	}
106
+    // Build file list
107
+    $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
108
+    $totalsize=0;
109
+    foreach($filearray as $key => $file)
110
+    {
111
+        $totalsize+=$file['size'];
112
+    }
113 113
 
114 114
 
115
-	// Contract card
115
+    // Contract card
116 116
 
117
-	$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
117
+    $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
118 118
 
119 119
 
120
-	$morehtmlref='';
121
-	//if (! empty($modCodeContract->code_auto)) {
122
-	$morehtmlref.=$object->ref;
123
-	/*} else {
120
+    $morehtmlref='';
121
+    //if (! empty($modCodeContract->code_auto)) {
122
+    $morehtmlref.=$object->ref;
123
+    /*} else {
124 124
 	 $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3);
125 125
 	$morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2);
126 126
 	}*/
127 127
 
128
-	$morehtmlref.='<div class="refidno">';
129
-	// Ref customer
130
-	$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
131
-	$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1);
132
-	// Ref supplier
133
-	$morehtmlref.='<br>';
134
-	$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
135
-	$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1);
136
-	// Thirdparty
137
-	$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
138
-	// Project
139
-	if (! empty($conf->projet->enabled))
140
-	{
141
-		$langs->load("projects");
142
-		$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
143
-		if ($user->rights->contrat->creer)
144
-		{
145
-			if ($action != 'classify')
146
-				//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
147
-				$morehtmlref.=' : ';
148
-			if ($action == 'classify') {
149
-				//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
150
-				$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
151
-				$morehtmlref.='<input type="hidden" name="action" value="classin">';
152
-				$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
153
-				$morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
154
-				$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
155
-				$morehtmlref.='</form>';
156
-			} else {
157
-				$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
158
-			}
159
-		} else {
160
-			if (! empty($object->fk_project)) {
161
-				$proj = new Project($db);
162
-				$proj->fetch($object->fk_project);
163
-				$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
164
-				$morehtmlref.=$proj->ref;
165
-				$morehtmlref.='</a>';
166
-			} else {
167
-				$morehtmlref.='';
168
-			}
169
-		}
170
-	}
171
-	$morehtmlref.='</div>';
172
-
173
-
174
-	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
175
-
176
-
177
-	print '<div class="fichecenter">';
178
-	print '<div class="underbanner clearboth"></div>';
128
+    $morehtmlref.='<div class="refidno">';
129
+    // Ref customer
130
+    $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
131
+    $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1);
132
+    // Ref supplier
133
+    $morehtmlref.='<br>';
134
+    $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
135
+    $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1);
136
+    // Thirdparty
137
+    $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
138
+    // Project
139
+    if (! empty($conf->projet->enabled))
140
+    {
141
+        $langs->load("projects");
142
+        $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
143
+        if ($user->rights->contrat->creer)
144
+        {
145
+            if ($action != 'classify')
146
+                //$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
147
+                $morehtmlref.=' : ';
148
+            if ($action == 'classify') {
149
+                //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
150
+                $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
151
+                $morehtmlref.='<input type="hidden" name="action" value="classin">';
152
+                $morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
153
+                $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
154
+                $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
155
+                $morehtmlref.='</form>';
156
+            } else {
157
+                $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
158
+            }
159
+        } else {
160
+            if (! empty($object->fk_project)) {
161
+                $proj = new Project($db);
162
+                $proj->fetch($object->fk_project);
163
+                $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
164
+                $morehtmlref.=$proj->ref;
165
+                $morehtmlref.='</a>';
166
+            } else {
167
+                $morehtmlref.='';
168
+            }
169
+        }
170
+    }
171
+    $morehtmlref.='</div>';
172
+
173
+
174
+    dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
175
+
176
+
177
+    print '<div class="fichecenter">';
178
+    print '<div class="underbanner clearboth"></div>';
179 179
 
180 180
 
181 181
     print '<table class="border" width="100%">';
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 }
196 196
 else
197 197
 {
198
-	print $langs->trans("ErrorUnknown");
198
+    print $langs->trans("ErrorUnknown");
199 199
 }
200 200
 
201 201
 
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -33,37 +33,37 @@  discard block
 block discarded – undo
33 33
 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
34 34
 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
35 35
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
36
-if (! empty($conf->projet->enabled)) {
37
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
36
+if (!empty($conf->projet->enabled)) {
37
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
38 38
 }
39 39
 
40 40
 // Load translation files required by the page
41 41
 $langs->loadLangs(array('other', 'products', 'contracts'));
42 42
 
43
-$action		= GETPOST('action','alpha');
44
-$confirm	= GETPOST('confirm','alpha');
45
-$id			= GETPOST('id','int');
46
-$ref		= GETPOST('ref','alpha');
43
+$action		= GETPOST('action', 'alpha');
44
+$confirm	= GETPOST('confirm', 'alpha');
45
+$id			= GETPOST('id', 'int');
46
+$ref		= GETPOST('ref', 'alpha');
47 47
 
48 48
 // Security check
49 49
 if ($user->societe_id > 0)
50 50
 {
51 51
 	unset($_GET["action"]);
52
-	$action='';
52
+	$action = '';
53 53
 	$socid = $user->societe_id;
54 54
 }
55 55
 $result = restrictedArea($user, 'contrat', $id);
56 56
 
57 57
 // Get parameters
58
-$sortfield = GETPOST("sortfield",'alpha');
59
-$sortorder = GETPOST("sortorder",'alpha');
60
-$page = GETPOST("page",'int');
58
+$sortfield = GETPOST("sortfield", 'alpha');
59
+$sortorder = GETPOST("sortorder", 'alpha');
60
+$page = GETPOST("page", 'int');
61 61
 if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
62 62
 $offset = $conf->liste_limit * $page;
63 63
 $pageprev = $page - 1;
64 64
 $pagenext = $page + 1;
65
-if (! $sortorder) $sortorder="ASC";
66
-if (! $sortfield) $sortfield="name";
65
+if (!$sortorder) $sortorder = "ASC";
66
+if (!$sortfield) $sortfield = "name";
67 67
 
68 68
 
69 69
 $object = new Contrat($db);
@@ -74,17 +74,17 @@  discard block
 block discarded – undo
74 74
 }
75 75
 
76 76
 $upload_dir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($object->ref);
77
-$modulepart='contract';
77
+$modulepart = 'contract';
78 78
 
79 79
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
80
-$hookmanager->initHooks(array('contractcard','globalcard'));
80
+$hookmanager->initHooks(array('contractcard', 'globalcard'));
81 81
 
82 82
 
83 83
 /*
84 84
  * Actions
85 85
  */
86 86
 
87
-include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
87
+include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
88 88
 
89 89
 
90 90
 /*
@@ -93,82 +93,82 @@  discard block
 block discarded – undo
93 93
 
94 94
 $form = new Form($db);
95 95
 
96
-llxHeader('',$langs->trans("Contract"),"");
96
+llxHeader('', $langs->trans("Contract"), "");
97 97
 
98 98
 
99 99
 if ($object->id)
100 100
 {
101
-	$head=contract_prepare_head($object);
101
+	$head = contract_prepare_head($object);
102 102
 
103 103
 	dol_fiche_head($head, 'documents', $langs->trans("Contract"), -1, 'contract');
104 104
 
105 105
 
106 106
 	// Build file list
107
-	$filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
108
-	$totalsize=0;
109
-	foreach($filearray as $key => $file)
107
+	$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
108
+	$totalsize = 0;
109
+	foreach ($filearray as $key => $file)
110 110
 	{
111
-		$totalsize+=$file['size'];
111
+		$totalsize += $file['size'];
112 112
 	}
113 113
 
114 114
 
115 115
 	// Contract card
116 116
 
117
-	$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
117
+	$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
118 118
 
119 119
 
120
-	$morehtmlref='';
120
+	$morehtmlref = '';
121 121
 	//if (! empty($modCodeContract->code_auto)) {
122
-	$morehtmlref.=$object->ref;
122
+	$morehtmlref .= $object->ref;
123 123
 	/*} else {
124 124
 	 $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3);
125 125
 	$morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2);
126 126
 	}*/
127 127
 
128
-	$morehtmlref.='<div class="refidno">';
128
+	$morehtmlref .= '<div class="refidno">';
129 129
 	// Ref customer
130
-	$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
131
-	$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1);
130
+	$morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
131
+	$morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1);
132 132
 	// Ref supplier
133
-	$morehtmlref.='<br>';
134
-	$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
135
-	$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1);
133
+	$morehtmlref .= '<br>';
134
+	$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
135
+	$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1);
136 136
 	// Thirdparty
137
-	$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
137
+	$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
138 138
 	// Project
139
-	if (! empty($conf->projet->enabled))
139
+	if (!empty($conf->projet->enabled))
140 140
 	{
141 141
 		$langs->load("projects");
142
-		$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
142
+		$morehtmlref .= '<br>'.$langs->trans('Project').' ';
143 143
 		if ($user->rights->contrat->creer)
144 144
 		{
145 145
 			if ($action != 'classify')
146 146
 				//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
147
-				$morehtmlref.=' : ';
147
+				$morehtmlref .= ' : ';
148 148
 			if ($action == 'classify') {
149 149
 				//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
150
-				$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
151
-				$morehtmlref.='<input type="hidden" name="action" value="classin">';
152
-				$morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
153
-				$morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
154
-				$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
155
-				$morehtmlref.='</form>';
150
+				$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
151
+				$morehtmlref .= '<input type="hidden" name="action" value="classin">';
152
+				$morehtmlref .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
153
+				$morehtmlref .= $formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
154
+				$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
155
+				$morehtmlref .= '</form>';
156 156
 			} else {
157
-				$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
157
+				$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
158 158
 			}
159 159
 		} else {
160
-			if (! empty($object->fk_project)) {
160
+			if (!empty($object->fk_project)) {
161 161
 				$proj = new Project($db);
162 162
 				$proj->fetch($object->fk_project);
163
-				$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
164
-				$morehtmlref.=$proj->ref;
165
-				$morehtmlref.='</a>';
163
+				$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
164
+				$morehtmlref .= $proj->ref;
165
+				$morehtmlref .= '</a>';
166 166
 			} else {
167
-				$morehtmlref.='';
167
+				$morehtmlref .= '';
168 168
 			}
169 169
 		}
170 170
 	}
171
-	$morehtmlref.='</div>';
171
+	$morehtmlref .= '</div>';
172 172
 
173 173
 
174 174
 	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 
181 181
     print '<table class="border" width="100%">';
182 182
     print '<tr><td class="titlefield">'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>';
183
-    print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.dol_print_size($totalsize,1,1).'</td></tr>';
183
+    print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.dol_print_size($totalsize, 1, 1).'</td></tr>';
184 184
     print '</table>';
185 185
 
186 186
     print '</div>';
@@ -190,8 +190,8 @@  discard block
 block discarded – undo
190 190
     $modulepart = 'contract';
191 191
     $permission = $user->rights->contrat->creer;
192 192
     $permtoedit = $user->rights->contrat->creer;
193
-    $param = '&id=' . $object->id;
194
-    include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
193
+    $param = '&id='.$object->id;
194
+    include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
195 195
 }
196 196
 else
197 197
 {
Please login to merge, or discard this patch.
Braces   +10 added lines, -6 removed lines patch added patch discarded remove patch
@@ -62,8 +62,12 @@  discard block
 block discarded – undo
62 62
 $offset = $conf->liste_limit * $page;
63 63
 $pageprev = $page - 1;
64 64
 $pagenext = $page + 1;
65
-if (! $sortorder) $sortorder="ASC";
66
-if (! $sortfield) $sortfield="name";
65
+if (! $sortorder) {
66
+    $sortorder="ASC";
67
+}
68
+if (! $sortfield) {
69
+    $sortfield="name";
70
+}
67 71
 
68 72
 
69 73
 $object = new Contrat($db);
@@ -142,9 +146,10 @@  discard block
 block discarded – undo
142 146
 		$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
143 147
 		if ($user->rights->contrat->creer)
144 148
 		{
145
-			if ($action != 'classify')
146
-				//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
149
+			if ($action != 'classify') {
150
+							//$morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
147 151
 				$morehtmlref.=' : ';
152
+			}
148 153
 			if ($action == 'classify') {
149 154
 				//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
150 155
 				$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
@@ -192,8 +197,7 @@  discard block
 block discarded – undo
192 197
     $permtoedit = $user->rights->contrat->creer;
193 198
     $param = '&id=' . $object->id;
194 199
     include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
195
-}
196
-else
200
+} else
197 201
 {
198 202
 	print $langs->trans("ErrorUnknown");
199 203
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/contrat/services_list.php 3 patches
Indentation   +320 added lines, -320 removed lines patch added patch discarded remove patch
@@ -93,20 +93,20 @@  discard block
 block discarded – undo
93 93
 
94 94
 if ($search_status != '')
95 95
 {
96
-	$tmp=explode('&', $search_status);
97
-	$mode=$tmp[0];
98
-	if (empty($tmp[1])) $filter='';
99
-	else
100
-	{
101
-		if ($tmp[1] == 'filter=notexpired') $filter='notexpired';
102
-		if ($tmp[1] == 'filter=expired') $filter='expired';
103
-	}
96
+    $tmp=explode('&', $search_status);
97
+    $mode=$tmp[0];
98
+    if (empty($tmp[1])) $filter='';
99
+    else
100
+    {
101
+        if ($tmp[1] == 'filter=notexpired') $filter='notexpired';
102
+        if ($tmp[1] == 'filter=expired') $filter='expired';
103
+    }
104 104
 }
105 105
 else
106 106
 {
107
-	$search_status = $mode;
108
-	if ($filter == 'expired') $search_status.='&filter=expired';
109
-	if ($filter == 'notexpired') $search_status.='&filter=notexpired';
107
+    $search_status = $mode;
108
+    if ($filter == 'expired') $search_status.='&filter=expired';
109
+    if ($filter == 'notexpired') $search_status.='&filter=notexpired';
110 110
 }
111 111
 
112 112
 $staticcontrat=new Contrat($db);
@@ -114,29 +114,29 @@  discard block
 block discarded – undo
114 114
 $companystatic=new Societe($db);
115 115
 
116 116
 $arrayfields=array(
117
-	'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80),
118
-	'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80),
119
-	'cd.qty'=>array('label'=>$langs->trans("Qty"), 'checked'=>0, 'position'=>100),
120
-	'cd.total_ht'=>array('label'=>$langs->trans("TotalHT"), 'checked'=>0, 'position'=>100),
121
-	'cd.total_tva'=>array('label'=>$langs->trans("TotalVAT"), 'checked'=>0, 'position'=>100),
122
-	'cd.tva_tx'=>array('label'=>$langs->trans("VAT"), 'checked'=>0, 'position'=>100),
123
-	'cd.subprice'=>array('label'=>$langs->trans("PriceUHT"), 'checked'=>0, 'position'=>100),
124
-	's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>100),
125
-	'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0")),
126
-	'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0)),
127
-	'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5)),
128
-	'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5)),
129
-	'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1),
130
-	//'cd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500),
131
-	'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500)
117
+    'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80),
118
+    'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80),
119
+    'cd.qty'=>array('label'=>$langs->trans("Qty"), 'checked'=>0, 'position'=>100),
120
+    'cd.total_ht'=>array('label'=>$langs->trans("TotalHT"), 'checked'=>0, 'position'=>100),
121
+    'cd.total_tva'=>array('label'=>$langs->trans("TotalVAT"), 'checked'=>0, 'position'=>100),
122
+    'cd.tva_tx'=>array('label'=>$langs->trans("VAT"), 'checked'=>0, 'position'=>100),
123
+    'cd.subprice'=>array('label'=>$langs->trans("PriceUHT"), 'checked'=>0, 'position'=>100),
124
+    's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>100),
125
+    'cd.date_ouverture_prevue'=>array('label'=>$langs->trans("DateStartPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode == "0")),
126
+    'cd.date_ouverture'=>array('label'=>$langs->trans("DateStartRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode > 0)),
127
+    'cd.date_fin_validite'=>array('label'=>$langs->trans("DateEndPlannedShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode < 5)),
128
+    'cd.date_cloture'=>array('label'=>$langs->trans("DateEndRealShort"), 'checked'=>(($mode == "" || $mode == -1) || $mode >= 5)),
129
+    'status'=>array('label'=>$langs->trans("Status"), 'checked'=>1),
130
+    //'cd.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500),
131
+    'cd.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500)
132 132
 );
133 133
 // Extra fields
134 134
 if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
135 135
 {
136
-	foreach($extrafields->attribute_label as $key => $val)
137
-	{
138
-		if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key]));
139
-	}
136
+    foreach($extrafields->attribute_label as $key => $val)
137
+    {
138
+        if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key]));
139
+    }
140 140
 }
141 141
 
142 142
 
@@ -155,37 +155,37 @@  discard block
 block discarded – undo
155 155
 
156 156
 if (empty($reshook))
157 157
 {
158
-	// Selection of new fields
159
-	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
160
-
161
-	if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers
162
-	{
163
-   		$search_product_category=0;
164
-		$search_name="";
165
-		$search_contract="";
166
-		$search_service="";
167
-		$search_status=-1;
168
-		$opouvertureprevuemonth="";
169
-		$opouvertureprevueday="";
170
-		$opouvertureprevueyear="";
171
-		$filter_opouvertureprevue="";
172
-		$op1month="";
173
-		$op1day="";
174
-		$op1year="";
175
-		$filter_op1="";
176
-		$op2month="";
177
-		$op2day="";
178
-		$op2year="";
179
-		$filter_op2="";
180
-		$opcloturemonth="";
181
-		$opclotureday="";
182
-		$opclotureyear="";
183
-		$filter_opcloture="";
184
-		$mode='';
185
-		$filter='';
186
-		$toselect='';
187
-		$search_array_options=array();
188
-	}
158
+    // Selection of new fields
159
+    include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
160
+
161
+    if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers
162
+    {
163
+            $search_product_category=0;
164
+        $search_name="";
165
+        $search_contract="";
166
+        $search_service="";
167
+        $search_status=-1;
168
+        $opouvertureprevuemonth="";
169
+        $opouvertureprevueday="";
170
+        $opouvertureprevueyear="";
171
+        $filter_opouvertureprevue="";
172
+        $op1month="";
173
+        $op1day="";
174
+        $op1year="";
175
+        $filter_op1="";
176
+        $op2month="";
177
+        $op2day="";
178
+        $op2year="";
179
+        $filter_op2="";
180
+        $opcloturemonth="";
181
+        $opclotureday="";
182
+        $opclotureyear="";
183
+        $filter_opcloture="";
184
+        $mode='';
185
+        $filter='';
186
+        $toselect='';
187
+        $search_array_options=array();
188
+    }
189 189
 }
190 190
 
191 191
 
@@ -255,13 +255,13 @@  discard block
 block discarded – undo
255 255
 $nbtotalofrecords = '';
256 256
 if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
257 257
 {
258
-	$result = $db->query($sql);
259
-	$nbtotalofrecords = $db->num_rows($result);
260
-	if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
261
-	{
262
-		$page = 0;
263
-		$offset = 0;
264
-	}
258
+    $result = $db->query($sql);
259
+    $nbtotalofrecords = $db->num_rows($result);
260
+    if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
261
+    {
262
+        $page = 0;
263
+        $offset = 0;
264
+    }
265 265
 }
266 266
 
267 267
 $sql .= $db->plimit($limit + 1, $offset);
@@ -271,8 +271,8 @@  discard block
 block discarded – undo
271 271
 $resql=$db->query($sql);
272 272
 if (! $resql)
273 273
 {
274
-	dol_print_error($db);
275
-	exit;
274
+    dol_print_error($db);
275
+    exit;
276 276
 }
277 277
 
278 278
 $num = $db->num_rows($resql);
@@ -310,8 +310,8 @@  discard block
 block discarded – undo
310 310
 
311 311
 // List of mass actions available
312 312
 $arrayofmassactions =  array(
313
-	//'presend'=>$langs->trans("SendByMail"),
314
-	//'builddoc'=>$langs->trans("PDFMerge"),
313
+    //'presend'=>$langs->trans("SendByMail"),
314
+    //'builddoc'=>$langs->trans("PDFMerge"),
315 315
 );
316 316
 //if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete");
317 317
 //if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
@@ -336,8 +336,8 @@  discard block
 block discarded – undo
336 336
 
337 337
 if ($sall)
338 338
 {
339
-	foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
340
-	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall).'</div>';
339
+    foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
340
+    print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall).'</div>';
341 341
 }
342 342
 
343 343
 $morefilter = '';
@@ -345,12 +345,12 @@  discard block
 block discarded – undo
345 345
 // If the user can view categories of products
346 346
 if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire))
347 347
 {
348
-	include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
349
-	$moreforfilter.='<div class="divsearchfield">';
350
-	$moreforfilter.=$langs->trans('IncludingProductWithTag'). ': ';
351
-	$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1);
352
-	$moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
353
-	$moreforfilter.='</div>';
348
+    include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
349
+    $moreforfilter.='<div class="divsearchfield">';
350
+    $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': ';
351
+    $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1);
352
+    $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
353
+    $moreforfilter.='</div>';
354 354
 }
355 355
 
356 356
 $parameters=array();
@@ -361,9 +361,9 @@  discard block
 block discarded – undo
361 361
 
362 362
 if (! empty($moreforfilter))
363 363
 {
364
-	print '<div class="liste_titre liste_titre_bydiv centpercent">';
365
-	print $moreforfilter;
366
-	print '</div>';
364
+    print '<div class="liste_titre liste_titre_bydiv centpercent">';
365
+    print $moreforfilter;
366
+    print '</div>';
367 367
 }
368 368
 
369 369
 $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
@@ -401,93 +401,93 @@  discard block
 block discarded – undo
401 401
 print '<tr class="liste_titre">';
402 402
 if (! empty($arrayfields['c.ref']['checked']))
403 403
 {
404
-	print '<td class="liste_titre">';
405
-	print '<input type="hidden" name="filter" value="'.$filter.'">';
406
-	print '<input type="hidden" name="mode" value="'.$mode.'">';
407
-	print '<input type="text" class="flat" size="3" name="search_contract" value="'.dol_escape_htmltag($search_contract).'">';
408
-	print '</td>';
404
+    print '<td class="liste_titre">';
405
+    print '<input type="hidden" name="filter" value="'.$filter.'">';
406
+    print '<input type="hidden" name="mode" value="'.$mode.'">';
407
+    print '<input type="text" class="flat" size="3" name="search_contract" value="'.dol_escape_htmltag($search_contract).'">';
408
+    print '</td>';
409 409
 }
410 410
 // Service label
411 411
 if (! empty($arrayfields['p.description']['checked']))
412 412
 {
413
-	print '<td class="liste_titre">';
414
-	print '<input type="text" class="flat maxwidth100" name="search_service" value="'.dol_escape_htmltag($search_service).'">';
415
-	print '</td>';
413
+    print '<td class="liste_titre">';
414
+    print '<input type="text" class="flat maxwidth100" name="search_service" value="'.dol_escape_htmltag($search_service).'">';
415
+    print '</td>';
416 416
 }
417 417
 // detail lines
418 418
 if (! empty($arrayfields['cd.qty']['checked']))
419 419
 {
420
-	print '<td class="liste_titre">';
421
-	print '</td>';
420
+    print '<td class="liste_titre">';
421
+    print '</td>';
422 422
 }
423 423
 if (! empty($arrayfields['cd.total_ht']['checked']))
424 424
 {
425
-	print '<td class="liste_titre">';
426
-	print '</td>';
425
+    print '<td class="liste_titre">';
426
+    print '</td>';
427 427
 }
428 428
 if (! empty($arrayfields['cd.total_tva']['checked']))
429 429
 {
430
-	print '<td class="liste_titre">';
431
-	print '</td>';
430
+    print '<td class="liste_titre">';
431
+    print '</td>';
432 432
 }
433 433
 if (! empty($arrayfields['cd.tva_tx']['checked']))
434 434
 {
435
-	print '<td class="liste_titre">';
436
-	print '</td>';
435
+    print '<td class="liste_titre">';
436
+    print '</td>';
437 437
 }
438 438
 if (! empty($arrayfields['cd.subprice']['checked']))
439 439
 {
440
-	print '<td class="liste_titre">';
441
-	print '</td>';
440
+    print '<td class="liste_titre">';
441
+    print '</td>';
442 442
 }
443 443
 // Third party
444 444
 if (! empty($arrayfields['s.nom']['checked']))
445 445
 {
446
-	print '<td class="liste_titre">';
447
-	print '<input type="text" class="flat maxwidth100" name="search_name" value="'.dol_escape_htmltag($search_name).'">';
448
-	print '</td>';
446
+    print '<td class="liste_titre">';
447
+    print '<input type="text" class="flat maxwidth100" name="search_name" value="'.dol_escape_htmltag($search_name).'">';
448
+    print '</td>';
449 449
 }
450 450
 
451 451
 
452 452
 if (! empty($arrayfields['cd.date_ouverture_prevue']['checked']))
453 453
 {
454
-	print '<td class="liste_titre" align="center">';
455
-	$arrayofoperators=array('<'=>'<','>'=>'>');
456
-	print $form->selectarray('filter_opouvertureprevue',$arrayofoperators,$filter_opouvertureprevue,1);
457
-	print ' ';
458
-	$filter_dateouvertureprevue=dol_mktime(0,0,0,$opouvertureprevuemonth,$opouvertureprevueday,$opouvertureprevueyear);
459
-	print $form->selectDate($filter_dateouvertureprevue, 'opouvertureprevue', 0, 0, 1, '', 1, 0);
460
-	print '</td>';
454
+    print '<td class="liste_titre" align="center">';
455
+    $arrayofoperators=array('<'=>'<','>'=>'>');
456
+    print $form->selectarray('filter_opouvertureprevue',$arrayofoperators,$filter_opouvertureprevue,1);
457
+    print ' ';
458
+    $filter_dateouvertureprevue=dol_mktime(0,0,0,$opouvertureprevuemonth,$opouvertureprevueday,$opouvertureprevueyear);
459
+    print $form->selectDate($filter_dateouvertureprevue, 'opouvertureprevue', 0, 0, 1, '', 1, 0);
460
+    print '</td>';
461 461
 }
462 462
 if (! empty($arrayfields['cd.date_ouverture']['checked']))
463 463
 {
464
-	print '<td class="liste_titre" align="center">';
465
-	$arrayofoperators=array('<'=>'<','>'=>'>');
466
-	print $form->selectarray('filter_op1',$arrayofoperators,$filter_op1,1);
467
-	print ' ';
468
-	$filter_date1=dol_mktime(0,0,0,$op1month,$op1day,$op1year);
469
-	print $form->selectDate($filter_date1, 'op1', 0, 0, 1, '', 1, 0);
470
-	print '</td>';
464
+    print '<td class="liste_titre" align="center">';
465
+    $arrayofoperators=array('<'=>'<','>'=>'>');
466
+    print $form->selectarray('filter_op1',$arrayofoperators,$filter_op1,1);
467
+    print ' ';
468
+    $filter_date1=dol_mktime(0,0,0,$op1month,$op1day,$op1year);
469
+    print $form->selectDate($filter_date1, 'op1', 0, 0, 1, '', 1, 0);
470
+    print '</td>';
471 471
 }
472 472
 if (! empty($arrayfields['cd.date_fin_validite']['checked']))
473 473
 {
474
-	print '<td class="liste_titre" align="center">';
475
-	$arrayofoperators=array('<'=>'<','>'=>'>');
476
-	print $form->selectarray('filter_op2',$arrayofoperators,$filter_op2,1);
477
-	print ' ';
478
-	$filter_date2=dol_mktime(0,0,0,$op2month,$op2day,$op2year);
479
-	print $form->selectDate($filter_date2, 'op2', 0, 0, 1, '', 1, 0);
480
-	print '</td>';
474
+    print '<td class="liste_titre" align="center">';
475
+    $arrayofoperators=array('<'=>'<','>'=>'>');
476
+    print $form->selectarray('filter_op2',$arrayofoperators,$filter_op2,1);
477
+    print ' ';
478
+    $filter_date2=dol_mktime(0,0,0,$op2month,$op2day,$op2year);
479
+    print $form->selectDate($filter_date2, 'op2', 0, 0, 1, '', 1, 0);
480
+    print '</td>';
481 481
 }
482 482
 if (! empty($arrayfields['cd.date_cloture']['checked']))
483 483
 {
484
-	print '<td class="liste_titre" align="center">';
485
-	$arrayofoperators=array('<'=>'<','>'=>'>');
486
-	print $form->selectarray('filter_opcloture',$arrayofoperators,$filter_opcloture,1);
487
-	print ' ';
488
-	$filter_date_cloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear);
489
-	print $form->selectDate($filter_date_cloture, 'opcloture', 0, 0, 1, '', 1, 0);
490
-	print '</td>';
484
+    print '<td class="liste_titre" align="center">';
485
+    $arrayofoperators=array('<'=>'<','>'=>'>');
486
+    print $form->selectarray('filter_opcloture',$arrayofoperators,$filter_opcloture,1);
487
+    print ' ';
488
+    $filter_date_cloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear);
489
+    print $form->selectDate($filter_date_cloture, 'opcloture', 0, 0, 1, '', 1, 0);
490
+    print '</td>';
491 491
 }
492 492
 // Extra fields
493 493
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
@@ -498,29 +498,29 @@  discard block
 block discarded – undo
498 498
 print $hookmanager->resPrint;
499 499
 if (! empty($arrayfields['cd.datec']['checked']))
500 500
 {
501
-	// Date creation
502
-	print '<td class="liste_titre">';
503
-	print '</td>';
501
+    // Date creation
502
+    print '<td class="liste_titre">';
503
+    print '</td>';
504 504
 }
505 505
 if (! empty($arrayfields['cd.tms']['checked']))
506 506
 {
507
-	// Date modification
508
-	print '<td class="liste_titre">';
509
-	print '</td>';
507
+    // Date modification
508
+    print '<td class="liste_titre">';
509
+    print '</td>';
510 510
 }
511 511
 if (! empty($arrayfields['status']['checked']))
512 512
 {
513
-	// Status
514
-	print '<td class="liste_titre" align="right">';
515
-	$arrayofstatus=array(
516
-		'0'=>$langs->trans("ServiceStatusInitial"),
517
-		'4'=>$langs->trans("ServiceStatusRunning"),
518
-		'4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"),
519
-		'4&filter=expired'=>$langs->trans("ServiceStatusLate"),
520
-		'5'=>$langs->trans("ServiceStatusClosed")
521
-	);
522
-	print $form->selectarray('search_status', $arrayofstatus, (strstr($search_status, ',')?-1:$search_status), 1, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone');
523
-	print '</td>';
513
+    // Status
514
+    print '<td class="liste_titre" align="right">';
515
+    $arrayofstatus=array(
516
+        '0'=>$langs->trans("ServiceStatusInitial"),
517
+        '4'=>$langs->trans("ServiceStatusRunning"),
518
+        '4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"),
519
+        '4&filter=expired'=>$langs->trans("ServiceStatusLate"),
520
+        '5'=>$langs->trans("ServiceStatusClosed")
521
+    );
522
+    print $form->selectarray('search_status', $arrayofstatus, (strstr($search_status, ',')?-1:$search_status), 1, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone');
523
+    print '</td>';
524 524
 }
525 525
 // Action column
526 526
 print '<td class="liste_titre" align="right">';
@@ -536,74 +536,74 @@  discard block
 block discarded – undo
536 536
 $totalarray=array();
537 537
 while ($i < min($num,$limit))
538 538
 {
539
-	$obj = $db->fetch_object($resql);
539
+    $obj = $db->fetch_object($resql);
540 540
 
541
-	$contractstatic->id=$obj->cid;
542
-	$contractstatic->ref=$obj->ref?$obj->ref:$obj->cid;
541
+    $contractstatic->id=$obj->cid;
542
+    $contractstatic->ref=$obj->ref?$obj->ref:$obj->cid;
543 543
 
544
-	$companystatic->id=$obj->socid;
545
-	$companystatic->name=$obj->name;
546
-	$companystatic->email=$obj->email;
547
-	$companystatic->client=$obj->client;
548
-	$companystatic->fournisseur=$obj->fournisseur;
544
+    $companystatic->id=$obj->socid;
545
+    $companystatic->name=$obj->name;
546
+    $companystatic->email=$obj->email;
547
+    $companystatic->client=$obj->client;
548
+    $companystatic->fournisseur=$obj->fournisseur;
549 549
 
550
-	print '<tr class="oddeven">';
550
+    print '<tr class="oddeven">';
551 551
 
552
-	// Ref
553
-	if (! empty($arrayfields['c.ref']['checked']))
554
-	{
555
-		print '<td>';
556
-		print $contractstatic->getNomUrl(1,16);
557
-		print '</td>';
552
+    // Ref
553
+    if (! empty($arrayfields['c.ref']['checked']))
554
+    {
555
+        print '<td>';
556
+        print $contractstatic->getNomUrl(1,16);
557
+        print '</td>';
558 558
         if (! $i) $totalarray['nbfield']++;
559
-	}
560
-	// Service
561
-	if (! empty($arrayfields['p.description']['checked']))
562
-	{
563
-		print '<td>';
564
-		if ($obj->pid > 0)
565
-		{
566
-			$productstatic->id=$obj->pid;
567
-			$productstatic->type=$obj->ptype;
568
-			$productstatic->ref=$obj->pref;
569
-			$productstatic->entity=$obj->pentity;
570
-			print $productstatic->getNomUrl(1,'',24);
571
-			print $obj->label?' - '.dol_trunc($obj->label,16):'';
572
-			if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description);
573
-		}
574
-		else
575
-		{
576
-			if ($obj->type == 0) print img_object($obj->description,'product').' '.dol_trunc($obj->description,24);
577
-			if ($obj->type == 1) print img_object($obj->description,'service').' '.dol_trunc($obj->description,24);
578
-		}
579
-		print '</td>';
559
+    }
560
+    // Service
561
+    if (! empty($arrayfields['p.description']['checked']))
562
+    {
563
+        print '<td>';
564
+        if ($obj->pid > 0)
565
+        {
566
+            $productstatic->id=$obj->pid;
567
+            $productstatic->type=$obj->ptype;
568
+            $productstatic->ref=$obj->pref;
569
+            $productstatic->entity=$obj->pentity;
570
+            print $productstatic->getNomUrl(1,'',24);
571
+            print $obj->label?' - '.dol_trunc($obj->label,16):'';
572
+            if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description);
573
+        }
574
+        else
575
+        {
576
+            if ($obj->type == 0) print img_object($obj->description,'product').' '.dol_trunc($obj->description,24);
577
+            if ($obj->type == 1) print img_object($obj->description,'service').' '.dol_trunc($obj->description,24);
578
+        }
579
+        print '</td>';
580 580
         if (! $i) $totalarray['nbfield']++;
581
-	}
581
+    }
582 582
 
583
-	if (! empty($arrayfields['cd.qty']['checked']))
584
-	{
585
-		print '<td>';
586
-		print $obj->qty;
587
-		print '</td>';
583
+    if (! empty($arrayfields['cd.qty']['checked']))
584
+    {
585
+        print '<td>';
586
+        print $obj->qty;
587
+        print '</td>';
588 588
         if (! $i) $totalarray['nbfield']++;
589
-	}
590
-	if (! empty($arrayfields['cd.total_ht']['checked']))
591
-	{
592
-		print '<td align="right">';
593
-		print price($obj->total_ht);
594
-		print '</td>';
595
-		$totalarray['totalht'] += $obj->total_ht;
589
+    }
590
+    if (! empty($arrayfields['cd.total_ht']['checked']))
591
+    {
592
+        print '<td align="right">';
593
+        print price($obj->total_ht);
594
+        print '</td>';
595
+        $totalarray['totalht'] += $obj->total_ht;
596 596
         if (! $i) {
597 597
             $totalarray['displaytotalline']++;
598 598
             $totalarray['nbfield']++;
599 599
             $totalarray['totalhtfield']=$totalarray['nbfield'];
600 600
         }
601 601
     }
602
-	if (! empty($arrayfields['cd.total_tva']['checked']))
603
-	{
604
-		print '<td align="right">';
605
-		print price($obj->total_tva);
606
-		print '</td>';
602
+    if (! empty($arrayfields['cd.total_tva']['checked']))
603
+    {
604
+        print '<td align="right">';
605
+        print price($obj->total_tva);
606
+        print '</td>';
607 607
         $totalarray['totalvat'] += $obj->total_tva;
608 608
         if (! $i) {
609 609
             $totalarray['nbfield']++;
@@ -611,136 +611,136 @@  discard block
 block discarded – undo
611 611
             $totalarray['displaytotalline']++;
612 612
         }
613 613
     }
614
-	if (! empty($arrayfields['cd.tva_tx']['checked']))
615
-	{
616
-		print '<td align="right">';
617
-		print price2num($obj->tva_tx).'%';
618
-		print '</td>';
614
+    if (! empty($arrayfields['cd.tva_tx']['checked']))
615
+    {
616
+        print '<td align="right">';
617
+        print price2num($obj->tva_tx).'%';
618
+        print '</td>';
619 619
         if (! $i) $totalarray['nbfield']++;
620
-	}
621
-	if (! empty($arrayfields['cd.subprice']['checked']))
622
-	{
623
-		print '<td align="right">';
624
-		print price($obj->subprice);
625
-		print '</td>';
620
+    }
621
+    if (! empty($arrayfields['cd.subprice']['checked']))
622
+    {
623
+        print '<td align="right">';
624
+        print price($obj->subprice);
625
+        print '</td>';
626 626
         if (! $i) $totalarray['nbfield']++;
627
-	}
627
+    }
628 628
 
629 629
 
630
-	// Third party
631
-	if (! empty($arrayfields['s.nom']['checked']))
632
-	{
633
-		print '<td>';
634
-		print $companystatic->getNomUrl(1,'customer',28);
635
-		print '</td>';
630
+    // Third party
631
+    if (! empty($arrayfields['s.nom']['checked']))
632
+    {
633
+        print '<td>';
634
+        print $companystatic->getNomUrl(1,'customer',28);
635
+        print '</td>';
636 636
         if (! $i) $totalarray['nbfield']++;
637
-	}
638
-
639
-	// Start date
640
-	if (! empty($arrayfields['cd.date_ouverture_prevue']['checked']))
641
-	{
642
-		print '<td align="center">';
643
-		print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour'):'&nbsp;');
644
-		if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0)
645
-		print ' '.img_picto($langs->trans("Late"),"warning");
646
-		else print '&nbsp;&nbsp;&nbsp;&nbsp;';
647
-		print '</td>';
637
+    }
638
+
639
+    // Start date
640
+    if (! empty($arrayfields['cd.date_ouverture_prevue']['checked']))
641
+    {
642
+        print '<td align="center">';
643
+        print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour'):'&nbsp;');
644
+        if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0)
645
+        print ' '.img_picto($langs->trans("Late"),"warning");
646
+        else print '&nbsp;&nbsp;&nbsp;&nbsp;';
647
+        print '</td>';
648 648
         if (! $i) $totalarray['nbfield']++;
649
-	}
650
-	if (! empty($arrayfields['cd.date_ouverture']['checked']))
651
-	{
652
-		print '<td align="center">'.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour'):'&nbsp;').'</td>';
649
+    }
650
+    if (! empty($arrayfields['cd.date_ouverture']['checked']))
651
+    {
652
+        print '<td align="center">'.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour'):'&nbsp;').'</td>';
653 653
         if (! $i) $totalarray['nbfield']++;
654
-	}
655
-	// End date
656
-	if (! empty($arrayfields['cd.date_fin_validite']['checked']))
657
-	{
658
-		print '<td align="center">'.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour'):'&nbsp;');
659
-		if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5)
660
-		{
661
-			$warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24;
662
-			$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
663
-			print img_warning($textlate);
664
-		}
665
-		else print '&nbsp;&nbsp;&nbsp;&nbsp;';
666
-		print '</td>';
654
+    }
655
+    // End date
656
+    if (! empty($arrayfields['cd.date_fin_validite']['checked']))
657
+    {
658
+        print '<td align="center">'.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour'):'&nbsp;');
659
+        if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5)
660
+        {
661
+            $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24;
662
+            $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
663
+            print img_warning($textlate);
664
+        }
665
+        else print '&nbsp;&nbsp;&nbsp;&nbsp;';
666
+        print '</td>';
667
+        if (! $i) $totalarray['nbfield']++;
668
+    }
669
+    // Close date (real end date)
670
+    if (! empty($arrayfields['cd.date_cloture']['checked']))
671
+    {
672
+        print '<td align="center">'.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').'</td>';
673
+        if (! $i) $totalarray['nbfield']++;
674
+    }
675
+
676
+    // Extra fields
677
+    include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
678
+    // Fields from hook
679
+    $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
680
+    $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters);    // Note that $action and $object may have been modified by hook
681
+    print $hookmanager->resPrint;
682
+    // Date creation
683
+    if (! empty($arrayfields['cd.datec']['checked']))
684
+    {
685
+        print '<td align="center">';
686
+        print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
687
+        print '</td>';
688
+        if (! $i) $totalarray['nbfield']++;
689
+    }
690
+    // Date modification
691
+    if (! empty($arrayfields['cd.tms']['checked']))
692
+    {
693
+        print '<td align="center">';
694
+        print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
695
+        print '</td>';
667 696
         if (! $i) $totalarray['nbfield']++;
668
-	}
669
-	// Close date (real end date)
670
-	if (! empty($arrayfields['cd.date_cloture']['checked']))
671
-	{
672
-		print '<td align="center">'.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').'</td>';
697
+    }
698
+    // Status
699
+    if (! empty($arrayfields['status']['checked']))
700
+    {
701
+        print '<td align="right">';
702
+        if ($obj->cstatut == 0)	// If contract is draft, we say line is also draft
703
+        {
704
+            print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now));
705
+        }
706
+        else
707
+        {
708
+            print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0);
709
+        }
710
+        print '</td>';
673 711
         if (! $i) $totalarray['nbfield']++;
674
-	}
675
-
676
-	// Extra fields
677
-	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
678
-	// Fields from hook
679
-	$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
680
-	$reshook=$hookmanager->executeHooks('printFieldListValue',$parameters);    // Note that $action and $object may have been modified by hook
681
-	print $hookmanager->resPrint;
682
-	// Date creation
683
-	if (! empty($arrayfields['cd.datec']['checked']))
684
-	{
685
-		print '<td align="center">';
686
-		print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
687
-		print '</td>';
688
-		if (! $i) $totalarray['nbfield']++;
689
-	}
690
-	// Date modification
691
-	if (! empty($arrayfields['cd.tms']['checked']))
692
-	{
693
-		print '<td align="center">';
694
-		print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
695
-		print '</td>';
696
-		if (! $i) $totalarray['nbfield']++;
697
-	}
698
-	// Status
699
-	if (! empty($arrayfields['status']['checked']))
700
-	{
701
-	   print '<td align="right">';
702
-	   if ($obj->cstatut == 0)	// If contract is draft, we say line is also draft
703
-	   {
704
-		   print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now));
705
-	   }
706
-	   else
707
-	   {
708
-		   print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0);
709
-	   }
710
-	   print '</td>';
711
-       if (! $i) $totalarray['nbfield']++;
712
-	}
713
-	// Action column
714
-	print '<td class="nowrap" align="center">';
715
-	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
716
-	{
717
-		$selected=0;
718
-		if (in_array($obj->rowid, $arrayofselected)) $selected=1;
719
-		print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
720
-	}
721
-	print '</td>';
722
-	if (! $i) $totalarray['nbfield']++;
723
-
724
-	print "</tr>\n";
725
-	$i++;
712
+    }
713
+    // Action column
714
+    print '<td class="nowrap" align="center">';
715
+    if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
716
+    {
717
+        $selected=0;
718
+        if (in_array($obj->rowid, $arrayofselected)) $selected=1;
719
+        print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
720
+    }
721
+    print '</td>';
722
+    if (! $i) $totalarray['nbfield']++;
723
+
724
+    print "</tr>\n";
725
+    $i++;
726 726
 }
727 727
 
728 728
 // Show total line
729 729
 if (isset($totalarray['displaytotalline'])) {
730
-	print '<tr class="liste_total">';
731
-	$i=0;
732
-	while ($i < $totalarray['nbfield']) {
733
-		$i++;
734
-		if ($i == 1) {
735
-			if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>';
736
-			else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>';
737
-		}
738
-		elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>';
739
-		elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>';
740
-		elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>';
741
-		else print '<td></td>';
742
-	}
743
-	print '</tr>';
730
+    print '<tr class="liste_total">';
731
+    $i=0;
732
+    while ($i < $totalarray['nbfield']) {
733
+        $i++;
734
+        if ($i == 1) {
735
+            if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>';
736
+            else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>';
737
+        }
738
+        elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>';
739
+        elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>';
740
+        elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>';
741
+        else print '<td></td>';
742
+    }
743
+    print '</tr>';
744 744
 }
745 745
 
746 746
 $db->free($resql);
Please login to merge, or discard this patch.
Spacing   +290 added lines, -290 removed lines patch added patch discarded remove patch
@@ -34,47 +34,47 @@  discard block
 block discarded – undo
34 34
 // Load translation files required by the page
35 35
 $langs->loadLangs(array('products', 'contracts', 'companies'));
36 36
 
37
-$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
38
-$sortfield = GETPOST("sortfield",'alpha');
39
-$sortorder = GETPOST("sortorder",'alpha');
40
-$page = GETPOST("page",'int');
37
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
38
+$sortfield = GETPOST("sortfield", 'alpha');
39
+$sortorder = GETPOST("sortorder", 'alpha');
40
+$page = GETPOST("page", 'int');
41 41
 if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
42 42
 $offset = $limit * $page;
43 43
 $pageprev = $page - 1;
44 44
 $pagenext = $page + 1;
45
-if (! $sortfield) $sortfield="c.rowid";
46
-if (! $sortorder) $sortorder="ASC";
45
+if (!$sortfield) $sortfield = "c.rowid";
46
+if (!$sortorder) $sortorder = "ASC";
47 47
 
48 48
 $mode = GETPOST("mode");
49
-$filter=GETPOST("filter");
50
-$search_name=GETPOST("search_name");
51
-$search_contract=GETPOST("search_contract");
52
-$search_service=GETPOST("search_service");
53
-$search_status=GETPOST("search_status","alpha");
54
-$statut=GETPOST('statut')?GETPOST('statut'):1;
55
-$search_product_category=GETPOST('search_product_category','int');
56
-$socid=GETPOST('socid','int');
57
-$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'contractservicelist'.$mode;
58
-
59
-$opouvertureprevuemonth=GETPOST('opouvertureprevuemonth');
60
-$opouvertureprevueday=GETPOST('opouvertureprevueday');
61
-$opouvertureprevueyear=GETPOST('opouvertureprevueyear');
62
-$filter_opouvertureprevue=GETPOST('filter_opouvertureprevue');
63
-
64
-$op1month=GETPOST('op1month');
65
-$op1day=GETPOST('op1day');
66
-$op1year=GETPOST('op1year');
67
-$filter_op1=GETPOST('filter_op1');
68
-
69
-$op2month=GETPOST('op2month');
70
-$op2day=GETPOST('op2day');
71
-$op2year=GETPOST('op2year');
72
-$filter_op2=GETPOST('filter_op2');
73
-
74
-$opcloturemonth=GETPOST('opcloturemonth');
75
-$opclotureday=GETPOST('opclotureday');
76
-$opclotureyear=GETPOST('opclotureyear');
77
-$filter_opcloture=GETPOST('filter_opcloture');
49
+$filter = GETPOST("filter");
50
+$search_name = GETPOST("search_name");
51
+$search_contract = GETPOST("search_contract");
52
+$search_service = GETPOST("search_service");
53
+$search_status = GETPOST("search_status", "alpha");
54
+$statut = GETPOST('statut') ?GETPOST('statut') : 1;
55
+$search_product_category = GETPOST('search_product_category', 'int');
56
+$socid = GETPOST('socid', 'int');
57
+$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'contractservicelist'.$mode;
58
+
59
+$opouvertureprevuemonth = GETPOST('opouvertureprevuemonth');
60
+$opouvertureprevueday = GETPOST('opouvertureprevueday');
61
+$opouvertureprevueyear = GETPOST('opouvertureprevueyear');
62
+$filter_opouvertureprevue = GETPOST('filter_opouvertureprevue');
63
+
64
+$op1month = GETPOST('op1month');
65
+$op1day = GETPOST('op1day');
66
+$op1year = GETPOST('op1year');
67
+$filter_op1 = GETPOST('filter_op1');
68
+
69
+$op2month = GETPOST('op2month');
70
+$op2day = GETPOST('op2day');
71
+$op2year = GETPOST('op2year');
72
+$filter_op2 = GETPOST('filter_op2');
73
+
74
+$opcloturemonth = GETPOST('opcloturemonth');
75
+$opclotureday = GETPOST('opclotureday');
76
+$opclotureyear = GETPOST('opclotureyear');
77
+$filter_opcloture = GETPOST('filter_opcloture');
78 78
 
79 79
 
80 80
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@@ -84,36 +84,36 @@  discard block
 block discarded – undo
84 84
 
85 85
 // fetch optionals attributes and labels
86 86
 $extralabels = $extrafields->fetch_name_optionals_label('contratdet');
87
-$search_array_options=$extrafields->getOptionalsFromPost($object->table_element,'','search_');
87
+$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
88 88
 
89 89
 // Security check
90
-$contratid = GETPOST('id','int');
91
-if (! empty($user->societe_id)) $socid=$user->societe_id;
92
-$result = restrictedArea($user, 'contrat',$contratid);
90
+$contratid = GETPOST('id', 'int');
91
+if (!empty($user->societe_id)) $socid = $user->societe_id;
92
+$result = restrictedArea($user, 'contrat', $contratid);
93 93
 
94 94
 if ($search_status != '')
95 95
 {
96
-	$tmp=explode('&', $search_status);
97
-	$mode=$tmp[0];
98
-	if (empty($tmp[1])) $filter='';
96
+	$tmp = explode('&', $search_status);
97
+	$mode = $tmp[0];
98
+	if (empty($tmp[1])) $filter = '';
99 99
 	else
100 100
 	{
101
-		if ($tmp[1] == 'filter=notexpired') $filter='notexpired';
102
-		if ($tmp[1] == 'filter=expired') $filter='expired';
101
+		if ($tmp[1] == 'filter=notexpired') $filter = 'notexpired';
102
+		if ($tmp[1] == 'filter=expired') $filter = 'expired';
103 103
 	}
104 104
 }
105 105
 else
106 106
 {
107 107
 	$search_status = $mode;
108
-	if ($filter == 'expired') $search_status.='&filter=expired';
109
-	if ($filter == 'notexpired') $search_status.='&filter=notexpired';
108
+	if ($filter == 'expired') $search_status .= '&filter=expired';
109
+	if ($filter == 'notexpired') $search_status .= '&filter=notexpired';
110 110
 }
111 111
 
112
-$staticcontrat=new Contrat($db);
113
-$staticcontratligne=new ContratLigne($db);
114
-$companystatic=new Societe($db);
112
+$staticcontrat = new Contrat($db);
113
+$staticcontratligne = new ContratLigne($db);
114
+$companystatic = new Societe($db);
115 115
 
116
-$arrayfields=array(
116
+$arrayfields = array(
117 117
 	'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80),
118 118
 	'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80),
119 119
 	'cd.qty'=>array('label'=>$langs->trans("Qty"), 'checked'=>0, 'position'=>100),
@@ -133,9 +133,9 @@  discard block
 block discarded – undo
133 133
 // Extra fields
134 134
 if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
135 135
 {
136
-	foreach($extrafields->attribute_label as $key => $val)
136
+	foreach ($extrafields->attribute_label as $key => $val)
137 137
 	{
138
-		if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key]));
138
+		if (!empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key] = array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key] < 0) ? 0 : 1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key]) != 3 && $extrafields->attribute_perms[$key]));
139 139
 	}
140 140
 }
141 141
 
@@ -146,11 +146,11 @@  discard block
 block discarded – undo
146 146
  * Actions
147 147
  */
148 148
 
149
-if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; }
150
-if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; }
149
+if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
150
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; }
151 151
 
152
-$parameters=array('socid'=>$socid);
153
-$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
152
+$parameters = array('socid'=>$socid);
153
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
154 154
 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
155 155
 
156 156
 if (empty($reshook))
@@ -158,33 +158,33 @@  discard block
 block discarded – undo
158 158
 	// Selection of new fields
159 159
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
160 160
 
161
-	if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers
161
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
162 162
 	{
163
-   		$search_product_category=0;
164
-		$search_name="";
165
-		$search_contract="";
166
-		$search_service="";
167
-		$search_status=-1;
168
-		$opouvertureprevuemonth="";
169
-		$opouvertureprevueday="";
170
-		$opouvertureprevueyear="";
171
-		$filter_opouvertureprevue="";
172
-		$op1month="";
173
-		$op1day="";
174
-		$op1year="";
175
-		$filter_op1="";
176
-		$op2month="";
177
-		$op2day="";
178
-		$op2year="";
179
-		$filter_op2="";
180
-		$opcloturemonth="";
181
-		$opclotureday="";
182
-		$opclotureyear="";
183
-		$filter_opcloture="";
184
-		$mode='';
185
-		$filter='';
186
-		$toselect='';
187
-		$search_array_options=array();
163
+   		$search_product_category = 0;
164
+		$search_name = "";
165
+		$search_contract = "";
166
+		$search_service = "";
167
+		$search_status = -1;
168
+		$opouvertureprevuemonth = "";
169
+		$opouvertureprevueday = "";
170
+		$opouvertureprevueyear = "";
171
+		$filter_opouvertureprevue = "";
172
+		$op1month = "";
173
+		$op1day = "";
174
+		$op1year = "";
175
+		$filter_op1 = "";
176
+		$op2month = "";
177
+		$op2day = "";
178
+		$op2year = "";
179
+		$filter_op2 = "";
180
+		$opcloturemonth = "";
181
+		$opclotureday = "";
182
+		$opclotureyear = "";
183
+		$filter_opcloture = "";
184
+		$mode = '';
185
+		$filter = '';
186
+		$toselect = '';
187
+		$search_array_options = array();
188 188
 	}
189 189
 }
190 190
 
@@ -193,64 +193,64 @@  discard block
 block discarded – undo
193 193
  * View
194 194
  */
195 195
 
196
-$now=dol_now();
196
+$now = dol_now();
197 197
 
198
-$form=new Form($db);
198
+$form = new Form($db);
199 199
 
200 200
 $sql = "SELECT c.rowid as cid, c.ref, c.statut as cstatut,";
201
-$sql.= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,";
202
-$sql.= " cd.rowid, cd.description, cd.statut,";
203
-$sql.= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,";
201
+$sql .= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,";
202
+$sql .= " cd.rowid, cd.description, cd.statut,";
203
+$sql .= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,";
204 204
 if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,";
205
-$sql.= " cd.date_ouverture_prevue,";
206
-$sql.= " cd.date_ouverture,";
207
-$sql.= " cd.date_fin_validite,";
208
-$sql.= " cd.date_cloture,";
209
-$sql.= " cd.qty,";
210
-$sql.= " cd.total_ht,";
211
-$sql.= " cd.total_tva,";
212
-$sql.= " cd.tva_tx,";
213
-$sql.= " cd.subprice,";
205
+$sql .= " cd.date_ouverture_prevue,";
206
+$sql .= " cd.date_ouverture,";
207
+$sql .= " cd.date_fin_validite,";
208
+$sql .= " cd.date_cloture,";
209
+$sql .= " cd.qty,";
210
+$sql .= " cd.total_ht,";
211
+$sql .= " cd.total_tva,";
212
+$sql .= " cd.tva_tx,";
213
+$sql .= " cd.subprice,";
214 214
 //$sql.= " cd.date_c as date_creation,";
215
-$sql.= " cd.tms as date_update";
215
+$sql .= " cd.tms as date_update";
216 216
 // Add fields from extrafields
217
-foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
217
+foreach ($extrafields->attribute_label as $key => $val) $sql .= ($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
218 218
 // Add fields from hooks
219
-$parameters=array();
220
-$reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters);    // Note that $action and $object may have been modified by hook
221
-$sql.=$hookmanager->resPrint;
222
-$sql.= " FROM ".MAIN_DB_PREFIX."contrat as c,";
223
-$sql.= " ".MAIN_DB_PREFIX."societe as s,";
219
+$parameters = array();
220
+$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
221
+$sql .= $hookmanager->resPrint;
222
+$sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,";
223
+$sql .= " ".MAIN_DB_PREFIX."societe as s,";
224 224
 if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,";
225
-$sql.= " ".MAIN_DB_PREFIX."contratdet as cd";
226
-if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet_extrafields as ef on (cd.rowid = ef.fk_object)";
227
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
228
-if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product';
229
-$sql.= " WHERE c.entity = ".$conf->entity;
230
-$sql.= " AND c.rowid = cd.fk_contrat";
231
-if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$search_product_category;
232
-$sql.= " AND c.fk_soc = s.rowid";
233
-if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
234
-if ($mode == "0") $sql.= " AND cd.statut = 0";
235
-if ($mode == "4") $sql.= " AND cd.statut = 4";
236
-if ($mode == "5") $sql.= " AND cd.statut = 5";
237
-if ($filter == "expired") $sql.= " AND cd.date_fin_validite < '".$db->idate($now)."'";
238
-if ($filter == "notexpired") $sql.= " AND cd.date_fin_validite >= '".$db->idate($now)."'";
239
-if ($search_name)     $sql.= " AND s.nom LIKE '%".$db->escape($search_name)."%'";
240
-if ($search_contract) $sql.= " AND c.ref LIKE '%".$db->escape($search_contract)."%' ";
241
-if ($search_service)  $sql.= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')";
242
-if ($socid > 0)       $sql.= " AND s.rowid = ".$socid;
243
-$filter_dateouvertureprevue=dol_mktime(0,0,0,$opouvertureprevuemonth,$opouvertureprevueday,$opouvertureprevueyear);
244
-$filter_date1=dol_mktime(0,0,0,$op1month,$op1day,$op1year);
245
-$filter_date2=dol_mktime(0,0,0,$op2month,$op2day,$op2year);
246
-$filter_datecloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear);
247
-if (! empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_dateouvertureprevue != '') $sql.= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue)."'";
248
-if (! empty($filter_op1) && $filter_op1 != -1 && $filter_date1 != '') $sql.= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1)."'";
249
-if (! empty($filter_op2) && $filter_op2 != -1 && $filter_date2 != '') $sql.= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2)."'";
250
-if (! empty($filter_opcloture) && $filter_opcloture != -1 && $filter_datecloture != '') $sql.= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture)."'";
225
+$sql .= " ".MAIN_DB_PREFIX."contratdet as cd";
226
+if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet_extrafields as ef on (cd.rowid = ef.fk_object)";
227
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
228
+if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product';
229
+$sql .= " WHERE c.entity = ".$conf->entity;
230
+$sql .= " AND c.rowid = cd.fk_contrat";
231
+if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category;
232
+$sql .= " AND c.fk_soc = s.rowid";
233
+if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
234
+if ($mode == "0") $sql .= " AND cd.statut = 0";
235
+if ($mode == "4") $sql .= " AND cd.statut = 4";
236
+if ($mode == "5") $sql .= " AND cd.statut = 5";
237
+if ($filter == "expired") $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'";
238
+if ($filter == "notexpired") $sql .= " AND cd.date_fin_validite >= '".$db->idate($now)."'";
239
+if ($search_name)     $sql .= " AND s.nom LIKE '%".$db->escape($search_name)."%'";
240
+if ($search_contract) $sql .= " AND c.ref LIKE '%".$db->escape($search_contract)."%' ";
241
+if ($search_service)  $sql .= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')";
242
+if ($socid > 0)       $sql .= " AND s.rowid = ".$socid;
243
+$filter_dateouvertureprevue = dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear);
244
+$filter_date1 = dol_mktime(0, 0, 0, $op1month, $op1day, $op1year);
245
+$filter_date2 = dol_mktime(0, 0, 0, $op2month, $op2day, $op2year);
246
+$filter_datecloture = dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear);
247
+if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_dateouvertureprevue != '') $sql .= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue)."'";
248
+if (!empty($filter_op1) && $filter_op1 != -1 && $filter_date1 != '') $sql .= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1)."'";
249
+if (!empty($filter_op2) && $filter_op2 != -1 && $filter_date2 != '') $sql .= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2)."'";
250
+if (!empty($filter_opcloture) && $filter_opcloture != -1 && $filter_datecloture != '') $sql .= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture)."'";
251 251
 // Add where from extra fields
252 252
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
253
-$sql .= $db->order($sortfield,$sortorder);
253
+$sql .= $db->order($sortfield, $sortorder);
254 254
 
255 255
 $nbtotalofrecords = '';
256 256
 if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
@@ -268,8 +268,8 @@  discard block
 block discarded – undo
268 268
 
269 269
 //print $sql;
270 270
 dol_syslog("contrat/services_list.php", LOG_DEBUG);
271
-$resql=$db->query($sql);
272
-if (! $resql)
271
+$resql = $db->query($sql);
272
+if (!$resql)
273 273
 {
274 274
 	dol_print_error($db);
275 275
 	exit;
@@ -288,36 +288,36 @@  discard block
 block discarded – undo
288 288
 
289 289
 llxHeader(null, $langs->trans("Services"));
290 290
 
291
-$param='';
292
-if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
293
-if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
294
-if ($search_contract) $param.='&amp;search_contract='.urlencode($search_contract);
295
-if ($search_name)      $param.='&amp;search_name='.urlencode($search_name);
296
-if ($search_service)  $param.='&amp;search_service='.urlencode($search_service);
297
-if ($mode)            $param.='&amp;mode='.urlencode($mode);
298
-if ($filter)          $param.='&amp;filter='.urlencode($filter);
299
-if (! empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) $param.='&amp;filter_opouvertureprevue='.urlencode($filter_opouvertureprevue);
300
-if (! empty($filter_op1) && $filter_op1 != -1) $param.='&amp;filter_op1='.urlencode($filter_op1);
301
-if (! empty($filter_op2) && $filter_op2 != -1) $param.='&amp;filter_op2='.urlencode($filter_op2);
302
-if (! empty($filter_opcloture) && $filter_opcloture != -1) $param.='&amp;filter_opcloture='.urlencode($filter_opcloture);
303
-if ($filter_dateouvertureprevue != '') $param.='&amp;opouvertureprevueday='.$opouvertureprevueday.'&amp;opouvertureprevuemonth='.$opouvertureprevuemonth.'&amp;opouvertureprevueyear='.$opouvertureprevueyear;
304
-if ($filter_date1 != '') $param.='&amp;op1day='.$op1day.'&amp;op1month='.$op1month.'&amp;op1year='.$op1year;
305
-if ($filter_date2 != '') $param.='&amp;op2day='.$op2day.'&amp;op2month='.$op2month.'&amp;op2year='.$op2year;
306
-if ($filter_datecloture != '') $param.='&amp;opclotureday='.$op2day.'&amp;opcloturemonth='.$op2month.'&amp;opclotureyear='.$op2year;
307
-if ($optioncss != '') $param.='&optioncss='.$optioncss;
291
+$param = '';
292
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
293
+if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
294
+if ($search_contract) $param .= '&amp;search_contract='.urlencode($search_contract);
295
+if ($search_name)      $param .= '&amp;search_name='.urlencode($search_name);
296
+if ($search_service)  $param .= '&amp;search_service='.urlencode($search_service);
297
+if ($mode)            $param .= '&amp;mode='.urlencode($mode);
298
+if ($filter)          $param .= '&amp;filter='.urlencode($filter);
299
+if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) $param .= '&amp;filter_opouvertureprevue='.urlencode($filter_opouvertureprevue);
300
+if (!empty($filter_op1) && $filter_op1 != -1) $param .= '&amp;filter_op1='.urlencode($filter_op1);
301
+if (!empty($filter_op2) && $filter_op2 != -1) $param .= '&amp;filter_op2='.urlencode($filter_op2);
302
+if (!empty($filter_opcloture) && $filter_opcloture != -1) $param .= '&amp;filter_opcloture='.urlencode($filter_opcloture);
303
+if ($filter_dateouvertureprevue != '') $param .= '&amp;opouvertureprevueday='.$opouvertureprevueday.'&amp;opouvertureprevuemonth='.$opouvertureprevuemonth.'&amp;opouvertureprevueyear='.$opouvertureprevueyear;
304
+if ($filter_date1 != '') $param .= '&amp;op1day='.$op1day.'&amp;op1month='.$op1month.'&amp;op1year='.$op1year;
305
+if ($filter_date2 != '') $param .= '&amp;op2day='.$op2day.'&amp;op2month='.$op2month.'&amp;op2year='.$op2year;
306
+if ($filter_datecloture != '') $param .= '&amp;opclotureday='.$op2day.'&amp;opcloturemonth='.$op2month.'&amp;opclotureyear='.$op2year;
307
+if ($optioncss != '') $param .= '&optioncss='.$optioncss;
308 308
 // Add $param from extra fields
309 309
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
310 310
 
311 311
 // List of mass actions available
312
-$arrayofmassactions =  array(
312
+$arrayofmassactions = array(
313 313
 	//'presend'=>$langs->trans("SendByMail"),
314 314
 	//'builddoc'=>$langs->trans("PDFMerge"),
315 315
 );
316 316
 //if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete");
317 317
 //if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
318
-$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
318
+$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
319 319
 
320
-print '<form method="POST" action="'. $_SERVER["PHP_SELF"] .'">';
320
+print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
321 321
 if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
322 322
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
323 323
 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
@@ -327,17 +327,17 @@  discard block
 block discarded – undo
327 327
 print '<input type="hidden" name="page" value="'.$page.'">';
328 328
 print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
329 329
 
330
-$title=$langs->trans("ListOfServices");
331
-if ($mode == "0") $title=$langs->trans("ListOfInactiveServices");	// Must use == "0"
332
-if ($mode == "4" && $filter != "expired") $title=$langs->trans("ListOfRunningServices");
333
-if ($mode == "4" && $filter == "expired") $title=$langs->trans("ListOfExpiredServices");
334
-if ($mode == "5") $title=$langs->trans("ListOfClosedServices");
330
+$title = $langs->trans("ListOfServices");
331
+if ($mode == "0") $title = $langs->trans("ListOfInactiveServices"); // Must use == "0"
332
+if ($mode == "4" && $filter != "expired") $title = $langs->trans("ListOfRunningServices");
333
+if ($mode == "4" && $filter == "expired") $title = $langs->trans("ListOfExpiredServices");
334
+if ($mode == "5") $title = $langs->trans("ListOfClosedServices");
335 335
 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit);
336 336
 
337 337
 if ($sall)
338 338
 {
339
-	foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
340
-	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall).'</div>';
339
+	foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
340
+	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
341 341
 }
342 342
 
343 343
 $morefilter = '';
@@ -346,60 +346,60 @@  discard block
 block discarded – undo
346 346
 if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire))
347 347
 {
348 348
 	include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
349
-	$moreforfilter.='<div class="divsearchfield">';
350
-	$moreforfilter.=$langs->trans('IncludingProductWithTag'). ': ';
349
+	$moreforfilter .= '<div class="divsearchfield">';
350
+	$moreforfilter .= $langs->trans('IncludingProductWithTag').': ';
351 351
 	$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1);
352
-	$moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
353
-	$moreforfilter.='</div>';
352
+	$moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
353
+	$moreforfilter .= '</div>';
354 354
 }
355 355
 
356
-$parameters=array();
357
-$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters);    // Note that $action and $object may have been modified by hook
356
+$parameters = array();
357
+$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
358 358
 if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
359 359
 else $moreforfilter = $hookmanager->resPrint;
360 360
 
361 361
 
362
-if (! empty($moreforfilter))
362
+if (!empty($moreforfilter))
363 363
 {
364 364
 	print '<div class="liste_titre liste_titre_bydiv centpercent">';
365 365
 	print $moreforfilter;
366 366
 	print '</div>';
367 367
 }
368 368
 
369
-$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
370
-$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage);	// This also change content of $arrayfields
369
+$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
370
+$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
371 371
 
372 372
 
373 373
 print '<div class="div-table-responsive">';
374
-print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
374
+print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
375 375
 
376 376
 print '<tr class="liste_titre">';
377
-if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'],$_SERVER["PHP_SELF"],"c.ref","",$param,"",$sortfield,$sortorder);
378
-if (! empty($arrayfields['p.description']['checked'])) print_liste_field_titre($arrayfields['p.description']['label'],$_SERVER["PHP_SELF"],"p.description","",$param,"",$sortfield,$sortorder);
379
-if (! empty($arrayfields['cd.qty']['checked']))  print_liste_field_titre($arrayfields['cd.qty']['label'],$_SERVER["PHP_SELF"],"cd.qty","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
380
-if (! empty($arrayfields['cd.total_ht']['checked']))  print_liste_field_titre($arrayfields['cd.total_ht']['label'],$_SERVER["PHP_SELF"],"cd.total_ht","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
381
-if (! empty($arrayfields['cd.total_tva']['checked']))  print_liste_field_titre($arrayfields['cd.total_tva']['label'],$_SERVER["PHP_SELF"],"cd.total_tva","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
382
-if (! empty($arrayfields['cd.tva_tx']['checked']))  print_liste_field_titre($arrayfields['cd.tva_tx']['label'],$_SERVER["PHP_SELF"],"cd.tva_tx","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
383
-if (! empty($arrayfields['cd.subprice']['checked']))  print_liste_field_titre($arrayfields['cd.subprice']['label'],$_SERVER["PHP_SELF"],"cd.subprice","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
384
-if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder);
385
-if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'],$_SERVER["PHP_SELF"],"cd.date_ouverture_prevue","",$param,'align="center"',$sortfield,$sortorder);
386
-if (! empty($arrayfields['cd.date_ouverture']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture']['label'],$_SERVER["PHP_SELF"],"cd.date_ouverture","",$param,'align="center"',$sortfield,$sortorder);
387
-if (! empty($arrayfields['cd.date_fin_validite']['checked'])) print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'],$_SERVER["PHP_SELF"],"cd.date_fin_validite","",$param,'align="center"',$sortfield,$sortorder);
388
-if (! empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre($arrayfields['cd.date_cloture']['label'],$_SERVER["PHP_SELF"],"cd.date_cloture","",$param,'align="center"',$sortfield,$sortorder);
377
+if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, "", $sortfield, $sortorder);
378
+if (!empty($arrayfields['p.description']['checked'])) print_liste_field_titre($arrayfields['p.description']['label'], $_SERVER["PHP_SELF"], "p.description", "", $param, "", $sortfield, $sortorder);
379
+if (!empty($arrayfields['cd.qty']['checked']))  print_liste_field_titre($arrayfields['cd.qty']['label'], $_SERVER["PHP_SELF"], "cd.qty", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
380
+if (!empty($arrayfields['cd.total_ht']['checked']))  print_liste_field_titre($arrayfields['cd.total_ht']['label'], $_SERVER["PHP_SELF"], "cd.total_ht", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
381
+if (!empty($arrayfields['cd.total_tva']['checked']))  print_liste_field_titre($arrayfields['cd.total_tva']['label'], $_SERVER["PHP_SELF"], "cd.total_tva", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
382
+if (!empty($arrayfields['cd.tva_tx']['checked']))  print_liste_field_titre($arrayfields['cd.tva_tx']['label'], $_SERVER["PHP_SELF"], "cd.tva_tx", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
383
+if (!empty($arrayfields['cd.subprice']['checked']))  print_liste_field_titre($arrayfields['cd.subprice']['label'], $_SERVER["PHP_SELF"], "cd.subprice", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
384
+if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder);
385
+if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture_prevue", "", $param, 'align="center"', $sortfield, $sortorder);
386
+if (!empty($arrayfields['cd.date_ouverture']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture", "", $param, 'align="center"', $sortfield, $sortorder);
387
+if (!empty($arrayfields['cd.date_fin_validite']['checked'])) print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'], $_SERVER["PHP_SELF"], "cd.date_fin_validite", "", $param, 'align="center"', $sortfield, $sortorder);
388
+if (!empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre($arrayfields['cd.date_cloture']['label'], $_SERVER["PHP_SELF"], "cd.date_cloture", "", $param, 'align="center"', $sortfield, $sortorder);
389 389
 // Extra fields
390 390
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
391 391
 // Hook fields
392
-$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder);
393
-$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters);    // Note that $action and $object may have been modified by hook
392
+$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
393
+$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
394 394
 print $hookmanager->resPrint;
395
-if (! empty($arrayfields['cd.datec']['checked']))  print_liste_field_titre($arrayfields['cd.datec']['label'],$_SERVER["PHP_SELF"],"cd.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
396
-if (! empty($arrayfields['cd.tms']['checked']))    print_liste_field_titre($arrayfields['cd.tms']['label'],$_SERVER["PHP_SELF"],"cd.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
397
-if (! empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'],$_SERVER["PHP_SELF"],"cd.statut,c.statut","",$param,'align="right"',$sortfield,$sortorder);
398
-print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ');
395
+if (!empty($arrayfields['cd.datec']['checked']))  print_liste_field_titre($arrayfields['cd.datec']['label'], $_SERVER["PHP_SELF"], "cd.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
396
+if (!empty($arrayfields['cd.tms']['checked']))    print_liste_field_titre($arrayfields['cd.tms']['label'], $_SERVER["PHP_SELF"], "cd.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
397
+if (!empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], "cd.statut,c.statut", "", $param, 'align="right"', $sortfield, $sortorder);
398
+print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ');
399 399
 print "</tr>\n";
400 400
 
401 401
 print '<tr class="liste_titre">';
402
-if (! empty($arrayfields['c.ref']['checked']))
402
+if (!empty($arrayfields['c.ref']['checked']))
403 403
 {
404 404
 	print '<td class="liste_titre">';
405 405
 	print '<input type="hidden" name="filter" value="'.$filter.'">';
@@ -408,40 +408,40 @@  discard block
 block discarded – undo
408 408
 	print '</td>';
409 409
 }
410 410
 // Service label
411
-if (! empty($arrayfields['p.description']['checked']))
411
+if (!empty($arrayfields['p.description']['checked']))
412 412
 {
413 413
 	print '<td class="liste_titre">';
414 414
 	print '<input type="text" class="flat maxwidth100" name="search_service" value="'.dol_escape_htmltag($search_service).'">';
415 415
 	print '</td>';
416 416
 }
417 417
 // detail lines
418
-if (! empty($arrayfields['cd.qty']['checked']))
418
+if (!empty($arrayfields['cd.qty']['checked']))
419 419
 {
420 420
 	print '<td class="liste_titre">';
421 421
 	print '</td>';
422 422
 }
423
-if (! empty($arrayfields['cd.total_ht']['checked']))
423
+if (!empty($arrayfields['cd.total_ht']['checked']))
424 424
 {
425 425
 	print '<td class="liste_titre">';
426 426
 	print '</td>';
427 427
 }
428
-if (! empty($arrayfields['cd.total_tva']['checked']))
428
+if (!empty($arrayfields['cd.total_tva']['checked']))
429 429
 {
430 430
 	print '<td class="liste_titre">';
431 431
 	print '</td>';
432 432
 }
433
-if (! empty($arrayfields['cd.tva_tx']['checked']))
433
+if (!empty($arrayfields['cd.tva_tx']['checked']))
434 434
 {
435 435
 	print '<td class="liste_titre">';
436 436
 	print '</td>';
437 437
 }
438
-if (! empty($arrayfields['cd.subprice']['checked']))
438
+if (!empty($arrayfields['cd.subprice']['checked']))
439 439
 {
440 440
 	print '<td class="liste_titre">';
441 441
 	print '</td>';
442 442
 }
443 443
 // Third party
444
-if (! empty($arrayfields['s.nom']['checked']))
444
+if (!empty($arrayfields['s.nom']['checked']))
445 445
 {
446 446
 	print '<td class="liste_titre">';
447 447
 	print '<input type="text" class="flat maxwidth100" name="search_name" value="'.dol_escape_htmltag($search_name).'">';
@@ -449,43 +449,43 @@  discard block
 block discarded – undo
449 449
 }
450 450
 
451 451
 
452
-if (! empty($arrayfields['cd.date_ouverture_prevue']['checked']))
452
+if (!empty($arrayfields['cd.date_ouverture_prevue']['checked']))
453 453
 {
454 454
 	print '<td class="liste_titre" align="center">';
455
-	$arrayofoperators=array('<'=>'<','>'=>'>');
456
-	print $form->selectarray('filter_opouvertureprevue',$arrayofoperators,$filter_opouvertureprevue,1);
455
+	$arrayofoperators = array('<'=>'<', '>'=>'>');
456
+	print $form->selectarray('filter_opouvertureprevue', $arrayofoperators, $filter_opouvertureprevue, 1);
457 457
 	print ' ';
458
-	$filter_dateouvertureprevue=dol_mktime(0,0,0,$opouvertureprevuemonth,$opouvertureprevueday,$opouvertureprevueyear);
458
+	$filter_dateouvertureprevue = dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear);
459 459
 	print $form->selectDate($filter_dateouvertureprevue, 'opouvertureprevue', 0, 0, 1, '', 1, 0);
460 460
 	print '</td>';
461 461
 }
462
-if (! empty($arrayfields['cd.date_ouverture']['checked']))
462
+if (!empty($arrayfields['cd.date_ouverture']['checked']))
463 463
 {
464 464
 	print '<td class="liste_titre" align="center">';
465
-	$arrayofoperators=array('<'=>'<','>'=>'>');
466
-	print $form->selectarray('filter_op1',$arrayofoperators,$filter_op1,1);
465
+	$arrayofoperators = array('<'=>'<', '>'=>'>');
466
+	print $form->selectarray('filter_op1', $arrayofoperators, $filter_op1, 1);
467 467
 	print ' ';
468
-	$filter_date1=dol_mktime(0,0,0,$op1month,$op1day,$op1year);
468
+	$filter_date1 = dol_mktime(0, 0, 0, $op1month, $op1day, $op1year);
469 469
 	print $form->selectDate($filter_date1, 'op1', 0, 0, 1, '', 1, 0);
470 470
 	print '</td>';
471 471
 }
472
-if (! empty($arrayfields['cd.date_fin_validite']['checked']))
472
+if (!empty($arrayfields['cd.date_fin_validite']['checked']))
473 473
 {
474 474
 	print '<td class="liste_titre" align="center">';
475
-	$arrayofoperators=array('<'=>'<','>'=>'>');
476
-	print $form->selectarray('filter_op2',$arrayofoperators,$filter_op2,1);
475
+	$arrayofoperators = array('<'=>'<', '>'=>'>');
476
+	print $form->selectarray('filter_op2', $arrayofoperators, $filter_op2, 1);
477 477
 	print ' ';
478
-	$filter_date2=dol_mktime(0,0,0,$op2month,$op2day,$op2year);
478
+	$filter_date2 = dol_mktime(0, 0, 0, $op2month, $op2day, $op2year);
479 479
 	print $form->selectDate($filter_date2, 'op2', 0, 0, 1, '', 1, 0);
480 480
 	print '</td>';
481 481
 }
482
-if (! empty($arrayfields['cd.date_cloture']['checked']))
482
+if (!empty($arrayfields['cd.date_cloture']['checked']))
483 483
 {
484 484
 	print '<td class="liste_titre" align="center">';
485
-	$arrayofoperators=array('<'=>'<','>'=>'>');
486
-	print $form->selectarray('filter_opcloture',$arrayofoperators,$filter_opcloture,1);
485
+	$arrayofoperators = array('<'=>'<', '>'=>'>');
486
+	print $form->selectarray('filter_opcloture', $arrayofoperators, $filter_opcloture, 1);
487 487
 	print ' ';
488
-	$filter_date_cloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear);
488
+	$filter_date_cloture = dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear);
489 489
 	print $form->selectDate($filter_date_cloture, 'opcloture', 0, 0, 1, '', 1, 0);
490 490
 	print '</td>';
491 491
 }
@@ -493,233 +493,233 @@  discard block
 block discarded – undo
493 493
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
494 494
 
495 495
 // Fields from hook
496
-$parameters=array('arrayfields'=>$arrayfields);
497
-$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters);    // Note that $action and $object may have been modified by hook
496
+$parameters = array('arrayfields'=>$arrayfields);
497
+$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
498 498
 print $hookmanager->resPrint;
499
-if (! empty($arrayfields['cd.datec']['checked']))
499
+if (!empty($arrayfields['cd.datec']['checked']))
500 500
 {
501 501
 	// Date creation
502 502
 	print '<td class="liste_titre">';
503 503
 	print '</td>';
504 504
 }
505
-if (! empty($arrayfields['cd.tms']['checked']))
505
+if (!empty($arrayfields['cd.tms']['checked']))
506 506
 {
507 507
 	// Date modification
508 508
 	print '<td class="liste_titre">';
509 509
 	print '</td>';
510 510
 }
511
-if (! empty($arrayfields['status']['checked']))
511
+if (!empty($arrayfields['status']['checked']))
512 512
 {
513 513
 	// Status
514 514
 	print '<td class="liste_titre" align="right">';
515
-	$arrayofstatus=array(
515
+	$arrayofstatus = array(
516 516
 		'0'=>$langs->trans("ServiceStatusInitial"),
517 517
 		'4'=>$langs->trans("ServiceStatusRunning"),
518 518
 		'4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"),
519 519
 		'4&filter=expired'=>$langs->trans("ServiceStatusLate"),
520 520
 		'5'=>$langs->trans("ServiceStatusClosed")
521 521
 	);
522
-	print $form->selectarray('search_status', $arrayofstatus, (strstr($search_status, ',')?-1:$search_status), 1, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone');
522
+	print $form->selectarray('search_status', $arrayofstatus, (strstr($search_status, ',') ?-1 : $search_status), 1, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone');
523 523
 	print '</td>';
524 524
 }
525 525
 // Action column
526 526
 print '<td class="liste_titre" align="right">';
527
-$searchpicto=$form->showFilterAndCheckAddButtons(0);
527
+$searchpicto = $form->showFilterAndCheckAddButtons(0);
528 528
 print $searchpicto;
529 529
 print '</td>';
530 530
 print "</tr>\n";
531 531
 
532
-$contractstatic=new Contrat($db);
533
-$productstatic=new Product($db);
532
+$contractstatic = new Contrat($db);
533
+$productstatic = new Product($db);
534 534
 
535
-$i=0;
536
-$totalarray=array();
537
-while ($i < min($num,$limit))
535
+$i = 0;
536
+$totalarray = array();
537
+while ($i < min($num, $limit))
538 538
 {
539 539
 	$obj = $db->fetch_object($resql);
540 540
 
541
-	$contractstatic->id=$obj->cid;
542
-	$contractstatic->ref=$obj->ref?$obj->ref:$obj->cid;
541
+	$contractstatic->id = $obj->cid;
542
+	$contractstatic->ref = $obj->ref ? $obj->ref : $obj->cid;
543 543
 
544
-	$companystatic->id=$obj->socid;
545
-	$companystatic->name=$obj->name;
546
-	$companystatic->email=$obj->email;
547
-	$companystatic->client=$obj->client;
548
-	$companystatic->fournisseur=$obj->fournisseur;
544
+	$companystatic->id = $obj->socid;
545
+	$companystatic->name = $obj->name;
546
+	$companystatic->email = $obj->email;
547
+	$companystatic->client = $obj->client;
548
+	$companystatic->fournisseur = $obj->fournisseur;
549 549
 
550 550
 	print '<tr class="oddeven">';
551 551
 
552 552
 	// Ref
553
-	if (! empty($arrayfields['c.ref']['checked']))
553
+	if (!empty($arrayfields['c.ref']['checked']))
554 554
 	{
555 555
 		print '<td>';
556
-		print $contractstatic->getNomUrl(1,16);
556
+		print $contractstatic->getNomUrl(1, 16);
557 557
 		print '</td>';
558
-        if (! $i) $totalarray['nbfield']++;
558
+        if (!$i) $totalarray['nbfield']++;
559 559
 	}
560 560
 	// Service
561
-	if (! empty($arrayfields['p.description']['checked']))
561
+	if (!empty($arrayfields['p.description']['checked']))
562 562
 	{
563 563
 		print '<td>';
564 564
 		if ($obj->pid > 0)
565 565
 		{
566
-			$productstatic->id=$obj->pid;
567
-			$productstatic->type=$obj->ptype;
568
-			$productstatic->ref=$obj->pref;
569
-			$productstatic->entity=$obj->pentity;
570
-			print $productstatic->getNomUrl(1,'',24);
571
-			print $obj->label?' - '.dol_trunc($obj->label,16):'';
572
-			if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description);
566
+			$productstatic->id = $obj->pid;
567
+			$productstatic->type = $obj->ptype;
568
+			$productstatic->ref = $obj->pref;
569
+			$productstatic->entity = $obj->pentity;
570
+			print $productstatic->getNomUrl(1, '', 24);
571
+			print $obj->label ? ' - '.dol_trunc($obj->label, 16) : '';
572
+			if (!empty($obj->description) && !empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description);
573 573
 		}
574 574
 		else
575 575
 		{
576
-			if ($obj->type == 0) print img_object($obj->description,'product').' '.dol_trunc($obj->description,24);
577
-			if ($obj->type == 1) print img_object($obj->description,'service').' '.dol_trunc($obj->description,24);
576
+			if ($obj->type == 0) print img_object($obj->description, 'product').' '.dol_trunc($obj->description, 24);
577
+			if ($obj->type == 1) print img_object($obj->description, 'service').' '.dol_trunc($obj->description, 24);
578 578
 		}
579 579
 		print '</td>';
580
-        if (! $i) $totalarray['nbfield']++;
580
+        if (!$i) $totalarray['nbfield']++;
581 581
 	}
582 582
 
583
-	if (! empty($arrayfields['cd.qty']['checked']))
583
+	if (!empty($arrayfields['cd.qty']['checked']))
584 584
 	{
585 585
 		print '<td>';
586 586
 		print $obj->qty;
587 587
 		print '</td>';
588
-        if (! $i) $totalarray['nbfield']++;
588
+        if (!$i) $totalarray['nbfield']++;
589 589
 	}
590
-	if (! empty($arrayfields['cd.total_ht']['checked']))
590
+	if (!empty($arrayfields['cd.total_ht']['checked']))
591 591
 	{
592 592
 		print '<td align="right">';
593 593
 		print price($obj->total_ht);
594 594
 		print '</td>';
595 595
 		$totalarray['totalht'] += $obj->total_ht;
596
-        if (! $i) {
596
+        if (!$i) {
597 597
             $totalarray['displaytotalline']++;
598 598
             $totalarray['nbfield']++;
599
-            $totalarray['totalhtfield']=$totalarray['nbfield'];
599
+            $totalarray['totalhtfield'] = $totalarray['nbfield'];
600 600
         }
601 601
     }
602
-	if (! empty($arrayfields['cd.total_tva']['checked']))
602
+	if (!empty($arrayfields['cd.total_tva']['checked']))
603 603
 	{
604 604
 		print '<td align="right">';
605 605
 		print price($obj->total_tva);
606 606
 		print '</td>';
607 607
         $totalarray['totalvat'] += $obj->total_tva;
608
-        if (! $i) {
608
+        if (!$i) {
609 609
             $totalarray['nbfield']++;
610
-            $totalarray['totalvatfield']=$totalarray['nbfield'];
610
+            $totalarray['totalvatfield'] = $totalarray['nbfield'];
611 611
             $totalarray['displaytotalline']++;
612 612
         }
613 613
     }
614
-	if (! empty($arrayfields['cd.tva_tx']['checked']))
614
+	if (!empty($arrayfields['cd.tva_tx']['checked']))
615 615
 	{
616 616
 		print '<td align="right">';
617 617
 		print price2num($obj->tva_tx).'%';
618 618
 		print '</td>';
619
-        if (! $i) $totalarray['nbfield']++;
619
+        if (!$i) $totalarray['nbfield']++;
620 620
 	}
621
-	if (! empty($arrayfields['cd.subprice']['checked']))
621
+	if (!empty($arrayfields['cd.subprice']['checked']))
622 622
 	{
623 623
 		print '<td align="right">';
624 624
 		print price($obj->subprice);
625 625
 		print '</td>';
626
-        if (! $i) $totalarray['nbfield']++;
626
+        if (!$i) $totalarray['nbfield']++;
627 627
 	}
628 628
 
629 629
 
630 630
 	// Third party
631
-	if (! empty($arrayfields['s.nom']['checked']))
631
+	if (!empty($arrayfields['s.nom']['checked']))
632 632
 	{
633 633
 		print '<td>';
634
-		print $companystatic->getNomUrl(1,'customer',28);
634
+		print $companystatic->getNomUrl(1, 'customer', 28);
635 635
 		print '</td>';
636
-        if (! $i) $totalarray['nbfield']++;
636
+        if (!$i) $totalarray['nbfield']++;
637 637
 	}
638 638
 
639 639
 	// Start date
640
-	if (! empty($arrayfields['cd.date_ouverture_prevue']['checked']))
640
+	if (!empty($arrayfields['cd.date_ouverture_prevue']['checked']))
641 641
 	{
642 642
 		print '<td align="center">';
643
-		print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour'):'&nbsp;');
643
+		print ($obj->date_ouverture_prevue ?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour') : '&nbsp;');
644 644
 		if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0)
645
-		print ' '.img_picto($langs->trans("Late"),"warning");
645
+		print ' '.img_picto($langs->trans("Late"), "warning");
646 646
 		else print '&nbsp;&nbsp;&nbsp;&nbsp;';
647 647
 		print '</td>';
648
-        if (! $i) $totalarray['nbfield']++;
648
+        if (!$i) $totalarray['nbfield']++;
649 649
 	}
650
-	if (! empty($arrayfields['cd.date_ouverture']['checked']))
650
+	if (!empty($arrayfields['cd.date_ouverture']['checked']))
651 651
 	{
652
-		print '<td align="center">'.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour'):'&nbsp;').'</td>';
653
-        if (! $i) $totalarray['nbfield']++;
652
+		print '<td align="center">'.($obj->date_ouverture ?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour') : '&nbsp;').'</td>';
653
+        if (!$i) $totalarray['nbfield']++;
654 654
 	}
655 655
 	// End date
656
-	if (! empty($arrayfields['cd.date_fin_validite']['checked']))
656
+	if (!empty($arrayfields['cd.date_fin_validite']['checked']))
657 657
 	{
658
-		print '<td align="center">'.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour'):'&nbsp;');
658
+		print '<td align="center">'.($obj->date_fin_validite ?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour') : '&nbsp;');
659 659
 		if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5)
660 660
 		{
661
-			$warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24;
661
+			$warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24;
662 662
 			$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
663 663
 			print img_warning($textlate);
664 664
 		}
665 665
 		else print '&nbsp;&nbsp;&nbsp;&nbsp;';
666 666
 		print '</td>';
667
-        if (! $i) $totalarray['nbfield']++;
667
+        if (!$i) $totalarray['nbfield']++;
668 668
 	}
669 669
 	// Close date (real end date)
670
-	if (! empty($arrayfields['cd.date_cloture']['checked']))
670
+	if (!empty($arrayfields['cd.date_cloture']['checked']))
671 671
 	{
672 672
 		print '<td align="center">'.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').'</td>';
673
-        if (! $i) $totalarray['nbfield']++;
673
+        if (!$i) $totalarray['nbfield']++;
674 674
 	}
675 675
 
676 676
 	// Extra fields
677 677
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
678 678
 	// Fields from hook
679
-	$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
680
-	$reshook=$hookmanager->executeHooks('printFieldListValue',$parameters);    // Note that $action and $object may have been modified by hook
679
+	$parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj);
680
+	$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
681 681
 	print $hookmanager->resPrint;
682 682
 	// Date creation
683
-	if (! empty($arrayfields['cd.datec']['checked']))
683
+	if (!empty($arrayfields['cd.datec']['checked']))
684 684
 	{
685 685
 		print '<td align="center">';
686 686
 		print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
687 687
 		print '</td>';
688
-		if (! $i) $totalarray['nbfield']++;
688
+		if (!$i) $totalarray['nbfield']++;
689 689
 	}
690 690
 	// Date modification
691
-	if (! empty($arrayfields['cd.tms']['checked']))
691
+	if (!empty($arrayfields['cd.tms']['checked']))
692 692
 	{
693 693
 		print '<td align="center">';
694 694
 		print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
695 695
 		print '</td>';
696
-		if (! $i) $totalarray['nbfield']++;
696
+		if (!$i) $totalarray['nbfield']++;
697 697
 	}
698 698
 	// Status
699
-	if (! empty($arrayfields['status']['checked']))
699
+	if (!empty($arrayfields['status']['checked']))
700 700
 	{
701 701
 	   print '<td align="right">';
702 702
 	   if ($obj->cstatut == 0)	// If contract is draft, we say line is also draft
703 703
 	   {
704
-		   print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now));
704
+		   print $contractstatic->LibStatut(0, 5, ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now));
705 705
 	   }
706 706
 	   else
707 707
 	   {
708
-		   print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0);
708
+		   print $staticcontratligne->LibStatut($obj->statut, 5, ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now) ? 1 : 0);
709 709
 	   }
710 710
 	   print '</td>';
711
-       if (! $i) $totalarray['nbfield']++;
711
+       if (!$i) $totalarray['nbfield']++;
712 712
 	}
713 713
 	// Action column
714 714
 	print '<td class="nowrap" align="center">';
715 715
 	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
716 716
 	{
717
-		$selected=0;
718
-		if (in_array($obj->rowid, $arrayofselected)) $selected=1;
719
-		print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
717
+		$selected = 0;
718
+		if (in_array($obj->rowid, $arrayofselected)) $selected = 1;
719
+		print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
720 720
 	}
721 721
 	print '</td>';
722
-	if (! $i) $totalarray['nbfield']++;
722
+	if (!$i) $totalarray['nbfield']++;
723 723
 
724 724
 	print "</tr>\n";
725 725
 	$i++;
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
 // Show total line
729 729
 if (isset($totalarray['displaytotalline'])) {
730 730
 	print '<tr class="liste_total">';
731
-	$i=0;
731
+	$i = 0;
732 732
 	while ($i < $totalarray['nbfield']) {
733 733
 		$i++;
734 734
 		if ($i == 1) {
@@ -745,8 +745,8 @@  discard block
 block discarded – undo
745 745
 
746 746
 $db->free($resql);
747 747
 
748
-$parameters=array('sql' => $sql);
749
-$reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters);    // Note that $action and $object may have been modified by hook
748
+$parameters = array('sql' => $sql);
749
+$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook
750 750
 print $hookmanager->resPrint;
751 751
 
752 752
 print '</table>';
Please login to merge, or discard this patch.
Braces   +296 added lines, -108 removed lines patch added patch discarded remove patch
@@ -42,8 +42,12 @@  discard block
 block discarded – undo
42 42
 $offset = $limit * $page;
43 43
 $pageprev = $page - 1;
44 44
 $pagenext = $page + 1;
45
-if (! $sortfield) $sortfield="c.rowid";
46
-if (! $sortorder) $sortorder="ASC";
45
+if (! $sortfield) {
46
+    $sortfield="c.rowid";
47
+}
48
+if (! $sortorder) {
49
+    $sortorder="ASC";
50
+}
47 51
 
48 52
 $mode = GETPOST("mode");
49 53
 $filter=GETPOST("filter");
@@ -88,26 +92,36 @@  discard block
 block discarded – undo
88 92
 
89 93
 // Security check
90 94
 $contratid = GETPOST('id','int');
91
-if (! empty($user->societe_id)) $socid=$user->societe_id;
95
+if (! empty($user->societe_id)) {
96
+    $socid=$user->societe_id;
97
+}
92 98
 $result = restrictedArea($user, 'contrat',$contratid);
93 99
 
94 100
 if ($search_status != '')
95 101
 {
96 102
 	$tmp=explode('&', $search_status);
97 103
 	$mode=$tmp[0];
98
-	if (empty($tmp[1])) $filter='';
99
-	else
104
+	if (empty($tmp[1])) {
105
+	    $filter='';
106
+	} else
100 107
 	{
101
-		if ($tmp[1] == 'filter=notexpired') $filter='notexpired';
102
-		if ($tmp[1] == 'filter=expired') $filter='expired';
108
+		if ($tmp[1] == 'filter=notexpired') {
109
+		    $filter='notexpired';
110
+		}
111
+		if ($tmp[1] == 'filter=expired') {
112
+		    $filter='expired';
113
+		}
103 114
 	}
104
-}
105
-else
115
+} else
106 116
 {
107 117
 	$search_status = $mode;
108
-	if ($filter == 'expired') $search_status.='&filter=expired';
109
-	if ($filter == 'notexpired') $search_status.='&filter=notexpired';
110
-}
118
+	if ($filter == 'expired') {
119
+	    $search_status.='&filter=expired';
120
+	}
121
+	if ($filter == 'notexpired') {
122
+	    $search_status.='&filter=notexpired';
123
+	}
124
+	}
111 125
 
112 126
 $staticcontrat=new Contrat($db);
113 127
 $staticcontratligne=new ContratLigne($db);
@@ -135,7 +149,9 @@  discard block
 block discarded – undo
135 149
 {
136 150
 	foreach($extrafields->attribute_label as $key => $val)
137 151
 	{
138
-		if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key]));
152
+		if (! empty($extrafields->attribute_list[$key])) {
153
+		    $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key]));
154
+		}
139 155
 	}
140 156
 }
141 157
 
@@ -151,16 +167,20 @@  discard block
 block discarded – undo
151 167
 
152 168
 $parameters=array('socid'=>$socid);
153 169
 $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
154
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
170
+if ($reshook < 0) {
171
+    setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
172
+}
155 173
 
156 174
 if (empty($reshook))
157 175
 {
158 176
 	// Selection of new fields
159 177
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
160 178
 
161
-	if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers
179
+	if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) {
180
+	    // All test are required to be compatible with all browsers
162 181
 	{
163 182
    		$search_product_category=0;
183
+	}
164 184
 		$search_name="";
165 185
 		$search_contract="";
166 186
 		$search_service="";
@@ -201,7 +221,9 @@  discard block
 block discarded – undo
201 221
 $sql.= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,";
202 222
 $sql.= " cd.rowid, cd.description, cd.statut,";
203 223
 $sql.= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,";
204
-if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,";
224
+if (!$user->rights->societe->client->voir && !$socid) {
225
+    $sql .= " sc.fk_soc, sc.fk_user,";
226
+}
205 227
 $sql.= " cd.date_ouverture_prevue,";
206 228
 $sql.= " cd.date_ouverture,";
207 229
 $sql.= " cd.date_fin_validite,";
@@ -214,40 +236,78 @@  discard block
 block discarded – undo
214 236
 //$sql.= " cd.date_c as date_creation,";
215 237
 $sql.= " cd.tms as date_update";
216 238
 // Add fields from extrafields
217
-foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
239
+foreach ($extrafields->attribute_label as $key => $val) {
240
+    $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : '');
241
+}
218 242
 // Add fields from hooks
219 243
 $parameters=array();
220 244
 $reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters);    // Note that $action and $object may have been modified by hook
221 245
 $sql.=$hookmanager->resPrint;
222 246
 $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c,";
223 247
 $sql.= " ".MAIN_DB_PREFIX."societe as s,";
224
-if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,";
248
+if (!$user->rights->societe->client->voir && !$socid) {
249
+    $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,";
250
+}
225 251
 $sql.= " ".MAIN_DB_PREFIX."contratdet as cd";
226
-if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet_extrafields as ef on (cd.rowid = ef.fk_object)";
252
+if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) {
253
+    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet_extrafields as ef on (cd.rowid = ef.fk_object)";
254
+}
227 255
 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
228
-if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product';
256
+if ($search_product_category > 0) {
257
+    $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product';
258
+}
229 259
 $sql.= " WHERE c.entity = ".$conf->entity;
230 260
 $sql.= " AND c.rowid = cd.fk_contrat";
231
-if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$search_product_category;
261
+if ($search_product_category > 0) {
262
+    $sql.=" AND cp.fk_categorie = ".$search_product_category;
263
+}
232 264
 $sql.= " AND c.fk_soc = s.rowid";
233
-if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
234
-if ($mode == "0") $sql.= " AND cd.statut = 0";
235
-if ($mode == "4") $sql.= " AND cd.statut = 4";
236
-if ($mode == "5") $sql.= " AND cd.statut = 5";
237
-if ($filter == "expired") $sql.= " AND cd.date_fin_validite < '".$db->idate($now)."'";
238
-if ($filter == "notexpired") $sql.= " AND cd.date_fin_validite >= '".$db->idate($now)."'";
239
-if ($search_name)     $sql.= " AND s.nom LIKE '%".$db->escape($search_name)."%'";
240
-if ($search_contract) $sql.= " AND c.ref LIKE '%".$db->escape($search_contract)."%' ";
241
-if ($search_service)  $sql.= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')";
242
-if ($socid > 0)       $sql.= " AND s.rowid = ".$socid;
265
+if (!$user->rights->societe->client->voir && !$socid) {
266
+    $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
267
+}
268
+if ($mode == "0") {
269
+    $sql.= " AND cd.statut = 0";
270
+}
271
+if ($mode == "4") {
272
+    $sql.= " AND cd.statut = 4";
273
+}
274
+if ($mode == "5") {
275
+    $sql.= " AND cd.statut = 5";
276
+}
277
+if ($filter == "expired") {
278
+    $sql.= " AND cd.date_fin_validite < '".$db->idate($now)."'";
279
+}
280
+if ($filter == "notexpired") {
281
+    $sql.= " AND cd.date_fin_validite >= '".$db->idate($now)."'";
282
+}
283
+if ($search_name) {
284
+    $sql.= " AND s.nom LIKE '%".$db->escape($search_name)."%'";
285
+}
286
+if ($search_contract) {
287
+    $sql.= " AND c.ref LIKE '%".$db->escape($search_contract)."%' ";
288
+}
289
+if ($search_service) {
290
+    $sql.= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')";
291
+}
292
+if ($socid > 0) {
293
+    $sql.= " AND s.rowid = ".$socid;
294
+}
243 295
 $filter_dateouvertureprevue=dol_mktime(0,0,0,$opouvertureprevuemonth,$opouvertureprevueday,$opouvertureprevueyear);
244 296
 $filter_date1=dol_mktime(0,0,0,$op1month,$op1day,$op1year);
245 297
 $filter_date2=dol_mktime(0,0,0,$op2month,$op2day,$op2year);
246 298
 $filter_datecloture=dol_mktime(0,0,0,$opcloturemonth,$opclotureday,$opclotureyear);
247
-if (! empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_dateouvertureprevue != '') $sql.= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue)."'";
248
-if (! empty($filter_op1) && $filter_op1 != -1 && $filter_date1 != '') $sql.= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1)."'";
249
-if (! empty($filter_op2) && $filter_op2 != -1 && $filter_date2 != '') $sql.= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2)."'";
250
-if (! empty($filter_opcloture) && $filter_opcloture != -1 && $filter_datecloture != '') $sql.= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture)."'";
299
+if (! empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_dateouvertureprevue != '') {
300
+    $sql.= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue)."'";
301
+}
302
+if (! empty($filter_op1) && $filter_op1 != -1 && $filter_date1 != '') {
303
+    $sql.= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1)."'";
304
+}
305
+if (! empty($filter_op2) && $filter_op2 != -1 && $filter_date2 != '') {
306
+    $sql.= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2)."'";
307
+}
308
+if (! empty($filter_opcloture) && $filter_opcloture != -1 && $filter_datecloture != '') {
309
+    $sql.= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture)."'";
310
+}
251 311
 // Add where from extra fields
252 312
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
253 313
 $sql .= $db->order($sortfield,$sortorder);
@@ -257,9 +317,11 @@  discard block
 block discarded – undo
257 317
 {
258 318
 	$result = $db->query($sql);
259 319
 	$nbtotalofrecords = $db->num_rows($result);
260
-	if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
320
+	if (($page * $limit) > $nbtotalofrecords) {
321
+	    // if total resultset is smaller then paging size (filtering), goto and load page 0
261 322
 	{
262 323
 		$page = 0;
324
+	}
263 325
 		$offset = 0;
264 326
 	}
265 327
 }
@@ -289,22 +351,54 @@  discard block
 block discarded – undo
289 351
 llxHeader(null, $langs->trans("Services"));
290 352
 
291 353
 $param='';
292
-if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
293
-if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
294
-if ($search_contract) $param.='&amp;search_contract='.urlencode($search_contract);
295
-if ($search_name)      $param.='&amp;search_name='.urlencode($search_name);
296
-if ($search_service)  $param.='&amp;search_service='.urlencode($search_service);
297
-if ($mode)            $param.='&amp;mode='.urlencode($mode);
298
-if ($filter)          $param.='&amp;filter='.urlencode($filter);
299
-if (! empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) $param.='&amp;filter_opouvertureprevue='.urlencode($filter_opouvertureprevue);
300
-if (! empty($filter_op1) && $filter_op1 != -1) $param.='&amp;filter_op1='.urlencode($filter_op1);
301
-if (! empty($filter_op2) && $filter_op2 != -1) $param.='&amp;filter_op2='.urlencode($filter_op2);
302
-if (! empty($filter_opcloture) && $filter_opcloture != -1) $param.='&amp;filter_opcloture='.urlencode($filter_opcloture);
303
-if ($filter_dateouvertureprevue != '') $param.='&amp;opouvertureprevueday='.$opouvertureprevueday.'&amp;opouvertureprevuemonth='.$opouvertureprevuemonth.'&amp;opouvertureprevueyear='.$opouvertureprevueyear;
304
-if ($filter_date1 != '') $param.='&amp;op1day='.$op1day.'&amp;op1month='.$op1month.'&amp;op1year='.$op1year;
305
-if ($filter_date2 != '') $param.='&amp;op2day='.$op2day.'&amp;op2month='.$op2month.'&amp;op2year='.$op2year;
306
-if ($filter_datecloture != '') $param.='&amp;opclotureday='.$op2day.'&amp;opcloturemonth='.$op2month.'&amp;opclotureyear='.$op2year;
307
-if ($optioncss != '') $param.='&optioncss='.$optioncss;
354
+if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
355
+    $param.='&contextpage='.urlencode($contextpage);
356
+}
357
+if ($limit > 0 && $limit != $conf->liste_limit) {
358
+    $param.='&limit='.$limit;
359
+}
360
+if ($search_contract) {
361
+    $param.='&amp;search_contract='.urlencode($search_contract);
362
+}
363
+if ($search_name) {
364
+    $param.='&amp;search_name='.urlencode($search_name);
365
+}
366
+if ($search_service) {
367
+    $param.='&amp;search_service='.urlencode($search_service);
368
+}
369
+if ($mode) {
370
+    $param.='&amp;mode='.urlencode($mode);
371
+}
372
+if ($filter) {
373
+    $param.='&amp;filter='.urlencode($filter);
374
+}
375
+if (! empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) {
376
+    $param.='&amp;filter_opouvertureprevue='.urlencode($filter_opouvertureprevue);
377
+}
378
+if (! empty($filter_op1) && $filter_op1 != -1) {
379
+    $param.='&amp;filter_op1='.urlencode($filter_op1);
380
+}
381
+if (! empty($filter_op2) && $filter_op2 != -1) {
382
+    $param.='&amp;filter_op2='.urlencode($filter_op2);
383
+}
384
+if (! empty($filter_opcloture) && $filter_opcloture != -1) {
385
+    $param.='&amp;filter_opcloture='.urlencode($filter_opcloture);
386
+}
387
+if ($filter_dateouvertureprevue != '') {
388
+    $param.='&amp;opouvertureprevueday='.$opouvertureprevueday.'&amp;opouvertureprevuemonth='.$opouvertureprevuemonth.'&amp;opouvertureprevueyear='.$opouvertureprevueyear;
389
+}
390
+if ($filter_date1 != '') {
391
+    $param.='&amp;op1day='.$op1day.'&amp;op1month='.$op1month.'&amp;op1year='.$op1year;
392
+}
393
+if ($filter_date2 != '') {
394
+    $param.='&amp;op2day='.$op2day.'&amp;op2month='.$op2month.'&amp;op2year='.$op2year;
395
+}
396
+if ($filter_datecloture != '') {
397
+    $param.='&amp;opclotureday='.$op2day.'&amp;opcloturemonth='.$op2month.'&amp;opclotureyear='.$op2year;
398
+}
399
+if ($optioncss != '') {
400
+    $param.='&optioncss='.$optioncss;
401
+}
308 402
 // Add $param from extra fields
309 403
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
310 404
 
@@ -318,7 +412,9 @@  discard block
 block discarded – undo
318 412
 $massactionbutton=$form->selectMassAction('', $arrayofmassactions);
319 413
 
320 414
 print '<form method="POST" action="'. $_SERVER["PHP_SELF"] .'">';
321
-if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
415
+if ($optioncss != '') {
416
+    print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
417
+}
322 418
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
323 419
 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
324 420
 print '<input type="hidden" name="action" value="list">';
@@ -328,15 +424,26 @@  discard block
 block discarded – undo
328 424
 print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
329 425
 
330 426
 $title=$langs->trans("ListOfServices");
331
-if ($mode == "0") $title=$langs->trans("ListOfInactiveServices");	// Must use == "0"
332
-if ($mode == "4" && $filter != "expired") $title=$langs->trans("ListOfRunningServices");
333
-if ($mode == "4" && $filter == "expired") $title=$langs->trans("ListOfExpiredServices");
334
-if ($mode == "5") $title=$langs->trans("ListOfClosedServices");
427
+if ($mode == "0") {
428
+    $title=$langs->trans("ListOfInactiveServices");
429
+}
430
+// Must use == "0"
431
+if ($mode == "4" && $filter != "expired") {
432
+    $title=$langs->trans("ListOfRunningServices");
433
+}
434
+if ($mode == "4" && $filter == "expired") {
435
+    $title=$langs->trans("ListOfExpiredServices");
436
+}
437
+if ($mode == "5") {
438
+    $title=$langs->trans("ListOfClosedServices");
439
+}
335 440
 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit);
336 441
 
337 442
 if ($sall)
338 443
 {
339
-	foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
444
+	foreach($fieldstosearchall as $key => $val) {
445
+	    $fieldstosearchall[$key]=$langs->trans($val);
446
+	}
340 447
 	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall).'</div>';
341 448
 }
342 449
 
@@ -355,8 +462,11 @@  discard block
 block discarded – undo
355 462
 
356 463
 $parameters=array();
357 464
 $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters);    // Note that $action and $object may have been modified by hook
358
-if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
359
-else $moreforfilter = $hookmanager->resPrint;
465
+if (empty($reshook)) {
466
+    $moreforfilter .= $hookmanager->resPrint;
467
+} else {
468
+    $moreforfilter = $hookmanager->resPrint;
469
+}
360 470
 
361 471
 
362 472
 if (! empty($moreforfilter))
@@ -374,27 +484,57 @@  discard block
 block discarded – undo
374 484
 print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
375 485
 
376 486
 print '<tr class="liste_titre">';
377
-if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'],$_SERVER["PHP_SELF"],"c.ref","",$param,"",$sortfield,$sortorder);
378
-if (! empty($arrayfields['p.description']['checked'])) print_liste_field_titre($arrayfields['p.description']['label'],$_SERVER["PHP_SELF"],"p.description","",$param,"",$sortfield,$sortorder);
379
-if (! empty($arrayfields['cd.qty']['checked']))  print_liste_field_titre($arrayfields['cd.qty']['label'],$_SERVER["PHP_SELF"],"cd.qty","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
380
-if (! empty($arrayfields['cd.total_ht']['checked']))  print_liste_field_titre($arrayfields['cd.total_ht']['label'],$_SERVER["PHP_SELF"],"cd.total_ht","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
381
-if (! empty($arrayfields['cd.total_tva']['checked']))  print_liste_field_titre($arrayfields['cd.total_tva']['label'],$_SERVER["PHP_SELF"],"cd.total_tva","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
382
-if (! empty($arrayfields['cd.tva_tx']['checked']))  print_liste_field_titre($arrayfields['cd.tva_tx']['label'],$_SERVER["PHP_SELF"],"cd.tva_tx","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
383
-if (! empty($arrayfields['cd.subprice']['checked']))  print_liste_field_titre($arrayfields['cd.subprice']['label'],$_SERVER["PHP_SELF"],"cd.subprice","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
384
-if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder);
385
-if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'],$_SERVER["PHP_SELF"],"cd.date_ouverture_prevue","",$param,'align="center"',$sortfield,$sortorder);
386
-if (! empty($arrayfields['cd.date_ouverture']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture']['label'],$_SERVER["PHP_SELF"],"cd.date_ouverture","",$param,'align="center"',$sortfield,$sortorder);
387
-if (! empty($arrayfields['cd.date_fin_validite']['checked'])) print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'],$_SERVER["PHP_SELF"],"cd.date_fin_validite","",$param,'align="center"',$sortfield,$sortorder);
388
-if (! empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre($arrayfields['cd.date_cloture']['label'],$_SERVER["PHP_SELF"],"cd.date_cloture","",$param,'align="center"',$sortfield,$sortorder);
487
+if (! empty($arrayfields['c.ref']['checked'])) {
488
+    print_liste_field_titre($arrayfields['c.ref']['label'],$_SERVER["PHP_SELF"],"c.ref","",$param,"",$sortfield,$sortorder);
489
+}
490
+if (! empty($arrayfields['p.description']['checked'])) {
491
+    print_liste_field_titre($arrayfields['p.description']['label'],$_SERVER["PHP_SELF"],"p.description","",$param,"",$sortfield,$sortorder);
492
+}
493
+if (! empty($arrayfields['cd.qty']['checked'])) {
494
+    print_liste_field_titre($arrayfields['cd.qty']['label'],$_SERVER["PHP_SELF"],"cd.qty","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
495
+}
496
+if (! empty($arrayfields['cd.total_ht']['checked'])) {
497
+    print_liste_field_titre($arrayfields['cd.total_ht']['label'],$_SERVER["PHP_SELF"],"cd.total_ht","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
498
+}
499
+if (! empty($arrayfields['cd.total_tva']['checked'])) {
500
+    print_liste_field_titre($arrayfields['cd.total_tva']['label'],$_SERVER["PHP_SELF"],"cd.total_tva","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
501
+}
502
+if (! empty($arrayfields['cd.tva_tx']['checked'])) {
503
+    print_liste_field_titre($arrayfields['cd.tva_tx']['label'],$_SERVER["PHP_SELF"],"cd.tva_tx","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
504
+}
505
+if (! empty($arrayfields['cd.subprice']['checked'])) {
506
+    print_liste_field_titre($arrayfields['cd.subprice']['label'],$_SERVER["PHP_SELF"],"cd.subprice","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
507
+}
508
+if (! empty($arrayfields['s.nom']['checked'])) {
509
+    print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder);
510
+}
511
+if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) {
512
+    print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'],$_SERVER["PHP_SELF"],"cd.date_ouverture_prevue","",$param,'align="center"',$sortfield,$sortorder);
513
+}
514
+if (! empty($arrayfields['cd.date_ouverture']['checked'])) {
515
+    print_liste_field_titre($arrayfields['cd.date_ouverture']['label'],$_SERVER["PHP_SELF"],"cd.date_ouverture","",$param,'align="center"',$sortfield,$sortorder);
516
+}
517
+if (! empty($arrayfields['cd.date_fin_validite']['checked'])) {
518
+    print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'],$_SERVER["PHP_SELF"],"cd.date_fin_validite","",$param,'align="center"',$sortfield,$sortorder);
519
+}
520
+if (! empty($arrayfields['cd.date_cloture']['checked'])) {
521
+    print_liste_field_titre($arrayfields['cd.date_cloture']['label'],$_SERVER["PHP_SELF"],"cd.date_cloture","",$param,'align="center"',$sortfield,$sortorder);
522
+}
389 523
 // Extra fields
390 524
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
391 525
 // Hook fields
392 526
 $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder);
393 527
 $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters);    // Note that $action and $object may have been modified by hook
394 528
 print $hookmanager->resPrint;
395
-if (! empty($arrayfields['cd.datec']['checked']))  print_liste_field_titre($arrayfields['cd.datec']['label'],$_SERVER["PHP_SELF"],"cd.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
396
-if (! empty($arrayfields['cd.tms']['checked']))    print_liste_field_titre($arrayfields['cd.tms']['label'],$_SERVER["PHP_SELF"],"cd.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
397
-if (! empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'],$_SERVER["PHP_SELF"],"cd.statut,c.statut","",$param,'align="right"',$sortfield,$sortorder);
529
+if (! empty($arrayfields['cd.datec']['checked'])) {
530
+    print_liste_field_titre($arrayfields['cd.datec']['label'],$_SERVER["PHP_SELF"],"cd.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
531
+}
532
+if (! empty($arrayfields['cd.tms']['checked'])) {
533
+    print_liste_field_titre($arrayfields['cd.tms']['label'],$_SERVER["PHP_SELF"],"cd.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder);
534
+}
535
+if (! empty($arrayfields['status']['checked'])) {
536
+    print_liste_field_titre($arrayfields['status']['label'],$_SERVER["PHP_SELF"],"cd.statut,c.statut","",$param,'align="right"',$sortfield,$sortorder);
537
+}
398 538
 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ');
399 539
 print "</tr>\n";
400 540
 
@@ -555,7 +695,9 @@  discard block
 block discarded – undo
555 695
 		print '<td>';
556 696
 		print $contractstatic->getNomUrl(1,16);
557 697
 		print '</td>';
558
-        if (! $i) $totalarray['nbfield']++;
698
+        if (! $i) {
699
+            $totalarray['nbfield']++;
700
+        }
559 701
 	}
560 702
 	// Service
561 703
 	if (! empty($arrayfields['p.description']['checked']))
@@ -569,15 +711,22 @@  discard block
 block discarded – undo
569 711
 			$productstatic->entity=$obj->pentity;
570 712
 			print $productstatic->getNomUrl(1,'',24);
571 713
 			print $obj->label?' - '.dol_trunc($obj->label,16):'';
572
-			if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description);
573
-		}
574
-		else
714
+			if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) {
715
+			    print '<br>'.dol_nl2br($obj->description);
716
+			}
717
+		} else
575 718
 		{
576
-			if ($obj->type == 0) print img_object($obj->description,'product').' '.dol_trunc($obj->description,24);
577
-			if ($obj->type == 1) print img_object($obj->description,'service').' '.dol_trunc($obj->description,24);
719
+			if ($obj->type == 0) {
720
+			    print img_object($obj->description,'product').' '.dol_trunc($obj->description,24);
721
+			}
722
+			if ($obj->type == 1) {
723
+			    print img_object($obj->description,'service').' '.dol_trunc($obj->description,24);
724
+			}
578 725
 		}
579 726
 		print '</td>';
580
-        if (! $i) $totalarray['nbfield']++;
727
+        if (! $i) {
728
+            $totalarray['nbfield']++;
729
+        }
581 730
 	}
582 731
 
583 732
 	if (! empty($arrayfields['cd.qty']['checked']))
@@ -585,7 +734,9 @@  discard block
 block discarded – undo
585 734
 		print '<td>';
586 735
 		print $obj->qty;
587 736
 		print '</td>';
588
-        if (! $i) $totalarray['nbfield']++;
737
+        if (! $i) {
738
+            $totalarray['nbfield']++;
739
+        }
589 740
 	}
590 741
 	if (! empty($arrayfields['cd.total_ht']['checked']))
591 742
 	{
@@ -616,14 +767,18 @@  discard block
 block discarded – undo
616 767
 		print '<td align="right">';
617 768
 		print price2num($obj->tva_tx).'%';
618 769
 		print '</td>';
619
-        if (! $i) $totalarray['nbfield']++;
770
+        if (! $i) {
771
+            $totalarray['nbfield']++;
772
+        }
620 773
 	}
621 774
 	if (! empty($arrayfields['cd.subprice']['checked']))
622 775
 	{
623 776
 		print '<td align="right">';
624 777
 		print price($obj->subprice);
625 778
 		print '</td>';
626
-        if (! $i) $totalarray['nbfield']++;
779
+        if (! $i) {
780
+            $totalarray['nbfield']++;
781
+        }
627 782
 	}
628 783
 
629 784
 
@@ -633,7 +788,9 @@  discard block
 block discarded – undo
633 788
 		print '<td>';
634 789
 		print $companystatic->getNomUrl(1,'customer',28);
635 790
 		print '</td>';
636
-        if (! $i) $totalarray['nbfield']++;
791
+        if (! $i) {
792
+            $totalarray['nbfield']++;
793
+        }
637 794
 	}
638 795
 
639 796
 	// Start date
@@ -641,16 +798,22 @@  discard block
 block discarded – undo
641 798
 	{
642 799
 		print '<td align="center">';
643 800
 		print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour'):'&nbsp;');
644
-		if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0)
645
-		print ' '.img_picto($langs->trans("Late"),"warning");
646
-		else print '&nbsp;&nbsp;&nbsp;&nbsp;';
801
+		if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) {
802
+				print ' '.img_picto($langs->trans("Late"),"warning");
803
+		} else {
804
+		    print '&nbsp;&nbsp;&nbsp;&nbsp;';
805
+		}
647 806
 		print '</td>';
648
-        if (! $i) $totalarray['nbfield']++;
807
+        if (! $i) {
808
+            $totalarray['nbfield']++;
809
+        }
649 810
 	}
650 811
 	if (! empty($arrayfields['cd.date_ouverture']['checked']))
651 812
 	{
652 813
 		print '<td align="center">'.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour'):'&nbsp;').'</td>';
653
-        if (! $i) $totalarray['nbfield']++;
814
+        if (! $i) {
815
+            $totalarray['nbfield']++;
816
+        }
654 817
 	}
655 818
 	// End date
656 819
 	if (! empty($arrayfields['cd.date_fin_validite']['checked']))
@@ -661,16 +824,21 @@  discard block
 block discarded – undo
661 824
 			$warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24;
662 825
 			$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
663 826
 			print img_warning($textlate);
827
+		} else {
828
+		    print '&nbsp;&nbsp;&nbsp;&nbsp;';
664 829
 		}
665
-		else print '&nbsp;&nbsp;&nbsp;&nbsp;';
666 830
 		print '</td>';
667
-        if (! $i) $totalarray['nbfield']++;
831
+        if (! $i) {
832
+            $totalarray['nbfield']++;
833
+        }
668 834
 	}
669 835
 	// Close date (real end date)
670 836
 	if (! empty($arrayfields['cd.date_cloture']['checked']))
671 837
 	{
672 838
 		print '<td align="center">'.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').'</td>';
673
-        if (! $i) $totalarray['nbfield']++;
839
+        if (! $i) {
840
+            $totalarray['nbfield']++;
841
+        }
674 842
 	}
675 843
 
676 844
 	// Extra fields
@@ -685,7 +853,9 @@  discard block
 block discarded – undo
685 853
 		print '<td align="center">';
686 854
 		print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
687 855
 		print '</td>';
688
-		if (! $i) $totalarray['nbfield']++;
856
+		if (! $i) {
857
+		    $totalarray['nbfield']++;
858
+		}
689 859
 	}
690 860
 	// Date modification
691 861
 	if (! empty($arrayfields['cd.tms']['checked']))
@@ -693,33 +863,44 @@  discard block
 block discarded – undo
693 863
 		print '<td align="center">';
694 864
 		print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
695 865
 		print '</td>';
696
-		if (! $i) $totalarray['nbfield']++;
866
+		if (! $i) {
867
+		    $totalarray['nbfield']++;
868
+		}
697 869
 	}
698 870
 	// Status
699 871
 	if (! empty($arrayfields['status']['checked']))
700 872
 	{
701 873
 	   print '<td align="right">';
702
-	   if ($obj->cstatut == 0)	// If contract is draft, we say line is also draft
874
+	   if ($obj->cstatut == 0) {
875
+	       // If contract is draft, we say line is also draft
703 876
 	   {
704 877
 		   print $contractstatic->LibStatut(0,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now));
705 878
 	   }
706
-	   else
879
+	   } else
707 880
 	   {
708 881
 		   print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0);
709 882
 	   }
710 883
 	   print '</td>';
711
-       if (! $i) $totalarray['nbfield']++;
884
+       if (! $i) {
885
+           $totalarray['nbfield']++;
886
+       }
712 887
 	}
713 888
 	// Action column
714 889
 	print '<td class="nowrap" align="center">';
715
-	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
890
+	if ($massactionbutton || $massaction) {
891
+	    // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
716 892
 	{
717 893
 		$selected=0;
718
-		if (in_array($obj->rowid, $arrayofselected)) $selected=1;
894
+	}
895
+		if (in_array($obj->rowid, $arrayofselected)) {
896
+		    $selected=1;
897
+		}
719 898
 		print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
720 899
 	}
721 900
 	print '</td>';
722
-	if (! $i) $totalarray['nbfield']++;
901
+	if (! $i) {
902
+	    $totalarray['nbfield']++;
903
+	}
723 904
 
724 905
 	print "</tr>\n";
725 906
 	$i++;
@@ -732,13 +913,20 @@  discard block
 block discarded – undo
732 913
 	while ($i < $totalarray['nbfield']) {
733 914
 		$i++;
734 915
 		if ($i == 1) {
735
-			if ($num < $limit && empty($offset)) print '<td align="left">'.$langs->trans("Total").'</td>';
736
-			else print '<td align="left">'.$langs->trans("Totalforthispage").'</td>';
916
+			if ($num < $limit && empty($offset)) {
917
+			    print '<td align="left">'.$langs->trans("Total").'</td>';
918
+			} else {
919
+			    print '<td align="left">'.$langs->trans("Totalforthispage").'</td>';
920
+			}
921
+		} elseif ($totalarray['totalhtfield'] == $i) {
922
+		    print '<td align="right">'.price($totalarray['totalht']).'</td>';
923
+		} elseif ($totalarray['totalvatfield'] == $i) {
924
+		    print '<td align="right">'.price($totalarray['totalvat']).'</td>';
925
+		} elseif ($totalarray['totalttcfield'] == $i) {
926
+		    print '<td align="right">'.price($totalarray['totalttc']).'</td>';
927
+		} else {
928
+		    print '<td></td>';
737 929
 		}
738
-		elseif ($totalarray['totalhtfield'] == $i) print '<td align="right">'.price($totalarray['totalht']).'</td>';
739
-		elseif ($totalarray['totalvatfield'] == $i) print '<td align="right">'.price($totalarray['totalvat']).'</td>';
740
-		elseif ($totalarray['totalttcfield'] == $i) print '<td align="right">'.price($totalarray['totalttc']).'</td>';
741
-		else print '<td></td>';
742 930
 	}
743 931
 	print '</tr>';
744 932
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/contrat/admin/contractdet_extrafields.php 3 patches
Braces   +6 added lines, -2 removed lines patch added patch discarded remove patch
@@ -40,13 +40,17 @@
 block discarded – undo
40 40
 // List of supported format
41 41
 $tmptype2label=ExtraFields::$type2label;
42 42
 $type2label=array('');
43
-foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val);
43
+foreach ($tmptype2label as $key => $val) {
44
+    $type2label[$key]=$langs->transnoentitiesnoconv($val);
45
+}
44 46
 
45 47
 $action=GETPOST('action', 'alpha');
46 48
 $attrname=GETPOST('attrname', 'alpha');
47 49
 $elementtype='contratdet';  //Must be the $element of the class that manage extrafield
48 50
 
49
-if (!$user->admin) accessforbidden();
51
+if (!$user->admin) {
52
+    accessforbidden();
53
+}
50 54
 
51 55
 
52 56
 /*
Please login to merge, or discard this patch.
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -93,8 +93,8 @@
 block discarded – undo
93 93
 
94 94
 if ($action == 'create')
95 95
 {
96
-	print '<br><div id="newattrib"></div>';
97
-	print load_fiche_titre($langs->trans('NewAttribute'));
96
+    print '<br><div id="newattrib"></div>';
97
+    print load_fiche_titre($langs->trans('NewAttribute'));
98 98
 
99 99
     require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
100 100
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
 
31 31
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
32 32
 defined('BASE_PATH') or die('Single entry point through the index.php of the main folder');
33
-require DOL_BASE_PATH . '/main.inc.php';
33
+require DOL_BASE_PATH.'/main.inc.php';
34 34
 require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
35 35
 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
36 36
 
@@ -41,13 +41,13 @@  discard block
 block discarded – undo
41 41
 $form = new Form($db);
42 42
 
43 43
 // List of supported format
44
-$tmptype2label=ExtraFields::$type2label;
45
-$type2label=array('');
46
-foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val);
44
+$tmptype2label = ExtraFields::$type2label;
45
+$type2label = array('');
46
+foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val);
47 47
 
48
-$action=GETPOST('action', 'alpha');
49
-$attrname=GETPOST('attrname', 'alpha');
50
-$elementtype='contratdet';  //Must be the $element of the class that manage extrafield
48
+$action = GETPOST('action', 'alpha');
49
+$attrname = GETPOST('attrname', 'alpha');
50
+$elementtype = 'contratdet'; //Must be the $element of the class that manage extrafield
51 51
 
52 52
 if (!$user->admin) accessforbidden();
53 53
 
@@ -68,10 +68,10 @@  discard block
 block discarded – undo
68 68
 
69 69
 llxHeader();
70 70
 
71
-$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
72
-print load_fiche_titre($langs->trans("ContractsSetup"),$linkback,'title_setup');
71
+$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
72
+print load_fiche_titre($langs->trans("ContractsSetup"), $linkback, 'title_setup');
73 73
 
74
-$head=contract_admin_prepare_head();
74
+$head = contract_admin_prepare_head();
75 75
 
76 76
 dol_fiche_head($head, 'attributeslines', $langs->trans("Contracts"), -1, 'contract');
77 77
 
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 /* Edition d'un champ optionnel                                               */
109 109
 /*                                                                            */
110 110
 /* ************************************************************************** */
111
-if ($action == 'edit' && ! empty($attrname))
111
+if ($action == 'edit' && !empty($attrname))
112 112
 {
113 113
     print "<br>";
114 114
     print load_fiche_titre($langs->trans("FieldEdition", $attrname));
Please login to merge, or discard this patch.
dolibarr/htdocs/contrat/admin/contract_extrafields.php 3 patches
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 
95 95
 if ($action == 'create')
96 96
 {
97
-	print '<br><div name="topofform" id="newattrib"></div>';
97
+    print '<br><div name="topofform" id="newattrib"></div>';
98 98
     print load_fiche_titre($langs->trans('NewAttribute'));
99 99
 
100 100
     require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 /* ************************************************************************** */
108 108
 if ($action == 'edit' && ! empty($attrname))
109 109
 {
110
-	print '<div name="topofform"></div><br>';
110
+    print '<div name="topofform"></div><br>';
111 111
     print load_fiche_titre($langs->trans("FieldEdition", $attrname));
112 112
 
113 113
     require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php';
Please login to merge, or discard this patch.
Braces   +6 added lines, -2 removed lines patch added patch discarded remove patch
@@ -40,13 +40,17 @@
 block discarded – undo
40 40
 // List of supported format
41 41
 $tmptype2label=ExtraFields::$type2label;
42 42
 $type2label=array('');
43
-foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val);
43
+foreach ($tmptype2label as $key => $val) {
44
+    $type2label[$key]=$langs->transnoentitiesnoconv($val);
45
+}
44 46
 
45 47
 $action=GETPOST('action', 'alpha');
46 48
 $attrname=GETPOST('attrname', 'alpha');
47 49
 $elementtype='contrat';  //Must be the $element of the class that manage extrafield
48 50
 
49
-if (!$user->admin) accessforbidden();
51
+if (!$user->admin) {
52
+    accessforbidden();
53
+}
50 54
 
51 55
 
52 56
 /*
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -30,24 +30,24 @@  discard block
 block discarded – undo
30 30
 
31 31
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
32 32
 defined('BASE_PATH') or die('Single entry point through the index.php of the main folder');
33
-require DOL_BASE_PATH . '/main.inc.php';
33
+require DOL_BASE_PATH.'/main.inc.php';
34 34
 require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
35 35
 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
36 36
 
37 37
 // Load translation files required by the page
38
-$langs->loadLangs(array("companies","admin","contracts"));
38
+$langs->loadLangs(array("companies", "admin", "contracts"));
39 39
 
40 40
 $extrafields = new ExtraFields($db);
41 41
 $form = new Form($db);
42 42
 
43 43
 // List of supported format
44
-$tmptype2label=ExtraFields::$type2label;
45
-$type2label=array('');
46
-foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val);
44
+$tmptype2label = ExtraFields::$type2label;
45
+$type2label = array('');
46
+foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val);
47 47
 
48
-$action=GETPOST('action', 'alpha');
49
-$attrname=GETPOST('attrname', 'alpha');
50
-$elementtype='contrat';  //Must be the $element of the class that manage extrafield
48
+$action = GETPOST('action', 'alpha');
49
+$attrname = GETPOST('attrname', 'alpha');
50
+$elementtype = 'contrat'; //Must be the $element of the class that manage extrafield
51 51
 
52 52
 if (!$user->admin) accessforbidden();
53 53
 
@@ -68,10 +68,10 @@  discard block
 block discarded – undo
68 68
 
69 69
 llxHeader();
70 70
 
71
-$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
72
-print load_fiche_titre($langs->trans("ContractsSetup"),$linkback,'title_setup');
71
+$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
72
+print load_fiche_titre($langs->trans("ContractsSetup"), $linkback, 'title_setup');
73 73
 
74
-$head=contract_admin_prepare_head();
74
+$head = contract_admin_prepare_head();
75 75
 
76 76
 dol_fiche_head($head, 'attributes', $langs->trans("Contracts"), -1, 'contract');
77 77
 
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 /* Edition of an optional field                                               */
109 109
 /*                                                                            */
110 110
 /* ************************************************************************** */
111
-if ($action == 'edit' && ! empty($attrname))
111
+if ($action == 'edit' && !empty($attrname))
112 112
 {
113 113
 	print '<div name="topofform"></div><br>';
114 114
     print load_fiche_titre($langs->trans("FieldEdition", $attrname));
Please login to merge, or discard this patch.