Test Failed
Push — master ( d56fde...b8c830 )
by Alxarafe
37:54
created
dolibarr/htdocs/societe/class/societe.class.php 1 patch
Indentation   +3920 added lines, -3920 removed lines patch added patch discarded remove patch
@@ -42,313 +42,313 @@  discard block
 block discarded – undo
42 42
  */
43 43
 class Societe extends CommonObject
44 44
 {
45
-	/**
46
-	 * @var string ID to identify managed object
47
-	 */
48
-	public $element='societe';
49
-
50
-	/**
51
-	 * @var string Name of table without prefix where object is stored
52
-	 */
53
-	public $table_element = 'societe';
54
-
55
-	/**
56
-	 * @var int Field with ID of parent key if this field has a parent
57
-	 */
58
-	public $fk_element='fk_soc';
59
-
60
-	public $fieldsforcombobox='nom,name_alias';
61
-	protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord');    // To test if we can delete object
62
-	protected $childtablesoncascade=array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm");
63
-	public $picto = 'company';
64
-
65
-	/**
66
-	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
67
-	 * @var int
68
-	 */
69
-	public $ismultientitymanaged = 1;
70
-
71
-	/**
72
-	 * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
73
-	 * @var integer
74
-	 */
75
-	public $restrictiononfksoc = 1;
76
-
77
-
78
-	// BEGIN MODULEBUILDER PROPERTIES
79
-	/**
80
-	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
81
-	 */
82
-	public $fields=array(
83
-		'rowid'         =>array('type'=>'integer',      'label'=>'TechnicalID',      'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'index'=>1, 'position'=>1, 'comment'=>'Id'),
84
-		'nom'           =>array('type'=>'varchar(128)', 'label'=>'Name',             'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
85
-		'name_alias'    =>array('type'=>'varchar(128)', 'label'=>'Name',             'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
86
-		'entity'        =>array('type'=>'integer',      'label'=>'Entity',           'enabled'=>1, 'visible'=>0,  'default'=>1,  'notnull'=>1,  'index'=>1, 'position'=>20),
87
-		'note_public'   =>array('type'=>'text',			'label'=>'NotePublic',		 'enabled'=>1, 'visible'=>0,  'position'=>60),
88
-		'note_private'  =>array('type'=>'text',			'label'=>'NotePrivate',		 'enabled'=>1, 'visible'=>0,  'position'=>61),
89
-		'datec'			=>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>500),
90
-		'tms'           =>array('type'=>'timestamp',    'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>501),
91
-		//'date_valid'    =>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>-2, 'position'=>502),
92
-		'fk_user_creat' =>array('type'=>'integer',      'label'=>'UserAuthor',       'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>510),
93
-		'fk_user_modif' =>array('type'=>'integer',      'label'=>'UserModif',        'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
94
-		//'fk_user_valid' =>array('type'=>'integer',      'label'=>'UserValidation',        'enabled'=>1, 'visible'=>-1, 'position'=>512),
95
-		'import_key'    =>array('type'=>'varchar(14)',  'label'=>'ImportId',         'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>1,  'position'=>1000),
96
-	);
97
-
98
-
99
-	/**
100
-	 * @var int Entity
101
-	 */
102
-	public $entity;
103
-
104
-	/**
105
-	 * Thirdparty name
106
-	 * @var string
107
-	 * @deprecated Use $name instead
108
-	 * @see $name
109
-	 */
110
-	public $nom;
111
-
112
-	/**
113
-	 * @var string name
114
-	 */
115
-	public $name;
116
-
117
-	/**
118
-	 * Alias names (commercial, trademark or alias names)
119
-	 * @var string
120
-	 */
121
-	public $name_alias;
122
-
123
-	public $particulier;
124
-
125
-	/**
126
-	 * @var string Address
127
-	 */
128
-	public $address;
129
-
130
-	public $zip;
131
-	public $town;
132
-
133
-	/**
134
-	 * Thirdparty status : 0=activity ceased, 1= in activity
135
-	 * @var int
136
-	 */
137
-	public $status=1;
138
-
139
-	/**
140
-	 * Id of department
141
-	 * @var int
142
-	 */
143
-	public $state_id;
144
-	public $state_code;
145
-	public $state;
146
-
147
-	/**
148
-	 * Id of region
149
-	 * @var int
150
-	 */
151
-	public $region_code;
152
-	public $region;
153
-
154
-	/**
155
-	 * State code
156
-	 * @var string
157
-	 * @deprecated Use state_code instead
158
-	 * @see $state_code
159
-	 */
160
-	public $departement_code;
161
-
162
-	/**
163
-	 * @var string
164
-	 * @deprecated Use state instead
165
-	 * @see $state
166
-	 */
167
-	public $departement;
168
-
169
-	/**
170
-	 * @var string
171
-	 * @deprecated Use country instead
172
-	 * @see $country
173
-	 */
174
-	public $pays;
175
-
176
-	/**
177
-	 * Phone number
178
-	 * @var string
179
-	 */
180
-	public $phone;
181
-	/**
182
-	 * Fax number
183
-	 * @var string
184
-	 */
185
-	public $fax;
186
-	/**
187
-	 * Email
188
-	 * @var string
189
-	 */
190
-	public $email;
191
-	/**
192
-	 * Skype username
193
-	 * @var string
194
-	 */
195
-	public $skype;
196
-	/**
197
-	 * Twitter username
198
-	 * @var string
199
-	 */
200
-	public $twitter;
201
-	/**
202
-	 * Facebook username
203
-	 * @var string
204
-	 */
205
-	public $facebook;
206
-	/**
207
-	 * Webpage
208
-	 * @var string
209
-	 */
210
-	public $url;
211
-
212
-	//! barcode
213
-	/**
214
-	 * Barcode value
215
-	 * @var string
216
-	 */
217
-	public $barcode;
218
-
219
-	// 6 professional id (usage depends on country)
220
-
221
-	/**
222
-	 * Professional ID 1 (Ex: Siren in France)
223
-	 * @var string
224
-	 */
225
-	public $idprof1;
226
-
227
-	/**
228
-	 * Professional ID 2 (Ex: Siret in France)
229
-	 * @var string
230
-	 */
231
-	public $idprof2;
232
-
233
-	/**
234
-	 * Professional ID 3 (Ex: Ape in France)
235
-	 * @var string
236
-	 */
237
-	public $idprof3;
238
-
239
-	/**
240
-	 * Professional ID 4 (Ex: RCS in France)
241
-	 * @var string
242
-	 */
243
-	public $idprof4;
244
-
245
-	/**
246
-	 * Professional ID 5
247
-	 * @var string
248
-	 */
249
-	public $idprof5;
250
-
251
-	/**
252
-	 * Professional ID 6
253
-	 * @var string
254
-	 */
255
-	public $idprof6;
256
-
257
-	public $prefix_comm;
258
-
259
-	public $tva_assuj=1;
260
-	/**
261
-	 * Intracommunitary VAT ID
262
-	 * @var string
263
-	 */
264
-	public $tva_intra;
265
-
266
-	// Local taxes
267
-	public $localtax1_assuj;
268
-	public $localtax1_value;
269
-	public $localtax2_assuj;
270
-	public $localtax2_value;
271
-
272
-	public $managers;
273
-	public $capital;
274
-	public $typent_id=0;
275
-	public $typent_code;
276
-	public $effectif;
277
-	public $effectif_id=0;
278
-	public $forme_juridique_code;
279
-	public $forme_juridique=0;
280
-
281
-	public $remise_percent;
282
-	public $remise_supplier_percent;
283
-	public $mode_reglement_supplier_id;
284
-	public $cond_reglement_supplier_id;
285
-
286
-	/**
45
+    /**
46
+     * @var string ID to identify managed object
47
+     */
48
+    public $element='societe';
49
+
50
+    /**
51
+     * @var string Name of table without prefix where object is stored
52
+     */
53
+    public $table_element = 'societe';
54
+
55
+    /**
56
+     * @var int Field with ID of parent key if this field has a parent
57
+     */
58
+    public $fk_element='fk_soc';
59
+
60
+    public $fieldsforcombobox='nom,name_alias';
61
+    protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord');    // To test if we can delete object
62
+    protected $childtablesoncascade=array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm");
63
+    public $picto = 'company';
64
+
65
+    /**
66
+     * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
67
+     * @var int
68
+     */
69
+    public $ismultientitymanaged = 1;
70
+
71
+    /**
72
+     * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
73
+     * @var integer
74
+     */
75
+    public $restrictiononfksoc = 1;
76
+
77
+
78
+    // BEGIN MODULEBUILDER PROPERTIES
79
+    /**
80
+     * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
81
+     */
82
+    public $fields=array(
83
+        'rowid'         =>array('type'=>'integer',      'label'=>'TechnicalID',      'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'index'=>1, 'position'=>1, 'comment'=>'Id'),
84
+        'nom'           =>array('type'=>'varchar(128)', 'label'=>'Name',             'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
85
+        'name_alias'    =>array('type'=>'varchar(128)', 'label'=>'Name',             'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
86
+        'entity'        =>array('type'=>'integer',      'label'=>'Entity',           'enabled'=>1, 'visible'=>0,  'default'=>1,  'notnull'=>1,  'index'=>1, 'position'=>20),
87
+        'note_public'   =>array('type'=>'text',			'label'=>'NotePublic',		 'enabled'=>1, 'visible'=>0,  'position'=>60),
88
+        'note_private'  =>array('type'=>'text',			'label'=>'NotePrivate',		 'enabled'=>1, 'visible'=>0,  'position'=>61),
89
+        'datec'			=>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>500),
90
+        'tms'           =>array('type'=>'timestamp',    'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>501),
91
+        //'date_valid'    =>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>-2, 'position'=>502),
92
+        'fk_user_creat' =>array('type'=>'integer',      'label'=>'UserAuthor',       'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>510),
93
+        'fk_user_modif' =>array('type'=>'integer',      'label'=>'UserModif',        'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
94
+        //'fk_user_valid' =>array('type'=>'integer',      'label'=>'UserValidation',        'enabled'=>1, 'visible'=>-1, 'position'=>512),
95
+        'import_key'    =>array('type'=>'varchar(14)',  'label'=>'ImportId',         'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>1,  'position'=>1000),
96
+    );
97
+
98
+
99
+    /**
100
+     * @var int Entity
101
+     */
102
+    public $entity;
103
+
104
+    /**
105
+     * Thirdparty name
106
+     * @var string
107
+     * @deprecated Use $name instead
108
+     * @see $name
109
+     */
110
+    public $nom;
111
+
112
+    /**
113
+     * @var string name
114
+     */
115
+    public $name;
116
+
117
+    /**
118
+     * Alias names (commercial, trademark or alias names)
119
+     * @var string
120
+     */
121
+    public $name_alias;
122
+
123
+    public $particulier;
124
+
125
+    /**
126
+     * @var string Address
127
+     */
128
+    public $address;
129
+
130
+    public $zip;
131
+    public $town;
132
+
133
+    /**
134
+     * Thirdparty status : 0=activity ceased, 1= in activity
135
+     * @var int
136
+     */
137
+    public $status=1;
138
+
139
+    /**
140
+     * Id of department
141
+     * @var int
142
+     */
143
+    public $state_id;
144
+    public $state_code;
145
+    public $state;
146
+
147
+    /**
148
+     * Id of region
149
+     * @var int
150
+     */
151
+    public $region_code;
152
+    public $region;
153
+
154
+    /**
155
+     * State code
156
+     * @var string
157
+     * @deprecated Use state_code instead
158
+     * @see $state_code
159
+     */
160
+    public $departement_code;
161
+
162
+    /**
163
+     * @var string
164
+     * @deprecated Use state instead
165
+     * @see $state
166
+     */
167
+    public $departement;
168
+
169
+    /**
170
+     * @var string
171
+     * @deprecated Use country instead
172
+     * @see $country
173
+     */
174
+    public $pays;
175
+
176
+    /**
177
+     * Phone number
178
+     * @var string
179
+     */
180
+    public $phone;
181
+    /**
182
+     * Fax number
183
+     * @var string
184
+     */
185
+    public $fax;
186
+    /**
187
+     * Email
188
+     * @var string
189
+     */
190
+    public $email;
191
+    /**
192
+     * Skype username
193
+     * @var string
194
+     */
195
+    public $skype;
196
+    /**
197
+     * Twitter username
198
+     * @var string
199
+     */
200
+    public $twitter;
201
+    /**
202
+     * Facebook username
203
+     * @var string
204
+     */
205
+    public $facebook;
206
+    /**
207
+     * Webpage
208
+     * @var string
209
+     */
210
+    public $url;
211
+
212
+    //! barcode
213
+    /**
214
+     * Barcode value
215
+     * @var string
216
+     */
217
+    public $barcode;
218
+
219
+    // 6 professional id (usage depends on country)
220
+
221
+    /**
222
+     * Professional ID 1 (Ex: Siren in France)
223
+     * @var string
224
+     */
225
+    public $idprof1;
226
+
227
+    /**
228
+     * Professional ID 2 (Ex: Siret in France)
229
+     * @var string
230
+     */
231
+    public $idprof2;
232
+
233
+    /**
234
+     * Professional ID 3 (Ex: Ape in France)
235
+     * @var string
236
+     */
237
+    public $idprof3;
238
+
239
+    /**
240
+     * Professional ID 4 (Ex: RCS in France)
241
+     * @var string
242
+     */
243
+    public $idprof4;
244
+
245
+    /**
246
+     * Professional ID 5
247
+     * @var string
248
+     */
249
+    public $idprof5;
250
+
251
+    /**
252
+     * Professional ID 6
253
+     * @var string
254
+     */
255
+    public $idprof6;
256
+
257
+    public $prefix_comm;
258
+
259
+    public $tva_assuj=1;
260
+    /**
261
+     * Intracommunitary VAT ID
262
+     * @var string
263
+     */
264
+    public $tva_intra;
265
+
266
+    // Local taxes
267
+    public $localtax1_assuj;
268
+    public $localtax1_value;
269
+    public $localtax2_assuj;
270
+    public $localtax2_value;
271
+
272
+    public $managers;
273
+    public $capital;
274
+    public $typent_id=0;
275
+    public $typent_code;
276
+    public $effectif;
277
+    public $effectif_id=0;
278
+    public $forme_juridique_code;
279
+    public $forme_juridique=0;
280
+
281
+    public $remise_percent;
282
+    public $remise_supplier_percent;
283
+    public $mode_reglement_supplier_id;
284
+    public $cond_reglement_supplier_id;
285
+
286
+    /**
287 287
      * @var int ID
288 288
      */
289
-	public $fk_prospectlevel;
290
-
291
-	public $name_bis;
292
-
293
-	//Log data
294
-
295
-	/**
296
-	 * Date of last update
297
-	 * @var string
298
-	 */
299
-	public $date_modification;
300
-	/**
301
-	 * User that made last update
302
-	 * @var string
303
-	 */
304
-	public $user_modification;
305
-	/**
306
-	 * Date of creation
307
-	 * @var string
308
-	 */
309
-	public $date_creation;
310
-	/**
311
-	 * User that created the thirdparty
312
-	 * @var User
313
-	 */
314
-	public $user_creation;
315
-
316
-
317
-	public $specimen;
318
-
319
-	/**
320
-	 * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
321
-	 * @var int
322
-	 */
323
-	public $client=0;
324
-	/**
325
-	 * 0=no prospect, 1=prospect
326
-	 * @var int
327
-	 */
328
-	public $prospect=0;
329
-	/**
330
-	 * 0=no supplier, 1=supplier
331
-	 * @var int
332
-	 */
333
-	public $fournisseur;
334
-
335
-	/**
336
-	 * Client code. E.g: CU2014-003
337
-	 * @var string
338
-	 */
339
-	public $code_client;
340
-
341
-	/**
342
-	 * Supplier code. E.g: SU2014-003
343
-	 * @var string
344
-	 */
345
-	public $code_fournisseur;
346
-
347
-	/**
348
-	 * Accounting code for client
349
-	 * @var string
350
-	 */
351
-	public $code_compta;
289
+    public $fk_prospectlevel;
290
+
291
+    public $name_bis;
292
+
293
+    //Log data
294
+
295
+    /**
296
+     * Date of last update
297
+     * @var string
298
+     */
299
+    public $date_modification;
300
+    /**
301
+     * User that made last update
302
+     * @var string
303
+     */
304
+    public $user_modification;
305
+    /**
306
+     * Date of creation
307
+     * @var string
308
+     */
309
+    public $date_creation;
310
+    /**
311
+     * User that created the thirdparty
312
+     * @var User
313
+     */
314
+    public $user_creation;
315
+
316
+
317
+    public $specimen;
318
+
319
+    /**
320
+     * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
321
+     * @var int
322
+     */
323
+    public $client=0;
324
+    /**
325
+     * 0=no prospect, 1=prospect
326
+     * @var int
327
+     */
328
+    public $prospect=0;
329
+    /**
330
+     * 0=no supplier, 1=supplier
331
+     * @var int
332
+     */
333
+    public $fournisseur;
334
+
335
+    /**
336
+     * Client code. E.g: CU2014-003
337
+     * @var string
338
+     */
339
+    public $code_client;
340
+
341
+    /**
342
+     * Supplier code. E.g: SU2014-003
343
+     * @var string
344
+     */
345
+    public $code_fournisseur;
346
+
347
+    /**
348
+     * Accounting code for client
349
+     * @var string
350
+     */
351
+    public $code_compta;
352 352
 
353 353
     /**
354 354
      * Accounting code for client
@@ -356,3795 +356,3795 @@  discard block
 block discarded – undo
356 356
      */
357 357
     public $code_compta_client;
358 358
 
359
-	/**
360
-	 * Accounting code for suppliers
361
-	 * @var string
362
-	 */
363
-	public $code_compta_fournisseur;
364
-
365
-	/**
366
-	 * @var string
367
-	 * @deprecated Note is split in public and private notes
368
-	 * @see $note_public, $note_private
369
-	 */
370
-	public $note;
371
-
372
-	/**
373
-	 * Private note
374
-	 * @var string
375
-	 */
376
-	public $note_private;
377
-
378
-	/**
379
-	 * Public note
380
-	 * @var string
381
-	 */
382
-	public $note_public;
383
-
384
-	//! code statut prospect
385
-	public $stcomm_id;
386
-	public $statut_commercial;
387
-
388
-	/**
389
-	 * Assigned price level
390
-	 * @var int
391
-	 */
392
-	public $price_level;
393
-	public $outstanding_limit;
394
-
395
-	/**
396
-	 * Min order amounts
397
-	 */
398
-	public $order_min_amount;
399
-	public $supplier_order_min_amount;
400
-
401
-	/**
402
-	 * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
403
-	 * @var int
404
-	 */
405
-	public $commercial_id;
406
-	/**
407
-	 * Id of parent thirdparty (if one)
408
-	 * @var int
409
-	 */
410
-	public $parent;
411
-	/**
412
-	 * Default language code of thirdparty (en_US, ...)
413
-	 * @var string
414
-	 */
415
-	public $default_lang;
416
-
417
-	/**
418
-	 * @var string Ref
419
-	 */
420
-	public $ref;
421
-
422
-	public $ref_int;
423
-	/**
424
-	 * External user reference.
425
-	 * This is to allow external systems to store their id and make self-developed synchronizing functions easier to
426
-	 * build.
427
-	 * @var string
428
-	 */
429
-	public $ref_ext;
430
-
431
-	/**
432
-	 * Import key.
433
-	 * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
434
-	 * to an import process
435
-	 * @var string
436
-	 */
437
-	public $import_key;
438
-
439
-	/**
440
-	 * Supplier WebServices URL
441
-	 * @var string
442
-	 */
443
-	public $webservices_url;
444
-
445
-	/**
446
-	 * Supplier WebServices Key
447
-	 * @var string
448
-	 */
449
-	public $webservices_key;
450
-
451
-	public $logo;
452
-	public $logo_small;
453
-	public $logo_mini;
454
-
455
-	public $array_options;
456
-
457
-	// Incoterms
458
-	/**
359
+    /**
360
+     * Accounting code for suppliers
361
+     * @var string
362
+     */
363
+    public $code_compta_fournisseur;
364
+
365
+    /**
366
+     * @var string
367
+     * @deprecated Note is split in public and private notes
368
+     * @see $note_public, $note_private
369
+     */
370
+    public $note;
371
+
372
+    /**
373
+     * Private note
374
+     * @var string
375
+     */
376
+    public $note_private;
377
+
378
+    /**
379
+     * Public note
380
+     * @var string
381
+     */
382
+    public $note_public;
383
+
384
+    //! code statut prospect
385
+    public $stcomm_id;
386
+    public $statut_commercial;
387
+
388
+    /**
389
+     * Assigned price level
390
+     * @var int
391
+     */
392
+    public $price_level;
393
+    public $outstanding_limit;
394
+
395
+    /**
396
+     * Min order amounts
397
+     */
398
+    public $order_min_amount;
399
+    public $supplier_order_min_amount;
400
+
401
+    /**
402
+     * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
403
+     * @var int
404
+     */
405
+    public $commercial_id;
406
+    /**
407
+     * Id of parent thirdparty (if one)
408
+     * @var int
409
+     */
410
+    public $parent;
411
+    /**
412
+     * Default language code of thirdparty (en_US, ...)
413
+     * @var string
414
+     */
415
+    public $default_lang;
416
+
417
+    /**
418
+     * @var string Ref
419
+     */
420
+    public $ref;
421
+
422
+    public $ref_int;
423
+    /**
424
+     * External user reference.
425
+     * This is to allow external systems to store their id and make self-developed synchronizing functions easier to
426
+     * build.
427
+     * @var string
428
+     */
429
+    public $ref_ext;
430
+
431
+    /**
432
+     * Import key.
433
+     * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
434
+     * to an import process
435
+     * @var string
436
+     */
437
+    public $import_key;
438
+
439
+    /**
440
+     * Supplier WebServices URL
441
+     * @var string
442
+     */
443
+    public $webservices_url;
444
+
445
+    /**
446
+     * Supplier WebServices Key
447
+     * @var string
448
+     */
449
+    public $webservices_key;
450
+
451
+    public $logo;
452
+    public $logo_small;
453
+    public $logo_mini;
454
+
455
+    public $array_options;
456
+
457
+    // Incoterms
458
+    /**
459 459
      * @var int ID
460 460
      */
461
-	public $fk_incoterms;
461
+    public $fk_incoterms;
462 462
 
463
-	public $location_incoterms;
464
-	public $libelle_incoterms;  //Used into tooltip
463
+    public $location_incoterms;
464
+    public $libelle_incoterms;  //Used into tooltip
465 465
 
466
-	// Multicurrency
467
-	/**
466
+    // Multicurrency
467
+    /**
468 468
      * @var int ID
469 469
      */
470
-	public $fk_multicurrency;
471
-
472
-	public $multicurrency_code;
473
-
474
-
475
-	// END MODULEBUILDER PROPERTIES
476
-
477
-
478
-	/**
479
-	 *    Constructor
480
-	 *
481
-	 *    @param	DoliDB		$db		Database handler
482
-	 */
483
-	public function __construct($db)
484
-	{
485
-		$this->db = $db;
486
-
487
-		$this->client = 0;
488
-		$this->prospect = 0;
489
-		$this->fournisseur = 0;
490
-		$this->typent_id  = 0;
491
-		$this->effectif_id  = 0;
492
-		$this->forme_juridique_code  = 0;
493
-		$this->tva_assuj = 1;
494
-		$this->status = 1;
495
-	}
496
-
497
-
498
-	/**
499
-	 *    Create third party in database.
500
-	 *    $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement.
501
-	 *
502
-	 *    @param	User	$user       Object of user that ask creation
503
-	 *    @return   int         		>= 0 if OK, < 0 if KO
504
-	 */
505
-	function create(User $user)
506
-	{
507
-		global $langs,$conf,$mysoc;
508
-
509
-		$error=0;
510
-
511
-		// Clean parameters
512
-		if (empty($this->status)) $this->status=0;
513
-		$this->name=$this->name?trim($this->name):trim($this->nom);
514
-		if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
515
-		$this->nom=$this->name; // For backward compatibility
516
-		if (empty($this->client))      $this->client=0;
517
-		if (empty($this->fournisseur)) $this->fournisseur=0;
518
-		$this->import_key = trim($this->import_key);
519
-
520
-		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
521
-		if (empty($this->fk_multicurrency))
522
-		{
523
-			$this->multicurrency_code = '';
524
-			$this->fk_multicurrency = 0;
525
-		}
526
-
527
-		dol_syslog(get_class($this)."::create ".$this->name);
528
-
529
-		$now=dol_now();
530
-
531
-		$this->db->begin();
532
-
533
-		// For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
534
-		if ($this->code_client == -1 || $this->code_client === 'auto')           $this->get_codeclient($this,0);
535
-		if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this,1);
536
-
537
-		// Check more parameters (including mandatory setup
538
-		// If error, this->errors[] is filled
539
-		$result = $this->verify();
540
-
541
-		if ($result >= 0)
542
-		{
543
-			$this->entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
544
-
545
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
546
-			$sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$this->db->escape($this->entity).", '".$this->db->idate($now)."'";
547
-			$sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
548
-			$sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
549
-			$sql.= ", ".$this->status;
550
-			$sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
551
-			$sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
552
-			$sql.= ", 0";
553
-			$sql.= ", ".(int) $this->fk_incoterms;
554
-			$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
555
-			$sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
556
-			$sql.= ", ".(int) $this->fk_multicurrency;
557
-			$sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
558
-
559
-			dol_syslog(get_class($this)."::create", LOG_DEBUG);
560
-			$result=$this->db->query($sql);
561
-			if ($result)
562
-			{
563
-				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
564
-
565
-				$ret = $this->update($this->id,$user,0,1,1,'add');
566
-
567
-				// Ajout du commercial affecte
568
-				if ($this->commercial_id != '' && $this->commercial_id != -1)
569
-				{
570
-					$this->add_commercial($user, $this->commercial_id);
571
-				}
572
-				// si un commercial cree un client il lui est affecte automatiquement
573
-				elseif (empty($user->rights->societe->client->voir))
574
-				{
575
-					$this->add_commercial($user, $user->id);
576
-				}
577
-
578
-				if ($ret >= 0)
579
-				{
580
-					// Call trigger
581
-					$result=$this->call_trigger('COMPANY_CREATE',$user);
582
-					if ($result < 0) $error++;
583
-					// End call triggers
584
-				}
585
-				else $error++;
586
-
587
-				if (! $error)
588
-				{
589
-					dol_syslog(get_class($this)."::Create success id=".$this->id);
590
-					$this->db->commit();
591
-					return $this->id;
592
-				}
593
-				else
594
-				{
595
-					dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR);
596
-					$this->db->rollback();
597
-					return -4;
598
-				}
599
-			}
600
-			else
601
-			{
602
-				if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
603
-				{
604
-					$this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);    // duplicate on a field (code or profid or ...)
605
-					$result=-1;
606
-				}
607
-				else
608
-				{
609
-					$this->error=$this->db->lasterror();
610
-					$result=-2;
611
-				}
612
-				$this->db->rollback();
613
-				return $result;
614
-			}
615
-		}
616
-		else
617
-		{
618
-			$this->db->rollback();
619
-			dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
620
-			return -3;
621
-		}
622
-	}
470
+    public $fk_multicurrency;
471
+
472
+    public $multicurrency_code;
473
+
474
+
475
+    // END MODULEBUILDER PROPERTIES
476
+
477
+
478
+    /**
479
+     *    Constructor
480
+     *
481
+     *    @param	DoliDB		$db		Database handler
482
+     */
483
+    public function __construct($db)
484
+    {
485
+        $this->db = $db;
486
+
487
+        $this->client = 0;
488
+        $this->prospect = 0;
489
+        $this->fournisseur = 0;
490
+        $this->typent_id  = 0;
491
+        $this->effectif_id  = 0;
492
+        $this->forme_juridique_code  = 0;
493
+        $this->tva_assuj = 1;
494
+        $this->status = 1;
495
+    }
496
+
497
+
498
+    /**
499
+     *    Create third party in database.
500
+     *    $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement.
501
+     *
502
+     *    @param	User	$user       Object of user that ask creation
503
+     *    @return   int         		>= 0 if OK, < 0 if KO
504
+     */
505
+    function create(User $user)
506
+    {
507
+        global $langs,$conf,$mysoc;
508
+
509
+        $error=0;
510
+
511
+        // Clean parameters
512
+        if (empty($this->status)) $this->status=0;
513
+        $this->name=$this->name?trim($this->name):trim($this->nom);
514
+        if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
515
+        $this->nom=$this->name; // For backward compatibility
516
+        if (empty($this->client))      $this->client=0;
517
+        if (empty($this->fournisseur)) $this->fournisseur=0;
518
+        $this->import_key = trim($this->import_key);
519
+
520
+        if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
521
+        if (empty($this->fk_multicurrency))
522
+        {
523
+            $this->multicurrency_code = '';
524
+            $this->fk_multicurrency = 0;
525
+        }
526
+
527
+        dol_syslog(get_class($this)."::create ".$this->name);
528
+
529
+        $now=dol_now();
530
+
531
+        $this->db->begin();
532
+
533
+        // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
534
+        if ($this->code_client == -1 || $this->code_client === 'auto')           $this->get_codeclient($this,0);
535
+        if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this,1);
536
+
537
+        // Check more parameters (including mandatory setup
538
+        // If error, this->errors[] is filled
539
+        $result = $this->verify();
540
+
541
+        if ($result >= 0)
542
+        {
543
+            $this->entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
544
+
545
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
546
+            $sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$this->db->escape($this->entity).", '".$this->db->idate($now)."'";
547
+            $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
548
+            $sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
549
+            $sql.= ", ".$this->status;
550
+            $sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
551
+            $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
552
+            $sql.= ", 0";
553
+            $sql.= ", ".(int) $this->fk_incoterms;
554
+            $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
555
+            $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
556
+            $sql.= ", ".(int) $this->fk_multicurrency;
557
+            $sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
558
+
559
+            dol_syslog(get_class($this)."::create", LOG_DEBUG);
560
+            $result=$this->db->query($sql);
561
+            if ($result)
562
+            {
563
+                $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
564
+
565
+                $ret = $this->update($this->id,$user,0,1,1,'add');
566
+
567
+                // Ajout du commercial affecte
568
+                if ($this->commercial_id != '' && $this->commercial_id != -1)
569
+                {
570
+                    $this->add_commercial($user, $this->commercial_id);
571
+                }
572
+                // si un commercial cree un client il lui est affecte automatiquement
573
+                elseif (empty($user->rights->societe->client->voir))
574
+                {
575
+                    $this->add_commercial($user, $user->id);
576
+                }
577
+
578
+                if ($ret >= 0)
579
+                {
580
+                    // Call trigger
581
+                    $result=$this->call_trigger('COMPANY_CREATE',$user);
582
+                    if ($result < 0) $error++;
583
+                    // End call triggers
584
+                }
585
+                else $error++;
586
+
587
+                if (! $error)
588
+                {
589
+                    dol_syslog(get_class($this)."::Create success id=".$this->id);
590
+                    $this->db->commit();
591
+                    return $this->id;
592
+                }
593
+                else
594
+                {
595
+                    dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR);
596
+                    $this->db->rollback();
597
+                    return -4;
598
+                }
599
+            }
600
+            else
601
+            {
602
+                if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
603
+                {
604
+                    $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);    // duplicate on a field (code or profid or ...)
605
+                    $result=-1;
606
+                }
607
+                else
608
+                {
609
+                    $this->error=$this->db->lasterror();
610
+                    $result=-2;
611
+                }
612
+                $this->db->rollback();
613
+                return $result;
614
+            }
615
+        }
616
+        else
617
+        {
618
+            $this->db->rollback();
619
+            dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
620
+            return -3;
621
+        }
622
+    }
623 623
 
624 624
 
625 625
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
626
-	/**
627
-	 * Create a contact/address from thirdparty
628
-	 *
629
-	 * @param 	User	$user		Object user
630
-	 * @return 	int					<0 if KO, >0 if OK
631
-	 */
632
-	function create_individual(User $user)
633
-	{
626
+    /**
627
+     * Create a contact/address from thirdparty
628
+     *
629
+     * @param 	User	$user		Object user
630
+     * @return 	int					<0 if KO, >0 if OK
631
+     */
632
+    function create_individual(User $user)
633
+    {
634 634
         // phpcs:enable
635
-		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
636
-		$contact=new Contact($this->db);
637
-
638
-		$contact->name              = $this->name_bis;
639
-		$contact->firstname         = $this->firstname;
640
-		$contact->civility_id       = $this->civility_id;
641
-		$contact->socid             = $this->id;	// fk_soc
642
-		$contact->statut            = 1;
643
-		$contact->priv              = 0;
644
-		$contact->country_id        = $this->country_id;
645
-		$contact->state_id          = $this->state_id;
646
-		$contact->address           = $this->address;
647
-		$contact->email             = $this->email;
648
-		$contact->zip               = $this->zip;
649
-		$contact->town              = $this->town;
650
-		$contact->phone_pro         = $this->phone;
651
-
652
-		$result = $contact->create($user);
653
-		if ($result < 0)
654
-		{
655
-			$this->error = $contact->error;
656
-			$this->errors = $contact->errors;
657
-			dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
658
-		}
659
-
660
-		return $result;
661
-	}
662
-
663
-	/**
664
-	 *    Check properties of third party are ok (like name, third party codes, ...)
665
-	 *    Used before an add or update.
666
-	 *
667
-	 *    @return     int		0 if OK, <0 if KO
668
-	 */
669
-	function verify()
670
-	{
671
-		global $conf, $langs, $mysoc;
672
-
673
-		$error = 0;
674
-		$this->errors=array();
675
-
676
-		$result = 0;
677
-		$this->name	= trim($this->name);
678
-		$this->nom=$this->name; // For backward compatibility
679
-
680
-		if (! $this->name)
681
-		{
682
-			$this->errors[] = 'ErrorBadThirdPartyName';
683
-			$result = -2;
684
-		}
685
-
686
-		if ($this->client)
687
-		{
688
-			$rescode = $this->check_codeclient();
689
-			if ($rescode <> 0)
690
-			{
691
-				if ($rescode == -1)
692
-				{
693
-					$this->errors[] = 'ErrorBadCustomerCodeSyntax';
694
-				}
695
-				elseif ($rescode == -2)
696
-				{
697
-					$this->errors[] = 'ErrorCustomerCodeRequired';
698
-				}
699
-				elseif ($rescode == -3)
700
-				{
701
-					$this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
702
-				}
703
-				elseif ($rescode == -4)
704
-				{
705
-					$this->errors[] = 'ErrorPrefixRequired';
706
-				}
707
-				$result = -3;
708
-			}
709
-		}
710
-
711
-		if ($this->fournisseur)
712
-		{
713
-			$rescode = $this->check_codefournisseur();
714
-			if ($rescode <> 0)
715
-			{
716
-				if ($rescode == -1)
717
-				{
718
-					$this->errors[] = 'ErrorBadSupplierCodeSyntax';
719
-				}
720
-				elseif ($rescode == -2)
721
-				{
722
-					$this->errors[] = 'ErrorSupplierCodeRequired';
723
-				}
724
-				elseif ($rescode == -3)
725
-				{
726
-					$this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
727
-				}
728
-				elseif ($rescode == -5)
729
-				{
730
-					$this->errors[] = 'ErrorprefixRequired';
731
-				}
732
-				$result = -3;
733
-			}
734
-		}
735
-
736
-		// Check for duplicate or mandatory fields defined into setup
737
-		$array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL');
738
-		foreach($array_to_check as $key)
739
-		{
740
-			$keymin=strtolower($key);
741
-			$i=(int) preg_replace('/[^0-9]/','',$key);
742
-			$vallabel=$this->$keymin;
743
-
744
-			if ($i > 0)
745
-			{
746
-				if ($this->isACompany())
747
-				{
748
-					// Check for unicity
749
-					if ($vallabel && $this->id_prof_verifiable($i))
750
-					{
751
-						if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
752
-						{
753
-							$langs->load("errors");
754
-							$error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
755
-						}
756
-					}
757
-
758
-					// Check for mandatory prof id (but only if country is other than ours)
759
-					if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id)
760
-					{
761
-						$idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY';
762
-						if (! $vallabel && ! empty($conf->global->$idprof_mandatory))
763
-						{
764
-							$langs->load("errors");
765
-							$error++;
766
-							$this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
767
-						}
768
-					}
769
-				}
770
-			}
771
-			else
772
-			{
773
-				//var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
774
-				//var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
775
-				if ($key == 'EMAIL')
776
-				{
777
-					// Check for unicity
778
-					if ($vallabel && ! empty($conf->global->SOCIETE_EMAIL_UNIQUE))
779
-					{
780
-						if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
781
-						{
782
-							$langs->load("errors");
783
-							$error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
784
-						}
785
-					}
786
-
787
-					// Check for mandatory
788
-					if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email))
789
-					{
790
-						$langs->load("errors");
791
-						$error++;
792
-						$this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
793
-					}
794
-				}
795
-			}
796
-		}
797
-
798
-		if ($error) $result = -4;
799
-
800
-		return $result;
801
-	}
802
-
803
-	/**
804
-	 *      Update parameters of third party
805
-	 *
806
-	 *      @param	int		$id              			Id of company (deprecated, use 0 here and call update on an object loaded by a fetch)
807
-	 *      @param  User	$user            			Utilisateur qui demande la mise a jour
808
-	 *      @param  int		$call_trigger    			0=no, 1=yes
809
-	 *		@param	int		$allowmodcodeclient			Inclut modif code client et code compta
810
-	 *		@param	int		$allowmodcodefournisseur	Inclut modif code fournisseur et code compta fournisseur
811
-	 *		@param	string	$action						'add' or 'update' or 'merge'
812
-	 *		@param	int		$nosyncmember				Do not synchronize info of linked member
813
-	 *      @return int  			           			<0 if KO, >=0 if OK
814
-	 */
815
-	function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
816
-	{
817
-		global $langs,$conf,$hookmanager;
818
-
819
-		require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
820
-
821
-		if (empty($id)) $id = $this->id;
822
-
823
-		$error=0;
824
-
825
-		dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
826
-
827
-		$now=dol_now();
828
-
829
-		// Clean parameters
830
-		$this->id			= $id;
831
-		$this->entity		= ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
832
-		$this->name			= $this->name?trim($this->name):trim($this->nom);
833
-		$this->nom			= $this->name;	// For backward compatibility
834
-		$this->name_alias	= trim($this->name_alias);
835
-		$this->ref_ext		= trim($this->ref_ext);
836
-		$this->address		= $this->address?trim($this->address):trim($this->address);
837
-		$this->zip			= $this->zip?trim($this->zip):trim($this->zip);
838
-		$this->town			= $this->town?trim($this->town):trim($this->town);
839
-		$this->state_id		= trim($this->state_id);
840
-		$this->country_id	= ($this->country_id > 0)?$this->country_id:0;
841
-		$this->phone		= trim($this->phone);
842
-		$this->phone		= preg_replace("/\s/","",$this->phone);
843
-		$this->phone		= preg_replace("/\./","",$this->phone);
844
-		$this->fax			= trim($this->fax);
845
-		$this->fax			= preg_replace("/\s/","",$this->fax);
846
-		$this->fax			= preg_replace("/\./","",$this->fax);
847
-		$this->email		= trim($this->email);
848
-		$this->skype		= trim($this->skype);
849
-		$this->twitter		= trim($this->twitter);
850
-		$this->facebook		= trim($this->facebook);
851
-		$this->url			= $this->url?clean_url($this->url,0):'';
852
-		$this->note_private = trim($this->note_private);
853
-		$this->note_public  = trim($this->note_public);
854
-		$this->idprof1		= trim($this->idprof1);
855
-		$this->idprof2		= trim($this->idprof2);
856
-		$this->idprof3		= trim($this->idprof3);
857
-		$this->idprof4		= trim($this->idprof4);
858
-		$this->idprof5		= (! empty($this->idprof5)?trim($this->idprof5):'');
859
-		$this->idprof6		= (! empty($this->idprof6)?trim($this->idprof6):'');
860
-		$this->prefix_comm	= trim($this->prefix_comm);
861
-		$this->outstanding_limit = price2num($this->outstanding_limit);
862
-		$this->order_min_amount = price2num($this->order_min_amount);
863
-		$this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
864
-
865
-		$this->tva_assuj	= trim($this->tva_assuj);
866
-		$this->tva_intra	= dol_sanitizeFileName($this->tva_intra,'');
867
-		if (empty($this->status)) $this->status = 0;
868
-
869
-		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
870
-		if (empty($this->fk_multicurrency))
871
-		{
872
-			$this->multicurrency_code = '';
873
-			$this->fk_multicurrency = 0;
874
-		}
875
-
876
-		// Local taxes
877
-		$this->localtax1_assuj=trim($this->localtax1_assuj);
878
-		$this->localtax2_assuj=trim($this->localtax2_assuj);
879
-
880
-		$this->localtax1_value=trim($this->localtax1_value);
881
-		$this->localtax2_value=trim($this->localtax2_value);
882
-
883
-		if ($this->capital != '') $this->capital=price2num(trim($this->capital));
884
-		if (! is_numeric($this->capital)) $this->capital = '';     // '' = undef
885
-
886
-		$this->effectif_id=trim($this->effectif_id);
887
-		$this->forme_juridique_code=trim($this->forme_juridique_code);
888
-
889
-		//Gencod
890
-		$this->barcode=trim($this->barcode);
891
-
892
-		// For automatic creation
893
-		if ($this->code_client == -1 || $this->code_client === 'auto')           $this->get_codeclient($this,0);
894
-		if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this,1);
895
-
896
-		$this->code_compta=trim($this->code_compta);
897
-		$this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
898
-
899
-		// Check parameters. More tests are done later in the ->verify()
900
-		if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
901
-		{
902
-			$langs->load("errors");
903
-			$this->error = $langs->trans("BadValueForParameterClientOrSupplier");
904
-			return -1;
905
-		}
906
-
907
-		$customer=false;
908
-		if (! empty($allowmodcodeclient) && ! empty($this->client))
909
-		{
910
-			// Attention get_codecompta peut modifier le code suivant le module utilise
911
-			if (empty($this->code_compta))
912
-			{
913
-				$ret=$this->get_codecompta('customer');
914
-				if ($ret < 0) return -1;
915
-			}
916
-
917
-			$customer=true;
918
-		}
919
-
920
-		$supplier=false;
921
-		if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
922
-		{
923
-			// Attention get_codecompta peut modifier le code suivant le module utilise
924
-			if (empty($this->code_compta_fournisseur))
925
-			{
926
-				$ret=$this->get_codecompta('supplier');
927
-				if ($ret < 0) return -1;
928
-			}
929
-
930
-			$supplier=true;
931
-		}
932
-
933
-		//Web services
934
-		$this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
935
-		$this->webservices_key = trim($this->webservices_key);
936
-
937
-		//Incoterms
938
-		$this->fk_incoterms = (int) $this->fk_incoterms;
939
-		$this->location_incoterms = trim($this->location_incoterms);
940
-
941
-		$this->db->begin();
942
-
943
-		// Check name is required and codes are ok or unique.
944
-		// If error, this->errors[] is filled
945
-		$result = 0;
946
-		if ($action != 'add' && $action != 'merge')
947
-		{
948
-			// We don't check when update called during a create because verify was already done.
949
-			// For a merge, we suppose source data is clean and a customer code of a deleted thirdparty must be accepted into a target thirdparty with empty code without duplicate error
950
-			$result = $this->verify();
951
-
952
-			// If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
953
-			// So we can update record that were using and old numbering rule.
954
-			if (is_array($this->errors))
955
-			{
956
-				if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client)
957
-				{
958
-					if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]);	// Remove error message
959
-				}
960
-				if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur)
961
-				{
962
-					if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]);	// Remove error message
963
-				}
964
-				if (empty($this->errors))	// If there is no more error, we can make like if there is no error at all
965
-				{
966
-					$result = 0;
967
-				}
968
-			}
969
-		}
970
-
971
-		if ($result >= 0)
972
-		{
973
-			dol_syslog(get_class($this)."::update verify ok or not done");
974
-
975
-			$sql  = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
976
-			$sql .= "entity = " . $this->db->escape($this->entity);
977
-			$sql .= ",nom = '" . $this->db->escape($this->name) ."'"; // Required
978
-			$sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
979
-			$sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
980
-			$sql .= ",address = '" . $this->db->escape($this->address) ."'";
981
-
982
-			$sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
983
-			$sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
984
-
985
-			$sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
986
-			$sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
987
-
988
-			$sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
989
-			$sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
990
-			$sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
991
-			$sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
992
-			$sql .= ",twitter = ".(! empty($this->twitter)?"'".$this->db->escape($this->twitter)."'":"null");
993
-			$sql .= ",facebook = ".(! empty($this->facebook)?"'".$this->db->escape($this->facebook)."'":"null");
994
-			$sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
995
-
996
-			$sql .= ",parent = " . ($this->parent > 0 ? $this->parent : "null");
997
-
998
-			$sql .= ",note_private = ".(! empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null");
999
-			$sql .= ",note_public = ".(! empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null");
1000
-
1001
-			$sql .= ",siren   = '". $this->db->escape($this->idprof1) ."'";
1002
-			$sql .= ",siret   = '". $this->db->escape($this->idprof2) ."'";
1003
-			$sql .= ",ape     = '". $this->db->escape($this->idprof3) ."'";
1004
-			$sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
1005
-			$sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
1006
-			$sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
1007
-
1008
-			$sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null");
1009
-			$sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
1010
-			$sql .= ",status = " .$this->status;
1011
-
1012
-			// Local taxes
1013
-			$sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null");
1014
-			$sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null");
1015
-			if($this->localtax1_assuj==1)
1016
-			{
1017
-				if($this->localtax1_value!='')
1018
-				{
1019
-					$sql .=",localtax1_value =".$this->localtax1_value;
1020
-				}
1021
-				else $sql .=",localtax1_value =0.000";
1022
-			}
1023
-			else $sql .=",localtax1_value =0.000";
1024
-
1025
-			if($this->localtax2_assuj==1)
1026
-			{
1027
-				if($this->localtax2_value!='')
1028
-				{
1029
-					$sql .=",localtax2_value =".$this->localtax2_value;
1030
-				}
1031
-				else $sql .=",localtax2_value =0.000";
1032
-			}
1033
-			else $sql .=",localtax2_value =0.000";
1034
-
1035
-			$sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1036
-
1037
-			$sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
1038
-
1039
-			$sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
1040
-			if (isset($this->stcomm_id))
1041
-			{
1042
-				$sql .= ",fk_stcomm=".(!empty($this->stcomm_id)  ? $this->stcomm_id : "0");
1043
-			}
1044
-			$sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
1045
-
1046
-			$sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
1047
-
1048
-			$sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
1049
-			$sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
1050
-			$sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
1051
-			$sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
1052
-			$sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
1053
-
1054
-			$sql .= ",client = " . (! empty($this->client)?$this->client:0);
1055
-			$sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
1056
-			$sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
1057
-			$sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
1058
-			$sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
1059
-			$sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
1060
-			$sql .= ",order_min_amount= ".($this->order_min_amount!=''?$this->order_min_amount:'null');
1061
-			$sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount!=''?$this->supplier_order_min_amount:'null');
1062
-			$sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1063
-
1064
-			$sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
1065
-			$sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
1066
-
1067
-			//Incoterms
1068
-			$sql.= ", fk_incoterms = ".$this->fk_incoterms;
1069
-			$sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
1070
-
1071
-			if ($customer)
1072
-			{
1073
-				$sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
1074
-				$sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
1075
-			}
1076
-
1077
-			if ($supplier)
1078
-			{
1079
-				$sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
1080
-				$sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
1081
-			}
1082
-			$sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id:"null");
1083
-			$sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1084
-			$sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1085
-			$sql .= " WHERE rowid = " . (int) $id;
1086
-
1087
-			$resql=$this->db->query($sql);
1088
-			if ($resql)
1089
-			{
1090
-				if (is_object($this->oldcopy))	// If we have information on old values
1091
-				{
1092
-					if ($this->oldcopy->country_id != $this->country_id)
1093
-					{
1094
-						unset($this->country_code);
1095
-						unset($this->country);
1096
-					}
1097
-					if ($this->oldcopy->state_id != $this->state_id)
1098
-					{
1099
-						unset($this->state_code);
1100
-						unset($this->state);
1101
-					}
1102
-				}
1103
-				else
1104
-				{
1105
-					unset($this->country_code);	// We clean this, in the doubt, because it may have been changed after an update of country_id
1106
-					unset($this->country);
1107
-					unset($this->state_code);
1108
-					unset($this->state);
1109
-				}
1110
-
1111
-				$nbrowsaffected = $this->db->affected_rows($resql);
1112
-
1113
-				if (! $error && $nbrowsaffected)
1114
-				{
1115
-					// Update information on linked member if it is an update
1116
-					if (! $nosyncmember && ! empty($conf->adherent->enabled))
1117
-					{
1118
-						require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1119
-
1120
-						dol_syslog(get_class($this)."::update update linked member");
1121
-
1122
-						$lmember=new Adherent($this->db);
1123
-						$result=$lmember->fetch(0, 0, $this->id);
1124
-
1125
-						if ($result > 0)
1126
-						{
1127
-							$lmember->societe=$this->name;
1128
-							//$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname;	// We keep firstname and lastname of member unchanged
1129
-							//$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname;		// We keep firstname and lastname of member unchanged
1130
-							$lmember->address=$this->address;
1131
-							$lmember->email=$this->email;
1132
-							$lmember->skype=$this->skype;
1133
-							$lmember->twitter=$this->twitter;
1134
-							$lmember->facebook=$this->facebook;
1135
-							$lmember->phone=$this->phone;
1136
-
1137
-							$result=$lmember->update($user,0,1,1,1);	// Use nosync to 1 to avoid cyclic updates
1138
-							if ($result < 0)
1139
-							{
1140
-								$this->error=$lmember->error;
1141
-								dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
1142
-								$error++;
1143
-							}
1144
-						}
1145
-						elseif ($result < 0)
1146
-						{
1147
-							$this->error=$lmember->error;
1148
-							$error++;
1149
-						}
1150
-					}
1151
-				}
1152
-
1153
-				$action='update';
1154
-
1155
-				// Actions on extra fields
1156
-				if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1157
-				{
1158
-					$result=$this->insertExtraFields();
1159
-					if ($result < 0)
1160
-					{
1161
-						$error++;
1162
-					}
1163
-				}
1164
-
1165
-				if (! $error && $call_trigger)
1166
-				{
1167
-					// Call trigger
1168
-					$result=$this->call_trigger('COMPANY_MODIFY',$user);
1169
-					if ($result < 0) $error++;
1170
-					// End call triggers
1171
-				}
1172
-
1173
-				if (! $error)
1174
-				{
1175
-					dol_syslog(get_class($this)."::Update success");
1176
-					$this->db->commit();
1177
-					return 1;
1178
-				}
1179
-				else
1180
-				{
1181
-					$this->db->rollback();
1182
-					return -1;
1183
-				}
1184
-			}
1185
-			else
1186
-			{
1187
-				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1188
-				{
1189
-					// Doublon
1190
-					$this->error = $langs->trans("ErrorDuplicateField");
1191
-					$result = -1;
1192
-				}
1193
-				else
1194
-				{
1195
-					$this->error = $this->db->lasterror();
1196
-					$result = -2;
1197
-				}
1198
-				$this->db->rollback();
1199
-				return $result;
1200
-			}
1201
-		}
1202
-		else
1203
-	   {
1204
-			$this->db->rollback();
1205
-			dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
1206
-			return -3;
1207
-		}
1208
-	}
1209
-
1210
-	/**
1211
-	 *    Load a third party from database into memory
1212
-	 *
1213
-	 *    @param	int		$rowid			Id of third party to load
1214
-	 *    @param    string	$ref			Reference of third party, name (Warning, this can return several records)
1215
-	 *    @param    string	$ref_ext       	External reference of third party (Warning, this information is a free field not provided by Dolibarr)
1216
-	 *    @param    string	$ref_int       	Internal reference of third party (not used by dolibarr)
1217
-	 *    @param    string	$idprof1		Prof id 1 of third party (Warning, this can return several records)
1218
-	 *    @param    string	$idprof2		Prof id 2 of third party (Warning, this can return several records)
1219
-	 *    @param    string	$idprof3		Prof id 3 of third party (Warning, this can return several records)
1220
-	 *    @param    string	$idprof4		Prof id 4 of third party (Warning, this can return several records)
1221
-	 *    @param    string	$idprof5		Prof id 5 of third party (Warning, this can return several records)
1222
-	 *    @param    string	$idprof6		Prof id 6 of third party (Warning, this can return several records)
1223
-	 *    @param    string	$email   		Email of third party (Warning, this can return several records)
1224
-	 *    @param    string	$ref_alias 		Name_alias of third party (Warning, this can return several records)
1225
-	 *    @return   int						>0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
1226
-	 */
1227
-	function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='', $email='', $ref_alias='')
1228
-	{
1229
-		global $langs;
1230
-		global $conf;
1231
-
1232
-		if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1;
1233
-
1234
-		$sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
1235
-		$sql .= ', s.status';
1236
-		$sql .= ', s.price_level';
1237
-		$sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1238
-		$sql .= ', s.phone, s.fax, s.email, s.skype, s.twitter, s.facebook, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
1239
-		$sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1240
-		$sql .= ', s.capital, s.tva_intra';
1241
-		$sql .= ', s.fk_typent as typent_id';
1242
-		$sql .= ', s.fk_effectif as effectif_id';
1243
-		$sql .= ', s.fk_forme_juridique as forme_juridique_code';
1244
-		$sql .= ', s.webservices_url, s.webservices_key';
1245
-		$sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
1246
-		$sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.remise_supplier, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
1247
-		$sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
1248
-		$sql .= ', s.fk_shipping_method';
1249
-		$sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1250
-		$sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1251
-		$sql .= ', s.fk_multicurrency, s.multicurrency_code';
1252
-		$sql .= ', fj.libelle as forme_juridique';
1253
-		$sql .= ', e.libelle as effectif';
1254
-		$sql .= ', c.code as country_code, c.label as country';
1255
-		$sql .= ', d.code_departement as state_code, d.nom as state';
1256
-		$sql .= ', st.libelle as stcomm';
1257
-		$sql .= ', te.code as typent_code';
1258
-		$sql .= ', i.libelle as libelle_incoterms';
1259
-		$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1260
-		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1261
-		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1262
-		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1263
-		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1264
-		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1265
-		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1266
-		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1267
-
1268
-		$sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1269
-		if ($rowid)     $sql .= ' AND s.rowid = '.$rowid;
1270
-		if ($ref)       $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1271
-		if ($ref_alias) $sql .= " AND s.nom_alias = '".$this->db->escape($ref_alias)."'";
1272
-		if ($ref_ext)   $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1273
-		if ($ref_int)   $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'";
1274
-		if ($idprof1)   $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1275
-		if ($idprof2)   $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1276
-		if ($idprof3)   $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1277
-		if ($idprof4)   $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1278
-		if ($idprof5)   $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1279
-		if ($idprof6)   $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1280
-		if ($email)     $sql .= " AND s.email = '".$this->db->escape($email)."'";
1281
-
1282
-		$resql=$this->db->query($sql);
1283
-		if ($resql)
1284
-		{
1285
-			$num=$this->db->num_rows($resql);
1286
-			if ($num > 1)
1287
-			{
1288
-				$this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
1289
-				dol_syslog($this->error, LOG_ERR);
1290
-				$result = -2;
1291
-			}
1292
-			elseif ($num)   // $num = 1
1293
-			{
1294
-				$obj = $this->db->fetch_object($resql);
1295
-
1296
-				$this->id           = $obj->rowid;
1297
-				$this->entity       = $obj->entity;
1298
-				$this->canvas		= $obj->canvas;
1299
-
1300
-				$this->ref          = $obj->rowid;
1301
-				$this->name 		= $obj->name;
1302
-				$this->nom          = $obj->name;		// deprecated
1303
-				$this->name_alias = $obj->name_alias;
1304
-				$this->ref_ext      = $obj->ref_ext;
1305
-				$this->ref_int      = $obj->ref_int;
1306
-
1307
-				$this->date_creation     = $this->db->jdate($obj->date_creation);
1308
-				$this->date_modification = $this->db->jdate($obj->date_modification);
1309
-				$this->user_creation     = $obj->fk_user_creat;
1310
-				$this->user_modification = $obj->fk_user_modif;
1311
-
1312
-				$this->address 		= $obj->address;
1313
-				$this->zip 			= $obj->zip;
1314
-				$this->town 		= $obj->town;
1315
-
1316
-				$this->country_id   = $obj->country_id;
1317
-				$this->country_code = $obj->country_id?$obj->country_code:'';
1318
-				$this->country 		= $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
1319
-
1320
-				$this->state_id     = $obj->fk_departement;
1321
-				$this->state_code   = $obj->state_code;
1322
-				$this->state        = ($obj->state!='-'?$obj->state:'');
1323
-
1324
-				$transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
1325
-				$libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
1326
-				$this->stcomm_id = $obj->fk_stcomm;     // id statut commercial
1327
-				$this->statut_commercial = $libelle;    // libelle statut commercial
1328
-
1329
-				$this->email = $obj->email;
1330
-				$this->skype = $obj->skype;
1331
-				$this->twitter = $obj->twitter;
1332
-				$this->facebook = $obj->facebook;
1333
-				$this->url = $obj->url;
1334
-				$this->phone = $obj->phone;
1335
-				$this->fax = $obj->fax;
1336
-
1337
-				$this->parent    = $obj->parent;
1338
-
1339
-				$this->idprof1		= $obj->idprof1;
1340
-				$this->idprof2		= $obj->idprof2;
1341
-				$this->idprof3		= $obj->idprof3;
1342
-				$this->idprof4		= $obj->idprof4;
1343
-				$this->idprof5		= $obj->idprof5;
1344
-				$this->idprof6		= $obj->idprof6;
1345
-
1346
-				$this->capital   = $obj->capital;
1347
-
1348
-				$this->code_client = $obj->code_client;
1349
-				$this->code_fournisseur = $obj->code_fournisseur;
1350
-
1351
-				$this->code_compta = $obj->code_compta;
1352
-				$this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1353
-
1354
-				$this->barcode = $obj->barcode;
1355
-
1356
-				$this->tva_assuj      = $obj->tva_assuj;
1357
-				$this->tva_intra      = $obj->tva_intra;
1358
-				$this->status = $obj->status;
1359
-
1360
-				// Local Taxes
1361
-				$this->localtax1_assuj      = $obj->localtax1_assuj;
1362
-				$this->localtax2_assuj      = $obj->localtax2_assuj;
1363
-
1364
-				$this->localtax1_value		= $obj->localtax1_value;
1365
-				$this->localtax2_value		= $obj->localtax2_value;
1366
-
1367
-				$this->typent_id      = $obj->typent_id;
1368
-				$this->typent_code    = $obj->typent_code;
1369
-
1370
-				$this->effectif_id    = $obj->effectif_id;
1371
-				$this->effectif       = $obj->effectif_id?$obj->effectif:'';
1372
-
1373
-				$this->forme_juridique_code= $obj->forme_juridique_code;
1374
-				$this->forme_juridique     = $obj->forme_juridique_code?$obj->forme_juridique:'';
1375
-
1376
-				$this->fk_prospectlevel = $obj->fk_prospectlevel;
1377
-
1378
-				$this->prefix_comm = $obj->prefix_comm;
1379
-
1380
-				$this->remise_percent		= $obj->remise_client;
1381
-				$this->remise_supplier_percent		= $obj->remise_supplier;
1382
-				$this->mode_reglement_id 	= $obj->mode_reglement;
1383
-				$this->cond_reglement_id 	= $obj->cond_reglement;
1384
-				$this->mode_reglement_supplier_id 	= $obj->mode_reglement_supplier;
1385
-				$this->cond_reglement_supplier_id 	= $obj->cond_reglement_supplier;
1386
-				$this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1387
-				$this->fk_account			= $obj->fk_account;
1388
-
1389
-				$this->client      = $obj->client;
1390
-				$this->fournisseur = $obj->fournisseur;
1391
-
1392
-				$this->note = $obj->note_private; // TODO Deprecated for backward comtability
1393
-				$this->note_private = $obj->note_private;
1394
-				$this->note_public = $obj->note_public;
1395
-				$this->modelpdf = $obj->model_pdf;
1396
-				$this->default_lang = $obj->default_lang;
1397
-				$this->logo = $obj->logo;
1398
-
1399
-				$this->webservices_url = $obj->webservices_url;
1400
-				$this->webservices_key = $obj->webservices_key;
1401
-
1402
-				$this->outstanding_limit		= $obj->outstanding_limit;
1403
-				$this->order_min_amount			= $obj->order_min_amount;
1404
-				$this->supplier_order_min_amount	= $obj->supplier_order_min_amount;
1405
-
1406
-				// multiprix
1407
-				$this->price_level = $obj->price_level;
1408
-
1409
-				$this->import_key = $obj->import_key;
1410
-
1411
-				//Incoterms
1412
-				$this->fk_incoterms = $obj->fk_incoterms;
1413
-				$this->location_incoterms = $obj->location_incoterms;
1414
-				$this->libelle_incoterms = $obj->libelle_incoterms;
1415
-
1416
-				// multicurrency
1417
-				$this->fk_multicurrency = $obj->fk_multicurrency;
1418
-				$this->multicurrency_code = $obj->multicurrency_code;
1419
-
1420
-				$result = 1;
1421
-
1422
-				// fetch optionals attributes and labels
1423
-				$this->fetch_optionals();
1424
-			}
1425
-			else
1426
-			{
1427
-				$result = 0;
1428
-			}
1429
-
1430
-			$this->db->free($resql);
1431
-		}
1432
-		else
1433
-		{
1434
-			$this->error=$this->db->lasterror();
1435
-			$result = -3;
1436
-		}
1437
-
1438
-		// Use first price level if level not defined for third party
1439
-		if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1;
1440
-
1441
-		return $result;
1442
-	}
1443
-
1444
-	/**
1445
-	 *    Delete a third party from database and all its dependencies (contacts, rib...)
1446
-	 *
1447
-	 *    @param	int		$id             Id of third party to delete
1448
-	 *    @param    User    $fuser          User who ask to delete thirparty
1449
-	 *    @param    int		$call_trigger   0=No, 1=yes
1450
-	 *    @return	int						<0 if KO, 0 if nothing done, >0 if OK
1451
-	 */
1452
-	function delete($id, User $fuser=null, $call_trigger=1)
1453
-	{
1454
-		global $langs, $conf, $user;
1455
-
1456
-		if (empty($fuser)) $fuser=$user;
1457
-
1458
-		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1459
-
1460
-		$entity=isset($this->entity)?$this->entity:$conf->entity;
1461
-
1462
-		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1463
-		$error = 0;
1464
-
1465
-		// Test if child exists
1466
-		$objectisused = $this->isObjectUsed($id);
1467
-		if (empty($objectisused))
1468
-		{
1469
-			$this->db->begin();
1470
-
1471
-			// User is mandatory for trigger call
1472
-			if (! $error && $call_trigger)
1473
-			{
1474
-				// Call trigger
1475
-				$result=$this->call_trigger('COMPANY_DELETE',$fuser);
1476
-				if ($result < 0) $error++;
1477
-				// End call triggers
1478
-			}
1479
-
1480
-			if (! $error)
1481
-			{
1482
-				require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1483
-				$static_cat = new Categorie($this->db);
1484
-				$toute_categs = array();
1485
-
1486
-				// Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
1487
-				if ($this->client || $this->prospect)
1488
-				{
1489
-					$toute_categs['customer'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER);
1490
-				}
1491
-				if ($this->fournisseur)
1492
-				{
1493
-					$toute_categs['supplier'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER);
1494
-				}
1495
-
1496
-				// Remove each "Categorie"
1497
-				foreach ($toute_categs as $type => $categs_type)
1498
-				{
1499
-					foreach ($categs_type as $cat)
1500
-					{
1501
-						$cat->del_type($this, $type);
1502
-					}
1503
-				}
1504
-			}
1505
-
1506
-			foreach ($this->childtablesoncascade as $tabletodelete)
1507
-			{
1508
-				if (! $error)
1509
-				{
1510
-					$sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
1511
-					$sql.= " WHERE fk_soc = " . $id;
1512
-					if (! $this->db->query($sql))
1513
-					{
1514
-						$error++;
1515
-						$this->errors[] = $this->db->lasterror();
1516
-					}
1517
-				}
1518
-			}
1519
-
1520
-			// Removed extrafields
1521
-			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1522
-			{
1523
-				$result=$this->deleteExtraFields();
1524
-				if ($result < 0)
1525
-				{
1526
-					$error++;
1527
-					dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1528
-				}
1529
-			}
1530
-
1531
-			// Remove links to subsidiaries companies
1532
-			if (! $error)
1533
-			{
1534
-				$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1535
-				$sql.= " SET parent = NULL";
1536
-				$sql.= " WHERE parent = " . $id;
1537
-				if (! $this->db->query($sql))
1538
-				{
1539
-					$error++;
1540
-					$this->errors[] = $this->db->lasterror();
1541
-				}
1542
-			}
1543
-
1544
-			// Remove third party
1545
-			if (! $error)
1546
-			{
1547
-				$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
1548
-				$sql.= " WHERE rowid = " . $id;
1549
-				if (! $this->db->query($sql))
1550
-				{
1551
-					$error++;
1552
-					$this->errors[] = $this->db->lasterror();
1553
-				}
1554
-			}
1555
-
1556
-			if (! $error)
1557
-			{
1558
-				$this->db->commit();
1559
-
1560
-				// Delete directory
1561
-				if (! empty($conf->societe->multidir_output[$entity]))
1562
-				{
1563
-					$docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
1564
-					if (dol_is_dir($docdir))
1565
-					{
1566
-						dol_delete_dir_recursive($docdir);
1567
-					}
1568
-				}
1569
-
1570
-				return 1;
1571
-			}
1572
-			else
1573
-			{
1574
-				dol_syslog($this->error, LOG_ERR);
1575
-				$this->db->rollback();
1576
-				return -1;
1577
-			}
1578
-		}
1579
-		else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
1580
-		return 0;
1581
-	}
635
+        require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
636
+        $contact=new Contact($this->db);
637
+
638
+        $contact->name              = $this->name_bis;
639
+        $contact->firstname         = $this->firstname;
640
+        $contact->civility_id       = $this->civility_id;
641
+        $contact->socid             = $this->id;	// fk_soc
642
+        $contact->statut            = 1;
643
+        $contact->priv              = 0;
644
+        $contact->country_id        = $this->country_id;
645
+        $contact->state_id          = $this->state_id;
646
+        $contact->address           = $this->address;
647
+        $contact->email             = $this->email;
648
+        $contact->zip               = $this->zip;
649
+        $contact->town              = $this->town;
650
+        $contact->phone_pro         = $this->phone;
651
+
652
+        $result = $contact->create($user);
653
+        if ($result < 0)
654
+        {
655
+            $this->error = $contact->error;
656
+            $this->errors = $contact->errors;
657
+            dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
658
+        }
659
+
660
+        return $result;
661
+    }
662
+
663
+    /**
664
+     *    Check properties of third party are ok (like name, third party codes, ...)
665
+     *    Used before an add or update.
666
+     *
667
+     *    @return     int		0 if OK, <0 if KO
668
+     */
669
+    function verify()
670
+    {
671
+        global $conf, $langs, $mysoc;
672
+
673
+        $error = 0;
674
+        $this->errors=array();
675
+
676
+        $result = 0;
677
+        $this->name	= trim($this->name);
678
+        $this->nom=$this->name; // For backward compatibility
679
+
680
+        if (! $this->name)
681
+        {
682
+            $this->errors[] = 'ErrorBadThirdPartyName';
683
+            $result = -2;
684
+        }
685
+
686
+        if ($this->client)
687
+        {
688
+            $rescode = $this->check_codeclient();
689
+            if ($rescode <> 0)
690
+            {
691
+                if ($rescode == -1)
692
+                {
693
+                    $this->errors[] = 'ErrorBadCustomerCodeSyntax';
694
+                }
695
+                elseif ($rescode == -2)
696
+                {
697
+                    $this->errors[] = 'ErrorCustomerCodeRequired';
698
+                }
699
+                elseif ($rescode == -3)
700
+                {
701
+                    $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
702
+                }
703
+                elseif ($rescode == -4)
704
+                {
705
+                    $this->errors[] = 'ErrorPrefixRequired';
706
+                }
707
+                $result = -3;
708
+            }
709
+        }
710
+
711
+        if ($this->fournisseur)
712
+        {
713
+            $rescode = $this->check_codefournisseur();
714
+            if ($rescode <> 0)
715
+            {
716
+                if ($rescode == -1)
717
+                {
718
+                    $this->errors[] = 'ErrorBadSupplierCodeSyntax';
719
+                }
720
+                elseif ($rescode == -2)
721
+                {
722
+                    $this->errors[] = 'ErrorSupplierCodeRequired';
723
+                }
724
+                elseif ($rescode == -3)
725
+                {
726
+                    $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
727
+                }
728
+                elseif ($rescode == -5)
729
+                {
730
+                    $this->errors[] = 'ErrorprefixRequired';
731
+                }
732
+                $result = -3;
733
+            }
734
+        }
735
+
736
+        // Check for duplicate or mandatory fields defined into setup
737
+        $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL');
738
+        foreach($array_to_check as $key)
739
+        {
740
+            $keymin=strtolower($key);
741
+            $i=(int) preg_replace('/[^0-9]/','',$key);
742
+            $vallabel=$this->$keymin;
743
+
744
+            if ($i > 0)
745
+            {
746
+                if ($this->isACompany())
747
+                {
748
+                    // Check for unicity
749
+                    if ($vallabel && $this->id_prof_verifiable($i))
750
+                    {
751
+                        if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
752
+                        {
753
+                            $langs->load("errors");
754
+                            $error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
755
+                        }
756
+                    }
757
+
758
+                    // Check for mandatory prof id (but only if country is other than ours)
759
+                    if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id)
760
+                    {
761
+                        $idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY';
762
+                        if (! $vallabel && ! empty($conf->global->$idprof_mandatory))
763
+                        {
764
+                            $langs->load("errors");
765
+                            $error++;
766
+                            $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
767
+                        }
768
+                    }
769
+                }
770
+            }
771
+            else
772
+            {
773
+                //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
774
+                //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
775
+                if ($key == 'EMAIL')
776
+                {
777
+                    // Check for unicity
778
+                    if ($vallabel && ! empty($conf->global->SOCIETE_EMAIL_UNIQUE))
779
+                    {
780
+                        if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
781
+                        {
782
+                            $langs->load("errors");
783
+                            $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
784
+                        }
785
+                    }
786
+
787
+                    // Check for mandatory
788
+                    if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email))
789
+                    {
790
+                        $langs->load("errors");
791
+                        $error++;
792
+                        $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
793
+                    }
794
+                }
795
+            }
796
+        }
797
+
798
+        if ($error) $result = -4;
799
+
800
+        return $result;
801
+    }
802
+
803
+    /**
804
+     *      Update parameters of third party
805
+     *
806
+     *      @param	int		$id              			Id of company (deprecated, use 0 here and call update on an object loaded by a fetch)
807
+     *      @param  User	$user            			Utilisateur qui demande la mise a jour
808
+     *      @param  int		$call_trigger    			0=no, 1=yes
809
+     *		@param	int		$allowmodcodeclient			Inclut modif code client et code compta
810
+     *		@param	int		$allowmodcodefournisseur	Inclut modif code fournisseur et code compta fournisseur
811
+     *		@param	string	$action						'add' or 'update' or 'merge'
812
+     *		@param	int		$nosyncmember				Do not synchronize info of linked member
813
+     *      @return int  			           			<0 if KO, >=0 if OK
814
+     */
815
+    function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
816
+    {
817
+        global $langs,$conf,$hookmanager;
818
+
819
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
820
+
821
+        if (empty($id)) $id = $this->id;
822
+
823
+        $error=0;
824
+
825
+        dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
826
+
827
+        $now=dol_now();
828
+
829
+        // Clean parameters
830
+        $this->id			= $id;
831
+        $this->entity		= ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
832
+        $this->name			= $this->name?trim($this->name):trim($this->nom);
833
+        $this->nom			= $this->name;	// For backward compatibility
834
+        $this->name_alias	= trim($this->name_alias);
835
+        $this->ref_ext		= trim($this->ref_ext);
836
+        $this->address		= $this->address?trim($this->address):trim($this->address);
837
+        $this->zip			= $this->zip?trim($this->zip):trim($this->zip);
838
+        $this->town			= $this->town?trim($this->town):trim($this->town);
839
+        $this->state_id		= trim($this->state_id);
840
+        $this->country_id	= ($this->country_id > 0)?$this->country_id:0;
841
+        $this->phone		= trim($this->phone);
842
+        $this->phone		= preg_replace("/\s/","",$this->phone);
843
+        $this->phone		= preg_replace("/\./","",$this->phone);
844
+        $this->fax			= trim($this->fax);
845
+        $this->fax			= preg_replace("/\s/","",$this->fax);
846
+        $this->fax			= preg_replace("/\./","",$this->fax);
847
+        $this->email		= trim($this->email);
848
+        $this->skype		= trim($this->skype);
849
+        $this->twitter		= trim($this->twitter);
850
+        $this->facebook		= trim($this->facebook);
851
+        $this->url			= $this->url?clean_url($this->url,0):'';
852
+        $this->note_private = trim($this->note_private);
853
+        $this->note_public  = trim($this->note_public);
854
+        $this->idprof1		= trim($this->idprof1);
855
+        $this->idprof2		= trim($this->idprof2);
856
+        $this->idprof3		= trim($this->idprof3);
857
+        $this->idprof4		= trim($this->idprof4);
858
+        $this->idprof5		= (! empty($this->idprof5)?trim($this->idprof5):'');
859
+        $this->idprof6		= (! empty($this->idprof6)?trim($this->idprof6):'');
860
+        $this->prefix_comm	= trim($this->prefix_comm);
861
+        $this->outstanding_limit = price2num($this->outstanding_limit);
862
+        $this->order_min_amount = price2num($this->order_min_amount);
863
+        $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
864
+
865
+        $this->tva_assuj	= trim($this->tva_assuj);
866
+        $this->tva_intra	= dol_sanitizeFileName($this->tva_intra,'');
867
+        if (empty($this->status)) $this->status = 0;
868
+
869
+        if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
870
+        if (empty($this->fk_multicurrency))
871
+        {
872
+            $this->multicurrency_code = '';
873
+            $this->fk_multicurrency = 0;
874
+        }
875
+
876
+        // Local taxes
877
+        $this->localtax1_assuj=trim($this->localtax1_assuj);
878
+        $this->localtax2_assuj=trim($this->localtax2_assuj);
879
+
880
+        $this->localtax1_value=trim($this->localtax1_value);
881
+        $this->localtax2_value=trim($this->localtax2_value);
882
+
883
+        if ($this->capital != '') $this->capital=price2num(trim($this->capital));
884
+        if (! is_numeric($this->capital)) $this->capital = '';     // '' = undef
885
+
886
+        $this->effectif_id=trim($this->effectif_id);
887
+        $this->forme_juridique_code=trim($this->forme_juridique_code);
888
+
889
+        //Gencod
890
+        $this->barcode=trim($this->barcode);
891
+
892
+        // For automatic creation
893
+        if ($this->code_client == -1 || $this->code_client === 'auto')           $this->get_codeclient($this,0);
894
+        if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this,1);
895
+
896
+        $this->code_compta=trim($this->code_compta);
897
+        $this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
898
+
899
+        // Check parameters. More tests are done later in the ->verify()
900
+        if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
901
+        {
902
+            $langs->load("errors");
903
+            $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
904
+            return -1;
905
+        }
906
+
907
+        $customer=false;
908
+        if (! empty($allowmodcodeclient) && ! empty($this->client))
909
+        {
910
+            // Attention get_codecompta peut modifier le code suivant le module utilise
911
+            if (empty($this->code_compta))
912
+            {
913
+                $ret=$this->get_codecompta('customer');
914
+                if ($ret < 0) return -1;
915
+            }
916
+
917
+            $customer=true;
918
+        }
919
+
920
+        $supplier=false;
921
+        if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
922
+        {
923
+            // Attention get_codecompta peut modifier le code suivant le module utilise
924
+            if (empty($this->code_compta_fournisseur))
925
+            {
926
+                $ret=$this->get_codecompta('supplier');
927
+                if ($ret < 0) return -1;
928
+            }
929
+
930
+            $supplier=true;
931
+        }
932
+
933
+        //Web services
934
+        $this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
935
+        $this->webservices_key = trim($this->webservices_key);
936
+
937
+        //Incoterms
938
+        $this->fk_incoterms = (int) $this->fk_incoterms;
939
+        $this->location_incoterms = trim($this->location_incoterms);
940
+
941
+        $this->db->begin();
942
+
943
+        // Check name is required and codes are ok or unique.
944
+        // If error, this->errors[] is filled
945
+        $result = 0;
946
+        if ($action != 'add' && $action != 'merge')
947
+        {
948
+            // We don't check when update called during a create because verify was already done.
949
+            // For a merge, we suppose source data is clean and a customer code of a deleted thirdparty must be accepted into a target thirdparty with empty code without duplicate error
950
+            $result = $this->verify();
951
+
952
+            // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
953
+            // So we can update record that were using and old numbering rule.
954
+            if (is_array($this->errors))
955
+            {
956
+                if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client)
957
+                {
958
+                    if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]);	// Remove error message
959
+                }
960
+                if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur)
961
+                {
962
+                    if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]);	// Remove error message
963
+                }
964
+                if (empty($this->errors))	// If there is no more error, we can make like if there is no error at all
965
+                {
966
+                    $result = 0;
967
+                }
968
+            }
969
+        }
970
+
971
+        if ($result >= 0)
972
+        {
973
+            dol_syslog(get_class($this)."::update verify ok or not done");
974
+
975
+            $sql  = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
976
+            $sql .= "entity = " . $this->db->escape($this->entity);
977
+            $sql .= ",nom = '" . $this->db->escape($this->name) ."'"; // Required
978
+            $sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
979
+            $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
980
+            $sql .= ",address = '" . $this->db->escape($this->address) ."'";
981
+
982
+            $sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
983
+            $sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
984
+
985
+            $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
986
+            $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
987
+
988
+            $sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
989
+            $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
990
+            $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
991
+            $sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
992
+            $sql .= ",twitter = ".(! empty($this->twitter)?"'".$this->db->escape($this->twitter)."'":"null");
993
+            $sql .= ",facebook = ".(! empty($this->facebook)?"'".$this->db->escape($this->facebook)."'":"null");
994
+            $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
995
+
996
+            $sql .= ",parent = " . ($this->parent > 0 ? $this->parent : "null");
997
+
998
+            $sql .= ",note_private = ".(! empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null");
999
+            $sql .= ",note_public = ".(! empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null");
1000
+
1001
+            $sql .= ",siren   = '". $this->db->escape($this->idprof1) ."'";
1002
+            $sql .= ",siret   = '". $this->db->escape($this->idprof2) ."'";
1003
+            $sql .= ",ape     = '". $this->db->escape($this->idprof3) ."'";
1004
+            $sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
1005
+            $sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
1006
+            $sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
1007
+
1008
+            $sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null");
1009
+            $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
1010
+            $sql .= ",status = " .$this->status;
1011
+
1012
+            // Local taxes
1013
+            $sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null");
1014
+            $sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null");
1015
+            if($this->localtax1_assuj==1)
1016
+            {
1017
+                if($this->localtax1_value!='')
1018
+                {
1019
+                    $sql .=",localtax1_value =".$this->localtax1_value;
1020
+                }
1021
+                else $sql .=",localtax1_value =0.000";
1022
+            }
1023
+            else $sql .=",localtax1_value =0.000";
1024
+
1025
+            if($this->localtax2_assuj==1)
1026
+            {
1027
+                if($this->localtax2_value!='')
1028
+                {
1029
+                    $sql .=",localtax2_value =".$this->localtax2_value;
1030
+                }
1031
+                else $sql .=",localtax2_value =0.000";
1032
+            }
1033
+            else $sql .=",localtax2_value =0.000";
1034
+
1035
+            $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
1036
+
1037
+            $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
1038
+
1039
+            $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
1040
+            if (isset($this->stcomm_id))
1041
+            {
1042
+                $sql .= ",fk_stcomm=".(!empty($this->stcomm_id)  ? $this->stcomm_id : "0");
1043
+            }
1044
+            $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
1045
+
1046
+            $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
1047
+
1048
+            $sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
1049
+            $sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
1050
+            $sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
1051
+            $sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
1052
+            $sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
1053
+
1054
+            $sql .= ",client = " . (! empty($this->client)?$this->client:0);
1055
+            $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
1056
+            $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
1057
+            $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
1058
+            $sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
1059
+            $sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
1060
+            $sql .= ",order_min_amount= ".($this->order_min_amount!=''?$this->order_min_amount:'null');
1061
+            $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount!=''?$this->supplier_order_min_amount:'null');
1062
+            $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
1063
+
1064
+            $sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
1065
+            $sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
1066
+
1067
+            //Incoterms
1068
+            $sql.= ", fk_incoterms = ".$this->fk_incoterms;
1069
+            $sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
1070
+
1071
+            if ($customer)
1072
+            {
1073
+                $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
1074
+                $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
1075
+            }
1076
+
1077
+            if ($supplier)
1078
+            {
1079
+                $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
1080
+                $sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
1081
+            }
1082
+            $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id:"null");
1083
+            $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
1084
+            $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
1085
+            $sql .= " WHERE rowid = " . (int) $id;
1086
+
1087
+            $resql=$this->db->query($sql);
1088
+            if ($resql)
1089
+            {
1090
+                if (is_object($this->oldcopy))	// If we have information on old values
1091
+                {
1092
+                    if ($this->oldcopy->country_id != $this->country_id)
1093
+                    {
1094
+                        unset($this->country_code);
1095
+                        unset($this->country);
1096
+                    }
1097
+                    if ($this->oldcopy->state_id != $this->state_id)
1098
+                    {
1099
+                        unset($this->state_code);
1100
+                        unset($this->state);
1101
+                    }
1102
+                }
1103
+                else
1104
+                {
1105
+                    unset($this->country_code);	// We clean this, in the doubt, because it may have been changed after an update of country_id
1106
+                    unset($this->country);
1107
+                    unset($this->state_code);
1108
+                    unset($this->state);
1109
+                }
1110
+
1111
+                $nbrowsaffected = $this->db->affected_rows($resql);
1112
+
1113
+                if (! $error && $nbrowsaffected)
1114
+                {
1115
+                    // Update information on linked member if it is an update
1116
+                    if (! $nosyncmember && ! empty($conf->adherent->enabled))
1117
+                    {
1118
+                        require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1119
+
1120
+                        dol_syslog(get_class($this)."::update update linked member");
1121
+
1122
+                        $lmember=new Adherent($this->db);
1123
+                        $result=$lmember->fetch(0, 0, $this->id);
1124
+
1125
+                        if ($result > 0)
1126
+                        {
1127
+                            $lmember->societe=$this->name;
1128
+                            //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname;	// We keep firstname and lastname of member unchanged
1129
+                            //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname;		// We keep firstname and lastname of member unchanged
1130
+                            $lmember->address=$this->address;
1131
+                            $lmember->email=$this->email;
1132
+                            $lmember->skype=$this->skype;
1133
+                            $lmember->twitter=$this->twitter;
1134
+                            $lmember->facebook=$this->facebook;
1135
+                            $lmember->phone=$this->phone;
1136
+
1137
+                            $result=$lmember->update($user,0,1,1,1);	// Use nosync to 1 to avoid cyclic updates
1138
+                            if ($result < 0)
1139
+                            {
1140
+                                $this->error=$lmember->error;
1141
+                                dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
1142
+                                $error++;
1143
+                            }
1144
+                        }
1145
+                        elseif ($result < 0)
1146
+                        {
1147
+                            $this->error=$lmember->error;
1148
+                            $error++;
1149
+                        }
1150
+                    }
1151
+                }
1152
+
1153
+                $action='update';
1154
+
1155
+                // Actions on extra fields
1156
+                if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1157
+                {
1158
+                    $result=$this->insertExtraFields();
1159
+                    if ($result < 0)
1160
+                    {
1161
+                        $error++;
1162
+                    }
1163
+                }
1164
+
1165
+                if (! $error && $call_trigger)
1166
+                {
1167
+                    // Call trigger
1168
+                    $result=$this->call_trigger('COMPANY_MODIFY',$user);
1169
+                    if ($result < 0) $error++;
1170
+                    // End call triggers
1171
+                }
1172
+
1173
+                if (! $error)
1174
+                {
1175
+                    dol_syslog(get_class($this)."::Update success");
1176
+                    $this->db->commit();
1177
+                    return 1;
1178
+                }
1179
+                else
1180
+                {
1181
+                    $this->db->rollback();
1182
+                    return -1;
1183
+                }
1184
+            }
1185
+            else
1186
+            {
1187
+                if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1188
+                {
1189
+                    // Doublon
1190
+                    $this->error = $langs->trans("ErrorDuplicateField");
1191
+                    $result = -1;
1192
+                }
1193
+                else
1194
+                {
1195
+                    $this->error = $this->db->lasterror();
1196
+                    $result = -2;
1197
+                }
1198
+                $this->db->rollback();
1199
+                return $result;
1200
+            }
1201
+        }
1202
+        else
1203
+        {
1204
+            $this->db->rollback();
1205
+            dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
1206
+            return -3;
1207
+        }
1208
+    }
1209
+
1210
+    /**
1211
+     *    Load a third party from database into memory
1212
+     *
1213
+     *    @param	int		$rowid			Id of third party to load
1214
+     *    @param    string	$ref			Reference of third party, name (Warning, this can return several records)
1215
+     *    @param    string	$ref_ext       	External reference of third party (Warning, this information is a free field not provided by Dolibarr)
1216
+     *    @param    string	$ref_int       	Internal reference of third party (not used by dolibarr)
1217
+     *    @param    string	$idprof1		Prof id 1 of third party (Warning, this can return several records)
1218
+     *    @param    string	$idprof2		Prof id 2 of third party (Warning, this can return several records)
1219
+     *    @param    string	$idprof3		Prof id 3 of third party (Warning, this can return several records)
1220
+     *    @param    string	$idprof4		Prof id 4 of third party (Warning, this can return several records)
1221
+     *    @param    string	$idprof5		Prof id 5 of third party (Warning, this can return several records)
1222
+     *    @param    string	$idprof6		Prof id 6 of third party (Warning, this can return several records)
1223
+     *    @param    string	$email   		Email of third party (Warning, this can return several records)
1224
+     *    @param    string	$ref_alias 		Name_alias of third party (Warning, this can return several records)
1225
+     *    @return   int						>0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
1226
+     */
1227
+    function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='', $email='', $ref_alias='')
1228
+    {
1229
+        global $langs;
1230
+        global $conf;
1231
+
1232
+        if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1;
1233
+
1234
+        $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
1235
+        $sql .= ', s.status';
1236
+        $sql .= ', s.price_level';
1237
+        $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
1238
+        $sql .= ', s.phone, s.fax, s.email, s.skype, s.twitter, s.facebook, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
1239
+        $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
1240
+        $sql .= ', s.capital, s.tva_intra';
1241
+        $sql .= ', s.fk_typent as typent_id';
1242
+        $sql .= ', s.fk_effectif as effectif_id';
1243
+        $sql .= ', s.fk_forme_juridique as forme_juridique_code';
1244
+        $sql .= ', s.webservices_url, s.webservices_key';
1245
+        $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
1246
+        $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.remise_supplier, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
1247
+        $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
1248
+        $sql .= ', s.fk_shipping_method';
1249
+        $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
1250
+        $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
1251
+        $sql .= ', s.fk_multicurrency, s.multicurrency_code';
1252
+        $sql .= ', fj.libelle as forme_juridique';
1253
+        $sql .= ', e.libelle as effectif';
1254
+        $sql .= ', c.code as country_code, c.label as country';
1255
+        $sql .= ', d.code_departement as state_code, d.nom as state';
1256
+        $sql .= ', st.libelle as stcomm';
1257
+        $sql .= ', te.code as typent_code';
1258
+        $sql .= ', i.libelle as libelle_incoterms';
1259
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
1260
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
1261
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
1262
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
1263
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
1264
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
1265
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
1266
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
1267
+
1268
+        $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
1269
+        if ($rowid)     $sql .= ' AND s.rowid = '.$rowid;
1270
+        if ($ref)       $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
1271
+        if ($ref_alias) $sql .= " AND s.nom_alias = '".$this->db->escape($ref_alias)."'";
1272
+        if ($ref_ext)   $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
1273
+        if ($ref_int)   $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'";
1274
+        if ($idprof1)   $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
1275
+        if ($idprof2)   $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
1276
+        if ($idprof3)   $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
1277
+        if ($idprof4)   $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
1278
+        if ($idprof5)   $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
1279
+        if ($idprof6)   $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
1280
+        if ($email)     $sql .= " AND s.email = '".$this->db->escape($email)."'";
1281
+
1282
+        $resql=$this->db->query($sql);
1283
+        if ($resql)
1284
+        {
1285
+            $num=$this->db->num_rows($resql);
1286
+            if ($num > 1)
1287
+            {
1288
+                $this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
1289
+                dol_syslog($this->error, LOG_ERR);
1290
+                $result = -2;
1291
+            }
1292
+            elseif ($num)   // $num = 1
1293
+            {
1294
+                $obj = $this->db->fetch_object($resql);
1295
+
1296
+                $this->id           = $obj->rowid;
1297
+                $this->entity       = $obj->entity;
1298
+                $this->canvas		= $obj->canvas;
1299
+
1300
+                $this->ref          = $obj->rowid;
1301
+                $this->name 		= $obj->name;
1302
+                $this->nom          = $obj->name;		// deprecated
1303
+                $this->name_alias = $obj->name_alias;
1304
+                $this->ref_ext      = $obj->ref_ext;
1305
+                $this->ref_int      = $obj->ref_int;
1306
+
1307
+                $this->date_creation     = $this->db->jdate($obj->date_creation);
1308
+                $this->date_modification = $this->db->jdate($obj->date_modification);
1309
+                $this->user_creation     = $obj->fk_user_creat;
1310
+                $this->user_modification = $obj->fk_user_modif;
1311
+
1312
+                $this->address 		= $obj->address;
1313
+                $this->zip 			= $obj->zip;
1314
+                $this->town 		= $obj->town;
1315
+
1316
+                $this->country_id   = $obj->country_id;
1317
+                $this->country_code = $obj->country_id?$obj->country_code:'';
1318
+                $this->country 		= $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
1319
+
1320
+                $this->state_id     = $obj->fk_departement;
1321
+                $this->state_code   = $obj->state_code;
1322
+                $this->state        = ($obj->state!='-'?$obj->state:'');
1323
+
1324
+                $transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
1325
+                $libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
1326
+                $this->stcomm_id = $obj->fk_stcomm;     // id statut commercial
1327
+                $this->statut_commercial = $libelle;    // libelle statut commercial
1328
+
1329
+                $this->email = $obj->email;
1330
+                $this->skype = $obj->skype;
1331
+                $this->twitter = $obj->twitter;
1332
+                $this->facebook = $obj->facebook;
1333
+                $this->url = $obj->url;
1334
+                $this->phone = $obj->phone;
1335
+                $this->fax = $obj->fax;
1336
+
1337
+                $this->parent    = $obj->parent;
1338
+
1339
+                $this->idprof1		= $obj->idprof1;
1340
+                $this->idprof2		= $obj->idprof2;
1341
+                $this->idprof3		= $obj->idprof3;
1342
+                $this->idprof4		= $obj->idprof4;
1343
+                $this->idprof5		= $obj->idprof5;
1344
+                $this->idprof6		= $obj->idprof6;
1345
+
1346
+                $this->capital   = $obj->capital;
1347
+
1348
+                $this->code_client = $obj->code_client;
1349
+                $this->code_fournisseur = $obj->code_fournisseur;
1350
+
1351
+                $this->code_compta = $obj->code_compta;
1352
+                $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
1353
+
1354
+                $this->barcode = $obj->barcode;
1355
+
1356
+                $this->tva_assuj      = $obj->tva_assuj;
1357
+                $this->tva_intra      = $obj->tva_intra;
1358
+                $this->status = $obj->status;
1359
+
1360
+                // Local Taxes
1361
+                $this->localtax1_assuj      = $obj->localtax1_assuj;
1362
+                $this->localtax2_assuj      = $obj->localtax2_assuj;
1363
+
1364
+                $this->localtax1_value		= $obj->localtax1_value;
1365
+                $this->localtax2_value		= $obj->localtax2_value;
1366
+
1367
+                $this->typent_id      = $obj->typent_id;
1368
+                $this->typent_code    = $obj->typent_code;
1369
+
1370
+                $this->effectif_id    = $obj->effectif_id;
1371
+                $this->effectif       = $obj->effectif_id?$obj->effectif:'';
1372
+
1373
+                $this->forme_juridique_code= $obj->forme_juridique_code;
1374
+                $this->forme_juridique     = $obj->forme_juridique_code?$obj->forme_juridique:'';
1375
+
1376
+                $this->fk_prospectlevel = $obj->fk_prospectlevel;
1377
+
1378
+                $this->prefix_comm = $obj->prefix_comm;
1379
+
1380
+                $this->remise_percent		= $obj->remise_client;
1381
+                $this->remise_supplier_percent		= $obj->remise_supplier;
1382
+                $this->mode_reglement_id 	= $obj->mode_reglement;
1383
+                $this->cond_reglement_id 	= $obj->cond_reglement;
1384
+                $this->mode_reglement_supplier_id 	= $obj->mode_reglement_supplier;
1385
+                $this->cond_reglement_supplier_id 	= $obj->cond_reglement_supplier;
1386
+                $this->shipping_method_id   = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
1387
+                $this->fk_account			= $obj->fk_account;
1388
+
1389
+                $this->client      = $obj->client;
1390
+                $this->fournisseur = $obj->fournisseur;
1391
+
1392
+                $this->note = $obj->note_private; // TODO Deprecated for backward comtability
1393
+                $this->note_private = $obj->note_private;
1394
+                $this->note_public = $obj->note_public;
1395
+                $this->modelpdf = $obj->model_pdf;
1396
+                $this->default_lang = $obj->default_lang;
1397
+                $this->logo = $obj->logo;
1398
+
1399
+                $this->webservices_url = $obj->webservices_url;
1400
+                $this->webservices_key = $obj->webservices_key;
1401
+
1402
+                $this->outstanding_limit		= $obj->outstanding_limit;
1403
+                $this->order_min_amount			= $obj->order_min_amount;
1404
+                $this->supplier_order_min_amount	= $obj->supplier_order_min_amount;
1405
+
1406
+                // multiprix
1407
+                $this->price_level = $obj->price_level;
1408
+
1409
+                $this->import_key = $obj->import_key;
1410
+
1411
+                //Incoterms
1412
+                $this->fk_incoterms = $obj->fk_incoterms;
1413
+                $this->location_incoterms = $obj->location_incoterms;
1414
+                $this->libelle_incoterms = $obj->libelle_incoterms;
1415
+
1416
+                // multicurrency
1417
+                $this->fk_multicurrency = $obj->fk_multicurrency;
1418
+                $this->multicurrency_code = $obj->multicurrency_code;
1419
+
1420
+                $result = 1;
1421
+
1422
+                // fetch optionals attributes and labels
1423
+                $this->fetch_optionals();
1424
+            }
1425
+            else
1426
+            {
1427
+                $result = 0;
1428
+            }
1429
+
1430
+            $this->db->free($resql);
1431
+        }
1432
+        else
1433
+        {
1434
+            $this->error=$this->db->lasterror();
1435
+            $result = -3;
1436
+        }
1437
+
1438
+        // Use first price level if level not defined for third party
1439
+        if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1;
1440
+
1441
+        return $result;
1442
+    }
1443
+
1444
+    /**
1445
+     *    Delete a third party from database and all its dependencies (contacts, rib...)
1446
+     *
1447
+     *    @param	int		$id             Id of third party to delete
1448
+     *    @param    User    $fuser          User who ask to delete thirparty
1449
+     *    @param    int		$call_trigger   0=No, 1=yes
1450
+     *    @return	int						<0 if KO, 0 if nothing done, >0 if OK
1451
+     */
1452
+    function delete($id, User $fuser=null, $call_trigger=1)
1453
+    {
1454
+        global $langs, $conf, $user;
1455
+
1456
+        if (empty($fuser)) $fuser=$user;
1457
+
1458
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1459
+
1460
+        $entity=isset($this->entity)?$this->entity:$conf->entity;
1461
+
1462
+        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1463
+        $error = 0;
1464
+
1465
+        // Test if child exists
1466
+        $objectisused = $this->isObjectUsed($id);
1467
+        if (empty($objectisused))
1468
+        {
1469
+            $this->db->begin();
1470
+
1471
+            // User is mandatory for trigger call
1472
+            if (! $error && $call_trigger)
1473
+            {
1474
+                // Call trigger
1475
+                $result=$this->call_trigger('COMPANY_DELETE',$fuser);
1476
+                if ($result < 0) $error++;
1477
+                // End call triggers
1478
+            }
1479
+
1480
+            if (! $error)
1481
+            {
1482
+                require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1483
+                $static_cat = new Categorie($this->db);
1484
+                $toute_categs = array();
1485
+
1486
+                // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
1487
+                if ($this->client || $this->prospect)
1488
+                {
1489
+                    $toute_categs['customer'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER);
1490
+                }
1491
+                if ($this->fournisseur)
1492
+                {
1493
+                    $toute_categs['supplier'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER);
1494
+                }
1495
+
1496
+                // Remove each "Categorie"
1497
+                foreach ($toute_categs as $type => $categs_type)
1498
+                {
1499
+                    foreach ($categs_type as $cat)
1500
+                    {
1501
+                        $cat->del_type($this, $type);
1502
+                    }
1503
+                }
1504
+            }
1505
+
1506
+            foreach ($this->childtablesoncascade as $tabletodelete)
1507
+            {
1508
+                if (! $error)
1509
+                {
1510
+                    $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
1511
+                    $sql.= " WHERE fk_soc = " . $id;
1512
+                    if (! $this->db->query($sql))
1513
+                    {
1514
+                        $error++;
1515
+                        $this->errors[] = $this->db->lasterror();
1516
+                    }
1517
+                }
1518
+            }
1519
+
1520
+            // Removed extrafields
1521
+            if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1522
+            {
1523
+                $result=$this->deleteExtraFields();
1524
+                if ($result < 0)
1525
+                {
1526
+                    $error++;
1527
+                    dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
1528
+                }
1529
+            }
1530
+
1531
+            // Remove links to subsidiaries companies
1532
+            if (! $error)
1533
+            {
1534
+                $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1535
+                $sql.= " SET parent = NULL";
1536
+                $sql.= " WHERE parent = " . $id;
1537
+                if (! $this->db->query($sql))
1538
+                {
1539
+                    $error++;
1540
+                    $this->errors[] = $this->db->lasterror();
1541
+                }
1542
+            }
1543
+
1544
+            // Remove third party
1545
+            if (! $error)
1546
+            {
1547
+                $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
1548
+                $sql.= " WHERE rowid = " . $id;
1549
+                if (! $this->db->query($sql))
1550
+                {
1551
+                    $error++;
1552
+                    $this->errors[] = $this->db->lasterror();
1553
+                }
1554
+            }
1555
+
1556
+            if (! $error)
1557
+            {
1558
+                $this->db->commit();
1559
+
1560
+                // Delete directory
1561
+                if (! empty($conf->societe->multidir_output[$entity]))
1562
+                {
1563
+                    $docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
1564
+                    if (dol_is_dir($docdir))
1565
+                    {
1566
+                        dol_delete_dir_recursive($docdir);
1567
+                    }
1568
+                }
1569
+
1570
+                return 1;
1571
+            }
1572
+            else
1573
+            {
1574
+                dol_syslog($this->error, LOG_ERR);
1575
+                $this->db->rollback();
1576
+                return -1;
1577
+            }
1578
+        }
1579
+        else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
1580
+        return 0;
1581
+    }
1582 1582
 
1583 1583
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1584
-	/**
1585
-	 *  Define third party as a customer
1586
-	 *
1587
-	 *	@return		int		<0 if KO, >0 if OK
1588
-	 */
1589
-	function set_as_client()
1590
-	{
1584
+    /**
1585
+     *  Define third party as a customer
1586
+     *
1587
+     *	@return		int		<0 if KO, >0 if OK
1588
+     */
1589
+    function set_as_client()
1590
+    {
1591 1591
         // phpcs:enable
1592
-		if ($this->id)
1593
-		{
1594
-			$newclient=1;
1595
-			if ($this->client == 2 || $this->client == 3) $newclient=3;	//If prospect, we keep prospect tag
1596
-			$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1597
-			$sql.= " SET client = ".$newclient;
1598
-			$sql.= " WHERE rowid = " . $this->id;
1599
-
1600
-			$resql=$this->db->query($sql);
1601
-			if ($resql)
1602
-			{
1603
-				$this->client = $newclient;
1604
-				return 1;
1605
-			}
1606
-			else return -1;
1607
-		}
1608
-		return 0;
1609
-	}
1592
+        if ($this->id)
1593
+        {
1594
+            $newclient=1;
1595
+            if ($this->client == 2 || $this->client == 3) $newclient=3;	//If prospect, we keep prospect tag
1596
+            $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
1597
+            $sql.= " SET client = ".$newclient;
1598
+            $sql.= " WHERE rowid = " . $this->id;
1599
+
1600
+            $resql=$this->db->query($sql);
1601
+            if ($resql)
1602
+            {
1603
+                $this->client = $newclient;
1604
+                return 1;
1605
+            }
1606
+            else return -1;
1607
+        }
1608
+        return 0;
1609
+    }
1610 1610
 
1611 1611
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1612
-	/**
1613
-	 *  Definit la societe comme un client
1614
-	 *
1615
-	 *  @param	float	$remise		Valeur en % de la remise
1616
-	 *  @param  string	$note		Note/Motif de modification de la remise
1617
-	 *  @param  User	$user		Utilisateur qui definie la remise
1618
-	 *	@return	int					<0 if KO, >0 if OK
1619
-	 */
1620
-	function set_remise_client($remise, $note, User $user)
1621
-	{
1612
+    /**
1613
+     *  Definit la societe comme un client
1614
+     *
1615
+     *  @param	float	$remise		Valeur en % de la remise
1616
+     *  @param  string	$note		Note/Motif de modification de la remise
1617
+     *  @param  User	$user		Utilisateur qui definie la remise
1618
+     *	@return	int					<0 if KO, >0 if OK
1619
+     */
1620
+    function set_remise_client($remise, $note, User $user)
1621
+    {
1622 1622
         // phpcs:enable
1623
-		global $conf, $langs;
1624
-
1625
-		// Nettoyage parametres
1626
-		$note=trim($note);
1627
-		if (! $note)
1628
-		{
1629
-			$this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
1630
-			return -2;
1631
-		}
1632
-
1633
-		dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
1634
-
1635
-		if ($this->id)
1636
-		{
1637
-			$this->db->begin();
1638
-
1639
-			$now=dol_now();
1640
-
1641
-			// Positionne remise courante
1642
-			$sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1643
-			$sql.= " SET remise_client = '".$this->db->escape($remise)."'";
1644
-			$sql.= " WHERE rowid = " . $this->id;
1645
-			$resql=$this->db->query($sql);
1646
-			if (! $resql)
1647
-			{
1648
-				$this->db->rollback();
1649
-				$this->error=$this->db->error();
1650
-				return -1;
1651
-			}
1652
-
1653
-			// Ecrit trace dans historique des remises
1654
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
1655
-			$sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
1656
-			$sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1657
-			$sql.= " '".$this->db->escape($note)."',";
1658
-			$sql.= " ".$user->id;
1659
-			$sql.= ")";
1660
-
1661
-			$resql=$this->db->query($sql);
1662
-			if (! $resql)
1663
-			{
1664
-				$this->db->rollback();
1665
-				$this->error=$this->db->lasterror();
1666
-				return -1;
1667
-			}
1668
-
1669
-			$this->db->commit();
1670
-			return 1;
1671
-		}
1672
-	}
1623
+        global $conf, $langs;
1624
+
1625
+        // Nettoyage parametres
1626
+        $note=trim($note);
1627
+        if (! $note)
1628
+        {
1629
+            $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
1630
+            return -2;
1631
+        }
1632
+
1633
+        dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
1634
+
1635
+        if ($this->id)
1636
+        {
1637
+            $this->db->begin();
1638
+
1639
+            $now=dol_now();
1640
+
1641
+            // Positionne remise courante
1642
+            $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1643
+            $sql.= " SET remise_client = '".$this->db->escape($remise)."'";
1644
+            $sql.= " WHERE rowid = " . $this->id;
1645
+            $resql=$this->db->query($sql);
1646
+            if (! $resql)
1647
+            {
1648
+                $this->db->rollback();
1649
+                $this->error=$this->db->error();
1650
+                return -1;
1651
+            }
1652
+
1653
+            // Ecrit trace dans historique des remises
1654
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
1655
+            $sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
1656
+            $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1657
+            $sql.= " '".$this->db->escape($note)."',";
1658
+            $sql.= " ".$user->id;
1659
+            $sql.= ")";
1660
+
1661
+            $resql=$this->db->query($sql);
1662
+            if (! $resql)
1663
+            {
1664
+                $this->db->rollback();
1665
+                $this->error=$this->db->lasterror();
1666
+                return -1;
1667
+            }
1668
+
1669
+            $this->db->commit();
1670
+            return 1;
1671
+        }
1672
+    }
1673 1673
 
1674 1674
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1675
-	/**
1676
-	 *  Definit la societe comme un client
1677
-	 *
1678
-	 *  @param	float	$remise		Valeur en % de la remise
1679
-	 *  @param  string	$note		Note/Motif de modification de la remise
1680
-	 *  @param  User	$user		Utilisateur qui definie la remise
1681
-	 *	@return	int					<0 if KO, >0 if OK
1682
-	 */
1683
-	function set_remise_supplier($remise, $note, User $user)
1684
-	{
1675
+    /**
1676
+     *  Definit la societe comme un client
1677
+     *
1678
+     *  @param	float	$remise		Valeur en % de la remise
1679
+     *  @param  string	$note		Note/Motif de modification de la remise
1680
+     *  @param  User	$user		Utilisateur qui definie la remise
1681
+     *	@return	int					<0 if KO, >0 if OK
1682
+     */
1683
+    function set_remise_supplier($remise, $note, User $user)
1684
+    {
1685 1685
         // phpcs:enable
1686
-		global $conf, $langs;
1687
-
1688
-		// Nettoyage parametres
1689
-		$note=trim($note);
1690
-		if (! $note)
1691
-		{
1692
-			$this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
1693
-			return -2;
1694
-		}
1695
-
1696
-		dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
1697
-
1698
-		if ($this->id)
1699
-		{
1700
-			$this->db->begin();
1701
-
1702
-			$now=dol_now();
1703
-
1704
-			// Positionne remise courante
1705
-			$sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1706
-			$sql.= " SET remise_supplier = '".$this->db->escape($remise)."'";
1707
-			$sql.= " WHERE rowid = " . $this->id;
1708
-			$resql=$this->db->query($sql);
1709
-			if (! $resql)
1710
-			{
1711
-				$this->db->rollback();
1712
-				$this->error=$this->db->error();
1713
-				return -1;
1714
-			}
1715
-
1716
-			// Ecrit trace dans historique des remises
1717
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
1718
-			$sql.= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
1719
-			$sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1720
-			$sql.= " '".$this->db->escape($note)."',";
1721
-			$sql.= " ".$user->id;
1722
-			$sql.= ")";
1723
-
1724
-			$resql=$this->db->query($sql);
1725
-			if (! $resql)
1726
-			{
1727
-				$this->db->rollback();
1728
-				$this->error=$this->db->lasterror();
1729
-				return -1;
1730
-			}
1731
-
1732
-			$this->db->commit();
1733
-			return 1;
1734
-		}
1735
-	}
1686
+        global $conf, $langs;
1687
+
1688
+        // Nettoyage parametres
1689
+        $note=trim($note);
1690
+        if (! $note)
1691
+        {
1692
+            $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
1693
+            return -2;
1694
+        }
1695
+
1696
+        dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
1697
+
1698
+        if ($this->id)
1699
+        {
1700
+            $this->db->begin();
1701
+
1702
+            $now=dol_now();
1703
+
1704
+            // Positionne remise courante
1705
+            $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
1706
+            $sql.= " SET remise_supplier = '".$this->db->escape($remise)."'";
1707
+            $sql.= " WHERE rowid = " . $this->id;
1708
+            $resql=$this->db->query($sql);
1709
+            if (! $resql)
1710
+            {
1711
+                $this->db->rollback();
1712
+                $this->error=$this->db->error();
1713
+                return -1;
1714
+            }
1715
+
1716
+            // Ecrit trace dans historique des remises
1717
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
1718
+            $sql.= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
1719
+            $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
1720
+            $sql.= " '".$this->db->escape($note)."',";
1721
+            $sql.= " ".$user->id;
1722
+            $sql.= ")";
1723
+
1724
+            $resql=$this->db->query($sql);
1725
+            if (! $resql)
1726
+            {
1727
+                $this->db->rollback();
1728
+                $this->error=$this->db->lasterror();
1729
+                return -1;
1730
+            }
1731
+
1732
+            $this->db->commit();
1733
+            return 1;
1734
+        }
1735
+    }
1736 1736
 
1737 1737
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1738
-	/**
1739
-	 *    	Add a discount for third party
1740
-	 *
1741
-	 *    	@param	float	$remise     	Amount of discount
1742
-	 *    	@param  User	$user       	User adding discount
1743
-	 *    	@param  string	$desc			Reason of discount
1744
-	 *      @param  float	$tva_tx     	VAT rate
1745
-	 *      @param	int		$discount_type	0 => customer discount, 1 => supplier discount
1746
-	 *		@return	int					<0 if KO, id of discount record if OK
1747
-	 */
1748
-	function set_remise_except($remise, User $user, $desc, $tva_tx=0, $discount_type=0)
1749
-	{
1738
+    /**
1739
+     *    	Add a discount for third party
1740
+     *
1741
+     *    	@param	float	$remise     	Amount of discount
1742
+     *    	@param  User	$user       	User adding discount
1743
+     *    	@param  string	$desc			Reason of discount
1744
+     *      @param  float	$tva_tx     	VAT rate
1745
+     *      @param	int		$discount_type	0 => customer discount, 1 => supplier discount
1746
+     *		@return	int					<0 if KO, id of discount record if OK
1747
+     */
1748
+    function set_remise_except($remise, User $user, $desc, $tva_tx=0, $discount_type=0)
1749
+    {
1750 1750
         // phpcs:enable
1751
-		global $langs;
1752
-
1753
-		// Clean parameters
1754
-		$remise = price2num($remise);
1755
-		$desc = trim($desc);
1756
-
1757
-		// Check parameters
1758
-		if (! $remise > 0)
1759
-		{
1760
-			$this->error=$langs->trans("ErrorWrongValueForParameter","1");
1761
-			return -1;
1762
-		}
1763
-		if (! $desc)
1764
-		{
1765
-			$this->error=$langs->trans("ErrorWrongValueForParameter","3");
1766
-			return -2;
1767
-		}
1768
-
1769
-		if ($this->id)
1770
-		{
1771
-			require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1772
-
1773
-			$discount = new DiscountAbsolute($this->db);
1774
-			$discount->fk_soc=$this->id;
1775
-
1776
-			$discount->discount_type=$discount_type;
1777
-
1778
-			$discount->amount_ht=$discount->multicurrency_amount_ht=price2num($remise,'MT');
1779
-			$discount->amount_tva=$discount->multicurrency_amount_tva=price2num($remise*$tva_tx/100,'MT');
1780
-			$discount->amount_ttc=$discount->multicurrency_amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT');
1781
-
1782
-			$discount->tva_tx=price2num($tva_tx,'MT');
1783
-			$discount->description=$desc;
1784
-
1785
-			$result=$discount->create($user);
1786
-			if ($result > 0)
1787
-			{
1788
-				return $result;
1789
-			}
1790
-			else
1791
-			{
1792
-				$this->error=$discount->error;
1793
-				return -3;
1794
-			}
1795
-		}
1796
-		else return 0;
1797
-	}
1798
-
1799
-	/**
1800
-	 *  Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe
1801
-	 *
1802
-	 *	@param	User	$user			Filtre sur un user auteur des remises
1803
-	 * 	@param	string	$filter			Filtre autre
1804
-	 * 	@param	integer	$maxvalue		Filter on max value for discount
1805
-	 * 	@param	int		$discount_type	0 => customer discount, 1 => supplier discount
1806
-	 *	@return	int					<0 if KO, Credit note amount otherwise
1807
-	 */
1808
-	function getAvailableDiscounts($user='',$filter='',$maxvalue=0,$discount_type=0)
1809
-	{
1810
-		require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1811
-
1812
-		$discountstatic=new DiscountAbsolute($this->db);
1813
-		$result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue,$discount_type);
1814
-		if ($result >= 0)
1815
-		{
1816
-			return $result;
1817
-		}
1818
-		else
1819
-		{
1820
-			$this->error=$discountstatic->error;
1821
-			return -1;
1822
-		}
1823
-	}
1824
-
1825
-	/**
1826
-	 *  Return array of sales representatives
1827
-	 *
1828
-	 *  @param	User	$user		Object user
1829
-	 *  @param	int		$mode		0=Array with properties, 1=Array of id.
1830
-	 *  @return array       		Array of sales representatives of third party
1831
-	 */
1832
-	function getSalesRepresentatives(User $user, $mode=0)
1833
-	{
1834
-		global $conf;
1835
-
1836
-		$reparray=array();
1837
-
1838
-		$sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
1839
-		$sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
1840
-		if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1841
-		{
1842
-			$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1843
-			$sql.= " WHERE ((ug.fk_user = sc.fk_user";
1844
-			$sql.= " AND ug.entity = ".$conf->entity.")";
1845
-			$sql.= " OR u.admin = 1)";
1846
-		}
1847
-		else
1848
-			$sql.= " WHERE entity in (0, ".$conf->entity.")";
1849
-
1850
-		$sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
1851
-
1852
-		$resql = $this->db->query($sql);
1853
-		if ($resql)
1854
-		{
1855
-			$num = $this->db->num_rows($resql);
1856
-			$i=0;
1857
-			while ($i < $num)
1858
-			{
1859
-				$obj = $this->db->fetch_object($resql);
1860
-
1861
-				if (empty($mode))
1862
-				{
1863
-					$reparray[$i]['id']=$obj->rowid;
1864
-					$reparray[$i]['lastname']=$obj->lastname;
1865
-					$reparray[$i]['firstname']=$obj->firstname;
1866
-					$reparray[$i]['email']=$obj->email;
1867
-					$reparray[$i]['statut']=$obj->statut;
1868
-					$reparray[$i]['entity']=$obj->entity;
1869
-					$reparray[$i]['login']=$obj->login;
1870
-					$reparray[$i]['photo']=$obj->photo;
1871
-				}
1872
-				else
1873
-				{
1874
-					$reparray[]=$obj->rowid;
1875
-				}
1876
-				$i++;
1877
-			}
1878
-			return $reparray;
1879
-		}
1880
-		else {
1881
-			dol_print_error($this->db);
1882
-			return -1;
1883
-		}
1884
-	}
1751
+        global $langs;
1752
+
1753
+        // Clean parameters
1754
+        $remise = price2num($remise);
1755
+        $desc = trim($desc);
1756
+
1757
+        // Check parameters
1758
+        if (! $remise > 0)
1759
+        {
1760
+            $this->error=$langs->trans("ErrorWrongValueForParameter","1");
1761
+            return -1;
1762
+        }
1763
+        if (! $desc)
1764
+        {
1765
+            $this->error=$langs->trans("ErrorWrongValueForParameter","3");
1766
+            return -2;
1767
+        }
1768
+
1769
+        if ($this->id)
1770
+        {
1771
+            require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1772
+
1773
+            $discount = new DiscountAbsolute($this->db);
1774
+            $discount->fk_soc=$this->id;
1775
+
1776
+            $discount->discount_type=$discount_type;
1777
+
1778
+            $discount->amount_ht=$discount->multicurrency_amount_ht=price2num($remise,'MT');
1779
+            $discount->amount_tva=$discount->multicurrency_amount_tva=price2num($remise*$tva_tx/100,'MT');
1780
+            $discount->amount_ttc=$discount->multicurrency_amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT');
1781
+
1782
+            $discount->tva_tx=price2num($tva_tx,'MT');
1783
+            $discount->description=$desc;
1784
+
1785
+            $result=$discount->create($user);
1786
+            if ($result > 0)
1787
+            {
1788
+                return $result;
1789
+            }
1790
+            else
1791
+            {
1792
+                $this->error=$discount->error;
1793
+                return -3;
1794
+            }
1795
+        }
1796
+        else return 0;
1797
+    }
1798
+
1799
+    /**
1800
+     *  Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe
1801
+     *
1802
+     *	@param	User	$user			Filtre sur un user auteur des remises
1803
+     * 	@param	string	$filter			Filtre autre
1804
+     * 	@param	integer	$maxvalue		Filter on max value for discount
1805
+     * 	@param	int		$discount_type	0 => customer discount, 1 => supplier discount
1806
+     *	@return	int					<0 if KO, Credit note amount otherwise
1807
+     */
1808
+    function getAvailableDiscounts($user='',$filter='',$maxvalue=0,$discount_type=0)
1809
+    {
1810
+        require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
1811
+
1812
+        $discountstatic=new DiscountAbsolute($this->db);
1813
+        $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue,$discount_type);
1814
+        if ($result >= 0)
1815
+        {
1816
+            return $result;
1817
+        }
1818
+        else
1819
+        {
1820
+            $this->error=$discountstatic->error;
1821
+            return -1;
1822
+        }
1823
+    }
1824
+
1825
+    /**
1826
+     *  Return array of sales representatives
1827
+     *
1828
+     *  @param	User	$user		Object user
1829
+     *  @param	int		$mode		0=Array with properties, 1=Array of id.
1830
+     *  @return array       		Array of sales representatives of third party
1831
+     */
1832
+    function getSalesRepresentatives(User $user, $mode=0)
1833
+    {
1834
+        global $conf;
1835
+
1836
+        $reparray=array();
1837
+
1838
+        $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
1839
+        $sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
1840
+        if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1841
+        {
1842
+            $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1843
+            $sql.= " WHERE ((ug.fk_user = sc.fk_user";
1844
+            $sql.= " AND ug.entity = ".$conf->entity.")";
1845
+            $sql.= " OR u.admin = 1)";
1846
+        }
1847
+        else
1848
+            $sql.= " WHERE entity in (0, ".$conf->entity.")";
1849
+
1850
+        $sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
1851
+
1852
+        $resql = $this->db->query($sql);
1853
+        if ($resql)
1854
+        {
1855
+            $num = $this->db->num_rows($resql);
1856
+            $i=0;
1857
+            while ($i < $num)
1858
+            {
1859
+                $obj = $this->db->fetch_object($resql);
1860
+
1861
+                if (empty($mode))
1862
+                {
1863
+                    $reparray[$i]['id']=$obj->rowid;
1864
+                    $reparray[$i]['lastname']=$obj->lastname;
1865
+                    $reparray[$i]['firstname']=$obj->firstname;
1866
+                    $reparray[$i]['email']=$obj->email;
1867
+                    $reparray[$i]['statut']=$obj->statut;
1868
+                    $reparray[$i]['entity']=$obj->entity;
1869
+                    $reparray[$i]['login']=$obj->login;
1870
+                    $reparray[$i]['photo']=$obj->photo;
1871
+                }
1872
+                else
1873
+                {
1874
+                    $reparray[]=$obj->rowid;
1875
+                }
1876
+                $i++;
1877
+            }
1878
+            return $reparray;
1879
+        }
1880
+        else {
1881
+            dol_print_error($this->db);
1882
+            return -1;
1883
+        }
1884
+    }
1885 1885
 
1886 1886
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1887
-	/**
1888
-	 * Set the price level
1889
-	 *
1890
-	 * @param 	int		$price_level	Level of price
1891
-	 * @param 	User	$user			Use making change
1892
-	 * @return	int						<0 if KO, >0 if OK
1893
-	 */
1894
-	function set_price_level($price_level, User $user)
1895
-	{
1887
+    /**
1888
+     * Set the price level
1889
+     *
1890
+     * @param 	int		$price_level	Level of price
1891
+     * @param 	User	$user			Use making change
1892
+     * @return	int						<0 if KO, >0 if OK
1893
+     */
1894
+    function set_price_level($price_level, User $user)
1895
+    {
1896 1896
         // phpcs:enable
1897
-		if ($this->id)
1898
-		{
1899
-			$now=dol_now();
1900
-
1901
-			$sql  = "UPDATE ".MAIN_DB_PREFIX."societe";
1902
-			$sql .= " SET price_level = '".$this->db->escape($price_level)."'";
1903
-			$sql .= " WHERE rowid = " . $this->id;
1904
-
1905
-			if (! $this->db->query($sql))
1906
-			{
1907
-				dol_print_error($this->db);
1908
-				return -1;
1909
-			}
1910
-
1911
-			$sql  = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
1912
-			$sql .= " (datec, fk_soc, price_level, fk_user_author)";
1913
-			$sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")";
1914
-
1915
-			if (! $this->db->query($sql))
1916
-			{
1917
-				dol_print_error($this->db);
1918
-				return -1;
1919
-			}
1920
-			return 1;
1921
-		}
1922
-		return -1;
1923
-	}
1897
+        if ($this->id)
1898
+        {
1899
+            $now=dol_now();
1900
+
1901
+            $sql  = "UPDATE ".MAIN_DB_PREFIX."societe";
1902
+            $sql .= " SET price_level = '".$this->db->escape($price_level)."'";
1903
+            $sql .= " WHERE rowid = " . $this->id;
1904
+
1905
+            if (! $this->db->query($sql))
1906
+            {
1907
+                dol_print_error($this->db);
1908
+                return -1;
1909
+            }
1910
+
1911
+            $sql  = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
1912
+            $sql .= " (datec, fk_soc, price_level, fk_user_author)";
1913
+            $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")";
1914
+
1915
+            if (! $this->db->query($sql))
1916
+            {
1917
+                dol_print_error($this->db);
1918
+                return -1;
1919
+            }
1920
+            return 1;
1921
+        }
1922
+        return -1;
1923
+    }
1924 1924
 
1925 1925
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1926
-	/**
1927
-	 *	Add link to sales representative
1928
-	 *
1929
-	 *	@param	User	$user		Object user
1930
-	 *	@param	int		$commid		Id of user
1931
-	 *	@return	void
1932
-	 */
1933
-	function add_commercial(User $user, $commid)
1934
-	{
1926
+    /**
1927
+     *	Add link to sales representative
1928
+     *
1929
+     *	@param	User	$user		Object user
1930
+     *	@param	int		$commid		Id of user
1931
+     *	@return	void
1932
+     */
1933
+    function add_commercial(User $user, $commid)
1934
+    {
1935 1935
         // phpcs:enable
1936
-		$error=0;
1936
+        $error=0;
1937 1937
 
1938 1938
 
1939
-		if ($this->id > 0 && $commid > 0)
1940
-		{
1941
-			$sql = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux";
1942
-			$sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1939
+        if ($this->id > 0 && $commid > 0)
1940
+        {
1941
+            $sql = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux";
1942
+            $sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1943 1943
 
1944
-			$this->db->query($sql);
1944
+            $this->db->query($sql);
1945 1945
 
1946
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
1947
-			$sql.= " ( fk_soc, fk_user )";
1948
-			$sql.= " VALUES (".$this->id.",".$commid.")";
1946
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
1947
+            $sql.= " ( fk_soc, fk_user )";
1948
+            $sql.= " VALUES (".$this->id.",".$commid.")";
1949 1949
 
1950
-			if (! $this->db->query($sql) )
1951
-			{
1952
-				dol_syslog(get_class($this)."::add_commercial Erreur");
1953
-			}
1954
-			else {
1955
-				$this->context=array('commercial_modified'=>$commid);
1950
+            if (! $this->db->query($sql) )
1951
+            {
1952
+                dol_syslog(get_class($this)."::add_commercial Erreur");
1953
+            }
1954
+            else {
1955
+                $this->context=array('commercial_modified'=>$commid);
1956 1956
 
1957
-				$result=$this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE',$user);
1957
+                $result=$this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE',$user);
1958 1958
                 if ($result < 0) $error++;
1959
-			}
1960
-		}
1961
-	}
1959
+            }
1960
+        }
1961
+    }
1962 1962
 
1963 1963
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1964
-	/**
1965
-	 *	Add link to sales representative
1966
-	 *
1967
-	 *	@param	User	$user		Object user
1968
-	 *	@param	int		$commid		Id of user
1969
-	 *	@return	void
1970
-	 */
1971
-	function del_commercial(User $user, $commid)
1972
-	{
1964
+    /**
1965
+     *	Add link to sales representative
1966
+     *
1967
+     *	@param	User	$user		Object user
1968
+     *	@param	int		$commid		Id of user
1969
+     *	@return	void
1970
+     */
1971
+    function del_commercial(User $user, $commid)
1972
+    {
1973 1973
         // phpcs:enable
1974
-		$error=0;
1975
-		$this->context=array('commercial_modified'=>$commid);
1974
+        $error=0;
1975
+        $this->context=array('commercial_modified'=>$commid);
1976 1976
 
1977
-		$result=$this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE',$user);
1977
+        $result=$this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE',$user);
1978 1978
         if ($result < 0) $error++;
1979 1979
 
1980
-		if ($this->id > 0 && $commid > 0)
1981
-		{
1982
-			$sql  = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux ";
1983
-			$sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1984
-
1985
-			if (! $this->db->query($sql) )
1986
-			{
1987
-				dol_syslog(get_class($this)."::del_commercial Erreur");
1988
-			}
1989
-		}
1990
-	}
1991
-
1992
-
1993
-	/**
1994
-	 *    	Return a link on thirdparty (with picto)
1995
-	 *
1996
-	 *		@param	int		$withpicto		          Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
1997
-	 *		@param	string	$option			          Target of link ('', 'customer', 'prospect', 'supplier', 'project')
1998
-	 *		@param	int		$maxlen			          Max length of name
1999
-	 *      @param	int  	$notooltip		          1=Disable tooltip
2000
-	 *      @param  int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
2001
-	 *		@return	string					          String with URL
2002
-	 */
2003
-	function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1)
2004
-	{
2005
-		global $conf, $langs, $hookmanager;
2006
-
2007
-		if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
2008
-
2009
-		$name=$this->name?$this->name:$this->nom;
2010
-
2011
-		if(!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)){
2012
-
2013
-             if(empty($option) && $this->client > 0) $option = 'customer';
2014
-             if(empty($option) && $this->fournisseur > 0) $option = 'supplier';
2015
-         }
2016
-
2017
-
2018
-		if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
2019
-		{
2020
-			$code = '';
2021
-			if (($this->client) && (! empty ( $this->code_client ))
2022
-				&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
2023
-				|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
2024
-				)
2025
-			)
2026
-			{
2027
-				$code = $this->code_client . ' - ';
2028
-			}
2029
-
2030
-			if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))
2031
-				&& ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
2032
-				|| $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
2033
-				)
2034
-			)
2035
-			{
2036
-				$code .= $this->code_fournisseur . ' - ';
2037
-			}
2038
-
2039
-			if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1)
2040
-			{
2041
-				$name =$code.' '.$name;
2042
-			}
2043
-			else
2044
-			{
2045
-				$name =$code;
2046
-			}
2047
-		}
2048
-
2049
-		if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
2050
-
2051
-		$result=''; $label='';
2052
-		$linkstart=''; $linkend='';
2053
-
2054
-		if (! empty($this->logo) && class_exists('Form'))
2055
-		{
2056
-			$label.= '<div class="photointooltip">';
2057
-			$label.= Form::showphoto('societe', $this, 0, 40, 0, 'photowithmargin', 'mini', 0);	// Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
2058
-			$label.= '</div><div style="clear: both;"></div>';
2059
-		}
2060
-
2061
-		$label.= '<div class="centpercent">';
2062
-
2063
-		if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
2064
-		{
2065
-		   $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
2066
-		   $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2067
-		}
2068
-		elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
2069
-		{
2070
-			$label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
2071
-			$linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2072
-		}
2073
-		elseif ($option == 'supplier')
2074
-		{
2075
-			$label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
2076
-			$linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2077
-		}
2078
-		elseif ($option == 'agenda')
2079
-		{
2080
-			$label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
2081
-			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2082
-		}
2083
-		elseif ($option == 'project')
2084
-		{
2085
-			$label.= '<u>' . $langs->trans("ShowProject") . '</u>';
2086
-			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2087
-		}
2088
-		elseif ($option == 'margin')
2089
-		{
2090
-			$label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
2091
-			$linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2092
-		}
2093
-		elseif ($option == 'contact')
2094
-		{
2095
-			$label.= '<u>' . $langs->trans("ShowContacts") . '</u>';
2096
-			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2097
-		}
2098
-		elseif ($option == 'ban')
2099
-		{
2100
-			$label.= '<u>' . $langs->trans("ShowBan") . '</u>';
2101
-			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2102
-		}
2103
-
2104
-		// By default
2105
-		if (empty($linkstart))
2106
-		{
2107
-			$label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
2108
-			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2109
-		}
2110
-
2111
-		if (! empty($this->name))
2112
-		{
2113
-			$label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
2114
-			if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
2115
-			$label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email;
2116
-		}
2117
-		if (! empty($this->country_code))
2118
-			$label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
2119
-		if (! empty($this->tva_intra) || (! empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false))
2120
-			$label.= '<br><b>' . $langs->trans('VATIntra') . ':</b> '. $this->tva_intra;
2121
-		if (! empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP))
2122
-		{
2123
-			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false) $label.= '<br><b>' . $langs->trans('ProfId1'.$this->country_code) . ':</b> '. $this->idprof1;
2124
-			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false) $label.= '<br><b>' . $langs->trans('ProfId2'.$this->country_code) . ':</b> '. $this->idprof2;
2125
-			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false) $label.= '<br><b>' . $langs->trans('ProfId3'.$this->country_code) . ':</b> '. $this->idprof3;
2126
-			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false) $label.= '<br><b>' . $langs->trans('ProfId4'.$this->country_code) . ':</b> '. $this->idprof4;
2127
-			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false) $label.= '<br><b>' . $langs->trans('ProfId5'.$this->country_code) . ':</b> '. $this->idprof5;
2128
-			if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false) $label.= '<br><b>' . $langs->trans('ProfId6'.$this->country_code) . ':</b> '. $this->idprof6;
2129
-		}
2130
-		if (! empty($this->code_client) && ($this->client == 1 || $this->client == 3))
2131
-			$label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
2132
-		if (! empty($this->code_fournisseur) && $this->fournisseur)
2133
-			$label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
2134
-		if (! empty($conf->accounting->enabled) && ($this->client == 1 || $this->client == 3))
2135
-			$label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. ($this->code_compta ? $this->code_compta : $this->code_compta_client);
2136
-		if (! empty($conf->accounting->enabled) && $this->fournisseur)
2137
-			$label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
2138
-
2139
-		$label.= '</div>';
2140
-
2141
-		// Add type of canvas
2142
-		$linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'');
2143
-		// Add param to save lastsearch_values or not
2144
-		$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
2145
-		if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
2146
-		if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1';
2147
-		$linkstart.='"';
2148
-
2149
-		$linkclose='';
2150
-		if (empty($notooltip))
2151
-		{
2152
-			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
2153
-			{
2154
-				$label=$langs->trans("ShowCompany");
2155
-				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
2156
-			}
2157
-			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
2158
-			$linkclose.=' class="classfortooltip refurl"';
2159
-
2160
-		 	/*
1980
+        if ($this->id > 0 && $commid > 0)
1981
+        {
1982
+            $sql  = "DELETE FROM  ".MAIN_DB_PREFIX."societe_commerciaux ";
1983
+            $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
1984
+
1985
+            if (! $this->db->query($sql) )
1986
+            {
1987
+                dol_syslog(get_class($this)."::del_commercial Erreur");
1988
+            }
1989
+        }
1990
+    }
1991
+
1992
+
1993
+    /**
1994
+     *    	Return a link on thirdparty (with picto)
1995
+     *
1996
+     *		@param	int		$withpicto		          Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
1997
+     *		@param	string	$option			          Target of link ('', 'customer', 'prospect', 'supplier', 'project')
1998
+     *		@param	int		$maxlen			          Max length of name
1999
+     *      @param	int  	$notooltip		          1=Disable tooltip
2000
+     *      @param  int     $save_lastsearch_value    -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
2001
+     *		@return	string					          String with URL
2002
+     */
2003
+    function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1)
2004
+    {
2005
+        global $conf, $langs, $hookmanager;
2006
+
2007
+        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
2008
+
2009
+        $name=$this->name?$this->name:$this->nom;
2010
+
2011
+        if(!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)){
2012
+
2013
+                if(empty($option) && $this->client > 0) $option = 'customer';
2014
+                if(empty($option) && $this->fournisseur > 0) $option = 'supplier';
2015
+            }
2016
+
2017
+
2018
+        if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
2019
+        {
2020
+            $code = '';
2021
+            if (($this->client) && (! empty ( $this->code_client ))
2022
+                && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
2023
+                || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
2024
+                )
2025
+            )
2026
+            {
2027
+                $code = $this->code_client . ' - ';
2028
+            }
2029
+
2030
+            if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))
2031
+                && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
2032
+                || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
2033
+                )
2034
+            )
2035
+            {
2036
+                $code .= $this->code_fournisseur . ' - ';
2037
+            }
2038
+
2039
+            if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1)
2040
+            {
2041
+                $name =$code.' '.$name;
2042
+            }
2043
+            else
2044
+            {
2045
+                $name =$code;
2046
+            }
2047
+        }
2048
+
2049
+        if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
2050
+
2051
+        $result=''; $label='';
2052
+        $linkstart=''; $linkend='';
2053
+
2054
+        if (! empty($this->logo) && class_exists('Form'))
2055
+        {
2056
+            $label.= '<div class="photointooltip">';
2057
+            $label.= Form::showphoto('societe', $this, 0, 40, 0, 'photowithmargin', 'mini', 0);	// Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
2058
+            $label.= '</div><div style="clear: both;"></div>';
2059
+        }
2060
+
2061
+        $label.= '<div class="centpercent">';
2062
+
2063
+        if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
2064
+        {
2065
+            $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
2066
+            $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2067
+        }
2068
+        elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
2069
+        {
2070
+            $label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
2071
+            $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
2072
+        }
2073
+        elseif ($option == 'supplier')
2074
+        {
2075
+            $label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
2076
+            $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
2077
+        }
2078
+        elseif ($option == 'agenda')
2079
+        {
2080
+            $label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
2081
+            $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
2082
+        }
2083
+        elseif ($option == 'project')
2084
+        {
2085
+            $label.= '<u>' . $langs->trans("ShowProject") . '</u>';
2086
+            $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
2087
+        }
2088
+        elseif ($option == 'margin')
2089
+        {
2090
+            $label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
2091
+            $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
2092
+        }
2093
+        elseif ($option == 'contact')
2094
+        {
2095
+            $label.= '<u>' . $langs->trans("ShowContacts") . '</u>';
2096
+            $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
2097
+        }
2098
+        elseif ($option == 'ban')
2099
+        {
2100
+            $label.= '<u>' . $langs->trans("ShowBan") . '</u>';
2101
+            $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
2102
+        }
2103
+
2104
+        // By default
2105
+        if (empty($linkstart))
2106
+        {
2107
+            $label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
2108
+            $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
2109
+        }
2110
+
2111
+        if (! empty($this->name))
2112
+        {
2113
+            $label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
2114
+            if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
2115
+            $label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email;
2116
+        }
2117
+        if (! empty($this->country_code))
2118
+            $label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
2119
+        if (! empty($this->tva_intra) || (! empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false))
2120
+            $label.= '<br><b>' . $langs->trans('VATIntra') . ':</b> '. $this->tva_intra;
2121
+        if (! empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP))
2122
+        {
2123
+            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false) $label.= '<br><b>' . $langs->trans('ProfId1'.$this->country_code) . ':</b> '. $this->idprof1;
2124
+            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false) $label.= '<br><b>' . $langs->trans('ProfId2'.$this->country_code) . ':</b> '. $this->idprof2;
2125
+            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false) $label.= '<br><b>' . $langs->trans('ProfId3'.$this->country_code) . ':</b> '. $this->idprof3;
2126
+            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false) $label.= '<br><b>' . $langs->trans('ProfId4'.$this->country_code) . ':</b> '. $this->idprof4;
2127
+            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false) $label.= '<br><b>' . $langs->trans('ProfId5'.$this->country_code) . ':</b> '. $this->idprof5;
2128
+            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false) $label.= '<br><b>' . $langs->trans('ProfId6'.$this->country_code) . ':</b> '. $this->idprof6;
2129
+        }
2130
+        if (! empty($this->code_client) && ($this->client == 1 || $this->client == 3))
2131
+            $label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
2132
+        if (! empty($this->code_fournisseur) && $this->fournisseur)
2133
+            $label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
2134
+        if (! empty($conf->accounting->enabled) && ($this->client == 1 || $this->client == 3))
2135
+            $label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. ($this->code_compta ? $this->code_compta : $this->code_compta_client);
2136
+        if (! empty($conf->accounting->enabled) && $this->fournisseur)
2137
+            $label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
2138
+
2139
+        $label.= '</div>';
2140
+
2141
+        // Add type of canvas
2142
+        $linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'');
2143
+        // Add param to save lastsearch_values or not
2144
+        $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
2145
+        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
2146
+        if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1';
2147
+        $linkstart.='"';
2148
+
2149
+        $linkclose='';
2150
+        if (empty($notooltip))
2151
+        {
2152
+            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
2153
+            {
2154
+                $label=$langs->trans("ShowCompany");
2155
+                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
2156
+            }
2157
+            $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
2158
+            $linkclose.=' class="classfortooltip refurl"';
2159
+
2160
+                /*
2161 2161
 			$hookmanager->initHooks(array('thirdpartydao'));
2162 2162
 			$parameters=array('id'=>$this->id);
2163 2163
 			$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
2164 2164
 			if ($reshook > 0) $linkclose = $hookmanager->resPrint;
2165 2165
 			*/
2166
-		}
2167
-		$linkstart.=$linkclose.'>';
2168
-		$linkend='</a>';
2169
-
2170
-		global $user;
2171
-		if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id)
2172
-		{
2173
-			$linkstart='';
2174
-			$linkend='';
2175
-		}
2176
-
2177
-		$result.=$linkstart;
2178
-		if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1);
2179
-		if ($withpicto != 2) $result.=($maxlen?dol_trunc($name,$maxlen):$name);
2180
-		$result.=$linkend;
2181
-
2182
-		global $action;
2183
-		$hookmanager->initHooks(array('thirdpartydao'));
2184
-		$parameters=array('id'=>$this->id, 'getnomurl'=>$result);
2185
-		$reshook=$hookmanager->executeHooks('getNomUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
2186
-		if ($reshook > 0) $result = $hookmanager->resPrint;
2187
-		else $result .= $hookmanager->resPrint;
2188
-
2189
-		return $result;
2190
-	}
2191
-
2192
-	/**
2193
-	 *    Return label of status (activity, closed)
2194
-	 *
2195
-	 *    @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2196
-	 *    @return   string        		Libelle
2197
-	 */
2198
-	function getLibStatut($mode=0)
2199
-	{
2200
-		return $this->LibStatut($this->status,$mode);
2201
-	}
2166
+        }
2167
+        $linkstart.=$linkclose.'>';
2168
+        $linkend='</a>';
2169
+
2170
+        global $user;
2171
+        if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id)
2172
+        {
2173
+            $linkstart='';
2174
+            $linkend='';
2175
+        }
2176
+
2177
+        $result.=$linkstart;
2178
+        if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1);
2179
+        if ($withpicto != 2) $result.=($maxlen?dol_trunc($name,$maxlen):$name);
2180
+        $result.=$linkend;
2181
+
2182
+        global $action;
2183
+        $hookmanager->initHooks(array('thirdpartydao'));
2184
+        $parameters=array('id'=>$this->id, 'getnomurl'=>$result);
2185
+        $reshook=$hookmanager->executeHooks('getNomUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
2186
+        if ($reshook > 0) $result = $hookmanager->resPrint;
2187
+        else $result .= $hookmanager->resPrint;
2188
+
2189
+        return $result;
2190
+    }
2191
+
2192
+    /**
2193
+     *    Return label of status (activity, closed)
2194
+     *
2195
+     *    @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2196
+     *    @return   string        		Libelle
2197
+     */
2198
+    function getLibStatut($mode=0)
2199
+    {
2200
+        return $this->LibStatut($this->status,$mode);
2201
+    }
2202 2202
 
2203 2203
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2204
-	/**
2205
-	 *  Renvoi le libelle d'un statut donne
2206
-	 *
2207
-	 *  @param	int		$statut         Id statut
2208
-	 *  @param	int		$mode           0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
2209
-	 *  @return	string          		Libelle du statut
2210
-	 */
2211
-	function LibStatut($statut,$mode=0)
2212
-	{
2204
+    /**
2205
+     *  Renvoi le libelle d'un statut donne
2206
+     *
2207
+     *  @param	int		$statut         Id statut
2208
+     *  @param	int		$mode           0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
2209
+     *  @return	string          		Libelle du statut
2210
+     */
2211
+    function LibStatut($statut,$mode=0)
2212
+    {
2213 2213
         // phpcs:enable
2214
-		global $langs;
2215
-		$langs->load('companies');
2216
-
2217
-		if ($mode == 0)
2218
-		{
2219
-			if ($statut==0) return $langs->trans("ActivityCeased");
2220
-			elseif ($statut==1) return $langs->trans("InActivity");
2221
-		}
2222
-		elseif ($mode == 1)
2223
-		{
2224
-			if ($statut==0) return $langs->trans("ActivityCeased");
2225
-			elseif ($statut==1) return $langs->trans("InActivity");
2226
-		}
2227
-		elseif ($mode == 2)
2228
-		{
2229
-			if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2230
-			elseif ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2231
-		}
2232
-		elseif ($mode == 3)
2233
-		{
2234
-			if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2235
-			elseif ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2236
-		}
2237
-		elseif ($mode == 4)
2238
-		{
2239
-			if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2240
-			elseif ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2241
-		}
2242
-		elseif ($mode == 5)
2243
-		{
2244
-			if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans("ActivityCeased").'</span> '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2245
-			elseif ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans("InActivity").'</span> '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2246
-		}
2247
-		elseif ($mode == 6)
2248
-		{
2249
-			if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans("ActivityCeased").'</span> '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2250
-			elseif ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans("InActivity").'</span> '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2251
-		}
2252
-	}
2214
+        global $langs;
2215
+        $langs->load('companies');
2216
+
2217
+        if ($mode == 0)
2218
+        {
2219
+            if ($statut==0) return $langs->trans("ActivityCeased");
2220
+            elseif ($statut==1) return $langs->trans("InActivity");
2221
+        }
2222
+        elseif ($mode == 1)
2223
+        {
2224
+            if ($statut==0) return $langs->trans("ActivityCeased");
2225
+            elseif ($statut==1) return $langs->trans("InActivity");
2226
+        }
2227
+        elseif ($mode == 2)
2228
+        {
2229
+            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2230
+            elseif ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2231
+        }
2232
+        elseif ($mode == 3)
2233
+        {
2234
+            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2235
+            elseif ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2236
+        }
2237
+        elseif ($mode == 4)
2238
+        {
2239
+            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2240
+            elseif ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2241
+        }
2242
+        elseif ($mode == 5)
2243
+        {
2244
+            if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans("ActivityCeased").'</span> '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2245
+            elseif ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans("InActivity").'</span> '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2246
+        }
2247
+        elseif ($mode == 6)
2248
+        {
2249
+            if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans("ActivityCeased").'</span> '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2250
+            elseif ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans("InActivity").'</span> '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2251
+        }
2252
+    }
2253 2253
 
2254 2254
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2255
-	/**
2256
-	 *    Return list of contacts emails existing for third party
2257
-	 *
2258
-	 *	  @param	  int		$addthirdparty		1=Add also a record for thirdparty email
2259
-	 *    @return     array       					Array of contacts emails
2260
-	 */
2261
-	function thirdparty_and_contact_email_array($addthirdparty=0)
2262
-	{
2255
+    /**
2256
+     *    Return list of contacts emails existing for third party
2257
+     *
2258
+     *	  @param	  int		$addthirdparty		1=Add also a record for thirdparty email
2259
+     *    @return     array       					Array of contacts emails
2260
+     */
2261
+    function thirdparty_and_contact_email_array($addthirdparty=0)
2262
+    {
2263 2263
         // phpcs:enable
2264
-		global $langs;
2265
-
2266
-		$contact_emails = $this->contact_property_array('email',1);
2267
-		if ($this->email && $addthirdparty)
2268
-		{
2269
-			if (empty($this->name)) $this->name=$this->nom;
2270
-			$contact_emails['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->email.">";
2271
-		}
2272
-		//var_dump($contact_emails)
2273
-		return $contact_emails;
2274
-	}
2264
+        global $langs;
2265
+
2266
+        $contact_emails = $this->contact_property_array('email',1);
2267
+        if ($this->email && $addthirdparty)
2268
+        {
2269
+            if (empty($this->name)) $this->name=$this->nom;
2270
+            $contact_emails['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->email.">";
2271
+        }
2272
+        //var_dump($contact_emails)
2273
+        return $contact_emails;
2274
+    }
2275 2275
 
2276 2276
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2277
-	/**
2278
-	 *    Return list of contacts mobile phone existing for third party
2279
-	 *
2280
-	 *    @return     array       Array of contacts emails
2281
-	 */
2282
-	function thirdparty_and_contact_phone_array()
2283
-	{
2277
+    /**
2278
+     *    Return list of contacts mobile phone existing for third party
2279
+     *
2280
+     *    @return     array       Array of contacts emails
2281
+     */
2282
+    function thirdparty_and_contact_phone_array()
2283
+    {
2284 2284
         // phpcs:enable
2285
-		global $langs;
2285
+        global $langs;
2286 2286
 
2287
-		$contact_phone = $this->contact_property_array('mobile');
2287
+        $contact_phone = $this->contact_property_array('mobile');
2288 2288
 
2289
-		if (! empty($this->phone))	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2290
-		{
2291
-			if (empty($this->name)) $this->name=$this->nom;
2292
-			// TODO: Tester si tel non deja present dans tableau contact
2293
-			$contact_phone['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->phone.">";
2294
-		}
2295
-		return $contact_phone;
2296
-	}
2289
+        if (! empty($this->phone))	// If a phone of thirdparty is defined, we add it ot mobile of contacts
2290
+        {
2291
+            if (empty($this->name)) $this->name=$this->nom;
2292
+            // TODO: Tester si tel non deja present dans tableau contact
2293
+            $contact_phone['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->phone.">";
2294
+        }
2295
+        return $contact_phone;
2296
+    }
2297 2297
 
2298 2298
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2299
-	/**
2300
-	 *  Return list of contacts emails or mobile existing for third party
2301
-	 *
2302
-	 *  @param	string	$mode       		'email' or 'mobile'
2303
-	 * 	@param	int		$hidedisabled		1=Hide contact if disabled
2304
-	 *  @return array       				Array of contacts emails or mobile. Example: array(id=>'Name <email>')
2305
-	 */
2306
-	function contact_property_array($mode='email', $hidedisabled=0)
2307
-	{
2299
+    /**
2300
+     *  Return list of contacts emails or mobile existing for third party
2301
+     *
2302
+     *  @param	string	$mode       		'email' or 'mobile'
2303
+     * 	@param	int		$hidedisabled		1=Hide contact if disabled
2304
+     *  @return array       				Array of contacts emails or mobile. Example: array(id=>'Name <email>')
2305
+     */
2306
+    function contact_property_array($mode='email', $hidedisabled=0)
2307
+    {
2308 2308
         // phpcs:enable
2309
-		global $langs;
2310
-
2311
-		$contact_property = array();
2312
-
2313
-
2314
-		$sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
2315
-		$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2316
-		$sql.= " WHERE fk_soc = ".$this->id;
2317
-
2318
-		$resql=$this->db->query($sql);
2319
-		if ($resql)
2320
-		{
2321
-			$nump = $this->db->num_rows($resql);
2322
-			if ($nump)
2323
-			{
2324
-				$sepa="("; $sepb=")";
2325
-				if ($mode == 'email')
2326
-				{
2327
-					//$sepa="&lt;"; $sepb="&gt;";
2328
-					$sepa="<"; $sepb=">";
2329
-				}
2330
-				$i = 0;
2331
-				while ($i < $nump)
2332
-				{
2333
-					$obj = $this->db->fetch_object($resql);
2334
-					if ($mode == 'email') $property=$obj->email;
2335
-					else if ($mode == 'mobile') $property=$obj->phone_mobile;
2336
-					else $property=$obj->$mode;
2337
-
2338
-					// Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2339
-					if ($obj->statut == 1 || empty($hidedisabled))
2340
-					{
2341
-						if (empty($property))
2342
-						{
2343
-							if ($mode == 'email') $property=$langs->transnoentitiesnoconv("NoEMail");
2344
-							else if ($mode == 'mobile') $property=$langs->transnoentitiesnoconv("NoMobilePhone");
2345
-						}
2346
-
2347
-						if (!empty($obj->poste))
2348
-						{
2349
-							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2350
-						}
2351
-						else
2352
-						{
2353
-							$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2354
-						}
2355
-					}
2356
-					$i++;
2357
-				}
2358
-			}
2359
-		}
2360
-		else
2361
-		{
2362
-			dol_print_error($this->db);
2363
-		}
2364
-		return $contact_property;
2365
-	}
2309
+        global $langs;
2310
+
2311
+        $contact_property = array();
2312
+
2313
+
2314
+        $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
2315
+        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2316
+        $sql.= " WHERE fk_soc = ".$this->id;
2317
+
2318
+        $resql=$this->db->query($sql);
2319
+        if ($resql)
2320
+        {
2321
+            $nump = $this->db->num_rows($resql);
2322
+            if ($nump)
2323
+            {
2324
+                $sepa="("; $sepb=")";
2325
+                if ($mode == 'email')
2326
+                {
2327
+                    //$sepa="&lt;"; $sepb="&gt;";
2328
+                    $sepa="<"; $sepb=">";
2329
+                }
2330
+                $i = 0;
2331
+                while ($i < $nump)
2332
+                {
2333
+                    $obj = $this->db->fetch_object($resql);
2334
+                    if ($mode == 'email') $property=$obj->email;
2335
+                    else if ($mode == 'mobile') $property=$obj->phone_mobile;
2336
+                    else $property=$obj->$mode;
2337
+
2338
+                    // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
2339
+                    if ($obj->statut == 1 || empty($hidedisabled))
2340
+                    {
2341
+                        if (empty($property))
2342
+                        {
2343
+                            if ($mode == 'email') $property=$langs->transnoentitiesnoconv("NoEMail");
2344
+                            else if ($mode == 'mobile') $property=$langs->transnoentitiesnoconv("NoMobilePhone");
2345
+                        }
2346
+
2347
+                        if (!empty($obj->poste))
2348
+                        {
2349
+                            $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2350
+                        }
2351
+                        else
2352
+                        {
2353
+                            $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
2354
+                        }
2355
+                    }
2356
+                    $i++;
2357
+                }
2358
+            }
2359
+        }
2360
+        else
2361
+        {
2362
+            dol_print_error($this->db);
2363
+        }
2364
+        return $contact_property;
2365
+    }
2366 2366
 
2367 2367
 
2368 2368
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2369
-	/**
2370
-	 *    Renvoie la liste des contacts de cette societe
2371
-	 *
2372
-	 *    @return     array      tableau des contacts
2373
-	 */
2374
-	function contact_array()
2375
-	{
2369
+    /**
2370
+     *    Renvoie la liste des contacts de cette societe
2371
+     *
2372
+     *    @return     array      tableau des contacts
2373
+     */
2374
+    function contact_array()
2375
+    {
2376 2376
         // phpcs:enable
2377
-		$contacts = array();
2378
-
2379
-		$sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2380
-		$resql=$this->db->query($sql);
2381
-		if ($resql)
2382
-		{
2383
-			$nump = $this->db->num_rows($resql);
2384
-			if ($nump)
2385
-			{
2386
-				$i = 0;
2387
-				while ($i < $nump)
2388
-				{
2389
-					$obj = $this->db->fetch_object($resql);
2390
-					$contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname);
2391
-					$i++;
2392
-				}
2393
-			}
2394
-		}
2395
-		else
2396
-		{
2397
-			dol_print_error($this->db);
2398
-		}
2399
-		return $contacts;
2400
-	}
2377
+        $contacts = array();
2378
+
2379
+        $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2380
+        $resql=$this->db->query($sql);
2381
+        if ($resql)
2382
+        {
2383
+            $nump = $this->db->num_rows($resql);
2384
+            if ($nump)
2385
+            {
2386
+                $i = 0;
2387
+                while ($i < $nump)
2388
+                {
2389
+                    $obj = $this->db->fetch_object($resql);
2390
+                    $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname);
2391
+                    $i++;
2392
+                }
2393
+            }
2394
+        }
2395
+        else
2396
+        {
2397
+            dol_print_error($this->db);
2398
+        }
2399
+        return $contacts;
2400
+    }
2401 2401
 
2402 2402
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2403
-	/**
2404
-	 *    Renvoie la liste des contacts de cette societe
2405
-	 *
2406
-	 *    @return    array    $contacts    tableau des contacts
2407
-	 */
2408
-	function contact_array_objects()
2409
-	{
2403
+    /**
2404
+     *    Renvoie la liste des contacts de cette societe
2405
+     *
2406
+     *    @return    array    $contacts    tableau des contacts
2407
+     */
2408
+    function contact_array_objects()
2409
+    {
2410 2410
         // phpcs:enable
2411
-		require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2412
-		$contacts = array();
2413
-
2414
-		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2415
-		$resql=$this->db->query($sql);
2416
-		if ($resql)
2417
-		{
2418
-			$nump = $this->db->num_rows($resql);
2419
-			if ($nump)
2420
-			{
2421
-				$i = 0;
2422
-				while ($i < $nump)
2423
-				{
2424
-					$obj = $this->db->fetch_object($resql);
2425
-					$contact = new Contact($this->db);
2426
-					$contact->fetch($obj->rowid);
2427
-					$contacts[] = $contact;
2428
-					$i++;
2429
-				}
2430
-			}
2431
-		}
2432
-		else
2433
-		{
2434
-			dol_print_error($this->db);
2435
-		}
2436
-		return $contacts;
2437
-	}
2411
+        require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2412
+        $contacts = array();
2413
+
2414
+        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
2415
+        $resql=$this->db->query($sql);
2416
+        if ($resql)
2417
+        {
2418
+            $nump = $this->db->num_rows($resql);
2419
+            if ($nump)
2420
+            {
2421
+                $i = 0;
2422
+                while ($i < $nump)
2423
+                {
2424
+                    $obj = $this->db->fetch_object($resql);
2425
+                    $contact = new Contact($this->db);
2426
+                    $contact->fetch($obj->rowid);
2427
+                    $contacts[] = $contact;
2428
+                    $i++;
2429
+                }
2430
+            }
2431
+        }
2432
+        else
2433
+        {
2434
+            dol_print_error($this->db);
2435
+        }
2436
+        return $contacts;
2437
+    }
2438 2438
 
2439 2439
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2440
-	/**
2441
-	 *  Return property of contact from its id
2442
-	 *
2443
-	 *  @param	int		$rowid      id of contact
2444
-	 *  @param  string	$mode       'email' or 'mobile'
2445
-	 *  @return string  			Email of contact with format: "Full name <email>"
2446
-	 */
2447
-	function contact_get_property($rowid,$mode)
2448
-	{
2440
+    /**
2441
+     *  Return property of contact from its id
2442
+     *
2443
+     *  @param	int		$rowid      id of contact
2444
+     *  @param  string	$mode       'email' or 'mobile'
2445
+     *  @return string  			Email of contact with format: "Full name <email>"
2446
+     */
2447
+    function contact_get_property($rowid,$mode)
2448
+    {
2449 2449
         // phpcs:enable
2450
-		$contact_property='';
2450
+        $contact_property='';
2451 2451
 
2452
-		if (empty($rowid)) return '';
2452
+        if (empty($rowid)) return '';
2453 2453
 
2454
-		$sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
2455
-		$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2456
-		$sql.= " WHERE rowid = '".$rowid."'";
2454
+        $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
2455
+        $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
2456
+        $sql.= " WHERE rowid = '".$rowid."'";
2457 2457
 
2458
-		$resql=$this->db->query($sql);
2459
-		if ($resql)
2460
-		{
2461
-			$nump = $this->db->num_rows($resql);
2458
+        $resql=$this->db->query($sql);
2459
+        if ($resql)
2460
+        {
2461
+            $nump = $this->db->num_rows($resql);
2462 2462
 
2463
-			if ($nump)
2464
-			{
2465
-				$obj = $this->db->fetch_object($resql);
2463
+            if ($nump)
2464
+            {
2465
+                $obj = $this->db->fetch_object($resql);
2466 2466
 
2467
-				if ($mode == 'email') $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
2468
-				else if ($mode == 'mobile') $contact_property = $obj->phone_mobile;
2469
-			}
2470
-			return $contact_property;
2471
-		}
2472
-		else
2473
-		{
2474
-			dol_print_error($this->db);
2475
-		}
2476
-	}
2467
+                if ($mode == 'email') $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
2468
+                else if ($mode == 'mobile') $contact_property = $obj->phone_mobile;
2469
+            }
2470
+            return $contact_property;
2471
+        }
2472
+        else
2473
+        {
2474
+            dol_print_error($this->db);
2475
+        }
2476
+    }
2477 2477
 
2478 2478
 
2479 2479
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2480
-	/**
2481
-	 *  Return bank number property of thirdparty (label or rum)
2482
-	 *
2483
-	 *	@param	string	$mode	'label' or 'rum' or 'format'
2484
-	 *  @return	string			Bank number
2485
-	 */
2486
-	function display_rib($mode='label')
2487
-	{
2480
+    /**
2481
+     *  Return bank number property of thirdparty (label or rum)
2482
+     *
2483
+     *	@param	string	$mode	'label' or 'rum' or 'format'
2484
+     *  @return	string			Bank number
2485
+     */
2486
+    function display_rib($mode='label')
2487
+    {
2488 2488
         // phpcs:enable
2489
-		require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2490
-
2491
-		$bac = new CompanyBankAccount($this->db);
2492
-		$bac->fetch(0,$this->id);
2493
-
2494
-		if ($mode == 'label')
2495
-		{
2496
-			return $bac->getRibLabel(true);
2497
-		}
2498
-		elseif ($mode == 'rum')
2499
-		{
2500
-			if (empty($bac->rum))
2501
-			{
2502
-				require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
2503
-				$prelevement = new BonPrelevement($this->db);
2504
-				$bac->fetch_thirdparty();
2505
-				$bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
2506
-			}
2507
-			return $bac->rum;
2508
-		}
2509
-		elseif ($mode == 'format')
2510
-		{
2511
-			return $bac->frstrecur;
2512
-		}
2513
-
2514
-		return 'BadParameterToFunctionDisplayRib';
2515
-	}
2489
+        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2490
+
2491
+        $bac = new CompanyBankAccount($this->db);
2492
+        $bac->fetch(0,$this->id);
2493
+
2494
+        if ($mode == 'label')
2495
+        {
2496
+            return $bac->getRibLabel(true);
2497
+        }
2498
+        elseif ($mode == 'rum')
2499
+        {
2500
+            if (empty($bac->rum))
2501
+            {
2502
+                require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
2503
+                $prelevement = new BonPrelevement($this->db);
2504
+                $bac->fetch_thirdparty();
2505
+                $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
2506
+            }
2507
+            return $bac->rum;
2508
+        }
2509
+        elseif ($mode == 'format')
2510
+        {
2511
+            return $bac->frstrecur;
2512
+        }
2513
+
2514
+        return 'BadParameterToFunctionDisplayRib';
2515
+    }
2516 2516
 
2517 2517
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2518
-	/**
2519
-	 * Return Array of RIB
2520
-	 *
2521
-	 * @return     array|int        0 if KO, Array of CompanyBanckAccount if OK
2522
-	 */
2523
-	function get_all_rib()
2524
-	{
2518
+    /**
2519
+     * Return Array of RIB
2520
+     *
2521
+     * @return     array|int        0 if KO, Array of CompanyBanckAccount if OK
2522
+     */
2523
+    function get_all_rib()
2524
+    {
2525 2525
         // phpcs:enable
2526
-		require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2527
-		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".$this->id;
2528
-		$result = $this->db->query($sql);
2529
-		if (!$result) {
2530
-			$this->error++;
2531
-			$this->errors[] = $this->db->lasterror;
2532
-			return 0;
2533
-		} else {
2534
-			$num_rows = $this->db->num_rows($result);
2535
-			$rib_array = array();
2536
-			if ($num_rows) {
2537
-				while ($obj = $this->db->fetch_object($result)) {
2538
-					$rib = new CompanyBankAccount($this->db);
2539
-					$rib->fetch($obj->rowid);
2540
-					$rib_array[] = $rib;
2541
-				}
2542
-			}
2543
-			return $rib_array;
2544
-		}
2545
-	}
2526
+        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
2527
+        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".$this->id;
2528
+        $result = $this->db->query($sql);
2529
+        if (!$result) {
2530
+            $this->error++;
2531
+            $this->errors[] = $this->db->lasterror;
2532
+            return 0;
2533
+        } else {
2534
+            $num_rows = $this->db->num_rows($result);
2535
+            $rib_array = array();
2536
+            if ($num_rows) {
2537
+                while ($obj = $this->db->fetch_object($result)) {
2538
+                    $rib = new CompanyBankAccount($this->db);
2539
+                    $rib->fetch($obj->rowid);
2540
+                    $rib_array[] = $rib;
2541
+                }
2542
+            }
2543
+            return $rib_array;
2544
+        }
2545
+    }
2546 2546
 
2547 2547
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2548
-	/**
2549
-	 *  Attribut un code client a partir du module de controle des codes.
2550
-	 *  Return value is stored into this->code_client
2551
-	 *
2552
-	 *	@param	Societe		$objsoc		Object thirdparty
2553
-	 *	@param	int			$type		Should be 0 to say customer
2554
-	 *  @return void
2555
-	 */
2556
-	function get_codeclient($objsoc=0,$type=0)
2557
-	{
2548
+    /**
2549
+     *  Attribut un code client a partir du module de controle des codes.
2550
+     *  Return value is stored into this->code_client
2551
+     *
2552
+     *	@param	Societe		$objsoc		Object thirdparty
2553
+     *	@param	int			$type		Should be 0 to say customer
2554
+     *  @return void
2555
+     */
2556
+    function get_codeclient($objsoc=0,$type=0)
2557
+    {
2558 2558
         // phpcs:enable
2559
-		global $conf;
2560
-		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2561
-		{
2562
-			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2563
-
2564
-			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2565
-			foreach ($dirsociete as $dirroot)
2566
-			{
2567
-				$res=dol_include_once($dirroot.$module.'.php');
2568
-				if ($res) break;
2569
-			}
2570
-			$mod = new $module();
2571
-
2572
-			$this->code_client = $mod->getNextValue($objsoc,$type);
2573
-			$this->prefixCustomerIsRequired = $mod->prefixIsRequired;
2574
-
2575
-			dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
2576
-		}
2577
-	}
2559
+        global $conf;
2560
+        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2561
+        {
2562
+            $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2563
+
2564
+            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2565
+            foreach ($dirsociete as $dirroot)
2566
+            {
2567
+                $res=dol_include_once($dirroot.$module.'.php');
2568
+                if ($res) break;
2569
+            }
2570
+            $mod = new $module();
2571
+
2572
+            $this->code_client = $mod->getNextValue($objsoc,$type);
2573
+            $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
2574
+
2575
+            dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
2576
+        }
2577
+    }
2578 2578
 
2579 2579
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2580
-	/**
2581
-	 *  Attribut un code fournisseur a partir du module de controle des codes.
2582
-	 *  Return value is stored into this->code_fournisseur
2583
-	 *
2584
-	 *	@param	Societe		$objsoc		Object thirdparty
2585
-	 *	@param	int			$type		Should be 1 to say supplier
2586
-	 *  @return void
2587
-	 */
2588
-	function get_codefournisseur($objsoc=0,$type=1)
2589
-	{
2580
+    /**
2581
+     *  Attribut un code fournisseur a partir du module de controle des codes.
2582
+     *  Return value is stored into this->code_fournisseur
2583
+     *
2584
+     *	@param	Societe		$objsoc		Object thirdparty
2585
+     *	@param	int			$type		Should be 1 to say supplier
2586
+     *  @return void
2587
+     */
2588
+    function get_codefournisseur($objsoc=0,$type=1)
2589
+    {
2590 2590
         // phpcs:enable
2591
-		global $conf;
2592
-		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2593
-		{
2594
-			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2591
+        global $conf;
2592
+        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2593
+        {
2594
+            $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2595 2595
 
2596
-			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2597
-			foreach ($dirsociete as $dirroot)
2598
-			{
2599
-				$res=dol_include_once($dirroot.$module.'.php');
2600
-				if ($res) break;
2601
-			}
2602
-			$mod = new $module();
2596
+            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2597
+            foreach ($dirsociete as $dirroot)
2598
+            {
2599
+                $res=dol_include_once($dirroot.$module.'.php');
2600
+                if ($res) break;
2601
+            }
2602
+            $mod = new $module();
2603 2603
 
2604
-			$this->code_fournisseur = $mod->getNextValue($objsoc,$type);
2604
+            $this->code_fournisseur = $mod->getNextValue($objsoc,$type);
2605 2605
 
2606
-			dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2607
-		}
2608
-	}
2606
+            dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2607
+        }
2608
+    }
2609 2609
 
2610 2610
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2611
-	/**
2612
-	 *    Verifie si un code client est modifiable en fonction des parametres
2613
-	 *    du module de controle des codes.
2614
-	 *
2615
-	 *    @return     int		0=No, 1=Yes
2616
-	 */
2617
-	function codeclient_modifiable()
2618
-	{
2611
+    /**
2612
+     *    Verifie si un code client est modifiable en fonction des parametres
2613
+     *    du module de controle des codes.
2614
+     *
2615
+     *    @return     int		0=No, 1=Yes
2616
+     */
2617
+    function codeclient_modifiable()
2618
+    {
2619 2619
         // phpcs:enable
2620
-		global $conf;
2621
-		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2622
-		{
2623
-			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2624
-
2625
-			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2626
-			foreach ($dirsociete as $dirroot)
2627
-			{
2628
-				$res=dol_include_once($dirroot.$module.'.php');
2629
-				if ($res) break;
2630
-			}
2631
-
2632
-			$mod = new $module();
2633
-
2634
-			dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
2635
-			if ($mod->code_modifiable_null && ! $this->code_client) return 1;
2636
-			if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
2637
-			if ($mod->code_modifiable) return 1;	// A mettre en dernier
2638
-			return 0;
2639
-		}
2640
-		else
2641
-		{
2642
-			return 0;
2643
-		}
2644
-	}
2620
+        global $conf;
2621
+        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2622
+        {
2623
+            $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2624
+
2625
+            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2626
+            foreach ($dirsociete as $dirroot)
2627
+            {
2628
+                $res=dol_include_once($dirroot.$module.'.php');
2629
+                if ($res) break;
2630
+            }
2631
+
2632
+            $mod = new $module();
2633
+
2634
+            dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
2635
+            if ($mod->code_modifiable_null && ! $this->code_client) return 1;
2636
+            if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
2637
+            if ($mod->code_modifiable) return 1;	// A mettre en dernier
2638
+            return 0;
2639
+        }
2640
+        else
2641
+        {
2642
+            return 0;
2643
+        }
2644
+    }
2645 2645
 
2646 2646
 
2647 2647
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2648
-	/**
2649
-	 *    Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes
2650
-	 *
2651
-	 *    @return     int		0=No, 1=Yes
2652
-	 */
2653
-	function codefournisseur_modifiable()
2654
-	{
2648
+    /**
2649
+     *    Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes
2650
+     *
2651
+     *    @return     int		0=No, 1=Yes
2652
+     */
2653
+    function codefournisseur_modifiable()
2654
+    {
2655 2655
         // phpcs:enable
2656
-		global $conf;
2657
-		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2658
-		{
2659
-			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2660
-
2661
-			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2662
-			foreach ($dirsociete as $dirroot)
2663
-			{
2664
-				$res=dol_include_once($dirroot.$module.'.php');
2665
-				if ($res) break;
2666
-			}
2667
-
2668
-			$mod = new $module();
2669
-
2670
-			dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
2671
-			if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
2672
-			if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
2673
-			if ($mod->code_modifiable) return 1;	// A mettre en dernier
2674
-			return 0;
2675
-		}
2676
-		else
2677
-		{
2678
-			return 0;
2679
-		}
2680
-	}
2656
+        global $conf;
2657
+        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2658
+        {
2659
+            $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2660
+
2661
+            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2662
+            foreach ($dirsociete as $dirroot)
2663
+            {
2664
+                $res=dol_include_once($dirroot.$module.'.php');
2665
+                if ($res) break;
2666
+            }
2667
+
2668
+            $mod = new $module();
2669
+
2670
+            dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
2671
+            if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
2672
+            if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
2673
+            if ($mod->code_modifiable) return 1;	// A mettre en dernier
2674
+            return 0;
2675
+        }
2676
+        else
2677
+        {
2678
+            return 0;
2679
+        }
2680
+    }
2681 2681
 
2682 2682
 
2683 2683
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2684
-	/**
2685
-	 *  Check customer code
2686
-	 *
2687
-	 *  @return     int				0 if OK
2688
-	 * 								-1 ErrorBadCustomerCodeSyntax
2689
-	 * 								-2 ErrorCustomerCodeRequired
2690
-	 * 								-3 ErrorCustomerCodeAlreadyUsed
2691
-	 * 								-4 ErrorPrefixRequired
2692
-	 */
2693
-	function check_codeclient()
2694
-	{
2684
+    /**
2685
+     *  Check customer code
2686
+     *
2687
+     *  @return     int				0 if OK
2688
+     * 								-1 ErrorBadCustomerCodeSyntax
2689
+     * 								-2 ErrorCustomerCodeRequired
2690
+     * 								-3 ErrorCustomerCodeAlreadyUsed
2691
+     * 								-4 ErrorPrefixRequired
2692
+     */
2693
+    function check_codeclient()
2694
+    {
2695 2695
         // phpcs:enable
2696
-		global $conf;
2697
-		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2698
-		{
2699
-			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2700
-
2701
-			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2702
-			foreach ($dirsociete as $dirroot)
2703
-			{
2704
-				$res=dol_include_once($dirroot.$module.'.php');
2705
-				if ($res) break;
2706
-			}
2707
-
2708
-			$mod = new $module();
2709
-
2710
-		   	dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
2711
-		   	$result = $mod->verif($this->db, $this->code_client, $this, 0);
2712
-			return $result;
2713
-		}
2714
-		else
2715
-		{
2716
-			return 0;
2717
-		}
2718
-	}
2696
+        global $conf;
2697
+        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2698
+        {
2699
+            $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2700
+
2701
+            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2702
+            foreach ($dirsociete as $dirroot)
2703
+            {
2704
+                $res=dol_include_once($dirroot.$module.'.php');
2705
+                if ($res) break;
2706
+            }
2707
+
2708
+            $mod = new $module();
2709
+
2710
+                dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
2711
+                $result = $mod->verif($this->db, $this->code_client, $this, 0);
2712
+            return $result;
2713
+        }
2714
+        else
2715
+        {
2716
+            return 0;
2717
+        }
2718
+    }
2719 2719
 
2720 2720
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2721
-	/**
2722
-	 *    Check supplier code
2723
-	 *
2724
-	 *    @return     int		0 if OK
2725
-	 * 							-1 ErrorBadCustomerCodeSyntax
2726
-	 * 							-2 ErrorCustomerCodeRequired
2727
-	 * 							-3 ErrorCustomerCodeAlreadyUsed
2728
-	 * 							-4 ErrorPrefixRequired
2729
-	 */
2730
-	function check_codefournisseur()
2731
-	{
2721
+    /**
2722
+     *    Check supplier code
2723
+     *
2724
+     *    @return     int		0 if OK
2725
+     * 							-1 ErrorBadCustomerCodeSyntax
2726
+     * 							-2 ErrorCustomerCodeRequired
2727
+     * 							-3 ErrorCustomerCodeAlreadyUsed
2728
+     * 							-4 ErrorPrefixRequired
2729
+     */
2730
+    function check_codefournisseur()
2731
+    {
2732 2732
         // phpcs:enable
2733
-		global $conf;
2734
-		if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2735
-		{
2736
-			$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2737
-
2738
-			$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2739
-			foreach ($dirsociete as $dirroot)
2740
-			{
2741
-				$res=dol_include_once($dirroot.$module.'.php');
2742
-				if ($res) break;
2743
-			}
2744
-
2745
-			$mod = new $module();
2746
-
2747
-			dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2748
-			$result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
2749
-			return $result;
2750
-		}
2751
-		else
2752
-		{
2753
-			return 0;
2754
-		}
2755
-	}
2733
+        global $conf;
2734
+        if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
2735
+        {
2736
+            $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
2737
+
2738
+            $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
2739
+            foreach ($dirsociete as $dirroot)
2740
+            {
2741
+                $res=dol_include_once($dirroot.$module.'.php');
2742
+                if ($res) break;
2743
+            }
2744
+
2745
+            $mod = new $module();
2746
+
2747
+            dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
2748
+            $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
2749
+            return $result;
2750
+        }
2751
+        else
2752
+        {
2753
+            return 0;
2754
+        }
2755
+    }
2756 2756
 
2757 2757
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2758
-	/**
2759
-	 *    	Renvoie un code compta, suivant le module de code compta.
2760
-	 *      Peut etre identique a celui saisit ou genere automatiquement.
2761
-	 *      A ce jour seule la generation automatique est implementee
2762
-	 *
2763
-	 *    	@param	string	$type		Type of thirdparty ('customer' or 'supplier')
2764
-	 *		@return	string				Code compta si ok, 0 si aucun, <0 si ko
2765
-	 */
2766
-	function get_codecompta($type)
2767
-	{
2758
+    /**
2759
+     *    	Renvoie un code compta, suivant le module de code compta.
2760
+     *      Peut etre identique a celui saisit ou genere automatiquement.
2761
+     *      A ce jour seule la generation automatique est implementee
2762
+     *
2763
+     *    	@param	string	$type		Type of thirdparty ('customer' or 'supplier')
2764
+     *		@return	string				Code compta si ok, 0 si aucun, <0 si ko
2765
+     */
2766
+    function get_codecompta($type)
2767
+    {
2768 2768
         // phpcs:enable
2769
-		global $conf;
2770
-
2771
-		if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
2772
-		{
2773
-			$res=false;
2774
-			$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2775
-			foreach ($dirsociete as $dirroot)
2776
-			{
2777
-				$res=dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
2778
-				if ($res) break;
2779
-			}
2780
-
2781
-			if ($res)
2782
-			{
2783
-				$classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
2784
-				$mod = new $classname;
2785
-
2786
-				// Defini code compta dans $mod->code
2787
-				$result = $mod->get_code($this->db, $this, $type);
2788
-
2789
-				if ($type == 'customer') $this->code_compta = $mod->code;
2790
-				else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
2791
-
2792
-				return $result;
2793
-			}
2794
-			else
2795
-			{
2796
-				$this->error = 'ErrorAccountancyCodeNotDefined';
2797
-				return -1;
2798
-			}
2799
-		}
2800
-		else
2801
-		{
2802
-			if ($type == 'customer') $this->code_compta = '';
2803
-			else if ($type == 'supplier') $this->code_compta_fournisseur = '';
2804
-
2805
-			return 0;
2806
-		}
2807
-	}
2769
+        global $conf;
2770
+
2771
+        if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
2772
+        {
2773
+            $res=false;
2774
+            $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2775
+            foreach ($dirsociete as $dirroot)
2776
+            {
2777
+                $res=dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
2778
+                if ($res) break;
2779
+            }
2780
+
2781
+            if ($res)
2782
+            {
2783
+                $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
2784
+                $mod = new $classname;
2785
+
2786
+                // Defini code compta dans $mod->code
2787
+                $result = $mod->get_code($this->db, $this, $type);
2788
+
2789
+                if ($type == 'customer') $this->code_compta = $mod->code;
2790
+                else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
2791
+
2792
+                return $result;
2793
+            }
2794
+            else
2795
+            {
2796
+                $this->error = 'ErrorAccountancyCodeNotDefined';
2797
+                return -1;
2798
+            }
2799
+        }
2800
+        else
2801
+        {
2802
+            if ($type == 'customer') $this->code_compta = '';
2803
+            else if ($type == 'supplier') $this->code_compta_fournisseur = '';
2804
+
2805
+            return 0;
2806
+        }
2807
+    }
2808 2808
 
2809 2809
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2810
-	/**
2811
-	 *    Define parent commany of current company
2812
-	 *
2813
-	 *    @param	int		$id     Id of thirdparty to set or '' to remove
2814
-	 *    @return	int     		<0 if KO, >0 if OK
2815
-	 */
2816
-	function set_parent($id)
2817
-	{
2810
+    /**
2811
+     *    Define parent commany of current company
2812
+     *
2813
+     *    @param	int		$id     Id of thirdparty to set or '' to remove
2814
+     *    @return	int     		<0 if KO, >0 if OK
2815
+     */
2816
+    function set_parent($id)
2817
+    {
2818 2818
         // phpcs:enable
2819
-		if ($this->id)
2820
-		{
2821
-			$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2822
-			$sql.= " SET parent = ".($id > 0 ? $id : "null");
2823
-			$sql.= " WHERE rowid = " . $this->id;
2824
-			dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
2825
-			$resql=$this->db->query($sql);
2826
-			if ($resql)
2827
-			{
2828
-				$this->parent = $id;
2829
-				return 1;
2830
-			}
2831
-			else
2832
-			{
2833
-				return -1;
2834
-			}
2835
-		}
2836
-		else return -1;
2837
-	}
2819
+        if ($this->id)
2820
+        {
2821
+            $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
2822
+            $sql.= " SET parent = ".($id > 0 ? $id : "null");
2823
+            $sql.= " WHERE rowid = " . $this->id;
2824
+            dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
2825
+            $resql=$this->db->query($sql);
2826
+            if ($resql)
2827
+            {
2828
+                $this->parent = $id;
2829
+                return 1;
2830
+            }
2831
+            else
2832
+            {
2833
+                return -1;
2834
+            }
2835
+        }
2836
+        else return -1;
2837
+    }
2838 2838
 
2839 2839
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2840
-	/**
2841
-	 *  Returns if a profid sould be verified
2842
-	 *
2843
-	 *  @param	int		$idprof		1,2,3,4,5,6 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm,5=idprof5,6=idprof6)
2844
-	 *  @return boolean         	true , false
2845
-	 */
2846
-	function id_prof_verifiable($idprof)
2847
-	{
2840
+    /**
2841
+     *  Returns if a profid sould be verified
2842
+     *
2843
+     *  @param	int		$idprof		1,2,3,4,5,6 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm,5=idprof5,6=idprof6)
2844
+     *  @return boolean         	true , false
2845
+     */
2846
+    function id_prof_verifiable($idprof)
2847
+    {
2848 2848
         // phpcs:enable
2849
-		global $conf;
2850
-
2851
-	 	switch($idprof)
2852
-		{
2853
-			case 1:
2854
-				$ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
2855
-				break;
2856
-			case 2:
2857
-				$ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
2858
-				break;
2859
-			case 3:
2860
-				$ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
2861
-				break;
2862
-			case 4:
2863
-				$ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
2864
-				break;
2865
-			case 5:
2866
-				$ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true);
2867
-				break;
2868
-			case 6:
2869
-				$ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true);
2870
-				break;
2871
-			default:
2872
-				$ret=false;
2873
-		}
2874
-
2875
-		return $ret;
2876
-	}
2849
+        global $conf;
2850
+
2851
+            switch($idprof)
2852
+        {
2853
+            case 1:
2854
+                $ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
2855
+                break;
2856
+            case 2:
2857
+                $ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
2858
+                break;
2859
+            case 3:
2860
+                $ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
2861
+                break;
2862
+            case 4:
2863
+                $ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
2864
+                break;
2865
+            case 5:
2866
+                $ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true);
2867
+                break;
2868
+            case 6:
2869
+                $ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true);
2870
+                break;
2871
+            default:
2872
+                $ret=false;
2873
+        }
2874
+
2875
+        return $ret;
2876
+    }
2877 2877
 
2878 2878
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2879
-	/**
2880
-	 *    Verify if a profid exists into database for others thirds
2881
-	 *
2882
-	 *    @param	string	$idprof		'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm)
2883
-	 *    @param	string	$value		Value of profid
2884
-	 *    @param	int		$socid		Id of thirdparty to exclude (if update)
2885
-	 *    @return   boolean				True if exists, False if not
2886
-	 */
2887
-	function id_prof_exists($idprof, $value, $socid=0)
2888
-	{
2879
+    /**
2880
+     *    Verify if a profid exists into database for others thirds
2881
+     *
2882
+     *    @param	string	$idprof		'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm)
2883
+     *    @param	string	$value		Value of profid
2884
+     *    @param	int		$socid		Id of thirdparty to exclude (if update)
2885
+     *    @return   boolean				True if exists, False if not
2886
+     */
2887
+    function id_prof_exists($idprof, $value, $socid=0)
2888
+    {
2889 2889
         // phpcs:enable
2890
-		$field = $idprof;
2891
-
2892
-	 	switch($idprof)	// For backward compatibility
2893
-		{
2894
-			case '1':
2895
-			case 'idprof1':
2896
-				$field="siren";
2897
-				break;
2898
-			case '2':
2899
-			case 'idprof2':
2900
-				$field="siret";
2901
-				break;
2902
-			case '3':
2903
-			case 'idprof3':
2904
-				$field="ape";
2905
-				break;
2906
-			case '4':
2907
-			case 'idprof4':
2908
-				$field="idprof4";
2909
-				break;
2910
-			case '5':
2911
-				$field="idprof5";
2912
-				break;
2913
-			case '6':
2914
-				$field="idprof6";
2915
-				break;
2916
-	 	}
2917
-
2918
-		 //Verify duplicate entries
2919
-		$sql  = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
2920
-		if($socid) $sql .= " AND rowid <> ".$socid;
2921
-		$resql = $this->db->query($sql);
2922
-		if ($resql)
2923
-		{
2924
-			$obj = $this->db->fetch_object($resql);
2925
-			$count = $obj->idprof;
2926
-		}
2927
-		else
2928
-		{
2929
-			$count = 0;
2930
-			print $this->db->error();
2931
-		}
2932
-		$this->db->free($resql);
2933
-
2934
-		if ($count > 0) return true;
2935
-		else return false;
2936
-	}
2890
+        $field = $idprof;
2891
+
2892
+            switch($idprof)	// For backward compatibility
2893
+        {
2894
+            case '1':
2895
+            case 'idprof1':
2896
+                $field="siren";
2897
+                break;
2898
+            case '2':
2899
+            case 'idprof2':
2900
+                $field="siret";
2901
+                break;
2902
+            case '3':
2903
+            case 'idprof3':
2904
+                $field="ape";
2905
+                break;
2906
+            case '4':
2907
+            case 'idprof4':
2908
+                $field="idprof4";
2909
+                break;
2910
+            case '5':
2911
+                $field="idprof5";
2912
+                break;
2913
+            case '6':
2914
+                $field="idprof6";
2915
+                break;
2916
+            }
2917
+
2918
+            //Verify duplicate entries
2919
+        $sql  = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
2920
+        if($socid) $sql .= " AND rowid <> ".$socid;
2921
+        $resql = $this->db->query($sql);
2922
+        if ($resql)
2923
+        {
2924
+            $obj = $this->db->fetch_object($resql);
2925
+            $count = $obj->idprof;
2926
+        }
2927
+        else
2928
+        {
2929
+            $count = 0;
2930
+            print $this->db->error();
2931
+        }
2932
+        $this->db->free($resql);
2933
+
2934
+        if ($count > 0) return true;
2935
+        else return false;
2936
+    }
2937 2937
 
2938 2938
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2939
-	/**
2940
-	 *  Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...)
2941
-	 *
2942
-	 *  @param	int			$idprof         1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
2943
-	 *  @param  Societe		$soc            Objet societe
2944
-	 *  @return int             			<=0 if KO, >0 if OK
2945
-	 *  TODO better to have this in a lib than into a business class
2946
-	 */
2947
-	function id_prof_check($idprof,$soc)
2948
-	{
2939
+    /**
2940
+     *  Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...)
2941
+     *
2942
+     *  @param	int			$idprof         1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
2943
+     *  @param  Societe		$soc            Objet societe
2944
+     *  @return int             			<=0 if KO, >0 if OK
2945
+     *  TODO better to have this in a lib than into a business class
2946
+     */
2947
+    function id_prof_check($idprof,$soc)
2948
+    {
2949 2949
         // phpcs:enable
2950
-		global $conf;
2951
-
2952
-		$ok=1;
2953
-
2954
-		if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
2955
-
2956
-		// Verifie SIREN si pays FR
2957
-		if ($idprof == 1 && $soc->country_code == 'FR')
2958
-		{
2959
-			$chaine=trim($this->idprof1);
2960
-			$chaine=preg_replace('/(\s)/','',$chaine);
2961
-
2962
-			if (!is_numeric($chaine)) return -1;
2963
-			if (dol_strlen($chaine) != 9) return -1;
2964
-
2965
-			// on prend chaque chiffre un par un
2966
-			// si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
2967
-			// on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
2968
-			// on ajoute cette valeur à la somme totale
2969
-
2970
-			for ($index = 0; $index < 9; $index ++)
2971
-			{
2972
-				$number = (int) $siren[$index];
2973
-				if (($index % 2) != 0) { if (($number *= 2) > 9) $number -= 9; }
2974
-				$sum += $number;
2975
-			}
2976
-
2977
-			// le numéro est valide si la somme des chiffres est multiple de 10
2978
-			if (($sum % 10) != 0) return -1;
2979
-		}
2980
-
2981
-		// Verifie SIRET si pays FR
2982
-		if ($idprof == 2 && $soc->country_code == 'FR')
2983
-		{
2984
-			$chaine=trim($this->idprof2);
2985
-			$chaine=preg_replace('/(\s)/','',$chaine);
2986
-
2987
-			if (!is_numeric($chaine)) return -1;
2988
-			if (dol_strlen($chaine) != 14) return -1;
2989
-
2990
-			// on prend chaque chiffre un par un
2991
-			// si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
2992
-			// on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
2993
-			// on ajoute cette valeur à la somme totale
2994
-
2995
-			for ($index = 0; $index < 14; $index ++)
2996
-			{
2997
-				$number = (int) $chaine[$index];
2998
-				if (($index % 2) == 0) { if (($number *= 2) > 9) $number -= 9; }
2999
-				$sum += $number;
3000
-			}
3001
-
3002
-			// le numéro est valide si la somme des chiffres est multiple de 10
3003
-			if (($sum % 10) != 0) return -1;
3004
-		}
3005
-
3006
-		//Verify CIF/NIF/NIE if pays ES
3007
-		//Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
3008
-		if ($idprof == 1 && $soc->country_code == 'ES')
3009
-		{
3010
-			$string=trim($this->idprof1);
3011
-			$string=preg_replace('/(\s)/','',$string);
3012
-			$string = strtoupper($string);
3013
-
3014
-			for ($i = 0; $i < 9; $i ++)
3015
-			$num[$i] = substr($string, $i, 1);
3016
-
3017
-			//Check format
3018
-			if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string))
3019
-			return 0;
3020
-
3021
-			//Check NIF
3022
-			if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
3023
-				if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
3024
-				return 1;
3025
-				else
3026
-				return -1;
3027
-
3028
-			//algorithm checking type code CIF
3029
-			$sum = $num[2] + $num[4] + $num[6];
3030
-			for ($i = 1; $i < 8; $i += 2)
3031
-			$sum += intval(substr((2 * $num[$i]),0,1)) + intval(substr((2 * $num[$i]),1,1));
3032
-			$n = 10 - substr($sum, strlen($sum) - 1, 1);
3033
-
3034
-			//Chek special NIF
3035
-			if (preg_match('/^[KLM]{1}/', $string))
3036
-				if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
3037
-				return 1;
3038
-				else
3039
-				return -1;
3040
-
3041
-			//Check CIF
3042
-			if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
3043
-				if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
3044
-				return 2;
3045
-				else
3046
-				return -2;
3047
-
3048
-			//Check NIE T
3049
-			if (preg_match('/^[T]{1}/', $string))
3050
-				if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
3051
-				return 3;
3052
-				else
3053
-				return -3;
3054
-
3055
-			//Check NIE XYZ
3056
-			if (preg_match('/^[XYZ]{1}/', $string))
3057
-				if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
3058
-				return 3;
3059
-				else
3060
-				return -3;
3061
-
3062
-			//Can not be verified
3063
-			return -4;
3064
-		}
3065
-
3066
-		//Verify NIF if country is PT
3067
-		//Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3068
-		if ($idprof == 1 && $soc->country_code == 'PT')
3069
-		{
3070
-			$string=trim($this->idprof1);
3071
-			$string=preg_replace('/(\s)/','',$string);
3072
-
3073
-			for ($i = 0; $i < 9; $i ++) {
3074
-				$num[$i] = substr($string, $i, 1);
3075
-			}
3076
-
3077
-			//Check NIF
3078
-			if (preg_match('/(^[0-9]{9}$)/', $string)) {
3079
-				return 1;
3080
-			}
3081
-			else {
3082
-				return -1;
3083
-			}
3084
-		}
3085
-
3086
-		return $ok;
3087
-	}
2950
+        global $conf;
2951
+
2952
+        $ok=1;
2953
+
2954
+        if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
2955
+
2956
+        // Verifie SIREN si pays FR
2957
+        if ($idprof == 1 && $soc->country_code == 'FR')
2958
+        {
2959
+            $chaine=trim($this->idprof1);
2960
+            $chaine=preg_replace('/(\s)/','',$chaine);
2961
+
2962
+            if (!is_numeric($chaine)) return -1;
2963
+            if (dol_strlen($chaine) != 9) return -1;
2964
+
2965
+            // on prend chaque chiffre un par un
2966
+            // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
2967
+            // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
2968
+            // on ajoute cette valeur à la somme totale
2969
+
2970
+            for ($index = 0; $index < 9; $index ++)
2971
+            {
2972
+                $number = (int) $siren[$index];
2973
+                if (($index % 2) != 0) { if (($number *= 2) > 9) $number -= 9; }
2974
+                $sum += $number;
2975
+            }
2976
+
2977
+            // le numéro est valide si la somme des chiffres est multiple de 10
2978
+            if (($sum % 10) != 0) return -1;
2979
+        }
2980
+
2981
+        // Verifie SIRET si pays FR
2982
+        if ($idprof == 2 && $soc->country_code == 'FR')
2983
+        {
2984
+            $chaine=trim($this->idprof2);
2985
+            $chaine=preg_replace('/(\s)/','',$chaine);
2986
+
2987
+            if (!is_numeric($chaine)) return -1;
2988
+            if (dol_strlen($chaine) != 14) return -1;
2989
+
2990
+            // on prend chaque chiffre un par un
2991
+            // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
2992
+            // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
2993
+            // on ajoute cette valeur à la somme totale
2994
+
2995
+            for ($index = 0; $index < 14; $index ++)
2996
+            {
2997
+                $number = (int) $chaine[$index];
2998
+                if (($index % 2) == 0) { if (($number *= 2) > 9) $number -= 9; }
2999
+                $sum += $number;
3000
+            }
3001
+
3002
+            // le numéro est valide si la somme des chiffres est multiple de 10
3003
+            if (($sum % 10) != 0) return -1;
3004
+        }
3005
+
3006
+        //Verify CIF/NIF/NIE if pays ES
3007
+        //Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
3008
+        if ($idprof == 1 && $soc->country_code == 'ES')
3009
+        {
3010
+            $string=trim($this->idprof1);
3011
+            $string=preg_replace('/(\s)/','',$string);
3012
+            $string = strtoupper($string);
3013
+
3014
+            for ($i = 0; $i < 9; $i ++)
3015
+            $num[$i] = substr($string, $i, 1);
3016
+
3017
+            //Check format
3018
+            if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string))
3019
+            return 0;
3020
+
3021
+            //Check NIF
3022
+            if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
3023
+                if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
3024
+                return 1;
3025
+                else
3026
+                return -1;
3027
+
3028
+            //algorithm checking type code CIF
3029
+            $sum = $num[2] + $num[4] + $num[6];
3030
+            for ($i = 1; $i < 8; $i += 2)
3031
+            $sum += intval(substr((2 * $num[$i]),0,1)) + intval(substr((2 * $num[$i]),1,1));
3032
+            $n = 10 - substr($sum, strlen($sum) - 1, 1);
3033
+
3034
+            //Chek special NIF
3035
+            if (preg_match('/^[KLM]{1}/', $string))
3036
+                if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
3037
+                return 1;
3038
+                else
3039
+                return -1;
3040
+
3041
+            //Check CIF
3042
+            if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
3043
+                if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
3044
+                return 2;
3045
+                else
3046
+                return -2;
3047
+
3048
+            //Check NIE T
3049
+            if (preg_match('/^[T]{1}/', $string))
3050
+                if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
3051
+                return 3;
3052
+                else
3053
+                return -3;
3054
+
3055
+            //Check NIE XYZ
3056
+            if (preg_match('/^[XYZ]{1}/', $string))
3057
+                if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
3058
+                return 3;
3059
+                else
3060
+                return -3;
3061
+
3062
+            //Can not be verified
3063
+            return -4;
3064
+        }
3065
+
3066
+        //Verify NIF if country is PT
3067
+        //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
3068
+        if ($idprof == 1 && $soc->country_code == 'PT')
3069
+        {
3070
+            $string=trim($this->idprof1);
3071
+            $string=preg_replace('/(\s)/','',$string);
3072
+
3073
+            for ($i = 0; $i < 9; $i ++) {
3074
+                $num[$i] = substr($string, $i, 1);
3075
+            }
3076
+
3077
+            //Check NIF
3078
+            if (preg_match('/(^[0-9]{9}$)/', $string)) {
3079
+                return 1;
3080
+            }
3081
+            else {
3082
+                return -1;
3083
+            }
3084
+        }
3085
+
3086
+        return $ok;
3087
+    }
3088 3088
 
3089 3089
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3090
-	/**
3091
-	 *   Return an url to check online a professional id or empty string
3092
-	 *
3093
-	 *   @param		int		$idprof         1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
3094
-	 *   @param 	Societe	$thirdparty     Object thirdparty
3095
-	 *   @return	string          		Url or empty string if no URL known
3096
-	 *   TODO better in a lib than into business class
3097
-	 */
3098
-	function id_prof_url($idprof,$thirdparty)
3099
-	{
3090
+    /**
3091
+     *   Return an url to check online a professional id or empty string
3092
+     *
3093
+     *   @param		int		$idprof         1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
3094
+     *   @param 	Societe	$thirdparty     Object thirdparty
3095
+     *   @return	string          		Url or empty string if no URL known
3096
+     *   TODO better in a lib than into business class
3097
+     */
3098
+    function id_prof_url($idprof,$thirdparty)
3099
+    {
3100 3100
         // phpcs:enable
3101
-		global $conf,$langs,$hookmanager;
3101
+        global $conf,$langs,$hookmanager;
3102 3102
 
3103
-		$url='';
3104
-		$action = '';
3103
+        $url='';
3104
+        $action = '';
3105 3105
 
3106
-		$hookmanager->initHooks(array('idprofurl'));
3107
-		$parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
3108
-		$reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
3109
-		if (empty($reshook)) {
3110
-			if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3111
-				return '';
3112
-			}
3106
+        $hookmanager->initHooks(array('idprofurl'));
3107
+        $parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
3108
+        $reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
3109
+        if (empty($reshook)) {
3110
+            if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
3111
+                return '';
3112
+            }
3113 3113
 
3114
-			// TODO Move links to validate professional ID into a dictionary table "country" + "link"
3114
+            // TODO Move links to validate professional ID into a dictionary table "country" + "link"
3115 3115
             $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
3116
-			if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3117
-				$url='http://www.societe.com/cgi-bin/search?champs='.$strippedIdProf1;    // See also http://avis-situation-sirene.insee.fr/
3118
-			}
3119
-			if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3120
-				$url='https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3121
-			}
3122
-			if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3123
-				$url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3124
-			}
3125
-			if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3126
-				$url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3127
-			}
3128
-			if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3129
-				$url='http://www.nif.pt/'.$strippedIdProf1;
3130
-			}
3131
-
3132
-			if ($url) {
3133
-				return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
3134
-			}
3135
-		}
3136
-		else {
3137
-			return $hookmanager->resPrint;
3138
-		}
3139
-
3140
-		return '';
3141
-	}
3116
+            if ($idprof == 1 && $thirdparty->country_code == 'FR') {
3117
+                $url='http://www.societe.com/cgi-bin/search?champs='.$strippedIdProf1;    // See also http://avis-situation-sirene.insee.fr/
3118
+            }
3119
+            if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
3120
+                $url='https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
3121
+            }
3122
+            if ($idprof == 1 && $thirdparty->country_code == 'ES') {
3123
+                $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
3124
+            }
3125
+            if ($idprof == 1 && $thirdparty->country_code == 'IN') {
3126
+                $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
3127
+            }
3128
+            if ($idprof == 1 && $thirdparty->country_code == 'PT') {
3129
+                $url='http://www.nif.pt/'.$strippedIdProf1;
3130
+            }
3131
+
3132
+            if ($url) {
3133
+                return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
3134
+            }
3135
+        }
3136
+        else {
3137
+            return $hookmanager->resPrint;
3138
+        }
3139
+
3140
+        return '';
3141
+    }
3142 3142
 
3143 3143
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3144
-	/**
3145
-	 *   Indique si la societe a des projets
3146
-	 *
3147
-	 *   @return     bool	   true si la societe a des projets, false sinon
3148
-	 */
3149
-	function has_projects()
3150
-	{
3144
+    /**
3145
+     *   Indique si la societe a des projets
3146
+     *
3147
+     *   @return     bool	   true si la societe a des projets, false sinon
3148
+     */
3149
+    function has_projects()
3150
+    {
3151 3151
         // phpcs:enable
3152
-		$sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
3153
-		$resql = $this->db->query($sql);
3154
-		if ($resql)
3155
-		{
3156
-			$obj = $this->db->fetch_object($resql);
3157
-			$count = $obj->numproj;
3158
-		}
3159
-		else
3160
-		{
3161
-			$count = 0;
3162
-			print $this->db->error();
3163
-		}
3164
-		$this->db->free($resql);
3165
-		return ($count > 0);
3166
-	}
3167
-
3168
-
3169
-	/**
3170
-	 *  Load information for tab info
3171
-	 *
3172
-	 *  @param  int		$id     Id of thirdparty to load
3173
-	 *  @return	void
3174
-	 */
3175
-	function info($id)
3176
-	{
3177
-		$sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
3178
-		$sql.= " fk_user_creat, fk_user_modif";
3179
-		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
3180
-		$sql.= " WHERE s.rowid = ".$id;
3181
-
3182
-		$result=$this->db->query($sql);
3183
-		if ($result)
3184
-		{
3185
-			if ($this->db->num_rows($result))
3186
-			{
3187
-				$obj = $this->db->fetch_object($result);
3188
-
3189
-				$this->id = $obj->rowid;
3190
-
3191
-				if ($obj->fk_user_creat) {
3192
-					$cuser = new User($this->db);
3193
-					$cuser->fetch($obj->fk_user_creat);
3194
-					$this->user_creation     = $cuser;
3195
-				}
3196
-
3197
-				if ($obj->fk_user_modif) {
3198
-					$muser = new User($this->db);
3199
-					$muser->fetch($obj->fk_user_modif);
3200
-					$this->user_modification = $muser;
3201
-				}
3202
-
3203
-				$this->ref			     = $obj->name;
3204
-				$this->date_creation     = $this->db->jdate($obj->date_creation);
3205
-				$this->date_modification = $this->db->jdate($obj->date_modification);
3206
-			}
3207
-
3208
-			$this->db->free($result);
3209
-		}
3210
-		else
3211
-		{
3212
-			dol_print_error($this->db);
3213
-		}
3214
-	}
3215
-
3216
-	/**
3217
-	 *  Return if third party is a company (Business) or an end user (Consumer)
3218
-	 *
3219
-	 *  @return    boolean     true=is a company, false=a and user
3220
-	 */
3221
-	function isACompany()
3222
-	{
3223
-		global $conf;
3224
-
3225
-		// Define if third party is treated as company (or not) when nature is unknown
3226
-		$isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
3227
-		if (! empty($this->tva_intra)) $isacompany=1;
3228
-		else if (! empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN')
3229
-		{
3230
-			// TODO Add a field is_a_company into dictionary
3231
-			if (preg_match('/^TE_PRIVATE/', $this->typent_code)) $isacompany=0;
3232
-			else $isacompany=1;
3233
-		}
3234
-
3235
-		return $isacompany;
3236
-	}
3237
-
3238
-	/**
3239
-	 *  Return if a company is inside the EEC (European Economic Community)
3240
-	 *
3241
-	 *  @return     boolean		true = country inside EEC, false = country outside EEC
3242
-	 */
3243
-	function isInEEC()
3244
-	{
3245
-		require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3246
-		return isInEEC($this);
3247
-	}
3152
+        $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
3153
+        $resql = $this->db->query($sql);
3154
+        if ($resql)
3155
+        {
3156
+            $obj = $this->db->fetch_object($resql);
3157
+            $count = $obj->numproj;
3158
+        }
3159
+        else
3160
+        {
3161
+            $count = 0;
3162
+            print $this->db->error();
3163
+        }
3164
+        $this->db->free($resql);
3165
+        return ($count > 0);
3166
+    }
3167
+
3168
+
3169
+    /**
3170
+     *  Load information for tab info
3171
+     *
3172
+     *  @param  int		$id     Id of thirdparty to load
3173
+     *  @return	void
3174
+     */
3175
+    function info($id)
3176
+    {
3177
+        $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
3178
+        $sql.= " fk_user_creat, fk_user_modif";
3179
+        $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
3180
+        $sql.= " WHERE s.rowid = ".$id;
3181
+
3182
+        $result=$this->db->query($sql);
3183
+        if ($result)
3184
+        {
3185
+            if ($this->db->num_rows($result))
3186
+            {
3187
+                $obj = $this->db->fetch_object($result);
3188
+
3189
+                $this->id = $obj->rowid;
3190
+
3191
+                if ($obj->fk_user_creat) {
3192
+                    $cuser = new User($this->db);
3193
+                    $cuser->fetch($obj->fk_user_creat);
3194
+                    $this->user_creation     = $cuser;
3195
+                }
3196
+
3197
+                if ($obj->fk_user_modif) {
3198
+                    $muser = new User($this->db);
3199
+                    $muser->fetch($obj->fk_user_modif);
3200
+                    $this->user_modification = $muser;
3201
+                }
3202
+
3203
+                $this->ref			     = $obj->name;
3204
+                $this->date_creation     = $this->db->jdate($obj->date_creation);
3205
+                $this->date_modification = $this->db->jdate($obj->date_modification);
3206
+            }
3207
+
3208
+            $this->db->free($result);
3209
+        }
3210
+        else
3211
+        {
3212
+            dol_print_error($this->db);
3213
+        }
3214
+    }
3215
+
3216
+    /**
3217
+     *  Return if third party is a company (Business) or an end user (Consumer)
3218
+     *
3219
+     *  @return    boolean     true=is a company, false=a and user
3220
+     */
3221
+    function isACompany()
3222
+    {
3223
+        global $conf;
3224
+
3225
+        // Define if third party is treated as company (or not) when nature is unknown
3226
+        $isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
3227
+        if (! empty($this->tva_intra)) $isacompany=1;
3228
+        else if (! empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN')
3229
+        {
3230
+            // TODO Add a field is_a_company into dictionary
3231
+            if (preg_match('/^TE_PRIVATE/', $this->typent_code)) $isacompany=0;
3232
+            else $isacompany=1;
3233
+        }
3234
+
3235
+        return $isacompany;
3236
+    }
3237
+
3238
+    /**
3239
+     *  Return if a company is inside the EEC (European Economic Community)
3240
+     *
3241
+     *  @return     boolean		true = country inside EEC, false = country outside EEC
3242
+     */
3243
+    function isInEEC()
3244
+    {
3245
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3246
+        return isInEEC($this);
3247
+    }
3248 3248
 
3249 3249
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3250
-	/**
3251
-	 *  Charge la liste des categories fournisseurs
3252
-	 *
3253
-	 *  @return    int      0 if success, <> 0 if error
3254
-	 */
3255
-	function LoadSupplierCateg()
3256
-	{
3250
+    /**
3251
+     *  Charge la liste des categories fournisseurs
3252
+     *
3253
+     *  @return    int      0 if success, <> 0 if error
3254
+     */
3255
+    function LoadSupplierCateg()
3256
+    {
3257 3257
         // phpcs:enable
3258
-		$this->SupplierCategories = array();
3259
-		$sql = "SELECT rowid, label";
3260
-		$sql.= " FROM ".MAIN_DB_PREFIX."categorie";
3261
-		$sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
3262
-
3263
-		$resql=$this->db->query($sql);
3264
-		if ($resql)
3265
-		{
3266
-			while ($obj = $this->db->fetch_object($resql) )
3267
-			{
3268
-				$this->SupplierCategories[$obj->rowid] = $obj->label;
3269
-			}
3270
-			return 0;
3271
-		}
3272
-		else
3273
-		{
3274
-			return -1;
3275
-		}
3276
-	}
3258
+        $this->SupplierCategories = array();
3259
+        $sql = "SELECT rowid, label";
3260
+        $sql.= " FROM ".MAIN_DB_PREFIX."categorie";
3261
+        $sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
3262
+
3263
+        $resql=$this->db->query($sql);
3264
+        if ($resql)
3265
+        {
3266
+            while ($obj = $this->db->fetch_object($resql) )
3267
+            {
3268
+                $this->SupplierCategories[$obj->rowid] = $obj->label;
3269
+            }
3270
+            return 0;
3271
+        }
3272
+        else
3273
+        {
3274
+            return -1;
3275
+        }
3276
+    }
3277 3277
 
3278 3278
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3279
-	/**
3280
-	 *  Insert link supplier - category
3281
-	 *
3282
-	 *	@param	int		$categorie_id		Id of category
3283
-	 *  @return int      					0 if success, <> 0 if error
3284
-	 */
3285
-	function AddFournisseurInCategory($categorie_id)
3286
-	{
3279
+    /**
3280
+     *  Insert link supplier - category
3281
+     *
3282
+     *	@param	int		$categorie_id		Id of category
3283
+     *  @return int      					0 if success, <> 0 if error
3284
+     */
3285
+    function AddFournisseurInCategory($categorie_id)
3286
+    {
3287 3287
         // phpcs:enable
3288
-		if ($categorie_id > 0 && $this->id > 0)
3289
-		{
3290
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
3291
-			$sql.= " VALUES (".$categorie_id.", ".$this->id.")";
3288
+        if ($categorie_id > 0 && $this->id > 0)
3289
+        {
3290
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
3291
+            $sql.= " VALUES (".$categorie_id.", ".$this->id.")";
3292 3292
 
3293
-			if ($resql=$this->db->query($sql)) return 0;
3294
-		}
3295
-		else
3296
-		{
3297
-			return 0;
3298
-		}
3299
-		return -1;
3300
-	}
3293
+            if ($resql=$this->db->query($sql)) return 0;
3294
+        }
3295
+        else
3296
+        {
3297
+            return 0;
3298
+        }
3299
+        return -1;
3300
+    }
3301 3301
 
3302 3302
 
3303 3303
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3304
-	/**
3305
-	 *  Create a third party into database from a member object
3306
-	 *
3307
-	 *  @param	Adherent	$member			Object member
3308
-	 * 	@param	string		$socname		Name of third party to force
3309
-	 *	@param	string		$socalias		Alias name of third party to force
3310
-	 *  @param	string		$customercode	Customer code
3311
-	 *  @return int							<0 if KO, id of created account if OK
3312
-	 */
3313
-	function create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
3314
-	{
3304
+    /**
3305
+     *  Create a third party into database from a member object
3306
+     *
3307
+     *  @param	Adherent	$member			Object member
3308
+     * 	@param	string		$socname		Name of third party to force
3309
+     *	@param	string		$socalias		Alias name of third party to force
3310
+     *  @param	string		$customercode	Customer code
3311
+     *  @return int							<0 if KO, id of created account if OK
3312
+     */
3313
+    function create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
3314
+    {
3315 3315
         // phpcs:enable
3316
-		global $user,$langs;
3317
-
3318
-		dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
3319
-
3320
-		$name = $socname?$socname:$member->societe;
3321
-		if (empty($name)) $name=$member->getFullName($langs);
3322
-
3323
-		$alias = $socalias?$socalias:'';
3324
-
3325
-		// Positionne parametres
3326
-		$this->nom=$name;				// TODO deprecated
3327
-		$this->name=$name;
3328
-		$this->name_alias=$alias;
3329
-		$this->address=$member->address;
3330
-		$this->zip=$member->zip;
3331
-		$this->town=$member->town;
3332
-		$this->country_code=$member->country_code;
3333
-		$this->country_id=$member->country_id;
3334
-		$this->phone=$member->phone;       // Prof phone
3335
-		$this->email=$member->email;
3336
-		$this->skype=$member->skype;
3337
-		$this->twitter=$member->twitter;
3338
-		$this->facebook=$member->facebook;
3339
-
3340
-		$this->client = 1;				// A member is a customer by default
3341
-		$this->code_client = ($customercode?$customercode:-1);
3342
-		$this->code_fournisseur = -1;
3343
-
3344
-		$this->db->begin();
3345
-
3346
-		// Cree et positionne $this->id
3347
-		$result=$this->create($user);
3348
-		if ($result >= 0)
3349
-		{
3350
-			$sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
3351
-			$sql.= " SET fk_soc=".$this->id;
3352
-			$sql.= " WHERE rowid=".$member->id;
3353
-
3354
-			$resql=$this->db->query($sql);
3355
-			if ($resql)
3356
-			{
3357
-				$this->db->commit();
3358
-				return $this->id;
3359
-			}
3360
-			else
3361
-			{
3362
-				$this->error=$this->db->error();
3363
-
3364
-				$this->db->rollback();
3365
-				return -1;
3366
-			}
3367
-		}
3368
-		else
3369
-		{
3370
-			// $this->error deja positionne
3371
-			dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
3372
-
3373
-			$this->db->rollback();
3374
-			return $result;
3375
-		}
3376
-	}
3377
-
3378
-	/**
3379
-	 * 	Set properties with value into $conf
3380
-	 *
3381
-	 * 	@param	Conf	$conf		Conf object (possibility to use another entity)
3382
-	 * 	@return	void
3383
-	 */
3384
-	function setMysoc(Conf $conf)
3385
-	{
3386
-		global $langs;
3387
-
3388
-		$this->id=0;
3389
-		$this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
3390
-		$this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3391
-		$this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
3392
-		$this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
3393
-		$this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE;
3394
-		$this->region_code=empty($conf->global->MAIN_INFO_SOCIETE_REGION)?'':$conf->global->MAIN_INFO_SOCIETE_REGION;
3395
-		$this->object=empty($conf->global->MAIN_INFO_SOCIETE_OBJECT)?'':$conf->global->MAIN_INFO_SOCIETE_OBJECT;
3396
-
3397
-		$this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
3398
-
3399
-		$this->nom=$this->name; 									// deprecated
3400
-
3401
-		// We define country_id, country_code and country
3402
-		$country_id=$country_code=$country_label='';
3403
-		if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
3404
-		{
3405
-			$tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3406
-			$country_id=$tmp[0];
3407
-			if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3408
-			{
3409
-				$country_code=$tmp[1];
3410
-				$country_label=$tmp[2];
3411
-			}
3412
-			else                    // For backward compatibility
3413
-			{
3414
-				dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3415
-				include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3416
-				$country_code=getCountry($country_id,2,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3417
-				$country_label=getCountry($country_id,0,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3418
-			}
3419
-		}
3420
-		$this->country_id=$country_id;
3421
-		$this->country_code=$country_code;
3422
-		$this->country=$country_label;
3423
-		if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3424
-
3425
-		$this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
3426
-		$this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
3427
-		$this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
3428
-		// Id prof generiques
3429
-		$this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
3430
-		$this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
3431
-		$this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
3432
-		$this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
3433
-		$this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
3434
-		$this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
3435
-		$this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA;	// VAT number, not necessarly INTRA.
3436
-		$this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3437
-		$this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
3438
-		$this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3439
-		$this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
3440
-		$this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
3441
-		$this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3442
-		$this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3443
-
3444
-		// Define if company use vat or not
3445
-		$this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
3446
-
3447
-		// Define if company use local taxes
3448
-		$this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0);
3449
-		$this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0);
3450
-	}
3451
-
3452
-	/**
3453
-	 *  Initialise an instance with random values.
3454
-	 *  Used to build previews or test instances.
3455
-	 *	id must be 0 if object instance is a specimen.
3456
-	 *
3457
-	 *  @return	void
3458
-	 */
3459
-	function initAsSpecimen()
3460
-	{
3461
-		$now=dol_now();
3462
-
3463
-		// Initialize parameters
3464
-		$this->id=0;
3465
-		$this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog');
3466
-		$this->nom = $this->name;   // For backward compatibility
3467
-		$this->ref_ext = 'Ref ext';
3468
-		$this->specimen=1;
3469
-		$this->address='21 jump street';
3470
-		$this->zip='99999';
3471
-		$this->town='MyTown';
3472
-		$this->state_id=1;
3473
-		$this->state_code='AA';
3474
-		$this->state='MyState';
3475
-		$this->country_id=1;
3476
-		$this->country_code='FR';
3477
-		$this->email='[email protected]';
3478
-		$this->skype='tom.hanson';
3479
-		$this->twitter='tomhanson';
3480
-		$this->facebook='tomhanson';
3481
-		$this->url='http://www.specimen.com';
3482
-
3483
-		$this->phone='0909090901';
3484
-		$this->fax='0909090909';
3485
-
3486
-		$this->code_client='CC-'.dol_print_date($now,'dayhourlog');
3487
-		$this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog');
3488
-		$this->capital=10000;
3489
-		$this->client=1;
3490
-		$this->prospect=1;
3491
-		$this->fournisseur=1;
3492
-		$this->tva_assuj=1;
3493
-		$this->tva_intra='EU1234567';
3494
-		$this->note_public='This is a comment (public)';
3495
-		$this->note_private='This is a comment (private)';
3496
-
3497
-		$this->idprof1='idprof1';
3498
-		$this->idprof2='idprof2';
3499
-		$this->idprof3='idprof3';
3500
-		$this->idprof4='idprof4';
3501
-		$this->idprof5='idprof5';
3502
-		$this->idprof6='idprof6';
3503
-	}
3504
-
3505
-	/**
3506
-	 *  Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
3507
-	 *
3508
-	 *	@param		int		$localTaxNum	To get info for only localtax1 or localtax2
3509
-	 *  @return		boolean					true or false
3510
-	 */
3511
-	function useLocalTax($localTaxNum=0)
3512
-	{
3513
-		$sql  = "SELECT t.localtax1, t.localtax2";
3514
-		$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3515
-		$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3516
-		$sql .= " AND t.active = 1";
3517
-		if (empty($localTaxNum))   $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3518
-		elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
3519
-		elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
3520
-
3521
-		dol_syslog("useLocalTax", LOG_DEBUG);
3522
-		$resql=$this->db->query($sql);
3523
-		if ($resql)
3524
-		{
3525
-   			return ($this->db->num_rows($resql) > 0);
3526
-		}
3527
-		else return false;
3528
-	}
3529
-
3530
-	/**
3531
-	 *  Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
3532
-	 *
3533
-	 *  @return		boolean					true or false
3534
-	 */
3535
-	function useNPR()
3536
-	{
3537
-		$sql  = "SELECT t.rowid";
3538
-		$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3539
-		$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3540
-		$sql .= " AND t.active = 1 AND t.recuperableonly = 1";
3541
-
3542
-		dol_syslog("useNPR", LOG_DEBUG);
3543
-		$resql=$this->db->query($sql);
3544
-		if ($resql)
3545
-		{
3546
-			return ($this->db->num_rows($resql) > 0);
3547
-		}
3548
-		else return false;
3549
-	}
3550
-
3551
-	/**
3552
-	 *  Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
3553
-	 *
3554
-	 *  @return		boolean			true or false
3555
-	 */
3556
-	function useRevenueStamp()
3557
-	{
3558
-		$sql  = "SELECT COUNT(*) as nb";
3559
-		$sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
3560
-		$sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3561
-		$sql .= " AND r.active = 1";
3562
-
3563
-		dol_syslog("useRevenueStamp", LOG_DEBUG);
3564
-		$resql=$this->db->query($sql);
3565
-		if ($resql)
3566
-		{
3567
-			$obj=$this->db->fetch_object($resql);
3568
-   			return (($obj->nb > 0)?true:false);
3569
-		}
3570
-		else
3571
-		{
3572
-			$this->error=$this->db->lasterror();
3573
-			return false;
3574
-		}
3575
-	}
3576
-
3577
-	/**
3578
-	 *	Return prostect level
3579
-	 *
3580
-	 *  @return     string        Libelle
3581
-	 */
3582
-	function getLibProspLevel()
3583
-	{
3584
-		return $this->LibProspLevel($this->fk_prospectlevel);
3585
-	}
3316
+        global $user,$langs;
3317
+
3318
+        dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
3319
+
3320
+        $name = $socname?$socname:$member->societe;
3321
+        if (empty($name)) $name=$member->getFullName($langs);
3322
+
3323
+        $alias = $socalias?$socalias:'';
3324
+
3325
+        // Positionne parametres
3326
+        $this->nom=$name;				// TODO deprecated
3327
+        $this->name=$name;
3328
+        $this->name_alias=$alias;
3329
+        $this->address=$member->address;
3330
+        $this->zip=$member->zip;
3331
+        $this->town=$member->town;
3332
+        $this->country_code=$member->country_code;
3333
+        $this->country_id=$member->country_id;
3334
+        $this->phone=$member->phone;       // Prof phone
3335
+        $this->email=$member->email;
3336
+        $this->skype=$member->skype;
3337
+        $this->twitter=$member->twitter;
3338
+        $this->facebook=$member->facebook;
3339
+
3340
+        $this->client = 1;				// A member is a customer by default
3341
+        $this->code_client = ($customercode?$customercode:-1);
3342
+        $this->code_fournisseur = -1;
3343
+
3344
+        $this->db->begin();
3345
+
3346
+        // Cree et positionne $this->id
3347
+        $result=$this->create($user);
3348
+        if ($result >= 0)
3349
+        {
3350
+            $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
3351
+            $sql.= " SET fk_soc=".$this->id;
3352
+            $sql.= " WHERE rowid=".$member->id;
3353
+
3354
+            $resql=$this->db->query($sql);
3355
+            if ($resql)
3356
+            {
3357
+                $this->db->commit();
3358
+                return $this->id;
3359
+            }
3360
+            else
3361
+            {
3362
+                $this->error=$this->db->error();
3363
+
3364
+                $this->db->rollback();
3365
+                return -1;
3366
+            }
3367
+        }
3368
+        else
3369
+        {
3370
+            // $this->error deja positionne
3371
+            dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
3372
+
3373
+            $this->db->rollback();
3374
+            return $result;
3375
+        }
3376
+    }
3377
+
3378
+    /**
3379
+     * 	Set properties with value into $conf
3380
+     *
3381
+     * 	@param	Conf	$conf		Conf object (possibility to use another entity)
3382
+     * 	@return	void
3383
+     */
3384
+    function setMysoc(Conf $conf)
3385
+    {
3386
+        global $langs;
3387
+
3388
+        $this->id=0;
3389
+        $this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
3390
+        $this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3391
+        $this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
3392
+        $this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
3393
+        $this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE;
3394
+        $this->region_code=empty($conf->global->MAIN_INFO_SOCIETE_REGION)?'':$conf->global->MAIN_INFO_SOCIETE_REGION;
3395
+        $this->object=empty($conf->global->MAIN_INFO_SOCIETE_OBJECT)?'':$conf->global->MAIN_INFO_SOCIETE_OBJECT;
3396
+
3397
+        $this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
3398
+
3399
+        $this->nom=$this->name; 									// deprecated
3400
+
3401
+        // We define country_id, country_code and country
3402
+        $country_id=$country_code=$country_label='';
3403
+        if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
3404
+        {
3405
+            $tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3406
+            $country_id=$tmp[0];
3407
+            if (! empty($tmp[1]))   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3408
+            {
3409
+                $country_code=$tmp[1];
3410
+                $country_label=$tmp[2];
3411
+            }
3412
+            else                    // For backward compatibility
3413
+            {
3414
+                dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3415
+                include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
3416
+                $country_code=getCountry($country_id,2,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3417
+                $country_label=getCountry($country_id,0,$this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3418
+            }
3419
+        }
3420
+        $this->country_id=$country_id;
3421
+        $this->country_code=$country_code;
3422
+        $this->country=$country_label;
3423
+        if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
3424
+
3425
+        $this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
3426
+        $this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
3427
+        $this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
3428
+        // Id prof generiques
3429
+        $this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
3430
+        $this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
3431
+        $this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
3432
+        $this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
3433
+        $this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
3434
+        $this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
3435
+        $this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA;	// VAT number, not necessarly INTRA.
3436
+        $this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3437
+        $this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
3438
+        $this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3439
+        $this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
3440
+        $this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
3441
+        $this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3442
+        $this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3443
+
3444
+        // Define if company use vat or not
3445
+        $this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
3446
+
3447
+        // Define if company use local taxes
3448
+        $this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0);
3449
+        $this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0);
3450
+    }
3451
+
3452
+    /**
3453
+     *  Initialise an instance with random values.
3454
+     *  Used to build previews or test instances.
3455
+     *	id must be 0 if object instance is a specimen.
3456
+     *
3457
+     *  @return	void
3458
+     */
3459
+    function initAsSpecimen()
3460
+    {
3461
+        $now=dol_now();
3462
+
3463
+        // Initialize parameters
3464
+        $this->id=0;
3465
+        $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog');
3466
+        $this->nom = $this->name;   // For backward compatibility
3467
+        $this->ref_ext = 'Ref ext';
3468
+        $this->specimen=1;
3469
+        $this->address='21 jump street';
3470
+        $this->zip='99999';
3471
+        $this->town='MyTown';
3472
+        $this->state_id=1;
3473
+        $this->state_code='AA';
3474
+        $this->state='MyState';
3475
+        $this->country_id=1;
3476
+        $this->country_code='FR';
3477
+        $this->email='[email protected]';
3478
+        $this->skype='tom.hanson';
3479
+        $this->twitter='tomhanson';
3480
+        $this->facebook='tomhanson';
3481
+        $this->url='http://www.specimen.com';
3482
+
3483
+        $this->phone='0909090901';
3484
+        $this->fax='0909090909';
3485
+
3486
+        $this->code_client='CC-'.dol_print_date($now,'dayhourlog');
3487
+        $this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog');
3488
+        $this->capital=10000;
3489
+        $this->client=1;
3490
+        $this->prospect=1;
3491
+        $this->fournisseur=1;
3492
+        $this->tva_assuj=1;
3493
+        $this->tva_intra='EU1234567';
3494
+        $this->note_public='This is a comment (public)';
3495
+        $this->note_private='This is a comment (private)';
3496
+
3497
+        $this->idprof1='idprof1';
3498
+        $this->idprof2='idprof2';
3499
+        $this->idprof3='idprof3';
3500
+        $this->idprof4='idprof4';
3501
+        $this->idprof5='idprof5';
3502
+        $this->idprof6='idprof6';
3503
+    }
3504
+
3505
+    /**
3506
+     *  Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
3507
+     *
3508
+     *	@param		int		$localTaxNum	To get info for only localtax1 or localtax2
3509
+     *  @return		boolean					true or false
3510
+     */
3511
+    function useLocalTax($localTaxNum=0)
3512
+    {
3513
+        $sql  = "SELECT t.localtax1, t.localtax2";
3514
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3515
+        $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3516
+        $sql .= " AND t.active = 1";
3517
+        if (empty($localTaxNum))   $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3518
+        elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
3519
+        elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
3520
+
3521
+        dol_syslog("useLocalTax", LOG_DEBUG);
3522
+        $resql=$this->db->query($sql);
3523
+        if ($resql)
3524
+        {
3525
+                return ($this->db->num_rows($resql) > 0);
3526
+        }
3527
+        else return false;
3528
+    }
3529
+
3530
+    /**
3531
+     *  Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
3532
+     *
3533
+     *  @return		boolean					true or false
3534
+     */
3535
+    function useNPR()
3536
+    {
3537
+        $sql  = "SELECT t.rowid";
3538
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
3539
+        $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3540
+        $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
3541
+
3542
+        dol_syslog("useNPR", LOG_DEBUG);
3543
+        $resql=$this->db->query($sql);
3544
+        if ($resql)
3545
+        {
3546
+            return ($this->db->num_rows($resql) > 0);
3547
+        }
3548
+        else return false;
3549
+    }
3550
+
3551
+    /**
3552
+     *  Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
3553
+     *
3554
+     *  @return		boolean			true or false
3555
+     */
3556
+    function useRevenueStamp()
3557
+    {
3558
+        $sql  = "SELECT COUNT(*) as nb";
3559
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
3560
+        $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
3561
+        $sql .= " AND r.active = 1";
3562
+
3563
+        dol_syslog("useRevenueStamp", LOG_DEBUG);
3564
+        $resql=$this->db->query($sql);
3565
+        if ($resql)
3566
+        {
3567
+            $obj=$this->db->fetch_object($resql);
3568
+                return (($obj->nb > 0)?true:false);
3569
+        }
3570
+        else
3571
+        {
3572
+            $this->error=$this->db->lasterror();
3573
+            return false;
3574
+        }
3575
+    }
3576
+
3577
+    /**
3578
+     *	Return prostect level
3579
+     *
3580
+     *  @return     string        Libelle
3581
+     */
3582
+    function getLibProspLevel()
3583
+    {
3584
+        return $this->LibProspLevel($this->fk_prospectlevel);
3585
+    }
3586 3586
 
3587 3587
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3588
-	/**
3589
-	 *  Return label of prospect level
3590
-	 *
3591
-	 *  @param	int		$fk_prospectlevel   	Prospect level
3592
-	 *  @return string        					label of level
3593
-	 */
3594
-	function LibProspLevel($fk_prospectlevel)
3595
-	{
3588
+    /**
3589
+     *  Return label of prospect level
3590
+     *
3591
+     *  @param	int		$fk_prospectlevel   	Prospect level
3592
+     *  @return string        					label of level
3593
+     */
3594
+    function LibProspLevel($fk_prospectlevel)
3595
+    {
3596 3596
         // phpcs:enable
3597
-		global $langs;
3597
+        global $langs;
3598 3598
 
3599
-		$lib=$langs->trans("ProspectLevel".$fk_prospectlevel);
3600
-		// If lib not found in language file, we get label from cache/databse
3601
-		if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
3602
-		{
3603
-			$lib=$langs->getLabelFromKey($this->db,$fk_prospectlevel,'c_prospectlevel','code','label');
3604
-		}
3605
-		return $lib;
3606
-	}
3599
+        $lib=$langs->trans("ProspectLevel".$fk_prospectlevel);
3600
+        // If lib not found in language file, we get label from cache/databse
3601
+        if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
3602
+        {
3603
+            $lib=$langs->getLabelFromKey($this->db,$fk_prospectlevel,'c_prospectlevel','code','label');
3604
+        }
3605
+        return $lib;
3606
+    }
3607 3607
 
3608 3608
 
3609 3609
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3610
-	/**
3611
-	 *  Set prospect level
3612
-	 *
3613
-	 *  @param  User	$user		Utilisateur qui definie la remise
3614
-	 *	@return	int					<0 if KO, >0 if OK
3615
-	 * @deprecated Use update function instead
3616
-	 */
3617
-	function set_prospect_level(User $user)
3618
-	{
3610
+    /**
3611
+     *  Set prospect level
3612
+     *
3613
+     *  @param  User	$user		Utilisateur qui definie la remise
3614
+     *	@return	int					<0 if KO, >0 if OK
3615
+     * @deprecated Use update function instead
3616
+     */
3617
+    function set_prospect_level(User $user)
3618
+    {
3619 3619
         // phpcs:enable
3620
-		return $this->update($this->id, $user);
3621
-	}
3622
-
3623
-	/**
3624
-	 *  Return status of prospect
3625
-	 *
3626
-	 *  @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
3627
-	 *  @param	string	$label		Label to use for status for added status
3628
-	 *  @return string        		Libelle
3629
-	 */
3630
-	function getLibProspCommStatut($mode=0, $label='')
3631
-	{
3632
-		return $this->LibProspCommStatut($this->stcomm_id, $mode, $label);
3633
-	}
3620
+        return $this->update($this->id, $user);
3621
+    }
3622
+
3623
+    /**
3624
+     *  Return status of prospect
3625
+     *
3626
+     *  @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
3627
+     *  @param	string	$label		Label to use for status for added status
3628
+     *  @return string        		Libelle
3629
+     */
3630
+    function getLibProspCommStatut($mode=0, $label='')
3631
+    {
3632
+        return $this->LibProspCommStatut($this->stcomm_id, $mode, $label);
3633
+    }
3634 3634
 
3635 3635
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3636
-	/**
3637
-	 *  Return label of a given status
3638
-	 *
3639
-	 *  @param	int|string	$statut        	Id or code for prospection status
3640
-	 *  @param  int			$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
3641
-	 *  @param	string		$label			Label to use for status for added status
3642
-	 *  @return string       	 			Libelle du statut
3643
-	 */
3644
-	function LibProspCommStatut($statut, $mode=0, $label='')
3645
-	{
3636
+    /**
3637
+     *  Return label of a given status
3638
+     *
3639
+     *  @param	int|string	$statut        	Id or code for prospection status
3640
+     *  @param  int			$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
3641
+     *  @param	string		$label			Label to use for status for added status
3642
+     *  @return string       	 			Libelle du statut
3643
+     */
3644
+    function LibProspCommStatut($statut, $mode=0, $label='')
3645
+    {
3646 3646
         // phpcs:enable
3647
-		global $langs;
3648
-		$langs->load('customers');
3649
-
3650
-		if ($mode == 2)
3651
-		{
3652
-			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3653
-			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3654
-			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3655
-			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3656
-			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3657
-			else
3658
-			{
3659
-				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3660
-			}
3661
-		}
3662
-		if ($mode == 3)
3663
-		{
3664
-			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1);
3665
-			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
3666
-			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1);
3667
-			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2);
3668
-			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3);
3669
-			else
3670
-			{
3671
-				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0);
3672
-			}
3673
-		}
3674
-		if ($mode == 4)
3675
-		{
3676
-			if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3677
-			elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3678
-			elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3679
-			elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3680
-			elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3681
-			else
3682
-			{
3683
-				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3684
-			}
3685
-		}
3686
-
3687
-		return "Error, mode/status not found";
3688
-	}
3647
+        global $langs;
3648
+        $langs->load('customers');
3649
+
3650
+        if ($mode == 2)
3651
+        {
3652
+            if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3653
+            elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3654
+            elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3655
+            elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3656
+            elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3657
+            else
3658
+            {
3659
+                return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3660
+            }
3661
+        }
3662
+        if ($mode == 3)
3663
+        {
3664
+            if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1);
3665
+            elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
3666
+            elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1);
3667
+            elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2);
3668
+            elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3);
3669
+            else
3670
+            {
3671
+                return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0);
3672
+            }
3673
+        }
3674
+        if ($mode == 4)
3675
+        {
3676
+            if ($statut == '-1' || $statut == 'ST_NO')         return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
3677
+            elseif ($statut ==  '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
3678
+            elseif ($statut ==  '1' || $statut == 'ST_TODO')  return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
3679
+            elseif ($statut ==  '2' || $statut == 'ST_PEND')  return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
3680
+            elseif ($statut ==  '3' || $statut == 'ST_DONE')  return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
3681
+            else
3682
+            {
3683
+                return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
3684
+            }
3685
+        }
3686
+
3687
+        return "Error, mode/status not found";
3688
+    }
3689 3689
 
3690 3690
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3691
-	/**
3692
-	 *  Set outstanding value
3693
-	 *
3694
-	 *  @param  User	$user		User making change
3695
-	 *	@return	int					<0 if KO, >0 if OK
3696
-	 * @deprecated Use update function instead
3697
-	 */
3698
-	function set_OutstandingBill(User $user)
3699
-	{
3691
+    /**
3692
+     *  Set outstanding value
3693
+     *
3694
+     *  @param  User	$user		User making change
3695
+     *	@return	int					<0 if KO, >0 if OK
3696
+     * @deprecated Use update function instead
3697
+     */
3698
+    function set_OutstandingBill(User $user)
3699
+    {
3700 3700
         // phpcs:enable
3701
-		return $this->update($this->id, $user);
3702
-	}
3703
-
3704
-	/**
3705
-	 *  Return amount of order not paid and total
3706
-	 *
3707
-	 *  @param     string      $mode    'customer' or 'supplier'
3708
-	 *  @return    array				array('opened'=>Amount, 'total'=>Total amount)
3709
-	 */
3710
-	function getOutstandingProposals($mode='customer')
3711
-	{
3712
-		$table='propal';
3713
-		if ($mode == 'supplier') $table = 'supplier_proposal';
3714
-
3715
-		$sql  = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3716
-		$sql .= " WHERE fk_soc = ". $this->id;
3717
-		if ($mode == 'supplier') {
3718
-			$sql .= " AND entity IN (".getEntity('supplier_proposal').")";
3719
-		} else {
3720
-			$sql .= " AND entity IN (".getEntity('propal').")";
3721
-		}
3722
-
3723
-		dol_syslog("getOutstandingProposals", LOG_DEBUG);
3724
-		$resql=$this->db->query($sql);
3725
-		if ($resql)
3726
-		{
3727
-			$outstandingOpened = 0;
3728
-			$outstandingTotal = 0;
3729
-			$outstandingTotalIncTax = 0;
3730
-			while($obj=$this->db->fetch_object($resql)) {
3731
-				$outstandingTotal+= $obj->total_ht;
3732
-				$outstandingTotalIncTax+= $obj->total_ttc;
3733
-				if ($obj->fk_statut != 0)    // Not a draft
3734
-				{
3735
-					$outstandingOpened+=$obj->total_ttc;
3736
-				}
3737
-			}
3738
-			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);	// 'opened' is 'incl taxes'
3739
-		}
3740
-		else
3741
-			return array();
3742
-	}
3743
-
3744
-	/**
3745
-	 *  Return amount of order not paid and total
3746
-	 *
3747
-	 *  @param     string      $mode    'customer' or 'supplier'
3748
-	 *  @return		array				array('opened'=>Amount, 'total'=>Total amount)
3749
-	 */
3750
-	function getOutstandingOrders($mode='customer')
3751
-	{
3752
-		$table='commande';
3753
-		if ($mode == 'supplier') $table = 'commande_fournisseur';
3754
-
3755
-		$sql  = "SELECT rowid, total_ht, total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3756
-		$sql .= " WHERE fk_soc = ". $this->id;
3757
-		if ($mode == 'supplier') {
3758
-			$sql .= " AND entity IN (".getEntity('supplier_order').")";
3759
-		} else {
3760
-			$sql .= " AND entity IN (".getEntity('commande').")";
3761
-		}
3762
-
3763
-		dol_syslog("getOutstandingOrders", LOG_DEBUG);
3764
-		$resql=$this->db->query($sql);
3765
-		if ($resql)
3766
-		{
3767
-			$outstandingOpened = 0;
3768
-			$outstandingTotal = 0;
3769
-			$outstandingTotalIncTax = 0;
3770
-			while($obj=$this->db->fetch_object($resql)) {
3771
-				$outstandingTotal+= $obj->total_ht;
3772
-				$outstandingTotalIncTax+= $obj->total_ttc;
3773
-				if ($obj->fk_statut != 0)    // Not a draft
3774
-				{
3775
-					$outstandingOpened+=$obj->total_ttc;
3776
-				}
3777
-			}
3778
-			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);	// 'opened' is 'incl taxes'
3779
-		}
3780
-		else
3781
-			return array();
3782
-	}
3783
-
3784
-	/**
3785
-	 *  Return amount of bill not paid and total
3786
-	 *
3787
-	 *  @param     string      $mode    'customer' or 'supplier'
3788
-	 *  @return		array				array('opened'=>Amount, 'total'=>Total amount)
3789
-	 */
3790
-	function getOutstandingBills($mode='customer')
3791
-	{
3792
-		$table='facture';
3793
-		if ($mode == 'supplier') $table = 'facture_fourn';
3794
-
3795
-		/* Accurate value of remain to pay is to sum remaintopay for each invoice
3701
+        return $this->update($this->id, $user);
3702
+    }
3703
+
3704
+    /**
3705
+     *  Return amount of order not paid and total
3706
+     *
3707
+     *  @param     string      $mode    'customer' or 'supplier'
3708
+     *  @return    array				array('opened'=>Amount, 'total'=>Total amount)
3709
+     */
3710
+    function getOutstandingProposals($mode='customer')
3711
+    {
3712
+        $table='propal';
3713
+        if ($mode == 'supplier') $table = 'supplier_proposal';
3714
+
3715
+        $sql  = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3716
+        $sql .= " WHERE fk_soc = ". $this->id;
3717
+        if ($mode == 'supplier') {
3718
+            $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
3719
+        } else {
3720
+            $sql .= " AND entity IN (".getEntity('propal').")";
3721
+        }
3722
+
3723
+        dol_syslog("getOutstandingProposals", LOG_DEBUG);
3724
+        $resql=$this->db->query($sql);
3725
+        if ($resql)
3726
+        {
3727
+            $outstandingOpened = 0;
3728
+            $outstandingTotal = 0;
3729
+            $outstandingTotalIncTax = 0;
3730
+            while($obj=$this->db->fetch_object($resql)) {
3731
+                $outstandingTotal+= $obj->total_ht;
3732
+                $outstandingTotalIncTax+= $obj->total_ttc;
3733
+                if ($obj->fk_statut != 0)    // Not a draft
3734
+                {
3735
+                    $outstandingOpened+=$obj->total_ttc;
3736
+                }
3737
+            }
3738
+            return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);	// 'opened' is 'incl taxes'
3739
+        }
3740
+        else
3741
+            return array();
3742
+    }
3743
+
3744
+    /**
3745
+     *  Return amount of order not paid and total
3746
+     *
3747
+     *  @param     string      $mode    'customer' or 'supplier'
3748
+     *  @return		array				array('opened'=>Amount, 'total'=>Total amount)
3749
+     */
3750
+    function getOutstandingOrders($mode='customer')
3751
+    {
3752
+        $table='commande';
3753
+        if ($mode == 'supplier') $table = 'commande_fournisseur';
3754
+
3755
+        $sql  = "SELECT rowid, total_ht, total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
3756
+        $sql .= " WHERE fk_soc = ". $this->id;
3757
+        if ($mode == 'supplier') {
3758
+            $sql .= " AND entity IN (".getEntity('supplier_order').")";
3759
+        } else {
3760
+            $sql .= " AND entity IN (".getEntity('commande').")";
3761
+        }
3762
+
3763
+        dol_syslog("getOutstandingOrders", LOG_DEBUG);
3764
+        $resql=$this->db->query($sql);
3765
+        if ($resql)
3766
+        {
3767
+            $outstandingOpened = 0;
3768
+            $outstandingTotal = 0;
3769
+            $outstandingTotalIncTax = 0;
3770
+            while($obj=$this->db->fetch_object($resql)) {
3771
+                $outstandingTotal+= $obj->total_ht;
3772
+                $outstandingTotalIncTax+= $obj->total_ttc;
3773
+                if ($obj->fk_statut != 0)    // Not a draft
3774
+                {
3775
+                    $outstandingOpened+=$obj->total_ttc;
3776
+                }
3777
+            }
3778
+            return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);	// 'opened' is 'incl taxes'
3779
+        }
3780
+        else
3781
+            return array();
3782
+    }
3783
+
3784
+    /**
3785
+     *  Return amount of bill not paid and total
3786
+     *
3787
+     *  @param     string      $mode    'customer' or 'supplier'
3788
+     *  @return		array				array('opened'=>Amount, 'total'=>Total amount)
3789
+     */
3790
+    function getOutstandingBills($mode='customer')
3791
+    {
3792
+        $table='facture';
3793
+        if ($mode == 'supplier') $table = 'facture_fourn';
3794
+
3795
+        /* Accurate value of remain to pay is to sum remaintopay for each invoice
3796 3796
 		 $paiement = $invoice->getSommePaiement();
3797 3797
 		 $creditnotes=$invoice->getSumCreditNotesUsed();
3798 3798
 		 $deposits=$invoice->getSumDepositsUsed();
3799 3799
 		 $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3800 3800
 		 $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3801 3801
 		 */
3802
-		if ($mode == 'supplier') $sql  = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3803
-		else $sql  = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3804
-		$sql .= " WHERE fk_soc = ". $this->id;
3805
-		if ($mode == 'supplier') {
3806
-			$sql .= " AND entity IN (".getEntity('facture_fourn').")";
3807
-		} else {
3808
-			$sql .= " AND entity IN (".getEntity('invoice').")";
3809
-		}
3810
-
3811
-		dol_syslog("getOutstandingBills", LOG_DEBUG);
3812
-		$resql=$this->db->query($sql);
3813
-		if ($resql)
3814
-		{
3815
-			$outstandingOpened = 0;
3816
-			$outstandingTotal = 0;
3817
-			$outstandingTotalIncTax = 0;
3818
-			if ($mode == 'supplier')
3819
-			{
3820
-				require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
3821
-				$tmpobject=new FactureFournisseur($this->db);
3822
-			}
3823
-			else
3824
-			{
3825
-				require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3826
-				$tmpobject=new Facture($this->db);
3827
-			}
3828
-			while($obj=$this->db->fetch_object($resql)) {
3829
-				$tmpobject->id=$obj->rowid;
3830
-				if ($obj->fk_statut != 0                                           // Not a draft
3831
-					&& ! ($obj->fk_statut == 3 && $obj->close_code == 'replaced')  // Not a replaced invoice
3832
-					)
3833
-				{
3834
-					$outstandingTotal+= $obj->total_ht;
3835
-					$outstandingTotalIncTax+= $obj->total_ttc;
3836
-				}
3837
-				if ($obj->paye == 0
3838
-					&& $obj->fk_statut != 0    // Not a draft
3839
-					&& $obj->fk_statut != 3	   // Not abandonned
3840
-					&& $obj->fk_statut != 2)   // Not classified as paid
3841
-				//$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3842
-				{
3843
-					$paiement = $tmpobject->getSommePaiement();
3844
-					$creditnotes = $tmpobject->getSumCreditNotesUsed();
3845
-					$deposits = $tmpobject->getSumDepositsUsed();
3846
-					$outstandingOpened+=$obj->total_ttc - $paiement - $creditnotes - $deposits;
3847
-				}
3848
-			}
3849
-			return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);	// 'opened' is 'incl taxes'
3850
-		}
3851
-		else
3852
-		{
3853
-			return array();
3854
-		}
3855
-	}
3802
+        if ($mode == 'supplier') $sql  = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3803
+        else $sql  = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
3804
+        $sql .= " WHERE fk_soc = ". $this->id;
3805
+        if ($mode == 'supplier') {
3806
+            $sql .= " AND entity IN (".getEntity('facture_fourn').")";
3807
+        } else {
3808
+            $sql .= " AND entity IN (".getEntity('invoice').")";
3809
+        }
3810
+
3811
+        dol_syslog("getOutstandingBills", LOG_DEBUG);
3812
+        $resql=$this->db->query($sql);
3813
+        if ($resql)
3814
+        {
3815
+            $outstandingOpened = 0;
3816
+            $outstandingTotal = 0;
3817
+            $outstandingTotalIncTax = 0;
3818
+            if ($mode == 'supplier')
3819
+            {
3820
+                require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
3821
+                $tmpobject=new FactureFournisseur($this->db);
3822
+            }
3823
+            else
3824
+            {
3825
+                require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3826
+                $tmpobject=new Facture($this->db);
3827
+            }
3828
+            while($obj=$this->db->fetch_object($resql)) {
3829
+                $tmpobject->id=$obj->rowid;
3830
+                if ($obj->fk_statut != 0                                           // Not a draft
3831
+                    && ! ($obj->fk_statut == 3 && $obj->close_code == 'replaced')  // Not a replaced invoice
3832
+                    )
3833
+                {
3834
+                    $outstandingTotal+= $obj->total_ht;
3835
+                    $outstandingTotalIncTax+= $obj->total_ttc;
3836
+                }
3837
+                if ($obj->paye == 0
3838
+                    && $obj->fk_statut != 0    // Not a draft
3839
+                    && $obj->fk_statut != 3	   // Not abandonned
3840
+                    && $obj->fk_statut != 2)   // Not classified as paid
3841
+                //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3842
+                {
3843
+                    $paiement = $tmpobject->getSommePaiement();
3844
+                    $creditnotes = $tmpobject->getSumCreditNotesUsed();
3845
+                    $deposits = $tmpobject->getSumDepositsUsed();
3846
+                    $outstandingOpened+=$obj->total_ttc - $paiement - $creditnotes - $deposits;
3847
+                }
3848
+            }
3849
+            return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax);	// 'opened' is 'incl taxes'
3850
+        }
3851
+        else
3852
+        {
3853
+            return array();
3854
+        }
3855
+    }
3856 3856
 
3857 3857
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3858
-	/**
3859
-	 *  Return amount of bill not paid
3860
-	 *
3861
-	 *  @return		int				Amount in debt for thirdparty
3862
-	 *  @deprecated
3863
-	 *  @see getOutstandingBills()
3864
-	 */
3865
-	function get_OutstandingBill()
3866
-	{
3858
+    /**
3859
+     *  Return amount of bill not paid
3860
+     *
3861
+     *  @return		int				Amount in debt for thirdparty
3862
+     *  @deprecated
3863
+     *  @see getOutstandingBills()
3864
+     */
3865
+    function get_OutstandingBill()
3866
+    {
3867 3867
         // phpcs:enable
3868
-		/* Accurate value of remain to pay is to sum remaintopay for each invoice
3868
+        /* Accurate value of remain to pay is to sum remaintopay for each invoice
3869 3869
 	     $paiement = $invoice->getSommePaiement();
3870 3870
 	     $creditnotes=$invoice->getSumCreditNotesUsed();
3871 3871
 	     $deposits=$invoice->getSumDepositsUsed();
3872 3872
 	     $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3873 3873
 	     $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3874 3874
 	     */
3875
-		$sql  = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
3876
-		$sql .= " WHERE fk_soc = ". $this->id;
3877
-		$sql .= " AND paye = 0";
3878
-		$sql .= " AND fk_statut <> 0";	// Not a draft
3879
-		//$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3880
-		$sql .= " AND fk_statut <> 3";		// Not abandonned
3881
-		$sql .= " AND fk_statut <> 2";		// Not clasified as paid
3882
-
3883
-		dol_syslog("get_OutstandingBill", LOG_DEBUG);
3884
-		$resql=$this->db->query($sql);
3885
-		if ($resql)
3886
-		{
3887
-			$outstandingAmount = 0;
3888
-			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3889
-			$tmpobject=new Facture($this->db);
3890
-			while($obj=$this->db->fetch_object($resql)) {
3891
-				$tmpobject->id=$obj->rowid;
3892
-				$paiement = $tmpobject->getSommePaiement();
3893
-				$creditnotes = $tmpobject->getSumCreditNotesUsed();
3894
-				$deposits = $tmpobject->getSumDepositsUsed();
3895
-				$outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
3896
-			}
3897
-			return $outstandingAmount;
3898
-		}
3899
-		else
3900
-			return 0;
3901
-	}
3902
-
3903
-	/**
3904
-	 * Return label of status customer is prospect/customer
3905
-	 *
3906
-	 * @return   string        	Label
3907
-	 */
3908
-	function getLibCustProspStatut()
3909
-	{
3910
-		return $this->LibCustProspStatut($this->client);
3911
-	}
3875
+        $sql  = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
3876
+        $sql .= " WHERE fk_soc = ". $this->id;
3877
+        $sql .= " AND paye = 0";
3878
+        $sql .= " AND fk_statut <> 0";	// Not a draft
3879
+        //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3880
+        $sql .= " AND fk_statut <> 3";		// Not abandonned
3881
+        $sql .= " AND fk_statut <> 2";		// Not clasified as paid
3882
+
3883
+        dol_syslog("get_OutstandingBill", LOG_DEBUG);
3884
+        $resql=$this->db->query($sql);
3885
+        if ($resql)
3886
+        {
3887
+            $outstandingAmount = 0;
3888
+            require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
3889
+            $tmpobject=new Facture($this->db);
3890
+            while($obj=$this->db->fetch_object($resql)) {
3891
+                $tmpobject->id=$obj->rowid;
3892
+                $paiement = $tmpobject->getSommePaiement();
3893
+                $creditnotes = $tmpobject->getSumCreditNotesUsed();
3894
+                $deposits = $tmpobject->getSumDepositsUsed();
3895
+                $outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
3896
+            }
3897
+            return $outstandingAmount;
3898
+        }
3899
+        else
3900
+            return 0;
3901
+    }
3902
+
3903
+    /**
3904
+     * Return label of status customer is prospect/customer
3905
+     *
3906
+     * @return   string        	Label
3907
+     */
3908
+    function getLibCustProspStatut()
3909
+    {
3910
+        return $this->LibCustProspStatut($this->client);
3911
+    }
3912 3912
 
3913 3913
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3914
-	/**
3915
-	 *  Renvoi le libelle d'un statut donne
3916
-	 *
3917
-	 *  @param	int		$statut         Id statut
3918
-	 *  @return	string          		Libelle du statut
3919
-	 */
3920
-	function LibCustProspStatut($statut)
3921
-	{
3914
+    /**
3915
+     *  Renvoi le libelle d'un statut donne
3916
+     *
3917
+     *  @param	int		$statut         Id statut
3918
+     *  @return	string          		Libelle du statut
3919
+     */
3920
+    function LibCustProspStatut($statut)
3921
+    {
3922 3922
         // phpcs:enable
3923
-		global $langs;
3924
-		$langs->load('companies');
3925
-
3926
-		if ($statut==0) return $langs->trans("NorProspectNorCustomer");
3927
-		if ($statut==1) return $langs->trans("Customer");
3928
-		if ($statut==2) return $langs->trans("Prospect");
3929
-		if ($statut==3) return $langs->trans("ProspectCustomer");
3930
-	}
3931
-
3932
-
3933
-	/**
3934
-	 *  Create a document onto disk according to template module.
3935
-	 *
3936
-	 *	@param	string		$modele			Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
3937
-	 *	@param	Translate	$outputlangs	objet lang a utiliser pour traduction
3938
-	 *  @param  int			$hidedetails    Hide details of lines
3939
-	 *  @param  int			$hidedesc       Hide description
3940
-	 *  @param  int			$hideref        Hide ref
3941
-	 *  @param  null|array  $moreparams     Array to provide more information
3942
-	 *	@return int        					<0 if KO, >0 if OK
3943
-	 */
3944
-	public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
3945
-	{
3946
-		global $conf,$user,$langs;
3947
-
3948
-		if (! empty($moreparams) && ! empty($moreparams['use_companybankid']))
3949
-		{
3950
-			$modelpath = "core/modules/bank/doc/";
3951
-
3952
-			include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3953
-			$companybankaccount = new CompanyBankAccount($this->db);
3954
-			$result = $companybankaccount->fetch($moreparams['use_companybankid']);
3955
-			if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3956
-			$result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3957
-		}
3958
-		else
3959
-		{
3960
-			// Positionne le modele sur le nom du modele a utiliser
3961
-			if (! dol_strlen($modele))
3962
-			{
3963
-				if (! empty($conf->global->COMPANY_ADDON_PDF))
3964
-				{
3965
-					$modele = $conf->global->COMPANY_ADDON_PDF;
3966
-				}
3967
-				else
3968
-				{
3969
-					print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
3970
-					return 0;
3971
-				}
3972
-			}
3973
-
3974
-			$modelpath = "core/modules/societe/doc/";
3975
-
3976
-			$result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3977
-		}
3978
-
3979
-		return $result;
3980
-	}
3981
-
3982
-
3983
-	/**
3984
-	 * Sets object to supplied categories.
3985
-	 *
3986
-	 * Deletes object from existing categories not supplied.
3987
-	 * Adds it to non existing supplied categories.
3988
-	 * Existing categories are left untouch.
3989
-	 *
3990
-	 * @param 	int[]|int 	$categories 	Category ID or array of Categories IDs
3991
-	 * @param 	string 		$type 			Category type ('customer' or 'supplier')
3992
-	 * @return	int							<0 if KO, >0 if OK
3993
-	 */
3994
-	public function setCategories($categories, $type)
3995
-	{
3996
-		require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3997
-
3998
-		// Decode type
3999
-		if ($type == 'customer') {
4000
-			$type_id = Categorie::TYPE_CUSTOMER;
4001
-			$type_text = 'customer';
4002
-		} elseif ($type == 'supplier') {
4003
-			$type_id = Categorie::TYPE_SUPPLIER;
4004
-			$type_text = 'supplier';
4005
-		} else {
4006
-			dol_syslog(__METHOD__ . ': Type ' . $type .  'is an unknown company category type. Done nothing.', LOG_ERR);
4007
-			return -1;
4008
-		}
4009
-
4010
-		// Handle single category
4011
-		if (!is_array($categories)) {
4012
-			$categories = array($categories);
4013
-		}
4014
-
4015
-		// Get current categories
4016
-		$c = new Categorie($this->db);
4017
-		$existing = $c->containing($this->id, $type_id, 'id');
4018
-
4019
-		// Diff
4020
-		if (is_array($existing)) {
4021
-			$to_del = array_diff($existing, $categories);
4022
-			$to_add = array_diff($categories, $existing);
4023
-		} else {
4024
-			$to_del = array(); // Nothing to delete
4025
-			$to_add = $categories;
4026
-		}
4027
-
4028
-		$error = 0;
4029
-
4030
-		// Process
4031
-		foreach ($to_del as $del) {
4032
-			if ($c->fetch($del) > 0) {
4033
-				$c->del_type($this, $type_text);
4034
-			}
4035
-		}
4036
-		foreach ($to_add as $add) {
4037
-			if ($c->fetch($add) > 0)
4038
-			{
4039
-				$result = $c->add_type($this, $type_text);
4040
-				if ($result < 0)
4041
-				{
4042
-					$error++;
4043
-					$this->error = $c->error;
4044
-					$this->errors = $c->errors;
4045
-					break;
4046
-				}
4047
-			}
4048
-		}
4049
-
4050
-		return $error ? -1 : 1;
4051
-	}
4052
-
4053
-	/**
4054
-	 * Sets sales representatives of the thirdparty
4055
-	 *
4056
-	 * @param 	int[]|int 	$salesrep	 	User ID or array of user IDs
4057
-	 * @return	int							<0 if KO, >0 if OK
4058
-	 */
4059
-	public function setSalesRep($salesrep)
4060
-	{
4061
-		global $user;
4062
-
4063
-		// Handle single user
4064
-		if (!is_array($salesrep)) {
4065
-			$salesrep = array($salesrep);
4066
-		}
4067
-
4068
-		// Get current users
4069
-		$existing = $this->getSalesRepresentatives($user, 1);
4070
-
4071
-		// Diff
4072
-		if (is_array($existing)) {
4073
-			$to_del = array_diff($existing, $salesrep);
4074
-			$to_add = array_diff($salesrep, $existing);
4075
-		} else {
4076
-			$to_del = array(); // Nothing to delete
4077
-			$to_add = $salesrep;
4078
-		}
4079
-
4080
-		$error = 0;
4081
-
4082
-		// Process
4083
-		foreach ($to_del as $del) {
4084
-			$this->del_commercial($user, $del);
4085
-		}
4086
-		foreach ($to_add as $add) {
4087
-			$result = $this->add_commercial($user, $add);
4088
-			if ($result < 0)
4089
-			{
4090
-				$error++;
4091
-				$this->error = $c->error;
4092
-				$this->errors = $c->errors;
4093
-				break;
4094
-			}
4095
-		}
4096
-
4097
-		return $error ? -1 : 1;
4098
-	}
4099
-
4100
-
4101
-	/**
4102
-	 * Function used to replace a thirdparty id with another one.
4103
-	 * It must be used within a transaction to avoid trouble
4104
-	 *
4105
-	 * @param 	DoliDB 	$db 		Database handler
4106
-	 * @param 	int 	$origin_id 	Old thirdparty id (will be removed)
4107
-	 * @param 	int 	$dest_id 	New thirdparty id
4108
-	 * @return 	bool				True if success, False if error
4109
-	 */
4110
-	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
4111
-	{
4112
-		if ($origin_id == $dest_id)
4113
-		{
4114
-			dol_syslog('Error: Try to merge a thirdparty into itself');
4115
-			return false;
4116
-		}
4117
-
4118
-		/**
4119
-		 * Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some to avoid duplicate.
4120
-		 * Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
4121
-		 */
4122
-		$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4123
-		$sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
4124
-		$sql .= ' SELECT fk_user ';
4125
-		$sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4126
-		$sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
3923
+        global $langs;
3924
+        $langs->load('companies');
4127 3925
 
4128
-		$query = $db->query($sql);
3926
+        if ($statut==0) return $langs->trans("NorProspectNorCustomer");
3927
+        if ($statut==1) return $langs->trans("Customer");
3928
+        if ($statut==2) return $langs->trans("Prospect");
3929
+        if ($statut==3) return $langs->trans("ProspectCustomer");
3930
+    }
4129 3931
 
4130
-		while ($result = $db->fetch_object($query)) {
4131
-			$db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$result->rowid);
4132
-		}
4133 3932
 
4134
-		/**
4135
-		 * llx_societe_extrafields table must not be here because we don't care about the old thirdparty data
4136
-		 * Do not include llx_societe because it will be replaced later
4137
-		 */
4138
-		$tables = array(
4139
-			'societe_address',
4140
-			'societe_commerciaux',
4141
-			'societe_log',
4142
-			'societe_prices',
4143
-			'societe_remise',
4144
-			'societe_remise_except',
4145
-			'societe_rib'
4146
-		);
4147
-
4148
-		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
4149
-	}
3933
+    /**
3934
+     *  Create a document onto disk according to template module.
3935
+     *
3936
+     *	@param	string		$modele			Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
3937
+     *	@param	Translate	$outputlangs	objet lang a utiliser pour traduction
3938
+     *  @param  int			$hidedetails    Hide details of lines
3939
+     *  @param  int			$hidedesc       Hide description
3940
+     *  @param  int			$hideref        Hide ref
3941
+     *  @param  null|array  $moreparams     Array to provide more information
3942
+     *	@return int        					<0 if KO, >0 if OK
3943
+     */
3944
+    public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
3945
+    {
3946
+        global $conf,$user,$langs;
3947
+
3948
+        if (! empty($moreparams) && ! empty($moreparams['use_companybankid']))
3949
+        {
3950
+            $modelpath = "core/modules/bank/doc/";
3951
+
3952
+            include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
3953
+            $companybankaccount = new CompanyBankAccount($this->db);
3954
+            $result = $companybankaccount->fetch($moreparams['use_companybankid']);
3955
+            if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3956
+            $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3957
+        }
3958
+        else
3959
+        {
3960
+            // Positionne le modele sur le nom du modele a utiliser
3961
+            if (! dol_strlen($modele))
3962
+            {
3963
+                if (! empty($conf->global->COMPANY_ADDON_PDF))
3964
+                {
3965
+                    $modele = $conf->global->COMPANY_ADDON_PDF;
3966
+                }
3967
+                else
3968
+                {
3969
+                    print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
3970
+                    return 0;
3971
+                }
3972
+            }
3973
+
3974
+            $modelpath = "core/modules/societe/doc/";
3975
+
3976
+            $result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3977
+        }
3978
+
3979
+        return $result;
3980
+    }
3981
+
3982
+
3983
+    /**
3984
+     * Sets object to supplied categories.
3985
+     *
3986
+     * Deletes object from existing categories not supplied.
3987
+     * Adds it to non existing supplied categories.
3988
+     * Existing categories are left untouch.
3989
+     *
3990
+     * @param 	int[]|int 	$categories 	Category ID or array of Categories IDs
3991
+     * @param 	string 		$type 			Category type ('customer' or 'supplier')
3992
+     * @return	int							<0 if KO, >0 if OK
3993
+     */
3994
+    public function setCategories($categories, $type)
3995
+    {
3996
+        require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3997
+
3998
+        // Decode type
3999
+        if ($type == 'customer') {
4000
+            $type_id = Categorie::TYPE_CUSTOMER;
4001
+            $type_text = 'customer';
4002
+        } elseif ($type == 'supplier') {
4003
+            $type_id = Categorie::TYPE_SUPPLIER;
4004
+            $type_text = 'supplier';
4005
+        } else {
4006
+            dol_syslog(__METHOD__ . ': Type ' . $type .  'is an unknown company category type. Done nothing.', LOG_ERR);
4007
+            return -1;
4008
+        }
4009
+
4010
+        // Handle single category
4011
+        if (!is_array($categories)) {
4012
+            $categories = array($categories);
4013
+        }
4014
+
4015
+        // Get current categories
4016
+        $c = new Categorie($this->db);
4017
+        $existing = $c->containing($this->id, $type_id, 'id');
4018
+
4019
+        // Diff
4020
+        if (is_array($existing)) {
4021
+            $to_del = array_diff($existing, $categories);
4022
+            $to_add = array_diff($categories, $existing);
4023
+        } else {
4024
+            $to_del = array(); // Nothing to delete
4025
+            $to_add = $categories;
4026
+        }
4027
+
4028
+        $error = 0;
4029
+
4030
+        // Process
4031
+        foreach ($to_del as $del) {
4032
+            if ($c->fetch($del) > 0) {
4033
+                $c->del_type($this, $type_text);
4034
+            }
4035
+        }
4036
+        foreach ($to_add as $add) {
4037
+            if ($c->fetch($add) > 0)
4038
+            {
4039
+                $result = $c->add_type($this, $type_text);
4040
+                if ($result < 0)
4041
+                {
4042
+                    $error++;
4043
+                    $this->error = $c->error;
4044
+                    $this->errors = $c->errors;
4045
+                    break;
4046
+                }
4047
+            }
4048
+        }
4049
+
4050
+        return $error ? -1 : 1;
4051
+    }
4052
+
4053
+    /**
4054
+     * Sets sales representatives of the thirdparty
4055
+     *
4056
+     * @param 	int[]|int 	$salesrep	 	User ID or array of user IDs
4057
+     * @return	int							<0 if KO, >0 if OK
4058
+     */
4059
+    public function setSalesRep($salesrep)
4060
+    {
4061
+        global $user;
4062
+
4063
+        // Handle single user
4064
+        if (!is_array($salesrep)) {
4065
+            $salesrep = array($salesrep);
4066
+        }
4067
+
4068
+        // Get current users
4069
+        $existing = $this->getSalesRepresentatives($user, 1);
4070
+
4071
+        // Diff
4072
+        if (is_array($existing)) {
4073
+            $to_del = array_diff($existing, $salesrep);
4074
+            $to_add = array_diff($salesrep, $existing);
4075
+        } else {
4076
+            $to_del = array(); // Nothing to delete
4077
+            $to_add = $salesrep;
4078
+        }
4079
+
4080
+        $error = 0;
4081
+
4082
+        // Process
4083
+        foreach ($to_del as $del) {
4084
+            $this->del_commercial($user, $del);
4085
+        }
4086
+        foreach ($to_add as $add) {
4087
+            $result = $this->add_commercial($user, $add);
4088
+            if ($result < 0)
4089
+            {
4090
+                $error++;
4091
+                $this->error = $c->error;
4092
+                $this->errors = $c->errors;
4093
+                break;
4094
+            }
4095
+        }
4096
+
4097
+        return $error ? -1 : 1;
4098
+    }
4099
+
4100
+
4101
+    /**
4102
+     * Function used to replace a thirdparty id with another one.
4103
+     * It must be used within a transaction to avoid trouble
4104
+     *
4105
+     * @param 	DoliDB 	$db 		Database handler
4106
+     * @param 	int 	$origin_id 	Old thirdparty id (will be removed)
4107
+     * @param 	int 	$dest_id 	New thirdparty id
4108
+     * @return 	bool				True if success, False if error
4109
+     */
4110
+    public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
4111
+    {
4112
+        if ($origin_id == $dest_id)
4113
+        {
4114
+            dol_syslog('Error: Try to merge a thirdparty into itself');
4115
+            return false;
4116
+        }
4117
+
4118
+        /**
4119
+         * Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some to avoid duplicate.
4120
+         * Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
4121
+         */
4122
+        $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4123
+        $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
4124
+        $sql .= ' SELECT fk_user ';
4125
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
4126
+        $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
4127
+
4128
+        $query = $db->query($sql);
4129
+
4130
+        while ($result = $db->fetch_object($query)) {
4131
+            $db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$result->rowid);
4132
+        }
4133
+
4134
+        /**
4135
+         * llx_societe_extrafields table must not be here because we don't care about the old thirdparty data
4136
+         * Do not include llx_societe because it will be replaced later
4137
+         */
4138
+        $tables = array(
4139
+            'societe_address',
4140
+            'societe_commerciaux',
4141
+            'societe_log',
4142
+            'societe_prices',
4143
+            'societe_remise',
4144
+            'societe_remise_except',
4145
+            'societe_rib'
4146
+        );
4147
+
4148
+        return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
4149
+    }
4150 4150
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/societe/card.php 1 patch
Indentation   +1029 added lines, -1029 removed lines patch added patch discarded remove patch
@@ -76,9 +76,9 @@  discard block
 block discarded – undo
76 76
 
77 77
 if (! ($object->id > 0) && $action == 'view')
78 78
 {
79
-	$langs->load("errors");
80
-	print($langs->trans('ErrorRecordNotFound'));
81
-	exit;
79
+    $langs->load("errors");
80
+    print($langs->trans('ErrorRecordNotFound'));
81
+    exit;
82 82
 }
83 83
 
84 84
 // Get object canvas (By default, this is not defined, so standard usage of dolibarr)
@@ -116,191 +116,191 @@  discard block
 block discarded – undo
116 116
         }
117 117
     }
118 118
 
119
-	if ($action == 'confirm_merge' && $confirm == 'yes' && $user->rights->societe->creer)
120
-	{
121
-		$error = 0;
122
-		$soc_origin_id = GETPOST('soc_origin', 'int');
123
-		$soc_origin = new Societe($db);
124
-
125
-		if ($soc_origin_id <= 0)
126
-		{
127
-			$langs->load('errors');
128
-			$langs->load('companies');
129
-			setEventMessages($langs->trans('ErrorThirdPartyIdIsMandatory', $langs->trans('MergeOriginThirdparty')), null, 'errors');
130
-		}
131
-		else
132
-		{
133
-			if (!$error && $soc_origin->fetch($soc_origin_id) < 1)
134
-			{
135
-				setEventMessages($langs->trans('ErrorRecordNotFound'), null, 'errors');
136
-				$error++;
137
-			}
138
-
139
-			if (!$error)
140
-			{
141
-			    // TODO Move the merge function into class of object.
142
-
143
-				$db->begin();
144
-
145
-				// Recopy some data
146
-				$object->client = $object->client | $soc_origin->client;
147
-				$object->fournisseur = $object->fournisseur | $soc_origin->fournisseur;
148
-				$listofproperties=array(
149
-					'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'twitter', 'facebook', 'url', 'barcode',
150
-					'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
151
-					'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
152
-					'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency',
153
-					'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
154
-					'model_pdf', 'fk_projet'
155
-				);
156
-				foreach ($listofproperties as $property)
157
-				{
158
-					if (empty($object->$property)) $object->$property = $soc_origin->$property;
159
-				}
119
+    if ($action == 'confirm_merge' && $confirm == 'yes' && $user->rights->societe->creer)
120
+    {
121
+        $error = 0;
122
+        $soc_origin_id = GETPOST('soc_origin', 'int');
123
+        $soc_origin = new Societe($db);
160 124
 
161
-				// Concat some data
162
-				$listofproperties=array(
163
-				    'note_public', 'note_private'
164
-				);
165
-				foreach ($listofproperties as $property)
166
-				{
167
-				    $object->$property = dol_concatdesc($object->$property, $soc_origin->$property);
168
-				}
125
+        if ($soc_origin_id <= 0)
126
+        {
127
+            $langs->load('errors');
128
+            $langs->load('companies');
129
+            setEventMessages($langs->trans('ErrorThirdPartyIdIsMandatory', $langs->trans('MergeOriginThirdparty')), null, 'errors');
130
+        }
131
+        else
132
+        {
133
+            if (!$error && $soc_origin->fetch($soc_origin_id) < 1)
134
+            {
135
+                setEventMessages($langs->trans('ErrorRecordNotFound'), null, 'errors');
136
+                $error++;
137
+            }
169 138
 
170
-				// Merge extrafields
171
-				if (is_array($soc_origin->array_options))
172
-				{
173
-					foreach ($soc_origin->array_options as $key => $val)
174
-					{
175
-					    if (empty($object->array_options[$key])) $object->array_options[$key] = $val;
176
-					}
177
-				}
139
+            if (!$error)
140
+            {
141
+                // TODO Move the merge function into class of object.
178 142
 
179
-				// Merge categories
180
-				$static_cat = new Categorie($db);
181
-
182
-				$custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
183
-				$custcats = $static_cat->containing($object->id, 'customer', 'id');
184
-				$custcats = array_merge($custcats,$custcats_ori);
185
-				$object->setCategories($custcats, 'customer');
186
-
187
-				$suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
188
-				$suppcats = $static_cat->containing($object->id, 'supplier', 'id');
189
-				$suppcats = array_merge($suppcats,$suppcats_ori);
190
-				$object->setCategories($suppcats, 'supplier');
191
-
192
-				// If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
193
-				if ($soc_origin->code_client == $object->code_client
194
-					|| $soc_origin->code_fournisseur == $object->code_fournisseur
195
-					|| $soc_origin->barcode == $object->barcode)
196
-				{
197
-					dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
198
-					$soc_origin->code_client = '';
199
-					$soc_origin->code_fournisseur = '';
200
-					$soc_origin->barcode = '';
201
-					$soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
202
-				}
143
+                $db->begin();
203 144
 
204
-				// Update
205
-				$object->update($object->id, $user, 0, 1, 1, 'merge');
206
-				if ($result < 0)
207
-				{
208
-					$error++;
209
-				}
145
+                // Recopy some data
146
+                $object->client = $object->client | $soc_origin->client;
147
+                $object->fournisseur = $object->fournisseur | $soc_origin->fournisseur;
148
+                $listofproperties=array(
149
+                    'address', 'zip', 'town', 'state_id', 'country_id', 'phone', 'phone_pro', 'fax', 'email', 'skype', 'twitter', 'facebook', 'url', 'barcode',
150
+                    'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6',
151
+                    'tva_intra', 'effectif_id', 'forme_juridique', 'remise_percent', 'remise_supplier_percent', 'mode_reglement_supplier_id', 'cond_reglement_supplier_id', 'name_bis',
152
+                    'stcomm_id', 'outstanding_limit', 'price_level', 'parent', 'default_lang', 'ref', 'ref_ext', 'import_key', 'fk_incoterms', 'fk_multicurrency',
153
+                    'code_client', 'code_fournisseur', 'code_compta', 'code_compta_fournisseur',
154
+                    'model_pdf', 'fk_projet'
155
+                );
156
+                foreach ($listofproperties as $property)
157
+                {
158
+                    if (empty($object->$property)) $object->$property = $soc_origin->$property;
159
+                }
210 160
 
211
-				// Move links
212
-				if (! $error)
213
-				{
214
-					$objects = array(
215
-						'Adherent' => '/adherents/class/adherent.class.php',
216
-						'Societe' => '/societe/class/societe.class.php',
217
-						//'Categorie' => '/categories/class/categorie.class.php',
218
-						'ActionComm' => '/comm/action/class/actioncomm.class.php',
219
-						'Propal' => '/comm/propal/class/propal.class.php',
220
-						'Commande' => '/commande/class/commande.class.php',
221
-						'Facture' => '/compta/facture/class/facture.class.php',
222
-						'FactureRec' => '/compta/facture/class/facture-rec.class.php',
223
-						'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
224
-						'Contact' => '/contact/class/contact.class.php',
225
-						'Contrat' => '/contrat/class/contrat.class.php',
226
-						'Expedition' => '/expedition/class/expedition.class.php',
227
-						'Fichinter' => '/fichinter/class/fichinter.class.php',
228
-						'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
229
-						'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
230
-						'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
231
-						'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
232
-						'Livraison' => '/livraison/class/livraison.class.php',
233
-						'Product' => '/product/class/product.class.php',
234
-						'Project' => '/projet/class/project.class.php',
235
-						'User' => '/user/class/user.class.php',
236
-					);
237
-
238
-					//First, all core objects must update their tables
239
-					foreach ($objects as $object_name => $object_file)
240
-					{
241
-						require_once DOL_DOCUMENT_ROOT.$object_file;
161
+                // Concat some data
162
+                $listofproperties=array(
163
+                    'note_public', 'note_private'
164
+                );
165
+                foreach ($listofproperties as $property)
166
+                {
167
+                    $object->$property = dol_concatdesc($object->$property, $soc_origin->$property);
168
+                }
242 169
 
243
-						if (!$error && !$object_name::replaceThirdparty($db, $soc_origin->id, $object->id))
244
-						{
245
-							$error++;
246
-							setEventMessages($db->lasterror(), null, 'errors');
247
-						}
248
-					}
249
-				}
170
+                // Merge extrafields
171
+                if (is_array($soc_origin->array_options))
172
+                {
173
+                    foreach ($soc_origin->array_options as $key => $val)
174
+                    {
175
+                        if (empty($object->array_options[$key])) $object->array_options[$key] = $val;
176
+                    }
177
+                }
250 178
 
251
-				// External modules should update their ones too
252
-				if (! $error)
253
-				{
254
-					$reshook = $hookmanager->executeHooks('replaceThirdparty', array(
255
-						'soc_origin' => $soc_origin->id,
256
-						'soc_dest' => $object->id
257
-					), $soc_dest, $action);
179
+                // Merge categories
180
+                $static_cat = new Categorie($db);
258 181
 
259
-					if ($reshook < 0)
260
-					{
261
-						setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
262
-						$error++;
263
-					}
264
-				}
182
+                $custcats_ori = $static_cat->containing($soc_origin->id, 'customer', 'id');
183
+                $custcats = $static_cat->containing($object->id, 'customer', 'id');
184
+                $custcats = array_merge($custcats,$custcats_ori);
185
+                $object->setCategories($custcats, 'customer');
265 186
 
187
+                $suppcats_ori = $static_cat->containing($soc_origin->id, 'supplier', 'id');
188
+                $suppcats = $static_cat->containing($object->id, 'supplier', 'id');
189
+                $suppcats = array_merge($suppcats,$suppcats_ori);
190
+                $object->setCategories($suppcats, 'supplier');
266 191
 
267
-				if (! $error)
268
-				{
269
-					$object->context=array('merge'=>1, 'mergefromid'=>$soc_origin->id);
192
+                // If thirdparty has a new code that is same than origin, we clean origin code to avoid duplicate key from database unique keys.
193
+                if ($soc_origin->code_client == $object->code_client
194
+                    || $soc_origin->code_fournisseur == $object->code_fournisseur
195
+                    || $soc_origin->barcode == $object->barcode)
196
+                {
197
+                    dol_syslog("We clean customer and supplier code so we will be able to make the update of target");
198
+                    $soc_origin->code_client = '';
199
+                    $soc_origin->code_fournisseur = '';
200
+                    $soc_origin->barcode = '';
201
+                    $soc_origin->update($soc_origin->id, $user, 0, 1, 1, 'merge');
202
+                }
270 203
 
271
-					// Call trigger
272
-					$result=$object->call_trigger('COMPANY_MODIFY',$user);
273
-					if ($result < 0)
274
-					{
275
-						setEventMessages($object->error, $object->errors, 'errors');
276
-						$error++;
277
-					}
278
-					// End call triggers
279
-				}
204
+                // Update
205
+                $object->update($object->id, $user, 0, 1, 1, 'merge');
206
+                if ($result < 0)
207
+                {
208
+                    $error++;
209
+                }
280 210
 
281
-				if (!$error)
282
-				{
283
-					//We finally remove the old thirdparty
284
-					if ($soc_origin->delete($soc_origin->id, $user) < 1)
285
-					{
286
-						$error++;
287
-					}
288
-				}
211
+                // Move links
212
+                if (! $error)
213
+                {
214
+                    $objects = array(
215
+                        'Adherent' => '/adherents/class/adherent.class.php',
216
+                        'Societe' => '/societe/class/societe.class.php',
217
+                        //'Categorie' => '/categories/class/categorie.class.php',
218
+                        'ActionComm' => '/comm/action/class/actioncomm.class.php',
219
+                        'Propal' => '/comm/propal/class/propal.class.php',
220
+                        'Commande' => '/commande/class/commande.class.php',
221
+                        'Facture' => '/compta/facture/class/facture.class.php',
222
+                        'FactureRec' => '/compta/facture/class/facture-rec.class.php',
223
+                        'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
224
+                        'Contact' => '/contact/class/contact.class.php',
225
+                        'Contrat' => '/contrat/class/contrat.class.php',
226
+                        'Expedition' => '/expedition/class/expedition.class.php',
227
+                        'Fichinter' => '/fichinter/class/fichinter.class.php',
228
+                        'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
229
+                        'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
230
+                        'SupplierProposal' => '/supplier_proposal/class/supplier_proposal.class.php',
231
+                        'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
232
+                        'Livraison' => '/livraison/class/livraison.class.php',
233
+                        'Product' => '/product/class/product.class.php',
234
+                        'Project' => '/projet/class/project.class.php',
235
+                        'User' => '/user/class/user.class.php',
236
+                    );
237
+
238
+                    //First, all core objects must update their tables
239
+                    foreach ($objects as $object_name => $object_file)
240
+                    {
241
+                        require_once DOL_DOCUMENT_ROOT.$object_file;
289 242
 
290
-				if (!$error)
291
-				{
292
-					setEventMessages($langs->trans('ThirdpartiesMergeSuccess'), null, 'mesgs');
293
-					$db->commit();
294
-				}
295
-				else
296
-				{
297
-				    $langs->load("errors");
298
-					setEventMessages($langs->trans('ErrorsThirdpartyMerge'), null, 'errors');
299
-					$db->rollback();
300
-				}
301
-			}
302
-		}
303
-	}
243
+                        if (!$error && !$object_name::replaceThirdparty($db, $soc_origin->id, $object->id))
244
+                        {
245
+                            $error++;
246
+                            setEventMessages($db->lasterror(), null, 'errors');
247
+                        }
248
+                    }
249
+                }
250
+
251
+                // External modules should update their ones too
252
+                if (! $error)
253
+                {
254
+                    $reshook = $hookmanager->executeHooks('replaceThirdparty', array(
255
+                        'soc_origin' => $soc_origin->id,
256
+                        'soc_dest' => $object->id
257
+                    ), $soc_dest, $action);
258
+
259
+                    if ($reshook < 0)
260
+                    {
261
+                        setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
262
+                        $error++;
263
+                    }
264
+                }
265
+
266
+
267
+                if (! $error)
268
+                {
269
+                    $object->context=array('merge'=>1, 'mergefromid'=>$soc_origin->id);
270
+
271
+                    // Call trigger
272
+                    $result=$object->call_trigger('COMPANY_MODIFY',$user);
273
+                    if ($result < 0)
274
+                    {
275
+                        setEventMessages($object->error, $object->errors, 'errors');
276
+                        $error++;
277
+                    }
278
+                    // End call triggers
279
+                }
280
+
281
+                if (!$error)
282
+                {
283
+                    //We finally remove the old thirdparty
284
+                    if ($soc_origin->delete($soc_origin->id, $user) < 1)
285
+                    {
286
+                        $error++;
287
+                    }
288
+                }
289
+
290
+                if (!$error)
291
+                {
292
+                    setEventMessages($langs->trans('ThirdpartiesMergeSuccess'), null, 'mesgs');
293
+                    $db->commit();
294
+                }
295
+                else
296
+                {
297
+                    $langs->load("errors");
298
+                    setEventMessages($langs->trans('ErrorsThirdpartyMerge'), null, 'errors');
299
+                    $db->rollback();
300
+                }
301
+            }
302
+        }
303
+    }
304 304
 
305 305
     if (GETPOST('getcustomercode'))
306 306
     {
@@ -316,17 +316,17 @@  discard block
 block discarded – undo
316 316
 
317 317
     if($action=='set_localtax1')
318 318
     {
319
-    	//obtidre selected del combobox
320
-    	$value=GETPOST('lt1');
321
-    	$object->fetch($socid);
322
-    	$res=$object->setValueFrom('localtax1_value', $value, '', null, 'text', '', $user, 'COMPANY_MODIFY');
319
+        //obtidre selected del combobox
320
+        $value=GETPOST('lt1');
321
+        $object->fetch($socid);
322
+        $res=$object->setValueFrom('localtax1_value', $value, '', null, 'text', '', $user, 'COMPANY_MODIFY');
323 323
     }
324 324
     if($action=='set_localtax2')
325 325
     {
326
-    	//obtidre selected del combobox
327
-    	$value=GETPOST('lt2');
328
-    	$object->fetch($socid);
329
-    	$res=$object->setValueFrom('localtax2_value', $value, '', null, 'text', '', $user, 'COMPANY_MODIFY');
326
+        //obtidre selected del combobox
327
+        $value=GETPOST('lt2');
328
+        $object->fetch($socid);
329
+        $res=$object->setValueFrom('localtax2_value', $value, '', null, 'text', '', $user, 'COMPANY_MODIFY');
330 330
     }
331 331
 
332 332
     if ($action == 'update_extras') {
@@ -341,12 +341,12 @@  discard block
 block discarded – undo
341 341
 
342 342
         if (! $error)
343 343
         {
344
-        	$result = $object->insertExtraFields('COMPANY_MODIFY');
345
-        	if ($result < 0)
346
-        	{
347
-        		setEventMessages($object->error, $object->errors, 'errors');
348
-        		$error++;
349
-        	}
344
+            $result = $object->insertExtraFields('COMPANY_MODIFY');
345
+            if ($result < 0)
346
+            {
347
+                setEventMessages($object->error, $object->errors, 'errors');
348
+                $error++;
349
+            }
350 350
         }
351 351
 
352 352
         if ($error) $action = 'edit_extras';
@@ -376,145 +376,145 @@  discard block
 block discarded – undo
376 376
 
377 377
         if (! $error)
378 378
         {
379
-        	if ($action == 'update')
380
-	        {
381
-	        	$ret=$object->fetch($socid);
382
-				$object->oldcopy = clone $object;
383
-	        }
384
-			else $object->canvas=$canvas;
385
-
386
-	        if (GETPOST("private") == 1)	// Ask to create a contact
387
-	        {
388
-	            $object->particulier		= GETPOST("private");
389
-
390
-	            $object->name				= dolGetFirstLastname(GETPOST('firstname','alpha'),GETPOST('name','alpha'));
391
-	            $object->civility_id		= GETPOST('civility_id');	// Note: civility id is a code, not an int
392
-	            // Add non official properties
393
-	            $object->name_bis			= GETPOST('name','alpha');
394
-	            $object->firstname			= GETPOST('firstname','alpha');
395
-	        }
396
-	        else
397
-	        {
398
-	            $object->name				= GETPOST('name', 'alpha');
399
-	        }
400
-	        $object->entity					= (GETPOSTISSET('entity')?GETPOST('entity', 'int'):$conf->entity);
401
-	        $object->name_alias				= GETPOST('name_alias');
402
-	        $object->address				= GETPOST('address');
403
-	        $object->zip					= GETPOST('zipcode', 'alpha');
404
-	        $object->town					= GETPOST('town', 'alpha');
405
-	        $object->country_id				= GETPOST('country_id', 'int');
406
-	        $object->state_id				= GETPOST('state_id', 'int');
407
-	        $object->skype					= GETPOST('skype', 'alpha');
408
-	        $object->twitter				= GETPOST('twitter', 'alpha');
409
-	        $object->facebook				= GETPOST('facebook', 'alpha');
410
-	        $object->phone					= GETPOST('phone', 'alpha');
411
-	        $object->fax					= GETPOST('fax','alpha');
412
-	        $object->email					= trim(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL));
413
-	        $object->url					= trim(GETPOST('url', 'custom', 0, FILTER_SANITIZE_URL));
414
-	        $object->idprof1				= trim(GETPOST('idprof1', 'alpha'));
415
-	        $object->idprof2				= trim(GETPOST('idprof2', 'alpha'));
416
-	        $object->idprof3				= trim(GETPOST('idprof3', 'alpha'));
417
-	        $object->idprof4				= trim(GETPOST('idprof4', 'alpha'));
418
-	        $object->idprof5				= trim(GETPOST('idprof5', 'alpha'));
419
-	        $object->idprof6				= trim(GETPOST('idprof6', 'alpha'));
420
-	        $object->prefix_comm			= GETPOST('prefix_comm', 'alpha');
421
-	        $object->code_client			= GETPOSTISSET('customer_code')?GETPOST('customer_code', 'alpha'):GETPOST('code_client', 'alpha');
422
-	        $object->code_fournisseur		= GETPOSTISSET('supplier_code')?GETPOST('supplier_code', 'alpha'):GETPOST('code_fournisseur', 'alpha');
423
-	        $object->capital				= GETPOST('capital', 'alpha');
424
-	        $object->barcode				= GETPOST('barcode', 'alpha');
425
-
426
-	        $object->tva_intra				= GETPOST('tva_intra', 'alpha');
427
-	        $object->tva_assuj				= GETPOST('assujtva_value', 'alpha');
428
-	        $object->status					= GETPOST('status', 'alpha');
429
-
430
-	        // Local Taxes
431
-	        $object->localtax1_assuj		= GETPOST('localtax1assuj_value', 'alpha');
432
-	        $object->localtax2_assuj		= GETPOST('localtax2assuj_value', 'alpha');
433
-
434
-	        $object->localtax1_value		= GETPOST('lt1', 'alpha');
435
-	        $object->localtax2_value		= GETPOST('lt2', 'alpha');
436
-
437
-	        $object->forme_juridique_code	= GETPOST('forme_juridique_code', 'int');
438
-	        $object->effectif_id			= GETPOST('effectif_id', 'int');
439
-	        $object->typent_id				= GETPOST('typent_id','int');
440
-
441
-	        $object->typent_code			= dol_getIdFromCode($db, $object->typent_id, 'c_typent', 'id', 'code');	// Force typent_code too so check in verify() will be done on new type
442
-
443
-	        $object->client					= GETPOST('client', 'int');
444
-	        $object->fournisseur			= GETPOST('fournisseur', 'int');
445
-
446
-	        $object->commercial_id			= GETPOST('commercial_id', 'int');
447
-	        $object->default_lang			= GETPOST('default_lang');
448
-
449
-	        // Webservices url/key
450
-	        $object->webservices_url		= GETPOST('webservices_url', 'custom', 0, FILTER_SANITIZE_URL);
451
-	        $object->webservices_key		= GETPOST('webservices_key', 'san_alpha');
452
-
453
-			// Incoterms
454
-			if (!empty($conf->incoterm->enabled))
455
-			{
456
-				$object->fk_incoterms		= GETPOST('incoterm_id', 'int');
457
-				$object->location_incoterms	= GETPOST('location_incoterms', 'alpha');
458
-			}
459
-
460
-			// Multicurrency
461
-			if (!empty($conf->multicurrency->enabled))
462
-			{
463
-				$object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
464
-			}
465
-
466
-	        // Fill array 'array_options' with data from add form
467
-	        $ret = $extrafields->setOptionalsFromPost($extralabels,$object);
468
-			if ($ret < 0)
469
-			{
470
-				 $error++;
471
-			}
472
-
473
-	        if (GETPOST('deletephoto')) $object->logo = '';
474
-	        else if (! empty($_FILES['photo']['name'])) $object->logo = dol_sanitizeFileName($_FILES['photo']['name']);
475
-
476
-	        // Check parameters
477
-	        if (! GETPOST('cancel','alpha'))
478
-	        {
479
-	            if (! empty($object->email) && ! isValidEMail($object->email))
480
-	            {
481
-	                $langs->load("errors");
482
-	                $error++;
483
-	                setEventMessages('', $langs->trans("ErrorBadEMail",$object->email), 'errors');
484
-	            }
485
-	            if (! empty($object->url) && ! isValidUrl($object->url))
486
-	            {
487
-	                $langs->load("errors");
488
-	                setEventMessages('', $langs->trans("ErrorBadUrl",$object->url), 'errors');
489
-	            }
490
-	            if (! empty($object->webservices_url)) {
491
-	                //Check if has transport, without any the soap client will give error
492
-	                if (strpos($object->webservices_url, "http") === false)
493
-	                {
494
-	                    $object->webservices_url = "http://".$object->webservices_url;
495
-	                }
496
-	                if (! isValidUrl($object->webservices_url)) {
497
-	                    $langs->load("errors");
498
-	                    $error++; $errors[] = $langs->trans("ErrorBadUrl",$object->webservices_url);
499
-	                }
500
-	            }
501
-
502
-	            // We set country_id, country_code and country for the selected country
503
-	            $object->country_id=GETPOST('country_id')!=''?GETPOST('country_id'):$mysoc->country_id;
504
-	            if ($object->country_id)
505
-	            {
506
-	            	$tmparray=getCountry($object->country_id,'all');
507
-	            	$object->country_code=$tmparray['code'];
508
-	            	$object->country=$tmparray['label'];
509
-	            }
510
-	        }
379
+            if ($action == 'update')
380
+            {
381
+                $ret=$object->fetch($socid);
382
+                $object->oldcopy = clone $object;
383
+            }
384
+            else $object->canvas=$canvas;
385
+
386
+            if (GETPOST("private") == 1)	// Ask to create a contact
387
+            {
388
+                $object->particulier		= GETPOST("private");
389
+
390
+                $object->name				= dolGetFirstLastname(GETPOST('firstname','alpha'),GETPOST('name','alpha'));
391
+                $object->civility_id		= GETPOST('civility_id');	// Note: civility id is a code, not an int
392
+                // Add non official properties
393
+                $object->name_bis			= GETPOST('name','alpha');
394
+                $object->firstname			= GETPOST('firstname','alpha');
395
+            }
396
+            else
397
+            {
398
+                $object->name				= GETPOST('name', 'alpha');
399
+            }
400
+            $object->entity					= (GETPOSTISSET('entity')?GETPOST('entity', 'int'):$conf->entity);
401
+            $object->name_alias				= GETPOST('name_alias');
402
+            $object->address				= GETPOST('address');
403
+            $object->zip					= GETPOST('zipcode', 'alpha');
404
+            $object->town					= GETPOST('town', 'alpha');
405
+            $object->country_id				= GETPOST('country_id', 'int');
406
+            $object->state_id				= GETPOST('state_id', 'int');
407
+            $object->skype					= GETPOST('skype', 'alpha');
408
+            $object->twitter				= GETPOST('twitter', 'alpha');
409
+            $object->facebook				= GETPOST('facebook', 'alpha');
410
+            $object->phone					= GETPOST('phone', 'alpha');
411
+            $object->fax					= GETPOST('fax','alpha');
412
+            $object->email					= trim(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL));
413
+            $object->url					= trim(GETPOST('url', 'custom', 0, FILTER_SANITIZE_URL));
414
+            $object->idprof1				= trim(GETPOST('idprof1', 'alpha'));
415
+            $object->idprof2				= trim(GETPOST('idprof2', 'alpha'));
416
+            $object->idprof3				= trim(GETPOST('idprof3', 'alpha'));
417
+            $object->idprof4				= trim(GETPOST('idprof4', 'alpha'));
418
+            $object->idprof5				= trim(GETPOST('idprof5', 'alpha'));
419
+            $object->idprof6				= trim(GETPOST('idprof6', 'alpha'));
420
+            $object->prefix_comm			= GETPOST('prefix_comm', 'alpha');
421
+            $object->code_client			= GETPOSTISSET('customer_code')?GETPOST('customer_code', 'alpha'):GETPOST('code_client', 'alpha');
422
+            $object->code_fournisseur		= GETPOSTISSET('supplier_code')?GETPOST('supplier_code', 'alpha'):GETPOST('code_fournisseur', 'alpha');
423
+            $object->capital				= GETPOST('capital', 'alpha');
424
+            $object->barcode				= GETPOST('barcode', 'alpha');
425
+
426
+            $object->tva_intra				= GETPOST('tva_intra', 'alpha');
427
+            $object->tva_assuj				= GETPOST('assujtva_value', 'alpha');
428
+            $object->status					= GETPOST('status', 'alpha');
429
+
430
+            // Local Taxes
431
+            $object->localtax1_assuj		= GETPOST('localtax1assuj_value', 'alpha');
432
+            $object->localtax2_assuj		= GETPOST('localtax2assuj_value', 'alpha');
433
+
434
+            $object->localtax1_value		= GETPOST('lt1', 'alpha');
435
+            $object->localtax2_value		= GETPOST('lt2', 'alpha');
436
+
437
+            $object->forme_juridique_code	= GETPOST('forme_juridique_code', 'int');
438
+            $object->effectif_id			= GETPOST('effectif_id', 'int');
439
+            $object->typent_id				= GETPOST('typent_id','int');
440
+
441
+            $object->typent_code			= dol_getIdFromCode($db, $object->typent_id, 'c_typent', 'id', 'code');	// Force typent_code too so check in verify() will be done on new type
442
+
443
+            $object->client					= GETPOST('client', 'int');
444
+            $object->fournisseur			= GETPOST('fournisseur', 'int');
445
+
446
+            $object->commercial_id			= GETPOST('commercial_id', 'int');
447
+            $object->default_lang			= GETPOST('default_lang');
448
+
449
+            // Webservices url/key
450
+            $object->webservices_url		= GETPOST('webservices_url', 'custom', 0, FILTER_SANITIZE_URL);
451
+            $object->webservices_key		= GETPOST('webservices_key', 'san_alpha');
452
+
453
+            // Incoterms
454
+            if (!empty($conf->incoterm->enabled))
455
+            {
456
+                $object->fk_incoterms		= GETPOST('incoterm_id', 'int');
457
+                $object->location_incoterms	= GETPOST('location_incoterms', 'alpha');
458
+            }
459
+
460
+            // Multicurrency
461
+            if (!empty($conf->multicurrency->enabled))
462
+            {
463
+                $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
464
+            }
465
+
466
+            // Fill array 'array_options' with data from add form
467
+            $ret = $extrafields->setOptionalsFromPost($extralabels,$object);
468
+            if ($ret < 0)
469
+            {
470
+                    $error++;
471
+            }
472
+
473
+            if (GETPOST('deletephoto')) $object->logo = '';
474
+            else if (! empty($_FILES['photo']['name'])) $object->logo = dol_sanitizeFileName($_FILES['photo']['name']);
475
+
476
+            // Check parameters
477
+            if (! GETPOST('cancel','alpha'))
478
+            {
479
+                if (! empty($object->email) && ! isValidEMail($object->email))
480
+                {
481
+                    $langs->load("errors");
482
+                    $error++;
483
+                    setEventMessages('', $langs->trans("ErrorBadEMail",$object->email), 'errors');
484
+                }
485
+                if (! empty($object->url) && ! isValidUrl($object->url))
486
+                {
487
+                    $langs->load("errors");
488
+                    setEventMessages('', $langs->trans("ErrorBadUrl",$object->url), 'errors');
489
+                }
490
+                if (! empty($object->webservices_url)) {
491
+                    //Check if has transport, without any the soap client will give error
492
+                    if (strpos($object->webservices_url, "http") === false)
493
+                    {
494
+                        $object->webservices_url = "http://".$object->webservices_url;
495
+                    }
496
+                    if (! isValidUrl($object->webservices_url)) {
497
+                        $langs->load("errors");
498
+                        $error++; $errors[] = $langs->trans("ErrorBadUrl",$object->webservices_url);
499
+                    }
500
+                }
501
+
502
+                // We set country_id, country_code and country for the selected country
503
+                $object->country_id=GETPOST('country_id')!=''?GETPOST('country_id'):$mysoc->country_id;
504
+                if ($object->country_id)
505
+                {
506
+                    $tmparray=getCountry($object->country_id,'all');
507
+                    $object->country_code=$tmparray['code'];
508
+                    $object->country=$tmparray['label'];
509
+                }
510
+            }
511 511
         }
512 512
 
513 513
         if (! $error)
514 514
         {
515 515
             if ($action == 'add')
516 516
             {
517
-            	$error = 0;
517
+                $error = 0;
518 518
 
519 519
                 $db->begin();
520 520
 
@@ -523,45 +523,45 @@  discard block
 block discarded – undo
523 523
 
524 524
                 $result = $object->create($user);
525 525
 
526
-				if ($result >= 0)
527
-				{
528
-					if ($object->particulier)
529
-					{
530
-						dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
531
-						$result=$object->create_individual($user);
532
-						if ($result < 0)
533
-						{
534
-							setEventMessages($object->error, $object->errors, 'errors');
535
-							$error++;
536
-						}
537
-					}
526
+                if ($result >= 0)
527
+                {
528
+                    if ($object->particulier)
529
+                    {
530
+                        dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
531
+                        $result=$object->create_individual($user);
532
+                        if ($result < 0)
533
+                        {
534
+                            setEventMessages($object->error, $object->errors, 'errors');
535
+                            $error++;
536
+                        }
537
+                    }
538 538
 
539
-					// Links with users
540
-					$salesreps = GETPOST('commercial', 'array');
541
-					$result = $object->setSalesRep($salesreps);
542
-					if ($result < 0)
543
-					{
544
-						$error++;
545
-						setEventMessages($object->error, $object->errors, 'errors');
546
-					}
539
+                    // Links with users
540
+                    $salesreps = GETPOST('commercial', 'array');
541
+                    $result = $object->setSalesRep($salesreps);
542
+                    if ($result < 0)
543
+                    {
544
+                        $error++;
545
+                        setEventMessages($object->error, $object->errors, 'errors');
546
+                    }
547 547
 
548
-					// Customer categories association
549
-					$custcats = GETPOST('custcats', 'array');
550
-					$result = $object->setCategories($custcats, 'customer');
551
-					if ($result < 0)
552
-					{
553
-						$error++;
554
-						setEventMessages($object->error, $object->errors, 'errors');
555
-					}
548
+                    // Customer categories association
549
+                    $custcats = GETPOST('custcats', 'array');
550
+                    $result = $object->setCategories($custcats, 'customer');
551
+                    if ($result < 0)
552
+                    {
553
+                        $error++;
554
+                        setEventMessages($object->error, $object->errors, 'errors');
555
+                    }
556 556
 
557
-					// Supplier categories association
558
-					$suppcats = GETPOST('suppcats', 'array');
559
-					$result = $object->setCategories($suppcats, 'supplier');
560
-					if ($result < 0)
561
-					{
562
-						$error++;
563
-						setEventMessages($object->error, $object->errors, 'errors');
564
-					}
557
+                    // Supplier categories association
558
+                    $suppcats = GETPOST('suppcats', 'array');
559
+                    $result = $object->setCategories($suppcats, 'supplier');
560
+                    if ($result < 0)
561
+                    {
562
+                        $error++;
563
+                        setEventMessages($object->error, $object->errors, 'errors');
564
+                    }
565 565
 
566 566
                     // Logo/Photo save
567 567
                     $dir     = $conf->societe->multidir_output[$conf->entity]."/".$object->id."/logos/";
@@ -590,52 +590,52 @@  discard block
 block discarded – undo
590 590
                         }
591 591
                     }
592 592
                     else
593
-					{
594
-						switch($_FILES['photo']['error'])
595
-						{
596
-						    case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
597
-						    case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
598
-						      $errors[] = "ErrorFileSizeTooLarge";
599
-						      break;
600
-	      					case 3: //uploaded file was only partially uploaded
601
-						      $errors[] = "ErrorFilePartiallyUploaded";
602
-						      break;
603
-						}
604
-	                }
593
+                    {
594
+                        switch($_FILES['photo']['error'])
595
+                        {
596
+                            case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
597
+                            case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
598
+                              $errors[] = "ErrorFileSizeTooLarge";
599
+                                break;
600
+                                case 3: //uploaded file was only partially uploaded
601
+                              $errors[] = "ErrorFilePartiallyUploaded";
602
+                                break;
603
+                        }
604
+                    }
605 605
                     // Gestion du logo de la société
606 606
                 }
607 607
                 else
608
-				{
609
-				    if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') // TODO Sometime errors on duplicate on profid and not on code, so we must manage this case
610
-					{
611
-						$duplicate_code_error = true;
612
-						$object->code_fournisseur = null;
613
-						$object->code_client = null;
614
-					}
608
+                {
609
+                    if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') // TODO Sometime errors on duplicate on profid and not on code, so we must manage this case
610
+                    {
611
+                        $duplicate_code_error = true;
612
+                        $object->code_fournisseur = null;
613
+                        $object->code_client = null;
614
+                    }
615 615
 
616 616
                     setEventMessages($object->error, $object->errors, 'errors');
617
-                   	$error++;
617
+                        $error++;
618 618
                 }
619 619
 
620 620
                 if ($result >= 0 && ! $error)
621 621
                 {
622 622
                     $db->commit();
623 623
 
624
-                	if (! empty($backtopage))
625
-                	{
626
-                	    if (preg_match('/\?/', $backtopage)) $backtopage.='&socid='.$object->id;
627
-               		    header("Location: ".$backtopage);
628
-                    	exit;
629
-                	}
630
-                	else
631
-                	{
632
-                    	$url=$_SERVER["PHP_SELF"]."?socid=".$object->id;
633
-                    	if (($object->client == 1 || $object->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $url=DOL_URL_ROOT."/comm/card.php?socid=".$object->id;
634
-                    	else if ($object->fournisseur == 1) $url=DOL_URL_ROOT."/fourn/card.php?socid=".$object->id;
635
-
636
-                		header("Location: ".$url);
637
-                    	exit;
638
-                	}
624
+                    if (! empty($backtopage))
625
+                    {
626
+                        if (preg_match('/\?/', $backtopage)) $backtopage.='&socid='.$object->id;
627
+                            header("Location: ".$backtopage);
628
+                        exit;
629
+                    }
630
+                    else
631
+                    {
632
+                        $url=$_SERVER["PHP_SELF"]."?socid=".$object->id;
633
+                        if (($object->client == 1 || $object->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $url=DOL_URL_ROOT."/comm/card.php?socid=".$object->id;
634
+                        else if ($object->fournisseur == 1) $url=DOL_URL_ROOT."/fourn/card.php?socid=".$object->id;
635
+
636
+                        header("Location: ".$url);
637
+                        exit;
638
+                    }
639 639
                 }
640 640
                 else
641 641
                 {
@@ -646,20 +646,20 @@  discard block
 block discarded – undo
646 646
 
647 647
             if ($action == 'update')
648 648
             {
649
-            	$error = 0;
649
+                $error = 0;
650 650
 
651 651
                 if (GETPOST('cancel','alpha'))
652 652
                 {
653
-                	if (! empty($backtopage))
654
-                	{
655
-               		    header("Location: ".$backtopage);
656
-                    	exit;
657
-                	}
658
-                	else
659
-                	{
660
-               		    header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid);
661
-                    	exit;
662
-                	}
653
+                    if (! empty($backtopage))
654
+                    {
655
+                            header("Location: ".$backtopage);
656
+                        exit;
657
+                    }
658
+                    else
659
+                    {
660
+                            header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid);
661
+                        exit;
662
+                    }
663 663
                 }
664 664
 
665 665
                 // To not set code if third party is not concerned. But if it had values, we keep them.
@@ -674,36 +674,36 @@  discard block
 block discarded – undo
674 674
                     $error++;
675 675
                 }
676 676
 
677
-				// Links with users
678
-				$salesreps = GETPOST('commercial', 'array');
679
-				$result = $object->setSalesRep($salesreps);
680
-				if ($result < 0)
681
-				{
682
-					$error++;
683
-					setEventMessages($object->error, $object->errors, 'errors');
684
-				}
677
+                // Links with users
678
+                $salesreps = GETPOST('commercial', 'array');
679
+                $result = $object->setSalesRep($salesreps);
680
+                if ($result < 0)
681
+                {
682
+                    $error++;
683
+                    setEventMessages($object->error, $object->errors, 'errors');
684
+                }
685 685
 
686
-				// Prevent thirdparty's emptying if a user hasn't rights $user->rights->categorie->lire (in such a case, post of 'custcats' is not defined)
687
-				if (! $error && !empty($user->rights->categorie->lire))
688
-				{
689
-					// Customer categories association
690
-					$categories = GETPOST( 'custcats', 'array' );
691
-					$result = $object->setCategories($categories, 'customer');
692
-					if ($result < 0)
693
-					{
694
-						$error++;
695
-						setEventMessages($object->error, $object->errors, 'errors');
696
-					}
686
+                // Prevent thirdparty's emptying if a user hasn't rights $user->rights->categorie->lire (in such a case, post of 'custcats' is not defined)
687
+                if (! $error && !empty($user->rights->categorie->lire))
688
+                {
689
+                    // Customer categories association
690
+                    $categories = GETPOST( 'custcats', 'array' );
691
+                    $result = $object->setCategories($categories, 'customer');
692
+                    if ($result < 0)
693
+                    {
694
+                        $error++;
695
+                        setEventMessages($object->error, $object->errors, 'errors');
696
+                    }
697 697
 
698
-					// Supplier categories association
699
-					$categories = GETPOST('suppcats', 'array');
700
-					$result = $object->setCategories($categories, 'supplier');
701
-					if ($result < 0)
702
-					{
703
-						$error++;
704
-						setEventMessages($object->error, $object->errors, 'errors');
705
-					}
706
-				}
698
+                    // Supplier categories association
699
+                    $categories = GETPOST('suppcats', 'array');
700
+                    $result = $object->setCategories($categories, 'supplier');
701
+                    if ($result < 0)
702
+                    {
703
+                        $error++;
704
+                        setEventMessages($object->error, $object->errors, 'errors');
705
+                    }
706
+                }
707 707
 
708 708
                 // Logo/Photo save
709 709
                 $dir     = $conf->societe->multidir_output[$object->entity]."/".$object->id."/logos";
@@ -732,38 +732,38 @@  discard block
 block discarded – undo
732 732
                             }
733 733
                             else
734 734
                             {
735
-                            	// Create thumbs
736
-                            	$object->addThumbs($newfile);
735
+                                // Create thumbs
736
+                                $object->addThumbs($newfile);
737 737
 
738 738
                                 // Index file in database
739 739
                                 if (! empty($conf->global->THIRDPARTY_LOGO_ALLOW_EXTERNAL_DOWNLOAD))
740 740
                                 {
741
-                                	require_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
742
-                                	// the dir dirname($newfile) is directory of logo, so we should have only one file at once into index, so we delete indexes for the dir
743
-                                	deleteFilesIntoDatabaseIndex(dirname($newfile), '', '', 'uploaded', 1);
744
-                                	// now we index the uploaded logo file
745
-                                	addFileIntoDatabaseIndex(dirname($newfile), basename($newfile), '', 'uploaded', 1);
741
+                                    require_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
742
+                                    // the dir dirname($newfile) is directory of logo, so we should have only one file at once into index, so we delete indexes for the dir
743
+                                    deleteFilesIntoDatabaseIndex(dirname($newfile), '', '', 'uploaded', 1);
744
+                                    // now we index the uploaded logo file
745
+                                    addFileIntoDatabaseIndex(dirname($newfile), basename($newfile), '', 'uploaded', 1);
746 746
                                 }
747 747
                             }
748 748
                         }
749 749
                     }
750 750
                     else
751
-					{
751
+                    {
752 752
                         $errors[] = "ErrorBadImageFormat";
753 753
                     }
754 754
                 }
755 755
                 else
756 756
                 {
757
-					switch($_FILES['photo']['error'])
758
-					{
759
-					    case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
760
-					    case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
761
-					      $errors[] = "ErrorFileSizeTooLarge";
762
-					      break;
763
-      					case 3: //uploaded file was only partially uploaded
764
-					      $errors[] = "ErrorFilePartiallyUploaded";
765
-					      break;
766
-					}
757
+                    switch($_FILES['photo']['error'])
758
+                    {
759
+                        case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
760
+                        case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
761
+                          $errors[] = "ErrorFileSizeTooLarge";
762
+                            break;
763
+                            case 3: //uploaded file was only partially uploaded
764
+                          $errors[] = "ErrorFilePartiallyUploaded";
765
+                            break;
766
+                    }
767 767
                 }
768 768
                 // Gestion du logo de la société
769 769
 
@@ -772,28 +772,28 @@  discard block
 block discarded – undo
772 772
                 if (! $error && $object->fk_soc > 0)
773 773
                 {
774 774
 
775
-                	$sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
776
-                	$sql.= " SET fk_soc = NULL WHERE fk_soc = " . $id;
777
-                	if (! $object->db->query($sql))
778
-                	{
779
-                		$error++;
780
-                		$object->error .= $object->db->lasterror();
781
-                		setEventMessages($object->error, $object->errors, 'errors');
782
-                	}
775
+                    $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
776
+                    $sql.= " SET fk_soc = NULL WHERE fk_soc = " . $id;
777
+                    if (! $object->db->query($sql))
778
+                    {
779
+                        $error++;
780
+                        $object->error .= $object->db->lasterror();
781
+                        setEventMessages($object->error, $object->errors, 'errors');
782
+                    }
783 783
                 }
784 784
 
785 785
                 if (! $error && ! count($errors))
786 786
                 {
787
-                	if (! empty($backtopage))
788
-                	{
789
-               		    header("Location: ".$backtopage);
790
-                    	exit;
791
-                	}
792
-                	else
793
-                	{
794
-               		    header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid);
795
-                    	exit;
796
-                	}
787
+                    if (! empty($backtopage))
788
+                    {
789
+                            header("Location: ".$backtopage);
790
+                        exit;
791
+                    }
792
+                    else
793
+                    {
794
+                            header("Location: ".$_SERVER["PHP_SELF"]."?socid=".$socid);
795
+                        exit;
796
+                    }
797 797
                 }
798 798
                 else
799 799
                 {
@@ -804,7 +804,7 @@  discard block
 block discarded – undo
804 804
         }
805 805
         else
806 806
         {
807
-        	$action = ($action=='add'?'create':'edit');
807
+            $action = ($action=='add'?'create':'edit');
808 808
         }
809 809
     }
810 810
 
@@ -822,8 +822,8 @@  discard block
 block discarded – undo
822 822
         else
823 823
         {
824 824
             $langs->load("errors");
825
-           	setEventMessages($object->error, $object->errors, 'errors');
826
-           	$error++;
825
+                setEventMessages($object->error, $object->errors, 'errors');
826
+                $error++;
827 827
             $action='';
828 828
         }
829 829
     }
@@ -831,15 +831,15 @@  discard block
 block discarded – undo
831 831
     // Set parent company
832 832
     if ($action == 'set_thirdparty' && $user->rights->societe->creer)
833 833
     {
834
-    	$object->fetch($socid);
835
-    	$result = $object->set_parent(GETPOST('editparentcompany','int'));
834
+        $object->fetch($socid);
835
+        $result = $object->set_parent(GETPOST('editparentcompany','int'));
836 836
     }
837 837
 
838 838
     // Set incoterm
839 839
     if ($action == 'set_incoterms' && !empty($conf->incoterm->enabled))
840 840
     {
841
-    	$object->fetch($socid);
842
-    	$result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
841
+        $object->fetch($socid);
842
+        $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
843 843
     }
844 844
 
845 845
     $id=$socid;
@@ -872,7 +872,7 @@  discard block
 block discarded – undo
872 872
 if ($socid > 0 && empty($object->id))
873 873
 {
874 874
     $result=$object->fetch($socid);
875
-	if ($result <= 0) dol_print_error('',$object->error);
875
+    if ($result <= 0) dol_print_error('',$object->error);
876 876
 }
877 877
 
878 878
 $title=$langs->trans("ThirdParty");
@@ -887,7 +887,7 @@  discard block
 block discarded – undo
887 887
     // -----------------------------------------
888 888
     // When used with CANVAS
889 889
     // -----------------------------------------
890
-   	$objcanvas->assign_values($action, $object->id, $object->ref);	// Set value for templates
890
+        $objcanvas->assign_values($action, $object->id, $object->ref);	// Set value for templates
891 891
     $objcanvas->display_canvas($action);							// Show template
892 892
 }
893 893
 else
@@ -900,9 +900,9 @@  discard block
 block discarded – undo
900 900
         /*
901 901
          *  Creation
902 902
          */
903
-		$private=GETPOST("private","int");
904
-		if (! empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT) && ! isset($_GET['private']) && ! isset($_POST['private'])) $private=1;
905
-    	if (empty($private)) $private=0;
903
+        $private=GETPOST("private","int");
904
+        if (! empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT) && ! isset($_GET['private']) && ! isset($_POST['private'])) $private=1;
905
+        if (empty($private)) $private=0;
906 906
 
907 907
         // Load object modCodeTiers
908 908
         $module=(! empty($conf->global->SOCIETE_CODECLIENT_ADDON)?$conf->global->SOCIETE_CODECLIENT_ADDON:'mod_codeclient_leopard');
@@ -948,12 +948,12 @@  discard block
 block discarded – undo
948 948
         $object->client				= GETPOST('client')?GETPOST('client'):$object->client;
949 949
 
950 950
         if(empty($duplicate_code_error)) {
951
-	        $object->code_client		= GETPOST('customer_code', 'alpha');
952
-	        $object->fournisseur		= GETPOST('fournisseur')?GETPOST('fournisseur'):$object->fournisseur;
951
+            $object->code_client		= GETPOST('customer_code', 'alpha');
952
+            $object->fournisseur		= GETPOST('fournisseur')?GETPOST('fournisseur'):$object->fournisseur;
953
+        }
954
+        else {
955
+            setEventMessages($langs->trans('NewCustomerSupplierCodeProposed'),'', 'warnings');
953 956
         }
954
-		else {
955
-			setEventMessages($langs->trans('NewCustomerSupplierCodeProposed'),'', 'warnings');
956
-		}
957 957
 
958 958
         $object->code_fournisseur	= GETPOST('supplier_code', 'alpha');
959 959
         $object->address			= GETPOST('address', 'alpha');
@@ -1107,18 +1107,18 @@  discard block
 block discarded – undo
1107 1107
             print '<div class="hideonsmartphone float">';
1108 1108
             print $langs->trans("ThirdPartyType").': &nbsp; &nbsp; ';
1109 1109
             print '</div>';
1110
-	        print '<label for="radiocompany" class="radiocompany">';
1110
+            print '<label for="radiocompany" class="radiocompany">';
1111 1111
             print '<input type="radio" id="radiocompany" class="flat" name="private"  value="0"'.($private?'':' checked').'>';
1112
-	        print '&nbsp;';
1112
+            print '&nbsp;';
1113 1113
             print $langs->trans("CreateThirdPartyOnly");
1114
-	        print '</label>';
1114
+            print '</label>';
1115 1115
             print ' &nbsp; &nbsp; ';
1116
-	        print '<label for="radioprivate" class="radioprivate">';
1116
+            print '<label for="radioprivate" class="radioprivate">';
1117 1117
             $text ='<input type="radio" id="radioprivate" class="flat" name="private" value="1"'.($private?' checked':'').'>';
1118
-	        $text.='&nbsp;';
1119
-	        $text.= $langs->trans("CreateThirdPartyAndContact");
1120
-	        $htmltext=$langs->trans("ToCreateContactWithSameName");
1121
-	        print $form->textwithpicto($text, $htmltext, 1, 'help', '', 0, 3);
1118
+            $text.='&nbsp;';
1119
+            $text.= $langs->trans("CreateThirdPartyAndContact");
1120
+            $htmltext=$langs->trans("ToCreateContactWithSameName");
1121
+            print $form->textwithpicto($text, $htmltext, 1, 'help', '', 0, 3);
1122 1122
             print '</label>';
1123 1123
             print '</div>';
1124 1124
             print "<br>\n";
@@ -1142,28 +1142,28 @@  discard block
 block discarded – undo
1142 1142
         print '<table class="border" width="100%">';
1143 1143
 
1144 1144
         // Name, firstname
1145
-	    print '<tr><td class="titlefieldcreate">';
1145
+        print '<tr><td class="titlefieldcreate">';
1146 1146
         if ($object->particulier || $private)
1147 1147
         {
1148
-	        print '<span id="TypeName" class="fieldrequired">'.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName','name').'</span>';
1148
+            print '<span id="TypeName" class="fieldrequired">'.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName','name').'</span>';
1149 1149
         }
1150 1150
         else
1151
-		{
1152
-			print '<span id="TypeName" class="fieldrequired">'.$form->editfieldkey('ThirdPartyName', 'name', '', $object, 0).'</span>';
1151
+        {
1152
+            print '<span id="TypeName" class="fieldrequired">'.$form->editfieldkey('ThirdPartyName', 'name', '', $object, 0).'</span>';
1153 1153
         }
1154
-	    print '</td><td'.(empty($conf->global->SOCIETE_USEPREFIX)?' colspan="3"':'').'>';
1155
-	    print '<input type="text" class="minwidth300" maxlength="128" name="name" id="name" value="'.$object->name.'" autofocus="autofocus"></td>';
1156
-	    if (! empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
1157
-	    {
1158
-		    print '<td>'.$langs->trans('Prefix').'</td><td><input type="text" size="5" maxlength="5" name="prefix_comm" value="'.$object->prefix_comm.'"></td>';
1159
-	    }
1160
-	    print '</tr>';
1154
+        print '</td><td'.(empty($conf->global->SOCIETE_USEPREFIX)?' colspan="3"':'').'>';
1155
+        print '<input type="text" class="minwidth300" maxlength="128" name="name" id="name" value="'.$object->name.'" autofocus="autofocus"></td>';
1156
+        if (! empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
1157
+        {
1158
+            print '<td>'.$langs->trans('Prefix').'</td><td><input type="text" size="5" maxlength="5" name="prefix_comm" value="'.$object->prefix_comm.'"></td>';
1159
+        }
1160
+        print '</tr>';
1161 1161
 
1162 1162
         // If javascript on, we show option individual
1163 1163
         if ($conf->use_javascript_ajax)
1164 1164
         {
1165 1165
             print '<tr class="individualline"><td>'.$form->editfieldkey('FirstName', 'firstname', '', $object, 0).'</td>';
1166
-	        print '<td colspan="3"><input type="text" class="minwidth300" maxlength="128" name="firstname" id="firstname" value="'.$object->firstname.'"></td>';
1166
+            print '<td colspan="3"><input type="text" class="minwidth300" maxlength="128" name="firstname" id="firstname" value="'.$object->firstname.'"></td>';
1167 1167
             print '</tr>';
1168 1168
             // Title
1169 1169
             print '<tr class="individualline"><td>'.$form->editfieldkey('UserTitle', 'civility_id', '', $object, 0).'</td><td colspan="3" class="maxwidthonsmartphone">';
@@ -1173,12 +1173,12 @@  discard block
 block discarded – undo
1173 1173
 
1174 1174
         // Alias names (commercial, trademark or alias names)
1175 1175
         print '<tr id="name_alias"><td><label for="name_alias_input">'.$langs->trans('AliasNames').'</label></td>';
1176
-	    print '<td colspan="3"><input type="text" class="minwidth300" name="name_alias" id="name_alias_input" value="'.$object->name_alias.'"></td></tr>';
1176
+        print '<td colspan="3"><input type="text" class="minwidth300" name="name_alias" id="name_alias_input" value="'.$object->name_alias.'"></td></tr>';
1177 1177
 
1178 1178
         // Prospect/Customer
1179 1179
         print '<tr><td class="titlefieldcreate">'.$form->editfieldkey('ProspectCustomer', 'customerprospect', '', $object, 0, 'string', '', 1).'</td>';
1180
-	    print '<td class="maxwidthonsmartphone">';
1181
-	    $selected=GETPOST('client','int')!=''?GETPOST('client','int'):$object->client;
1180
+        print '<td class="maxwidthonsmartphone">';
1181
+        $selected=GETPOST('client','int')!=''?GETPOST('client','int'):$object->client;
1182 1182
         print '<select class="flat" name="client" id="customerprospect">';
1183 1183
         if (GETPOST("type") == '') print '<option value="-1">&nbsp;</option>';
1184 1184
         if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="2"'.($selected==2?' selected':'').'>'.$langs->trans('Prospect').'</option>';
@@ -1189,7 +1189,7 @@  discard block
 block discarded – undo
1189 1189
 
1190 1190
         print '<td>'.$form->editfieldkey('CustomerCode', 'customer_code', '', $object, 0).'</td><td>';
1191 1191
         print '<table class="nobordernopadding"><tr><td>';
1192
-		$tmpcode=$object->code_client;
1192
+        $tmpcode=$object->code_client;
1193 1193
         if (empty($tmpcode) && ! empty($modCodeClient->code_auto)) $tmpcode=$modCodeClient->getNextValue($object,0);
1194 1194
         print '<input type="text" name="customer_code" id="customer_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">';
1195 1195
         print '</td><td>';
@@ -1199,7 +1199,7 @@  discard block
 block discarded – undo
1199 1199
         print '</td></tr>';
1200 1200
 
1201 1201
         if ((! empty($conf->fournisseur->enabled) && ! empty($user->rights->fournisseur->lire))
1202
-        	|| (! empty($conf->supplier_proposal->enabled) && ! empty($user->rights->supplier_proposal->lire)))
1202
+            || (! empty($conf->supplier_proposal->enabled) && ! empty($user->rights->supplier_proposal->lire)))
1203 1203
         {
1204 1204
             // Supplier
1205 1205
             print '<tr>';
@@ -1211,19 +1211,19 @@  discard block
 block discarded – undo
1211 1211
             print '<td>';
1212 1212
             if (! empty($conf->fournisseur->enabled) && ! empty($user->rights->fournisseur->lire))
1213 1213
             {
1214
-            	print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0);
1214
+                print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0);
1215 1215
             }
1216 1216
             print '</td><td>';
1217 1217
             if (! empty($conf->fournisseur->enabled) && ! empty($user->rights->fournisseur->lire))
1218 1218
             {
1219
-	            print '<table class="nobordernopadding"><tr><td>';
1220
-	            $tmpcode=$object->code_fournisseur;
1221
-	            if (empty($tmpcode) && ! empty($modCodeFournisseur->code_auto)) $tmpcode=$modCodeFournisseur->getNextValue($object,1);
1222
-	            print '<input type="text" name="supplier_code" id="supplier_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">';
1223
-	            print '</td><td>';
1224
-	            $s=$modCodeFournisseur->getToolTip($langs,$object,1);
1225
-	            print $form->textwithpicto('',$s,1);
1226
-	            print '</td></tr></table>';
1219
+                print '<table class="nobordernopadding"><tr><td>';
1220
+                $tmpcode=$object->code_fournisseur;
1221
+                if (empty($tmpcode) && ! empty($modCodeFournisseur->code_auto)) $tmpcode=$modCodeFournisseur->getNextValue($object,1);
1222
+                print '<input type="text" name="supplier_code" id="supplier_code" class="maxwidthonsmartphone" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">';
1223
+                print '</td><td>';
1224
+                $s=$modCodeFournisseur->getToolTip($langs,$object,1);
1225
+                print $form->textwithpicto('',$s,1);
1226
+                print '</td></tr></table>';
1227 1227
             }
1228 1228
             print '</td></tr>';
1229 1229
         }
@@ -1237,13 +1237,13 @@  discard block
 block discarded – undo
1237 1237
         if (! empty($conf->barcode->enabled))
1238 1238
         {
1239 1239
             print '<tr><td>'.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).'</td>';
1240
-	        print '<td colspan="3"><input type="text" name="barcode" id="barcode" value="'.$object->barcode.'">';
1240
+            print '<td colspan="3"><input type="text" name="barcode" id="barcode" value="'.$object->barcode.'">';
1241 1241
             print '</td></tr>';
1242 1242
         }
1243 1243
 
1244 1244
         // Address
1245 1245
         print '<tr><td class="tdtop">'.$form->editfieldkey('Address', 'address', '', $object, 0).'</td>';
1246
-	    print '<td colspan="3"><textarea name="address" id="address" class="quatrevingtpercent" rows="'.ROWS_2.'" wrap="soft">';
1246
+        print '<td colspan="3"><textarea name="address" id="address" class="quatrevingtpercent" rows="'.ROWS_2.'" wrap="soft">';
1247 1247
         print $object->address;
1248 1248
         print '</textarea></td></tr>';
1249 1249
 
@@ -1279,43 +1279,43 @@  discard block
 block discarded – undo
1279 1279
 
1280 1280
         // Email / Web
1281 1281
         print '<tr><td>'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '', $conf->global->SOCIETE_EMAIL_MANDATORY).'</td>';
1282
-	    print '<td colspan="3"><input type="text" name="email" id="email" value="'.$object->email.'"></td></tr>';
1282
+        print '<td colspan="3"><input type="text" name="email" id="email" value="'.$object->email.'"></td></tr>';
1283 1283
         print '<tr><td>'.$form->editfieldkey('Web', 'url', '', $object, 0).'</td>';
1284
-	    print '<td colspan="3"><input type="text" name="url" id="url" value="'.$object->url.'"></td></tr>';
1284
+        print '<td colspan="3"><input type="text" name="url" id="url" value="'.$object->url.'"></td></tr>';
1285 1285
 
1286 1286
         if (! empty($conf->socialnetworks->enabled))
1287 1287
         {
1288
-        	// Skype
1289
-        	if (! empty($conf->global->SOCIALNETWORKS_SKYPE))
1290
-        	{
1291
-        		print '<tr><td>'.$form->editfieldkey('Skype', 'skype', '', $object, 0).'</td>';
1292
-				print '<td colspan="3">';
1293
-				print '<input type="text" name="skype" class="minwidth100" maxlength="80" id="skype" value="'.dol_escape_htmltag(GETPOSTISSET("skype")?GETPOST("skype",'alpha'):$object->skype).'">';
1294
-				print '</td></tr>';
1295
-        	}
1296
-        	// Twitter
1297
-        	if (! empty($conf->global->SOCIALNETWORKS_TWITTER))
1298
-        	{
1299
-        		print '<tr><td>'.$form->editfieldkey('Twitter', 'twitter', '', $object, 0).'</td>';
1300
-				print '<td colspan="3">';
1301
-				print '<input type="text" name="twitter" class="minwidth100" maxlength="80" id="twitter" value="'.dol_escape_htmltag(GETPOSTISSET("twitter")?GETPOST("twitter",'alpha'):$object->twitter).'">';
1302
-				print '</td></tr>';
1303
-        	}
1304
-        	// Facebook
1305
-        	if (! empty($conf->global->SOCIALNETWORKS_FACEBOOK))
1306
-        	{
1307
-	        	print '<tr><td>'.$form->editfieldkey('Facebook', 'facebook', '', $object, 0).'</td>';
1308
-				print '<td colspan="3">';
1309
-				print '<input type="text" name="facebook" class="minwidth100" maxlength="80" id="facebook" value="'.dol_escape_htmltag(GETPOSTISSET("facebook")?GETPOST("facebook",'alpha'):$object->facebook).'">';
1310
-				print '</td></tr>';
1311
-        	}
1288
+            // Skype
1289
+            if (! empty($conf->global->SOCIALNETWORKS_SKYPE))
1290
+            {
1291
+                print '<tr><td>'.$form->editfieldkey('Skype', 'skype', '', $object, 0).'</td>';
1292
+                print '<td colspan="3">';
1293
+                print '<input type="text" name="skype" class="minwidth100" maxlength="80" id="skype" value="'.dol_escape_htmltag(GETPOSTISSET("skype")?GETPOST("skype",'alpha'):$object->skype).'">';
1294
+                print '</td></tr>';
1295
+            }
1296
+            // Twitter
1297
+            if (! empty($conf->global->SOCIALNETWORKS_TWITTER))
1298
+            {
1299
+                print '<tr><td>'.$form->editfieldkey('Twitter', 'twitter', '', $object, 0).'</td>';
1300
+                print '<td colspan="3">';
1301
+                print '<input type="text" name="twitter" class="minwidth100" maxlength="80" id="twitter" value="'.dol_escape_htmltag(GETPOSTISSET("twitter")?GETPOST("twitter",'alpha'):$object->twitter).'">';
1302
+                print '</td></tr>';
1303
+            }
1304
+            // Facebook
1305
+            if (! empty($conf->global->SOCIALNETWORKS_FACEBOOK))
1306
+            {
1307
+                print '<tr><td>'.$form->editfieldkey('Facebook', 'facebook', '', $object, 0).'</td>';
1308
+                print '<td colspan="3">';
1309
+                print '<input type="text" name="facebook" class="minwidth100" maxlength="80" id="facebook" value="'.dol_escape_htmltag(GETPOSTISSET("facebook")?GETPOST("facebook",'alpha'):$object->facebook).'">';
1310
+                print '</td></tr>';
1311
+            }
1312 1312
         }
1313 1313
 
1314 1314
         // Phone / Fax
1315 1315
         print '<tr><td>'.$form->editfieldkey('Phone', 'phone', '', $object, 0).'</td>';
1316
-	    print '<td><input type="text" name="phone" id="phone" class="maxwidth100onsmartphone quatrevingtpercent" value="'.$object->phone.'"></td>';
1316
+        print '<td><input type="text" name="phone" id="phone" class="maxwidth100onsmartphone quatrevingtpercent" value="'.$object->phone.'"></td>';
1317 1317
         print '<td>'.$form->editfieldkey('Fax', 'fax', '', $object, 0).'</td>';
1318
-	    print '<td><input type="text" name="fax" id="fax" class="maxwidth100onsmartphone quatrevingtpercent" value="'.$object->fax.'"></td></tr>';
1318
+        print '<td><input type="text" name="fax" id="fax" class="maxwidth100onsmartphone quatrevingtpercent" value="'.$object->fax.'"></td></tr>';
1319 1319
 
1320 1320
         // Prof ids
1321 1321
         $i=1; $j=0;
@@ -1324,7 +1324,7 @@  discard block
 block discarded – undo
1324 1324
             $idprof=$langs->transcountry('ProfId'.$i,$object->country_code);
1325 1325
             if ($idprof!='-')
1326 1326
             {
1327
-	            $key='idprof'.$i;
1327
+                $key='idprof'.$i;
1328 1328
 
1329 1329
                 if (($j % 2) == 0) print '<tr>';
1330 1330
 
@@ -1423,7 +1423,7 @@  discard block
 block discarded – undo
1423 1423
 
1424 1424
         // Capital
1425 1425
         print '<tr><td>'.$form->editfieldkey('Capital', 'capital', '', $object, 0).'</td>';
1426
-	    print '<td colspan="3"><input type="text" name="capital" id="capital" size="10" value="'.$object->capital.'"> ';
1426
+        print '<td colspan="3"><input type="text" name="capital" id="capital" size="10" value="'.$object->capital.'"> ';
1427 1427
         print '<span class="hideonsmartphone">'.$langs->trans("Currency".$conf->currency).'</span></td></tr>';
1428 1428
 
1429 1429
         if (! empty($conf->global->MAIN_MULTILANGS))
@@ -1434,47 +1434,47 @@  discard block
 block discarded – undo
1434 1434
             print '</tr>';
1435 1435
         }
1436 1436
 
1437
-		// Incoterms
1438
-		if (!empty($conf->incoterm->enabled))
1439
-		{
1440
-			print '<tr>';
1441
-			print '<td>'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).'</td>';
1442
-	        print '<td colspan="3" class="maxwidthonsmartphone">';
1443
-	        print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''));
1444
-			print '</td></tr>';
1445
-		}
1446
-
1447
-		// Categories
1448
-		if (! empty($conf->categorie->enabled)  && ! empty($user->rights->categorie->lire))
1449
-		{
1450
-			$langs->load('categories');
1451
-
1452
-			// Customer
1453
-			//if ($object->prospect || $object->client || (! $object->fournisseur && ! empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER))) {
1454
-			print '<tr class="visibleifcustomer"><td class="toptd">' . $form->editfieldkey('CustomersProspectsCategoriesShort', 'custcats', '', $object, 0) . '</td><td colspan="3">';
1455
-			$cate_arbo = $form->select_all_categories(Categorie::TYPE_CUSTOMER, null, 'parent', null, null, 1);
1456
-			print $form->multiselectarray('custcats', $cate_arbo, GETPOST('custcats', 'array'), null, null, null, null, "90%");
1457
-			print "</td></tr>";
1458
-			//}
1459
-
1460
-			// Supplier
1461
-			//if ($object->fournisseur) {
1462
-			print '<tr class="visibleifsupplier"><td class="toptd">' . $form->editfieldkey('SuppliersCategoriesShort', 'suppcats', '', $object, 0) . '</td><td colspan="3">';
1463
-			$cate_arbo = $form->select_all_categories(Categorie::TYPE_SUPPLIER, null, 'parent', null, null, 1);
1464
-			print $form->multiselectarray('suppcats', $cate_arbo, GETPOST('suppcats', 'array'), null, null, null, null, "90%");
1465
-			print "</td></tr>";
1466
-			//}
1467
-		}
1468
-
1469
-		// Multicurrency
1470
-		if (! empty($conf->multicurrency->enabled))
1471
-		{
1472
-			print '<tr>';
1473
-			print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
1474
-	        print '<td colspan="3" class="maxwidthonsmartphone">';
1475
-	        print $form->selectMultiCurrency(($object->multicurrency_code ? $object->multicurrency_code : $conf->currency), 'multicurrency_code', 1);
1476
-			print '</td></tr>';
1477
-		}
1437
+        // Incoterms
1438
+        if (!empty($conf->incoterm->enabled))
1439
+        {
1440
+            print '<tr>';
1441
+            print '<td>'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).'</td>';
1442
+            print '<td colspan="3" class="maxwidthonsmartphone">';
1443
+            print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''));
1444
+            print '</td></tr>';
1445
+        }
1446
+
1447
+        // Categories
1448
+        if (! empty($conf->categorie->enabled)  && ! empty($user->rights->categorie->lire))
1449
+        {
1450
+            $langs->load('categories');
1451
+
1452
+            // Customer
1453
+            //if ($object->prospect || $object->client || (! $object->fournisseur && ! empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER))) {
1454
+            print '<tr class="visibleifcustomer"><td class="toptd">' . $form->editfieldkey('CustomersProspectsCategoriesShort', 'custcats', '', $object, 0) . '</td><td colspan="3">';
1455
+            $cate_arbo = $form->select_all_categories(Categorie::TYPE_CUSTOMER, null, 'parent', null, null, 1);
1456
+            print $form->multiselectarray('custcats', $cate_arbo, GETPOST('custcats', 'array'), null, null, null, null, "90%");
1457
+            print "</td></tr>";
1458
+            //}
1459
+
1460
+            // Supplier
1461
+            //if ($object->fournisseur) {
1462
+            print '<tr class="visibleifsupplier"><td class="toptd">' . $form->editfieldkey('SuppliersCategoriesShort', 'suppcats', '', $object, 0) . '</td><td colspan="3">';
1463
+            $cate_arbo = $form->select_all_categories(Categorie::TYPE_SUPPLIER, null, 'parent', null, null, 1);
1464
+            print $form->multiselectarray('suppcats', $cate_arbo, GETPOST('suppcats', 'array'), null, null, null, null, "90%");
1465
+            print "</td></tr>";
1466
+            //}
1467
+        }
1468
+
1469
+        // Multicurrency
1470
+        if (! empty($conf->multicurrency->enabled))
1471
+        {
1472
+            print '<tr>';
1473
+            print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
1474
+            print '<td colspan="3" class="maxwidthonsmartphone">';
1475
+            print $form->selectMultiCurrency(($object->multicurrency_code ? $object->multicurrency_code : $conf->currency), 'multicurrency_code', 1);
1476
+            print '</td></tr>';
1477
+        }
1478 1478
 
1479 1479
         // Other attributes
1480 1480
         $parameters=array('colspan' => ' colspan="3"', 'colspanvalue' => '3');
@@ -1482,17 +1482,17 @@  discard block
 block discarded – undo
1482 1482
         print $hookmanager->resPrint;
1483 1483
         if (empty($reshook))
1484 1484
         {
1485
-        	print $object->showOptionals($extrafields,'edit');
1485
+            print $object->showOptionals($extrafields,'edit');
1486 1486
         }
1487 1487
 
1488
-		// Assign a sale representative
1489
-		print '<tr>';
1490
-		print '<td>'.$form->editfieldkey('AllocateCommercial', 'commercial_id', '', $object, 0).'</td>';
1491
-		print '<td colspan="3" class="maxwidthonsmartphone">';
1492
-		$userlist = $form->select_dolusers('', '', 0, null, 0, '', '', 0, 0, 0, '', 0, '', '', 0, 1);
1493
-		// Note: If user has no right to "see all thirdparties", we for selection of sale representative to him, so after creation he can see the record.
1494
-		print $form->multiselectarray('commercial', $userlist, (count(GETPOST('commercial', 'array')) > 0?GETPOST('commercial', 'array'):(empty($user->rights->societe->client->voir)?array($user->id):array())), null, null, null, null, "90%");
1495
-		print '</td></tr>';
1488
+        // Assign a sale representative
1489
+        print '<tr>';
1490
+        print '<td>'.$form->editfieldkey('AllocateCommercial', 'commercial_id', '', $object, 0).'</td>';
1491
+        print '<td colspan="3" class="maxwidthonsmartphone">';
1492
+        $userlist = $form->select_dolusers('', '', 0, null, 0, '', '', 0, 0, 0, '', 0, '', '', 0, 1);
1493
+        // Note: If user has no right to "see all thirdparties", we for selection of sale representative to him, so after creation he can see the record.
1494
+        print $form->multiselectarray('commercial', $userlist, (count(GETPOST('commercial', 'array')) > 0?GETPOST('commercial', 'array'):(empty($user->rights->societe->client->voir)?array($user->id):array())), null, null, null, null, "90%");
1495
+        print '</td></tr>';
1496 1496
 
1497 1497
         // Ajout du logo
1498 1498
         print '<tr class="hideonsmartphone">';
@@ -1528,10 +1528,10 @@  discard block
 block discarded – undo
1528 1528
 
1529 1529
         if ($socid)
1530 1530
         {
1531
-        	$res=$object->fetch_optionals();
1531
+            $res=$object->fetch_optionals();
1532 1532
             //if ($res < 0) { dol_print_error($db); exit; }
1533 1533
 
1534
-	        $head = societe_prepare_head($object);
1534
+            $head = societe_prepare_head($object);
1535 1535
 
1536 1536
             // Load object modCodeTiers
1537 1537
             $module=(! empty($conf->global->SOCIETE_CODECLIENT_ADDON)?$conf->global->SOCIETE_CODECLIENT_ADDON:'mod_codeclient_leopard');
@@ -1569,7 +1569,7 @@  discard block
 block discarded – undo
1569 1569
                 $prefixSupplierIsUsed = $modCodeFournisseur->verif_prefixIsUsed();
1570 1570
             }
1571 1571
 
1572
-			$object->oldcopy = clone $object;
1572
+            $object->oldcopy = clone $object;
1573 1573
 
1574 1574
             if (GETPOSTISSET('name'))
1575 1575
             {
@@ -1613,12 +1613,12 @@  discard block
 block discarded – undo
1613 1613
                 $object->webservices_url        = GETPOST('webservices_url', 'custom', 0, FILTER_SANITIZE_URL);
1614 1614
                 $object->webservices_key        = GETPOST('webservices_key', 'san_alpha');
1615 1615
 
1616
-				//Incoterms
1617
-				if (!empty($conf->incoterm->enabled))
1618
-				{
1619
-					$object->fk_incoterms			= GETPOST('incoterm_id', 'int');
1620
-					$object->location_incoterms		= GETPOST('lcoation_incoterms', 'alpha');
1621
-				}
1616
+                //Incoterms
1617
+                if (!empty($conf->incoterm->enabled))
1618
+                {
1619
+                    $object->fk_incoterms			= GETPOST('incoterm_id', 'int');
1620
+                    $object->location_incoterms		= GETPOST('lcoation_incoterms', 'alpha');
1621
+                }
1622 1622
 
1623 1623
                 //Local Taxes
1624 1624
                 $object->localtax1_assuj		= GETPOST('localtax1assuj_value');
@@ -1630,23 +1630,23 @@  discard block
 block discarded – undo
1630 1630
                 // We set country_id, and country_code label of the chosen country
1631 1631
                 if ($object->country_id > 0)
1632 1632
                 {
1633
-                	$tmparray=getCountry($object->country_id,'all');
1633
+                    $tmparray=getCountry($object->country_id,'all');
1634 1634
                     $object->country_code	= $tmparray['code'];
1635 1635
                     $object->country		= $tmparray['label'];
1636 1636
                 }
1637 1637
             }
1638 1638
 
1639 1639
             if($object->localtax1_assuj==0){
1640
-            	$sub=0;
1640
+                $sub=0;
1641 1641
             }else{$sub=1;}
1642 1642
             if($object->localtax2_assuj==0){
1643
-            	$sub2=0;
1643
+                $sub2=0;
1644 1644
             }else{$sub2=1;}
1645 1645
 
1646 1646
             if ($conf->use_javascript_ajax)
1647 1647
             {
1648
-            	print "\n".'<script type="text/javascript">';
1649
-            	print '$(document).ready(function () {
1648
+                print "\n".'<script type="text/javascript">';
1649
+                print '$(document).ready(function () {
1650 1650
     			var val='.$sub.';
1651 1651
     			var val2='.$sub2.';
1652 1652
     			if("#localtax1assuj_value".value==undefined){
@@ -1735,20 +1735,20 @@  discard block
 block discarded – undo
1735 1735
             print '<table class="border" width="100%">';
1736 1736
 
1737 1737
             // Ref/ID
1738
-			if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID))
1739
-			{
1740
-		        print '<tr><td class="titlefieldcreate">'.$langs->trans("ID").'</td><td colspan="3">';
1741
-            	print $object->ref;
1742
-            	print '</td></tr>';
1743
-			}
1738
+            if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID))
1739
+            {
1740
+                print '<tr><td class="titlefieldcreate">'.$langs->trans("ID").'</td><td colspan="3">';
1741
+                print $object->ref;
1742
+                print '</td></tr>';
1743
+            }
1744 1744
 
1745 1745
             // Name
1746 1746
             print '<tr><td class="titlefieldcreate">'.$form->editfieldkey('ThirdPartyName', 'name', '', $object, 0, 'string', '', 1).'</td>';
1747
-	        print '<td colspan="3"><input type="text" class="minwidth300" maxlength="128" name="name" id="name" value="'.dol_escape_htmltag($object->name).'" autofocus="autofocus"></td></tr>';
1747
+            print '<td colspan="3"><input type="text" class="minwidth300" maxlength="128" name="name" id="name" value="'.dol_escape_htmltag($object->name).'" autofocus="autofocus"></td></tr>';
1748 1748
 
1749
-	        // Alias names (commercial, trademark or alias names)
1750
-	        print '<tr id="name_alias"><td><label for="name_alias_input">'.$langs->trans('AliasNames').'</label></td>';
1751
-	        print '<td colspan="3"><input type="text" class="minwidth300" name="name_alias" id="name_alias_input" value="'.dol_escape_htmltag($object->name_alias).'"></td></tr>';
1749
+            // Alias names (commercial, trademark or alias names)
1750
+            print '<tr id="name_alias"><td><label for="name_alias_input">'.$langs->trans('AliasNames').'</label></td>';
1751
+            print '<td colspan="3"><input type="text" class="minwidth300" name="name_alias" id="name_alias_input" value="'.dol_escape_htmltag($object->name_alias).'"></td></tr>';
1752 1752
 
1753 1753
             // Prefix
1754 1754
             if (! empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
@@ -1769,7 +1769,7 @@  discard block
 block discarded – undo
1769 1769
 
1770 1770
             // Prospect/Customer
1771 1771
             print '<tr><td>'.$form->editfieldkey('ProspectCustomer', 'customerprospect', '', $object, 0, 'string', '', 1).'</td>';
1772
-	        print '<td class="maxwidthonsmartphone"><select class="flat" name="client" id="customerprospect">';
1772
+            print '<td class="maxwidthonsmartphone"><select class="flat" name="client" id="customerprospect">';
1773 1773
             if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="2"'.($object->client==2?' selected':'').'>'.$langs->trans('Prospect').'</option>';
1774 1774
             if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print '<option value="3"'.($object->client==3?' selected':'').'>'.$langs->trans('ProspectCustomer').'</option>';
1775 1775
             if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print '<option value="1"'.($object->client==1?' selected':'').'>'.$langs->trans('Customer').'</option>';
@@ -1787,7 +1787,7 @@  discard block
 block discarded – undo
1787 1787
             }
1788 1788
             else if ($object->codeclient_modifiable())
1789 1789
             {
1790
-            	print '<input type="text" name="customer_code" id="customer_code" size="16" value="'.dol_escape_htmltag($object->code_client).'" maxlength="15">';
1790
+                print '<input type="text" name="customer_code" id="customer_code" size="16" value="'.dol_escape_htmltag($object->code_client).'" maxlength="15">';
1791 1791
             }
1792 1792
             else
1793 1793
             {
@@ -1803,7 +1803,7 @@  discard block
 block discarded – undo
1803 1803
 
1804 1804
             // Supplier
1805 1805
             if ((! empty($conf->fournisseur->enabled) && ! empty($user->rights->fournisseur->lire))
1806
-            	|| (! empty($conf->supplier_proposal->enabled) && ! empty($user->rights->supplier_proposal->lire)))
1806
+                || (! empty($conf->supplier_proposal->enabled) && ! empty($user->rights->supplier_proposal->lire)))
1807 1807
             {
1808 1808
                 print '<tr>';
1809 1809
                 print '<td>'.$form->editfieldkey('Supplier', 'fournisseur', '', $object, 0, 'string', '', 1).'</td><td class="maxwidthonsmartphone">';
@@ -1812,32 +1812,32 @@  discard block
 block discarded – undo
1812 1812
                 print '<td>';
1813 1813
                 if (! empty($conf->fournisseur->enabled) && ! empty($user->rights->fournisseur->lire))
1814 1814
                 {
1815
-                	print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0);
1815
+                    print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0);
1816 1816
                 }
1817 1817
                 print '</td><td>';
1818 1818
                 if (! empty($conf->fournisseur->enabled) && ! empty($user->rights->fournisseur->lire))
1819 1819
                 {
1820
-	                print '<table class="nobordernopadding"><tr><td>';
1821
-	                if ((!$object->code_fournisseur || $object->code_fournisseur == -1) && $modCodeFournisseur->code_auto)
1822
-	                {
1823
-	                    $tmpcode=$object->code_fournisseur;
1824
-	                    if (empty($tmpcode) && ! empty($object->oldcopy->code_fournisseur)) $tmpcode=$object->oldcopy->code_fournisseur; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value.
1825
-	                    if (empty($tmpcode) && ! empty($modCodeFournisseur->code_auto)) $tmpcode=$modCodeFournisseur->getNextValue($object,1);
1826
-	                    print '<input type="text" name="supplier_code" id="supplier_code" size="16" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">';
1827
-	                }
1828
-	                else if ($object->codefournisseur_modifiable())
1829
-	                {
1830
-	                    print '<input type="text" name="supplier_code" id="supplier_code" size="16" value="'.$object->code_fournisseur.'" maxlength="15">';
1831
-	                }
1832
-	                else
1833
-	              {
1834
-	                    print $object->code_fournisseur;
1835
-	                    print '<input type="hidden" name="supplier_code" value="'.$object->code_fournisseur.'">';
1836
-	                }
1837
-	                print '</td><td>';
1838
-	                $s=$modCodeFournisseur->getToolTip($langs,$object,1);
1839
-	                print $form->textwithpicto('',$s,1);
1840
-	                print '</td></tr></table>';
1820
+                    print '<table class="nobordernopadding"><tr><td>';
1821
+                    if ((!$object->code_fournisseur || $object->code_fournisseur == -1) && $modCodeFournisseur->code_auto)
1822
+                    {
1823
+                        $tmpcode=$object->code_fournisseur;
1824
+                        if (empty($tmpcode) && ! empty($object->oldcopy->code_fournisseur)) $tmpcode=$object->oldcopy->code_fournisseur; // When there is an error to update a thirdparty, the number for supplier and customer code is kept to old value.
1825
+                        if (empty($tmpcode) && ! empty($modCodeFournisseur->code_auto)) $tmpcode=$modCodeFournisseur->getNextValue($object,1);
1826
+                        print '<input type="text" name="supplier_code" id="supplier_code" size="16" value="'.dol_escape_htmltag($tmpcode).'" maxlength="15">';
1827
+                    }
1828
+                    else if ($object->codefournisseur_modifiable())
1829
+                    {
1830
+                        print '<input type="text" name="supplier_code" id="supplier_code" size="16" value="'.$object->code_fournisseur.'" maxlength="15">';
1831
+                    }
1832
+                    else
1833
+                    {
1834
+                        print $object->code_fournisseur;
1835
+                        print '<input type="hidden" name="supplier_code" value="'.$object->code_fournisseur.'">';
1836
+                    }
1837
+                    print '</td><td>';
1838
+                    $s=$modCodeFournisseur->getToolTip($langs,$object,1);
1839
+                    print $form->textwithpicto('',$s,1);
1840
+                    print '</td></tr></table>';
1841 1841
                 }
1842 1842
                 print '</td></tr>';
1843 1843
             }
@@ -1846,7 +1846,7 @@  discard block
 block discarded – undo
1846 1846
             if (! empty($conf->barcode->enabled))
1847 1847
             {
1848 1848
                 print '<tr><td class="tdtop">'.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).'</td>';
1849
-	            print '<td colspan="3"><input type="text" name="barcode" id="barcode" value="'.$object->barcode.'">';
1849
+                print '<td colspan="3"><input type="text" name="barcode" id="barcode" value="'.$object->barcode.'">';
1850 1850
                 print '</td></tr>';
1851 1851
             }
1852 1852
 
@@ -1857,7 +1857,7 @@  discard block
 block discarded – undo
1857 1857
 
1858 1858
             // Address
1859 1859
             print '<tr><td class="tdtop">'.$form->editfieldkey('Address', 'address', '', $object, 0).'</td>';
1860
-	        print '<td colspan="3"><textarea name="address" id="address" class="quatrevingtpercent" rows="3" wrap="soft">';
1860
+            print '<td colspan="3"><textarea name="address" id="address" class="quatrevingtpercent" rows="3" wrap="soft">';
1861 1861
             print $object->address;
1862 1862
             print '</textarea></td></tr>';
1863 1863
 
@@ -1892,37 +1892,37 @@  discard block
 block discarded – undo
1892 1892
 
1893 1893
             // EMail / Web
1894 1894
             print '<tr><td>'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '', (! empty($conf->global->SOCIETE_EMAIL_MANDATORY))).'</td>';
1895
-	        print '<td colspan="3"><input type="text" name="email" id="email" size="32" value="'.$object->email.'"></td></tr>';
1895
+            print '<td colspan="3"><input type="text" name="email" id="email" size="32" value="'.$object->email.'"></td></tr>';
1896 1896
             print '<tr><td>'.$form->editfieldkey('Web', 'url', '', $object, 0).'</td>';
1897
-	        print '<td colspan="3"><input type="text" name="url" id="url" size="32" value="'.$object->url.'"></td></tr>';
1898
-
1899
-	        if (! empty($conf->socialnetworks->enabled))
1900
-	        {
1901
-	        	// Skype
1902
-	        	if (! empty($conf->global->SOCIALNETWORKS_SKYPE))
1903
-	        	{
1904
-	        		print '<tr><td>'.$form->editfieldkey('Skype', 'skype', '', $object, 0).'</td>';
1905
-	        		print '<td colspan="3"><input type="text" name="skype" id="skype" value="'.$object->skype.'"></td></tr>';
1906
-	        	}
1907
-	        	// Twitter
1908
-	        	if (! empty($conf->global->SOCIALNETWORKS_TWITTER))
1909
-	        	{
1910
-	        		print '<tr><td>'.$form->editfieldkey('Twitter', 'twitter', '', $object, 0).'</td>';
1911
-	        		print '<td colspan="3"><input type="text" name="twitter" id="twitter" value="'.$object->twitter.'"></td></tr>';
1912
-	        	}
1913
-	        	// Facebook
1914
-	        	if (! empty($conf->global->SOCIALNETWORKS_FACEBOOK))
1915
-	        	{
1916
-	        		print '<tr><td>'.$form->editfieldkey('Facebook', 'facebook', '', $object, 0).'</td>';
1917
-	        		print '<td colspan="3"><input type="text" name="facebook" id="facebook" value="'.$object->facebook.'"></td></tr>';
1918
-	        	}
1919
-	        }
1897
+            print '<td colspan="3"><input type="text" name="url" id="url" size="32" value="'.$object->url.'"></td></tr>';
1898
+
1899
+            if (! empty($conf->socialnetworks->enabled))
1900
+            {
1901
+                // Skype
1902
+                if (! empty($conf->global->SOCIALNETWORKS_SKYPE))
1903
+                {
1904
+                    print '<tr><td>'.$form->editfieldkey('Skype', 'skype', '', $object, 0).'</td>';
1905
+                    print '<td colspan="3"><input type="text" name="skype" id="skype" value="'.$object->skype.'"></td></tr>';
1906
+                }
1907
+                // Twitter
1908
+                if (! empty($conf->global->SOCIALNETWORKS_TWITTER))
1909
+                {
1910
+                    print '<tr><td>'.$form->editfieldkey('Twitter', 'twitter', '', $object, 0).'</td>';
1911
+                    print '<td colspan="3"><input type="text" name="twitter" id="twitter" value="'.$object->twitter.'"></td></tr>';
1912
+                }
1913
+                // Facebook
1914
+                if (! empty($conf->global->SOCIALNETWORKS_FACEBOOK))
1915
+                {
1916
+                    print '<tr><td>'.$form->editfieldkey('Facebook', 'facebook', '', $object, 0).'</td>';
1917
+                    print '<td colspan="3"><input type="text" name="facebook" id="facebook" value="'.$object->facebook.'"></td></tr>';
1918
+                }
1919
+            }
1920 1920
 
1921 1921
             // Phone / Fax
1922 1922
             print '<tr><td>'.$form->editfieldkey('Phone', 'phone', '', $object, 0).'</td>';
1923
-	        print '<td><input type="text" name="phone" id="phone" class="maxwidth100onsmartphone quatrevingtpercent" value="'.$object->phone.'"></td>';
1923
+            print '<td><input type="text" name="phone" id="phone" class="maxwidth100onsmartphone quatrevingtpercent" value="'.$object->phone.'"></td>';
1924 1924
             print '<td>'.$form->editfieldkey('Fax', 'fax', '', $object, 0).'</td>';
1925
-	        print '<td><input type="text" name="fax" id="fax" class="maxwidth100onsmartphone quatrevingtpercent" value="'.$object->fax.'"></td></tr>';
1925
+            print '<td><input type="text" name="fax" id="fax" class="maxwidth100onsmartphone quatrevingtpercent" value="'.$object->fax.'"></td></tr>';
1926 1926
 
1927 1927
             // Prof ids
1928 1928
             $i=1; $j=0;
@@ -1931,13 +1931,13 @@  discard block
 block discarded – undo
1931 1931
                 $idprof=$langs->transcountry('ProfId'.$i,$object->country_code);
1932 1932
                 if ($idprof!='-')
1933 1933
                 {
1934
-	                $key='idprof'.$i;
1934
+                    $key='idprof'.$i;
1935 1935
 
1936
-	                if (($j % 2) == 0) print '<tr>';
1936
+                    if (($j % 2) == 0) print '<tr>';
1937 1937
 
1938
-	                $idprof_mandatory ='SOCIETE_IDPROF'.($i).'_MANDATORY';
1939
-	                print '<td>'.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', ! (empty($conf->global->$idprof_mandatory) || ! $object->isACompany())).'</td><td>';
1940
-	                print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code);
1938
+                    $idprof_mandatory ='SOCIETE_IDPROF'.($i).'_MANDATORY';
1939
+                    print '<td>'.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', ! (empty($conf->global->$idprof_mandatory) || ! $object->isACompany())).'</td><td>';
1940
+                    print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code);
1941 1941
                     print '</td>';
1942 1942
                     if (($j % 2) == 1) print '</tr>';
1943 1943
                     $j++;
@@ -2047,9 +2047,9 @@  discard block
 block discarded – undo
2047 2047
 
2048 2048
             // Capital
2049 2049
             print '<tr><td>'.$form->editfieldkey('Capital', 'capital', '', $object, 0).'</td>';
2050
-	        print '<td colspan="3"><input type="text" name="capital" id="capital" size="10" value="';
2051
-	        print $object->capital != '' ? dol_escape_htmltag(price($object->capital)) : '';
2052
-	        print '"> <font class="hideonsmartphone">'.$langs->trans("Currency".$conf->currency).'</font></td></tr>';
2050
+            print '<td colspan="3"><input type="text" name="capital" id="capital" size="10" value="';
2051
+            print $object->capital != '' ? dol_escape_htmltag(price($object->capital)) : '';
2052
+            print '"> <font class="hideonsmartphone">'.$langs->trans("Currency".$conf->currency).'</font></td></tr>';
2053 2053
 
2054 2054
             // Default language
2055 2055
             if (! empty($conf->global->MAIN_MULTILANGS))
@@ -2063,52 +2063,52 @@  discard block
 block discarded – undo
2063 2063
             // Incoterms
2064 2064
             if (!empty($conf->incoterm->enabled))
2065 2065
             {
2066
-            	print '<tr>';
2067
-      				print '<td>'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).'</td>';
2068
-            	print '<td colspan="3" class="maxwidthonsmartphone">';
2069
-            	print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''));
2070
-            	print '</td></tr>';
2071
-            }
2072
-
2073
-			// Categories
2074
-			if (! empty($conf->categorie->enabled)  && ! empty($user->rights->categorie->lire))
2075
-			{
2076
-				// Customer
2077
-				print '<tr class="visibleifcustomer"><td>' . $form->editfieldkey('CustomersCategoriesShort', 'custcats', '', $object, 0) . '</td>';
2078
-				print '<td colspan="3">';
2079
-				$cate_arbo = $form->select_all_categories(Categorie::TYPE_CUSTOMER, null, null, null, null, 1);
2080
-				$c = new Categorie($db);
2081
-				$cats = $c->containing($object->id, Categorie::TYPE_CUSTOMER);
2082
-				$arrayselected=array();
2083
-				foreach ($cats as $cat) {
2084
-					$arrayselected[] = $cat->id;
2085
-				}
2086
-				print $form->multiselectarray('custcats', $cate_arbo, $arrayselected, '', 0, '', 0, '90%');
2087
-				print "</td></tr>";
2088
-
2089
-				// Supplier
2090
-				print '<tr class="visibleifsupplier"><td>' . $form->editfieldkey('SuppliersCategoriesShort', 'suppcats', '', $object, 0) . '</td>';
2091
-				print '<td colspan="3">';
2092
-				$cate_arbo = $form->select_all_categories(Categorie::TYPE_SUPPLIER, null, null, null, null, 1);
2093
-				$c = new Categorie($db);
2094
-				$cats = $c->containing($object->id, Categorie::TYPE_SUPPLIER);
2095
-				$arrayselected=array();
2096
-				foreach ($cats as $cat) {
2097
-					$arrayselected[] = $cat->id;
2098
-				}
2099
-				print $form->multiselectarray('suppcats', $cate_arbo, $arrayselected, '', 0, '', 0, '90%');
2100
-				print "</td></tr>";
2101
-			}
2102
-
2103
-			// Multicurrency
2104
-			if (! empty($conf->multicurrency->enabled))
2105
-			{
2106
-				print '<tr>';
2107
-				print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
2108
-		        print '<td colspan="3" class="maxwidthonsmartphone">';
2109
-		        print $form->selectMultiCurrency(($object->multicurrency_code ? $object->multicurrency_code : $conf->currency), 'multicurrency_code', 1);
2110
-				print '</td></tr>';
2111
-			}
2066
+                print '<tr>';
2067
+                        print '<td>'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).'</td>';
2068
+                print '<td colspan="3" class="maxwidthonsmartphone">';
2069
+                print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''));
2070
+                print '</td></tr>';
2071
+            }
2072
+
2073
+            // Categories
2074
+            if (! empty($conf->categorie->enabled)  && ! empty($user->rights->categorie->lire))
2075
+            {
2076
+                // Customer
2077
+                print '<tr class="visibleifcustomer"><td>' . $form->editfieldkey('CustomersCategoriesShort', 'custcats', '', $object, 0) . '</td>';
2078
+                print '<td colspan="3">';
2079
+                $cate_arbo = $form->select_all_categories(Categorie::TYPE_CUSTOMER, null, null, null, null, 1);
2080
+                $c = new Categorie($db);
2081
+                $cats = $c->containing($object->id, Categorie::TYPE_CUSTOMER);
2082
+                $arrayselected=array();
2083
+                foreach ($cats as $cat) {
2084
+                    $arrayselected[] = $cat->id;
2085
+                }
2086
+                print $form->multiselectarray('custcats', $cate_arbo, $arrayselected, '', 0, '', 0, '90%');
2087
+                print "</td></tr>";
2088
+
2089
+                // Supplier
2090
+                print '<tr class="visibleifsupplier"><td>' . $form->editfieldkey('SuppliersCategoriesShort', 'suppcats', '', $object, 0) . '</td>';
2091
+                print '<td colspan="3">';
2092
+                $cate_arbo = $form->select_all_categories(Categorie::TYPE_SUPPLIER, null, null, null, null, 1);
2093
+                $c = new Categorie($db);
2094
+                $cats = $c->containing($object->id, Categorie::TYPE_SUPPLIER);
2095
+                $arrayselected=array();
2096
+                foreach ($cats as $cat) {
2097
+                    $arrayselected[] = $cat->id;
2098
+                }
2099
+                print $form->multiselectarray('suppcats', $cate_arbo, $arrayselected, '', 0, '', 0, '90%');
2100
+                print "</td></tr>";
2101
+            }
2102
+
2103
+            // Multicurrency
2104
+            if (! empty($conf->multicurrency->enabled))
2105
+            {
2106
+                print '<tr>';
2107
+                print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
2108
+                print '<td colspan="3" class="maxwidthonsmartphone">';
2109
+                print $form->selectMultiCurrency(($object->multicurrency_code ? $object->multicurrency_code : $conf->currency), 'multicurrency_code', 1);
2110
+                print '</td></tr>';
2111
+            }
2112 2112
 
2113 2113
             // Other attributes
2114 2114
             $parameters=array('colspan' => ' colspan="3"', 'colspanvalue' => '3');
@@ -2116,7 +2116,7 @@  discard block
 block discarded – undo
2116 2116
             print $hookmanager->resPrint;
2117 2117
             if (empty($reshook))
2118 2118
             {
2119
-            	print $object->showOptionals($extrafields,'edit');
2119
+                print $object->showOptionals($extrafields,'edit');
2120 2120
             }
2121 2121
 
2122 2122
             // Webservices url/key
@@ -2158,7 +2158,7 @@  discard block
 block discarded – undo
2158 2158
             print '</table>';
2159 2159
             print '</div>';
2160 2160
 
2161
-	          dol_fiche_end();
2161
+                dol_fiche_end();
2162 2162
 
2163 2163
             print '<div align="center">';
2164 2164
             print '<input type="submit" class="button" name="save" value="'.$langs->trans("Save").'">';
@@ -2171,7 +2171,7 @@  discard block
 block discarded – undo
2171 2171
     }
2172 2172
     else
2173 2173
     {
2174
-    	/*
2174
+        /*
2175 2175
          * View
2176 2176
          */
2177 2177
 
@@ -2189,19 +2189,19 @@  discard block
 block discarded – undo
2189 2189
             print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id, $langs->trans("DeleteACompany"), $langs->trans("ConfirmDeleteCompany"), "confirm_delete", '', 0, "action-delete");
2190 2190
         }
2191 2191
 
2192
-	    if ($action == 'merge')
2193
-	    {
2194
-		    $formquestion = array(
2195
-			    array(
2196
-				    'name' => 'soc_origin',
2197
-			    	'label' => $langs->trans('MergeOriginThirdparty'),
2198
-				    'type' => 'other',
2199
-				    'value' => $form->select_company('', 'soc_origin', 's.rowid != '.$object->id, 'SelectThirdParty', 0, 0, array(), 0, 'minwidth200')
2200
-			    )
2201
-		    );
2202
-
2203
-		    print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id, $langs->trans("MergeThirdparties"), $langs->trans("ConfirmMergeThirdparties"), "confirm_merge", $formquestion, 'no', 1, 250);
2204
-	    }
2192
+        if ($action == 'merge')
2193
+        {
2194
+            $formquestion = array(
2195
+                array(
2196
+                    'name' => 'soc_origin',
2197
+                    'label' => $langs->trans('MergeOriginThirdparty'),
2198
+                    'type' => 'other',
2199
+                    'value' => $form->select_company('', 'soc_origin', 's.rowid != '.$object->id, 'SelectThirdParty', 0, 0, array(), 0, 'minwidth200')
2200
+                )
2201
+            );
2202
+
2203
+            print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id, $langs->trans("MergeThirdparties"), $langs->trans("ConfirmMergeThirdparties"), "confirm_merge", $formquestion, 'no', 1, 250);
2204
+        }
2205 2205
 
2206 2206
         dol_htmloutput_mesg(is_numeric($error)?'':$error, $errors, 'error');
2207 2207
 
@@ -2216,20 +2216,20 @@  discard block
 block discarded – undo
2216 2216
         print '<div class="underbanner clearboth"></div>';
2217 2217
         print '<table class="border tableforfield" width="100%">';
2218 2218
 
2219
-    	// Prospect/Customer
2220
-    	print '<tr><td class="titlefield">'.$langs->trans('ProspectCustomer').'</td><td>';
2221
-    	print $object->getLibCustProspStatut();
2222
-    	print '</td></tr>';
2219
+        // Prospect/Customer
2220
+        print '<tr><td class="titlefield">'.$langs->trans('ProspectCustomer').'</td><td>';
2221
+        print $object->getLibCustProspStatut();
2222
+        print '</td></tr>';
2223 2223
 
2224
-    	// Supplier
2225
-   		if (! empty($conf->fournisseur->enabled) || ! empty($conf->supplier_proposal->enabled))
2226
-    	{
2227
-    		print '<tr><td>'.$langs->trans('Supplier').'</td><td>';
2228
-    		print yn($object->fournisseur);
2229
-    		print '</td></tr>';
2230
-    	}
2224
+        // Supplier
2225
+            if (! empty($conf->fournisseur->enabled) || ! empty($conf->supplier_proposal->enabled))
2226
+        {
2227
+            print '<tr><td>'.$langs->trans('Supplier').'</td><td>';
2228
+            print yn($object->fournisseur);
2229
+            print '</td></tr>';
2230
+        }
2231 2231
 
2232
-    	// Prefix
2232
+        // Prefix
2233 2233
         if (! empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
2234 2234
         {
2235 2235
             print '<tr><td>'.$langs->trans('Prefix').'</td><td>'.$object->prefix_comm.'</td>';
@@ -2267,9 +2267,9 @@  discard block
 block discarded – undo
2267 2267
             print '<tr><td>';
2268 2268
             print $langs->trans('Gencod').'</td><td>'.$object->barcode;
2269 2269
             print '</td>';
2270
-			if ($htmllogobar) $htmllogobar.=$form->showbarcode($object);
2270
+            if ($htmllogobar) $htmllogobar.=$form->showbarcode($object);
2271 2271
             print $htmllogobar;
2272
-			$htmllogobar='';
2272
+            $htmllogobar='';
2273 2273
             print '</tr>';
2274 2274
         }
2275 2275
 
@@ -2282,7 +2282,7 @@  discard block
 block discarded – undo
2282 2282
             {
2283 2283
                 //if (($j % 2) == 0) print '<tr>';
2284 2284
                 print '<tr>';
2285
-            	print '<td>'.$idprof.'</td><td>';
2285
+                print '<td>'.$idprof.'</td><td>';
2286 2286
                 $key='idprof'.$i;
2287 2287
                 print $object->$key;
2288 2288
                 if ($object->$key)
@@ -2306,108 +2306,108 @@  discard block
 block discarded – undo
2306 2306
 
2307 2307
         if ($object->fournisseur)
2308 2308
         {
2309
-	        // VAT is used
2310
-	        print '<tr><td>';
2311
-	        print $form->textwithpicto($langs->trans('VATIsUsed'),$langs->trans('VATIsUsedWhenSelling'));
2312
-	        print '</td><td>';
2313
-	        print yn($object->tva_assuj);
2314
-	        print '</td>';
2315
-			print '</tr>';
2309
+            // VAT is used
2310
+            print '<tr><td>';
2311
+            print $form->textwithpicto($langs->trans('VATIsUsed'),$langs->trans('VATIsUsedWhenSelling'));
2312
+            print '</td><td>';
2313
+            print yn($object->tva_assuj);
2314
+            print '</td>';
2315
+            print '</tr>';
2316 2316
         }
2317 2317
 
2318
-		// Local Taxes
2318
+        // Local Taxes
2319 2319
         if ($object->fournisseur || $mysoc->country_code=='ES')
2320 2320
         {
2321
-        	if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1")
2322
-			{
2323
-			    print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).'</td><td>';
2324
-			    print yn($object->localtax1_assuj);
2325
-			    print '</td></tr><tr><td>'.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).'</td><td>';
2326
-			    print yn($object->localtax2_assuj);
2327
-			    print '</td></tr>';
2328
-
2329
-			    if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1)))
2330
-			    {
2331
-			        print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">';
2332
-			        print '<input type="hidden" name="action" value="set_localtax1">';
2333
-			        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2334
-			        print '<tr><td>'.$langs->transcountry("TypeLocaltax1", $mysoc->country_code).' <a href="'.$_SERVER["PHP_SELF"].'?action=editRE&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</td>';
2335
-			        if($action == 'editRE')
2336
-			        {
2337
-			            print '<td align="left">';
2338
-			            $formcompany->select_localtax(1,$object->localtax1_value, "lt1");
2339
-			            print '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
2340
-			        }
2341
-			        else
2342
-			        {
2343
-			            print '<td>'.$object->localtax1_value.'</td>';
2344
-			        }
2345
-			        print '</tr></form>';
2346
-			    }
2347
-			    if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2)))
2348
-			    {
2349
-			        print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">';
2350
-			        print '<input type="hidden" name="action" value="set_localtax2">';
2351
-			        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2352
-			        print '<tr><td>'.$langs->transcountry("TypeLocaltax2", $mysoc->country_code).'<a href="'.$_SERVER["PHP_SELF"].'?action=editIRPF&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</td>';
2353
-			        if($action == 'editIRPF'){
2354
-			            print '<td align="left">';
2355
-			            $formcompany->select_localtax(2,$object->localtax2_value, "lt2");
2356
-			            print '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
2357
-			        }else{
2358
-			            print '<td>'.$object->localtax2_value.'</td>';
2359
-			        }
2360
-			        print '</tr></form>';
2361
-			    }
2362
-			}
2363
-			elseif($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj!="1")
2364
-			{
2365
-			    print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).'</td><td>';
2366
-			    print yn($object->localtax1_assuj);
2367
-			    print '</td></tr>';
2368
-			    if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1)))
2369
-			    {
2370
-			        print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">';
2371
-			        print '<input type="hidden" name="action" value="set_localtax1">';
2372
-			        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2373
-			        print '<tr><td> '.$langs->transcountry("TypeLocaltax1", $mysoc->country_code).'<a href="'.$_SERVER["PHP_SELF"].'?action=editRE&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</td>';
2374
-			        if($action == 'editRE'){
2375
-			            print '<td align="left">';
2376
-			            $formcompany->select_localtax(1,$object->localtax1_value, "lt1");
2377
-			            print '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
2378
-			        }else{
2379
-			            print '<td>'.$object->localtax1_value.'</td>';
2380
-			        }
2381
-			        print '</tr></form>';
2382
-			    }
2383
-			}
2384
-			elseif($mysoc->localtax2_assuj=="1" && $mysoc->localtax1_assuj!="1")
2385
-			{
2386
-			    print '<tr><td>'.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).'</td><td>';
2387
-			    print yn($object->localtax2_assuj);
2388
-			    print '</td></tr>';
2389
-			    if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2)))
2390
-			    {
2391
-
2392
-			        print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">';
2393
-			        print '<input type="hidden" name="action" value="set_localtax2">';
2394
-			        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2395
-			        print '<tr><td> '.$langs->transcountry("TypeLocaltax2", $mysoc->country_code).' <a href="'.$_SERVER["PHP_SELF"].'?action=editIRPF&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</td>';
2396
-			        if($action == 'editIRPF'){
2397
-			            print '<td align="left">';
2398
-			            $formcompany->select_localtax(2,$object->localtax2_value, "lt2");
2399
-			            print '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
2400
-			        }else{
2401
-			            print '<td>'.$object->localtax2_value.'</td>';
2402
-			        }
2403
-			        print '</tr></form>';
2404
-			    }
2405
-			}
2321
+            if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1")
2322
+            {
2323
+                print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).'</td><td>';
2324
+                print yn($object->localtax1_assuj);
2325
+                print '</td></tr><tr><td>'.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).'</td><td>';
2326
+                print yn($object->localtax2_assuj);
2327
+                print '</td></tr>';
2328
+
2329
+                if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1)))
2330
+                {
2331
+                    print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">';
2332
+                    print '<input type="hidden" name="action" value="set_localtax1">';
2333
+                    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2334
+                    print '<tr><td>'.$langs->transcountry("TypeLocaltax1", $mysoc->country_code).' <a href="'.$_SERVER["PHP_SELF"].'?action=editRE&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</td>';
2335
+                    if($action == 'editRE')
2336
+                    {
2337
+                        print '<td align="left">';
2338
+                        $formcompany->select_localtax(1,$object->localtax1_value, "lt1");
2339
+                        print '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
2340
+                    }
2341
+                    else
2342
+                    {
2343
+                        print '<td>'.$object->localtax1_value.'</td>';
2344
+                    }
2345
+                    print '</tr></form>';
2346
+                }
2347
+                if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2)))
2348
+                {
2349
+                    print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">';
2350
+                    print '<input type="hidden" name="action" value="set_localtax2">';
2351
+                    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2352
+                    print '<tr><td>'.$langs->transcountry("TypeLocaltax2", $mysoc->country_code).'<a href="'.$_SERVER["PHP_SELF"].'?action=editIRPF&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</td>';
2353
+                    if($action == 'editIRPF'){
2354
+                        print '<td align="left">';
2355
+                        $formcompany->select_localtax(2,$object->localtax2_value, "lt2");
2356
+                        print '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
2357
+                    }else{
2358
+                        print '<td>'.$object->localtax2_value.'</td>';
2359
+                    }
2360
+                    print '</tr></form>';
2361
+                }
2362
+            }
2363
+            elseif($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj!="1")
2364
+            {
2365
+                print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).'</td><td>';
2366
+                print yn($object->localtax1_assuj);
2367
+                print '</td></tr>';
2368
+                if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1)))
2369
+                {
2370
+                    print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">';
2371
+                    print '<input type="hidden" name="action" value="set_localtax1">';
2372
+                    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2373
+                    print '<tr><td> '.$langs->transcountry("TypeLocaltax1", $mysoc->country_code).'<a href="'.$_SERVER["PHP_SELF"].'?action=editRE&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</td>';
2374
+                    if($action == 'editRE'){
2375
+                        print '<td align="left">';
2376
+                        $formcompany->select_localtax(1,$object->localtax1_value, "lt1");
2377
+                        print '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
2378
+                    }else{
2379
+                        print '<td>'.$object->localtax1_value.'</td>';
2380
+                    }
2381
+                    print '</tr></form>';
2382
+                }
2383
+            }
2384
+            elseif($mysoc->localtax2_assuj=="1" && $mysoc->localtax1_assuj!="1")
2385
+            {
2386
+                print '<tr><td>'.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).'</td><td>';
2387
+                print yn($object->localtax2_assuj);
2388
+                print '</td></tr>';
2389
+                if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2)))
2390
+                {
2391
+
2392
+                    print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'">';
2393
+                    print '<input type="hidden" name="action" value="set_localtax2">';
2394
+                    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2395
+                    print '<tr><td> '.$langs->transcountry("TypeLocaltax2", $mysoc->country_code).' <a href="'.$_SERVER["PHP_SELF"].'?action=editIRPF&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</td>';
2396
+                    if($action == 'editIRPF'){
2397
+                        print '<td align="left">';
2398
+                        $formcompany->select_localtax(2,$object->localtax2_value, "lt2");
2399
+                        print '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
2400
+                    }else{
2401
+                        print '<td>'.$object->localtax2_value.'</td>';
2402
+                    }
2403
+                    print '</tr></form>';
2404
+                }
2405
+            }
2406 2406
         }
2407 2407
 
2408 2408
         // Sale tax code (VAT code)
2409 2409
         print '<tr>';
2410
-		print '<td class="nowrap">'.$langs->trans('VATIntra').'</td><td>';
2410
+        print '<td class="nowrap">'.$langs->trans('VATIntra').'</td><td>';
2411 2411
         if ($object->tva_intra)
2412 2412
         {
2413 2413
             $s='';
@@ -2458,25 +2458,25 @@  discard block
 block discarded – undo
2458 2458
         print '<div class="underbanner clearboth"></div>';
2459 2459
         print '<table class="border tableforfield" width="100%">';
2460 2460
 
2461
-    	// Tags / categories
2462
-		if (! empty($conf->categorie->enabled)  && ! empty($user->rights->categorie->lire))
2463
-		{
2464
-			// Customer
2465
-			if ($object->prospect || $object->client || (! $object->fournisseur && ! empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER))) {
2466
-				print '<tr><td>' . $langs->trans("CustomersCategoriesShort") . '</td>';
2467
-				print '<td>';
2468
-				print $form->showCategories($object->id, 'customer', 1);
2469
-				print "</td></tr>";
2470
-			}
2471
-
2472
-			// Supplier
2473
-			if ($object->fournisseur) {
2474
-				print '<tr><td>' . $langs->trans("SuppliersCategoriesShort") . '</td>';
2475
-				print '<td>';
2476
-				print $form->showCategories($object->id, 'supplier', 1);
2477
-				print "</td></tr>";
2478
-			}
2479
-		}
2461
+        // Tags / categories
2462
+        if (! empty($conf->categorie->enabled)  && ! empty($user->rights->categorie->lire))
2463
+        {
2464
+            // Customer
2465
+            if ($object->prospect || $object->client || (! $object->fournisseur && ! empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER))) {
2466
+                print '<tr><td>' . $langs->trans("CustomersCategoriesShort") . '</td>';
2467
+                print '<td>';
2468
+                print $form->showCategories($object->id, 'customer', 1);
2469
+                print "</td></tr>";
2470
+            }
2471
+
2472
+            // Supplier
2473
+            if ($object->fournisseur) {
2474
+                print '<tr><td>' . $langs->trans("SuppliersCategoriesShort") . '</td>';
2475
+                print '<td>';
2476
+                print $form->showCategories($object->id, 'supplier', 1);
2477
+                print "</td></tr>";
2478
+            }
2479
+        }
2480 2480
 
2481 2481
         // Legal
2482 2482
         print '<tr><td class="titlefield">'.$langs->trans('JuridicalStatus').'</td><td>'.$object->forme_juridique.'</td></tr>';
@@ -2503,61 +2503,61 @@  discard block
 block discarded – undo
2503 2503
         // Incoterms
2504 2504
         if (!empty($conf->incoterm->enabled))
2505 2505
         {
2506
-        	print '<tr><td>';
2507
-        	print '<table width="100%" class="nobordernopadding"><tr><td>';
2508
-        	print $langs->trans('IncotermLabel');
2509
-        	print '<td><td align="right">';
2510
-        	if ($user->rights->societe->creer) print '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$object->id.'&action=editincoterm">'.img_edit('',1).'</a>';
2511
-        	else print '&nbsp;';
2512
-        	print '</td></tr></table>';
2513
-        	print '</td>';
2514
-        	print '<td colspan="3">';
2515
-        	if ($action != 'editincoterm')
2516
-        	{
2517
-        		print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1);
2518
-        	}
2519
-        	else
2520
-        	{
2521
-        		print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?socid='.$object->id);
2522
-        	}
2523
-        	print '</td></tr>';
2524
-        }
2525
-
2526
-		// Multicurrency
2527
-		if (! empty($conf->multicurrency->enabled))
2528
-		{
2529
-			print '<tr>';
2530
-			print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
2531
-	        print '<td>';
2532
-	        print !empty($object->multicurrency_code) ? currency_name($object->multicurrency_code,1) : '';
2533
-			print '</td></tr>';
2534
-		}
2535
-
2536
-		// Other attributes
2537
-		$parameters=array('socid'=>$socid, 'colspan' => ' colspan="3"', 'colspanvalue' => '3');
2538
-		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
2506
+            print '<tr><td>';
2507
+            print '<table width="100%" class="nobordernopadding"><tr><td>';
2508
+            print $langs->trans('IncotermLabel');
2509
+            print '<td><td align="right">';
2510
+            if ($user->rights->societe->creer) print '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$object->id.'&action=editincoterm">'.img_edit('',1).'</a>';
2511
+            else print '&nbsp;';
2512
+            print '</td></tr></table>';
2513
+            print '</td>';
2514
+            print '<td colspan="3">';
2515
+            if ($action != 'editincoterm')
2516
+            {
2517
+                print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1);
2518
+            }
2519
+            else
2520
+            {
2521
+                print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?socid='.$object->id);
2522
+            }
2523
+            print '</td></tr>';
2524
+        }
2525
+
2526
+        // Multicurrency
2527
+        if (! empty($conf->multicurrency->enabled))
2528
+        {
2529
+            print '<tr>';
2530
+            print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
2531
+            print '<td>';
2532
+            print !empty($object->multicurrency_code) ? currency_name($object->multicurrency_code,1) : '';
2533
+            print '</td></tr>';
2534
+        }
2535
+
2536
+        // Other attributes
2537
+        $parameters=array('socid'=>$socid, 'colspan' => ' colspan="3"', 'colspanvalue' => '3');
2538
+        include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
2539 2539
 
2540 2540
         // Parent company
2541 2541
         if (empty($conf->global->SOCIETE_DISABLE_PARENTCOMPANY))
2542 2542
         {
2543
-        	// Payment term
2544
-        	print '<tr><td>';
2545
-        	print '<table class="nobordernopadding" width="100%"><tr><td>';
2546
-        	print $langs->trans('ParentCompany');
2547
-        	print '</td>';
2548
-        	if ($action != 'editparentcompany') print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editparentcompany&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</a></td>';
2549
-        	print '</tr></table>';
2550
-        	print '</td><td colspan="3">';
2551
-        	if ($action == 'editparentcompany')
2552
-        	{
2553
-        		$form->form_thirdparty($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->parent,'editparentcompany','s.rowid <> '.$object->id,1);
2554
-        	}
2555
-        	else
2556
-        	{
2557
-        		$form->form_thirdparty($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->parent,'none','s.rowid <> '.$object->id,1);
2558
-        	}
2559
-        	print '</td>';
2560
-        	print '</tr>';
2543
+            // Payment term
2544
+            print '<tr><td>';
2545
+            print '<table class="nobordernopadding" width="100%"><tr><td>';
2546
+            print $langs->trans('ParentCompany');
2547
+            print '</td>';
2548
+            if ($action != 'editparentcompany') print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editparentcompany&amp;socid='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'</a></td>';
2549
+            print '</tr></table>';
2550
+            print '</td><td colspan="3">';
2551
+            if ($action == 'editparentcompany')
2552
+            {
2553
+                $form->form_thirdparty($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->parent,'editparentcompany','s.rowid <> '.$object->id,1);
2554
+            }
2555
+            else
2556
+            {
2557
+                $form->form_thirdparty($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->parent,'none','s.rowid <> '.$object->id,1);
2558
+            }
2559
+            print '</td>';
2560
+            print '</tr>';
2561 2561
         }
2562 2562
 
2563 2563
         // Sales representative
@@ -2591,7 +2591,7 @@  discard block
 block discarded – undo
2591 2591
         }
2592 2592
 
2593 2593
         print '</table>';
2594
-		print '</div>';
2594
+        print '</div>';
2595 2595
 
2596 2596
         print '</div></div>';
2597 2597
         print '<div style="clear:both"></div>';
@@ -2604,128 +2604,128 @@  discard block
 block discarded – undo
2604 2604
          */
2605 2605
         if ($action != 'presend')
2606 2606
         {
2607
-	        print '<div class="tabsAction">'."\n";
2608
-
2609
-			$parameters=array();
2610
-			$reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
2611
-			if (empty($reshook))
2612
-			{
2613
-				$at_least_one_email_contact = false;
2614
-				$TContact = $object->contact_array_objects();
2615
-				foreach ($TContact as &$contact)
2616
-				{
2617
-					if (!empty($contact->email))
2618
-					{
2619
-						$at_least_one_email_contact = true;
2620
-						break;
2621
-					}
2622
-				}
2607
+            print '<div class="tabsAction">'."\n";
2623 2608
 
2624
-		        if (! empty($object->email) || $at_least_one_email_contact)
2625
-		        {
2626
-		        	$langs->load("mails");
2627
-		        	print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'&amp;action=presend&amp;mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>';
2628
-		        }
2629
-		        else
2630
-				{
2631
-		        	$langs->load("mails");
2632
-		       		print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NoEMail")).'">'.$langs->trans('SendMail').'</a></div>';
2633
-		        }
2634
-
2635
-		        if ($user->rights->societe->creer)
2636
-		        {
2637
-		            print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n";
2638
-		        }
2639
-
2640
-		        if ($user->rights->societe->supprimer)
2641
-		        {
2642
-		        	print '<div class="inline-block divButAction"><a class="butActionDelete" href="card.php?action=merge&socid='.$object->id.'" title="'.dol_escape_htmltag($langs->trans("MergeThirdparties")).'">'.$langs->trans('Merge').'</a></div>';
2643
-		        }
2644
-
2645
-		        if ($user->rights->societe->supprimer)
2646
-		        {
2647
-		            if ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile))	// We can't use preloaded confirm form with jmobile
2648
-		            {
2649
-		                print '<div class="inline-block divButAction"><span id="action-delete" class="butActionDelete">'.$langs->trans('Delete').'</span></div>'."\n";
2650
-		            }
2651
-		            else
2652
-					{
2653
-		                print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=delete">'.$langs->trans('Delete').'</a></div>'."\n";
2654
-		            }
2655
-		        }
2656
-			}
2609
+            $parameters=array();
2610
+            $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
2611
+            if (empty($reshook))
2612
+            {
2613
+                $at_least_one_email_contact = false;
2614
+                $TContact = $object->contact_array_objects();
2615
+                foreach ($TContact as &$contact)
2616
+                {
2617
+                    if (!empty($contact->email))
2618
+                    {
2619
+                        $at_least_one_email_contact = true;
2620
+                        break;
2621
+                    }
2622
+                }
2623
+
2624
+                if (! empty($object->email) || $at_least_one_email_contact)
2625
+                {
2626
+                    $langs->load("mails");
2627
+                    print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->id.'&amp;action=presend&amp;mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>';
2628
+                }
2629
+                else
2630
+                {
2631
+                    $langs->load("mails");
2632
+                        print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NoEMail")).'">'.$langs->trans('SendMail').'</a></div>';
2633
+                }
2634
+
2635
+                if ($user->rights->societe->creer)
2636
+                {
2637
+                    print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n";
2638
+                }
2639
+
2640
+                if ($user->rights->societe->supprimer)
2641
+                {
2642
+                    print '<div class="inline-block divButAction"><a class="butActionDelete" href="card.php?action=merge&socid='.$object->id.'" title="'.dol_escape_htmltag($langs->trans("MergeThirdparties")).'">'.$langs->trans('Merge').'</a></div>';
2643
+                }
2657 2644
 
2658
-	        print '</div>'."\n";
2645
+                if ($user->rights->societe->supprimer)
2646
+                {
2647
+                    if ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile))	// We can't use preloaded confirm form with jmobile
2648
+                    {
2649
+                        print '<div class="inline-block divButAction"><span id="action-delete" class="butActionDelete">'.$langs->trans('Delete').'</span></div>'."\n";
2650
+                    }
2651
+                    else
2652
+                    {
2653
+                        print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=delete">'.$langs->trans('Delete').'</a></div>'."\n";
2654
+                    }
2655
+                }
2656
+            }
2657
+
2658
+            print '</div>'."\n";
2659 2659
         }
2660 2660
 
2661 2661
         //Select mail models is same action as presend
2662
-		if (GETPOST('modelselected')) {
2663
-			$action = 'presend';
2664
-		}
2662
+        if (GETPOST('modelselected')) {
2663
+            $action = 'presend';
2664
+        }
2665 2665
 
2666
-		if ($action != 'presend')
2667
-		{
2668
-			print '<div class="fichecenter"><div class="fichehalfleft">';
2666
+        if ($action != 'presend')
2667
+        {
2668
+            print '<div class="fichecenter"><div class="fichehalfleft">';
2669 2669
 
2670
-	        if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC))
2671
-	        {
2672
-				print '<a name="builddoc"></a>'; // ancre
2670
+            if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC))
2671
+            {
2672
+                print '<a name="builddoc"></a>'; // ancre
2673 2673
 
2674
-	            /*
2674
+                /*
2675 2675
 	             * Documents generes
2676 2676
 	             */
2677
-	            $filedir=$conf->societe->multidir_output[$object->entity].'/'.$object->id;
2678
-	            $urlsource=$_SERVER["PHP_SELF"]."?socid=".$object->id;
2679
-	            $genallowed=$user->rights->societe->lire;
2680
-	            $delallowed=$user->rights->societe->creer;
2677
+                $filedir=$conf->societe->multidir_output[$object->entity].'/'.$object->id;
2678
+                $urlsource=$_SERVER["PHP_SELF"]."?socid=".$object->id;
2679
+                $genallowed=$user->rights->societe->lire;
2680
+                $delallowed=$user->rights->societe->creer;
2681 2681
 
2682
-	            print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang);
2683
-	        }
2682
+                print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang);
2683
+            }
2684 2684
 
2685
-			// Subsidiaries list
2686
-			if (empty($conf->global->SOCIETE_DISABLE_SUBSIDIARIES))
2687
-			{
2688
-				$result=show_subsidiaries($conf,$langs,$db,$object);
2689
-			}
2685
+            // Subsidiaries list
2686
+            if (empty($conf->global->SOCIETE_DISABLE_SUBSIDIARIES))
2687
+            {
2688
+                $result=show_subsidiaries($conf,$langs,$db,$object);
2689
+            }
2690 2690
 
2691
-			print '</div><div class="fichehalfright"><div class="ficheaddleft">';
2691
+            print '</div><div class="fichehalfright"><div class="ficheaddleft">';
2692 2692
 
2693
-			$MAXEVENT = 10;
2693
+            $MAXEVENT = 10;
2694 2694
 
2695
-			$morehtmlright = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$object->id.'">';
2696
-			$morehtmlright.= $langs->trans("SeeAll");
2697
-			$morehtmlright.= '</a>';
2695
+            $morehtmlright = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$object->id.'">';
2696
+            $morehtmlright.= $langs->trans("SeeAll");
2697
+            $morehtmlright.= '</a>';
2698 2698
 
2699
-			// List of actions on element
2700
-			include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
2701
-			$formactions = new FormActions($db);
2702
-			$somethingshown = $formactions->showactions($object, '', $socid, 1, '', $MAXEVENT, '', $morehtmlright);		// Show all action for thirdparty
2699
+            // List of actions on element
2700
+            include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
2701
+            $formactions = new FormActions($db);
2702
+            $somethingshown = $formactions->showactions($object, '', $socid, 1, '', $MAXEVENT, '', $morehtmlright);		// Show all action for thirdparty
2703 2703
 
2704
-			print '</div></div></div>';
2704
+            print '</div></div></div>';
2705 2705
 
2706
-			if (! empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD))
2707
-			{
2708
-				// Contacts list
2709
-				if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))
2710
-				{
2711
-					$result=show_contacts($conf,$langs,$db,$object,$_SERVER["PHP_SELF"].'?socid='.$object->id);
2712
-				}
2706
+            if (! empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD))
2707
+            {
2708
+                // Contacts list
2709
+                if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))
2710
+                {
2711
+                    $result=show_contacts($conf,$langs,$db,$object,$_SERVER["PHP_SELF"].'?socid='.$object->id);
2712
+                }
2713 2713
 
2714
-				// Addresses list
2715
-				if (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT))
2716
-				{
2717
-					$result=show_addresses($conf,$langs,$db,$object,$_SERVER["PHP_SELF"].'?socid='.$object->id);
2718
-				}
2719
-			}
2720
-		}
2714
+                // Addresses list
2715
+                if (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT))
2716
+                {
2717
+                    $result=show_addresses($conf,$langs,$db,$object,$_SERVER["PHP_SELF"].'?socid='.$object->id);
2718
+                }
2719
+            }
2720
+        }
2721 2721
 
2722
-		// Presend form
2723
-		$modelmail='thirdparty';
2724
-		$defaulttopic='Information';
2725
-		$diroutput = $conf->societe->dir_output;
2726
-		$trackid = 'thi'.$object->id;
2722
+        // Presend form
2723
+        $modelmail='thirdparty';
2724
+        $defaulttopic='Information';
2725
+        $diroutput = $conf->societe->dir_output;
2726
+        $trackid = 'thi'.$object->id;
2727 2727
 
2728
-		include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2728
+        include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2729 2729
     }
2730 2730
 }
2731 2731
 
Please login to merge, or discard this patch.
dolibarr/htdocs/societe/ajaxcountries.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -52,27 +52,27 @@
 block discarded – undo
52 52
 // Generate list of countries
53 53
 if (! empty($country))
54 54
 {
55
-	global $langs;
56
-	$langs->load("dict");
55
+    global $langs;
56
+    $langs->load("dict");
57 57
 
58
-	$sql = "SELECT rowid, code, label, active";
59
-	$sql.= " FROM ".MAIN_DB_PREFIX."c_country";
60
-	$sql.= " WHERE active = 1 AND label LIKE '%" . $db->escape(utf8_decode($country)) . "%'";
61
-	$sql.= " ORDER BY label ASC";
58
+    $sql = "SELECT rowid, code, label, active";
59
+    $sql.= " FROM ".MAIN_DB_PREFIX."c_country";
60
+    $sql.= " WHERE active = 1 AND label LIKE '%" . $db->escape(utf8_decode($country)) . "%'";
61
+    $sql.= " ORDER BY label ASC";
62 62
 
63
-	$resql=$db->query($sql);
64
-	if ($resql)
65
-	{
66
-		print '<ul>';
67
-		while($country = $db->fetch_object($resql))
68
-		{
69
-			print '<li>';
70
-			// Si traduction existe, on l'utilise, sinon on prend le libellé par défaut
71
-			print ($country->code && $langs->trans("Country".$country->code)!="Country".$country->code?$langs->trans("Country".$country->code):($country->label!='-'?$country->label:'&nbsp;'));
72
-			print '<span class="informal" style="display:none">'.$country->rowid.'-idcache</span>';
73
-			print '</li>';
74
-		}
75
-		print '</ul>';
76
-	}
63
+    $resql=$db->query($sql);
64
+    if ($resql)
65
+    {
66
+        print '<ul>';
67
+        while($country = $db->fetch_object($resql))
68
+        {
69
+            print '<li>';
70
+            // Si traduction existe, on l'utilise, sinon on prend le libellé par défaut
71
+            print ($country->code && $langs->trans("Country".$country->code)!="Country".$country->code?$langs->trans("Country".$country->code):($country->label!='-'?$country->label:'&nbsp;'));
72
+            print '<span class="informal" style="display:none">'.$country->rowid.'-idcache</span>';
73
+            print '</li>';
74
+        }
75
+        print '</ul>';
76
+    }
77 77
 }
78 78
 
Please login to merge, or discard this patch.
dolibarr/htdocs/societe/index.php 1 patch
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -62,32 +62,32 @@  discard block
 block discarded – undo
62 62
     // Search thirdparty
63 63
     if (! empty($conf->societe->enabled) && $user->rights->societe->lire)
64 64
     {
65
-    	$listofsearchfields['search_thirdparty']=array('text'=>'ThirdParty');
65
+        $listofsearchfields['search_thirdparty']=array('text'=>'ThirdParty');
66 66
     }
67 67
     // Search contact/address
68 68
     if (! empty($conf->societe->enabled) && $user->rights->societe->lire)
69 69
     {
70
-    	$listofsearchfields['search_contact']=array('text'=>'Contact');
70
+        $listofsearchfields['search_contact']=array('text'=>'Contact');
71 71
     }
72 72
 
73 73
     if (count($listofsearchfields))
74 74
     {
75
-    	print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">';
76
-    	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
77
-    	print '<table class="noborder nohover centpercent">';
78
-    	$i=0;
79
-    	foreach($listofsearchfields as $key => $value)
80
-    	{
81
-    		if ($i == 0) print '<tr class="liste_titre"><th colspan="3">'.$langs->trans("Search").'</th></tr>';
82
-    		print '<tr '.$bc[false].'>';
83
-    		print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>';
84
-    		if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>';
85
-    		print '</tr>';
86
-    		$i++;
87
-    	}
88
-    	print '</table>';
89
-    	print '</form>';
90
-    	print '<br>';
75
+        print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">';
76
+        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
77
+        print '<table class="noborder nohover centpercent">';
78
+        $i=0;
79
+        foreach($listofsearchfields as $key => $value)
80
+        {
81
+            if ($i == 0) print '<tr class="liste_titre"><th colspan="3">'.$langs->trans("Search").'</th></tr>';
82
+            print '<tr '.$bc[false].'>';
83
+            print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>';
84
+            if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>';
85
+            print '</tr>';
86
+            $i++;
87
+        }
88
+        print '</table>';
89
+        print '</form>';
90
+        print '<br>';
91 91
     }
92 92
 }
93 93
 
@@ -97,10 +97,10 @@  discard block
 block discarded – undo
97 97
  */
98 98
 
99 99
 $third = array(
100
-		'customer' => 0,
101
-		'prospect' => 0,
102
-		'supplier' => 0,
103
-		'other' =>0
100
+        'customer' => 0,
101
+        'prospect' => 0,
102
+        'supplier' => 0,
103
+        'other' =>0
104 104
 );
105 105
 $total=0;
106 106
 
@@ -140,13 +140,13 @@  discard block
 block discarded – undo
140 140
     if (! empty($conf->societe->enabled)) $dataseries[]=array($langs->trans("Others"), round($third['other']));
141 141
     include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
142 142
     $dolgraph = new DolGraph();
143
-	$dolgraph->SetData($dataseries);
144
-	$dolgraph->setShowLegend(1);
145
-	$dolgraph->setShowPercent(1);
146
-	$dolgraph->SetType(array('pie'));
147
-	$dolgraph->setWidth('100%');
148
-	$dolgraph->draw('idgraphthirdparties');
149
-	print $dolgraph->show();
143
+    $dolgraph->SetData($dataseries);
144
+    $dolgraph->setShowLegend(1);
145
+    $dolgraph->setShowPercent(1);
146
+    $dolgraph->SetType(array('pie'));
147
+    $dolgraph->setWidth('100%');
148
+    $dolgraph->draw('idgraphthirdparties');
149
+    print $dolgraph->show();
150 150
     print '</td></tr>'."\n";
151 151
 }
152 152
 else
@@ -180,80 +180,80 @@  discard block
 block discarded – undo
180 180
 
181 181
 if (! empty($conf->categorie->enabled) && ! empty($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES))
182 182
 {
183
-	require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
184
-	$elementtype = 'societe';
185
-
186
-	print '<br>';
187
-
188
-	print '<div class="div-table-responsive-no-min">';
189
-	print '<table class="noborder nohover" width="100%">';
190
-	print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Categories").'</th></tr>';
191
-	print '<tr '.$bc[0].'><td align="center" colspan="2">';
192
-	$sql = "SELECT c.label, count(*) as nb";
193
-	$sql.= " FROM ".MAIN_DB_PREFIX."categorie_societe as cs";
194
-	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON cs.fk_categorie = c.rowid";
195
-	$sql.= " WHERE c.type = 2";
196
-	if (! is_numeric($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)) $sql.= " AND c.label like '".$db->escape($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)."'";
197
-	$sql.= " AND c.entity IN (".getEntity('category').")";
198
-	$sql.= " GROUP BY c.label";
199
-	$total=0;
200
-	$result = $db->query($sql);
201
-	if ($result)
202
-	{
203
-		$num = $db->num_rows($result);
204
-		$i=0;
205
-		if (! empty($conf->use_javascript_ajax) )
206
-		{
207
-			$dataseries=array();
208
-			$rest=0;
209
-			$nbmax=10;
210
-
211
-			while ($i < $num)
212
-			{
213
-				$obj = $db->fetch_object($result);
214
-				if ($i < $nbmax)
215
-				{
216
-					$dataseries[]=array($obj->label, round($obj->nb));
217
-				}
218
-				else
219
-				{
220
-					$rest+=$obj->nb;
221
-				}
222
-				$total+=$obj->nb;
223
-				$i++;
224
-			}
225
-			if ($i > $nbmax)
226
-			{
227
-				$dataseries[]=array($langs->trans("Other"), round($rest));
228
-			}
229
-			include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
230
-			$dolgraph = new DolGraph();
231
-			$dolgraph->SetData($dataseries);
232
-			$dolgraph->setShowLegend(1);
233
-			$dolgraph->setShowPercent(1);
234
-			$dolgraph->SetType(array('pie'));
235
-			$dolgraph->setWidth('100%');
236
-			$dolgraph->draw('idgraphcateg');
237
-			print $dolgraph->show();
238
-		}
239
-		else
240
-		{
241
-			while ($i < $num)
242
-			{
243
-				$obj = $db->fetch_object($result);
244
-
245
-				print '<tr class="oddeven"><td>'.$obj->label.'</td><td>'.$obj->nb.'</td></tr>';
246
-				$total+=$obj->nb;
247
-				$i++;
248
-			}
249
-		}
250
-	}
251
-	print '</td></tr>';
252
-	print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td align="right">';
253
-	print $total;
254
-	print '</td></tr>';
255
-	print '</table>';
256
-	print '</div>';
183
+    require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
184
+    $elementtype = 'societe';
185
+
186
+    print '<br>';
187
+
188
+    print '<div class="div-table-responsive-no-min">';
189
+    print '<table class="noborder nohover" width="100%">';
190
+    print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Categories").'</th></tr>';
191
+    print '<tr '.$bc[0].'><td align="center" colspan="2">';
192
+    $sql = "SELECT c.label, count(*) as nb";
193
+    $sql.= " FROM ".MAIN_DB_PREFIX."categorie_societe as cs";
194
+    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON cs.fk_categorie = c.rowid";
195
+    $sql.= " WHERE c.type = 2";
196
+    if (! is_numeric($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)) $sql.= " AND c.label like '".$db->escape($conf->global->CATEGORY_GRAPHSTATS_ON_THIRDPARTIES)."'";
197
+    $sql.= " AND c.entity IN (".getEntity('category').")";
198
+    $sql.= " GROUP BY c.label";
199
+    $total=0;
200
+    $result = $db->query($sql);
201
+    if ($result)
202
+    {
203
+        $num = $db->num_rows($result);
204
+        $i=0;
205
+        if (! empty($conf->use_javascript_ajax) )
206
+        {
207
+            $dataseries=array();
208
+            $rest=0;
209
+            $nbmax=10;
210
+
211
+            while ($i < $num)
212
+            {
213
+                $obj = $db->fetch_object($result);
214
+                if ($i < $nbmax)
215
+                {
216
+                    $dataseries[]=array($obj->label, round($obj->nb));
217
+                }
218
+                else
219
+                {
220
+                    $rest+=$obj->nb;
221
+                }
222
+                $total+=$obj->nb;
223
+                $i++;
224
+            }
225
+            if ($i > $nbmax)
226
+            {
227
+                $dataseries[]=array($langs->trans("Other"), round($rest));
228
+            }
229
+            include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
230
+            $dolgraph = new DolGraph();
231
+            $dolgraph->SetData($dataseries);
232
+            $dolgraph->setShowLegend(1);
233
+            $dolgraph->setShowPercent(1);
234
+            $dolgraph->SetType(array('pie'));
235
+            $dolgraph->setWidth('100%');
236
+            $dolgraph->draw('idgraphcateg');
237
+            print $dolgraph->show();
238
+        }
239
+        else
240
+        {
241
+            while ($i < $num)
242
+            {
243
+                $obj = $db->fetch_object($result);
244
+
245
+                print '<tr class="oddeven"><td>'.$obj->label.'</td><td>'.$obj->nb.'</td></tr>';
246
+                $total+=$obj->nb;
247
+                $i++;
248
+            }
249
+        }
250
+    }
251
+    print '</td></tr>';
252
+    print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td align="right">';
253
+    print $total;
254
+    print '</td></tr>';
255
+    print '</table>';
256
+    print '</div>';
257 257
 }
258 258
 
259 259
 //print '</td><td valign="top" width="70%" class="notopnoleftnoright">';
@@ -324,20 +324,20 @@  discard block
 block discarded – undo
324 324
             print '<td align="center">';
325 325
             if ($thirdparty_static->client==1 || $thirdparty_static->client==3)
326 326
             {
327
-            	$thirdparty_static->name=$langs->trans("Customer");
328
-            	print $thirdparty_static->getNomUrl(0,'customer',0,1);
327
+                $thirdparty_static->name=$langs->trans("Customer");
328
+                print $thirdparty_static->getNomUrl(0,'customer',0,1);
329 329
             }
330 330
             if ($thirdparty_static->client == 3 && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print " / ";
331 331
             if (($thirdparty_static->client==2 || $thirdparty_static->client==3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
332 332
             {
333
-            	$thirdparty_static->name=$langs->trans("Prospect");
334
-            	print $thirdparty_static->getNomUrl(0,'prospect',0,1);
333
+                $thirdparty_static->name=$langs->trans("Prospect");
334
+                print $thirdparty_static->getNomUrl(0,'prospect',0,1);
335 335
             }
336 336
             if (! empty($conf->fournisseur->enabled) && $thirdparty_static->fournisseur)
337 337
             {
338 338
                 if ($thirdparty_static->client) print " / ";
339
-            	$thirdparty_static->name=$langs->trans("Supplier");
340
-            	print $thirdparty_static->getNomUrl(0,'supplier',0,1);
339
+                $thirdparty_static->name=$langs->trans("Supplier");
340
+                print $thirdparty_static->getNomUrl(0,'supplier',0,1);
341 341
             }
342 342
             print '</td>';
343 343
             // Last modified date
Please login to merge, or discard this patch.
dolibarr/htdocs/societe/list.php 1 patch
Indentation   +597 added lines, -597 removed lines patch added patch discarded remove patch
@@ -125,20 +125,20 @@  discard block
 block discarded – undo
125 125
 
126 126
 // List of fields to search into when doing a "search in all"
127 127
 $fieldstosearchall = array(
128
-	's.nom'=>"ThirdPartyName",
129
-	's.name_alias'=>"AliasNameShort",
130
-	's.code_client'=>"CustomerCode",
131
-	's.code_fournisseur'=>"SupplierCode",
132
-	's.code_compta'=>"CustomerAccountancyCodeShort",
133
-	's.code_compta_fournisseur'=>"SupplierAccountancyCodeShort",
134
-	's.email'=>"EMail",
135
-	's.url'=>"URL",
136
-	's.tva_intra'=>"VATIntra",
137
-	's.siren'=>"ProfId1",
138
-	's.siret'=>"ProfId2",
139
-	's.ape'=>"ProfId3",
140
-	's.phone'=>"Phone",
141
-	's.fax'=>"Fax",
128
+    's.nom'=>"ThirdPartyName",
129
+    's.name_alias'=>"AliasNameShort",
130
+    's.code_client'=>"CustomerCode",
131
+    's.code_fournisseur'=>"SupplierCode",
132
+    's.code_compta'=>"CustomerAccountancyCodeShort",
133
+    's.code_compta_fournisseur'=>"SupplierAccountancyCodeShort",
134
+    's.email'=>"EMail",
135
+    's.url'=>"URL",
136
+    's.tva_intra'=>"VATIntra",
137
+    's.siren'=>"ProfId1",
138
+    's.siret'=>"ProfId2",
139
+    's.ape'=>"ProfId3",
140
+    's.phone'=>"Phone",
141
+    's.fax'=>"Fax",
142 142
 );
143 143
 if (($tmp = $langs->transnoentities("ProfId4".$mysoc->country_code)) && $tmp != "ProfId4".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof4']='ProfId4';
144 144
 if (($tmp = $langs->transnoentities("ProfId5".$mysoc->country_code)) && $tmp != "ProfId5".$mysoc->country_code && $tmp != '-') $fieldstosearchall['s.idprof5']='ProfId5';
@@ -166,47 +166,47 @@  discard block
 block discarded – undo
166 166
 $checkprospectlevel=(in_array($contextpage, array('prospectlist')) ? 1 : 0);
167 167
 $checkstcomm=(in_array($contextpage, array('prospectlist')) ? 1 : 0);
168 168
 $arrayfields=array(
169
-	's.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0)),
170
-	's.nom'=>array('label'=>"ThirdPartyName", 'checked'=>1),
171
-	's.name_alias'=>array('label'=>"AliasNameShort", 'checked'=>1),
172
-	's.barcode'=>array('label'=>"Gencod", 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))),
173
-	's.code_client'=>array('label'=>"CustomerCodeShort", 'checked'=>$checkedcustomercode),
174
-	's.code_fournisseur'=>array('label'=>"SupplierCodeShort", 'checked'=>$checkedsuppliercode, 'enabled'=>(! empty($conf->fournisseur->enabled))),
175
-	's.code_compta'=>array('label'=>"CustomerAccountancyCodeShort", 'checked'=>$checkedcustomeraccountcode),
176
-	's.code_compta_fournisseur'=>array('label'=>"SupplierAccountancyCodeShort", 'checked'=>$checkedsupplieraccountcode, 'enabled'=>(! empty($conf->fournisseur->enabled))),
177
-	's.town'=>array('label'=>"Town", 'checked'=>1),
178
-	's.zip'=>array('label'=>"Zip", 'checked'=>1),
179
-	'state.nom'=>array('label'=>"State", 'checked'=>0),
180
-	'region.nom'=>array('label'=>"Region", 'checked'=>0),
181
-	'country.code_iso'=>array('label'=>"Country", 'checked'=>0),
182
-	's.email'=>array('label'=>"Email", 'checked'=>0),
183
-	's.url'=>array('label'=>"Url", 'checked'=>0),
184
-	's.phone'=>array('label'=>"Phone", 'checked'=>1),
185
-	's.fax'=>array('label'=>"Fax", 'checked'=>0),
186
-	'typent.code'=>array('label'=>"ThirdPartyType", 'checked'=>$checkedtypetiers),
187
-	'staff.code'=>array('label'=>"Staff", 'checked'=>0),
188
-	's.siren'=>array('label'=>"ProfId1Short", 'checked'=>$checkedprofid1),
189
-	's.siret'=>array('label'=>"ProfId2Short", 'checked'=>$checkedprofid2),
190
-	's.ape'=>array('label'=>"ProfId3Short", 'checked'=>$checkedprofid3),
191
-	's.idprof4'=>array('label'=>"ProfId4Short", 'checked'=>$checkedprofid4),
192
-	's.idprof5'=>array('label'=>"ProfId5Short", 'checked'=>$checkedprofid5),
193
-	's.idprof6'=>array('label'=>"ProfId6Short", 'checked'=>$checkedprofid6),
194
-	's.tva_intra'=>array('label'=>"VATIntra", 'checked'=>0),
195
-	'customerorsupplier'=>array('label'=>'Nature', 'checked'=>1),
196
-	's.fk_prospectlevel'=>array('label'=>"ProspectLevelShort", 'checked'=>$checkprospectlevel),
197
-	's.fk_stcomm'=>array('label'=>"StatusProsp", 'checked'=>$checkstcomm),
198
-	's.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500),
199
-	's.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500),
200
-	's.status'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000),
201
-	's.import_key'=>array('label'=>"ImportId", 'checked'=>0, 'position'=>1100),
169
+    's.rowid'=>array('label'=>"TechnicalID", 'checked'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0), 'enabled'=>($conf->global->MAIN_SHOW_TECHNICAL_ID?1:0)),
170
+    's.nom'=>array('label'=>"ThirdPartyName", 'checked'=>1),
171
+    's.name_alias'=>array('label'=>"AliasNameShort", 'checked'=>1),
172
+    's.barcode'=>array('label'=>"Gencod", 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))),
173
+    's.code_client'=>array('label'=>"CustomerCodeShort", 'checked'=>$checkedcustomercode),
174
+    's.code_fournisseur'=>array('label'=>"SupplierCodeShort", 'checked'=>$checkedsuppliercode, 'enabled'=>(! empty($conf->fournisseur->enabled))),
175
+    's.code_compta'=>array('label'=>"CustomerAccountancyCodeShort", 'checked'=>$checkedcustomeraccountcode),
176
+    's.code_compta_fournisseur'=>array('label'=>"SupplierAccountancyCodeShort", 'checked'=>$checkedsupplieraccountcode, 'enabled'=>(! empty($conf->fournisseur->enabled))),
177
+    's.town'=>array('label'=>"Town", 'checked'=>1),
178
+    's.zip'=>array('label'=>"Zip", 'checked'=>1),
179
+    'state.nom'=>array('label'=>"State", 'checked'=>0),
180
+    'region.nom'=>array('label'=>"Region", 'checked'=>0),
181
+    'country.code_iso'=>array('label'=>"Country", 'checked'=>0),
182
+    's.email'=>array('label'=>"Email", 'checked'=>0),
183
+    's.url'=>array('label'=>"Url", 'checked'=>0),
184
+    's.phone'=>array('label'=>"Phone", 'checked'=>1),
185
+    's.fax'=>array('label'=>"Fax", 'checked'=>0),
186
+    'typent.code'=>array('label'=>"ThirdPartyType", 'checked'=>$checkedtypetiers),
187
+    'staff.code'=>array('label'=>"Staff", 'checked'=>0),
188
+    's.siren'=>array('label'=>"ProfId1Short", 'checked'=>$checkedprofid1),
189
+    's.siret'=>array('label'=>"ProfId2Short", 'checked'=>$checkedprofid2),
190
+    's.ape'=>array('label'=>"ProfId3Short", 'checked'=>$checkedprofid3),
191
+    's.idprof4'=>array('label'=>"ProfId4Short", 'checked'=>$checkedprofid4),
192
+    's.idprof5'=>array('label'=>"ProfId5Short", 'checked'=>$checkedprofid5),
193
+    's.idprof6'=>array('label'=>"ProfId6Short", 'checked'=>$checkedprofid6),
194
+    's.tva_intra'=>array('label'=>"VATIntra", 'checked'=>0),
195
+    'customerorsupplier'=>array('label'=>'Nature', 'checked'=>1),
196
+    's.fk_prospectlevel'=>array('label'=>"ProspectLevelShort", 'checked'=>$checkprospectlevel),
197
+    's.fk_stcomm'=>array('label'=>"StatusProsp", 'checked'=>$checkstcomm),
198
+    's.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500),
199
+    's.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500),
200
+    's.status'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000),
201
+    's.import_key'=>array('label'=>"ImportId", 'checked'=>0, 'position'=>1100),
202 202
 );
203 203
 // Extra fields
204 204
 if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
205 205
 {
206
-   foreach($extrafields->attribute_label as $key => $val)
207
-   {
208
-		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]));
209
-   }
206
+    foreach($extrafields->attribute_label as $key => $val)
207
+    {
208
+        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]));
209
+    }
210 210
 }
211 211
 
212 212
 $object = new Societe($db);
@@ -225,67 +225,67 @@  discard block
 block discarded – undo
225 225
 
226 226
 if (empty($reshook))
227 227
 {
228
-	// Selection of new fields
229
-	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
230
-
231
-	// Did we click on purge search criteria ?
232
-	if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers
233
-	{
234
-		$search_id='';
235
-		$search_nom='';
236
-		$search_alias='';
237
-		$search_categ_cus=0;
238
-		$search_categ_sup=0;
239
-		$search_sale='';
240
-		$search_barcode="";
241
-		$search_customer_code='';
242
-		$search_supplier_code='';
243
-		$search_account_customer_code='';
244
-		$search_account_supplier_code='';
245
-		$search_town="";
246
-		$search_zip="";
247
-		$search_state="";
248
-		$search_country='';
249
-		$search_email='';
250
-		$search_phone='';
251
-		$search_fax='';
252
-		$search_url='';
253
-		$search_idprof1='';
254
-		$search_idprof2='';
255
-		$search_idprof3='';
256
-		$search_idprof4='';
257
-		$search_idprof5='';
258
-		$search_idprof6='';
259
-		$search_vat='';
260
-		$search_type='';
261
-		$search_type_thirdparty='';
262
-		$search_staff='';
263
-		$search_status=-1;
264
-		$search_stcomm='';
265
-	 	$search_level='';
266
-	 	$search_import_key='';
267
-	 	$toselect='';
268
-		$search_array_options=array();
269
-	}
270
-
271
-	// Mass actions
272
-	$objectclass='Societe';
273
-	$objectlabel='ThirdParty';
274
-	$permtoread = $user->rights->societe->lire;
275
-	$permtodelete = $user->rights->societe->supprimer;
276
-	$uploaddir = $conf->societe->dir_output;
277
-	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
278
-
279
-	if ($action == 'setstcomm')
280
-	{
281
-		$object = new Client($db);
282
-		$result=$object->fetch(GETPOST('stcommsocid'));
283
-		$object->stcomm_id=dol_getIdFromCode($db, GETPOST('stcomm','alpha'), 'c_stcomm');
284
-		$result=$object->update($object->id, $user);
285
-		if ($result < 0) setEventMessages($object->error,$object->errors,'errors');
286
-
287
-		$action='';
288
-	}
228
+    // Selection of new fields
229
+    include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
230
+
231
+    // Did we click on purge search criteria ?
232
+    if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers
233
+    {
234
+        $search_id='';
235
+        $search_nom='';
236
+        $search_alias='';
237
+        $search_categ_cus=0;
238
+        $search_categ_sup=0;
239
+        $search_sale='';
240
+        $search_barcode="";
241
+        $search_customer_code='';
242
+        $search_supplier_code='';
243
+        $search_account_customer_code='';
244
+        $search_account_supplier_code='';
245
+        $search_town="";
246
+        $search_zip="";
247
+        $search_state="";
248
+        $search_country='';
249
+        $search_email='';
250
+        $search_phone='';
251
+        $search_fax='';
252
+        $search_url='';
253
+        $search_idprof1='';
254
+        $search_idprof2='';
255
+        $search_idprof3='';
256
+        $search_idprof4='';
257
+        $search_idprof5='';
258
+        $search_idprof6='';
259
+        $search_vat='';
260
+        $search_type='';
261
+        $search_type_thirdparty='';
262
+        $search_staff='';
263
+        $search_status=-1;
264
+        $search_stcomm='';
265
+            $search_level='';
266
+            $search_import_key='';
267
+            $toselect='';
268
+        $search_array_options=array();
269
+    }
270
+
271
+    // Mass actions
272
+    $objectclass='Societe';
273
+    $objectlabel='ThirdParty';
274
+    $permtoread = $user->rights->societe->lire;
275
+    $permtodelete = $user->rights->societe->supprimer;
276
+    $uploaddir = $conf->societe->dir_output;
277
+    include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
278
+
279
+    if ($action == 'setstcomm')
280
+    {
281
+        $object = new Client($db);
282
+        $result=$object->fetch(GETPOST('stcommsocid'));
283
+        $object->stcomm_id=dol_getIdFromCode($db, GETPOST('stcomm','alpha'), 'c_stcomm');
284
+        $result=$object->update($object->id, $user);
285
+        if ($result < 0) setEventMessages($object->error,$object->errors,'errors');
286
+
287
+        $action='';
288
+    }
289 289
 }
290 290
 
291 291
 if ($search_status=='') $search_status=1; // always display active thirdparty first
@@ -328,13 +328,13 @@  discard block
 block discarded – undo
328 328
 $resql = $db->query($sql);
329 329
 if ($resql)
330 330
 {
331
-	while ($obj = $db->fetch_object($resql))
332
-	{
333
-		// Compute level text
334
-		$level=$langs->trans($obj->code);
335
-		if ($level == $obj->code) $level=$langs->trans($obj->label);
336
-		$tab_level[$obj->code] = $level;
337
-	}
331
+    while ($obj = $db->fetch_object($resql))
332
+    {
333
+        // Compute level text
334
+        $level=$langs->trans($obj->code);
335
+        if ($level == $obj->code) $level=$langs->trans($obj->label);
336
+        $tab_level[$obj->code] = $level;
337
+    }
338 338
 }
339 339
 else dol_print_error($db);
340 340
 
@@ -435,13 +435,13 @@  discard block
 block discarded – undo
435 435
 $nbtotalofrecords = '';
436 436
 if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
437 437
 {
438
-	$result = $db->query($sql);
439
-	$nbtotalofrecords = $db->num_rows($result);
440
-	if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
441
-	{
442
-		$page = 0;
443
-		$offset = 0;
444
-	}
438
+    $result = $db->query($sql);
439
+    $nbtotalofrecords = $db->num_rows($result);
440
+    if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
441
+    {
442
+        $page = 0;
443
+        $offset = 0;
444
+    }
445 445
 }
446 446
 
447 447
 $sql.= $db->plimit($limit+1, $offset);
@@ -449,8 +449,8 @@  discard block
 block discarded – undo
449 449
 $resql = $db->query($sql);
450 450
 if (! $resql)
451 451
 {
452
-	dol_print_error($db);
453
-	exit;
452
+    dol_print_error($db);
453
+    exit;
454 454
 }
455 455
 
456 456
 $num = $db->num_rows($resql);
@@ -459,21 +459,21 @@  discard block
 block discarded – undo
459 459
 
460 460
 if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && ($search_all != '' || $search_cti != '') && $action != 'list')
461 461
 {
462
-	$obj = $db->fetch_object($resql);
463
-	$id = $obj->rowid;
464
-	if(!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)){
465
-              if( $obj->client > 0) {
466
-                       header("Location: ".DOL_URL_ROOT.'/comm/card.php?socid='.$id);
467
-                       exit;
468
-               }
469
-               if( $obj->fournisseur > 0){
470
-                       header("Location: ".DOL_URL_ROOT.'/fourn/card.php?socid='.$id);
471
-                       exit;
472
-               }
473
-       }
474
-
475
-	header("Location: ".DOL_URL_ROOT.'/societe/card.php?socid='.$id);
476
-	exit;
462
+    $obj = $db->fetch_object($resql);
463
+    $id = $obj->rowid;
464
+    if(!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)){
465
+                if( $obj->client > 0) {
466
+                        header("Location: ".DOL_URL_ROOT.'/comm/card.php?socid='.$id);
467
+                        exit;
468
+                }
469
+                if( $obj->fournisseur > 0){
470
+                        header("Location: ".DOL_URL_ROOT.'/fourn/card.php?socid='.$id);
471
+                        exit;
472
+                }
473
+        }
474
+
475
+    header("Location: ".DOL_URL_ROOT.'/societe/card.php?socid='.$id);
476
+    exit;
477 477
 }
478 478
 
479 479
 $help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
@@ -524,12 +524,12 @@  discard block
 block discarded – undo
524 524
 // Show delete result message
525 525
 if (GETPOST('delsoc'))
526 526
 {
527
-	setEventMessages($langs->trans("CompanyDeleted",GETPOST('delsoc')), null, 'mesgs');
527
+    setEventMessages($langs->trans("CompanyDeleted",GETPOST('delsoc')), null, 'mesgs');
528 528
 }
529 529
 
530 530
 // List of mass actions available
531 531
 $arrayofmassactions =  array(
532
-	'presend'=>$langs->trans("SendByMail"),
532
+    'presend'=>$langs->trans("SendByMail"),
533 533
 //    'builddoc'=>$langs->trans("PDFMerge"),
534 534
 );
535 535
 //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer");
@@ -540,20 +540,20 @@  discard block
 block discarded – undo
540 540
 $newcardbutton='';
541 541
 if ($user->rights->societe->creer)
542 542
 {
543
-	$typefilter='';
544
-	$label='MenuNewThirdParty';
545
-
546
-	if(! empty($type))
547
-	{
548
-		$typefilter = '&amp;type='.$type;
549
-		if($type == 'p') $label='MenuNewProspect';
550
-		if($type == 'c') $label='MenuNewCustomer';
551
-		if($type == 'f') $label='NewSupplier';
552
-	}
553
-
554
-	$newcardbutton = '<a class="butActionNew" href="'.DOL_URL_ROOT.'/societe/card.php?action=create'.$typefilter.'"><span class="valignmiddle">'.$langs->trans($label).'</span>';
555
-	$newcardbutton.= '<span class="fa fa-plus-circle valignmiddle"></span>';
556
-	$newcardbutton.= '</a>';
543
+    $typefilter='';
544
+    $label='MenuNewThirdParty';
545
+
546
+    if(! empty($type))
547
+    {
548
+        $typefilter = '&amp;type='.$type;
549
+        if($type == 'p') $label='MenuNewProspect';
550
+        if($type == 'c') $label='MenuNewCustomer';
551
+        if($type == 'f') $label='NewSupplier';
552
+    }
553
+
554
+    $newcardbutton = '<a class="butActionNew" href="'.DOL_URL_ROOT.'/societe/card.php?action=create'.$typefilter.'"><span class="valignmiddle">'.$langs->trans($label).'</span>';
555
+    $newcardbutton.= '<span class="fa fa-plus-circle valignmiddle"></span>';
556
+    $newcardbutton.= '</a>';
557 557
 }
558 558
 
559 559
 print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'" name="formfilter" autocomplete="off">';
@@ -570,13 +570,13 @@  discard block
 block discarded – undo
570 570
 $textprofid=array();
571 571
 foreach(array(1,2,3,4,5,6) as $key)
572 572
 {
573
-	$label=$langs->transnoentities("ProfId".$key.$mysoc->country_code);
574
-	$textprofid[$key]='';
575
-	if ($label != "ProfId".$key.$mysoc->country_code)
576
-	{	// Get only text between ()
577
-		if (preg_match('/\((.*)\)/i',$label,$reg)) $label=$reg[1];
578
-		$textprofid[$key]=$langs->trans("ProfIdShortDesc",$key,$mysoc->country_code,$label);
579
-	}
573
+    $label=$langs->transnoentities("ProfId".$key.$mysoc->country_code);
574
+    $textprofid[$key]='';
575
+    if ($label != "ProfId".$key.$mysoc->country_code)
576
+    {	// Get only text between ()
577
+        if (preg_match('/\((.*)\)/i',$label,$reg)) $label=$reg[1];
578
+        $textprofid[$key]=$langs->trans("ProfIdShortDesc",$key,$mysoc->country_code,$label);
579
+    }
580 580
 }
581 581
 
582 582
 $topicmail="Information";
@@ -587,51 +587,51 @@  discard block
 block discarded – undo
587 587
 
588 588
 if ($search_all)
589 589
 {
590
-	foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
591
-	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall).'</div>';
590
+    foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
591
+    print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall).'</div>';
592 592
 }
593 593
 
594 594
 // Filter on categories
595 595
 $moreforfilter='';
596 596
 if (empty($type) || $type == 'c' || $type == 'p')
597 597
 {
598
-	if (! empty($conf->categorie->enabled))
599
-	{
600
-		require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
601
-		$moreforfilter.='<div class="divsearchfield">';
602
-	 	$moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': ';
603
-		$moreforfilter.=$formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $langs->trans('CustomersProspectsCategoriesShort'));
604
-	 	$moreforfilter.='</div>';
605
-	}
598
+    if (! empty($conf->categorie->enabled))
599
+    {
600
+        require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
601
+        $moreforfilter.='<div class="divsearchfield">';
602
+            $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': ';
603
+        $moreforfilter.=$formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $langs->trans('CustomersProspectsCategoriesShort'));
604
+            $moreforfilter.='</div>';
605
+    }
606 606
 }
607 607
 if (empty($type) || $type == 'f')
608 608
 {
609
-	if (! empty($conf->categorie->enabled))
610
-	{
611
-		require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
612
-		$moreforfilter.='<div class="divsearchfield">';
613
-		$moreforfilter.=$langs->trans('SuppliersCategoriesShort').': ';
614
-		$moreforfilter.=$formother->select_categories('supplier',$search_categ_sup,'search_categ_sup',1);
615
-		$moreforfilter.='</div>';
616
-	}
609
+    if (! empty($conf->categorie->enabled))
610
+    {
611
+        require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
612
+        $moreforfilter.='<div class="divsearchfield">';
613
+        $moreforfilter.=$langs->trans('SuppliersCategoriesShort').': ';
614
+        $moreforfilter.=$formother->select_categories('supplier',$search_categ_sup,'search_categ_sup',1);
615
+        $moreforfilter.='</div>';
616
+    }
617 617
 }
618 618
 
619 619
 // If the user can view prospects other than his'
620 620
 if ($user->rights->societe->client->voir || $socid)
621 621
 {
622
- 	$moreforfilter.='<div class="divsearchfield">';
623
- 	$moreforfilter.=$langs->trans('SalesRepresentatives'). ': ';
624
-	$moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user, 0, 1, 'maxwidth300');
625
-	$moreforfilter.='</div>';
622
+        $moreforfilter.='<div class="divsearchfield">';
623
+        $moreforfilter.=$langs->trans('SalesRepresentatives'). ': ';
624
+    $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user, 0, 1, 'maxwidth300');
625
+    $moreforfilter.='</div>';
626 626
 }
627 627
 if ($moreforfilter)
628 628
 {
629
-	print '<div class="liste_titre liste_titre_bydiv centpercent">';
630
-	print $moreforfilter;
631
-	$parameters=array('type'=>$type);
632
-	$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters);    // Note that $action and $object may have been modified by hook
633
-	print $hookmanager->resPrint;
634
-	print '</div>';
629
+    print '<div class="liste_titre liste_titre_bydiv centpercent">';
630
+    print $moreforfilter;
631
+    $parameters=array('type'=>$type);
632
+    $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters);    // Note that $action and $object may have been modified by hook
633
+    print $hookmanager->resPrint;
634
+    print '</div>';
635 635
 }
636 636
 
637 637
 $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
@@ -647,217 +647,217 @@  discard block
 block discarded – undo
647 647
 print '<tr class="liste_titre_filter">';
648 648
 if (! empty($arrayfields['s.rowid']['checked']))
649 649
 {
650
-	print '<td class="liste_titre">';
651
-	print '<input class="flat searchstring" type="text" name="search_id" size="1" value="'.dol_escape_htmltag($search_id).'">';
652
-	print '</td>';
650
+    print '<td class="liste_titre">';
651
+    print '<input class="flat searchstring" type="text" name="search_id" size="1" value="'.dol_escape_htmltag($search_id).'">';
652
+    print '</td>';
653 653
 }
654 654
 if (! empty($arrayfields['s.nom']['checked']))
655 655
 {
656
-	print '<td class="liste_titre">';
657
-	if (! empty($search_nom_only) && empty($search_nom)) $search_nom=$search_nom_only;
658
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_nom" value="'.dol_escape_htmltag($search_nom).'">';
659
-	print '</td>';
656
+    print '<td class="liste_titre">';
657
+    if (! empty($search_nom_only) && empty($search_nom)) $search_nom=$search_nom_only;
658
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_nom" value="'.dol_escape_htmltag($search_nom).'">';
659
+    print '</td>';
660 660
 }
661 661
 if (! empty($arrayfields['s.name_alias']['checked']))
662 662
 {
663
-	print '<td class="liste_titre">';
664
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_alias" value="'.dol_escape_htmltag($search_alias).'">';
665
-	print '</td>';
663
+    print '<td class="liste_titre">';
664
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_alias" value="'.dol_escape_htmltag($search_alias).'">';
665
+    print '</td>';
666 666
 }
667 667
 // Barcode
668 668
 if (! empty($arrayfields['s.barcode']['checked']))
669 669
 {
670
-	print '<td class="liste_titre">';
671
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_barcode" value="'.dol_escape_htmltag($search_barcode).'">';
672
-	print '</td>';
670
+    print '<td class="liste_titre">';
671
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_barcode" value="'.dol_escape_htmltag($search_barcode).'">';
672
+    print '</td>';
673 673
 }
674 674
 // Customer code
675 675
 if (! empty($arrayfields['s.code_client']['checked']))
676 676
 {
677
-	print '<td class="liste_titre">';
678
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_customer_code" value="'.dol_escape_htmltag($search_customer_code).'">';
679
-	print '</td>';
677
+    print '<td class="liste_titre">';
678
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_customer_code" value="'.dol_escape_htmltag($search_customer_code).'">';
679
+    print '</td>';
680 680
 }
681 681
 // Supplier code
682 682
 if (! empty($arrayfields['s.code_fournisseur']['checked']))
683 683
 {
684
-	print '<td class="liste_titre">';
685
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_supplier_code" value="'.dol_escape_htmltag($search_supplier_code).'">';
686
-	print '</td>';
684
+    print '<td class="liste_titre">';
685
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_supplier_code" value="'.dol_escape_htmltag($search_supplier_code).'">';
686
+    print '</td>';
687 687
 }
688 688
 // Account Customer code
689 689
 if (! empty($arrayfields['s.code_compta']['checked']))
690 690
 {
691
-	print '<td class="liste_titre">';
692
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_account_customer_code" value="'.dol_escape_htmltag($search_account_customer_code).'">';
693
-	print '</td>';
691
+    print '<td class="liste_titre">';
692
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_account_customer_code" value="'.dol_escape_htmltag($search_account_customer_code).'">';
693
+    print '</td>';
694 694
 }
695 695
 // Account Supplier code
696 696
 if (! empty($arrayfields['s.code_compta_fournisseur']['checked']))
697 697
 {
698
-	print '<td class="liste_titre">';
699
-	print '<input class="flat maxwidth50" type="text" name="search_account_supplier_code" value="'.dol_escape_htmltag($search_account_supplier_code).'">';
700
-	print '</td>';
698
+    print '<td class="liste_titre">';
699
+    print '<input class="flat maxwidth50" type="text" name="search_account_supplier_code" value="'.dol_escape_htmltag($search_account_supplier_code).'">';
700
+    print '</td>';
701 701
 }
702 702
 // Town
703 703
 if (! empty($arrayfields['s.town']['checked']))
704 704
 {
705
-	print '<td class="liste_titre">';
706
-	print '<input class="flat searchstring" size="6" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'">';
707
-	print '</td>';
705
+    print '<td class="liste_titre">';
706
+    print '<input class="flat searchstring" size="6" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'">';
707
+    print '</td>';
708 708
 }
709 709
 // Zip
710 710
 if (! empty($arrayfields['s.zip']['checked']))
711 711
 {
712
-	print '<td class="liste_titre">';
713
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'">';
714
-	print '</td>';
712
+    print '<td class="liste_titre">';
713
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'">';
714
+    print '</td>';
715 715
 }
716 716
 // State
717 717
 if (! empty($arrayfields['state.nom']['checked']))
718 718
 {
719
-	print '<td class="liste_titre">';
720
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
721
-	print '</td>';
719
+    print '<td class="liste_titre">';
720
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
721
+    print '</td>';
722 722
 }
723 723
 // Region
724 724
 if (! empty($arrayfields['region.nom']['checked']))
725 725
 {
726
-	print '<td class="liste_titre">';
727
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_region" value="'.dol_escape_htmltag($search_region).'">';
728
-	print '</td>';
726
+    print '<td class="liste_titre">';
727
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_region" value="'.dol_escape_htmltag($search_region).'">';
728
+    print '</td>';
729 729
 }
730 730
 // Country
731 731
 if (! empty($arrayfields['country.code_iso']['checked']))
732 732
 {
733
-	print '<td class="liste_titre" align="center">';
734
-	print $form->select_country($search_country,'search_country','',0,'maxwidth100');
735
-	print '</td>';
733
+    print '<td class="liste_titre" align="center">';
734
+    print $form->select_country($search_country,'search_country','',0,'maxwidth100');
735
+    print '</td>';
736 736
 }
737 737
 // Company type
738 738
 if (! empty($arrayfields['typent.code']['checked']))
739 739
 {
740
-	print '<td class="liste_titre maxwidthonsmartphone" align="center">';
741
-	print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT));
742
-	print '</td>';
740
+    print '<td class="liste_titre maxwidthonsmartphone" align="center">';
741
+    print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT));
742
+    print '</td>';
743 743
 }
744 744
 // Staff
745 745
 if (! empty($arrayfields['staff.code']['checked']))
746 746
 {
747
-	print '<td class="liste_titre maxwidthonsmartphone" align="center">';
748
-	print $form->selectarray("search_staff", $formcompany->effectif_array(0), $search_staff, 0, 0, 0, '', 0, 0, 0, $sort, 'maxwidth100');
749
-	print '</td>';
747
+    print '<td class="liste_titre maxwidthonsmartphone" align="center">';
748
+    print $form->selectarray("search_staff", $formcompany->effectif_array(0), $search_staff, 0, 0, 0, '', 0, 0, 0, $sort, 'maxwidth100');
749
+    print '</td>';
750 750
 }
751 751
 if (! empty($arrayfields['s.email']['checked']))
752 752
 {
753
-	// Email
754
-	print '<td class="liste_titre">';
755
-	print '<input class="flat searchemail maxwidth50" type="text" name="search_email" value="'.dol_escape_htmltag($search_email).'">';
756
-	print '</td>';
753
+    // Email
754
+    print '<td class="liste_titre">';
755
+    print '<input class="flat searchemail maxwidth50" type="text" name="search_email" value="'.dol_escape_htmltag($search_email).'">';
756
+    print '</td>';
757 757
 }
758 758
 if (! empty($arrayfields['s.phone']['checked']))
759 759
 {
760
-	// Phone
761
-	print '<td class="liste_titre">';
762
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_phone" value="'.dol_escape_htmltag($search_phone).'">';
763
-	print '</td>';
760
+    // Phone
761
+    print '<td class="liste_titre">';
762
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_phone" value="'.dol_escape_htmltag($search_phone).'">';
763
+    print '</td>';
764 764
 }
765 765
 if (! empty($arrayfields['s.fax']['checked']))
766 766
 {
767
-	// Fax
768
-	print '<td class="liste_titre">';
769
-	print '<input class="flat searchstring" size="4" type="text" name="search_fax" value="'.dol_escape_htmltag($search_fax).'">';
770
-	print '</td>';
767
+    // Fax
768
+    print '<td class="liste_titre">';
769
+    print '<input class="flat searchstring" size="4" type="text" name="search_fax" value="'.dol_escape_htmltag($search_fax).'">';
770
+    print '</td>';
771 771
 }
772 772
 if (! empty($arrayfields['s.url']['checked']))
773 773
 {
774
-	// Url
775
-	print '<td class="liste_titre">';
776
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_url" value="'.dol_escape_htmltag($search_url).'">';
777
-	print '</td>';
774
+    // Url
775
+    print '<td class="liste_titre">';
776
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_url" value="'.dol_escape_htmltag($search_url).'">';
777
+    print '</td>';
778 778
 }
779 779
 if (! empty($arrayfields['s.siren']['checked']))
780 780
 {
781
-	// IdProf1
782
-	print '<td class="liste_titre">';
783
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_idprof1" value="'.dol_escape_htmltag($search_idprof1).'">';
784
-	print '</td>';
781
+    // IdProf1
782
+    print '<td class="liste_titre">';
783
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_idprof1" value="'.dol_escape_htmltag($search_idprof1).'">';
784
+    print '</td>';
785 785
 }
786 786
 if (! empty($arrayfields['s.siret']['checked']))
787 787
 {
788
-	// IdProf2
789
-	print '<td class="liste_titre">';
790
-	print '<input class="flat searchstring" size="4" type="text" name="search_idprof2" value="'.dol_escape_htmltag($search_idprof2).'">';
791
-	print '</td>';
788
+    // IdProf2
789
+    print '<td class="liste_titre">';
790
+    print '<input class="flat searchstring" size="4" type="text" name="search_idprof2" value="'.dol_escape_htmltag($search_idprof2).'">';
791
+    print '</td>';
792 792
 }
793 793
 if (! empty($arrayfields['s.ape']['checked']))
794 794
 {
795
-	// IdProf3
796
-	print '<td class="liste_titre">';
797
-	print '<input class="flat searchstring" size="4" type="text" name="search_idprof3" value="'.dol_escape_htmltag($search_idprof3).'">';
798
-	print '</td>';
795
+    // IdProf3
796
+    print '<td class="liste_titre">';
797
+    print '<input class="flat searchstring" size="4" type="text" name="search_idprof3" value="'.dol_escape_htmltag($search_idprof3).'">';
798
+    print '</td>';
799 799
 }
800 800
 if (! empty($arrayfields['s.idprof4']['checked']))
801 801
 {
802
-	// IdProf4
803
-	print '<td class="liste_titre">';
804
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_idprof4" value="'.dol_escape_htmltag($search_idprof4).'">';
805
-	print '</td>';
802
+    // IdProf4
803
+    print '<td class="liste_titre">';
804
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_idprof4" value="'.dol_escape_htmltag($search_idprof4).'">';
805
+    print '</td>';
806 806
 }
807 807
 if (! empty($arrayfields['s.idprof5']['checked']))
808 808
 {
809
-	// IdProf5
810
-	print '<td class="liste_titre">';
811
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_idprof5" value="'.dol_escape_htmltag($search_idprof5).'">';
812
-	print '</td>';
809
+    // IdProf5
810
+    print '<td class="liste_titre">';
811
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_idprof5" value="'.dol_escape_htmltag($search_idprof5).'">';
812
+    print '</td>';
813 813
 }
814 814
 if (! empty($arrayfields['s.idprof6']['checked']))
815 815
 {
816
-	// IdProf6
817
-	print '<td class="liste_titre">';
818
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_idprof6" value="'.dol_escape_htmltag($search_idprof6).'">';
819
-	print '</td>';
816
+    // IdProf6
817
+    print '<td class="liste_titre">';
818
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_idprof6" value="'.dol_escape_htmltag($search_idprof6).'">';
819
+    print '</td>';
820 820
 }
821 821
 if (! empty($arrayfields['s.tva_intra']['checked']))
822 822
 {
823
-	// Vat number
824
-	print '<td class="liste_titre">';
825
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_vat" value="'.dol_escape_htmltag($search_vat).'">';
826
-	print '</td>';
823
+    // Vat number
824
+    print '<td class="liste_titre">';
825
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_vat" value="'.dol_escape_htmltag($search_vat).'">';
826
+    print '</td>';
827 827
 }
828 828
 
829 829
 // Type (customer/prospect/supplier)
830 830
 if (! empty($arrayfields['customerorsupplier']['checked']))
831 831
 {
832
-	print '<td class="liste_titre maxwidthonsmartphone" align="middle">';
833
-	if ($type != '') print '<input type="hidden" name="type" value="'.$type.'">';
834
-	print '<select class="flat" name="search_type">';
835
-	print '<option value="-1"'.($search_type==''?' selected':'').'>&nbsp;</option>';
836
-	if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print '<option value="1,3"'.($search_type=='1,3'?' selected':'').'>'.$langs->trans('Customer').'</option>';
837
-	if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="2,3"'.($search_type=='2,3'?' selected':'').'>'.$langs->trans('Prospect').'</option>';
838
-	//if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="3"'.($search_type=='3'?' selected':'').'>'.$langs->trans('ProspectCustomer').'</option>';
839
-	print '<option value="4"'.($search_type=='4'?' selected':'').'>'.$langs->trans('Supplier').'</option>';
840
-	print '<option value="0"'.($search_type=='0'?' selected':'').'>'.$langs->trans('Others').'</option>';
841
-	print '</select></td>';
832
+    print '<td class="liste_titre maxwidthonsmartphone" align="middle">';
833
+    if ($type != '') print '<input type="hidden" name="type" value="'.$type.'">';
834
+    print '<select class="flat" name="search_type">';
835
+    print '<option value="-1"'.($search_type==''?' selected':'').'>&nbsp;</option>';
836
+    if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print '<option value="1,3"'.($search_type=='1,3'?' selected':'').'>'.$langs->trans('Customer').'</option>';
837
+    if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="2,3"'.($search_type=='2,3'?' selected':'').'>'.$langs->trans('Prospect').'</option>';
838
+    //if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) print '<option value="3"'.($search_type=='3'?' selected':'').'>'.$langs->trans('ProspectCustomer').'</option>';
839
+    print '<option value="4"'.($search_type=='4'?' selected':'').'>'.$langs->trans('Supplier').'</option>';
840
+    print '<option value="0"'.($search_type=='0'?' selected':'').'>'.$langs->trans('Others').'</option>';
841
+    print '</select></td>';
842 842
 }
843 843
 // Prospect level
844 844
 if (! empty($arrayfields['s.fk_prospectlevel']['checked']))
845 845
 {
846
- 	print '<td class="liste_titre" align="center">';
847
- 	print $form->multiselectarray('search_level', $tab_level, $search_level, 0, 0, 'width75', 0, 0, '', '', '', 2);
848
-	print '</td>';
846
+        print '<td class="liste_titre" align="center">';
847
+        print $form->multiselectarray('search_level', $tab_level, $search_level, 0, 0, 'width75', 0, 0, '', '', '', 2);
848
+    print '</td>';
849 849
 }
850 850
 // Prospect status
851 851
 if (! empty($arrayfields['s.fk_stcomm']['checked']))
852 852
 {
853
-	print '<td class="liste_titre maxwidthonsmartphone" align="center">';
854
-	$arraystcomm=array();
855
-	foreach($prospectstatic->cacheprospectstatus as $key => $val)
856
-	{
857
-		$arraystcomm[$val['id']]=($langs->trans("StatusProspect".$val['id']) != "StatusProspect".$val['id'] ? $langs->trans("StatusProspect".$val['id']) : $val['label']);
858
-	}
859
-	print $form->selectarray('search_stcomm', $arraystcomm, $search_stcomm, -2);
860
-	print '</td>';
853
+    print '<td class="liste_titre maxwidthonsmartphone" align="center">';
854
+    $arraystcomm=array();
855
+    foreach($prospectstatic->cacheprospectstatus as $key => $val)
856
+    {
857
+        $arraystcomm[$val['id']]=($langs->trans("StatusProspect".$val['id']) != "StatusProspect".$val['id'] ? $langs->trans("StatusProspect".$val['id']) : $val['label']);
858
+    }
859
+    print $form->selectarray('search_stcomm', $arraystcomm, $search_stcomm, -2);
860
+    print '</td>';
861 861
 }
862 862
 // Extra fields
863 863
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
@@ -869,27 +869,27 @@  discard block
 block discarded – undo
869 869
 // Date creation
870 870
 if (! empty($arrayfields['s.datec']['checked']))
871 871
 {
872
-	print '<td class="liste_titre">';
873
-	print '</td>';
872
+    print '<td class="liste_titre">';
873
+    print '</td>';
874 874
 }
875 875
 // Date modification
876 876
 if (! empty($arrayfields['s.tms']['checked']))
877 877
 {
878
-	print '<td class="liste_titre">';
879
-	print '</td>';
878
+    print '<td class="liste_titre">';
879
+    print '</td>';
880 880
 }
881 881
 // Status
882 882
 if (! empty($arrayfields['s.status']['checked']))
883 883
 {
884
-	print '<td class="liste_titre center minwidth75imp">';
885
-	print $form->selectarray('search_status', array('0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')), $search_status, 1);
886
-	print '</td>';
884
+    print '<td class="liste_titre center minwidth75imp">';
885
+    print $form->selectarray('search_status', array('0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')), $search_status, 1);
886
+    print '</td>';
887 887
 }
888 888
 if (! empty($arrayfields['s.import_key']['checked']))
889 889
 {
890
-	print '<td class="liste_titre center">';
891
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_import_key" value="'.dol_escape_htmltag($search_import_key).'">';
892
-	print '</td>';
890
+    print '<td class="liste_titre center">';
891
+    print '<input class="flat searchstring maxwidth50" type="text" name="search_import_key" value="'.dol_escape_htmltag($search_import_key).'">';
892
+    print '</td>';
893 893
 }
894 894
 // Action column
895 895
 print '<td class="liste_titre" align="right">';
@@ -947,289 +947,289 @@  discard block
 block discarded – undo
947 947
 $totalarray=array();
948 948
 while ($i < min($num, $limit))
949 949
 {
950
-	$obj = $db->fetch_object($resql);
951
-
952
-	$companystatic->id=$obj->rowid;
953
-	$companystatic->name=$obj->name;
954
-	$companystatic->name_alias=$obj->name_alias;
955
-	$companystatic->logo=$obj->logo;
956
-	$companystatic->canvas=$obj->canvas;
957
-	$companystatic->client=$obj->client;
958
-	$companystatic->status=$obj->status;
959
-	$companystatic->email=$obj->email;
960
-	$companystatic->fournisseur=$obj->fournisseur;
961
-	$companystatic->code_client=$obj->code_client;
962
-	$companystatic->code_fournisseur=$obj->code_fournisseur;
963
-
964
-	$companystatic->code_compta_client=$obj->code_compta;
965
-	$companystatic->code_compta_fournisseur=$obj->code_compta_fournisseur;
966
-
967
-   	$companystatic->fk_prospectlevel=$obj->fk_prospectlevel;
968
-
969
-	print '<tr class="oddeven">';
970
-	if (! empty($arrayfields['s.rowid']['checked']))
971
-	{
972
-		print '<td class="tdoverflowmax50">';
973
-		print $obj->rowid;
974
-		print "</td>\n";
975
-		if (! $i) $totalarray['nbfield']++;
976
-	}
977
-	if (! empty($arrayfields['s.nom']['checked']))
978
-	{
979
-		$savalias = $obj->name_alias;
980
-		if (! empty($arrayfields['s.name_alias']['checked'])) $companystatic->name_alias='';
981
-		print '<td class="tdoverflowmax200">';
982
-		print $companystatic->getNomUrl(1, '', 100, 0, 1);
983
-		print "</td>\n";
984
-		$companystatic->name_alias = $savalias;
950
+    $obj = $db->fetch_object($resql);
951
+
952
+    $companystatic->id=$obj->rowid;
953
+    $companystatic->name=$obj->name;
954
+    $companystatic->name_alias=$obj->name_alias;
955
+    $companystatic->logo=$obj->logo;
956
+    $companystatic->canvas=$obj->canvas;
957
+    $companystatic->client=$obj->client;
958
+    $companystatic->status=$obj->status;
959
+    $companystatic->email=$obj->email;
960
+    $companystatic->fournisseur=$obj->fournisseur;
961
+    $companystatic->code_client=$obj->code_client;
962
+    $companystatic->code_fournisseur=$obj->code_fournisseur;
963
+
964
+    $companystatic->code_compta_client=$obj->code_compta;
965
+    $companystatic->code_compta_fournisseur=$obj->code_compta_fournisseur;
966
+
967
+        $companystatic->fk_prospectlevel=$obj->fk_prospectlevel;
968
+
969
+    print '<tr class="oddeven">';
970
+    if (! empty($arrayfields['s.rowid']['checked']))
971
+    {
972
+        print '<td class="tdoverflowmax50">';
973
+        print $obj->rowid;
974
+        print "</td>\n";
985 975
         if (! $i) $totalarray['nbfield']++;
986
-	}
987
-	if (! empty($arrayfields['s.name_alias']['checked']))
988
-	{
989
-		print '<td class="tdoverflowmax200">';
990
-		print $companystatic->name_alias;
991
-		print "</td>\n";
992
-		if (! $i) $totalarray['nbfield']++;
993
-	}
994
-	// Barcode
995
-	if (! empty($arrayfields['s.barcode']['checked']))
996
-	{
997
-		print '<td>'.$obj->barcode.'</td>';
998
-		if (! $i) $totalarray['nbfield']++;
999
-	}
1000
-	// Customer code
1001
-	if (! empty($arrayfields['s.code_client']['checked']))
1002
-	{
1003
-		print '<td class="nowraponall">'.$obj->code_client.'</td>';
1004
-		if (! $i) $totalarray['nbfield']++;
1005
-	}
1006
-	// Supplier code
1007
-	if (! empty($arrayfields['s.code_fournisseur']['checked']))
1008
-	{
1009
-		print '<td class="nowraponall">'.$obj->code_fournisseur.'</td>';
1010
-		if (! $i) $totalarray['nbfield']++;
1011
-	}
1012
-	// Account customer code
1013
-	if (! empty($arrayfields['s.code_compta']['checked']))
1014
-	{
1015
-		print '<td>'.$obj->code_compta.'</td>';
1016
-		if (! $i) $totalarray['nbfield']++;
1017
-	}
1018
-	// Account supplier code
1019
-	if (! empty($arrayfields['s.code_compta_fournisseur']['checked']))
1020
-	{
1021
-		print '<td>'.$obj->code_compta_fournisseur.'</td>';
1022
-		if (! $i) $totalarray['nbfield']++;
1023
-	}
1024
-	// Town
1025
-	if (! empty($arrayfields['s.town']['checked']))
1026
-	{
1027
-		print "<td>".$obj->town."</td>\n";
1028
-		if (! $i) $totalarray['nbfield']++;
1029
-	}
1030
-	// Zip
1031
-	if (! empty($arrayfields['s.zip']['checked']))
1032
-	{
1033
-		print "<td>".$obj->zip."</td>\n";
1034
-		if (! $i) $totalarray['nbfield']++;
1035
-	}
1036
-	// State
1037
-	if (! empty($arrayfields['state.nom']['checked']))
1038
-	{
1039
-		print "<td>".$obj->state_name."</td>\n";
1040
-		if (! $i) $totalarray['nbfield']++;
1041
-	}
1042
-	// Region
1043
-	if (! empty($arrayfields['region.nom']['checked']))
1044
-	{
1045
-		print "<td>".$obj->region_name."</td>\n";
1046
-		if (! $i) $totalarray['nbfield']++;
1047
-	}
1048
-	// Country
1049
-	if (! empty($arrayfields['country.code_iso']['checked']))
1050
-	{
1051
-		print '<td align="center">';
1052
-		$tmparray=getCountry($obj->fk_pays,'all');
1053
-		print $tmparray['label'];
1054
-		print '</td>';
1055
-		if (! $i) $totalarray['nbfield']++;
1056
-	}
1057
-	// Type ent
1058
-	if (! empty($arrayfields['typent.code']['checked']))
1059
-	{
1060
-		print '<td align="center">';
1061
-		if (! is_array($typenArray) || count($typenArray)==0) $typenArray = $formcompany->typent_array(1);
1062
-		print $typenArray[$obj->typent_code];
1063
-		print '</td>';
1064
-		if (! $i) $totalarray['nbfield']++;
1065
-	}
1066
-	// Staff
1067
-	if (! empty($arrayfields['staff.code']['checked']))
1068
-	{
1069
-		print '<td align="center">';
1070
-		if (! is_array($staffArray) || count($staffArray)==0) $staffArray = $formcompany->effectif_array(1);
1071
-		print $staffArray[$obj->staff_code];
1072
-		print '</td>';
1073
-		if (! $i) $totalarray['nbfield']++;
1074
-	}
1075
-	if (! empty($arrayfields['s.email']['checked']))
1076
-	{
1077
-		print "<td>".$obj->email."</td>\n";
1078
-		if (! $i) $totalarray['nbfield']++;
1079
-	}
1080
-	if (! empty($arrayfields['s.phone']['checked']))
1081
-	{
1082
-		print "<td>".dol_print_phone($obj->phone, $obj->country_code, 0, $obj->rowid)."</td>\n";
1083
-		if (! $i) $totalarray['nbfield']++;
1084
-	}
1085
-	if (! empty($arrayfields['s.fax']['checked']))
1086
-	{
1087
-		print "<td>".dol_print_phone($obj->fax, $obj->country_code, 0, $obj->rowid)."</td>\n";
1088
-		if (! $i) $totalarray['nbfield']++;
1089
-	}
1090
-	if (! empty($arrayfields['s.url']['checked']))
1091
-	{
1092
-		print "<td>".$obj->url."</td>\n";
1093
-		if (! $i) $totalarray['nbfield']++;
1094
-	}
1095
-	if (! empty($arrayfields['s.siren']['checked']))
1096
-	{
1097
-		print "<td>".$obj->idprof1."</td>\n";
1098
-		if (! $i) $totalarray['nbfield']++;
1099
-	}
1100
-	if (! empty($arrayfields['s.siret']['checked']))
1101
-	{
1102
-		print "<td>".$obj->idprof2."</td>\n";
1103
-		if (! $i) $totalarray['nbfield']++;
1104
-	}
1105
-	if (! empty($arrayfields['s.ape']['checked']))
1106
-	{
1107
-		print "<td>".$obj->idprof3."</td>\n";
1108
-		if (! $i) $totalarray['nbfield']++;
1109
-	}
1110
-	if (! empty($arrayfields['s.idprof4']['checked']))
1111
-	{
1112
-		print "<td>".$obj->idprof4."</td>\n";
1113
-		if (! $i) $totalarray['nbfield']++;
1114
-	}
1115
-	if (! empty($arrayfields['s.idprof5']['checked']))
1116
-	{
1117
-		print "<td>".$obj->idprof5."</td>\n";
1118
-		if (! $i) $totalarray['nbfield']++;
1119
-	}
1120
-	if (! empty($arrayfields['s.idprof6']['checked']))
1121
-	{
1122
-		print "<td>".$obj->idprof6."</td>\n";
1123
-		if (! $i) $totalarray['nbfield']++;
1124
-	}
1125
-	if (! empty($arrayfields['s.tva_intra']['checked']))
1126
-	{
1127
-		print "<td>".$obj->tva_intra."</td>\n";
1128
-		if (! $i) $totalarray['nbfield']++;
1129
-	}
1130
-	// Type
1131
-	if (! empty($arrayfields['customerorsupplier']['checked']))
1132
-	{
1133
-		print '<td align="center">';
1134
-		$s='';
1135
-		if (($obj->client==1 || $obj->client==3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))
1136
-		{
1137
-	  		$companystatic->name=$langs->trans("Customer");
1138
-	  		$companystatic->name_alias='';
1139
-			$s.=$companystatic->getNomUrl(0,'customer',0,1);
1140
-		}
1141
-		if (($obj->client==2 || $obj->client==3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
1142
-		{
1143
-			if ($s) $s.=" / ";
1144
-			$companystatic->name=$langs->trans("Prospect");
1145
-	  		$companystatic->name_alias='';
1146
-			$s.=$companystatic->getNomUrl(0,'prospect',0,1);
1147
-		}
1148
-		if ((! empty($conf->fournisseur->enabled) || ! empty($conf->supplier_proposal->enabled)) && $obj->fournisseur)
1149
-		{
1150
-			if ($s) $s.=" / ";
1151
-			$companystatic->name=$langs->trans("Supplier");
1152
-	  		$companystatic->name_alias='';
1153
-			$s.=$companystatic->getNomUrl(0,'supplier',0,1);
1154
-		}
1155
-		print $s;
1156
-		print '</td>';
1157
-		if (! $i) $totalarray['nbfield']++;
1158
-	}
1159
-
1160
-	if (! empty($arrayfields['s.fk_prospectlevel']['checked']))
1161
-	{
1162
-		// Prospect level
1163
-		print '<td align="center">';
1164
-		print $companystatic->getLibProspLevel();
1165
-		print "</td>";
1166
-		if (! $i) $totalarray['nbfield']++;
1167
-	}
1168
-
1169
-	if (! empty($arrayfields['s.fk_stcomm']['checked']))
1170
-	{
1171
-		// Prospect status
1172
-		print '<td align="center" class="nowrap"><div class="nowrap">';
1173
-		print '<div class="inline-block">'.$companystatic->LibProspCommStatut($obj->stcomm_id,2,$prospectstatic->cacheprospectstatus[$obj->stcomm_id]['label']);
1174
-		print '</div> - <div class="inline-block">';
1175
-		foreach($prospectstatic->cacheprospectstatus as $key => $val)
1176
-		{
1177
-			$titlealt='default';
1178
-			if (! empty($val['code']) && ! in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt=$val['label'];
1179
-			if ($obj->stcomm_id != $val['id']) print '<a class="pictosubstatus" href="'.$_SERVER["PHP_SELF"].'?stcommsocid='.$obj->rowid.'&stcomm='.$val['code'].'&action=setstcomm'.$param.($page?'&page='.urlencode($page):'').'">'.img_action($titlealt,$val['code']).'</a>';
1180
-		}
1181
-		print '</div></div></td>';
1182
-		if (! $i) $totalarray['nbfield']++;
1183
-	}
1184
-	// Extra fields
1185
-	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
1186
-	// Fields from hook
1187
-	$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
1188
-	$reshook=$hookmanager->executeHooks('printFieldListValue',$parameters);    // Note that $action and $object may have been modified by hook
1189
-	print $hookmanager->resPrint;
1190
-	// Date creation
1191
-	if (! empty($arrayfields['s.datec']['checked']))
1192
-	{
1193
-		print '<td align="center" class="nowrap">';
1194
-		print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
1195
-		print '</td>';
1196
-		if (! $i) $totalarray['nbfield']++;
1197
-	}
1198
-	// Date modification
1199
-	if (! empty($arrayfields['s.tms']['checked']))
1200
-	{
1201
-		print '<td align="center" class="nowrap">';
1202
-		print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
1203
-		print '</td>';
1204
-		if (! $i) $totalarray['nbfield']++;
1205
-	}
1206
-	// Status
1207
-	if (! empty($arrayfields['s.status']['checked']))
1208
-	{
1209
-		print '<td align="center" class="nowrap">'.$companystatic->getLibStatut(3).'</td>';
1210
-		if (! $i) $totalarray['nbfield']++;
1211
-	}
1212
-	if (! empty($arrayfields['s.import_key']['checked']))
1213
-	{
1214
-		print '<td class="tdoverflowmax100">';
1215
-		print $obj->import_key;
1216
-		print "</td>\n";
1217
-		if (! $i) $totalarray['nbfield']++;
1218
-	}
1219
-
1220
-	// Action column
1221
-	print '<td class="nowrap" align="center">';
1222
-	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
1223
-	{
1224
-		$selected=0;
1225
-		if (in_array($obj->rowid, $arrayofselected)) $selected=1;
1226
-		print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
1227
-	}
1228
-	print '</td>';
1229
-	if (! $i) $totalarray['nbfield']++;
1230
-
1231
-	print '</tr>'."\n";
1232
-	$i++;
976
+    }
977
+    if (! empty($arrayfields['s.nom']['checked']))
978
+    {
979
+        $savalias = $obj->name_alias;
980
+        if (! empty($arrayfields['s.name_alias']['checked'])) $companystatic->name_alias='';
981
+        print '<td class="tdoverflowmax200">';
982
+        print $companystatic->getNomUrl(1, '', 100, 0, 1);
983
+        print "</td>\n";
984
+        $companystatic->name_alias = $savalias;
985
+        if (! $i) $totalarray['nbfield']++;
986
+    }
987
+    if (! empty($arrayfields['s.name_alias']['checked']))
988
+    {
989
+        print '<td class="tdoverflowmax200">';
990
+        print $companystatic->name_alias;
991
+        print "</td>\n";
992
+        if (! $i) $totalarray['nbfield']++;
993
+    }
994
+    // Barcode
995
+    if (! empty($arrayfields['s.barcode']['checked']))
996
+    {
997
+        print '<td>'.$obj->barcode.'</td>';
998
+        if (! $i) $totalarray['nbfield']++;
999
+    }
1000
+    // Customer code
1001
+    if (! empty($arrayfields['s.code_client']['checked']))
1002
+    {
1003
+        print '<td class="nowraponall">'.$obj->code_client.'</td>';
1004
+        if (! $i) $totalarray['nbfield']++;
1005
+    }
1006
+    // Supplier code
1007
+    if (! empty($arrayfields['s.code_fournisseur']['checked']))
1008
+    {
1009
+        print '<td class="nowraponall">'.$obj->code_fournisseur.'</td>';
1010
+        if (! $i) $totalarray['nbfield']++;
1011
+    }
1012
+    // Account customer code
1013
+    if (! empty($arrayfields['s.code_compta']['checked']))
1014
+    {
1015
+        print '<td>'.$obj->code_compta.'</td>';
1016
+        if (! $i) $totalarray['nbfield']++;
1017
+    }
1018
+    // Account supplier code
1019
+    if (! empty($arrayfields['s.code_compta_fournisseur']['checked']))
1020
+    {
1021
+        print '<td>'.$obj->code_compta_fournisseur.'</td>';
1022
+        if (! $i) $totalarray['nbfield']++;
1023
+    }
1024
+    // Town
1025
+    if (! empty($arrayfields['s.town']['checked']))
1026
+    {
1027
+        print "<td>".$obj->town."</td>\n";
1028
+        if (! $i) $totalarray['nbfield']++;
1029
+    }
1030
+    // Zip
1031
+    if (! empty($arrayfields['s.zip']['checked']))
1032
+    {
1033
+        print "<td>".$obj->zip."</td>\n";
1034
+        if (! $i) $totalarray['nbfield']++;
1035
+    }
1036
+    // State
1037
+    if (! empty($arrayfields['state.nom']['checked']))
1038
+    {
1039
+        print "<td>".$obj->state_name."</td>\n";
1040
+        if (! $i) $totalarray['nbfield']++;
1041
+    }
1042
+    // Region
1043
+    if (! empty($arrayfields['region.nom']['checked']))
1044
+    {
1045
+        print "<td>".$obj->region_name."</td>\n";
1046
+        if (! $i) $totalarray['nbfield']++;
1047
+    }
1048
+    // Country
1049
+    if (! empty($arrayfields['country.code_iso']['checked']))
1050
+    {
1051
+        print '<td align="center">';
1052
+        $tmparray=getCountry($obj->fk_pays,'all');
1053
+        print $tmparray['label'];
1054
+        print '</td>';
1055
+        if (! $i) $totalarray['nbfield']++;
1056
+    }
1057
+    // Type ent
1058
+    if (! empty($arrayfields['typent.code']['checked']))
1059
+    {
1060
+        print '<td align="center">';
1061
+        if (! is_array($typenArray) || count($typenArray)==0) $typenArray = $formcompany->typent_array(1);
1062
+        print $typenArray[$obj->typent_code];
1063
+        print '</td>';
1064
+        if (! $i) $totalarray['nbfield']++;
1065
+    }
1066
+    // Staff
1067
+    if (! empty($arrayfields['staff.code']['checked']))
1068
+    {
1069
+        print '<td align="center">';
1070
+        if (! is_array($staffArray) || count($staffArray)==0) $staffArray = $formcompany->effectif_array(1);
1071
+        print $staffArray[$obj->staff_code];
1072
+        print '</td>';
1073
+        if (! $i) $totalarray['nbfield']++;
1074
+    }
1075
+    if (! empty($arrayfields['s.email']['checked']))
1076
+    {
1077
+        print "<td>".$obj->email."</td>\n";
1078
+        if (! $i) $totalarray['nbfield']++;
1079
+    }
1080
+    if (! empty($arrayfields['s.phone']['checked']))
1081
+    {
1082
+        print "<td>".dol_print_phone($obj->phone, $obj->country_code, 0, $obj->rowid)."</td>\n";
1083
+        if (! $i) $totalarray['nbfield']++;
1084
+    }
1085
+    if (! empty($arrayfields['s.fax']['checked']))
1086
+    {
1087
+        print "<td>".dol_print_phone($obj->fax, $obj->country_code, 0, $obj->rowid)."</td>\n";
1088
+        if (! $i) $totalarray['nbfield']++;
1089
+    }
1090
+    if (! empty($arrayfields['s.url']['checked']))
1091
+    {
1092
+        print "<td>".$obj->url."</td>\n";
1093
+        if (! $i) $totalarray['nbfield']++;
1094
+    }
1095
+    if (! empty($arrayfields['s.siren']['checked']))
1096
+    {
1097
+        print "<td>".$obj->idprof1."</td>\n";
1098
+        if (! $i) $totalarray['nbfield']++;
1099
+    }
1100
+    if (! empty($arrayfields['s.siret']['checked']))
1101
+    {
1102
+        print "<td>".$obj->idprof2."</td>\n";
1103
+        if (! $i) $totalarray['nbfield']++;
1104
+    }
1105
+    if (! empty($arrayfields['s.ape']['checked']))
1106
+    {
1107
+        print "<td>".$obj->idprof3."</td>\n";
1108
+        if (! $i) $totalarray['nbfield']++;
1109
+    }
1110
+    if (! empty($arrayfields['s.idprof4']['checked']))
1111
+    {
1112
+        print "<td>".$obj->idprof4."</td>\n";
1113
+        if (! $i) $totalarray['nbfield']++;
1114
+    }
1115
+    if (! empty($arrayfields['s.idprof5']['checked']))
1116
+    {
1117
+        print "<td>".$obj->idprof5."</td>\n";
1118
+        if (! $i) $totalarray['nbfield']++;
1119
+    }
1120
+    if (! empty($arrayfields['s.idprof6']['checked']))
1121
+    {
1122
+        print "<td>".$obj->idprof6."</td>\n";
1123
+        if (! $i) $totalarray['nbfield']++;
1124
+    }
1125
+    if (! empty($arrayfields['s.tva_intra']['checked']))
1126
+    {
1127
+        print "<td>".$obj->tva_intra."</td>\n";
1128
+        if (! $i) $totalarray['nbfield']++;
1129
+    }
1130
+    // Type
1131
+    if (! empty($arrayfields['customerorsupplier']['checked']))
1132
+    {
1133
+        print '<td align="center">';
1134
+        $s='';
1135
+        if (($obj->client==1 || $obj->client==3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))
1136
+        {
1137
+                $companystatic->name=$langs->trans("Customer");
1138
+                $companystatic->name_alias='';
1139
+            $s.=$companystatic->getNomUrl(0,'customer',0,1);
1140
+        }
1141
+        if (($obj->client==2 || $obj->client==3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
1142
+        {
1143
+            if ($s) $s.=" / ";
1144
+            $companystatic->name=$langs->trans("Prospect");
1145
+                $companystatic->name_alias='';
1146
+            $s.=$companystatic->getNomUrl(0,'prospect',0,1);
1147
+        }
1148
+        if ((! empty($conf->fournisseur->enabled) || ! empty($conf->supplier_proposal->enabled)) && $obj->fournisseur)
1149
+        {
1150
+            if ($s) $s.=" / ";
1151
+            $companystatic->name=$langs->trans("Supplier");
1152
+                $companystatic->name_alias='';
1153
+            $s.=$companystatic->getNomUrl(0,'supplier',0,1);
1154
+        }
1155
+        print $s;
1156
+        print '</td>';
1157
+        if (! $i) $totalarray['nbfield']++;
1158
+    }
1159
+
1160
+    if (! empty($arrayfields['s.fk_prospectlevel']['checked']))
1161
+    {
1162
+        // Prospect level
1163
+        print '<td align="center">';
1164
+        print $companystatic->getLibProspLevel();
1165
+        print "</td>";
1166
+        if (! $i) $totalarray['nbfield']++;
1167
+    }
1168
+
1169
+    if (! empty($arrayfields['s.fk_stcomm']['checked']))
1170
+    {
1171
+        // Prospect status
1172
+        print '<td align="center" class="nowrap"><div class="nowrap">';
1173
+        print '<div class="inline-block">'.$companystatic->LibProspCommStatut($obj->stcomm_id,2,$prospectstatic->cacheprospectstatus[$obj->stcomm_id]['label']);
1174
+        print '</div> - <div class="inline-block">';
1175
+        foreach($prospectstatic->cacheprospectstatus as $key => $val)
1176
+        {
1177
+            $titlealt='default';
1178
+            if (! empty($val['code']) && ! in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt=$val['label'];
1179
+            if ($obj->stcomm_id != $val['id']) print '<a class="pictosubstatus" href="'.$_SERVER["PHP_SELF"].'?stcommsocid='.$obj->rowid.'&stcomm='.$val['code'].'&action=setstcomm'.$param.($page?'&page='.urlencode($page):'').'">'.img_action($titlealt,$val['code']).'</a>';
1180
+        }
1181
+        print '</div></div></td>';
1182
+        if (! $i) $totalarray['nbfield']++;
1183
+    }
1184
+    // Extra fields
1185
+    include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
1186
+    // Fields from hook
1187
+    $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
1188
+    $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters);    // Note that $action and $object may have been modified by hook
1189
+    print $hookmanager->resPrint;
1190
+    // Date creation
1191
+    if (! empty($arrayfields['s.datec']['checked']))
1192
+    {
1193
+        print '<td align="center" class="nowrap">';
1194
+        print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
1195
+        print '</td>';
1196
+        if (! $i) $totalarray['nbfield']++;
1197
+    }
1198
+    // Date modification
1199
+    if (! empty($arrayfields['s.tms']['checked']))
1200
+    {
1201
+        print '<td align="center" class="nowrap">';
1202
+        print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
1203
+        print '</td>';
1204
+        if (! $i) $totalarray['nbfield']++;
1205
+    }
1206
+    // Status
1207
+    if (! empty($arrayfields['s.status']['checked']))
1208
+    {
1209
+        print '<td align="center" class="nowrap">'.$companystatic->getLibStatut(3).'</td>';
1210
+        if (! $i) $totalarray['nbfield']++;
1211
+    }
1212
+    if (! empty($arrayfields['s.import_key']['checked']))
1213
+    {
1214
+        print '<td class="tdoverflowmax100">';
1215
+        print $obj->import_key;
1216
+        print "</td>\n";
1217
+        if (! $i) $totalarray['nbfield']++;
1218
+    }
1219
+
1220
+    // Action column
1221
+    print '<td class="nowrap" align="center">';
1222
+    if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
1223
+    {
1224
+        $selected=0;
1225
+        if (in_array($obj->rowid, $arrayofselected)) $selected=1;
1226
+        print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
1227
+    }
1228
+    print '</td>';
1229
+    if (! $i) $totalarray['nbfield']++;
1230
+
1231
+    print '</tr>'."\n";
1232
+    $i++;
1233 1233
 }
1234 1234
 
1235 1235
 $db->free($resql);
Please login to merge, or discard this patch.
dolibarr/htdocs/main.inc.php 1 patch
Indentation   +1481 added lines, -1481 removed lines patch added patch discarded remove patch
@@ -38,34 +38,34 @@  discard block
 block discarded – undo
38 38
 $micro_start_time = 0;
39 39
 if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']))
40 40
 {
41
-	list($usec, $sec) = explode(" ", microtime());
42
-	$micro_start_time=((float) $usec + (float) $sec);
43
-	// Add Xdebug code coverage
44
-	//define('XDEBUGCOVERAGE',1);
45
-	if (defined('XDEBUGCOVERAGE')) {
46
-		xdebug_start_code_coverage();
47
-	}
41
+    list($usec, $sec) = explode(" ", microtime());
42
+    $micro_start_time=((float) $usec + (float) $sec);
43
+    // Add Xdebug code coverage
44
+    //define('XDEBUGCOVERAGE',1);
45
+    if (defined('XDEBUGCOVERAGE')) {
46
+        xdebug_start_code_coverage();
47
+    }
48 48
 }
49 49
 
50 50
 // Removed magic_quotes
51 51
 if (function_exists('get_magic_quotes_gpc'))	// magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5
52 52
 {
53
-	if (get_magic_quotes_gpc())
54
-	{
55
-		// Forcing parameter setting magic_quotes_gpc and cleaning parameters
56
-		// (Otherwise he would have for each position, condition
57
-		// Reading stripslashes variable according to state get_magic_quotes_gpc).
58
-		// Off mode recommended (just do $db->escape for insert / update).
59
-		function stripslashes_deep($value)
60
-		{
61
-			return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));
62
-		}
63
-		$_GET     = array_map('stripslashes_deep', $_GET);
64
-		$_POST    = array_map('stripslashes_deep', $_POST);
65
-		$_FILES   = array_map('stripslashes_deep', $_FILES);
66
-		//$_COOKIE  = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql
67
-		@set_magic_quotes_runtime(0);
68
-	}
53
+    if (get_magic_quotes_gpc())
54
+    {
55
+        // Forcing parameter setting magic_quotes_gpc and cleaning parameters
56
+        // (Otherwise he would have for each position, condition
57
+        // Reading stripslashes variable according to state get_magic_quotes_gpc).
58
+        // Off mode recommended (just do $db->escape for insert / update).
59
+        function stripslashes_deep($value)
60
+        {
61
+            return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));
62
+        }
63
+        $_GET     = array_map('stripslashes_deep', $_GET);
64
+        $_POST    = array_map('stripslashes_deep', $_POST);
65
+        $_FILES   = array_map('stripslashes_deep', $_FILES);
66
+        //$_COOKIE  = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql
67
+        @set_magic_quotes_runtime(0);
68
+    }
69 69
 }
70 70
 
71 71
 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -93,58 +93,58 @@  discard block
 block discarded – undo
93 93
  */
94 94
 function testSqlAndScriptInject($val, $type)
95 95
 {
96
-	$inj = 0;
97
-	// For SQL Injection (only GET are used to be included into bad escaped SQL requests)
98
-	if ($type == 1 || $type == 3)
99
-	{
100
-		$inj += preg_match('/delete\s+from/i',	 $val);
101
-		$inj += preg_match('/create\s+table/i',	 $val);
102
-		$inj += preg_match('/insert\s+into/i', 	 $val);
103
-		$inj += preg_match('/select\s+from/i', 	 $val);
104
-		$inj += preg_match('/into\s+(outfile|dumpfile)/i',  $val);
105
-		$inj += preg_match('/user\s*\(/i',  $val);						// avoid to use function user() that return current database login
106
-		$inj += preg_match('/information_schema/i',  $val);				// avoid to use request that read information_schema database
107
-	}
108
-	if ($type == 3)
109
-	{
110
-		$inj += preg_match('/select|update|delete|replace|group\s+by|concat|count|from/i',	 $val);
111
-	}
112
-	if ($type != 2)	// Not common key strings, so we can check them both on GET and POST
113
-	{
114
-		$inj += preg_match('/updatexml\(/i', 	 $val);
115
-		$inj += preg_match('/update.+set.+=/i',  $val);
116
-		$inj += preg_match('/union.+select/i', 	 $val);
117
-		$inj += preg_match('/(\.\.%2f)+/i',		 $val);
118
-	}
119
-	// For XSS Injection done by adding javascript with script
120
-	// This is all cases a browser consider text is javascript:
121
-	// When it found '<script', 'javascript:', '<style', 'onload\s=' on body tag, '="&' on a tag size with old browsers
122
-	// All examples on page: http://ha.ckers.org/xss.html#XSScalc
123
-	// More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
124
-	$inj += preg_match('/<script/i', $val);
125
-	$inj += preg_match('/<iframe/i', $val);
126
-	$inj += preg_match('/<audio/i', $val);
127
-	$inj += preg_match('/Set\.constructor/i', $val);	// ECMA script 6
128
-	if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
129
-	$inj += preg_match('/base[\s]+href/si', $val);
130
-	$inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
131
-	$inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
132
-	$inj += preg_match('/onfocus\s*=/i', $val);       // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
133
-	$inj += preg_match('/onload\s*=/i', $val);        // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
134
-	$inj += preg_match('/onloadstart\s*=/i', $val);   // onload can be set on audio tag <audio onloadstart=alert(1)>
135
-	$inj += preg_match('/onclick\s*=/i', $val);       // onclick can be set on img text html tag like <img onclick = alert(1)>
136
-	$inj += preg_match('/onscroll\s*=/i', $val);      // onscroll can be on textarea
137
-	//$inj += preg_match('/on[A-Z][a-z]+\*=/', $val);   // To lock event handlers onAbort(), ...
138
-	$inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);		// refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
139
-	//if ($type == 1)
140
-	//{
141
-		$inj += preg_match('/javascript:/i', $val);
142
-		$inj += preg_match('/vbscript:/i', $val);
143
-	//}
144
-	// For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
145
-	if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
146
-	if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
147
-	return $inj;
96
+    $inj = 0;
97
+    // For SQL Injection (only GET are used to be included into bad escaped SQL requests)
98
+    if ($type == 1 || $type == 3)
99
+    {
100
+        $inj += preg_match('/delete\s+from/i',	 $val);
101
+        $inj += preg_match('/create\s+table/i',	 $val);
102
+        $inj += preg_match('/insert\s+into/i', 	 $val);
103
+        $inj += preg_match('/select\s+from/i', 	 $val);
104
+        $inj += preg_match('/into\s+(outfile|dumpfile)/i',  $val);
105
+        $inj += preg_match('/user\s*\(/i',  $val);						// avoid to use function user() that return current database login
106
+        $inj += preg_match('/information_schema/i',  $val);				// avoid to use request that read information_schema database
107
+    }
108
+    if ($type == 3)
109
+    {
110
+        $inj += preg_match('/select|update|delete|replace|group\s+by|concat|count|from/i',	 $val);
111
+    }
112
+    if ($type != 2)	// Not common key strings, so we can check them both on GET and POST
113
+    {
114
+        $inj += preg_match('/updatexml\(/i', 	 $val);
115
+        $inj += preg_match('/update.+set.+=/i',  $val);
116
+        $inj += preg_match('/union.+select/i', 	 $val);
117
+        $inj += preg_match('/(\.\.%2f)+/i',		 $val);
118
+    }
119
+    // For XSS Injection done by adding javascript with script
120
+    // This is all cases a browser consider text is javascript:
121
+    // When it found '<script', 'javascript:', '<style', 'onload\s=' on body tag, '="&' on a tag size with old browsers
122
+    // All examples on page: http://ha.ckers.org/xss.html#XSScalc
123
+    // More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
124
+    $inj += preg_match('/<script/i', $val);
125
+    $inj += preg_match('/<iframe/i', $val);
126
+    $inj += preg_match('/<audio/i', $val);
127
+    $inj += preg_match('/Set\.constructor/i', $val);	// ECMA script 6
128
+    if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
129
+    $inj += preg_match('/base[\s]+href/si', $val);
130
+    $inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
131
+    $inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
132
+    $inj += preg_match('/onfocus\s*=/i', $val);       // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
133
+    $inj += preg_match('/onload\s*=/i', $val);        // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
134
+    $inj += preg_match('/onloadstart\s*=/i', $val);   // onload can be set on audio tag <audio onloadstart=alert(1)>
135
+    $inj += preg_match('/onclick\s*=/i', $val);       // onclick can be set on img text html tag like <img onclick = alert(1)>
136
+    $inj += preg_match('/onscroll\s*=/i', $val);      // onscroll can be on textarea
137
+    //$inj += preg_match('/on[A-Z][a-z]+\*=/', $val);   // To lock event handlers onAbort(), ...
138
+    $inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);		// refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
139
+    //if ($type == 1)
140
+    //{
141
+        $inj += preg_match('/javascript:/i', $val);
142
+        $inj += preg_match('/vbscript:/i', $val);
143
+    //}
144
+    // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
145
+    if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
146
+    if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
147
+    return $inj;
148 148
 }
149 149
 
150 150
 /**
@@ -156,58 +156,58 @@  discard block
 block discarded – undo
156 156
  */
157 157
 function analyseVarsForSqlAndScriptsInjection(&$var, $type)
158 158
 {
159
-	if (is_array($var))
160
-	{
161
-		foreach ($var as $key => $value)	// Warning, $key may also be used for attacks
162
-		{
163
-			if (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type))
164
-			{
165
-				//$var[$key] = $value;	// This is useless
166
-			}
167
-			else
168
-			{
169
-				print 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')';
170
-				exit;
171
-			}
172
-		}
173
-		return true;
174
-	}
175
-	else
176
-	{
177
-		return (testSqlAndScriptInject($var, $type) <= 0);
178
-	}
159
+    if (is_array($var))
160
+    {
161
+        foreach ($var as $key => $value)	// Warning, $key may also be used for attacks
162
+        {
163
+            if (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type))
164
+            {
165
+                //$var[$key] = $value;	// This is useless
166
+            }
167
+            else
168
+            {
169
+                print 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')';
170
+                exit;
171
+            }
172
+        }
173
+        return true;
174
+    }
175
+    else
176
+    {
177
+        return (testSqlAndScriptInject($var, $type) <= 0);
178
+    }
179 179
 }
180 180
 
181 181
 
182 182
 // Check consistency of NOREQUIREXXX DEFINES
183 183
 if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && ! defined('NOREQUIREMENU'))
184 184
 {
185
-	print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them';
186
-	exit;
185
+    print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them';
186
+    exit;
187 187
 }
188 188
 
189 189
 // Sanity check on URL
190 190
 if (! empty($_SERVER["PHP_SELF"]))
191 191
 {
192
-	$morevaltochecklikepost=array($_SERVER["PHP_SELF"]);
193
-	analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);
192
+    $morevaltochecklikepost=array($_SERVER["PHP_SELF"]);
193
+    analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);
194 194
 }
195 195
 // Sanity check on GET parameters
196 196
 if (! defined('NOSCANGETFORINJECTION') && ! empty($_SERVER["QUERY_STRING"]))
197 197
 {
198
-	$morevaltochecklikeget=array($_SERVER["QUERY_STRING"]);
199
-	analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);
198
+    $morevaltochecklikeget=array($_SERVER["QUERY_STRING"]);
199
+    analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);
200 200
 }
201 201
 // Sanity check on POST
202 202
 if (! defined('NOSCANPOSTFORINJECTION'))
203 203
 {
204
-	analyseVarsForSqlAndScriptsInjection($_POST,0);
204
+    analyseVarsForSqlAndScriptsInjection($_POST,0);
205 205
 }
206 206
 
207 207
 // This is to make Dolibarr working with Plesk
208 208
 if (! empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs')
209 209
 {
210
-	set_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');
210
+    set_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');
211 211
 }
212 212
 
213 213
 // Include the conf.php and functions.lib.php
@@ -218,20 +218,20 @@  discard block
 block discarded – undo
218 218
 // DOL_AUTOSET_COOKIE=cookiename:val1,val2 and  cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , ))
219 219
 if (! empty($_POST["DOL_AUTOSET_COOKIE"]))
220 220
 {
221
-	$tmpautoset=explode(':',$_POST["DOL_AUTOSET_COOKIE"],2);
222
-	$tmplist=explode(',',$tmpautoset[1]);
223
-	$cookiearrayvalue=array();
224
-	foreach ($tmplist as $tmpkey)
225
-	{
226
-		$postkey=$tmpautoset[0].'_'.$tmpkey;
227
-		//var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
228
-		if (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];
229
-	}
230
-	$cookiename=$tmpautoset[0];
231
-	$cookievalue=json_encode($cookiearrayvalue);
232
-	//var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);
233
-	setcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);	// keep cookie 1 year and add tag httponly
234
-	if (empty($cookievalue)) unset($_COOKIE[$cookiename]);
221
+    $tmpautoset=explode(':',$_POST["DOL_AUTOSET_COOKIE"],2);
222
+    $tmplist=explode(',',$tmpautoset[1]);
223
+    $cookiearrayvalue=array();
224
+    foreach ($tmplist as $tmpkey)
225
+    {
226
+        $postkey=$tmpautoset[0].'_'.$tmpkey;
227
+        //var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
228
+        if (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];
229
+    }
230
+    $cookiename=$tmpautoset[0];
231
+    $cookievalue=json_encode($cookiearrayvalue);
232
+    //var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);
233
+    setcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);	// keep cookie 1 year and add tag httponly
234
+    if (empty($cookievalue)) unset($_COOKIE[$cookiename]);
235 235
 }
236 236
 
237 237
 
@@ -248,8 +248,8 @@  discard block
 block discarded – undo
248 248
 // We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished.
249 249
 if (! defined('NOSESSION'))
250 250
 {
251
-	session_start();
252
-	/*if (ini_get('register_globals'))    // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
251
+    session_start();
252
+    /*if (ini_get('register_globals'))    // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
253 253
 	{
254 254
 		foreach ($_SESSION as $key=>$value)
255 255
 		{
@@ -267,72 +267,72 @@  discard block
 block discarded – undo
267 267
 // Detection browser
268 268
 if (isset($_SERVER["HTTP_USER_AGENT"]))
269 269
 {
270
-	$tmp=getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
271
-	$conf->browser->name=$tmp['browsername'];
272
-	$conf->browser->os=$tmp['browseros'];
273
-	$conf->browser->version=$tmp['browserversion'];
274
-	$conf->browser->layout=$tmp['layout'];     // 'classic', 'phone', 'tablet'
275
-	//var_dump($conf->browser);
276
-
277
-	if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
278
-	if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
270
+    $tmp=getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
271
+    $conf->browser->name=$tmp['browsername'];
272
+    $conf->browser->os=$tmp['browseros'];
273
+    $conf->browser->version=$tmp['browserversion'];
274
+    $conf->browser->layout=$tmp['layout'];     // 'classic', 'phone', 'tablet'
275
+    //var_dump($conf->browser);
276
+
277
+    if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
278
+    if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
279 279
 }
280 280
 
281 281
 // Force HTTPS if required ($conf->file->main_force_https is 0/1 or https dolibarr root url)
282 282
 // $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off'
283 283
 if (! empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on'))
284 284
 {
285
-	$newurl='';
286
-	if (is_numeric($conf->file->main_force_https))
287
-	{
288
-		if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
289
-		{
290
-			if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
291
-			{
292
-				$newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
293
-			}
294
-		}
295
-		else	// Check HTTPS environment variable (Apache/mod_ssl only)
296
-		{
297
-			$newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
298
-		}
299
-	}
300
-	else
301
-	{
302
-		// Check HTTPS environment variable (Apache/mod_ssl only)
303
-		$newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
304
-	}
305
-	// Start redirect
306
-	if ($newurl)
307
-	{
308
-		dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
309
-		header("Location: ".$newurl);
310
-		exit;
311
-	}
312
-	else
313
-	{
314
-		dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
315
-	}
285
+    $newurl='';
286
+    if (is_numeric($conf->file->main_force_https))
287
+    {
288
+        if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
289
+        {
290
+            if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
291
+            {
292
+                $newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
293
+            }
294
+        }
295
+        else	// Check HTTPS environment variable (Apache/mod_ssl only)
296
+        {
297
+            $newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
298
+        }
299
+    }
300
+    else
301
+    {
302
+        // Check HTTPS environment variable (Apache/mod_ssl only)
303
+        $newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
304
+    }
305
+    // Start redirect
306
+    if ($newurl)
307
+    {
308
+        dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
309
+        header("Location: ".$newurl);
310
+        exit;
311
+    }
312
+    else
313
+    {
314
+        dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
315
+    }
316 316
 }
317 317
 
318 318
 if (! defined('NOLOGIN') && ! defined('NOIPCHECK') && ! empty($dolibarr_main_restrict_ip))
319 319
 {
320
-	$listofip=explode(',', $dolibarr_main_restrict_ip);
321
-	$found = false;
322
-	foreach($listofip as $ip)
323
-	{
324
-		$ip=trim($ip);
325
-		if ($ip == $_SERVER['REMOTE_ADDR'])
326
-		{
327
-			$found = true;
328
-			break;
329
-		}
330
-	}
331
-	if (! $found)
332
-	{
333
-		print 'Access refused by IP protection';
334
-		exit;
335
-	}
320
+    $listofip=explode(',', $dolibarr_main_restrict_ip);
321
+    $found = false;
322
+    foreach($listofip as $ip)
323
+    {
324
+        $ip=trim($ip);
325
+        if ($ip == $_SERVER['REMOTE_ADDR'])
326
+        {
327
+            $found = true;
328
+            break;
329
+        }
330
+    }
331
+    if (! $found)
332
+    {
333
+        print 'Access refused by IP protection';
334
+        exit;
335
+    }
336 336
 }
337 337
 
338 338
 // Loading of additional presentation includes
@@ -342,75 +342,75 @@  discard block
 block discarded – undo
342 342
 // If install or upgrade process not done or not completely finished, we call the install page.
343 343
 if (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED))
344 344
 {
345
-	dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
346
-	header("Location: ".DOL_URL_ROOT."/install/index.php");
347
-	exit;
345
+    dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
346
+    header("Location: ".DOL_URL_ROOT."/install/index.php");
347
+    exit;
348 348
 }
349 349
 // If an upgrade process is required, we call the install page.
350 350
 if ((! empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))
351 351
 || (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ! empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))
352 352
 {
353
-	$versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;
354
-	require_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';
355
-	$dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
356
-	$dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
357
-	$rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
358
-	if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
359
-	{
360
-		dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
361
-		header("Location: ".DOL_URL_ROOT."/install/index.php");
362
-		exit;
363
-	}
353
+    $versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;
354
+    require_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';
355
+    $dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
356
+    $dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
357
+    $rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
358
+    if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
359
+    {
360
+        dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
361
+        header("Location: ".DOL_URL_ROOT."/install/index.php");
362
+        exit;
363
+    }
364 364
 }
365 365
 
366 366
 // Creation of a token against CSRF vulnerabilities
367 367
 if (! defined('NOTOKENRENEWAL'))
368 368
 {
369
-	// roulement des jetons car cree a chaque appel
370
-	if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
369
+    // roulement des jetons car cree a chaque appel
370
+    if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
371 371
 
372
-	// Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
373
-	$token = dol_hash(uniqid(mt_rand(), true)); // Generates a hash of a random number
374
-	$_SESSION['newtoken'] = $token;
372
+    // Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
373
+    $token = dol_hash(uniqid(mt_rand(), true)); // Generates a hash of a random number
374
+    $_SESSION['newtoken'] = $token;
375 375
 }
376 376
 if ((! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))
377
-	|| defined('CSRFCHECK_WITH_TOKEN'))	// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set
377
+    || defined('CSRFCHECK_WITH_TOKEN'))	// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set
378 378
 {
379
-	if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
380
-	{
381
-		print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
382
-		print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
383
-		die;
384
-	}
385
-	if ($_SERVER['REQUEST_METHOD'] === 'POST')  // This test must be after loading $_SESSION['token'].
386
-	{
387
-		if (GETPOST('token', 'alpha') != $_SESSION['token'])
388
-		{
389
-			dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
390
-			//print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
391
-			unset($_POST);
392
-		}
393
-	}
379
+    if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
380
+    {
381
+        print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
382
+        print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
383
+        die;
384
+    }
385
+    if ($_SERVER['REQUEST_METHOD'] === 'POST')  // This test must be after loading $_SESSION['token'].
386
+    {
387
+        if (GETPOST('token', 'alpha') != $_SESSION['token'])
388
+        {
389
+            dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
390
+            //print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
391
+            unset($_POST);
392
+        }
393
+    }
394 394
 }
395 395
 
396 396
 // Disable modules (this must be after session_start and after conf has been loaded)
397 397
 if (GETPOST('disablemodules','alpha'))  $_SESSION["disablemodules"]=GETPOST('disablemodules','alpha');
398 398
 if (! empty($_SESSION["disablemodules"]))
399 399
 {
400
-	$disabled_modules=explode(',',$_SESSION["disablemodules"]);
401
-	foreach($disabled_modules as $module)
402
-	{
403
-		if ($module)
404
-		{
405
-			if (empty($conf->$module)) $conf->$module=new stdClass();
406
-			$conf->$module->enabled=false;
407
-			if ($module == 'fournisseur')		// Special case
408
-			{
409
-				$conf->supplier_order->enabled=0;
410
-				$conf->supplier_invoice->enabled=0;
411
-			}
412
-		}
413
-	}
400
+    $disabled_modules=explode(',',$_SESSION["disablemodules"]);
401
+    foreach($disabled_modules as $module)
402
+    {
403
+        if ($module)
404
+        {
405
+            if (empty($conf->$module)) $conf->$module=new stdClass();
406
+            $conf->$module->enabled=false;
407
+            if ($module == 'fournisseur')		// Special case
408
+            {
409
+                $conf->supplier_order->enabled=0;
410
+                $conf->supplier_invoice->enabled=0;
411
+            }
412
+        }
413
+    }
414 414
 }
415 415
 
416 416
 /*
@@ -419,481 +419,481 @@  discard block
 block discarded – undo
419 419
 $login='';
420 420
 if (! defined('NOLOGIN'))
421 421
 {
422
-	// $authmode lists the different means of identification to be tested in order of preference.
423
-	// Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...'
422
+    // $authmode lists the different means of identification to be tested in order of preference.
423
+    // Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...'
424 424
 
425
-	if (defined('MAIN_AUTHENTICATION_MODE'))
426
-	{
427
-		$dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE');
428
-	}
429
-	else
430
-	{
431
-		// Authentication mode
432
-		if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
433
-		// Authentication mode: forceuser
434
-		if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
435
-	}
436
-	// Set authmode
437
-	$authmode=explode(',',$dolibarr_main_authentication);
438
-
439
-	// No authentication mode
440
-	if (! count($authmode))
441
-	{
442
-		$langs->load('main');
443
-		dol_print_error('',$langs->trans("ErrorConfigParameterNotDefined",'dolibarr_main_authentication'));
444
-		exit;
445
-	}
446
-
447
-	// If login request was already post, we retrieve login from the session
448
-	// Call module if not realized that his request.
449
-	// At the end of this phase, the variable $login is defined.
450
-	$resultFetchUser='';
451
-	$test=true;
452
-	if (! isset($_SESSION["dol_login"]))
453
-	{
454
-		// It is not already authenticated and it requests the login / password
455
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
456
-
457
-		$dol_dst_observed=GETPOST("dst_observed",'int',3);
458
-		$dol_dst_first=GETPOST("dst_first",'int',3);
459
-		$dol_dst_second=GETPOST("dst_second",'int',3);
460
-		$dol_screenwidth=GETPOST("screenwidth",'int',3);
461
-		$dol_screenheight=GETPOST("screenheight",'int',3);
462
-		$dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);
463
-		$dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);
464
-		$dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);
465
-		$dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);
466
-		$dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);
467
-		//dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
468
-
469
-		// If in demo mode, we check we go to home page through the public/demo/index.php page
470
-		if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
471
-		{
472
-			if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
473
-			{
474
-				dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
475
-				$url='';
476
-				$url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
477
-				$url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
478
-				$url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');
479
-				$url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');
480
-				$url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');
481
-				$url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');
482
-				header("Location: ".$url);
483
-				exit;
484
-			}
485
-		}
425
+    if (defined('MAIN_AUTHENTICATION_MODE'))
426
+    {
427
+        $dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE');
428
+    }
429
+    else
430
+    {
431
+        // Authentication mode
432
+        if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
433
+        // Authentication mode: forceuser
434
+        if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
435
+    }
436
+    // Set authmode
437
+    $authmode=explode(',',$dolibarr_main_authentication);
438
+
439
+    // No authentication mode
440
+    if (! count($authmode))
441
+    {
442
+        $langs->load('main');
443
+        dol_print_error('',$langs->trans("ErrorConfigParameterNotDefined",'dolibarr_main_authentication'));
444
+        exit;
445
+    }
486 446
 
487
-		// Verification security graphic code
488
-		if (GETPOST("username","alpha",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
489
-		{
490
-			$sessionkey = 'dol_antispam_value';
491
-			$ok=(array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
492
-
493
-			// Check code
494
-			if (! $ok)
495
-			{
496
-				dol_syslog('Bad value for code, connexion refused');
497
-				// Load translation files required by page
498
-				$langs->loadLangs(array('main', 'errors'));
499
-
500
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadValueForCode");
501
-				$test=false;
502
-
503
-				// Call trigger for the "security events" log
504
-				$user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST("username","alpha",2);
505
-				// Call of triggers
506
-				include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
507
-				$interface=new Interfaces($db);
508
-				$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
509
-				if ($result < 0) {
510
-					$error++;
511
-				}
512
-				// End Call of triggers
513
-
514
-				// Hooks on failed login
515
-				$action='';
516
-				$hookmanager->initHooks(array('login'));
517
-				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
518
-				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
519
-				if ($reshook < 0) $error++;
520
-
521
-				// Note: exit is done later
522
-			}
523
-		}
447
+    // If login request was already post, we retrieve login from the session
448
+    // Call module if not realized that his request.
449
+    // At the end of this phase, the variable $login is defined.
450
+    $resultFetchUser='';
451
+    $test=true;
452
+    if (! isset($_SESSION["dol_login"]))
453
+    {
454
+        // It is not already authenticated and it requests the login / password
455
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
456
+
457
+        $dol_dst_observed=GETPOST("dst_observed",'int',3);
458
+        $dol_dst_first=GETPOST("dst_first",'int',3);
459
+        $dol_dst_second=GETPOST("dst_second",'int',3);
460
+        $dol_screenwidth=GETPOST("screenwidth",'int',3);
461
+        $dol_screenheight=GETPOST("screenheight",'int',3);
462
+        $dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);
463
+        $dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);
464
+        $dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);
465
+        $dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);
466
+        $dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);
467
+        //dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
468
+
469
+        // If in demo mode, we check we go to home page through the public/demo/index.php page
470
+        if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
471
+        {
472
+            if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
473
+            {
474
+                dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
475
+                $url='';
476
+                $url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
477
+                $url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
478
+                $url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');
479
+                $url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');
480
+                $url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');
481
+                $url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');
482
+                header("Location: ".$url);
483
+                exit;
484
+            }
485
+        }
524 486
 
525
-		$allowedmethodtopostusername = 2;
526
-		if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD');
527
-		$usertotest		= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",$allowedmethodtopostusername));
528
-		$passwordtotest	= GETPOST('password','none',$allowedmethodtopostusername);
529
-		$entitytotest	= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
487
+        // Verification security graphic code
488
+        if (GETPOST("username","alpha",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
489
+        {
490
+            $sessionkey = 'dol_antispam_value';
491
+            $ok=(array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
530 492
 
531
-		// Define if we received data to test the login.
532
-		$goontestloop=false;
533
-		if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
534
-		if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
535
-		if (GETPOST("username","alpha",$allowedmethodtopostusername) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
493
+            // Check code
494
+            if (! $ok)
495
+            {
496
+                dol_syslog('Bad value for code, connexion refused');
497
+                // Load translation files required by page
498
+                $langs->loadLangs(array('main', 'errors'));
499
+
500
+                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadValueForCode");
501
+                $test=false;
502
+
503
+                // Call trigger for the "security events" log
504
+                $user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST("username","alpha",2);
505
+                // Call of triggers
506
+                include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
507
+                $interface=new Interfaces($db);
508
+                $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
509
+                if ($result < 0) {
510
+                    $error++;
511
+                }
512
+                // End Call of triggers
536 513
 
537
-		if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
538
-		{
539
-			include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
540
-			$langs=new Translate("",$conf);
541
-			$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
542
-			if (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');
543
-			$langs->setDefaultLang($langcode);
544
-		}
514
+                // Hooks on failed login
515
+                $action='';
516
+                $hookmanager->initHooks(array('login'));
517
+                $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
518
+                $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
519
+                if ($reshook < 0) $error++;
545 520
 
546
-		// Validation of login/pass/entity
547
-		// If ok, the variable login will be returned
548
-		// If error, we will put error message in session under the name dol_loginmesg
549
-		if ($test && $goontestloop)
550
-		{
551
-			$login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);
552
-			if ($login)
553
-			{
554
-				$dol_authmode=$conf->authmode;	// This properties is defined only when logged, to say what mode was successfully used
555
-				$dol_tz=$_POST["tz"];
556
-				$dol_tz_string=$_POST["tz_string"];
557
-				$dol_tz_string=preg_replace('/\s*\(.+\)$/','',$dol_tz_string);
558
-				$dol_tz_string=preg_replace('/,/','/',$dol_tz_string);
559
-				$dol_tz_string=preg_replace('/\s/','_',$dol_tz_string);
560
-				$dol_dst=0;
561
-				if (isset($_POST["dst_first"]) && isset($_POST["dst_second"]))
562
-				{
563
-					include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
564
-					$datenow=dol_now();
565
-					$datefirst=dol_stringtotime($_POST["dst_first"]);
566
-					$datesecond=dol_stringtotime($_POST["dst_second"]);
567
-					if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
568
-				}
569
-				//print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
570
-			}
571
-
572
-			if (! $login)
573
-			{
574
-				dol_syslog('Bad password, connexion refused',LOG_DEBUG);
575
-				// Load translation files required by page
576
-				$langs->loadLangs(array('main', 'errors'));
577
-
578
-				// Bad password. No authmode has found a good password.
579
-				// We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
580
-				if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
581
-
582
-				// Call trigger for the "security events" log
583
-				$user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
584
-				// Call of triggers
585
-				include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
586
-				$interface=new Interfaces($db);
587
-				$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST("username","alpha",2));
588
-				if ($result < 0) {
589
-					$error++;
590
-				}
591
-				// End Call of triggers
592
-
593
-				// Hooks on failed login
594
-				$action='';
595
-				$hookmanager->initHooks(array('login'));
596
-				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
597
-				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
598
-				if ($reshook < 0) $error++;
599
-
600
-				// Note: exit is done in next chapter
601
-			}
602
-		}
521
+                // Note: exit is done later
522
+            }
523
+        }
603 524
 
604
-		// End test login / passwords
605
-		if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
606
-		{
607
-			// No data to test login, so we show the login page
608
-			dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
609
-			if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
610
-			else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
611
-			exit;
612
-		}
525
+        $allowedmethodtopostusername = 2;
526
+        if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD');
527
+        $usertotest		= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",$allowedmethodtopostusername));
528
+        $passwordtotest	= GETPOST('password','none',$allowedmethodtopostusername);
529
+        $entitytotest	= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
613 530
 
614
-		$resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
615
-		if ($resultFetchUser <= 0)
616
-		{
617
-			dol_syslog('User not found, connexion refused');
618
-			session_destroy();
619
-			session_name($sessionname);
620
-			session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
621
-			session_start();    // Fixing the bug of register_globals here is useless since session is empty
622
-
623
-			if ($resultFetchUser == 0)
624
-			{
625
-				// Load translation files required by page
626
-				$langs->loadLangs(array('main', 'errors'));
627
-
628
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
629
-
630
-				$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
631
-			}
632
-			if ($resultFetchUser < 0)
633
-			{
634
-				$_SESSION["dol_loginmesg"]=$user->error;
635
-
636
-				$user->trigger_mesg=$user->error;
637
-			}
638
-
639
-			// Call triggers for the "security events" log
640
-			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
641
-			$interface=new Interfaces($db);
642
-			$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
643
-			if ($result < 0) {
644
-				$error++;
645
-			}
646
-			// End call triggers
647
-
648
-			// Hooks on failed login
649
-			$action='';
650
-			$hookmanager->initHooks(array('login'));
651
-			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
652
-			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
653
-			if ($reshook < 0) $error++;
654
-
655
-			$paramsurl=array();
656
-			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
657
-			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
658
-			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
659
-			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
660
-			exit;
661
-		}
662
-	}
663
-	else
664
-	{
665
-		// We are already into an authenticated session
666
-		$login=$_SESSION["dol_login"];
667
-		$entity=$_SESSION["dol_entity"];
668
-		dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
531
+        // Define if we received data to test the login.
532
+        $goontestloop=false;
533
+        if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
534
+        if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
535
+        if (GETPOST("username","alpha",$allowedmethodtopostusername) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
669 536
 
670
-		$resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
671
-		if ($resultFetchUser <= 0)
672
-		{
673
-			// Account has been removed after login
674
-			dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
675
-			session_destroy();
676
-			session_name($sessionname);
677
-			session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
678
-			session_start();    // Fixing the bug of register_globals here is useless since session is empty
679
-
680
-			if ($resultFetchUser == 0)
681
-			{
682
-				// Load translation files required by page
683
-				$langs->loadLangs(array('main', 'errors'));
684
-
685
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
686
-
687
-				$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
688
-			}
689
-			if ($resultFetchUser < 0)
690
-			{
691
-				$_SESSION["dol_loginmesg"]=$user->error;
692
-
693
-				$user->trigger_mesg=$user->error;
694
-			}
695
-
696
-			// Call triggers for the "security events" log
697
-			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
698
-			$interface=new Interfaces($db);
699
-			$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
700
-			if ($result < 0) {
701
-				$error++;
702
-			}
703
-			// End call triggers
704
-
705
-			// Hooks on failed login
706
-			$action='';
707
-			$hookmanager->initHooks(array('login'));
708
-			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
709
-			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
710
-			if ($reshook < 0) $error++;
711
-
712
-			$paramsurl=array();
713
-			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
714
-			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
715
-			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
716
-			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
717
-			exit;
718
-		}
719
-		else
720
-		{
721
-		    // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
722
-		    $hookmanager->initHooks(array('main'));
723
-
724
-		    // Code for search criteria persistence.
725
-		    if (! empty($_GET['save_lastsearch_values']))    // We must use $_GET here
726
-		    {
727
-			    $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
728
-			    $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
729
-			    // Clean $relativepathstring
730
-   			    if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
731
-			    $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
732
-			    $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
733
-			    //var_dump($relativepathstring);
734
-
735
-			    // We click on a link that leave a page we have to save search criteria, contextpage, limit and page. We save them from tmp to no tmp
736
-			    if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
737
-			    {
738
-			    	$_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];
739
-				    unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
740
-			    }
741
-			    if (! empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]))
742
-			    {
743
-			    	$_SESSION['lastsearch_contextpage_'.$relativepathstring]=$_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
744
-			    	unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
745
-			    }
746
-			    if (! empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 1)
747
-			    {
748
-			    	$_SESSION['lastsearch_page_'.$relativepathstring]=$_SESSION['lastsearch_page_tmp_'.$relativepathstring];
749
-			    	unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
750
-			    }
751
-			    if (! empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit)
752
-			    {
753
-			    	$_SESSION['lastsearch_limit_'.$relativepathstring]=$_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
754
-			    	unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
755
-			    }
756
-		    }
757
-
758
-		    $action = '';
759
-		    $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action);
760
-		    if ($reshook < 0) {
761
-			    setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
762
-		    }
763
-		}
764
-	}
537
+        if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
538
+        {
539
+            include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
540
+            $langs=new Translate("",$conf);
541
+            $langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
542
+            if (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');
543
+            $langs->setDefaultLang($langcode);
544
+        }
765 545
 
766
-	// Is it a new session that has started ?
767
-	// If we are here, this means authentication was successfull.
768
-	if (! isset($_SESSION["dol_login"]))
769
-	{
770
-		// New session for this login has started.
771
-		$error=0;
772
-
773
-		// Store value into session (values always stored)
774
-		$_SESSION["dol_login"]=$user->login;
775
-		$_SESSION["dol_authmode"]=isset($dol_authmode)?$dol_authmode:'';
776
-		$_SESSION["dol_tz"]=isset($dol_tz)?$dol_tz:'';
777
-		$_SESSION["dol_tz_string"]=isset($dol_tz_string)?$dol_tz_string:'';
778
-		$_SESSION["dol_dst"]=isset($dol_dst)?$dol_dst:'';
779
-		$_SESSION["dol_dst_observed"]=isset($dol_dst_observed)?$dol_dst_observed:'';
780
-		$_SESSION["dol_dst_first"]=isset($dol_dst_first)?$dol_dst_first:'';
781
-		$_SESSION["dol_dst_second"]=isset($dol_dst_second)?$dol_dst_second:'';
782
-		$_SESSION["dol_screenwidth"]=isset($dol_screenwidth)?$dol_screenwidth:'';
783
-		$_SESSION["dol_screenheight"]=isset($dol_screenheight)?$dol_screenheight:'';
784
-		$_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
785
-		$_SESSION["dol_entity"]=$conf->entity;
786
-		// Store value into session (values stored only if defined)
787
-		if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
788
-		if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
789
-		if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
790
-		if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
791
-		if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
792
-
793
-		dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
794
-
795
-		$db->begin();
796
-
797
-		$user->update_last_login_date();
798
-
799
-		$loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
800
-
801
-		// Call triggers for the "security events" log
802
-		$user->trigger_mesg = $loginfo;
803
-		// Call triggers
804
-		include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
805
-		$interface=new Interfaces($db);
806
-		$result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);
807
-		if ($result < 0) {
808
-			$error++;
809
-		}
810
-		// End call triggers
546
+        // Validation of login/pass/entity
547
+        // If ok, the variable login will be returned
548
+        // If error, we will put error message in session under the name dol_loginmesg
549
+        if ($test && $goontestloop)
550
+        {
551
+            $login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);
552
+            if ($login)
553
+            {
554
+                $dol_authmode=$conf->authmode;	// This properties is defined only when logged, to say what mode was successfully used
555
+                $dol_tz=$_POST["tz"];
556
+                $dol_tz_string=$_POST["tz_string"];
557
+                $dol_tz_string=preg_replace('/\s*\(.+\)$/','',$dol_tz_string);
558
+                $dol_tz_string=preg_replace('/,/','/',$dol_tz_string);
559
+                $dol_tz_string=preg_replace('/\s/','_',$dol_tz_string);
560
+                $dol_dst=0;
561
+                if (isset($_POST["dst_first"]) && isset($_POST["dst_second"]))
562
+                {
563
+                    include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
564
+                    $datenow=dol_now();
565
+                    $datefirst=dol_stringtotime($_POST["dst_first"]);
566
+                    $datesecond=dol_stringtotime($_POST["dst_second"]);
567
+                    if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
568
+                }
569
+                //print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
570
+            }
811 571
 
812
-		// Hooks on successfull login
813
-		$action='';
814
-		$hookmanager->initHooks(array('login'));
815
-		$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
816
-		$reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
817
-		if ($reshook < 0) $error++;
572
+            if (! $login)
573
+            {
574
+                dol_syslog('Bad password, connexion refused',LOG_DEBUG);
575
+                // Load translation files required by page
576
+                $langs->loadLangs(array('main', 'errors'));
577
+
578
+                // Bad password. No authmode has found a good password.
579
+                // We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
580
+                if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
581
+
582
+                // Call trigger for the "security events" log
583
+                $user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
584
+                // Call of triggers
585
+                include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
586
+                $interface=new Interfaces($db);
587
+                $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST("username","alpha",2));
588
+                if ($result < 0) {
589
+                    $error++;
590
+                }
591
+                // End Call of triggers
818 592
 
819
-		if ($error)
820
-		{
821
-			$db->rollback();
822
-			session_destroy();
823
-			dol_print_error($db,'Error in some triggers USER_LOGIN or in some hooks afterLogin');
824
-			exit;
825
-		}
826
-		else
827
-		{
828
-			$db->commit();
829
-		}
593
+                // Hooks on failed login
594
+                $action='';
595
+                $hookmanager->initHooks(array('login'));
596
+                $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
597
+                $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
598
+                if ($reshook < 0) $error++;
830 599
 
831
-		// Change landing page if defined.
832
-		$landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
833
-		if (! empty($landingpage))    // Example: /index.php
834
-		{
835
-			$newpath=dol_buildpath($landingpage, 1);
836
-			if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
837
-			{
838
-				header('Location: '.$newpath);
839
-				exit;
840
-			}
841
-		}
842
-	}
600
+                // Note: exit is done in next chapter
601
+            }
602
+        }
603
+
604
+        // End test login / passwords
605
+        if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
606
+        {
607
+            // No data to test login, so we show the login page
608
+            dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
609
+            if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
610
+            else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
611
+            exit;
612
+        }
843 613
 
614
+        $resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
615
+        if ($resultFetchUser <= 0)
616
+        {
617
+            dol_syslog('User not found, connexion refused');
618
+            session_destroy();
619
+            session_name($sessionname);
620
+            session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
621
+            session_start();    // Fixing the bug of register_globals here is useless since session is empty
844 622
 
845
-	// If user admin, we force the rights-based modules
846
-	if ($user->admin)
847
-	{
848
-		$user->rights->user->user->lire=1;
849
-		$user->rights->user->user->creer=1;
850
-		$user->rights->user->user->password=1;
851
-		$user->rights->user->user->supprimer=1;
852
-		$user->rights->user->self->creer=1;
853
-		$user->rights->user->self->password=1;
854
-	}
855
-
856
-	/*
623
+            if ($resultFetchUser == 0)
624
+            {
625
+                // Load translation files required by page
626
+                $langs->loadLangs(array('main', 'errors'));
627
+
628
+                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
629
+
630
+                $user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
631
+            }
632
+            if ($resultFetchUser < 0)
633
+            {
634
+                $_SESSION["dol_loginmesg"]=$user->error;
635
+
636
+                $user->trigger_mesg=$user->error;
637
+            }
638
+
639
+            // Call triggers for the "security events" log
640
+            include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
641
+            $interface=new Interfaces($db);
642
+            $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
643
+            if ($result < 0) {
644
+                $error++;
645
+            }
646
+            // End call triggers
647
+
648
+            // Hooks on failed login
649
+            $action='';
650
+            $hookmanager->initHooks(array('login'));
651
+            $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
652
+            $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
653
+            if ($reshook < 0) $error++;
654
+
655
+            $paramsurl=array();
656
+            if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
657
+            if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
658
+            if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
659
+            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
660
+            exit;
661
+        }
662
+    }
663
+    else
664
+    {
665
+        // We are already into an authenticated session
666
+        $login=$_SESSION["dol_login"];
667
+        $entity=$_SESSION["dol_entity"];
668
+        dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
669
+
670
+        $resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
671
+        if ($resultFetchUser <= 0)
672
+        {
673
+            // Account has been removed after login
674
+            dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
675
+            session_destroy();
676
+            session_name($sessionname);
677
+            session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
678
+            session_start();    // Fixing the bug of register_globals here is useless since session is empty
679
+
680
+            if ($resultFetchUser == 0)
681
+            {
682
+                // Load translation files required by page
683
+                $langs->loadLangs(array('main', 'errors'));
684
+
685
+                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
686
+
687
+                $user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
688
+            }
689
+            if ($resultFetchUser < 0)
690
+            {
691
+                $_SESSION["dol_loginmesg"]=$user->error;
692
+
693
+                $user->trigger_mesg=$user->error;
694
+            }
695
+
696
+            // Call triggers for the "security events" log
697
+            include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
698
+            $interface=new Interfaces($db);
699
+            $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
700
+            if ($result < 0) {
701
+                $error++;
702
+            }
703
+            // End call triggers
704
+
705
+            // Hooks on failed login
706
+            $action='';
707
+            $hookmanager->initHooks(array('login'));
708
+            $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
709
+            $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
710
+            if ($reshook < 0) $error++;
711
+
712
+            $paramsurl=array();
713
+            if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
714
+            if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
715
+            if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
716
+            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
717
+            exit;
718
+        }
719
+        else
720
+        {
721
+            // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
722
+            $hookmanager->initHooks(array('main'));
723
+
724
+            // Code for search criteria persistence.
725
+            if (! empty($_GET['save_lastsearch_values']))    // We must use $_GET here
726
+            {
727
+                $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
728
+                $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
729
+                // Clean $relativepathstring
730
+                    if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
731
+                $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
732
+                $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
733
+                //var_dump($relativepathstring);
734
+
735
+                // We click on a link that leave a page we have to save search criteria, contextpage, limit and page. We save them from tmp to no tmp
736
+                if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
737
+                {
738
+                    $_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];
739
+                    unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
740
+                }
741
+                if (! empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]))
742
+                {
743
+                    $_SESSION['lastsearch_contextpage_'.$relativepathstring]=$_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
744
+                    unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
745
+                }
746
+                if (! empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 1)
747
+                {
748
+                    $_SESSION['lastsearch_page_'.$relativepathstring]=$_SESSION['lastsearch_page_tmp_'.$relativepathstring];
749
+                    unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
750
+                }
751
+                if (! empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit)
752
+                {
753
+                    $_SESSION['lastsearch_limit_'.$relativepathstring]=$_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
754
+                    unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
755
+                }
756
+            }
757
+
758
+            $action = '';
759
+            $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action);
760
+            if ($reshook < 0) {
761
+                setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
762
+            }
763
+        }
764
+    }
765
+
766
+    // Is it a new session that has started ?
767
+    // If we are here, this means authentication was successfull.
768
+    if (! isset($_SESSION["dol_login"]))
769
+    {
770
+        // New session for this login has started.
771
+        $error=0;
772
+
773
+        // Store value into session (values always stored)
774
+        $_SESSION["dol_login"]=$user->login;
775
+        $_SESSION["dol_authmode"]=isset($dol_authmode)?$dol_authmode:'';
776
+        $_SESSION["dol_tz"]=isset($dol_tz)?$dol_tz:'';
777
+        $_SESSION["dol_tz_string"]=isset($dol_tz_string)?$dol_tz_string:'';
778
+        $_SESSION["dol_dst"]=isset($dol_dst)?$dol_dst:'';
779
+        $_SESSION["dol_dst_observed"]=isset($dol_dst_observed)?$dol_dst_observed:'';
780
+        $_SESSION["dol_dst_first"]=isset($dol_dst_first)?$dol_dst_first:'';
781
+        $_SESSION["dol_dst_second"]=isset($dol_dst_second)?$dol_dst_second:'';
782
+        $_SESSION["dol_screenwidth"]=isset($dol_screenwidth)?$dol_screenwidth:'';
783
+        $_SESSION["dol_screenheight"]=isset($dol_screenheight)?$dol_screenheight:'';
784
+        $_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
785
+        $_SESSION["dol_entity"]=$conf->entity;
786
+        // Store value into session (values stored only if defined)
787
+        if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
788
+        if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
789
+        if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
790
+        if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
791
+        if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
792
+
793
+        dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
794
+
795
+        $db->begin();
796
+
797
+        $user->update_last_login_date();
798
+
799
+        $loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
800
+
801
+        // Call triggers for the "security events" log
802
+        $user->trigger_mesg = $loginfo;
803
+        // Call triggers
804
+        include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
805
+        $interface=new Interfaces($db);
806
+        $result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);
807
+        if ($result < 0) {
808
+            $error++;
809
+        }
810
+        // End call triggers
811
+
812
+        // Hooks on successfull login
813
+        $action='';
814
+        $hookmanager->initHooks(array('login'));
815
+        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
816
+        $reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
817
+        if ($reshook < 0) $error++;
818
+
819
+        if ($error)
820
+        {
821
+            $db->rollback();
822
+            session_destroy();
823
+            dol_print_error($db,'Error in some triggers USER_LOGIN or in some hooks afterLogin');
824
+            exit;
825
+        }
826
+        else
827
+        {
828
+            $db->commit();
829
+        }
830
+
831
+        // Change landing page if defined.
832
+        $landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
833
+        if (! empty($landingpage))    // Example: /index.php
834
+        {
835
+            $newpath=dol_buildpath($landingpage, 1);
836
+            if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
837
+            {
838
+                header('Location: '.$newpath);
839
+                exit;
840
+            }
841
+        }
842
+    }
843
+
844
+
845
+    // If user admin, we force the rights-based modules
846
+    if ($user->admin)
847
+    {
848
+        $user->rights->user->user->lire=1;
849
+        $user->rights->user->user->creer=1;
850
+        $user->rights->user->user->password=1;
851
+        $user->rights->user->user->supprimer=1;
852
+        $user->rights->user->self->creer=1;
853
+        $user->rights->user->self->password=1;
854
+    }
855
+
856
+    /*
857 857
      * Overwrite some configs globals (try to avoid this and have code to use instead $user->conf->xxx)
858 858
      */
859 859
 
860
-	// Set liste_limit
861
-	if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
862
-	if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
860
+    // Set liste_limit
861
+    if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
862
+    if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
863 863
 
864
-	// Replace conf->css by personalized value if theme not forced
865
-	if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
866
-	{
867
-		$conf->theme=$user->conf->MAIN_THEME;
868
-		$conf->css  = "/theme/".$conf->theme."/style.css.php";
869
-	}
864
+    // Replace conf->css by personalized value if theme not forced
865
+    if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
866
+    {
867
+        $conf->theme=$user->conf->MAIN_THEME;
868
+        $conf->css  = "/theme/".$conf->theme."/style.css.php";
869
+    }
870 870
 }
871 871
 
872 872
 // Case forcing style from url
873 873
 if (GETPOST('theme','alpha'))
874 874
 {
875
-	$conf->theme=GETPOST('theme','alpha',1);
876
-	$conf->css  = "/theme/".$conf->theme."/style.css.php";
875
+    $conf->theme=GETPOST('theme','alpha',1);
876
+    $conf->css  = "/theme/".$conf->theme."/style.css.php";
877 877
 }
878 878
 
879 879
 
880 880
 // Set javascript option
881 881
 if (! GETPOST('nojs','int'))   // If javascript was not disabled on URL
882 882
 {
883
-	if (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
884
-	{
885
-		$conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;
886
-	}
883
+    if (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
884
+    {
885
+        $conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;
886
+    }
887 887
 }
888 888
 else $conf->use_javascript_ajax=0;
889 889
 // Set MAIN_OPTIMIZEFORTEXTBROWSER
890 890
 if (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))   // If we must enable text browser
891 891
 {
892
-	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
892
+    $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
893 893
 }
894 894
 elseif (! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))
895 895
 {
896
-	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=$user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;
896
+    $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=$user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;
897 897
 }
898 898
 
899 899
 // Set terminal output option according to conf->browser.
@@ -904,56 +904,56 @@  discard block
 block discarded – undo
904 904
 if (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile']))                   $conf->dol_use_jmobile=1;
905 905
 if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover=1;
906 906
 if ((! empty($conf->browser->layout) && $conf->browser->layout == 'phone')
907
-	|| (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
908
-	|| (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
907
+    || (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
908
+    || (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
909 909
 )
910 910
 {
911
-	$conf->dol_optimize_smallscreen=1;
911
+    $conf->dol_optimize_smallscreen=1;
912 912
 }
913 913
 // If we force to use jmobile, then we reenable javascript
914 914
 if (! empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax=1;
915 915
 // Replace themes bugged with jmobile with eldy
916 916
 if (! empty($conf->dol_use_jmobile) && in_array($conf->theme,array('bureau2crea','cameleo','amarok')))
917 917
 {
918
-	$conf->theme='eldy';
919
-	$conf->css  =  "/theme/".$conf->theme."/style.css.php";
918
+    $conf->theme='eldy';
919
+    $conf->css  =  "/theme/".$conf->theme."/style.css.php";
920 920
 }
921 921
 
922 922
 if (! defined('NOREQUIRETRAN'))
923 923
 {
924
-	if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
925
-	{
926
-		// If user has chosen its own language
927
-		if (! empty($user->conf->MAIN_LANG_DEFAULT))
928
-		{
929
-			// If different than current language
930
-			//print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
931
-			if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)
932
-			{
933
-				$langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
934
-			}
935
-		}
936
-	}
924
+    if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
925
+    {
926
+        // If user has chosen its own language
927
+        if (! empty($user->conf->MAIN_LANG_DEFAULT))
928
+        {
929
+            // If different than current language
930
+            //print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
931
+            if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)
932
+            {
933
+                $langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
934
+            }
935
+        }
936
+    }
937 937
 }
938 938
 
939 939
 if (! defined('NOLOGIN'))
940 940
 {
941
-	// If the login is not recovered, it is identified with an account that does not exist.
942
-	// Hacking attempt?
943
-	if (! $user->login) accessforbidden();
941
+    // If the login is not recovered, it is identified with an account that does not exist.
942
+    // Hacking attempt?
943
+    if (! $user->login) accessforbidden();
944
+
945
+    // Check if user is active
946
+    if ($user->statut < 1)
947
+    {
948
+        // If not active, we refuse the user
949
+        $langs->load("other");
950
+        dol_syslog("Authentification ko as login is disabled");
951
+        accessforbidden($langs->trans("ErrorLoginDisabled"));
952
+        exit;
953
+    }
944 954
 
945
-	// Check if user is active
946
-	if ($user->statut < 1)
947
-	{
948
-		// If not active, we refuse the user
949
-		$langs->load("other");
950
-		dol_syslog("Authentification ko as login is disabled");
951
-		accessforbidden($langs->trans("ErrorLoginDisabled"));
952
-		exit;
953
-	}
954
-
955
-	// Load permissions
956
-	$user->getrights();
955
+    // Load permissions
956
+    $user->getrights();
957 957
 }
958 958
 
959 959
 
@@ -964,8 +964,8 @@  discard block
 block discarded – undo
964 964
 // Load main languages files
965 965
 if (! defined('NOREQUIRETRAN'))
966 966
 {
967
-	// Load translation files required by page
968
-	$langs->loadLangs(array('main', 'dict'));
967
+    // Load translation files required by page
968
+    $langs->loadLangs(array('main', 'dict'));
969 969
 }
970 970
 
971 971
 // Define some constants used for style of arrays
@@ -982,27 +982,27 @@  discard block
 block discarded – undo
982 982
 // Constants used to defined number of lines in textarea
983 983
 if (empty($conf->browser->firefox))
984 984
 {
985
-	define('ROWS_1',1);
986
-	define('ROWS_2',2);
987
-	define('ROWS_3',3);
988
-	define('ROWS_4',4);
989
-	define('ROWS_5',5);
990
-	define('ROWS_6',6);
991
-	define('ROWS_7',7);
992
-	define('ROWS_8',8);
993
-	define('ROWS_9',9);
985
+    define('ROWS_1',1);
986
+    define('ROWS_2',2);
987
+    define('ROWS_3',3);
988
+    define('ROWS_4',4);
989
+    define('ROWS_5',5);
990
+    define('ROWS_6',6);
991
+    define('ROWS_7',7);
992
+    define('ROWS_8',8);
993
+    define('ROWS_9',9);
994 994
 }
995 995
 else
996 996
 {
997
-	define('ROWS_1',0);
998
-	define('ROWS_2',1);
999
-	define('ROWS_3',2);
1000
-	define('ROWS_4',3);
1001
-	define('ROWS_5',4);
1002
-	define('ROWS_6',5);
1003
-	define('ROWS_7',6);
1004
-	define('ROWS_8',7);
1005
-	define('ROWS_9',8);
997
+    define('ROWS_1',0);
998
+    define('ROWS_2',1);
999
+    define('ROWS_3',2);
1000
+    define('ROWS_4',3);
1001
+    define('ROWS_5',4);
1002
+    define('ROWS_6',5);
1003
+    define('ROWS_7',6);
1004
+    define('ROWS_8',7);
1005
+    define('ROWS_9',8);
1006 1006
 }
1007 1007
 
1008 1008
 $heightforframes=50;
@@ -1010,36 +1010,36 @@  discard block
 block discarded – undo
1010 1010
 // Init menu manager
1011 1011
 if (! defined('NOREQUIREMENU'))
1012 1012
 {
1013
-	if (empty($user->societe_id))    // If internal user or not defined
1014
-	{
1015
-		$conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);
1016
-	}
1017
-	else                        // If external user
1018
-	{
1019
-		$conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
1020
-	}
1013
+    if (empty($user->societe_id))    // If internal user or not defined
1014
+    {
1015
+        $conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);
1016
+    }
1017
+    else                        // If external user
1018
+    {
1019
+        $conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
1020
+    }
1021 1021
 
1022
-	// Load the menu manager (only if not already done)
1023
-	$file_menu=$conf->standard_menu;
1024
-	if (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha');     // example: menu=eldy_menu.php
1025
-	if (! class_exists('MenuManager'))
1026
-	{
1027
-		$menufound=0;
1028
-		$dirmenus=array_merge(array("/core/menus/"),(array) $conf->modules_parts['menus']);
1029
-		foreach($dirmenus as $dirmenu)
1030
-		{
1031
-			$menufound=dol_include_once($dirmenu."standard/".$file_menu);
1032
-			if (class_exists('MenuManager')) break;
1033
-		}
1034
-		if (! class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
1035
-		{
1036
-			dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
1037
-			$file_menu='eldy_menu.php';
1038
-			include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
1039
-		}
1040
-	}
1041
-	$menumanager = new MenuManager($db, empty($user->societe_id)?0:1);
1042
-	$menumanager->loadMenu();
1022
+    // Load the menu manager (only if not already done)
1023
+    $file_menu=$conf->standard_menu;
1024
+    if (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha');     // example: menu=eldy_menu.php
1025
+    if (! class_exists('MenuManager'))
1026
+    {
1027
+        $menufound=0;
1028
+        $dirmenus=array_merge(array("/core/menus/"),(array) $conf->modules_parts['menus']);
1029
+        foreach($dirmenus as $dirmenu)
1030
+        {
1031
+            $menufound=dol_include_once($dirmenu."standard/".$file_menu);
1032
+            if (class_exists('MenuManager')) break;
1033
+        }
1034
+        if (! class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
1035
+        {
1036
+            dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
1037
+            $file_menu='eldy_menu.php';
1038
+            include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
1039
+        }
1040
+    }
1041
+    $menumanager = new MenuManager($db, empty($user->societe_id)?0:1);
1042
+    $menumanager->loadMenu();
1043 1043
 }
1044 1044
 
1045 1045
 
@@ -1048,52 +1048,52 @@  discard block
 block discarded – undo
1048 1048
 
1049 1049
 if (! function_exists("llxHeader"))
1050 1050
 {
1051
-	/**
1052
-	 *	Show HTML header HTML + BODY + Top menu + left menu + DIV
1053
-	 *
1054
-	 * @param 	string 	$head				Optionnal head lines
1055
-	 * @param 	string 	$title				HTML title
1056
-	 * @param	string	$help_url			Url links to help page
1057
-	 * 		                            	Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage
1058
-	 *                                  	For other external page: http://server/url
1059
-	 * @param	string	$target				Target to use on links
1060
-	 * @param 	int    	$disablejs			More content into html header
1061
-	 * @param 	int    	$disablehead		More content into html header
1062
-	 * @param 	array  	$arrayofjs			Array of complementary js files
1063
-	 * @param 	array  	$arrayofcss			Array of complementary css files
1064
-	 * @param	string	$morequerystring	Query string to add to the link "print" to get same parameters (use only if autodetect fails)
1065
-	 * @param   string  $morecssonbody      More CSS on body tag.
1066
-	 * @param	string	$replacemainareaby	Replace call to main_area() by a print of this string
1067
-	 * @return	void
1068
-	 */
1069
-	function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='')
1070
-	{
1071
-		global $conf;
1051
+    /**
1052
+     *	Show HTML header HTML + BODY + Top menu + left menu + DIV
1053
+     *
1054
+     * @param 	string 	$head				Optionnal head lines
1055
+     * @param 	string 	$title				HTML title
1056
+     * @param	string	$help_url			Url links to help page
1057
+     * 		                            	Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage
1058
+     *                                  	For other external page: http://server/url
1059
+     * @param	string	$target				Target to use on links
1060
+     * @param 	int    	$disablejs			More content into html header
1061
+     * @param 	int    	$disablehead		More content into html header
1062
+     * @param 	array  	$arrayofjs			Array of complementary js files
1063
+     * @param 	array  	$arrayofcss			Array of complementary css files
1064
+     * @param	string	$morequerystring	Query string to add to the link "print" to get same parameters (use only if autodetect fails)
1065
+     * @param   string  $morecssonbody      More CSS on body tag.
1066
+     * @param	string	$replacemainareaby	Replace call to main_area() by a print of this string
1067
+     * @return	void
1068
+     */
1069
+    function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='')
1070
+    {
1071
+        global $conf;
1072 1072
 
1073
-		// html header
1074
-		top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1073
+        // html header
1074
+        top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1075 1075
 
1076
-		print '<body id="mainbody"'.($morecssonbody?' class="'.$morecssonbody.'"':'').'>' . "\n";
1076
+        print '<body id="mainbody"'.($morecssonbody?' class="'.$morecssonbody.'"':'').'>' . "\n";
1077 1077
 
1078
-		// top menu and left menu area
1079
-		if (empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int'))
1080
-		{
1081
-			top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);
1082
-		}
1078
+        // top menu and left menu area
1079
+        if (empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int'))
1080
+        {
1081
+            top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);
1082
+        }
1083 1083
 
1084
-		if (empty($conf->dol_hide_leftmenu))
1085
-		{
1086
-			left_menu('', $help_url, '', '', 1, $title, 1);		// $menumanager is retreived with a global $menumanager inside this function
1087
-		}
1084
+        if (empty($conf->dol_hide_leftmenu))
1085
+        {
1086
+            left_menu('', $help_url, '', '', 1, $title, 1);		// $menumanager is retreived with a global $menumanager inside this function
1087
+        }
1088 1088
 
1089
-		// main area
1090
-		if ($replacemainareaby)
1091
-		{
1092
-			print $replacemainareaby;
1093
-			return;
1094
-		}
1095
-		main_area($title);
1096
-	}
1089
+        // main area
1090
+        if ($replacemainareaby)
1091
+        {
1092
+            print $replacemainareaby;
1093
+            return;
1094
+        }
1095
+        main_area($title);
1096
+    }
1097 1097
 }
1098 1098
 
1099 1099
 
@@ -1106,53 +1106,53 @@  discard block
 block discarded – undo
1106 1106
  */
1107 1107
 function top_httphead($contenttype='text/html', $forcenocache=0)
1108 1108
 {
1109
-	global $db, $conf, $hookmanager;
1110
-
1111
-	if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1112
-	else header("Content-Type: ".$contenttype);
1113
-	// Security options
1114
-	header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1115
-	header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
1116
-	//header("X-XSS-Protection: 1");      		// XSS protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated.
1117
-	if (! defined('FORCECSP'))
1118
-	{
1119
-		//if (! isset($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1120
-		//{
1121
-		//	// A default security policy that keep usage of js external component like ckeditor, stripe, google, working
1122
-		//	$contentsecuritypolicy = "font-src *; img-src *; style-src * 'unsafe-inline' 'unsafe-eval'; default-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; script-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; frame-src 'self' *.stripe.com; connect-src 'self';";
1123
-		//}
1124
-		//else $contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1125
-		$contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1126
-
1127
-		if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1128
-		$hookmanager->initHooks("main");
1129
-
1130
-		$parameters=array('contentsecuritypolicy'=>$contentsecuritypolicy);
1131
-		$result=$hookmanager->executeHooks('setContentSecurityPolicy',$parameters);    // Note that $action and $object may have been modified by some hooks
1132
-		if ($result > 0) $contentsecuritypolicy = $hookmanager->resPrint;	// Replace CSP
1133
-		else $contentsecuritypolicy .= $hookmanager->resPrint;				// Concat CSP
1134
-
1135
-		if (! empty($contentsecuritypolicy))
1136
-		{
1137
-			// For example, to restrict 'script', 'object', 'frames' or 'img' to some domains:
1138
-			// script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; frame-src https://youtube.com; img-src: https://static.example.com
1139
-			// For example, to restrict everything to one domain, except 'object', ...:
1140
-			// default-src https://cdn.example.net; object-src 'none'
1141
-			// For example, to restrict everything to itself except img that can be on other servers:
1142
-			// default-src 'self'; img-src *;
1143
-			// Pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over https and disable plugins:
1144
-			// default-src http: https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'
1145
-			header("Content-Security-Policy: ".$contentsecuritypolicy);
1146
-		}
1147
-	}
1148
-	elseif (constant('FORCECSP'))
1149
-	{
1150
-		header("Content-Security-Policy: ".constant('FORCECSP'));
1151
-	}
1152
-	if ($forcenocache)
1153
-	{
1154
-		header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0");
1155
-	}
1109
+    global $db, $conf, $hookmanager;
1110
+
1111
+    if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1112
+    else header("Content-Type: ".$contenttype);
1113
+    // Security options
1114
+    header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1115
+    header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
1116
+    //header("X-XSS-Protection: 1");      		// XSS protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated.
1117
+    if (! defined('FORCECSP'))
1118
+    {
1119
+        //if (! isset($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1120
+        //{
1121
+        //	// A default security policy that keep usage of js external component like ckeditor, stripe, google, working
1122
+        //	$contentsecuritypolicy = "font-src *; img-src *; style-src * 'unsafe-inline' 'unsafe-eval'; default-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; script-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; frame-src 'self' *.stripe.com; connect-src 'self';";
1123
+        //}
1124
+        //else $contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1125
+        $contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1126
+
1127
+        if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1128
+        $hookmanager->initHooks("main");
1129
+
1130
+        $parameters=array('contentsecuritypolicy'=>$contentsecuritypolicy);
1131
+        $result=$hookmanager->executeHooks('setContentSecurityPolicy',$parameters);    // Note that $action and $object may have been modified by some hooks
1132
+        if ($result > 0) $contentsecuritypolicy = $hookmanager->resPrint;	// Replace CSP
1133
+        else $contentsecuritypolicy .= $hookmanager->resPrint;				// Concat CSP
1134
+
1135
+        if (! empty($contentsecuritypolicy))
1136
+        {
1137
+            // For example, to restrict 'script', 'object', 'frames' or 'img' to some domains:
1138
+            // script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; frame-src https://youtube.com; img-src: https://static.example.com
1139
+            // For example, to restrict everything to one domain, except 'object', ...:
1140
+            // default-src https://cdn.example.net; object-src 'none'
1141
+            // For example, to restrict everything to itself except img that can be on other servers:
1142
+            // default-src 'self'; img-src *;
1143
+            // Pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over https and disable plugins:
1144
+            // default-src http: https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'
1145
+            header("Content-Security-Policy: ".$contentsecuritypolicy);
1146
+        }
1147
+    }
1148
+    elseif (constant('FORCECSP'))
1149
+    {
1150
+        header("Content-Security-Policy: ".constant('FORCECSP'));
1151
+    }
1152
+    if ($forcenocache)
1153
+    {
1154
+        header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0");
1155
+    }
1156 1156
 }
1157 1157
 
1158 1158
 /**
@@ -1171,220 +1171,220 @@  discard block
 block discarded – undo
1171 1171
  */
1172 1172
 function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $disablejmobile=0, $disablenofollow=0)
1173 1173
 {
1174
-	global $db, $conf, $langs, $user, $hookmanager;
1174
+    global $db, $conf, $langs, $user, $hookmanager;
1175 1175
 
1176
-	top_httphead();
1176
+    top_httphead();
1177 1177
 
1178
-	if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1178
+    if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1179 1179
 
1180
-	print '<!doctype html>'."\n";
1180
+    print '<!doctype html>'."\n";
1181 1181
 
1182
-	if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1183
-	else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1184
-	//print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1185
-	if (empty($disablehead))
1186
-	{
1187
-		$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1188
-
1189
-		print "<head>\n";
1190
-
1191
-		if (GETPOST('dol_basehref','alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1192
-
1193
-		// Displays meta
1194
-		print '<meta charset="UTF-8">'."\n";
1195
-		print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";	// Do not index
1196
-		print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n";		// Scale for mobile device
1197
-		print '<meta name="author" content="Dolibarr Development Team">'."\n";
1198
-
1199
-		// Favicon
1200
-		$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
1201
-		if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1202
-		if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1203
-		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1204
-		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1205
-		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1206
-
1207
-		// Auto refresh page
1208
-		if (GETPOST('autorefresh','int') > 0) print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh','int').'">';
1209
-
1210
-		// Displays title
1211
-		$appli=constant('DOL_APPLICATION_TITLE');
1212
-		if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1213
-
1214
-		print '<title>';
1215
-		$titletoshow='';
1216
-		if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) $titletoshow = dol_htmlentities($title);
1217
-		else if ($title) $titletoshow = dol_htmlentities($appli.' - '.$title);
1218
-		else $titletoshow = dol_htmlentities($appli);
1219
-
1220
-		if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1221
-		$hookmanager->initHooks("main");
1222
-		$parameters=array('title'=>$titletoshow);
1223
-		$result=$hookmanager->executeHooks('setHtmlTitle',$parameters);		// Note that $action and $object may have been modified by some hooks
1224
-		if ($result > 0) $titletoshow = $hookmanager->resPrint;				// Replace Title to show
1225
-		else $titletoshow .= $hookmanager->resPrint;						// Concat to Title to show
1226
-
1227
-		print $titletoshow;
1228
-		print '</title>';
1229
-
1230
-		print "\n";
1231
-
1232
-		if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1233
-		if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1234
-
1235
-		$themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1236
-		$themeparam.=($ext?'&amp;'.$ext:'');
1237
-		if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1238
-		if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1239
-		if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1240
-		if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
1241
-		if (GETPOST('dol_no_mouse_hover','int'))         { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }
1242
-		if (GETPOST('dol_use_jmobile','int'))            { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }
1243
-
1244
-		if (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)
1245
-		{
1246
-			print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1247
-			$jquerytheme = 'base';
1248
-			if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1249
-			if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1250
-			else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1251
-			if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1252
-			if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1253
-			{
1254
-				$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1255
-				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1256
-			}
1257
-		}
1182
+    if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1183
+    else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1184
+    //print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1185
+    if (empty($disablehead))
1186
+    {
1187
+        $ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1258 1188
 
1259
-		if (! defined('DISABLE_FONT_AWSOME'))
1260
-		{
1261
-			print '<!-- Includes CSS for font awesome -->'."\n";
1262
-			print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'">'."\n";
1263
-		}
1189
+        print "<head>\n";
1264 1190
 
1265
-		print '<!-- Includes CSS for Dolibarr theme -->'."\n";
1266
-		// Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1267
-		$themepath=dol_buildpath($conf->css,1);
1268
-		$themesubdir='';
1269
-		if (! empty($conf->modules_parts['theme']))	// This slow down
1270
-		{
1271
-			foreach($conf->modules_parts['theme'] as $reldir)
1272
-			{
1273
-				if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1274
-				{
1275
-					$themepath=dol_buildpath($reldir.$conf->css, 1);
1276
-					$themesubdir=$reldir;
1277
-					break;
1278
-				}
1279
-			}
1280
-		}
1191
+        if (GETPOST('dol_basehref','alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1281 1192
 
1282
-		//print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1283
-		print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1284
-		if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1193
+        // Displays meta
1194
+        print '<meta charset="UTF-8">'."\n";
1195
+        print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";	// Do not index
1196
+        print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n";		// Scale for mobile device
1197
+        print '<meta name="author" content="Dolibarr Development Team">'."\n";
1285 1198
 
1286
-		// CSS forced by modules (relative url starting with /)
1287
-		if (! empty($conf->modules_parts['css']))
1288
-		{
1289
-			$arraycss=(array) $conf->modules_parts['css'];
1290
-			foreach($arraycss as $modcss => $filescss)
1291
-			{
1292
-				$filescss=(array) $filescss;	// To be sure filecss is an array
1293
-				foreach($filescss as $cssfile)
1294
-				{
1295
-					if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1296
-					// cssfile is a relative path
1297
-					print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1298
-					// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1299
-					if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1300
-					print '">'."\n";
1301
-				}
1302
-			}
1303
-		}
1304
-		// CSS forced by page in top_htmlhead call (relative url starting with /)
1305
-		if (is_array($arrayofcss))
1306
-		{
1307
-			foreach($arrayofcss as $cssfile)
1308
-			{
1309
-				print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1310
-				// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1311
-				if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1312
-				print '">'."\n";
1313
-			}
1314
-		}
1199
+        // Favicon
1200
+        $favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
1201
+        if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1202
+        if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1203
+        //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1204
+        //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1205
+        //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1315 1206
 
1316
-		// Output standard javascript links
1317
-		if (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))
1318
-		{
1319
-			// JQuery. Must be before other includes
1320
-			print '<!-- Includes JS for JQuery -->'."\n";
1321
-			if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1322
-			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1323
-			if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1324
-			{
1325
-				if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1326
-				else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1327
-			}
1328
-			if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1329
-			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1330
-			if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1331
-			// jQuery jnotify
1332
-			if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1333
-			{
1334
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1335
-			}
1336
-			// Flot
1337
-			if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))
1338
-			{
1339
-				if (constant('JS_JQUERY_FLOT'))
1340
-				{
1341
-					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1342
-					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1343
-					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1344
-				}
1345
-				else
1346
-				{
1347
-					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1348
-					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1349
-					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1350
-				}
1351
-			}
1352
-			// jQuery jeditable
1353
-			if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))
1354
-			{
1355
-				print '<!-- JS to manage editInPlace feature -->'."\n";
1356
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1357
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1358
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1359
-				print '<script type="text/javascript">'."\n";
1360
-				print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
1361
-				print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
1362
-				print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n";	// Added in title attribute of span
1363
-				print 'var placeholderInPlace = \'&nbsp;\';'."\n";	// If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1364
-				print 'var cancelInPlace = \''.$langs->trans('Cancel').'\';'."\n";
1365
-				print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
1366
-				print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
1367
-				print 'var withInPlace = 300;';		// width in pixel for default string edit
1368
-				print '</script>'."\n";
1369
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1370
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1371
-			}
1207
+        // Auto refresh page
1208
+        if (GETPOST('autorefresh','int') > 0) print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh','int').'">';
1209
+
1210
+        // Displays title
1211
+        $appli=constant('DOL_APPLICATION_TITLE');
1212
+        if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1213
+
1214
+        print '<title>';
1215
+        $titletoshow='';
1216
+        if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) $titletoshow = dol_htmlentities($title);
1217
+        else if ($title) $titletoshow = dol_htmlentities($appli.' - '.$title);
1218
+        else $titletoshow = dol_htmlentities($appli);
1219
+
1220
+        if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1221
+        $hookmanager->initHooks("main");
1222
+        $parameters=array('title'=>$titletoshow);
1223
+        $result=$hookmanager->executeHooks('setHtmlTitle',$parameters);		// Note that $action and $object may have been modified by some hooks
1224
+        if ($result > 0) $titletoshow = $hookmanager->resPrint;				// Replace Title to show
1225
+        else $titletoshow .= $hookmanager->resPrint;						// Concat to Title to show
1226
+
1227
+        print $titletoshow;
1228
+        print '</title>';
1229
+
1230
+        print "\n";
1231
+
1232
+        if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1233
+        if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1234
+
1235
+        $themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1236
+        $themeparam.=($ext?'&amp;'.$ext:'');
1237
+        if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1238
+        if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1239
+        if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1240
+        if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
1241
+        if (GETPOST('dol_no_mouse_hover','int'))         { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }
1242
+        if (GETPOST('dol_use_jmobile','int'))            { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }
1243
+
1244
+        if (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)
1245
+        {
1246
+            print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1247
+            $jquerytheme = 'base';
1248
+            if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1249
+            if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1250
+            else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1251
+            if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1252
+            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1253
+            {
1254
+                $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1255
+                print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1256
+            }
1257
+        }
1258
+
1259
+        if (! defined('DISABLE_FONT_AWSOME'))
1260
+        {
1261
+            print '<!-- Includes CSS for font awesome -->'."\n";
1262
+            print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'">'."\n";
1263
+        }
1264
+
1265
+        print '<!-- Includes CSS for Dolibarr theme -->'."\n";
1266
+        // Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1267
+        $themepath=dol_buildpath($conf->css,1);
1268
+        $themesubdir='';
1269
+        if (! empty($conf->modules_parts['theme']))	// This slow down
1270
+        {
1271
+            foreach($conf->modules_parts['theme'] as $reldir)
1272
+            {
1273
+                if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1274
+                {
1275
+                    $themepath=dol_buildpath($reldir.$conf->css, 1);
1276
+                    $themesubdir=$reldir;
1277
+                    break;
1278
+                }
1279
+            }
1280
+        }
1281
+
1282
+        //print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1283
+        print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1284
+        if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1285
+
1286
+        // CSS forced by modules (relative url starting with /)
1287
+        if (! empty($conf->modules_parts['css']))
1288
+        {
1289
+            $arraycss=(array) $conf->modules_parts['css'];
1290
+            foreach($arraycss as $modcss => $filescss)
1291
+            {
1292
+                $filescss=(array) $filescss;	// To be sure filecss is an array
1293
+                foreach($filescss as $cssfile)
1294
+                {
1295
+                    if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1296
+                    // cssfile is a relative path
1297
+                    print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1298
+                    // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1299
+                    if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1300
+                    print '">'."\n";
1301
+                }
1302
+            }
1303
+        }
1304
+        // CSS forced by page in top_htmlhead call (relative url starting with /)
1305
+        if (is_array($arrayofcss))
1306
+        {
1307
+            foreach($arrayofcss as $cssfile)
1308
+            {
1309
+                print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1310
+                // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1311
+                if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1312
+                print '">'."\n";
1313
+            }
1314
+        }
1315
+
1316
+        // Output standard javascript links
1317
+        if (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))
1318
+        {
1319
+            // JQuery. Must be before other includes
1320
+            print '<!-- Includes JS for JQuery -->'."\n";
1321
+            if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1322
+            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1323
+            if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1324
+            {
1325
+                if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1326
+                else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1327
+            }
1328
+            if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1329
+            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1330
+            if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1331
+            // jQuery jnotify
1332
+            if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1333
+            {
1334
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1335
+            }
1336
+            // Flot
1337
+            if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))
1338
+            {
1339
+                if (constant('JS_JQUERY_FLOT'))
1340
+                {
1341
+                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1342
+                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1343
+                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1344
+                }
1345
+                else
1346
+                {
1347
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1348
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1349
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1350
+                }
1351
+            }
1352
+            // jQuery jeditable
1353
+            if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))
1354
+            {
1355
+                print '<!-- JS to manage editInPlace feature -->'."\n";
1356
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1357
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1358
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1359
+                print '<script type="text/javascript">'."\n";
1360
+                print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
1361
+                print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
1362
+                print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n";	// Added in title attribute of span
1363
+                print 'var placeholderInPlace = \'&nbsp;\';'."\n";	// If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1364
+                print 'var cancelInPlace = \''.$langs->trans('Cancel').'\';'."\n";
1365
+                print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
1366
+                print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
1367
+                print 'var withInPlace = 300;';		// width in pixel for default string edit
1368
+                print '</script>'."\n";
1369
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1370
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1371
+            }
1372 1372
             // jQuery Timepicker
1373 1373
             if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1374 1374
             {
1375
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1376
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1375
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1376
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1377 1377
             }
1378 1378
             if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1379 1379
             {
1380
-            	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1381
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";	// We include full because we need the support of containerCssClass
1380
+                $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1381
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";	// We include full because we need the support of containerCssClass
1382 1382
             }
1383 1383
             if (! defined('DISABLE_MULTISELECT'))     // jQuery plugin "mutiselect" to select with checkboxes
1384 1384
             {
1385
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1385
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1386 1386
             }
1387
-		}
1387
+        }
1388 1388
 
1389 1389
         if (! $disablejs && ! empty($conf->use_javascript_ajax))
1390 1390
         {
@@ -1396,7 +1396,7 @@  discard block
 block discarded – undo
1396 1396
                 $jsckeditor='ckeditor.js';
1397 1397
                 if (constant('JS_CKEDITOR'))	// To use external ckeditor 4 js lib
1398 1398
                 {
1399
-                	$pathckeditor=constant('JS_CKEDITOR');
1399
+                    $pathckeditor=constant('JS_CKEDITOR');
1400 1400
                 }
1401 1401
                 print '<script type="text/javascript">';
1402 1402
                 print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n";
@@ -1426,18 +1426,18 @@  discard block
 block discarded – undo
1426 1426
 
1427 1427
             // JS forced by modules (relative url starting with /)
1428 1428
             if (! empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1429
-        	{
1430
-        		$arrayjs=(array) $conf->modules_parts['js'];
1431
-	            foreach($arrayjs as $modjs => $filesjs)
1432
-	            {
1433
-        			$filesjs=(array) $filesjs;	// To be sure filejs is an array
1434
-		            foreach($filesjs as $jsfile)
1435
-		            {
1436
-	    	    		// jsfile is a relative path
1437
-	        	    	print '<!-- Include JS added by module '.$modjs. '-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1438
-		            }
1439
-	            }
1440
-        	}
1429
+            {
1430
+                $arrayjs=(array) $conf->modules_parts['js'];
1431
+                foreach($arrayjs as $modjs => $filesjs)
1432
+                {
1433
+                    $filesjs=(array) $filesjs;	// To be sure filejs is an array
1434
+                    foreach($filesjs as $jsfile)
1435
+                    {
1436
+                        // jsfile is a relative path
1437
+                        print '<!-- Include JS added by module '.$modjs. '-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1438
+                    }
1439
+                }
1440
+            }
1441 1441
             // JS forced by page in top_htmlhead (relative url starting with /)
1442 1442
             if (is_array($arrayofjs))
1443 1443
             {
@@ -1484,192 +1484,192 @@  discard block
 block discarded – undo
1484 1484
  */
1485 1485
 function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $helppagename='')
1486 1486
 {
1487
-	global $user, $conf, $langs, $db;
1488
-	global $dolibarr_main_authentication, $dolibarr_main_demo;
1489
-	global $hookmanager,$menumanager;
1487
+    global $user, $conf, $langs, $db;
1488
+    global $dolibarr_main_authentication, $dolibarr_main_demo;
1489
+    global $hookmanager,$menumanager;
1490 1490
 
1491
-	$searchform='';
1492
-	$bookmarks='';
1491
+    $searchform='';
1492
+    $bookmarks='';
1493 1493
 
1494
-	// Instantiate hooks of thirdparty module
1495
-	$hookmanager->initHooks(array('toprightmenu'));
1494
+    // Instantiate hooks of thirdparty module
1495
+    $hookmanager->initHooks(array('toprightmenu'));
1496 1496
 
1497
-	$toprightmenu='';
1497
+    $toprightmenu='';
1498 1498
 
1499
-	// For backward compatibility with old modules
1500
-	if (empty($conf->headerdone))
1501
-	{
1502
-		top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1503
-		print '<body id="mainbody">';
1504
-	}
1499
+    // For backward compatibility with old modules
1500
+    if (empty($conf->headerdone))
1501
+    {
1502
+        top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1503
+        print '<body id="mainbody">';
1504
+    }
1505 1505
 
1506
-	/*
1506
+    /*
1507 1507
      * Top menu
1508 1508
      */
1509
-	if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int')) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1510
-	{
1511
-		print "\n".'<!-- Start top horizontal -->'."\n";
1509
+    if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int')) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1510
+    {
1511
+        print "\n".'<!-- Start top horizontal -->'."\n";
1512 1512
 
1513
-		print '<div class="side-nav-vert'.(GETPOST('dol_invisible_topmenu','int')?' hidden':'').'"><div id="id-top">';		// dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
1513
+        print '<div class="side-nav-vert'.(GETPOST('dol_invisible_topmenu','int')?' hidden':'').'"><div id="id-top">';		// dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
1514 1514
 
1515
-		// Show menu entries
1516
-		print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'" class="tmenu">'."\n";
1517
-		$menumanager->atarget=$target;
1518
-		$menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks));      // This contains a \n
1519
-		print "</div>\n";
1515
+        // Show menu entries
1516
+        print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'" class="tmenu">'."\n";
1517
+        $menumanager->atarget=$target;
1518
+        $menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks));      // This contains a \n
1519
+        print "</div>\n";
1520 1520
 
1521
-		// Define link to login card
1522
-		$appli=constant('DOL_APPLICATION_TITLE');
1523
-		if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1524
-		{
1525
-			$appli=$conf->global->MAIN_APPLICATION_TITLE;
1526
-			if (preg_match('/\d\.\d/', $appli))
1527
-			{
1528
-				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1529
-			}
1530
-			else $appli.=" ".DOL_VERSION;
1531
-		}
1532
-		else $appli.=" ".DOL_VERSION;
1521
+        // Define link to login card
1522
+        $appli=constant('DOL_APPLICATION_TITLE');
1523
+        if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1524
+        {
1525
+            $appli=$conf->global->MAIN_APPLICATION_TITLE;
1526
+            if (preg_match('/\d\.\d/', $appli))
1527
+            {
1528
+                if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1529
+            }
1530
+            else $appli.=" ".DOL_VERSION;
1531
+        }
1532
+        else $appli.=" ".DOL_VERSION;
1533 1533
 
1534
-		if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1534
+        if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1535 1535
 
1536
-		$logouttext='';
1537
-		if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1538
-		{
1539
-			//$logouthtmltext=$appli.'<br>';
1540
-			if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
1541
-			{
1542
-				$logouthtmltext.=$langs->trans("Logout").'<br>';
1543
-
1544
-				$logouttext .='<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php">';
1545
-				//$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1546
-				$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1547
-				$logouttext .='</a>';
1548
-			}
1549
-			else
1550
-			{
1551
-				$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1552
-				$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1553
-			}
1554
-		}
1536
+        $logouttext='';
1537
+        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1538
+        {
1539
+            //$logouthtmltext=$appli.'<br>';
1540
+            if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
1541
+            {
1542
+                $logouthtmltext.=$langs->trans("Logout").'<br>';
1555 1543
 
1556
-		print '<div class="login_block">'."\n";
1544
+                $logouttext .='<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php">';
1545
+                //$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1546
+                $logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1547
+                $logouttext .='</a>';
1548
+            }
1549
+            else
1550
+            {
1551
+                $logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1552
+                $logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1553
+            }
1554
+        }
1557 1555
 
1558
-		// Add login user link
1559
-		$toprightmenu.='<div class="login_block_user">';
1556
+        print '<div class="login_block">'."\n";
1560 1557
 
1561
-		// Login name with photo and tooltip
1562
-		$mode=-1;
1563
-		$toprightmenu.='<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1564
-		$toprightmenu.=$user->getNomUrl($mode, '', 1, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');
1565
-		$toprightmenu.='</div></div>';
1558
+        // Add login user link
1559
+        $toprightmenu.='<div class="login_block_user">';
1566 1560
 
1567
-		$toprightmenu.='</div>'."\n";
1561
+        // Login name with photo and tooltip
1562
+        $mode=-1;
1563
+        $toprightmenu.='<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1564
+        $toprightmenu.=$user->getNomUrl($mode, '', 1, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');
1565
+        $toprightmenu.='</div></div>';
1568 1566
 
1569
-		$toprightmenu.='<div class="login_block_other">';
1567
+        $toprightmenu.='</div>'."\n";
1570 1568
 
1571
-		// Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
1572
-		$parameters=array();
1573
-		$result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1574
-		if (is_numeric($result))
1575
-		{
1576
-			if ($result == 0)
1577
-				$toprightmenu.=$hookmanager->resPrint;		// add
1578
-			else
1579
-				$toprightmenu=$hookmanager->resPrint;						// replace
1580
-		}
1581
-		else
1582
-		{
1583
-			$toprightmenu.=$result;	// For backward compatibility
1584
-		}
1569
+        $toprightmenu.='<div class="login_block_other">';
1585 1570
 
1586
-		// Link to module builder
1587
-		if (! empty($conf->modulebuilder->enabled))
1588
-		{
1589
-			$text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1590
-			//$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
1591
-			$text.='<span class="fa fa-bug atoplogin"></span>';
1592
-			$text.='</a>';
1593
-			$toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
1594
-		}
1571
+        // Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
1572
+        $parameters=array();
1573
+        $result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1574
+        if (is_numeric($result))
1575
+        {
1576
+            if ($result == 0)
1577
+                $toprightmenu.=$hookmanager->resPrint;		// add
1578
+            else
1579
+                $toprightmenu=$hookmanager->resPrint;						// replace
1580
+        }
1581
+        else
1582
+        {
1583
+            $toprightmenu.=$result;	// For backward compatibility
1584
+        }
1595 1585
 
1596
-		// Link to print main content area
1597
-		if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone')
1598
-		{
1599
-			$qs=dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1600
-
1601
-			if (is_array($_POST))
1602
-			{
1603
-				foreach($_POST as $key=>$value) {
1604
-					if ($key!=='action' && $key!=='password' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1605
-				}
1606
-			}
1607
-			$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
1608
-			$text ='<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
1609
-			//$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
1610
-			$text.='<span class="fa fa-print atoplogin"></span>';
1611
-			$text.='</a>';
1612
-			$toprightmenu.=@Form::textwithtooltip('',$langs->trans("PrintContentArea"),2,1,$text,'login_block_elem',2);
1613
-		}
1586
+        // Link to module builder
1587
+        if (! empty($conf->modulebuilder->enabled))
1588
+        {
1589
+            $text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1590
+            //$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
1591
+            $text.='<span class="fa fa-bug atoplogin"></span>';
1592
+            $text.='</a>';
1593
+            $toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
1594
+        }
1614 1595
 
1615
-		// Link to Dolibarr wiki pages
1616
-		if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1617
-		{
1618
-			$langs->load("help");
1596
+        // Link to print main content area
1597
+        if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone')
1598
+        {
1599
+            $qs=dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1600
+
1601
+            if (is_array($_POST))
1602
+            {
1603
+                foreach($_POST as $key=>$value) {
1604
+                    if ($key!=='action' && $key!=='password' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1605
+                }
1606
+            }
1607
+            $qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
1608
+            $text ='<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
1609
+            //$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
1610
+            $text.='<span class="fa fa-print atoplogin"></span>';
1611
+            $text.='</a>';
1612
+            $toprightmenu.=@Form::textwithtooltip('',$langs->trans("PrintContentArea"),2,1,$text,'login_block_elem',2);
1613
+        }
1614
+
1615
+        // Link to Dolibarr wiki pages
1616
+        if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1617
+        {
1618
+            $langs->load("help");
1619 1619
 
1620
-			$helpbaseurl='';
1621
-			$helppage='';
1622
-			$mode='';
1620
+            $helpbaseurl='';
1621
+            $helppage='';
1622
+            $mode='';
1623 1623
 
1624
-			if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1624
+            if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1625 1625
 
1626
-			// Get helpbaseurl, helppage and mode from helppagename and langs
1627
-			$arrayres=getHelpParamFor($helppagename,$langs);
1628
-			$helpbaseurl=$arrayres['helpbaseurl'];
1629
-			$helppage=$arrayres['helppage'];
1630
-			$mode=$arrayres['mode'];
1626
+            // Get helpbaseurl, helppage and mode from helppagename and langs
1627
+            $arrayres=getHelpParamFor($helppagename,$langs);
1628
+            $helpbaseurl=$arrayres['helpbaseurl'];
1629
+            $helppage=$arrayres['helppage'];
1630
+            $mode=$arrayres['mode'];
1631 1631
 
1632
-			// Link to help pages
1633
-			if ($helpbaseurl && $helppage)
1634
-			{
1635
-				$text='';
1636
-	            if(!empty($conf->global->MAIN_SHOWDATABASENAMEINHELPPAGESLINK)) {
1632
+            // Link to help pages
1633
+            if ($helpbaseurl && $helppage)
1634
+            {
1635
+                $text='';
1636
+                if(!empty($conf->global->MAIN_SHOWDATABASENAMEINHELPPAGESLINK)) {
1637 1637
                     $langs->load('admin');
1638 1638
                     $appli .= '<br>' . $langs->trans("Database") . ': ' . $db->database_name;
1639 1639
                 }
1640
-				$title=$appli.'<br>';
1641
-				$title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1642
-				if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1643
-				$text.='<a class="help" target="_blank" rel="noopener" href="';
1644
-				if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1645
-				else $text.=sprintf($helpbaseurl,$helppage);
1646
-				$text.='">';
1647
-				//$text.=img_picto('', 'helpdoc_top').' ';
1648
-				$text.='<span class="fa fa-question-circle atoplogin"></span>';
1649
-				//$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');
1650
-				//if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';
1651
-				$text.='</a>';
1652
-				//$toprightmenu.='</div>'."\n";
1653
-				$toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);
1654
-			}
1655
-		}
1640
+                $title=$appli.'<br>';
1641
+                $title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1642
+                if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1643
+                $text.='<a class="help" target="_blank" rel="noopener" href="';
1644
+                if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1645
+                else $text.=sprintf($helpbaseurl,$helppage);
1646
+                $text.='">';
1647
+                //$text.=img_picto('', 'helpdoc_top').' ';
1648
+                $text.='<span class="fa fa-question-circle atoplogin"></span>';
1649
+                //$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');
1650
+                //if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';
1651
+                $text.='</a>';
1652
+                //$toprightmenu.='</div>'."\n";
1653
+                $toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);
1654
+            }
1655
+        }
1656 1656
 
1657
-		// Logout link
1658
-		$toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
1657
+        // Logout link
1658
+        $toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
1659 1659
 
1660
-		$toprightmenu.='</div>';
1660
+        $toprightmenu.='</div>';
1661 1661
 
1662
-		print $toprightmenu;
1662
+        print $toprightmenu;
1663 1663
 
1664
-		print "</div>\n";		// end div class="login_block"
1664
+        print "</div>\n";		// end div class="login_block"
1665 1665
 
1666
-		print '</div></div>';
1666
+        print '</div></div>';
1667 1667
 
1668
-		print '<div style="clear: both;"></div>';
1669
-		print "<!-- End top horizontal menu -->\n\n";
1670
-	}
1668
+        print '<div style="clear: both;"></div>';
1669
+        print "<!-- End top horizontal menu -->\n\n";
1670
+    }
1671 1671
 
1672
-	if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1672
+    if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1673 1673
 }
1674 1674
 
1675 1675
 
@@ -1689,172 +1689,172 @@  discard block
 block discarded – undo
1689 1689
  */
1690 1690
 function left_menu($menu_array_before, $helppagename='', $notused='', $menu_array_after='', $leftmenuwithoutmainarea=0, $title='', $acceptdelayedhtml=0)
1691 1691
 {
1692
-	global $user, $conf, $langs, $db, $form;
1693
-	global $hookmanager, $menumanager;
1692
+    global $user, $conf, $langs, $db, $form;
1693
+    global $hookmanager, $menumanager;
1694 1694
 
1695
-	$searchform='';
1696
-	$bookmarks='';
1695
+    $searchform='';
1696
+    $bookmarks='';
1697 1697
 
1698
-	if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1698
+    if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1699 1699
 
1700
-	if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1701
-	{
1702
-		// Instantiate hooks of thirdparty module
1703
-		$hookmanager->initHooks(array('searchform','leftblock'));
1700
+    if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1701
+    {
1702
+        // Instantiate hooks of thirdparty module
1703
+        $hookmanager->initHooks(array('searchform','leftblock'));
1704 1704
 
1705
-		print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
1705
+        print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
1706 1706
 
1707
-		if ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM=1;	// Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
1707
+        if ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM=1;	// Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
1708 1708
 
1709
-		print "\n";
1709
+        print "\n";
1710 1710
 
1711
-		if (! is_object($form)) $form=new Form($db);
1712
-		$selected=-1;
1713
-		$usedbyinclude=1;
1714
-		include_once DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php';	// This set $arrayresult
1711
+        if (! is_object($form)) $form=new Form($db);
1712
+        $selected=-1;
1713
+        $usedbyinclude=1;
1714
+        include_once DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php';	// This set $arrayresult
1715 1715
 
1716
-		if ($conf->use_javascript_ajax && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1717
-		{
1718
-			//$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1719
-			$searchform.=$form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, '', 1, 0, (empty($conf->global->MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY)?1:0), 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1720
-		}
1721
-		else
1722
-		{
1723
-			foreach($arrayresult as $key => $val)
1724
-			{
1725
-				//$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth100', 'sall', $val['shortcut'], 'searchleft', img_picto('',$val['img']));
1726
-				$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'sall', $val['shortcut'], 'searchleft', img_picto('', $val['img'], '', false, 1, 1));
1727
-			}
1728
-		}
1716
+        if ($conf->use_javascript_ajax && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1717
+        {
1718
+            //$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1719
+            $searchform.=$form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, '', 1, 0, (empty($conf->global->MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY)?1:0), 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1720
+        }
1721
+        else
1722
+        {
1723
+            foreach($arrayresult as $key => $val)
1724
+            {
1725
+                //$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth100', 'sall', $val['shortcut'], 'searchleft', img_picto('',$val['img']));
1726
+                $searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'sall', $val['shortcut'], 'searchleft', img_picto('', $val['img'], '', false, 1, 1));
1727
+            }
1728
+        }
1729 1729
 
1730
-		// Execute hook printSearchForm
1731
-		$parameters=array('searchform'=>$searchform);
1732
-		$reshook=$hookmanager->executeHooks('printSearchForm',$parameters);    // Note that $action and $object may have been modified by some hooks
1733
-		if (empty($reshook))
1734
-		{
1735
-			$searchform.=$hookmanager->resPrint;
1736
-		}
1737
-		else $searchform=$hookmanager->resPrint;
1730
+        // Execute hook printSearchForm
1731
+        $parameters=array('searchform'=>$searchform);
1732
+        $reshook=$hookmanager->executeHooks('printSearchForm',$parameters);    // Note that $action and $object may have been modified by some hooks
1733
+        if (empty($reshook))
1734
+        {
1735
+            $searchform.=$hookmanager->resPrint;
1736
+        }
1737
+        else $searchform=$hookmanager->resPrint;
1738 1738
 
1739
-		// Force special value for $searchform
1740
-		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax))
1741
-		{
1742
-			$urltosearch=DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
1743
-			$searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div></div>';
1744
-		}
1745
-		elseif ($conf->use_javascript_ajax && ! empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1746
-		{
1747
-			$searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1748
-			$searchform.='<script type="text/javascript">
1739
+        // Force special value for $searchform
1740
+        if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax))
1741
+        {
1742
+            $urltosearch=DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
1743
+            $searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div></div>';
1744
+        }
1745
+        elseif ($conf->use_javascript_ajax && ! empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1746
+        {
1747
+            $searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1748
+            $searchform.='<script type="text/javascript">
1749 1749
             	jQuery(document).ready(function () {
1750 1750
             		jQuery("#divsearchforms1").click(function(){
1751 1751
 	                   jQuery("#divsearchforms2").toggle();
1752 1752
 	               });
1753 1753
             	});
1754 1754
                 </script>' . "\n";
1755
-			$searchform.='</div>';
1756
-		}
1755
+            $searchform.='</div>';
1756
+        }
1757 1757
 
1758
-		// Define $bookmarks
1759
-		if (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1760
-		{
1761
-			include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php';
1762
-			$langs->load("bookmarks");
1758
+        // Define $bookmarks
1759
+        if (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1760
+        {
1761
+            include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php';
1762
+            $langs->load("bookmarks");
1763 1763
 
1764
-			$bookmarks=printBookmarksList($db, $langs);
1765
-		}
1764
+            $bookmarks=printBookmarksList($db, $langs);
1765
+        }
1766 1766
 
1767
-		// Left column
1768
-		print '<!-- Begin left menu -->'."\n";
1767
+        // Left column
1768
+        print '<!-- Begin left menu -->'."\n";
1769 1769
 
1770
-		print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title="Left menu"').'>'."\n\n";
1770
+        print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title="Left menu"').'>'."\n\n";
1771 1771
 
1772
-		// Show left menu with other forms
1773
-		$menumanager->menu_array = $menu_array_before;
1774
-		$menumanager->menu_array_after = $menu_array_after;
1775
-		$menumanager->showmenu('left', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // output menu_array and menu found in database
1772
+        // Show left menu with other forms
1773
+        $menumanager->menu_array = $menu_array_before;
1774
+        $menumanager->menu_array_after = $menu_array_after;
1775
+        $menumanager->showmenu('left', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // output menu_array and menu found in database
1776 1776
 
1777
-		// Dolibarr version + help + bug report link
1778
-		print "\n";
1779
-		print "<!-- Begin Help Block-->\n";
1780
-		print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
1777
+        // Dolibarr version + help + bug report link
1778
+        print "\n";
1779
+        print "<!-- Begin Help Block-->\n";
1780
+        print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
1781 1781
 
1782
-		// Version
1783
-		if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
1784
-		{
1785
-			$doliurl='https://www.dolibarr.org';
1786
-			//local communities
1787
-			if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1788
-			if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1789
-			if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1790
-			if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1791
-			if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
1792
-
1793
-			$appli=constant('DOL_APPLICATION_TITLE');
1794
-			if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1795
-			{
1796
-				$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1797
-				if (preg_match('/\d\.\d/', $appli))
1798
-				{
1799
-					if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1800
-				}
1801
-				else $appli.=" ".DOL_VERSION;
1802
-			}
1803
-			else $appli.=" ".DOL_VERSION;
1804
-			print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1805
-			if ($doliurl) print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
1806
-			else print '<span class="help">';
1807
-			print $appli;
1808
-			if ($doliurl) print '</a>';
1809
-			else print '</span>';
1810
-			print '</div>'."\n";
1811
-		}
1782
+        // Version
1783
+        if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
1784
+        {
1785
+            $doliurl='https://www.dolibarr.org';
1786
+            //local communities
1787
+            if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1788
+            if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1789
+            if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1790
+            if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1791
+            if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
1792
+
1793
+            $appli=constant('DOL_APPLICATION_TITLE');
1794
+            if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1795
+            {
1796
+                $appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1797
+                if (preg_match('/\d\.\d/', $appli))
1798
+                {
1799
+                    if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1800
+                }
1801
+                else $appli.=" ".DOL_VERSION;
1802
+            }
1803
+            else $appli.=" ".DOL_VERSION;
1804
+            print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1805
+            if ($doliurl) print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
1806
+            else print '<span class="help">';
1807
+            print $appli;
1808
+            if ($doliurl) print '</a>';
1809
+            else print '</span>';
1810
+            print '</div>'."\n";
1811
+        }
1812 1812
 
1813
-		// Link to bugtrack
1814
-		if (! empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
1815
-		{
1816
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1817
-
1818
-			$bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';
1819
-			$bugbaseurl.= '?title=';
1820
-			$bugbaseurl.= urlencode("Bug: ");
1821
-			$bugbaseurl.= '&body=';
1822
-			$bugbaseurl.= urlencode("# Bug\n");
1823
-			$bugbaseurl.= urlencode("\n");
1824
-			$bugbaseurl.= urlencode("## Environment\n");
1825
-			$bugbaseurl.= urlencode("- **Version**: " . DOL_VERSION . "\n");
1826
-			$bugbaseurl.= urlencode("- **OS**: " . php_uname('s') . "\n");
1827
-			$bugbaseurl.= urlencode("- **Web server**: " . $_SERVER["SERVER_SOFTWARE"] . "\n");
1828
-			$bugbaseurl.= urlencode("- **PHP**: " . php_sapi_name() . ' ' . phpversion() . "\n");
1829
-			$bugbaseurl.= urlencode("- **Database**: " . $db::LABEL . ' ' . $db->getVersion() . "\n");
1830
-			$bugbaseurl.= urlencode("- **URL**: " . $_SERVER["REQUEST_URI"] . "\n");
1831
-			$bugbaseurl.= urlencode("\n");
1832
-			$bugbaseurl.= urlencode("## Report\n");
1833
-			print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
1834
-			print '<a class="help" target="_blank" rel="noopener" href="'.$bugbaseurl.'">'.$langs->trans("FindBug").'</a>';
1835
-			print '</div>';
1836
-		}
1813
+        // Link to bugtrack
1814
+        if (! empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
1815
+        {
1816
+            require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1817
+
1818
+            $bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';
1819
+            $bugbaseurl.= '?title=';
1820
+            $bugbaseurl.= urlencode("Bug: ");
1821
+            $bugbaseurl.= '&body=';
1822
+            $bugbaseurl.= urlencode("# Bug\n");
1823
+            $bugbaseurl.= urlencode("\n");
1824
+            $bugbaseurl.= urlencode("## Environment\n");
1825
+            $bugbaseurl.= urlencode("- **Version**: " . DOL_VERSION . "\n");
1826
+            $bugbaseurl.= urlencode("- **OS**: " . php_uname('s') . "\n");
1827
+            $bugbaseurl.= urlencode("- **Web server**: " . $_SERVER["SERVER_SOFTWARE"] . "\n");
1828
+            $bugbaseurl.= urlencode("- **PHP**: " . php_sapi_name() . ' ' . phpversion() . "\n");
1829
+            $bugbaseurl.= urlencode("- **Database**: " . $db::LABEL . ' ' . $db->getVersion() . "\n");
1830
+            $bugbaseurl.= urlencode("- **URL**: " . $_SERVER["REQUEST_URI"] . "\n");
1831
+            $bugbaseurl.= urlencode("\n");
1832
+            $bugbaseurl.= urlencode("## Report\n");
1833
+            print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
1834
+            print '<a class="help" target="_blank" rel="noopener" href="'.$bugbaseurl.'">'.$langs->trans("FindBug").'</a>';
1835
+            print '</div>';
1836
+        }
1837 1837
 
1838
-		print "</div>\n";
1839
-		print "<!-- End Help Block-->\n";
1840
-		print "\n";
1838
+        print "</div>\n";
1839
+        print "<!-- End Help Block-->\n";
1840
+        print "\n";
1841 1841
 
1842
-		print "</div>\n";
1843
-		print "<!-- End left menu -->\n";
1844
-		print "\n";
1842
+        print "</div>\n";
1843
+        print "<!-- End left menu -->\n";
1844
+        print "\n";
1845 1845
 
1846
-		// Execute hook printLeftBlock
1847
-		$parameters=array();
1848
-		$reshook=$hookmanager->executeHooks('printLeftBlock',$parameters);    // Note that $action and $object may have been modified by some hooks
1849
-		print $hookmanager->resPrint;
1846
+        // Execute hook printLeftBlock
1847
+        $parameters=array();
1848
+        $reshook=$hookmanager->executeHooks('printLeftBlock',$parameters);    // Note that $action and $object may have been modified by some hooks
1849
+        print $hookmanager->resPrint;
1850 1850
 
1851
-		print '</div></div> <!-- End side-nav id-left -->';	// End div id="side-nav" div id="id-left"
1852
-	}
1851
+        print '</div></div> <!-- End side-nav id-left -->';	// End div id="side-nav" div id="id-left"
1852
+    }
1853 1853
 
1854
-	print "\n";
1855
-	print '<!-- Begin right area -->'."\n";
1854
+    print "\n";
1855
+    print '<!-- Begin right area -->'."\n";
1856 1856
 
1857
-	if (empty($leftmenuwithoutmainarea)) main_area($title);
1857
+    if (empty($leftmenuwithoutmainarea)) main_area($title);
1858 1858
 }
1859 1859
 
1860 1860
 
@@ -1866,15 +1866,15 @@  discard block
 block discarded – undo
1866 1866
  */
1867 1867
 function main_area($title='')
1868 1868
 {
1869
-	global $conf, $langs;
1869
+    global $conf, $langs;
1870 1870
 
1871
-	if (empty($conf->dol_hide_leftmenu)) print '<div id="id-right">';
1871
+    if (empty($conf->dol_hide_leftmenu)) print '<div id="id-right">';
1872 1872
 
1873
-	print "\n";
1873
+    print "\n";
1874 1874
 
1875
-	print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1875
+    print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1876 1876
 
1877
-	if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1877
+    if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1878 1878
 }
1879 1879
 
1880 1880
 
@@ -1887,38 +1887,38 @@  discard block
 block discarded – undo
1887 1887
  */
1888 1888
 function getHelpParamFor($helppagename,$langs)
1889 1889
 {
1890
-	$helpbaseurl='';
1891
-	$helppage='';
1892
-	$mode='';
1893
-
1894
-	if (preg_match('/^http/i',$helppagename))
1895
-	{
1896
-		// If complete URL
1897
-		$helpbaseurl='%s';
1898
-		$helppage=$helppagename;
1899
-		$mode='local';
1900
-	}
1901
-	else
1902
-	{
1903
-		// If WIKI URL
1904
-		if (preg_match('/^es/i',$langs->defaultlang))
1905
-		{
1906
-			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1907
-			if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1908
-		}
1909
-		if (preg_match('/^fr/i',$langs->defaultlang))
1910
-		{
1911
-			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1912
-			if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1913
-		}
1914
-		if (empty($helppage))	// If help page not already found
1915
-		{
1916
-			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1917
-			if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1918
-		}
1919
-		$mode='wiki';
1920
-	}
1921
-	return array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);
1890
+    $helpbaseurl='';
1891
+    $helppage='';
1892
+    $mode='';
1893
+
1894
+    if (preg_match('/^http/i',$helppagename))
1895
+    {
1896
+        // If complete URL
1897
+        $helpbaseurl='%s';
1898
+        $helppage=$helppagename;
1899
+        $mode='local';
1900
+    }
1901
+    else
1902
+    {
1903
+        // If WIKI URL
1904
+        if (preg_match('/^es/i',$langs->defaultlang))
1905
+        {
1906
+            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1907
+            if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1908
+        }
1909
+        if (preg_match('/^fr/i',$langs->defaultlang))
1910
+        {
1911
+            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1912
+            if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1913
+        }
1914
+        if (empty($helppage))	// If help page not already found
1915
+        {
1916
+            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1917
+            if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1918
+        }
1919
+        $mode='wiki';
1920
+    }
1921
+    return array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);
1922 1922
 }
1923 1923
 
1924 1924
 
@@ -1939,138 +1939,138 @@  discard block
 block discarded – undo
1939 1939
  */
1940 1940
 function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey='', $prefhtmlinputname='',$img='', $showtitlebefore=0)
1941 1941
 {
1942
-	global $conf,$langs,$user;
1943
-
1944
-	$ret='';
1945
-	$ret.='<form action="'.$urlaction.'" method="post" class="searchform">';
1946
-	$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1947
-	$ret.='<input type="hidden" name="mode" value="search">';
1948
-	$ret.='<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
1949
-	if ($showtitlebefore) $ret.=$title.' ';
1950
-	$ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1951
-	$ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1952
-	$ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
1953
-	$ret.=' placeholder="'.strip_tags($title).'"';
1954
-	$ret.=' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1955
-	//$ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1956
-	$ret.='<button type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
1957
-	$ret.='<span class="fa fa-search"></span>';
1958
-	$ret.='</button>';
1959
-	$ret.="</form>\n";
1960
-	return $ret;
1942
+    global $conf,$langs,$user;
1943
+
1944
+    $ret='';
1945
+    $ret.='<form action="'.$urlaction.'" method="post" class="searchform">';
1946
+    $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1947
+    $ret.='<input type="hidden" name="mode" value="search">';
1948
+    $ret.='<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
1949
+    if ($showtitlebefore) $ret.=$title.' ';
1950
+    $ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1951
+    $ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1952
+    $ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
1953
+    $ret.=' placeholder="'.strip_tags($title).'"';
1954
+    $ret.=' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1955
+    //$ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1956
+    $ret.='<button type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
1957
+    $ret.='<span class="fa fa-search"></span>';
1958
+    $ret.='</button>';
1959
+    $ret.="</form>\n";
1960
+    return $ret;
1961 1961
 }
1962 1962
 
1963 1963
 
1964 1964
 if (! function_exists("llxFooter"))
1965 1965
 {
1966
-	/**
1967
-	 * Show HTML footer
1968
-	 * Close div /DIV class=fiche + /DIV id-right + /DIV id-container + /BODY + /HTML.
1969
-	 * If global var $delayedhtmlcontent was filled, we output it just before closing the body.
1970
-	 *
1971
-	 * @param	string	$comment    				A text to add as HTML comment into HTML generated page
1972
-	 * @param	string	$zone						'private' (for private pages) or 'public' (for public pages)
1973
-	 * @param	int		$disabledoutputofmessages	Clear all messages stored into session without diplaying them
1974
-	 * @return	void
1975
-	 */
1976
-	function llxFooter($comment='',$zone='private', $disabledoutputofmessages=0)
1977
-	{
1978
-		global $conf, $langs, $user, $object;
1979
-		global $delayedhtmlcontent;
1980
-		global $contextpage, $page, $limit;
1966
+    /**
1967
+     * Show HTML footer
1968
+     * Close div /DIV class=fiche + /DIV id-right + /DIV id-container + /BODY + /HTML.
1969
+     * If global var $delayedhtmlcontent was filled, we output it just before closing the body.
1970
+     *
1971
+     * @param	string	$comment    				A text to add as HTML comment into HTML generated page
1972
+     * @param	string	$zone						'private' (for private pages) or 'public' (for public pages)
1973
+     * @param	int		$disabledoutputofmessages	Clear all messages stored into session without diplaying them
1974
+     * @return	void
1975
+     */
1976
+    function llxFooter($comment='',$zone='private', $disabledoutputofmessages=0)
1977
+    {
1978
+        global $conf, $langs, $user, $object;
1979
+        global $delayedhtmlcontent;
1980
+        global $contextpage, $page, $limit;
1981 1981
 
1982
-		$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1982
+        $ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1983 1983
 
1984
-		// Global html output events ($mesgs, $errors, $warnings)
1985
-		dol_htmloutput_events($disabledoutputofmessages);
1984
+        // Global html output events ($mesgs, $errors, $warnings)
1985
+        dol_htmloutput_events($disabledoutputofmessages);
1986 1986
 
1987
-		// Code for search criteria persistence.
1988
-		// $user->lastsearch_values was set by the GETPOST when form field search_xxx exists
1989
-		if (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1990
-		{
1991
-			// Clean and save data
1992
-			foreach($user->lastsearch_values_tmp as $key => $val)
1993
-			{
1994
-				unset($_SESSION['lastsearch_values_tmp_'.$key]);			// Clean array to rebuild it just after
1995
-				if (count($val) && empty($_POST['button_removefilter']))	// If there is search criteria to save and we did not click on 'Clear filter' button
1996
-				{
1997
-					if (empty($val['sortfield'])) unset($val['sortfield']);
1998
-					if (empty($val['sortorder'])) unset($val['sortorder']);
1999
-					dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)");
2000
-					$_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
2001
-					unset($_SESSION['lastsearch_values_'.$key]);
2002
-				}
2003
-			}
2004
-		}
1987
+        // Code for search criteria persistence.
1988
+        // $user->lastsearch_values was set by the GETPOST when form field search_xxx exists
1989
+        if (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1990
+        {
1991
+            // Clean and save data
1992
+            foreach($user->lastsearch_values_tmp as $key => $val)
1993
+            {
1994
+                unset($_SESSION['lastsearch_values_tmp_'.$key]);			// Clean array to rebuild it just after
1995
+                if (count($val) && empty($_POST['button_removefilter']))	// If there is search criteria to save and we did not click on 'Clear filter' button
1996
+                {
1997
+                    if (empty($val['sortfield'])) unset($val['sortfield']);
1998
+                    if (empty($val['sortorder'])) unset($val['sortorder']);
1999
+                    dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)");
2000
+                    $_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
2001
+                    unset($_SESSION['lastsearch_values_'.$key]);
2002
+                }
2003
+            }
2004
+        }
2005 2005
 
2006 2006
 
2007
-		$relativepathstring = $_SERVER["PHP_SELF"];
2008
-		// Clean $relativepathstring
2009
-		if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
2010
-		$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
2011
-		$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
2012
-		if (preg_match('/list\.php$/', $relativepathstring))
2013
-		{
2014
-			unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
2015
-			unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
2016
-			unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
2007
+        $relativepathstring = $_SERVER["PHP_SELF"];
2008
+        // Clean $relativepathstring
2009
+        if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
2010
+        $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
2011
+        $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
2012
+        if (preg_match('/list\.php$/', $relativepathstring))
2013
+        {
2014
+            unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
2015
+            unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
2016
+            unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
2017 2017
 
2018
-			if (! empty($contextpage))                     $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]=$contextpage;
2019
-			if (! empty($page) && $page > 1)               $_SESSION['lastsearch_page_tmp_'.$relativepathstring]=$page;
2020
-			if (! empty($limit) && $limit != $conf->limit) $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]=$limit;
2018
+            if (! empty($contextpage))                     $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]=$contextpage;
2019
+            if (! empty($page) && $page > 1)               $_SESSION['lastsearch_page_tmp_'.$relativepathstring]=$page;
2020
+            if (! empty($limit) && $limit != $conf->limit) $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]=$limit;
2021 2021
 
2022
-			unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
2023
-			unset($_SESSION['lastsearch_page_'.$relativepathstring]);
2024
-			unset($_SESSION['lastsearch_limit_'.$relativepathstring]);
2025
-		}
2022
+            unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
2023
+            unset($_SESSION['lastsearch_page_'.$relativepathstring]);
2024
+            unset($_SESSION['lastsearch_limit_'.$relativepathstring]);
2025
+        }
2026 2026
 
2027
-		// Core error message
2028
-		if (! empty($conf->global->MAIN_CORE_ERROR))
2029
-		{
2030
-			// Ajax version
2031
-			if ($conf->use_javascript_ajax)
2032
-			{
2033
-				$title = img_warning().' '.$langs->trans('CoreErrorTitle');
2034
-				print ajax_dialog($title, $langs->trans('CoreErrorMessage'));
2035
-			}
2036
-			// html version
2037
-			else
2038
-			{
2039
-				$msg = img_warning().' '.$langs->trans('CoreErrorMessage');
2040
-				print '<div class="error">'.$msg.'</div>';
2041
-			}
2042
-
2043
-			//define("MAIN_CORE_ERROR",0);      // Constant was defined and we can't change value of a constant
2044
-		}
2027
+        // Core error message
2028
+        if (! empty($conf->global->MAIN_CORE_ERROR))
2029
+        {
2030
+            // Ajax version
2031
+            if ($conf->use_javascript_ajax)
2032
+            {
2033
+                $title = img_warning().' '.$langs->trans('CoreErrorTitle');
2034
+                print ajax_dialog($title, $langs->trans('CoreErrorMessage'));
2035
+            }
2036
+            // html version
2037
+            else
2038
+            {
2039
+                $msg = img_warning().' '.$langs->trans('CoreErrorMessage');
2040
+                print '<div class="error">'.$msg.'</div>';
2041
+            }
2045 2042
 
2046
-		print "\n\n";
2043
+            //define("MAIN_CORE_ERROR",0);      // Constant was defined and we can't change value of a constant
2044
+        }
2047 2045
 
2048
-		print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
2046
+        print "\n\n";
2049 2047
 
2050
-		if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'."\n"; // End div id-right
2048
+        print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
2051 2049
 
2052
-		if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
2050
+        if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'."\n"; // End div id-right
2053 2051
 
2054
-		print "\n";
2055
-		if ($comment) print '<!-- '.$comment.' -->'."\n";
2052
+        if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
2056 2053
 
2057
-		printCommonFooter($zone);
2054
+        print "\n";
2055
+        if ($comment) print '<!-- '.$comment.' -->'."\n";
2058 2056
 
2059
-		if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
2057
+        printCommonFooter($zone);
2060 2058
 
2061
-		if (! empty($conf->use_javascript_ajax))
2062
-		{
2063
-			print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
2064
-			print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'"></script>'."\n";
2065
-		}
2059
+        if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
2066 2060
 
2067
-		// Wrapper to add log when clicking on download or preview
2068
-		if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2069
-		{
2070
-			if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2071
-			{
2072
-				print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
2073
-				?>
2061
+        if (! empty($conf->use_javascript_ajax))
2062
+        {
2063
+            print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
2064
+            print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'"></script>'."\n";
2065
+        }
2066
+
2067
+        // Wrapper to add log when clicking on download or preview
2068
+        if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2069
+        {
2070
+            if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2071
+            {
2072
+                print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
2073
+                ?>
2074 2074
     			<script type="text/javascript">
2075 2075
     			jQuery(document).ready(function () {
2076 2076
     				$('a.documentpreview').click(function() {
@@ -2094,14 +2094,14 @@  discard block
 block discarded – undo
2094 2094
     			});
2095 2095
     			</script>
2096 2096
 				<?php
2097
-			}
2098
-	   	}
2097
+            }
2098
+            }
2099 2099
 
2100
-		// A div for the address popup
2101
-		print "\n<!-- A div to allow dialog popup -->\n";
2102
-		print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
2100
+        // A div for the address popup
2101
+        print "\n<!-- A div to allow dialog popup -->\n";
2102
+        print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
2103 2103
 
2104
-		print "</body>\n";
2105
-		print "</html>\n";
2106
-	}
2104
+        print "</body>\n";
2105
+        print "</html>\n";
2106
+    }
2107 2107
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/margin/index.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -25,11 +25,11 @@
 block discarded – undo
25 25
 require '../main.inc.php';
26 26
 
27 27
 if ($user->rights->produit->lire) {
28
-	$page = 'productMargins';
28
+    $page = 'productMargins';
29 29
 } elseif ($user->rights->societe->lire) {
30
-	$page = 'customerMargins';
30
+    $page = 'customerMargins';
31 31
 } else {
32
-	$page = 'agentMargins';
32
+    $page = 'agentMargins';
33 33
 }
34 34
 
35 35
 header('Location: '.dol_buildpath('/margin/'.$page.'.php', 1));
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.form.class.php 1 patch
Indentation   +6816 added lines, -6816 removed lines patch added patch discarded remove patch
@@ -51,564 +51,564 @@  discard block
 block discarded – undo
51 51
  */
52 52
 class Form
53 53
 {
54
-	/**
54
+    /**
55 55
      * @var DoliDB Database handler.
56 56
      */
57 57
     public $db;
58 58
 
59
-	/**
60
-	 * @var string Error code (or message)
61
-	 */
62
-	public $error='';
59
+    /**
60
+     * @var string Error code (or message)
61
+     */
62
+    public $error='';
63 63
 
64 64
     /**
65 65
      * @var string[]    Array of error strings
66 66
      */
67 67
     public $errors = array();
68 68
 
69
-	public $num;
70
-
71
-	// Cache arrays
72
-	public $cache_types_paiements=array();
73
-	public $cache_conditions_paiements=array();
74
-	public $cache_availability=array();
75
-	public $cache_demand_reason=array();
76
-	public $cache_types_fees=array();
77
-	public $cache_vatrates=array();
78
-
79
-
80
-	/**
81
-	 * Constructor
82
-	 *
83
-	 * @param		DoliDB		$db      Database handler
84
-	 */
85
-	public function __construct($db)
86
-	{
87
-		$this->db = $db;
88
-	}
89
-
90
-	/**
91
-	 * Output key field for an editable field
92
-	 *
93
-	 * @param   string	$text			Text of label or key to translate
94
-	 * @param   string	$htmlname		Name of select field ('edit' prefix will be added)
95
-	 * @param   string	$preselected    Value to show/edit (not used in this function)
96
-	 * @param	object	$object			Object
97
-	 * @param	boolean	$perm			Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
98
-	 * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
99
-	 * @param	string	$moreparam		More param to add on a href URL.
100
-	 * @param   int     $fieldrequired  1 if we want to show field as mandatory using the "fieldrequired" CSS.
101
-	 * @param   int     $notabletag     1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
102
-	 * @param	string	$paramid		Key of parameter for id ('id', 'socid')
103
-	 * @return	string					HTML edit field
104
-	 */
105
-	function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0, $paramid='id')
106
-	{
107
-		global $conf,$langs;
108
-
109
-		$ret='';
110
-
111
-		// TODO change for compatibility
112
-		if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))
113
-		{
114
-			if (! empty($perm))
115
-			{
116
-				$tmp=explode(':',$typeofdata);
117
-				$ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
118
-				if ($fieldrequired) $ret.='<span class="fieldrequired">';
119
-				$ret.= $langs->trans($text);
120
-				if ($fieldrequired) $ret.='</span>';
121
-				$ret.= '</div>'."\n";
122
-			}
123
-			else
124
-			{
125
-				if ($fieldrequired) $ret.='<span class="fieldrequired">';
126
-				$ret.= $langs->trans($text);
127
-				if ($fieldrequired) $ret.='</span>';
128
-			}
129
-		}
130
-		else
131
-		{
132
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
133
-			if ($fieldrequired) $ret.='<span class="fieldrequired">';
134
-			$ret.=$langs->trans($text);
135
-			if ($fieldrequired) $ret.='</span>';
136
-			if (! empty($notabletag)) $ret.=' ';
137
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
138
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align="right">';
139
-			if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
140
-			if (! empty($notabletag) && $notabletag == 1) $ret.=' : ';
141
-			if (! empty($notabletag) && $notabletag == 3) $ret.=' ';
142
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
143
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
144
-		}
145
-
146
-		return $ret;
147
-	}
148
-
149
-	/**
150
-	 * Output value of a field for an editable field
151
-	 *
152
-	 * @param	string	$text			Text of label (not used in this function)
153
-	 * @param	string	$htmlname		Name of select field
154
-	 * @param	string	$value			Value to show/edit
155
-	 * @param	object	$object			Object
156
-	 * @param	boolean	$perm			Permission to allow button to edit parameter
157
-	 * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...)
158
-	 * @param	string	$editvalue		When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value
159
-	 * @param	object	$extObject		External object
160
-	 * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
161
-	 * @param	string	$moreparam		More param to add on the form action href URL
162
-	 * @param   int     $notabletag     Do no output table tags
163
-	 * @param	string	$formatfunc		Call a specific function to output field
164
-	 * @param	string	$paramid		Key of parameter for id ('id', 'socid')
165
-	 * @return  string					HTML edit field
166
-	 */
167
-	function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='', $paramid='id')
168
-	{
169
-		global $conf,$langs,$db;
170
-
171
-		$ret='';
172
-
173
-		// Check parameters
174
-		if (empty($typeofdata)) return 'ErrorBadParameter';
175
-
176
-		// When option to edit inline is activated
177
-		if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
178
-		{
179
-			$ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
180
-		}
181
-		else
182
-		{
183
-			if (GETPOST('action','aZ09') == 'edit'.$htmlname)
184
-			{
185
-				$ret.="\n";
186
-				$ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam?'?'.$moreparam:'').'">';
187
-				$ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
188
-				$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
189
-				$ret.='<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
190
-				if (empty($notabletag)) $ret.='<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
191
-				if (empty($notabletag)) $ret.='<tr><td>';
192
-				if (preg_match('/^(string|email)/',$typeofdata))
193
-				{
194
-					$tmp=explode(':',$typeofdata);
195
-					$ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
196
-				}
197
-				else if (preg_match('/^(numeric|amount)/',$typeofdata))
198
-				{
199
-					$tmp=explode(':',$typeofdata);
200
-					$valuetoshow=price2num($editvalue?$editvalue:$value);
201
-					$ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
202
-				}
203
-				else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
204
-				{
205
-					$tmp=explode(':',$typeofdata);
206
-					$cols=$tmp[2];
207
-					$morealt='';
208
-					if (preg_match('/%/',$cols))
209
-					{
210
-						$morealt=' style="width: '.$cols.'"';
211
-						$cols='';
212
-					}
69
+    public $num;
213 70
 
214
-					$valuetoshow = ($editvalue?$editvalue:$value);
215
-
216
-					$ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'"'.($cols?' cols="'.$cols.'"':'class="quatrevingtpercent"').$morealt.'">';
217
-					$ret.=dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
218
-					$ret.='</textarea>';
219
-				}
220
-				else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
221
-				{
222
-					$ret.=$this->selectDate($value,$htmlname,0,0,1,'form'.$htmlname,1,0);
223
-				}
224
-				else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
225
-				{
226
-					$ret.=$this->selectDate($value,$htmlname,1,1,1,'form'.$htmlname,1,0);
227
-				}
228
-				else if (preg_match('/^select;/',$typeofdata))
229
-				{
230
-					 $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
231
-					 foreach($arraydata as $val)
232
-					 {
233
-						 $tmp=explode(':',$val);
234
-						 $arraylist[$tmp[0]]=$tmp[1];
235
-					 }
236
-					 $ret.=$this->selectarray($htmlname,$arraylist,$value);
237
-				}
238
-				else if (preg_match('/^ckeditor/',$typeofdata))
239
-				{
240
-					$tmp=explode(':',$typeofdata);		// Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols
241
-					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
242
-					$doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));
243
-					$ret.=$doleditor->Create(1);
244
-				}
245
-				if (empty($notabletag)) $ret.='</td>';
246
-
247
-				if (empty($notabletag)) $ret.='<td align="left">';
248
-				//else $ret.='<div class="clearboth"></div>';
249
-			   	$ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="modify" value="'.$langs->trans("Modify").'">';
250
-			   	if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'."\n";
251
-			   	$ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
252
-			   	if (empty($notabletag)) $ret.='</td>';
253
-
254
-			   	if (empty($notabletag)) $ret.='</tr></table>'."\n";
255
-				$ret.='</form>'."\n";
256
-			}
257
-			else
258
-			{
259
-				if (preg_match('/^(email)/',$typeofdata))              $ret.=dol_print_email($value,0,0,0,0,1);
260
-				elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
261
-				elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))  $ret.=dol_htmlentitiesbr($value);
262
-				elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
263
-				elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
264
-				else if (preg_match('/^select;/',$typeofdata))
265
-				{
266
-					$arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
267
-					foreach($arraydata as $val)
268
-					{
269
-						$tmp=explode(':',$val);
270
-						$arraylist[$tmp[0]]=$tmp[1];
271
-					}
272
-					$ret.=$arraylist[$value];
273
-				}
274
-				else if (preg_match('/^ckeditor/',$typeofdata))
275
-				{
276
-					$tmpcontent=dol_htmlentitiesbr($value);
277
-					if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
278
-					{
279
-						$firstline=preg_replace('/<br>.*/','',$tmpcontent);
280
-						$firstline=preg_replace('/[\n\r].*/','',$firstline);
281
-						$tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
282
-					}
283
-					$ret.=$tmpcontent;
284
-				}
285
-				else $ret.=$value;
286
-
287
-				if ($formatfunc && method_exists($object, $formatfunc))
288
-				{
289
-					$ret=$object->$formatfunc($ret);
290
-				}
291
-			}
292
-		}
293
-		return $ret;
294
-	}
295
-
296
-	/**
297
-	 * Output edit in place form
298
-	 *
299
-	 * @param	object	$object			Object
300
-	 * @param	string	$value			Value to show/edit
301
-	 * @param	string	$htmlname		DIV ID (field name)
302
-	 * @param	int		$condition		Condition to edit
303
-	 * @param	string	$inputType		Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx')
304
-	 * @param	string	$editvalue		When in edit mode, use this value as $value instead of value
305
-	 * @param	object	$extObject		External object
306
-	 * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
307
-	 * @return	string   		      	HTML edit in place
308
-	 */
309
-	private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
310
-	{
311
-		global $conf;
312
-
313
-		$out='';
314
-
315
-		// Check parameters
316
-		if (preg_match('/^text/',$inputType)) $value = dol_nl2br($value);
317
-		else if (preg_match('/^numeric/',$inputType)) $value = price($value);
318
-		else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
319
-
320
-		if ($condition)
321
-		{
322
-			$element		= false;
323
-			$table_element	= false;
324
-			$fk_element		= false;
325
-			$loadmethod		= false;
326
-			$savemethod		= false;
327
-			$ext_element	= false;
328
-			$button_only	= false;
329
-			$inputOption    = '';
330
-
331
-			if (is_object($object))
332
-			{
333
-				$element = $object->element;
334
-				$table_element = $object->table_element;
335
-				$fk_element = $object->id;
336
-			}
337
-
338
-			if (is_object($extObject))
339
-			{
340
-				$ext_element = $extObject->element;
341
-			}
342
-
343
-			if (preg_match('/^(string|email|numeric)/',$inputType))
344
-			{
345
-				$tmp=explode(':',$inputType);
346
-				$inputType=$tmp[0];
347
-				if (! empty($tmp[1])) $inputOption=$tmp[1];
348
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
349
-				$out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
350
-			}
351
-			else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
352
-			{
353
-				$tmp=explode(':',$inputType);
354
-				$inputType=$tmp[0];
355
-				if (! empty($tmp[1])) $inputOption=$tmp[1];
356
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
357
-
358
-				$out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
359
-			}
360
-			else if (preg_match('/^(select|autocomplete)/',$inputType))
361
-			{
362
-				$tmp=explode(':',$inputType);
363
-				$inputType=$tmp[0]; $loadmethod=$tmp[1];
364
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
365
-				if (! empty($tmp[3])) $button_only=true;
366
-			}
367
-			else if (preg_match('/^textarea/',$inputType))
368
-			{
369
-				$tmp=explode(':',$inputType);
370
-				$inputType=$tmp[0];
371
-				$rows=(empty($tmp[1])?'8':$tmp[1]);
372
-				$cols=(empty($tmp[2])?'80':$tmp[2]);
373
-			}
374
-			else if (preg_match('/^ckeditor/',$inputType))
375
-			{
376
-				$tmp=explode(':',$inputType);
377
-				$inputType=$tmp[0]; $toolbar=$tmp[1];
378
-				if (! empty($tmp[2])) $width=$tmp[2];
379
-				if (! empty($tmp[3])) $heigth=$tmp[3];
380
-				if (! empty($tmp[4])) $savemethod=$tmp[4];
381
-
382
-				if (! empty($conf->fckeditor->enabled))
383
-				{
384
-					$out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
385
-				}
386
-				else
387
-				{
388
-					$inputType = 'textarea';
389
-				}
390
-			}
391
-
392
-			$out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
393
-			$out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
394
-			$out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
395
-			$out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
396
-			if (! empty($savemethod))	$out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
397
-			if (! empty($ext_element))	$out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
398
-			if (! empty($custommsg))
399
-			{
400
-				if (is_array($custommsg))
401
-				{
402
-					if (!empty($custommsg['success']))
403
-						$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
404
-					if (!empty($custommsg['error']))
405
-						$out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
406
-				}
407
-				else
408
-					$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
409
-			}
410
-			if ($inputType == 'textarea') {
411
-				$out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
412
-				$out.= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
413
-			}
414
-			$out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
415
-			$out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
416
-		}
417
-		else
418
-		{
419
-			$out = $value;
420
-		}
421
-
422
-		return $out;
423
-	}
424
-
425
-	/**
426
-	 *	Show a text and picto with tooltip on text or picto.
427
-	 *  Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
428
-	 *
429
-	 *	@param	string		$text				Text to show
430
-	 *	@param	string		$htmltext			HTML content of tooltip. Must be HTML/UTF8 encoded.
431
-	 *	@param	int			$tooltipon			1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
432
-	 *	@param	int			$direction			-1=image is before, 0=no image, 1=image is after
433
-	 *	@param	string		$img				Html code for image (use img_xxx() function to get it)
434
-	 *	@param	string		$extracss			Add a CSS style to td tags
435
-	 *	@param	int			$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
436
-	 *	@param	string		$incbefore			Include code before the text
437
-	 *	@param	int			$noencodehtmltext	Do not encode into html entity the htmltext
438
-	 *  @param  string      $tooltiptrigger		''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
439
-	 *  @param	int			$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
440
-	 *	@return	string							Code html du tooltip (texte+picto)
441
-	 *	@see	Use function textwithpicto if you can.
442
-	 *  TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
443
-	 */
444
-	function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='', $forcenowrap=0)
445
-	{
446
-		global $conf;
447
-
448
-		if ($incbefore) $text = $incbefore.$text;
449
-		if (! $htmltext) return $text;
450
-
451
-		$tag='td';
452
-		if ($notabs == 2) $tag='div';
453
-		if ($notabs == 3) $tag='span';
454
-		// Sanitize tooltip
455
-		$htmltext=str_replace("\\","\\\\",$htmltext);
456
-		$htmltext=str_replace("\r","",$htmltext);
457
-		$htmltext=str_replace("\n","",$htmltext);
458
-
459
-		$extrastyle='';
460
-		if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }
461
-		if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }
462
-
463
-		$classfortooltip='classfortooltip';
464
-
465
-		$s='';$textfordialog='';
466
-
467
-		if ($tooltiptrigger == '')
468
-		{
469
-			$htmltext=str_replace('"',"&quot;",$htmltext);
470
-		}
471
-		else
472
-		{
473
-			$classfortooltip='classfortooltiponclick';
474
-			$textfordialog.='<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
475
-		}
476
-		if ($tooltipon == 2 || $tooltipon == 3)
477
-		{
478
-			$paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"';
479
-			if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
480
-			else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
481
-		}
482
-		else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
483
-		if ($tooltipon == 1 || $tooltipon == 3)
484
-		{
485
-			$paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" ';
486
-			if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
487
-			else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
488
-		}
489
-		else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
490
-		if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
491
-		elseif ($notabs == 2) $s.='<div class="inline-block'.($forcenowrap?' nowrap':'').'">';
492
-		// Define value if value is before
493
-		if ($direction < 0) {
494
-			$s.='<'.$tag.$paramfortooltipimg;
495
-			if ($tag == 'td') {
496
-				$s .= ' valign="top" width="14"';
497
-			}
498
-			$s.= '>'.$textfordialog.$img.'</'.$tag.'>';
499
-		}
500
-		// Use another method to help avoid having a space in value in order to use this value with jquery
501
-		// Define label
502
-		if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
503
-		// Define value if value is after
504
-		if ($direction > 0) {
505
-			$s.='<'.$tag.$paramfortooltipimg;
506
-			if ($tag == 'td') $s .= ' valign="middle" width="14"';
507
-			$s.= '>'.$textfordialog.$img.'</'.$tag.'>';
508
-		}
509
-		if (empty($notabs)) $s.='</tr></table>';
510
-		elseif ($notabs == 2) $s.='</div>';
511
-
512
-		return $s;
513
-	}
514
-
515
-	/**
516
-	 *	Show a text with a picto and a tooltip on picto
517
-	 *
518
-	 *	@param	string	$text				Text to show
519
-	 *	@param  string	$htmltext	     	Content of tooltip
520
-	 *	@param	int		$direction			1=Icon is after text, -1=Icon is before text, 0=no icon
521
-	 * 	@param	string	$type				Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath
522
-	 *  @param  string	$extracss           Add a CSS style to td, div or span tag
523
-	 *  @param  int		$noencodehtmltext   Do not encode into html entity the htmltext
524
-	 *  @param	int		$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
525
-	 *  @param  string  $tooltiptrigger     ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
526
-	 *  @param	int		$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
527
-	 * 	@return	string						HTML code of text, picto, tooltip
528
-	 */
529
-	function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='', $forcenowrap=0)
530
-	{
531
-		global $conf, $langs;
532
-
533
-		$alt = '';
534
-		if ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv("ClickToShowHelp");
535
-
536
-		//For backwards compatibility
537
-		if ($type == '0') $type = 'info';
538
-		elseif ($type == '1') $type = 'help';
539
-
540
-		// If info or help with no javascript, show only text
541
-		if (empty($conf->use_javascript_ajax))
542
-		{
543
-			if ($type == 'info' || $type == 'help')	return $text;
544
-			else
545
-			{
546
-				$alt = $htmltext;
547
-				$htmltext = '';
548
-			}
549
-		}
550
-
551
-		// If info or help with smartphone, show only text (tooltip hover can't works)
552
-		if (! empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
553
-		{
554
-			if ($type == 'info' || $type == 'help') return $text;
555
-		}
556
-		// If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)
557
-		if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
558
-		{
559
-			if ($type == 'info' || $type == 'help') return $text;
560
-		}
561
-
562
-		if ($type == 'info') $img = img_help(0, $alt);
563
-		elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
564
-		elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
565
-		elseif ($type == 'admin') $img = img_picto($alt, 'star');
566
-		elseif ($type == 'warning') $img = img_warning($alt);
567
-		else $img = img_picto($alt, $type);
568
-
569
-		return $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && ! $img)?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
570
-	}
571
-
572
-	/**
573
-	 * Generate select HTML to choose massaction
574
-	 *
575
-	 * @param	string	$selected		Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
576
-	 * @param	int		$arrayofaction	array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
577
-	 * @param   int     $alwaysvisible  1=select button always visible
578
-	 * @return	string					Select list
579
-	 */
580
-	function selectMassAction($selected, $arrayofaction, $alwaysvisible=0)
581
-	{
582
-		global $conf,$langs,$hookmanager;
583
-
584
-		if (count($arrayofaction) == 0) return;
585
-
586
-		$disabled=0;
587
-		$ret='<div class="centpercent center">';
588
-		$ret.='<select class="flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
589
-
590
-		// Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks.
591
-		$parameters=array();
592
-		$reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters);    // Note that $action and $object may have been modified by hook
593
-		if (empty($reshook))
594
-		{
595
-			$ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
596
-			foreach($arrayofaction as $code => $label)
597
-			{
598
-				$ret.='<option value="'.$code.'"'.($disabled?' disabled="disabled"':'').'>'.$label.'</option>';
599
-			}
600
-		}
601
-		$ret.=$hookmanager->resPrint;
602
-
603
-		$ret.='</select>';
604
-		// Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button
605
-		$ret.='<input type="submit" name="confirmmassactioninvisible" style="display: none" tabindex="-1">';	// Hidden button BEFORE so it is the one used when we submit with ENTER.
606
-		$ret.='<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
607
-		$ret.='</div>';
608
-
609
-		if (! empty($conf->use_javascript_ajax))
610
-		{
611
-			$ret.='<!-- JS CODE TO ENABLE mass action select -->
71
+    // Cache arrays
72
+    public $cache_types_paiements=array();
73
+    public $cache_conditions_paiements=array();
74
+    public $cache_availability=array();
75
+    public $cache_demand_reason=array();
76
+    public $cache_types_fees=array();
77
+    public $cache_vatrates=array();
78
+
79
+
80
+    /**
81
+     * Constructor
82
+     *
83
+     * @param		DoliDB		$db      Database handler
84
+     */
85
+    public function __construct($db)
86
+    {
87
+        $this->db = $db;
88
+    }
89
+
90
+    /**
91
+     * Output key field for an editable field
92
+     *
93
+     * @param   string	$text			Text of label or key to translate
94
+     * @param   string	$htmlname		Name of select field ('edit' prefix will be added)
95
+     * @param   string	$preselected    Value to show/edit (not used in this function)
96
+     * @param	object	$object			Object
97
+     * @param	boolean	$perm			Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
98
+     * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
99
+     * @param	string	$moreparam		More param to add on a href URL.
100
+     * @param   int     $fieldrequired  1 if we want to show field as mandatory using the "fieldrequired" CSS.
101
+     * @param   int     $notabletag     1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
102
+     * @param	string	$paramid		Key of parameter for id ('id', 'socid')
103
+     * @return	string					HTML edit field
104
+     */
105
+    function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0, $paramid='id')
106
+    {
107
+        global $conf,$langs;
108
+
109
+        $ret='';
110
+
111
+        // TODO change for compatibility
112
+        if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))
113
+        {
114
+            if (! empty($perm))
115
+            {
116
+                $tmp=explode(':',$typeofdata);
117
+                $ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
118
+                if ($fieldrequired) $ret.='<span class="fieldrequired">';
119
+                $ret.= $langs->trans($text);
120
+                if ($fieldrequired) $ret.='</span>';
121
+                $ret.= '</div>'."\n";
122
+            }
123
+            else
124
+            {
125
+                if ($fieldrequired) $ret.='<span class="fieldrequired">';
126
+                $ret.= $langs->trans($text);
127
+                if ($fieldrequired) $ret.='</span>';
128
+            }
129
+        }
130
+        else
131
+        {
132
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
133
+            if ($fieldrequired) $ret.='<span class="fieldrequired">';
134
+            $ret.=$langs->trans($text);
135
+            if ($fieldrequired) $ret.='</span>';
136
+            if (! empty($notabletag)) $ret.=' ';
137
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
138
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align="right">';
139
+            if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
140
+            if (! empty($notabletag) && $notabletag == 1) $ret.=' : ';
141
+            if (! empty($notabletag) && $notabletag == 3) $ret.=' ';
142
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
143
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
144
+        }
145
+
146
+        return $ret;
147
+    }
148
+
149
+    /**
150
+     * Output value of a field for an editable field
151
+     *
152
+     * @param	string	$text			Text of label (not used in this function)
153
+     * @param	string	$htmlname		Name of select field
154
+     * @param	string	$value			Value to show/edit
155
+     * @param	object	$object			Object
156
+     * @param	boolean	$perm			Permission to allow button to edit parameter
157
+     * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...)
158
+     * @param	string	$editvalue		When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value
159
+     * @param	object	$extObject		External object
160
+     * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
161
+     * @param	string	$moreparam		More param to add on the form action href URL
162
+     * @param   int     $notabletag     Do no output table tags
163
+     * @param	string	$formatfunc		Call a specific function to output field
164
+     * @param	string	$paramid		Key of parameter for id ('id', 'socid')
165
+     * @return  string					HTML edit field
166
+     */
167
+    function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='', $paramid='id')
168
+    {
169
+        global $conf,$langs,$db;
170
+
171
+        $ret='';
172
+
173
+        // Check parameters
174
+        if (empty($typeofdata)) return 'ErrorBadParameter';
175
+
176
+        // When option to edit inline is activated
177
+        if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
178
+        {
179
+            $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
180
+        }
181
+        else
182
+        {
183
+            if (GETPOST('action','aZ09') == 'edit'.$htmlname)
184
+            {
185
+                $ret.="\n";
186
+                $ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam?'?'.$moreparam:'').'">';
187
+                $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
188
+                $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
189
+                $ret.='<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
190
+                if (empty($notabletag)) $ret.='<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
191
+                if (empty($notabletag)) $ret.='<tr><td>';
192
+                if (preg_match('/^(string|email)/',$typeofdata))
193
+                {
194
+                    $tmp=explode(':',$typeofdata);
195
+                    $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
196
+                }
197
+                else if (preg_match('/^(numeric|amount)/',$typeofdata))
198
+                {
199
+                    $tmp=explode(':',$typeofdata);
200
+                    $valuetoshow=price2num($editvalue?$editvalue:$value);
201
+                    $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
202
+                }
203
+                else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
204
+                {
205
+                    $tmp=explode(':',$typeofdata);
206
+                    $cols=$tmp[2];
207
+                    $morealt='';
208
+                    if (preg_match('/%/',$cols))
209
+                    {
210
+                        $morealt=' style="width: '.$cols.'"';
211
+                        $cols='';
212
+                    }
213
+
214
+                    $valuetoshow = ($editvalue?$editvalue:$value);
215
+
216
+                    $ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'"'.($cols?' cols="'.$cols.'"':'class="quatrevingtpercent"').$morealt.'">';
217
+                    $ret.=dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
218
+                    $ret.='</textarea>';
219
+                }
220
+                else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
221
+                {
222
+                    $ret.=$this->selectDate($value,$htmlname,0,0,1,'form'.$htmlname,1,0);
223
+                }
224
+                else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
225
+                {
226
+                    $ret.=$this->selectDate($value,$htmlname,1,1,1,'form'.$htmlname,1,0);
227
+                }
228
+                else if (preg_match('/^select;/',$typeofdata))
229
+                {
230
+                        $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
231
+                        foreach($arraydata as $val)
232
+                        {
233
+                            $tmp=explode(':',$val);
234
+                            $arraylist[$tmp[0]]=$tmp[1];
235
+                        }
236
+                        $ret.=$this->selectarray($htmlname,$arraylist,$value);
237
+                }
238
+                else if (preg_match('/^ckeditor/',$typeofdata))
239
+                {
240
+                    $tmp=explode(':',$typeofdata);		// Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols
241
+                    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
242
+                    $doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));
243
+                    $ret.=$doleditor->Create(1);
244
+                }
245
+                if (empty($notabletag)) $ret.='</td>';
246
+
247
+                if (empty($notabletag)) $ret.='<td align="left">';
248
+                //else $ret.='<div class="clearboth"></div>';
249
+                    $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="modify" value="'.$langs->trans("Modify").'">';
250
+                    if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'."\n";
251
+                    $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
252
+                    if (empty($notabletag)) $ret.='</td>';
253
+
254
+                    if (empty($notabletag)) $ret.='</tr></table>'."\n";
255
+                $ret.='</form>'."\n";
256
+            }
257
+            else
258
+            {
259
+                if (preg_match('/^(email)/',$typeofdata))              $ret.=dol_print_email($value,0,0,0,0,1);
260
+                elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
261
+                elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))  $ret.=dol_htmlentitiesbr($value);
262
+                elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
263
+                elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
264
+                else if (preg_match('/^select;/',$typeofdata))
265
+                {
266
+                    $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
267
+                    foreach($arraydata as $val)
268
+                    {
269
+                        $tmp=explode(':',$val);
270
+                        $arraylist[$tmp[0]]=$tmp[1];
271
+                    }
272
+                    $ret.=$arraylist[$value];
273
+                }
274
+                else if (preg_match('/^ckeditor/',$typeofdata))
275
+                {
276
+                    $tmpcontent=dol_htmlentitiesbr($value);
277
+                    if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
278
+                    {
279
+                        $firstline=preg_replace('/<br>.*/','',$tmpcontent);
280
+                        $firstline=preg_replace('/[\n\r].*/','',$firstline);
281
+                        $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
282
+                    }
283
+                    $ret.=$tmpcontent;
284
+                }
285
+                else $ret.=$value;
286
+
287
+                if ($formatfunc && method_exists($object, $formatfunc))
288
+                {
289
+                    $ret=$object->$formatfunc($ret);
290
+                }
291
+            }
292
+        }
293
+        return $ret;
294
+    }
295
+
296
+    /**
297
+     * Output edit in place form
298
+     *
299
+     * @param	object	$object			Object
300
+     * @param	string	$value			Value to show/edit
301
+     * @param	string	$htmlname		DIV ID (field name)
302
+     * @param	int		$condition		Condition to edit
303
+     * @param	string	$inputType		Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx')
304
+     * @param	string	$editvalue		When in edit mode, use this value as $value instead of value
305
+     * @param	object	$extObject		External object
306
+     * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
307
+     * @return	string   		      	HTML edit in place
308
+     */
309
+    private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
310
+    {
311
+        global $conf;
312
+
313
+        $out='';
314
+
315
+        // Check parameters
316
+        if (preg_match('/^text/',$inputType)) $value = dol_nl2br($value);
317
+        else if (preg_match('/^numeric/',$inputType)) $value = price($value);
318
+        else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
319
+
320
+        if ($condition)
321
+        {
322
+            $element		= false;
323
+            $table_element	= false;
324
+            $fk_element		= false;
325
+            $loadmethod		= false;
326
+            $savemethod		= false;
327
+            $ext_element	= false;
328
+            $button_only	= false;
329
+            $inputOption    = '';
330
+
331
+            if (is_object($object))
332
+            {
333
+                $element = $object->element;
334
+                $table_element = $object->table_element;
335
+                $fk_element = $object->id;
336
+            }
337
+
338
+            if (is_object($extObject))
339
+            {
340
+                $ext_element = $extObject->element;
341
+            }
342
+
343
+            if (preg_match('/^(string|email|numeric)/',$inputType))
344
+            {
345
+                $tmp=explode(':',$inputType);
346
+                $inputType=$tmp[0];
347
+                if (! empty($tmp[1])) $inputOption=$tmp[1];
348
+                if (! empty($tmp[2])) $savemethod=$tmp[2];
349
+                $out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
350
+            }
351
+            else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
352
+            {
353
+                $tmp=explode(':',$inputType);
354
+                $inputType=$tmp[0];
355
+                if (! empty($tmp[1])) $inputOption=$tmp[1];
356
+                if (! empty($tmp[2])) $savemethod=$tmp[2];
357
+
358
+                $out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
359
+            }
360
+            else if (preg_match('/^(select|autocomplete)/',$inputType))
361
+            {
362
+                $tmp=explode(':',$inputType);
363
+                $inputType=$tmp[0]; $loadmethod=$tmp[1];
364
+                if (! empty($tmp[2])) $savemethod=$tmp[2];
365
+                if (! empty($tmp[3])) $button_only=true;
366
+            }
367
+            else if (preg_match('/^textarea/',$inputType))
368
+            {
369
+                $tmp=explode(':',$inputType);
370
+                $inputType=$tmp[0];
371
+                $rows=(empty($tmp[1])?'8':$tmp[1]);
372
+                $cols=(empty($tmp[2])?'80':$tmp[2]);
373
+            }
374
+            else if (preg_match('/^ckeditor/',$inputType))
375
+            {
376
+                $tmp=explode(':',$inputType);
377
+                $inputType=$tmp[0]; $toolbar=$tmp[1];
378
+                if (! empty($tmp[2])) $width=$tmp[2];
379
+                if (! empty($tmp[3])) $heigth=$tmp[3];
380
+                if (! empty($tmp[4])) $savemethod=$tmp[4];
381
+
382
+                if (! empty($conf->fckeditor->enabled))
383
+                {
384
+                    $out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
385
+                }
386
+                else
387
+                {
388
+                    $inputType = 'textarea';
389
+                }
390
+            }
391
+
392
+            $out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
393
+            $out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
394
+            $out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
395
+            $out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
396
+            if (! empty($savemethod))	$out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
397
+            if (! empty($ext_element))	$out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
398
+            if (! empty($custommsg))
399
+            {
400
+                if (is_array($custommsg))
401
+                {
402
+                    if (!empty($custommsg['success']))
403
+                        $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
404
+                    if (!empty($custommsg['error']))
405
+                        $out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
406
+                }
407
+                else
408
+                    $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
409
+            }
410
+            if ($inputType == 'textarea') {
411
+                $out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
412
+                $out.= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
413
+            }
414
+            $out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
415
+            $out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
416
+        }
417
+        else
418
+        {
419
+            $out = $value;
420
+        }
421
+
422
+        return $out;
423
+    }
424
+
425
+    /**
426
+     *	Show a text and picto with tooltip on text or picto.
427
+     *  Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
428
+     *
429
+     *	@param	string		$text				Text to show
430
+     *	@param	string		$htmltext			HTML content of tooltip. Must be HTML/UTF8 encoded.
431
+     *	@param	int			$tooltipon			1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
432
+     *	@param	int			$direction			-1=image is before, 0=no image, 1=image is after
433
+     *	@param	string		$img				Html code for image (use img_xxx() function to get it)
434
+     *	@param	string		$extracss			Add a CSS style to td tags
435
+     *	@param	int			$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
436
+     *	@param	string		$incbefore			Include code before the text
437
+     *	@param	int			$noencodehtmltext	Do not encode into html entity the htmltext
438
+     *  @param  string      $tooltiptrigger		''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
439
+     *  @param	int			$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
440
+     *	@return	string							Code html du tooltip (texte+picto)
441
+     *	@see	Use function textwithpicto if you can.
442
+     *  TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
443
+     */
444
+    function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='', $forcenowrap=0)
445
+    {
446
+        global $conf;
447
+
448
+        if ($incbefore) $text = $incbefore.$text;
449
+        if (! $htmltext) return $text;
450
+
451
+        $tag='td';
452
+        if ($notabs == 2) $tag='div';
453
+        if ($notabs == 3) $tag='span';
454
+        // Sanitize tooltip
455
+        $htmltext=str_replace("\\","\\\\",$htmltext);
456
+        $htmltext=str_replace("\r","",$htmltext);
457
+        $htmltext=str_replace("\n","",$htmltext);
458
+
459
+        $extrastyle='';
460
+        if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }
461
+        if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }
462
+
463
+        $classfortooltip='classfortooltip';
464
+
465
+        $s='';$textfordialog='';
466
+
467
+        if ($tooltiptrigger == '')
468
+        {
469
+            $htmltext=str_replace('"',"&quot;",$htmltext);
470
+        }
471
+        else
472
+        {
473
+            $classfortooltip='classfortooltiponclick';
474
+            $textfordialog.='<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
475
+        }
476
+        if ($tooltipon == 2 || $tooltipon == 3)
477
+        {
478
+            $paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"';
479
+            if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
480
+            else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
481
+        }
482
+        else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
483
+        if ($tooltipon == 1 || $tooltipon == 3)
484
+        {
485
+            $paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" ';
486
+            if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
487
+            else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
488
+        }
489
+        else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
490
+        if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
491
+        elseif ($notabs == 2) $s.='<div class="inline-block'.($forcenowrap?' nowrap':'').'">';
492
+        // Define value if value is before
493
+        if ($direction < 0) {
494
+            $s.='<'.$tag.$paramfortooltipimg;
495
+            if ($tag == 'td') {
496
+                $s .= ' valign="top" width="14"';
497
+            }
498
+            $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
499
+        }
500
+        // Use another method to help avoid having a space in value in order to use this value with jquery
501
+        // Define label
502
+        if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
503
+        // Define value if value is after
504
+        if ($direction > 0) {
505
+            $s.='<'.$tag.$paramfortooltipimg;
506
+            if ($tag == 'td') $s .= ' valign="middle" width="14"';
507
+            $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
508
+        }
509
+        if (empty($notabs)) $s.='</tr></table>';
510
+        elseif ($notabs == 2) $s.='</div>';
511
+
512
+        return $s;
513
+    }
514
+
515
+    /**
516
+     *	Show a text with a picto and a tooltip on picto
517
+     *
518
+     *	@param	string	$text				Text to show
519
+     *	@param  string	$htmltext	     	Content of tooltip
520
+     *	@param	int		$direction			1=Icon is after text, -1=Icon is before text, 0=no icon
521
+     * 	@param	string	$type				Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath
522
+     *  @param  string	$extracss           Add a CSS style to td, div or span tag
523
+     *  @param  int		$noencodehtmltext   Do not encode into html entity the htmltext
524
+     *  @param	int		$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
525
+     *  @param  string  $tooltiptrigger     ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
526
+     *  @param	int		$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
527
+     * 	@return	string						HTML code of text, picto, tooltip
528
+     */
529
+    function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='', $forcenowrap=0)
530
+    {
531
+        global $conf, $langs;
532
+
533
+        $alt = '';
534
+        if ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv("ClickToShowHelp");
535
+
536
+        //For backwards compatibility
537
+        if ($type == '0') $type = 'info';
538
+        elseif ($type == '1') $type = 'help';
539
+
540
+        // If info or help with no javascript, show only text
541
+        if (empty($conf->use_javascript_ajax))
542
+        {
543
+            if ($type == 'info' || $type == 'help')	return $text;
544
+            else
545
+            {
546
+                $alt = $htmltext;
547
+                $htmltext = '';
548
+            }
549
+        }
550
+
551
+        // If info or help with smartphone, show only text (tooltip hover can't works)
552
+        if (! empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
553
+        {
554
+            if ($type == 'info' || $type == 'help') return $text;
555
+        }
556
+        // If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)
557
+        if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
558
+        {
559
+            if ($type == 'info' || $type == 'help') return $text;
560
+        }
561
+
562
+        if ($type == 'info') $img = img_help(0, $alt);
563
+        elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
564
+        elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
565
+        elseif ($type == 'admin') $img = img_picto($alt, 'star');
566
+        elseif ($type == 'warning') $img = img_warning($alt);
567
+        else $img = img_picto($alt, $type);
568
+
569
+        return $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && ! $img)?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
570
+    }
571
+
572
+    /**
573
+     * Generate select HTML to choose massaction
574
+     *
575
+     * @param	string	$selected		Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
576
+     * @param	int		$arrayofaction	array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
577
+     * @param   int     $alwaysvisible  1=select button always visible
578
+     * @return	string					Select list
579
+     */
580
+    function selectMassAction($selected, $arrayofaction, $alwaysvisible=0)
581
+    {
582
+        global $conf,$langs,$hookmanager;
583
+
584
+        if (count($arrayofaction) == 0) return;
585
+
586
+        $disabled=0;
587
+        $ret='<div class="centpercent center">';
588
+        $ret.='<select class="flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
589
+
590
+        // Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks.
591
+        $parameters=array();
592
+        $reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters);    // Note that $action and $object may have been modified by hook
593
+        if (empty($reshook))
594
+        {
595
+            $ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
596
+            foreach($arrayofaction as $code => $label)
597
+            {
598
+                $ret.='<option value="'.$code.'"'.($disabled?' disabled="disabled"':'').'>'.$label.'</option>';
599
+            }
600
+        }
601
+        $ret.=$hookmanager->resPrint;
602
+
603
+        $ret.='</select>';
604
+        // Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button
605
+        $ret.='<input type="submit" name="confirmmassactioninvisible" style="display: none" tabindex="-1">';	// Hidden button BEFORE so it is the one used when we submit with ENTER.
606
+        $ret.='<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
607
+        $ret.='</div>';
608
+
609
+        if (! empty($conf->use_javascript_ajax))
610
+        {
611
+            $ret.='<!-- JS CODE TO ENABLE mass action select -->
612 612
     		<script type="text/javascript">
613 613
         		function initCheckForSelect(mode)	/* mode is 0 during init of page or click all, 1 when we click on 1 checkbox */
614 614
         		{
@@ -657,1266 +657,1266 @@  discard block
 block discarded – undo
657 657
         	});
658 658
     		</script>
659 659
         	';
660
-		}
660
+        }
661 661
 
662
-		return $ret;
663
-	}
662
+        return $ret;
663
+    }
664 664
 
665 665
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
666
-	/**
667
-	 *  Return combo list of activated countries, into language of user
668
-	 *
669
-	 *  @param	string	$selected       	Id or Code or Label of preselected country
670
-	 *  @param  string	$htmlname       	Name of html select object
671
-	 *  @param  string	$htmloption     	Options html on select object
672
-	 *  @param	integer	$maxlength			Max length for labels (0=no limit)
673
-	 *  @param	string	$morecss			More css class
674
-	 *  @param	string	$usecodeaskey		''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
675
-	 *  @param	int		$showempty			Show empty choice
676
-	 *  @param	int		$disablefavorites	1=Disable favorites,
677
-	 *  @param	int		$addspecialentries	1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
678
-	 *  @return string           			HTML string with select
679
-	 */
680
-	function select_country($selected='', $htmlname='country_id', $htmloption='', $maxlength=0, $morecss='minwidth300', $usecodeaskey='', $showempty=1, $disablefavorites=0, $addspecialentries=0)
681
-	{
666
+    /**
667
+     *  Return combo list of activated countries, into language of user
668
+     *
669
+     *  @param	string	$selected       	Id or Code or Label of preselected country
670
+     *  @param  string	$htmlname       	Name of html select object
671
+     *  @param  string	$htmloption     	Options html on select object
672
+     *  @param	integer	$maxlength			Max length for labels (0=no limit)
673
+     *  @param	string	$morecss			More css class
674
+     *  @param	string	$usecodeaskey		''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
675
+     *  @param	int		$showempty			Show empty choice
676
+     *  @param	int		$disablefavorites	1=Disable favorites,
677
+     *  @param	int		$addspecialentries	1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
678
+     *  @return string           			HTML string with select
679
+     */
680
+    function select_country($selected='', $htmlname='country_id', $htmloption='', $maxlength=0, $morecss='minwidth300', $usecodeaskey='', $showempty=1, $disablefavorites=0, $addspecialentries=0)
681
+    {
682 682
         // phpcs:enable
683
-		global $conf,$langs,$mysoc;
684
-
685
-		$langs->load("dict");
686
-
687
-		$out='';
688
-		$countryArray=array();
689
-		$favorite=array();
690
-		$label=array();
691
-		$atleastonefavorite=0;
692
-
693
-		$sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
694
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_country";
695
-		$sql.= " WHERE active > 0";
696
-		//$sql.= " ORDER BY code ASC";
697
-
698
-		dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
699
-		$resql=$this->db->query($sql);
700
-		if ($resql)
701
-		{
702
-			$out.= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" '.$htmloption.'>';
703
-			$num = $this->db->num_rows($resql);
704
-			$i = 0;
705
-			if ($num)
706
-			{
707
-				$foundselected=false;
708
-
709
-				while ($i < $num)
710
-				{
711
-					$obj = $this->db->fetch_object($resql);
712
-					$countryArray[$i]['rowid'] 		= $obj->rowid;
713
-					$countryArray[$i]['code_iso'] 	= $obj->code_iso;
714
-					$countryArray[$i]['code_iso3'] 	= $obj->code_iso3;
715
-					$countryArray[$i]['label']		= ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:''));
716
-					$countryArray[$i]['favorite']   = $obj->favorite;
717
-					$favorite[$i]					= $obj->favorite;
718
-					$label[$i] = dol_string_unaccent($countryArray[$i]['label']);
719
-					$i++;
720
-				}
721
-
722
-				if (empty($disablefavorites)) array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
723
-				else $countryArray = dol_sort_array($countryArray, 'label');
724
-
725
-				if ($showempty)
726
-				{
727
-					$out.='<option value="">&nbsp;</option>'."\n";
728
-				}
729
-
730
-				if ($addspecialentries)	// Add dedicated entries for groups of countries
731
-				{
732
-					//if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
733
-					$out.= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
734
-					$out.= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
735
-					if ($mysoc->isInEEC()) $out.= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
736
-					$out.= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
737
-					$out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
738
-				}
739
-
740
-				foreach ($countryArray as $row)
741
-				{
742
-					//if (empty($showempty) && empty($row['rowid'])) continue;
743
-					if (empty($row['rowid'])) continue;
744
-
745
-					if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
746
-					if (empty($row['favorite']) && $atleastonefavorite)
747
-					{
748
-						$atleastonefavorite=0;
749
-						$out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
750
-					}
751
-					if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )
752
-					{
753
-						$foundselected=true;
754
-						$out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'" selected>';
755
-					}
756
-					else
757
-					{
758
-						$out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'">';
759
-					}
760
-					if ($row['label']) $out.= dol_trunc($row['label'],$maxlength,'middle');
761
-					else $out.= '&nbsp;';
762
-					if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
763
-					$out.= '</option>';
764
-				}
765
-			}
766
-			$out.= '</select>';
767
-		}
768
-		else
769
-		{
770
-			dol_print_error($this->db);
771
-		}
772
-
773
-		// Make select dynamic
774
-		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
775
-		$out .= ajax_combobox('select'.$htmlname);
776
-
777
-		return $out;
778
-	}
683
+        global $conf,$langs,$mysoc;
684
+
685
+        $langs->load("dict");
686
+
687
+        $out='';
688
+        $countryArray=array();
689
+        $favorite=array();
690
+        $label=array();
691
+        $atleastonefavorite=0;
692
+
693
+        $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
694
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_country";
695
+        $sql.= " WHERE active > 0";
696
+        //$sql.= " ORDER BY code ASC";
697
+
698
+        dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
699
+        $resql=$this->db->query($sql);
700
+        if ($resql)
701
+        {
702
+            $out.= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" '.$htmloption.'>';
703
+            $num = $this->db->num_rows($resql);
704
+            $i = 0;
705
+            if ($num)
706
+            {
707
+                $foundselected=false;
708
+
709
+                while ($i < $num)
710
+                {
711
+                    $obj = $this->db->fetch_object($resql);
712
+                    $countryArray[$i]['rowid'] 		= $obj->rowid;
713
+                    $countryArray[$i]['code_iso'] 	= $obj->code_iso;
714
+                    $countryArray[$i]['code_iso3'] 	= $obj->code_iso3;
715
+                    $countryArray[$i]['label']		= ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:''));
716
+                    $countryArray[$i]['favorite']   = $obj->favorite;
717
+                    $favorite[$i]					= $obj->favorite;
718
+                    $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
719
+                    $i++;
720
+                }
779 721
 
780
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
781
-	/**
782
-	 *  Return select list of incoterms
783
-	 *
784
-	 *  @param	string	$selected       		Id or Code of preselected incoterm
785
-	 *  @param	string	$location_incoterms     Value of input location
786
-	 *  @param	string	$page       			Defined the form action
787
-	 *  @param  string	$htmlname       		Name of html select object
788
-	 *  @param  string	$htmloption     		Options html on select object
789
-	 * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
790
-	 *  @param	array	$events					Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
791
-	 *  @return string           				HTML string with select and input
792
-	 */
793
-	function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())
794
-	{
795
-        // phpcs:enable
796
-		global $conf,$langs;
797
-
798
-		$langs->load("dict");
799
-
800
-		$out='';
801
-		$incotermArray=array();
802
-
803
-		$sql = "SELECT rowid, code";
804
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms";
805
-		$sql.= " WHERE active > 0";
806
-		$sql.= " ORDER BY code ASC";
807
-
808
-		dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
809
-		$resql=$this->db->query($sql);
810
-		if ($resql)
811
-		{
812
-			if ($conf->use_javascript_ajax && ! $forcecombo)
813
-			{
814
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
815
-				$out .= ajax_combobox($htmlname, $events);
816
-			}
817
-
818
-			if (!empty($page))
819
-			{
820
-				$out .= '<form method="post" action="'.$page.'">';
821
-				$out .= '<input type="hidden" name="action" value="set_incoterms">';
822
-				$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
823
-			}
824
-
825
-			$out.= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
826
-			$out.= '<option value="0">&nbsp;</option>';
827
-			$num = $this->db->num_rows($resql);
828
-			$i = 0;
829
-			if ($num)
830
-			{
831
-				$foundselected=false;
832
-
833
-				while ($i < $num)
834
-				{
835
-					$obj = $this->db->fetch_object($resql);
836
-					$incotermArray[$i]['rowid'] = $obj->rowid;
837
-					$incotermArray[$i]['code'] = $obj->code;
838
-					$i++;
839
-				}
840
-
841
-				foreach ($incotermArray as $row)
842
-				{
843
-					if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
844
-					{
845
-						$out.= '<option value="'.$row['rowid'].'" selected>';
846
-					}
847
-					else
848
-					{
849
-						$out.= '<option value="'.$row['rowid'].'">';
850
-					}
722
+                if (empty($disablefavorites)) array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
723
+                else $countryArray = dol_sort_array($countryArray, 'label');
851 724
 
852
-					if ($row['code']) $out.= $row['code'];
725
+                if ($showempty)
726
+                {
727
+                    $out.='<option value="">&nbsp;</option>'."\n";
728
+                }
853 729
 
854
-					$out.= '</option>';
855
-				}
856
-			}
857
-			$out.= '</select>';
730
+                if ($addspecialentries)	// Add dedicated entries for groups of countries
731
+                {
732
+                    //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
733
+                    $out.= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
734
+                    $out.= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
735
+                    if ($mysoc->isInEEC()) $out.= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
736
+                    $out.= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
737
+                    $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
738
+                }
858 739
 
859
-			$out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
740
+                foreach ($countryArray as $row)
741
+                {
742
+                    //if (empty($showempty) && empty($row['rowid'])) continue;
743
+                    if (empty($row['rowid'])) continue;
860 744
 
861
-			if (!empty($page))
862
-			{
863
-				$out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
864
-			}
865
-		}
866
-		else
867
-		{
868
-			dol_print_error($this->db);
869
-		}
745
+                    if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
746
+                    if (empty($row['favorite']) && $atleastonefavorite)
747
+                    {
748
+                        $atleastonefavorite=0;
749
+                        $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
750
+                    }
751
+                    if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )
752
+                    {
753
+                        $foundselected=true;
754
+                        $out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'" selected>';
755
+                    }
756
+                    else
757
+                    {
758
+                        $out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'">';
759
+                    }
760
+                    if ($row['label']) $out.= dol_trunc($row['label'],$maxlength,'middle');
761
+                    else $out.= '&nbsp;';
762
+                    if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
763
+                    $out.= '</option>';
764
+                }
765
+            }
766
+            $out.= '</select>';
767
+        }
768
+        else
769
+        {
770
+            dol_print_error($this->db);
771
+        }
870 772
 
871
-		return $out;
872
-	}
773
+        // Make select dynamic
774
+        include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
775
+        $out .= ajax_combobox('select'.$htmlname);
873 776
 
874
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
875
-	/**
876
-	 *	Return list of types of lines (product or service)
877
-	 * 	Example: 0=product, 1=service, 9=other (for external module)
878
-	 *
879
-	 *	@param  string	$selected       Preselected type
880
-	 *	@param  string	$htmlname       Name of field in html form
881
-	 * 	@param	int		$showempty		Add an empty field
882
-	 * 	@param	int		$hidetext		Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
883
-	 * 	@param	integer	$forceall		1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service')
884
-	 *  @return	void
885
-	 */
886
-	function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
887
-	{
888
-        // phpcs:enable
889
-		global $db,$langs,$user,$conf;
890
-
891
-		// If product & services are enabled or both disabled.
892
-		if ($forceall == 1 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
893
-		|| (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
894
-		{
895
-			if (empty($hidetext)) print $langs->trans("Type").': ';
896
-			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
897
-			if ($showempty)
898
-			{
899
-				print '<option value="-1"';
900
-				if ($selected == -1) print ' selected';
901
-				print '>&nbsp;</option>';
902
-			}
903
-
904
-			print '<option value="0"';
905
-			if (0 == $selected) print ' selected';
906
-			print '>'.$langs->trans("Product");
907
-
908
-			print '<option value="1"';
909
-			if (1 == $selected) print ' selected';
910
-			print '>'.$langs->trans("Service");
911
-
912
-			print '</select>';
913
-			//if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
914
-		}
915
-		if ((empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled)) || $forceall == 3)
916
-		{
917
-			print $langs->trans("Service");
918
-			print '<input type="hidden" name="'.$htmlname.'" value="1">';
919
-		}
920
-		if ((empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2)
921
-		{
922
-			print $langs->trans("Product");
923
-			print '<input type="hidden" name="'.$htmlname.'" value="0">';
924
-		}
925
-		if ($forceall < 0)	// This should happened only for contracts when both predefined product and service are disabled.
926
-		{
927
-			print '<input type="hidden" name="'.$htmlname.'" value="1">';	// By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1
928
-		}
929
-	}
777
+        return $out;
778
+    }
930 779
 
931 780
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
932
-	/**
933
-	 *	Load into cache cache_types_fees, array of types of fees
934
-	 *
935
-	 *	@return     int             Nb of lines loaded, <0 if KO
936
-	 */
937
-	function load_cache_types_fees()
938
-	{
781
+    /**
782
+     *  Return select list of incoterms
783
+     *
784
+     *  @param	string	$selected       		Id or Code of preselected incoterm
785
+     *  @param	string	$location_incoterms     Value of input location
786
+     *  @param	string	$page       			Defined the form action
787
+     *  @param  string	$htmlname       		Name of html select object
788
+     *  @param  string	$htmloption     		Options html on select object
789
+     * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
790
+     *  @param	array	$events					Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
791
+     *  @return string           				HTML string with select and input
792
+     */
793
+    function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())
794
+    {
939 795
         // phpcs:enable
940
-		global $langs;
941
-
942
-		$num = count($this->cache_types_fees);
943
-		if ($num > 0) return 0;    // Cache already loaded
796
+        global $conf,$langs;
944 797
 
945
-		dol_syslog(__METHOD__, LOG_DEBUG);
798
+        $langs->load("dict");
946 799
 
947
-		$langs->load("trips");
800
+        $out='';
801
+        $incotermArray=array();
948 802
 
949
-		$sql = "SELECT c.code, c.label";
950
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
951
-		$sql.= " WHERE active > 0";
803
+        $sql = "SELECT rowid, code";
804
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms";
805
+        $sql.= " WHERE active > 0";
806
+        $sql.= " ORDER BY code ASC";
952 807
 
953
-		$resql=$this->db->query($sql);
954
-		if ($resql)
955
-		{
956
-			$num = $this->db->num_rows($resql);
957
-			$i = 0;
808
+        dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
809
+        $resql=$this->db->query($sql);
810
+        if ($resql)
811
+        {
812
+            if ($conf->use_javascript_ajax && ! $forcecombo)
813
+            {
814
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
815
+                $out .= ajax_combobox($htmlname, $events);
816
+            }
958 817
 
959
-			while ($i < $num)
960
-			{
961
-				$obj = $this->db->fetch_object($resql);
818
+            if (!empty($page))
819
+            {
820
+                $out .= '<form method="post" action="'.$page.'">';
821
+                $out .= '<input type="hidden" name="action" value="set_incoterms">';
822
+                $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
823
+            }
962 824
 
963
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
964
-				$label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
965
-				$this->cache_types_fees[$obj->code] = $label;
966
-				$i++;
967
-			}
825
+            $out.= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
826
+            $out.= '<option value="0">&nbsp;</option>';
827
+            $num = $this->db->num_rows($resql);
828
+            $i = 0;
829
+            if ($num)
830
+            {
831
+                $foundselected=false;
832
+
833
+                while ($i < $num)
834
+                {
835
+                    $obj = $this->db->fetch_object($resql);
836
+                    $incotermArray[$i]['rowid'] = $obj->rowid;
837
+                    $incotermArray[$i]['code'] = $obj->code;
838
+                    $i++;
839
+                }
968 840
 
969
-			asort($this->cache_types_fees);
841
+                foreach ($incotermArray as $row)
842
+                {
843
+                    if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
844
+                    {
845
+                        $out.= '<option value="'.$row['rowid'].'" selected>';
846
+                    }
847
+                    else
848
+                    {
849
+                        $out.= '<option value="'.$row['rowid'].'">';
850
+                    }
970 851
 
971
-			return $num;
972
-		}
973
-		else
974
-		{
975
-			dol_print_error($this->db);
976
-			return -1;
977
-		}
978
-	}
852
+                    if ($row['code']) $out.= $row['code'];
979 853
 
980
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
981
-	/**
982
-	 *	Return list of types of notes
983
-	 *
984
-	 *	@param	string		$selected		Preselected type
985
-	 *	@param  string		$htmlname		Name of field in form
986
-	 * 	@param	int			$showempty		Add an empty field
987
-	 * 	@return	void
988
-	 */
989
-	function select_type_fees($selected='',$htmlname='type',$showempty=0)
990
-	{
991
-        // phpcs:enable
992
-		global $user, $langs;
854
+                    $out.= '</option>';
855
+                }
856
+            }
857
+            $out.= '</select>';
993 858
 
994
-		dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
859
+            $out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
995 860
 
996
-		$this->load_cache_types_fees();
861
+            if (!empty($page))
862
+            {
863
+                $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
864
+            }
865
+        }
866
+        else
867
+        {
868
+            dol_print_error($this->db);
869
+        }
997 870
 
998
-		print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
999
-		if ($showempty)
1000
-		{
1001
-			print '<option value="-1"';
1002
-			if ($selected == -1) print ' selected';
1003
-			print '>&nbsp;</option>';
1004
-		}
871
+        return $out;
872
+    }
1005 873
 
1006
-		foreach($this->cache_types_fees as $key => $value)
1007
-		{
1008
-			print '<option value="'.$key.'"';
1009
-			if ($key == $selected) print ' selected';
1010
-			print '>';
1011
-			print $value;
1012
-			print '</option>';
1013
-		}
874
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
875
+    /**
876
+     *	Return list of types of lines (product or service)
877
+     * 	Example: 0=product, 1=service, 9=other (for external module)
878
+     *
879
+     *	@param  string	$selected       Preselected type
880
+     *	@param  string	$htmlname       Name of field in html form
881
+     * 	@param	int		$showempty		Add an empty field
882
+     * 	@param	int		$hidetext		Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
883
+     * 	@param	integer	$forceall		1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service')
884
+     *  @return	void
885
+     */
886
+    function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
887
+    {
888
+        // phpcs:enable
889
+        global $db,$langs,$user,$conf;
890
+
891
+        // If product & services are enabled or both disabled.
892
+        if ($forceall == 1 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
893
+        || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
894
+        {
895
+            if (empty($hidetext)) print $langs->trans("Type").': ';
896
+            print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
897
+            if ($showempty)
898
+            {
899
+                print '<option value="-1"';
900
+                if ($selected == -1) print ' selected';
901
+                print '>&nbsp;</option>';
902
+            }
1014 903
 
1015
-		print '</select>';
1016
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1017
-	}
904
+            print '<option value="0"';
905
+            if (0 == $selected) print ' selected';
906
+            print '>'.$langs->trans("Product");
1018 907
 
908
+            print '<option value="1"';
909
+            if (1 == $selected) print ' selected';
910
+            print '>'.$langs->trans("Service");
1019 911
 
1020
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1021
-	/**
1022
-	 *  Return HTML code to select a company.
1023
-	 *
1024
-	 *  @param		int			$selected				Preselected products
1025
-	 *  @param		string		$htmlname				Name of HTML select field (must be unique in page)
1026
-	 *  @param		int			$filter					Filter on thirdparty
1027
-	 *  @param		int			$limit					Limit on number of returned lines
1028
-	 *  @param		array		$ajaxoptions			Options for ajax_autocompleter
1029
-	 * 	@param		int			$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1030
-	 *  @return		string								Return select box for thirdparty.
1031
-	 *  @deprecated	3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)
1032
-	 */
1033
-	function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)
1034
-	{
1035
-        // phpcs:enable
1036
-   		return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit);
1037
-	}
912
+            print '</select>';
913
+            //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
914
+        }
915
+        if ((empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled)) || $forceall == 3)
916
+        {
917
+            print $langs->trans("Service");
918
+            print '<input type="hidden" name="'.$htmlname.'" value="1">';
919
+        }
920
+        if ((empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2)
921
+        {
922
+            print $langs->trans("Product");
923
+            print '<input type="hidden" name="'.$htmlname.'" value="0">';
924
+        }
925
+        if ($forceall < 0)	// This should happened only for contracts when both predefined product and service are disabled.
926
+        {
927
+            print '<input type="hidden" name="'.$htmlname.'" value="1">';	// By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1
928
+        }
929
+    }
1038 930
 
1039 931
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1040
-	/**
1041
-	 *  Output html form to select a third party
1042
-	 *
1043
-	 *	@param	string	$selected       		Preselected type
1044
-	 *	@param  string	$htmlname       		Name of field in form
1045
-	 *  @param  string	$filter         		optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')
1046
-	 *	@param	string	$showempty				Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
1047
-	 * 	@param	int		$showtype				Show third party type in combolist (customer, prospect or supplier)
1048
-	 * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1049
-	 *  @param	array	$events					Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1050
-	 *	@param	int		$limit					Maximum number of elements
1051
-	 *  @param	string	$morecss				Add more css styles to the SELECT component
1052
-	 *	@param  string	$moreparam      		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1053
-	 *	@param	string	$selected_input_value	Value of preselected input text (for use with ajax)
1054
-	 *  @param	int		$hidelabel				Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
1055
-	 *  @param	array	$ajaxoptions			Options for ajax_autocompleter
1056
-	 * 	@param  bool	$multiple				add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
1057
-	 * 	@return	string							HTML string with select box for thirdparty.
1058
-	 */
1059
-	function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array(), $multiple=false)
1060
-	{
932
+    /**
933
+     *	Load into cache cache_types_fees, array of types of fees
934
+     *
935
+     *	@return     int             Nb of lines loaded, <0 if KO
936
+     */
937
+    function load_cache_types_fees()
938
+    {
1061 939
         // phpcs:enable
1062
-		global $conf,$user,$langs;
1063
-
1064
-		$out='';
1065
-
1066
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)
1067
-		{
1068
-			// No immediate load of all database
1069
-			$placeholder='';
1070
-			if ($selected && empty($selected_input_value))
1071
-			{
1072
-				require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1073
-				$societetmp = new Societe($this->db);
1074
-				$societetmp->fetch($selected);
1075
-				$selected_input_value=$societetmp->name;
1076
-				unset($societetmp);
1077
-			}
1078
-			// mode 1
1079
-			$urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');
1080
-			$out.=  ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1081
-			$out.='<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
1082
-			if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1083
-			else if ($hidelabel > 1) {
1084
-				$placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1085
-				if ($hidelabel == 2) {
1086
-					$out.=  img_picto($langs->trans("Search"), 'search');
1087
-				}
1088
-			}
1089
-			$out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1090
-			if ($hidelabel == 3) {
1091
-				$out.=  img_picto($langs->trans("Search"), 'search');
1092
-			}
1093
-		}
1094
-		else
1095
-		{
1096
-			// Immediate load of all database
1097
-			$out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
1098
-		}
1099
-
1100
-		return $out;
1101
-	}
940
+        global $langs;
1102 941
 
1103
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1104
-	/**
1105
-	 *  Output html form to select a third party.
1106
-	 *  Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company.
1107
-	 *
1108
-	 *	@param	string	$selected       Preselected type
1109
-	 *	@param  string	$htmlname       Name of field in form
1110
-	 *  @param  string	$filter         Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
1111
-	 *	@param	string	$showempty		Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
1112
-	 * 	@param	int		$showtype		Show third party type in combolist (customer, prospect or supplier)
1113
-	 * 	@param	int		$forcecombo		Force to use standard HTML select component without beautification
1114
-	 *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1115
-	 *  @param	string	$filterkey		Filter on key value
1116
-	 *  @param	int		$outputmode		0=HTML select string, 1=Array
1117
-	 *  @param	int		$limit			Limit number of answers
1118
-	 *  @param	string	$morecss		Add more css styles to the SELECT component
1119
-	 *	@param  string	$moreparam      Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1120
-	 *	@param  bool	$multiple       add [] in the name of element and add 'multiple' attribut
1121
-	 * 	@return	string					HTML string with
1122
-	 */
1123
-	function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='', $multiple=false)
1124
-	{
1125
-        // phpcs:enable
1126
-		global $conf,$user,$langs;
1127
-
1128
-		$out='';
1129
-		$num=0;
1130
-		$outarray=array();
1131
-
1132
-		if ($selected === '') $selected = array();
1133
-		else if (!is_array($selected)) $selected = array($selected);
1134
-
1135
-		// Clean $filter that may contains sql conditions so sql code
1136
-		if (function_exists('testSqlAndScriptInject')) {
1137
-			if (testSqlAndScriptInject($filter, 3)>0) {
1138
-				$filter ='';
1139
-			}
1140
-		}
1141
-
1142
-		// On recherche les societes
1143
-		$sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
1144
-
1145
-		if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1146
-			$sql .= " ,s.address, s.zip, s.town";
1147
-		 	$sql .= " , dictp.code as country_code";
1148
-		}
1149
-
1150
-		$sql.= " FROM (".MAIN_DB_PREFIX ."societe as s";
1151
-		if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1152
-		$sql.= " )";
1153
-		if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1154
-			$sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
1155
-		}
1156
-		$sql.= " WHERE s.entity IN (".getEntity('societe').")";
1157
-		if (! empty($user->socid)) $sql.= " AND s.rowid = ".$user->socid;
1158
-		if ($filter) $sql.= " AND (".$filter.")";
1159
-		if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
1160
-		if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
1161
-		// Add criteria
1162
-		if ($filterkey && $filterkey != '')
1163
-		{
1164
-			$sql.=" AND (";
1165
-			$prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
1166
-			// For natural search
1167
-			$scrit = explode(' ', $filterkey);
1168
-			$i=0;
1169
-			if (count($scrit) > 1) $sql.="(";
1170
-			foreach ($scrit as $crit) {
1171
-				if ($i > 0) $sql.=" AND ";
1172
-				$sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
1173
-				$i++;
1174
-			}
1175
-			if (count($scrit) > 1) $sql.=")";
1176
-			if (! empty($conf->barcode->enabled))
1177
-			{
1178
-				$sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1179
-			}
1180
-			$sql.= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1181
-			$sql.=")";
1182
-		}
1183
-		$sql.=$this->db->order("nom","ASC");
1184
-		$sql.=$this->db->plimit($limit, 0);
1185
-
1186
-		// Build output string
1187
-		dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
1188
-		$resql=$this->db->query($sql);
1189
-		if ($resql)
1190
-		{
1191
-		   	if (! $forcecombo)
1192
-			{
1193
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1194
-				$out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
1195
-			}
1196
-
1197
-			// Construct $out and $outarray
1198
-			$out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparam?' '.$moreparam:'').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
1199
-
1200
-			$textifempty='';
1201
-			// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
1202
-			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
1203
-			if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
1204
-			{
1205
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
1206
-				else $textifempty.=$langs->trans("All");
1207
-			}
1208
-			if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
1209
-
1210
-			$num = $this->db->num_rows($resql);
1211
-			$i = 0;
1212
-			if ($num)
1213
-			{
1214
-				while ($i < $num)
1215
-				{
1216
-					$obj = $this->db->fetch_object($resql);
1217
-					$label='';
1218
-					if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
1219
-						if (($obj->client) && (!empty($obj->code_client))) {
1220
-							$label = $obj->code_client. ' - ';
1221
-						}
1222
-						if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
1223
-							$label .= $obj->code_fournisseur. ' - ';
1224
-						}
1225
-						$label.=' '.$obj->name;
1226
-					}
1227
-					else
1228
-					{
1229
-						$label=$obj->name;
1230
-					}
942
+        $num = count($this->cache_types_fees);
943
+        if ($num > 0) return 0;    // Cache already loaded
1231 944
 
1232
-					if(!empty($obj->name_alias)) {
1233
-						$label.=' ('.$obj->name_alias.')';
1234
-					}
945
+        dol_syslog(__METHOD__, LOG_DEBUG);
1235 946
 
1236
-					if ($showtype)
1237
-					{
1238
-						if ($obj->client || $obj->fournisseur) $label.=' (';
1239
-						if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
1240
-						if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
1241
-						if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
1242
-						if ($obj->client || $obj->fournisseur) $label.=')';
1243
-					}
947
+        $langs->load("trips");
1244 948
 
1245
-					if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1246
-						$label.='-'.$obj->address.'-'. $obj->zip.' '. $obj->town;
1247
-						if (!empty($obj->country_code)) {
1248
-							$label.= ' '. $langs->trans('Country'.$obj->country_code);
1249
-						}
1250
-					}
949
+        $sql = "SELECT c.code, c.label";
950
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
951
+        $sql.= " WHERE active > 0";
1251 952
 
1252
-					if (empty($outputmode))
1253
-					{
1254
-						if (in_array($obj->rowid,$selected))
1255
-						{
1256
-							$out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
1257
-						}
1258
-						else
1259
-						{
1260
-							$out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
1261
-						}
1262
-					}
1263
-					else
1264
-					{
1265
-						array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
1266
-					}
953
+        $resql=$this->db->query($sql);
954
+        if ($resql)
955
+        {
956
+            $num = $this->db->num_rows($resql);
957
+            $i = 0;
1267 958
 
1268
-					$i++;
1269
-					if (($i % 10) == 0) $out.="\n";
1270
-				}
1271
-			}
1272
-			$out.= '</select>'."\n";
1273
-		}
1274
-		else
1275
-		{
1276
-			dol_print_error($this->db);
1277
-		}
959
+            while ($i < $num)
960
+            {
961
+                $obj = $this->db->fetch_object($resql);
1278 962
 
1279
-		$this->result=array('nbofthirdparties'=>$num);
963
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
964
+                $label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
965
+                $this->cache_types_fees[$obj->code] = $label;
966
+                $i++;
967
+            }
1280 968
 
1281
-		if ($outputmode) return $outarray;
1282
-		return $out;
1283
-	}
969
+            asort($this->cache_types_fees);
1284 970
 
971
+            return $num;
972
+        }
973
+        else
974
+        {
975
+            dol_print_error($this->db);
976
+            return -1;
977
+        }
978
+    }
1285 979
 
1286 980
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1287
-	/**
1288
-	 *    	Return HTML combo list of absolute discounts
1289
-	 *
1290
-	 *    	@param	string	$selected       Id remise fixe pre-selectionnee
1291
-	 *    	@param  string	$htmlname       Nom champ formulaire
1292
-	 *    	@param  string	$filter         Criteres optionnels de filtre
1293
-	 * 		@param	int		$socid			Id of thirdparty
1294
-	 * 		@param	int		$maxvalue		Max value for lines that can be selected
1295
-	 * 		@return	int						Return number of qualifed lines in list
1296
-	 */
1297
-	function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
1298
-	{
981
+    /**
982
+     *	Return list of types of notes
983
+     *
984
+     *	@param	string		$selected		Preselected type
985
+     *	@param  string		$htmlname		Name of field in form
986
+     * 	@param	int			$showempty		Add an empty field
987
+     * 	@return	void
988
+     */
989
+    function select_type_fees($selected='',$htmlname='type',$showempty=0)
990
+    {
1299 991
         // phpcs:enable
1300
-		global $langs,$conf;
1301
-
1302
-		// On recherche les remises
1303
-		$sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1304
-		$sql.= " re.description, re.fk_facture_source";
1305
-		$sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
1306
-		$sql.= " WHERE re.fk_soc = ".(int) $socid;
1307
-		$sql.= " AND re.entity = " . $conf->entity;
1308
-		if ($filter) $sql.= " AND ".$filter;
1309
-		$sql.= " ORDER BY re.description ASC";
1310
-
1311
-		dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
1312
-		$resql=$this->db->query($sql);
1313
-		if ($resql)
1314
-		{
1315
-			print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
1316
-			$num = $this->db->num_rows($resql);
1317
-
1318
-			$qualifiedlines=$num;
1319
-
1320
-			$i = 0;
1321
-			if ($num)
1322
-			{
1323
-				print '<option value="0">&nbsp;</option>';
1324
-				while ($i < $num)
1325
-				{
1326
-					$obj = $this->db->fetch_object($resql);
1327
-					$desc=dol_trunc($obj->description,40);
1328
-					if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
1329
-					if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
1330
-					if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
1331
-					if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
1332
-
1333
-					$selectstring='';
1334
-					if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
1335
-
1336
-					$disabled='';
1337
-					if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
1338
-					{
1339
-						$qualifiedlines--;
1340
-						$disabled=' disabled';
1341
-					}
992
+        global $user, $langs;
1342 993
 
1343
-					if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
1344
-					{
1345
-						$tmpfac = new Facture($this->db);
1346
-						if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref;
1347
-					}
994
+        dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
1348 995
 
1349
-					print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
1350
-					$i++;
1351
-				}
1352
-			}
1353
-			print '</select>';
1354
-			return $qualifiedlines;
1355
-		}
1356
-		else
1357
-		{
1358
-			dol_print_error($this->db);
1359
-			return -1;
1360
-		}
1361
-	}
996
+        $this->load_cache_types_fees();
1362 997
 
1363
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1364
-	/**
1365
-	 *	Return list of all contacts (for a third party or all)
1366
-	 *
1367
-	 *	@param	int		$socid      	Id ot third party or 0 for all
1368
-	 *	@param  string	$selected   	Id contact pre-selectionne
1369
-	 *	@param  string	$htmlname  	    Name of HTML field ('none' for a not editable field)
1370
-	 *	@param  int		$showempty      0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
1371
-	 *	@param  string	$exclude        List of contacts id to exclude
1372
-	 *	@param	string	$limitto		Disable answers that are not id in this array list
1373
-	 *	@param	integer	$showfunction   Add function into label
1374
-	 *	@param	string	$moreclass		Add more class to class style
1375
-	 *	@param	integer	$showsoc	    Add company into label
1376
-	 * 	@param	int		$forcecombo		Force to use combo box
1377
-	 *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1378
-	 *  @param	bool	$options_only	Return options only (for ajax treatment)
1379
-	 *  @param	string	$moreparam		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1380
-	 *  @param	string	$htmlid			Html id to use instead of htmlname
1381
-	 *	@return	int						<0 if KO, Nb of contact in list if OK
1382
-	 *  @deprected						You can use selectcontacts directly (warning order of param was changed)
1383
-	 */
1384
-	function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false, $moreparam='', $htmlid='')
1385
-	{
1386
-        // phpcs:enable
1387
-		print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
1388
-		return $this->num;
1389
-	}
1390
-
1391
-	/**
1392
-	 *	Return HTML code of the SELECT of list of all contacts (for a third party or all).
1393
-	 *  This also set the number of contacts found into $this->num
1394
-	 *
1395
-	 * @since 9.0 Add afterSelectContactOptions hook
1396
-	 *
1397
-	 *	@param	int			$socid      	Id ot third party or 0 for all or -1 for empty list
1398
-	 *	@param  array|int	$selected   	Array of ID of pre-selected contact id
1399
-	 *	@param  string		$htmlname  	    Name of HTML field ('none' for a not editable field)
1400
-	 *	@param  int			$showempty     	0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
1401
-	 *	@param  string		$exclude        List of contacts id to exclude
1402
-	 *	@param	string		$limitto		Disable answers that are not id in this array list
1403
-	 *	@param	integer		$showfunction   Add function into label
1404
-	 *	@param	string		$moreclass		Add more class to class style
1405
-	 *	@param	bool		$options_only	Return options only (for ajax treatment)
1406
-	 *	@param	integer		$showsoc	    Add company into label
1407
-	 * 	@param	int			$forcecombo		Force to use combo box (so no ajax beautify effect)
1408
-	 *  @param	array		$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1409
-	 *  @param	string		$moreparam		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1410
-	 *  @param	string		$htmlid			Html id to use instead of htmlname
1411
-	 *  @param	bool		$multiple		add [] in the name of element and add 'multiple' attribut
1412
-	 *	@return	 int						<0 if KO, Nb of contact in list if OK
1413
-	 */
1414
-	function selectcontacts($socid, $selected='', $htmlname='contactid', $showempty=0, $exclude='', $limitto='', $showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array(), $moreparam='', $htmlid='', $multiple=false)
1415
-	{
1416
-		global $conf,$langs,$hookmanager,$action;
1417
-
1418
-		$langs->load('companies');
1419
-
1420
-		if (empty($htmlid)) $htmlid = $htmlname;
1421
-
1422
-		if ($selected === '') $selected = array();
1423
-		else if (!is_array($selected)) $selected = array($selected);
1424
-		$out='';
1425
-
1426
-		if (! is_object($hookmanager))
1427
-		{
1428
-			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1429
-			$hookmanager=new HookManager($this->db);
1430
-		}
1431
-
1432
-		// We search third parties
1433
-		$sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
1434
-		if ($showsoc > 0) $sql.= " , s.nom as company";
1435
-		$sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
1436
-		if ($showsoc > 0) $sql.= " LEFT OUTER JOIN  ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
1437
-		$sql.= " WHERE sp.entity IN (".getEntity('socpeople').")";
1438
-		if ($socid > 0 || $socid == -1) $sql.= " AND sp.fk_soc=".$socid;
1439
-		if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
1440
-		$sql.= " ORDER BY sp.lastname ASC";
1441
-
1442
-		dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
1443
-		$resql=$this->db->query($sql);
1444
-		if ($resql)
1445
-		{
1446
-			$num=$this->db->num_rows($resql);
1447
-
1448
-			if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)
1449
-			{
1450
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1451
-				$out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
1452
-			}
1453
-
1454
-			if ($htmlname != 'none' || $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
1455
-			if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>&nbsp;</option>';
1456
-			if ($showempty == 2) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>'.$langs->trans("Internal").'</option>';
1457
-			$num = $this->db->num_rows($resql);
1458
-			$i = 0;
1459
-			if ($num)
1460
-			{
1461
-				include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1462
-				$contactstatic=new Contact($this->db);
1463
-
1464
-				while ($i < $num)
1465
-				{
1466
-					$obj = $this->db->fetch_object($resql);
1467
-
1468
-					$contactstatic->id=$obj->rowid;
1469
-					$contactstatic->lastname=$obj->lastname;
1470
-					$contactstatic->firstname=$obj->firstname;
1471
-					if ($obj->statut == 1){
1472
-					if ($htmlname != 'none')
1473
-					{
1474
-						$disabled=0;
1475
-						if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
1476
-						if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
1477
-						if (!empty($selected) && in_array($obj->rowid, $selected))
1478
-						{
1479
-							$out.= '<option value="'.$obj->rowid.'"';
1480
-							if ($disabled) $out.= ' disabled';
1481
-							$out.= ' selected>';
1482
-							$out.= $contactstatic->getFullName($langs);
1483
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1484
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1485
-							$out.= '</option>';
1486
-						}
1487
-						else
1488
-						{
1489
-							$out.= '<option value="'.$obj->rowid.'"';
1490
-							if ($disabled) $out.= ' disabled';
1491
-							$out.= '>';
1492
-							$out.= $contactstatic->getFullName($langs);
1493
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1494
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1495
-							$out.= '</option>';
1496
-						}
1497
-					}
1498
-					else
1499
-					{
1500
-						if (in_array($obj->rowid, $selected))
1501
-						{
1502
-							$out.= $contactstatic->getFullName($langs);
1503
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1504
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1505
-						}
1506
-					}
1507
-				}
1508
-					$i++;
1509
-				}
1510
-			}
1511
-			else
1512
-			{
1513
-				$out.= '<option value="-1"'.(($showempty==2 || $multiple) ? '' : ' selected').' disabled>';
1514
-				$out.= ($socid != -1) ? ($langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
1515
-				$out.= '</option>';
1516
-			}
1517
-
1518
-			$parameters = array(
1519
-				'socid'=>$socid,
1520
-				'htmlname'=>$htmlname,
1521
-				'resql'=>$resql,
1522
-				'out'=>&$out,
1523
-				'showfunction'=>$showfunction,
1524
-				'showsoc'=>$showsoc,
1525
-			);
1526
-
1527
-			$reshook = $hookmanager->executeHooks( 'afterSelectContactOptions', $parameters, $this, $action );    // Note that $action and $object may have been modified by some hooks
1528
-
1529
-			if ($htmlname != 'none' || $options_only)
1530
-			{
1531
-				$out.= '</select>';
1532
-			}
1533
-
1534
-			$this->num = $num;
1535
-			return $out;
1536
-		}
1537
-		else
1538
-		{
1539
-			dol_print_error($this->db);
1540
-			return -1;
1541
-		}
1542
-	}
998
+        print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
999
+        if ($showempty)
1000
+        {
1001
+            print '<option value="-1"';
1002
+            if ($selected == -1) print ' selected';
1003
+            print '>&nbsp;</option>';
1004
+        }
1543 1005
 
1544
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1545
-	/**
1546
-	 *	Return select list of users
1547
-	 *
1548
-	 *  @param	string	$selected       Id user preselected
1549
-	 *  @param  string	$htmlname       Field name in form
1550
-	 *  @param  int		$show_empty     0=liste sans valeur nulle, 1=ajoute valeur inconnue
1551
-	 *  @param  array	$exclude        Array list of users id to exclude
1552
-	 * 	@param	int		$disabled		If select list must be disabled
1553
-	 *  @param  array	$include        Array list of users id to include
1554
-	 * 	@param	int		$enableonly		Array list of users id to be enabled. All other must be disabled
1555
-	 *  @param	string	$force_entity	'0' or Ids of environment to force
1556
-	 * 	@return	void
1557
-	 *  @deprecated		Use select_dolusers instead
1558
-	 *  @see select_dolusers()
1559
-	 */
1560
-	function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity='0')
1561
-	{
1562
-        // phpcs:enable
1563
-		print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
1564
-	}
1006
+        foreach($this->cache_types_fees as $key => $value)
1007
+        {
1008
+            print '<option value="'.$key.'"';
1009
+            if ($key == $selected) print ' selected';
1010
+            print '>';
1011
+            print $value;
1012
+            print '</option>';
1013
+        }
1565 1014
 
1566
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1567
-	/**
1568
-	 *	Return select list of users
1569
-	 *
1570
-	 *  @param	string	$selected       User id or user object of user preselected. If 0 or < -2, we use id of current user. If -1, keep unselected (if empty is allowed)
1571
-	 *  @param  string	$htmlname       Field name in form
1572
-	 *  @param  int		$show_empty     0=list with no empty value, 1=add also an empty value into list
1573
-	 *  @param  array	$exclude        Array list of users id to exclude
1574
-	 * 	@param	int		$disabled		If select list must be disabled
1575
-	 *  @param  array|string	$include        Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
1576
-	 * 	@param	array	$enableonly		Array list of users id to be enabled. If defined, it means that others will be disabled
1577
-	 *  @param	string	$force_entity	'0' or Ids of environment to force
1578
-	 *  @param	int		$maxlength		Maximum length of string into list (0=no limit)
1579
-	 *  @param	int		$showstatus		0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
1580
-	 *  @param	string	$morefilter		Add more filters into sql request (Example: 'employee = 1')
1581
-	 *  @param	integer	$show_every		0=default list, 1=add also a value "Everybody" at beginning of list
1582
-	 *  @param	string	$enableonlytext	If option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.
1583
-	 *  @param	string	$morecss		More css
1584
-	 *  @param  int     $noactive       Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
1585
-	 *  @param  int		$outputmode     0=HTML select string, 1=Array
1586
-	 *  @param  bool	$multiple       add [] in the name of element and add 'multiple' attribut
1587
-	 * 	@return	string					HTML select string
1588
-	 *  @see select_dolgroups
1589
-	 */
1590
-	function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0, $outputmode=0, $multiple=false)
1591
-	{
1015
+        print '</select>';
1016
+        if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1017
+    }
1018
+
1019
+
1020
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1021
+    /**
1022
+     *  Return HTML code to select a company.
1023
+     *
1024
+     *  @param		int			$selected				Preselected products
1025
+     *  @param		string		$htmlname				Name of HTML select field (must be unique in page)
1026
+     *  @param		int			$filter					Filter on thirdparty
1027
+     *  @param		int			$limit					Limit on number of returned lines
1028
+     *  @param		array		$ajaxoptions			Options for ajax_autocompleter
1029
+     * 	@param		int			$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1030
+     *  @return		string								Return select box for thirdparty.
1031
+     *  @deprecated	3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)
1032
+     */
1033
+    function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)
1034
+    {
1592 1035
         // phpcs:enable
1593
-		global $conf,$user,$langs;
1594
-
1595
-		// If no preselected user defined, we take current user
1596
-		if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
1597
-
1598
-		if ($selected === '') $selected = array();
1599
-		else if (!is_array($selected)) $selected = array($selected);
1600
-
1601
-		$excludeUsers=null;
1602
-		$includeUsers=null;
1603
-
1604
-		// Permettre l'exclusion d'utilisateurs
1605
-		if (is_array($exclude))	$excludeUsers = implode(",",$exclude);
1606
-		// Permettre l'inclusion d'utilisateurs
1607
-		if (is_array($include))	$includeUsers = implode(",",$include);
1608
-		else if ($include == 'hierarchy')
1609
-		{
1610
-			// Build list includeUsers to have only hierarchy
1611
-			$includeUsers = implode(",",$user->getAllChildIds(0));
1612
-		}
1613
-		else if ($include == 'hierarchyme')
1614
-		{
1615
-			// Build list includeUsers to have only hierarchy and current user
1616
-			$includeUsers = implode(",",$user->getAllChildIds(1));
1617
-		}
1618
-
1619
-		$out='';
1620
-		$outarray = array();
1621
-
1622
-		// Forge request to select users
1623
-		$sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
1624
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1625
-		{
1626
-			$sql.= ", e.label";
1627
-		}
1628
-		$sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
1629
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1630
-		{
1631
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
1632
-			if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
1633
-			else $sql.= " WHERE u.entity IS NOT NULL";
1634
-		}
1635
-		else
1636
-		{
1637
-			if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1638
-			{
1639
-				$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
1640
-				$sql.= " ON ug.fk_user = u.rowid";
1641
-				$sql.= " WHERE ug.entity = ".$conf->entity;
1642
-			}
1643
-			else
1644
-			{
1645
-				$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1646
-			}
1647
-		}
1648
-		if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
1649
-		if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
1650
-		if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")";
1651
-		if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
1652
-		if (! empty($morefilter)) $sql.=" ".$morefilter;
1653
-
1654
-		if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))	// MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
1655
-		{
1656
-			$sql.= " ORDER BY u.firstname ASC";
1657
-		}
1658
-		else
1659
-		{
1660
-			$sql.= " ORDER BY u.lastname ASC";
1661
-		}
1662
-
1663
-		dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
1664
-		$resql=$this->db->query($sql);
1665
-		if ($resql)
1666
-		{
1667
-			$num = $this->db->num_rows($resql);
1668
-			$i = 0;
1669
-			if ($num)
1670
-			{
1671
-		   		// Enhance with select2
1672
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1673
-				$out .= ajax_combobox($htmlname);
1674
-
1675
-				// do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
1676
-				$out.= '<select class="flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
1677
-				if ($show_empty && !$multiple) $out.= '<option value="-1"'.((empty($selected) || in_array(-1,$selected))?' selected':'').'>&nbsp;</option>'."\n";
1678
-				if ($show_every) $out.= '<option value="-2"'.((in_array(-2,$selected))?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
1679
-
1680
-				$userstatic=new User($this->db);
1681
-
1682
-				while ($i < $num)
1683
-				{
1684
-					$obj = $this->db->fetch_object($resql);
1685
-
1686
-					$userstatic->id=$obj->rowid;
1687
-					$userstatic->lastname=$obj->lastname;
1688
-					$userstatic->firstname=$obj->firstname;
1689
-
1690
-					$disableline='';
1691
-					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
1692
-
1693
-					if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && in_array($obj->rowid,$selected) ))
1694
-					{
1695
-						$out.= '<option value="'.$obj->rowid.'"';
1696
-						if ($disableline) $out.= ' disabled';
1697
-						$out.= ' selected>';
1698
-					}
1699
-					else
1700
-					{
1701
-						$out.= '<option value="'.$obj->rowid.'"';
1702
-						if ($disableline) $out.= ' disabled';
1703
-						$out.= '>';
1704
-					}
1036
+            return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit);
1037
+    }
1705 1038
 
1706
-					// $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
1707
-					$fullNameMode = 0;
1708
-					if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))
1709
-					{
1710
-						$fullNameMode = 1; //Firstname+lastname
1711
-					}
1712
-					$out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1713
-
1714
-					// Complete name with more info
1715
-					$moreinfo=0;
1716
-					if (! empty($conf->global->MAIN_SHOW_LOGIN))
1717
-					{
1718
-						$out.= ($moreinfo?' - ':' (').$obj->login;
1719
-						$moreinfo++;
1720
-					}
1721
-					if ($showstatus >= 0)
1722
-					{
1723
-						if ($obj->statut == 1 && $showstatus == 1)
1724
-						{
1725
-							$out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
1726
-							$moreinfo++;
1727
-						}
1728
-						if ($obj->statut == 0)
1729
-						{
1730
-							$out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
1731
-							$moreinfo++;
1732
-						}
1733
-					}
1734
-					if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity)
1735
-					{
1736
-						if (! $obj->entity)
1737
-						{
1738
-							$out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
1739
-							$moreinfo++;
1740
-						}
1741
-						else
1742
-						{
1743
-							$out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
1744
-							$moreinfo++;
1745
-					 	}
1746
-					}
1747
-					$out.=($moreinfo?')':'');
1748
-					if ($disableline && $disableline != '1')
1749
-					{
1750
-						$out.=' - '.$disableline;	// This is text from $enableonlytext parameter
1751
-					}
1752
-					$out.= '</option>';
1753
-					$outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1754
-
1755
-					$i++;
1756
-				}
1757
-			}
1758
-			else
1759
-			{
1760
-				$out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
1761
-				$out.= '<option value="">'.$langs->trans("None").'</option>';
1762
-			}
1763
-			$out.= '</select>';
1764
-		}
1765
-		else
1766
-		{
1767
-			dol_print_error($this->db);
1768
-		}
1769
-
1770
-		if ($outputmode) return $outarray;
1771
-		return $out;
1772
-	}
1039
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1040
+    /**
1041
+     *  Output html form to select a third party
1042
+     *
1043
+     *	@param	string	$selected       		Preselected type
1044
+     *	@param  string	$htmlname       		Name of field in form
1045
+     *  @param  string	$filter         		optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')
1046
+     *	@param	string	$showempty				Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
1047
+     * 	@param	int		$showtype				Show third party type in combolist (customer, prospect or supplier)
1048
+     * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1049
+     *  @param	array	$events					Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1050
+     *	@param	int		$limit					Maximum number of elements
1051
+     *  @param	string	$morecss				Add more css styles to the SELECT component
1052
+     *	@param  string	$moreparam      		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1053
+     *	@param	string	$selected_input_value	Value of preselected input text (for use with ajax)
1054
+     *  @param	int		$hidelabel				Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
1055
+     *  @param	array	$ajaxoptions			Options for ajax_autocompleter
1056
+     * 	@param  bool	$multiple				add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
1057
+     * 	@return	string							HTML string with select box for thirdparty.
1058
+     */
1059
+    function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array(), $multiple=false)
1060
+    {
1061
+        // phpcs:enable
1062
+        global $conf,$user,$langs;
1063
+
1064
+        $out='';
1065
+
1066
+        if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)
1067
+        {
1068
+            // No immediate load of all database
1069
+            $placeholder='';
1070
+            if ($selected && empty($selected_input_value))
1071
+            {
1072
+                require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1073
+                $societetmp = new Societe($this->db);
1074
+                $societetmp->fetch($selected);
1075
+                $selected_input_value=$societetmp->name;
1076
+                unset($societetmp);
1077
+            }
1078
+            // mode 1
1079
+            $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');
1080
+            $out.=  ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1081
+            $out.='<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
1082
+            if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1083
+            else if ($hidelabel > 1) {
1084
+                $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1085
+                if ($hidelabel == 2) {
1086
+                    $out.=  img_picto($langs->trans("Search"), 'search');
1087
+                }
1088
+            }
1089
+            $out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1090
+            if ($hidelabel == 3) {
1091
+                $out.=  img_picto($langs->trans("Search"), 'search');
1092
+            }
1093
+        }
1094
+        else
1095
+        {
1096
+            // Immediate load of all database
1097
+            $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
1098
+        }
1099
+
1100
+        return $out;
1101
+    }
1102
+
1103
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1104
+    /**
1105
+     *  Output html form to select a third party.
1106
+     *  Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company.
1107
+     *
1108
+     *	@param	string	$selected       Preselected type
1109
+     *	@param  string	$htmlname       Name of field in form
1110
+     *  @param  string	$filter         Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
1111
+     *	@param	string	$showempty		Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
1112
+     * 	@param	int		$showtype		Show third party type in combolist (customer, prospect or supplier)
1113
+     * 	@param	int		$forcecombo		Force to use standard HTML select component without beautification
1114
+     *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1115
+     *  @param	string	$filterkey		Filter on key value
1116
+     *  @param	int		$outputmode		0=HTML select string, 1=Array
1117
+     *  @param	int		$limit			Limit number of answers
1118
+     *  @param	string	$morecss		Add more css styles to the SELECT component
1119
+     *	@param  string	$moreparam      Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1120
+     *	@param  bool	$multiple       add [] in the name of element and add 'multiple' attribut
1121
+     * 	@return	string					HTML string with
1122
+     */
1123
+    function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='', $multiple=false)
1124
+    {
1125
+        // phpcs:enable
1126
+        global $conf,$user,$langs;
1127
+
1128
+        $out='';
1129
+        $num=0;
1130
+        $outarray=array();
1131
+
1132
+        if ($selected === '') $selected = array();
1133
+        else if (!is_array($selected)) $selected = array($selected);
1134
+
1135
+        // Clean $filter that may contains sql conditions so sql code
1136
+        if (function_exists('testSqlAndScriptInject')) {
1137
+            if (testSqlAndScriptInject($filter, 3)>0) {
1138
+                $filter ='';
1139
+            }
1140
+        }
1141
+
1142
+        // On recherche les societes
1143
+        $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
1144
+
1145
+        if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1146
+            $sql .= " ,s.address, s.zip, s.town";
1147
+                $sql .= " , dictp.code as country_code";
1148
+        }
1149
+
1150
+        $sql.= " FROM (".MAIN_DB_PREFIX ."societe as s";
1151
+        if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1152
+        $sql.= " )";
1153
+        if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1154
+            $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
1155
+        }
1156
+        $sql.= " WHERE s.entity IN (".getEntity('societe').")";
1157
+        if (! empty($user->socid)) $sql.= " AND s.rowid = ".$user->socid;
1158
+        if ($filter) $sql.= " AND (".$filter.")";
1159
+        if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
1160
+        if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
1161
+        // Add criteria
1162
+        if ($filterkey && $filterkey != '')
1163
+        {
1164
+            $sql.=" AND (";
1165
+            $prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
1166
+            // For natural search
1167
+            $scrit = explode(' ', $filterkey);
1168
+            $i=0;
1169
+            if (count($scrit) > 1) $sql.="(";
1170
+            foreach ($scrit as $crit) {
1171
+                if ($i > 0) $sql.=" AND ";
1172
+                $sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
1173
+                $i++;
1174
+            }
1175
+            if (count($scrit) > 1) $sql.=")";
1176
+            if (! empty($conf->barcode->enabled))
1177
+            {
1178
+                $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1179
+            }
1180
+            $sql.= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1181
+            $sql.=")";
1182
+        }
1183
+        $sql.=$this->db->order("nom","ASC");
1184
+        $sql.=$this->db->plimit($limit, 0);
1185
+
1186
+        // Build output string
1187
+        dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
1188
+        $resql=$this->db->query($sql);
1189
+        if ($resql)
1190
+        {
1191
+                if (! $forcecombo)
1192
+            {
1193
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1194
+                $out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
1195
+            }
1196
+
1197
+            // Construct $out and $outarray
1198
+            $out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparam?' '.$moreparam:'').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
1199
+
1200
+            $textifempty='';
1201
+            // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
1202
+            //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
1203
+            if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
1204
+            {
1205
+                if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
1206
+                else $textifempty.=$langs->trans("All");
1207
+            }
1208
+            if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
1209
+
1210
+            $num = $this->db->num_rows($resql);
1211
+            $i = 0;
1212
+            if ($num)
1213
+            {
1214
+                while ($i < $num)
1215
+                {
1216
+                    $obj = $this->db->fetch_object($resql);
1217
+                    $label='';
1218
+                    if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
1219
+                        if (($obj->client) && (!empty($obj->code_client))) {
1220
+                            $label = $obj->code_client. ' - ';
1221
+                        }
1222
+                        if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
1223
+                            $label .= $obj->code_fournisseur. ' - ';
1224
+                        }
1225
+                        $label.=' '.$obj->name;
1226
+                    }
1227
+                    else
1228
+                    {
1229
+                        $label=$obj->name;
1230
+                    }
1231
+
1232
+                    if(!empty($obj->name_alias)) {
1233
+                        $label.=' ('.$obj->name_alias.')';
1234
+                    }
1235
+
1236
+                    if ($showtype)
1237
+                    {
1238
+                        if ($obj->client || $obj->fournisseur) $label.=' (';
1239
+                        if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
1240
+                        if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
1241
+                        if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
1242
+                        if ($obj->client || $obj->fournisseur) $label.=')';
1243
+                    }
1244
+
1245
+                    if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1246
+                        $label.='-'.$obj->address.'-'. $obj->zip.' '. $obj->town;
1247
+                        if (!empty($obj->country_code)) {
1248
+                            $label.= ' '. $langs->trans('Country'.$obj->country_code);
1249
+                        }
1250
+                    }
1251
+
1252
+                    if (empty($outputmode))
1253
+                    {
1254
+                        if (in_array($obj->rowid,$selected))
1255
+                        {
1256
+                            $out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
1257
+                        }
1258
+                        else
1259
+                        {
1260
+                            $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
1261
+                        }
1262
+                    }
1263
+                    else
1264
+                    {
1265
+                        array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
1266
+                    }
1267
+
1268
+                    $i++;
1269
+                    if (($i % 10) == 0) $out.="\n";
1270
+                }
1271
+            }
1272
+            $out.= '</select>'."\n";
1273
+        }
1274
+        else
1275
+        {
1276
+            dol_print_error($this->db);
1277
+        }
1278
+
1279
+        $this->result=array('nbofthirdparties'=>$num);
1280
+
1281
+        if ($outputmode) return $outarray;
1282
+        return $out;
1283
+    }
1284
+
1285
+
1286
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1287
+    /**
1288
+     *    	Return HTML combo list of absolute discounts
1289
+     *
1290
+     *    	@param	string	$selected       Id remise fixe pre-selectionnee
1291
+     *    	@param  string	$htmlname       Nom champ formulaire
1292
+     *    	@param  string	$filter         Criteres optionnels de filtre
1293
+     * 		@param	int		$socid			Id of thirdparty
1294
+     * 		@param	int		$maxvalue		Max value for lines that can be selected
1295
+     * 		@return	int						Return number of qualifed lines in list
1296
+     */
1297
+    function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
1298
+    {
1299
+        // phpcs:enable
1300
+        global $langs,$conf;
1301
+
1302
+        // On recherche les remises
1303
+        $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1304
+        $sql.= " re.description, re.fk_facture_source";
1305
+        $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
1306
+        $sql.= " WHERE re.fk_soc = ".(int) $socid;
1307
+        $sql.= " AND re.entity = " . $conf->entity;
1308
+        if ($filter) $sql.= " AND ".$filter;
1309
+        $sql.= " ORDER BY re.description ASC";
1310
+
1311
+        dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
1312
+        $resql=$this->db->query($sql);
1313
+        if ($resql)
1314
+        {
1315
+            print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
1316
+            $num = $this->db->num_rows($resql);
1317
+
1318
+            $qualifiedlines=$num;
1319
+
1320
+            $i = 0;
1321
+            if ($num)
1322
+            {
1323
+                print '<option value="0">&nbsp;</option>';
1324
+                while ($i < $num)
1325
+                {
1326
+                    $obj = $this->db->fetch_object($resql);
1327
+                    $desc=dol_trunc($obj->description,40);
1328
+                    if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
1329
+                    if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
1330
+                    if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
1331
+                    if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
1332
+
1333
+                    $selectstring='';
1334
+                    if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
1335
+
1336
+                    $disabled='';
1337
+                    if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
1338
+                    {
1339
+                        $qualifiedlines--;
1340
+                        $disabled=' disabled';
1341
+                    }
1342
+
1343
+                    if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
1344
+                    {
1345
+                        $tmpfac = new Facture($this->db);
1346
+                        if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref;
1347
+                    }
1348
+
1349
+                    print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
1350
+                    $i++;
1351
+                }
1352
+            }
1353
+            print '</select>';
1354
+            return $qualifiedlines;
1355
+        }
1356
+        else
1357
+        {
1358
+            dol_print_error($this->db);
1359
+            return -1;
1360
+        }
1361
+    }
1362
+
1363
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1364
+    /**
1365
+     *	Return list of all contacts (for a third party or all)
1366
+     *
1367
+     *	@param	int		$socid      	Id ot third party or 0 for all
1368
+     *	@param  string	$selected   	Id contact pre-selectionne
1369
+     *	@param  string	$htmlname  	    Name of HTML field ('none' for a not editable field)
1370
+     *	@param  int		$showempty      0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
1371
+     *	@param  string	$exclude        List of contacts id to exclude
1372
+     *	@param	string	$limitto		Disable answers that are not id in this array list
1373
+     *	@param	integer	$showfunction   Add function into label
1374
+     *	@param	string	$moreclass		Add more class to class style
1375
+     *	@param	integer	$showsoc	    Add company into label
1376
+     * 	@param	int		$forcecombo		Force to use combo box
1377
+     *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1378
+     *  @param	bool	$options_only	Return options only (for ajax treatment)
1379
+     *  @param	string	$moreparam		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1380
+     *  @param	string	$htmlid			Html id to use instead of htmlname
1381
+     *	@return	int						<0 if KO, Nb of contact in list if OK
1382
+     *  @deprected						You can use selectcontacts directly (warning order of param was changed)
1383
+     */
1384
+    function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false, $moreparam='', $htmlid='')
1385
+    {
1386
+        // phpcs:enable
1387
+        print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
1388
+        return $this->num;
1389
+    }
1390
+
1391
+    /**
1392
+     *	Return HTML code of the SELECT of list of all contacts (for a third party or all).
1393
+     *  This also set the number of contacts found into $this->num
1394
+     *
1395
+     * @since 9.0 Add afterSelectContactOptions hook
1396
+     *
1397
+     *	@param	int			$socid      	Id ot third party or 0 for all or -1 for empty list
1398
+     *	@param  array|int	$selected   	Array of ID of pre-selected contact id
1399
+     *	@param  string		$htmlname  	    Name of HTML field ('none' for a not editable field)
1400
+     *	@param  int			$showempty     	0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
1401
+     *	@param  string		$exclude        List of contacts id to exclude
1402
+     *	@param	string		$limitto		Disable answers that are not id in this array list
1403
+     *	@param	integer		$showfunction   Add function into label
1404
+     *	@param	string		$moreclass		Add more class to class style
1405
+     *	@param	bool		$options_only	Return options only (for ajax treatment)
1406
+     *	@param	integer		$showsoc	    Add company into label
1407
+     * 	@param	int			$forcecombo		Force to use combo box (so no ajax beautify effect)
1408
+     *  @param	array		$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1409
+     *  @param	string		$moreparam		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1410
+     *  @param	string		$htmlid			Html id to use instead of htmlname
1411
+     *  @param	bool		$multiple		add [] in the name of element and add 'multiple' attribut
1412
+     *	@return	 int						<0 if KO, Nb of contact in list if OK
1413
+     */
1414
+    function selectcontacts($socid, $selected='', $htmlname='contactid', $showempty=0, $exclude='', $limitto='', $showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array(), $moreparam='', $htmlid='', $multiple=false)
1415
+    {
1416
+        global $conf,$langs,$hookmanager,$action;
1417
+
1418
+        $langs->load('companies');
1419
+
1420
+        if (empty($htmlid)) $htmlid = $htmlname;
1421
+
1422
+        if ($selected === '') $selected = array();
1423
+        else if (!is_array($selected)) $selected = array($selected);
1424
+        $out='';
1425
+
1426
+        if (! is_object($hookmanager))
1427
+        {
1428
+            include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1429
+            $hookmanager=new HookManager($this->db);
1430
+        }
1431
+
1432
+        // We search third parties
1433
+        $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
1434
+        if ($showsoc > 0) $sql.= " , s.nom as company";
1435
+        $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
1436
+        if ($showsoc > 0) $sql.= " LEFT OUTER JOIN  ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
1437
+        $sql.= " WHERE sp.entity IN (".getEntity('socpeople').")";
1438
+        if ($socid > 0 || $socid == -1) $sql.= " AND sp.fk_soc=".$socid;
1439
+        if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
1440
+        $sql.= " ORDER BY sp.lastname ASC";
1441
+
1442
+        dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
1443
+        $resql=$this->db->query($sql);
1444
+        if ($resql)
1445
+        {
1446
+            $num=$this->db->num_rows($resql);
1447
+
1448
+            if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)
1449
+            {
1450
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1451
+                $out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
1452
+            }
1453
+
1454
+            if ($htmlname != 'none' || $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
1455
+            if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>&nbsp;</option>';
1456
+            if ($showempty == 2) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>'.$langs->trans("Internal").'</option>';
1457
+            $num = $this->db->num_rows($resql);
1458
+            $i = 0;
1459
+            if ($num)
1460
+            {
1461
+                include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1462
+                $contactstatic=new Contact($this->db);
1463
+
1464
+                while ($i < $num)
1465
+                {
1466
+                    $obj = $this->db->fetch_object($resql);
1467
+
1468
+                    $contactstatic->id=$obj->rowid;
1469
+                    $contactstatic->lastname=$obj->lastname;
1470
+                    $contactstatic->firstname=$obj->firstname;
1471
+                    if ($obj->statut == 1){
1472
+                    if ($htmlname != 'none')
1473
+                    {
1474
+                        $disabled=0;
1475
+                        if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
1476
+                        if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
1477
+                        if (!empty($selected) && in_array($obj->rowid, $selected))
1478
+                        {
1479
+                            $out.= '<option value="'.$obj->rowid.'"';
1480
+                            if ($disabled) $out.= ' disabled';
1481
+                            $out.= ' selected>';
1482
+                            $out.= $contactstatic->getFullName($langs);
1483
+                            if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1484
+                            if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1485
+                            $out.= '</option>';
1486
+                        }
1487
+                        else
1488
+                        {
1489
+                            $out.= '<option value="'.$obj->rowid.'"';
1490
+                            if ($disabled) $out.= ' disabled';
1491
+                            $out.= '>';
1492
+                            $out.= $contactstatic->getFullName($langs);
1493
+                            if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1494
+                            if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1495
+                            $out.= '</option>';
1496
+                        }
1497
+                    }
1498
+                    else
1499
+                    {
1500
+                        if (in_array($obj->rowid, $selected))
1501
+                        {
1502
+                            $out.= $contactstatic->getFullName($langs);
1503
+                            if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1504
+                            if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1505
+                        }
1506
+                    }
1507
+                }
1508
+                    $i++;
1509
+                }
1510
+            }
1511
+            else
1512
+            {
1513
+                $out.= '<option value="-1"'.(($showempty==2 || $multiple) ? '' : ' selected').' disabled>';
1514
+                $out.= ($socid != -1) ? ($langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
1515
+                $out.= '</option>';
1516
+            }
1517
+
1518
+            $parameters = array(
1519
+                'socid'=>$socid,
1520
+                'htmlname'=>$htmlname,
1521
+                'resql'=>$resql,
1522
+                'out'=>&$out,
1523
+                'showfunction'=>$showfunction,
1524
+                'showsoc'=>$showsoc,
1525
+            );
1526
+
1527
+            $reshook = $hookmanager->executeHooks( 'afterSelectContactOptions', $parameters, $this, $action );    // Note that $action and $object may have been modified by some hooks
1528
+
1529
+            if ($htmlname != 'none' || $options_only)
1530
+            {
1531
+                $out.= '</select>';
1532
+            }
1533
+
1534
+            $this->num = $num;
1535
+            return $out;
1536
+        }
1537
+        else
1538
+        {
1539
+            dol_print_error($this->db);
1540
+            return -1;
1541
+        }
1542
+    }
1543
+
1544
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1545
+    /**
1546
+     *	Return select list of users
1547
+     *
1548
+     *  @param	string	$selected       Id user preselected
1549
+     *  @param  string	$htmlname       Field name in form
1550
+     *  @param  int		$show_empty     0=liste sans valeur nulle, 1=ajoute valeur inconnue
1551
+     *  @param  array	$exclude        Array list of users id to exclude
1552
+     * 	@param	int		$disabled		If select list must be disabled
1553
+     *  @param  array	$include        Array list of users id to include
1554
+     * 	@param	int		$enableonly		Array list of users id to be enabled. All other must be disabled
1555
+     *  @param	string	$force_entity	'0' or Ids of environment to force
1556
+     * 	@return	void
1557
+     *  @deprecated		Use select_dolusers instead
1558
+     *  @see select_dolusers()
1559
+     */
1560
+    function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity='0')
1561
+    {
1562
+        // phpcs:enable
1563
+        print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
1564
+    }
1565
+
1566
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1567
+    /**
1568
+     *	Return select list of users
1569
+     *
1570
+     *  @param	string	$selected       User id or user object of user preselected. If 0 or < -2, we use id of current user. If -1, keep unselected (if empty is allowed)
1571
+     *  @param  string	$htmlname       Field name in form
1572
+     *  @param  int		$show_empty     0=list with no empty value, 1=add also an empty value into list
1573
+     *  @param  array	$exclude        Array list of users id to exclude
1574
+     * 	@param	int		$disabled		If select list must be disabled
1575
+     *  @param  array|string	$include        Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
1576
+     * 	@param	array	$enableonly		Array list of users id to be enabled. If defined, it means that others will be disabled
1577
+     *  @param	string	$force_entity	'0' or Ids of environment to force
1578
+     *  @param	int		$maxlength		Maximum length of string into list (0=no limit)
1579
+     *  @param	int		$showstatus		0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
1580
+     *  @param	string	$morefilter		Add more filters into sql request (Example: 'employee = 1')
1581
+     *  @param	integer	$show_every		0=default list, 1=add also a value "Everybody" at beginning of list
1582
+     *  @param	string	$enableonlytext	If option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.
1583
+     *  @param	string	$morecss		More css
1584
+     *  @param  int     $noactive       Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
1585
+     *  @param  int		$outputmode     0=HTML select string, 1=Array
1586
+     *  @param  bool	$multiple       add [] in the name of element and add 'multiple' attribut
1587
+     * 	@return	string					HTML select string
1588
+     *  @see select_dolgroups
1589
+     */
1590
+    function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0, $outputmode=0, $multiple=false)
1591
+    {
1592
+        // phpcs:enable
1593
+        global $conf,$user,$langs;
1594
+
1595
+        // If no preselected user defined, we take current user
1596
+        if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
1597
+
1598
+        if ($selected === '') $selected = array();
1599
+        else if (!is_array($selected)) $selected = array($selected);
1600
+
1601
+        $excludeUsers=null;
1602
+        $includeUsers=null;
1603
+
1604
+        // Permettre l'exclusion d'utilisateurs
1605
+        if (is_array($exclude))	$excludeUsers = implode(",",$exclude);
1606
+        // Permettre l'inclusion d'utilisateurs
1607
+        if (is_array($include))	$includeUsers = implode(",",$include);
1608
+        else if ($include == 'hierarchy')
1609
+        {
1610
+            // Build list includeUsers to have only hierarchy
1611
+            $includeUsers = implode(",",$user->getAllChildIds(0));
1612
+        }
1613
+        else if ($include == 'hierarchyme')
1614
+        {
1615
+            // Build list includeUsers to have only hierarchy and current user
1616
+            $includeUsers = implode(",",$user->getAllChildIds(1));
1617
+        }
1618
+
1619
+        $out='';
1620
+        $outarray = array();
1621
+
1622
+        // Forge request to select users
1623
+        $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
1624
+        if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1625
+        {
1626
+            $sql.= ", e.label";
1627
+        }
1628
+        $sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
1629
+        if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1630
+        {
1631
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
1632
+            if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
1633
+            else $sql.= " WHERE u.entity IS NOT NULL";
1634
+        }
1635
+        else
1636
+        {
1637
+            if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1638
+            {
1639
+                $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
1640
+                $sql.= " ON ug.fk_user = u.rowid";
1641
+                $sql.= " WHERE ug.entity = ".$conf->entity;
1642
+            }
1643
+            else
1644
+            {
1645
+                $sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1646
+            }
1647
+        }
1648
+        if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
1649
+        if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
1650
+        if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")";
1651
+        if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
1652
+        if (! empty($morefilter)) $sql.=" ".$morefilter;
1653
+
1654
+        if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))	// MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
1655
+        {
1656
+            $sql.= " ORDER BY u.firstname ASC";
1657
+        }
1658
+        else
1659
+        {
1660
+            $sql.= " ORDER BY u.lastname ASC";
1661
+        }
1662
+
1663
+        dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
1664
+        $resql=$this->db->query($sql);
1665
+        if ($resql)
1666
+        {
1667
+            $num = $this->db->num_rows($resql);
1668
+            $i = 0;
1669
+            if ($num)
1670
+            {
1671
+                    // Enhance with select2
1672
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1673
+                $out .= ajax_combobox($htmlname);
1674
+
1675
+                // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
1676
+                $out.= '<select class="flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
1677
+                if ($show_empty && !$multiple) $out.= '<option value="-1"'.((empty($selected) || in_array(-1,$selected))?' selected':'').'>&nbsp;</option>'."\n";
1678
+                if ($show_every) $out.= '<option value="-2"'.((in_array(-2,$selected))?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
1679
+
1680
+                $userstatic=new User($this->db);
1681
+
1682
+                while ($i < $num)
1683
+                {
1684
+                    $obj = $this->db->fetch_object($resql);
1685
+
1686
+                    $userstatic->id=$obj->rowid;
1687
+                    $userstatic->lastname=$obj->lastname;
1688
+                    $userstatic->firstname=$obj->firstname;
1689
+
1690
+                    $disableline='';
1691
+                    if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
1692
+
1693
+                    if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && in_array($obj->rowid,$selected) ))
1694
+                    {
1695
+                        $out.= '<option value="'.$obj->rowid.'"';
1696
+                        if ($disableline) $out.= ' disabled';
1697
+                        $out.= ' selected>';
1698
+                    }
1699
+                    else
1700
+                    {
1701
+                        $out.= '<option value="'.$obj->rowid.'"';
1702
+                        if ($disableline) $out.= ' disabled';
1703
+                        $out.= '>';
1704
+                    }
1705
+
1706
+                    // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
1707
+                    $fullNameMode = 0;
1708
+                    if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))
1709
+                    {
1710
+                        $fullNameMode = 1; //Firstname+lastname
1711
+                    }
1712
+                    $out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1713
+
1714
+                    // Complete name with more info
1715
+                    $moreinfo=0;
1716
+                    if (! empty($conf->global->MAIN_SHOW_LOGIN))
1717
+                    {
1718
+                        $out.= ($moreinfo?' - ':' (').$obj->login;
1719
+                        $moreinfo++;
1720
+                    }
1721
+                    if ($showstatus >= 0)
1722
+                    {
1723
+                        if ($obj->statut == 1 && $showstatus == 1)
1724
+                        {
1725
+                            $out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
1726
+                            $moreinfo++;
1727
+                        }
1728
+                        if ($obj->statut == 0)
1729
+                        {
1730
+                            $out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
1731
+                            $moreinfo++;
1732
+                        }
1733
+                    }
1734
+                    if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity)
1735
+                    {
1736
+                        if (! $obj->entity)
1737
+                        {
1738
+                            $out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
1739
+                            $moreinfo++;
1740
+                        }
1741
+                        else
1742
+                        {
1743
+                            $out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
1744
+                            $moreinfo++;
1745
+                            }
1746
+                    }
1747
+                    $out.=($moreinfo?')':'');
1748
+                    if ($disableline && $disableline != '1')
1749
+                    {
1750
+                        $out.=' - '.$disableline;	// This is text from $enableonlytext parameter
1751
+                    }
1752
+                    $out.= '</option>';
1753
+                    $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1754
+
1755
+                    $i++;
1756
+                }
1757
+            }
1758
+            else
1759
+            {
1760
+                $out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
1761
+                $out.= '<option value="">'.$langs->trans("None").'</option>';
1762
+            }
1763
+            $out.= '</select>';
1764
+        }
1765
+        else
1766
+        {
1767
+            dol_print_error($this->db);
1768
+        }
1769
+
1770
+        if ($outputmode) return $outarray;
1771
+        return $out;
1772
+    }
1773 1773
 
1774 1774
 
1775 1775
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1776
-	/**
1777
-	 *	Return select list of users. Selected users are stored into session.
1778
-	 *  List of users are provided into $_SESSION['assignedtouser'].
1779
-	 *
1780
-	 *  @param  string	$action         Value for $action
1781
-	 *  @param  string	$htmlname       Field name in form
1782
-	 *  @param  int		$show_empty     0=list without the empty value, 1=add empty value
1783
-	 *  @param  array	$exclude        Array list of users id to exclude
1784
-	 * 	@param	int		$disabled		If select list must be disabled
1785
-	 *  @param  array	$include        Array list of users id to include or 'hierarchy' to have only supervised users
1786
-	 * 	@param	array	$enableonly		Array list of users id to be enabled. All other must be disabled
1787
-	 *  @param	int		$force_entity	'0' or Ids of environment to force
1788
-	 *  @param	int		$maxlength		Maximum length of string into list (0=no limit)
1789
-	 *  @param	int		$showstatus		0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
1790
-	 *  @param	string	$morefilter		Add more filters into sql request
1791
-	 *  @param	int		$showproperties		Show properties of each attendees
1792
-	 *  @param	array	$listofuserid		Array with properties of each user
1793
-	 *  @param	array	$listofcontactid	Array with properties of each contact
1794
-	 *  @param	array	$listofotherid		Array with properties of each other contact
1795
-	 * 	@return	string					HTML select string
1796
-	 *  @see select_dolgroups
1797
-	 */
1798
-	function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $showproperties=0, $listofuserid=array(), $listofcontactid=array(), $listofotherid=array())
1799
-	{
1776
+    /**
1777
+     *	Return select list of users. Selected users are stored into session.
1778
+     *  List of users are provided into $_SESSION['assignedtouser'].
1779
+     *
1780
+     *  @param  string	$action         Value for $action
1781
+     *  @param  string	$htmlname       Field name in form
1782
+     *  @param  int		$show_empty     0=list without the empty value, 1=add empty value
1783
+     *  @param  array	$exclude        Array list of users id to exclude
1784
+     * 	@param	int		$disabled		If select list must be disabled
1785
+     *  @param  array	$include        Array list of users id to include or 'hierarchy' to have only supervised users
1786
+     * 	@param	array	$enableonly		Array list of users id to be enabled. All other must be disabled
1787
+     *  @param	int		$force_entity	'0' or Ids of environment to force
1788
+     *  @param	int		$maxlength		Maximum length of string into list (0=no limit)
1789
+     *  @param	int		$showstatus		0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
1790
+     *  @param	string	$morefilter		Add more filters into sql request
1791
+     *  @param	int		$showproperties		Show properties of each attendees
1792
+     *  @param	array	$listofuserid		Array with properties of each user
1793
+     *  @param	array	$listofcontactid	Array with properties of each contact
1794
+     *  @param	array	$listofotherid		Array with properties of each other contact
1795
+     * 	@return	string					HTML select string
1796
+     *  @see select_dolgroups
1797
+     */
1798
+    function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $showproperties=0, $listofuserid=array(), $listofcontactid=array(), $listofotherid=array())
1799
+    {
1800 1800
         // phpcs:enable
1801
-		global $conf, $user, $langs;
1802
-
1803
-		$userstatic=new User($this->db);
1804
-		$out='';
1805
-
1806
-		// Method with no ajax
1807
-		//$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1808
-		if ($action == 'view')
1809
-		{
1810
-			$out.='';
1811
-		}
1812
-		else
1813
-		{
1814
-			$out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
1815
-			$out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () {    jQuery(".removedassigned").click(function() {        jQuery(".removedassignedhidden").val(jQuery(this).val());    });})</script>';
1816
-			$out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
1817
-			$out.=' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
1818
-			$out.='<br>';
1819
-		}
1820
-		$assignedtouser=array();
1821
-		if (!empty($_SESSION['assignedtouser']))
1822
-		{
1823
-			$assignedtouser=json_decode($_SESSION['assignedtouser'], true);
1824
-		}
1825
-		$nbassignetouser=count($assignedtouser);
1826
-
1827
-		if ($nbassignetouser && $action != 'view') $out.='<br>';
1828
-		if ($nbassignetouser) $out.='<ul class="attendees">';
1829
-		$i=0; $ownerid=0;
1830
-		foreach($assignedtouser as $key => $value)
1831
-		{
1832
-			if ($value['id'] == $ownerid) continue;
1833
-
1834
-			$out.='<li>';
1835
-			$userstatic->fetch($value['id']);
1836
-			$out.= $userstatic->getNomUrl(-1);
1837
-			if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; }
1838
-			if ($nbassignetouser > 1 && $action != 'view')
1839
-			{
1840
-				$out.=' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
1841
-			}
1842
-			// Show my availability
1843
-			if ($showproperties)
1844
-			{
1845
-				if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))
1846
-				{
1847
-					$out.='<div class="myavailability inline-block">';
1848
-					$out.='&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span>  <input id="transparency" class="marginleftonly marginrightonly" '.($action == 'view'?'disabled':'').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency']?' checked':'').'>'.$langs->trans("Busy");
1849
-					$out.='</div>';
1850
-				}
1851
-			}
1852
-			//$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
1853
-			//$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
1854
-
1855
-			$out.='</li>';
1856
-			$i++;
1857
-		}
1858
-		if ($nbassignetouser) $out.='</ul>';
1859
-
1860
-		//$out.='</form>';
1861
-		return $out;
1862
-	}
1801
+        global $conf, $user, $langs;
1802
+
1803
+        $userstatic=new User($this->db);
1804
+        $out='';
1805
+
1806
+        // Method with no ajax
1807
+        //$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1808
+        if ($action == 'view')
1809
+        {
1810
+            $out.='';
1811
+        }
1812
+        else
1813
+        {
1814
+            $out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
1815
+            $out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () {    jQuery(".removedassigned").click(function() {        jQuery(".removedassignedhidden").val(jQuery(this).val());    });})</script>';
1816
+            $out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
1817
+            $out.=' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
1818
+            $out.='<br>';
1819
+        }
1820
+        $assignedtouser=array();
1821
+        if (!empty($_SESSION['assignedtouser']))
1822
+        {
1823
+            $assignedtouser=json_decode($_SESSION['assignedtouser'], true);
1824
+        }
1825
+        $nbassignetouser=count($assignedtouser);
1826
+
1827
+        if ($nbassignetouser && $action != 'view') $out.='<br>';
1828
+        if ($nbassignetouser) $out.='<ul class="attendees">';
1829
+        $i=0; $ownerid=0;
1830
+        foreach($assignedtouser as $key => $value)
1831
+        {
1832
+            if ($value['id'] == $ownerid) continue;
1833
+
1834
+            $out.='<li>';
1835
+            $userstatic->fetch($value['id']);
1836
+            $out.= $userstatic->getNomUrl(-1);
1837
+            if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; }
1838
+            if ($nbassignetouser > 1 && $action != 'view')
1839
+            {
1840
+                $out.=' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
1841
+            }
1842
+            // Show my availability
1843
+            if ($showproperties)
1844
+            {
1845
+                if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))
1846
+                {
1847
+                    $out.='<div class="myavailability inline-block">';
1848
+                    $out.='&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span>  <input id="transparency" class="marginleftonly marginrightonly" '.($action == 'view'?'disabled':'').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency']?' checked':'').'>'.$langs->trans("Busy");
1849
+                    $out.='</div>';
1850
+                }
1851
+            }
1852
+            //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
1853
+            //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
1854
+
1855
+            $out.='</li>';
1856
+            $i++;
1857
+        }
1858
+        if ($nbassignetouser) $out.='</ul>';
1859
+
1860
+        //$out.='</form>';
1861
+        return $out;
1862
+    }
1863 1863
 
1864 1864
 
1865 1865
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1866
-	/**
1867
-	 *  Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
1868
-	 *
1869
-	 *  @param		int			$selected				Preselected products
1870
-	 *  @param		string		$htmlname				Name of HTML select field (must be unique in page)
1871
-	 *  @param		int			$filtertype				Filter on product type (''=nofilter, 0=product, 1=service)
1872
-	 *  @param		int			$limit					Limit on number of returned lines
1873
-	 *  @param		int			$price_level			Level of price to show
1874
-	 *  @param		int			$status					Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
1875
-	 *  @param		int			$finished				2=all, 1=finished, 0=raw material
1876
-	 *  @param		string		$selected_input_value	Value of preselected input text (for use with ajax)
1877
-	 *  @param		int			$hidelabel				Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
1878
-	 *  @param		array		$ajaxoptions			Options for ajax_autocompleter
1879
-	 *  @param      int			$socid					Thirdparty Id (to get also price dedicated to this customer)
1880
-	 *  @param		string		$showempty				'' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
1881
-	 * 	@param		int			$forcecombo				Force to use combo box
1882
-	 *  @param      string      $morecss                Add more css on select
1883
-	 *  @param      int         $hidepriceinlabel       1=Hide prices in label
1884
-	 *  @param      string      $warehouseStatus        warehouse status filter, following comma separated filter options can be used
1885
-	 *										            'warehouseopen' = select products from open warehouses,
1886
-	 *										            'warehouseclosed' = select products from closed warehouses,
1887
-	 *										            'warehouseinternal' = select products from warehouses for internal correct/transfer only
1888
-	 *  @param 		array 		$selected_combinations 	Selected combinations. Format: array([attrid] => attrval, [...])
1889
-	 *  @return		void
1890
-	 */
1891
-	function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array())
1892
-	{
1866
+    /**
1867
+     *  Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
1868
+     *
1869
+     *  @param		int			$selected				Preselected products
1870
+     *  @param		string		$htmlname				Name of HTML select field (must be unique in page)
1871
+     *  @param		int			$filtertype				Filter on product type (''=nofilter, 0=product, 1=service)
1872
+     *  @param		int			$limit					Limit on number of returned lines
1873
+     *  @param		int			$price_level			Level of price to show
1874
+     *  @param		int			$status					Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
1875
+     *  @param		int			$finished				2=all, 1=finished, 0=raw material
1876
+     *  @param		string		$selected_input_value	Value of preselected input text (for use with ajax)
1877
+     *  @param		int			$hidelabel				Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
1878
+     *  @param		array		$ajaxoptions			Options for ajax_autocompleter
1879
+     *  @param      int			$socid					Thirdparty Id (to get also price dedicated to this customer)
1880
+     *  @param		string		$showempty				'' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
1881
+     * 	@param		int			$forcecombo				Force to use combo box
1882
+     *  @param      string      $morecss                Add more css on select
1883
+     *  @param      int         $hidepriceinlabel       1=Hide prices in label
1884
+     *  @param      string      $warehouseStatus        warehouse status filter, following comma separated filter options can be used
1885
+     *										            'warehouseopen' = select products from open warehouses,
1886
+     *										            'warehouseclosed' = select products from closed warehouses,
1887
+     *										            'warehouseinternal' = select products from warehouses for internal correct/transfer only
1888
+     *  @param 		array 		$selected_combinations 	Selected combinations. Format: array([attrid] => attrval, [...])
1889
+     *  @return		void
1890
+     */
1891
+    function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array())
1892
+    {
1893 1893
         // phpcs:enable
1894
-		global $langs,$conf;
1895
-
1896
-		$price_level = (! empty($price_level) ? $price_level : 0);
1897
-
1898
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
1899
-		{
1900
-			$placeholder='';
1901
-
1902
-			if ($selected && empty($selected_input_value))
1903
-			{
1904
-				require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1905
-				$producttmpselect = new Product($this->db);
1906
-				$producttmpselect->fetch($selected);
1907
-				$selected_input_value=$producttmpselect->ref;
1908
-				unset($producttmpselect);
1909
-			}
1910
-			// mode=1 means customers products
1911
-			$urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
1912
-			//Price by customer
1913
-			if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
1914
-				$urloption.='&socid='.$socid;
1915
-			}
1916
-			print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1917
-
1918
-			if (!empty($conf->variants->enabled)) {
1919
-				?>
1894
+        global $langs,$conf;
1895
+
1896
+        $price_level = (! empty($price_level) ? $price_level : 0);
1897
+
1898
+        if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
1899
+        {
1900
+            $placeholder='';
1901
+
1902
+            if ($selected && empty($selected_input_value))
1903
+            {
1904
+                require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1905
+                $producttmpselect = new Product($this->db);
1906
+                $producttmpselect->fetch($selected);
1907
+                $selected_input_value=$producttmpselect->ref;
1908
+                unset($producttmpselect);
1909
+            }
1910
+            // mode=1 means customers products
1911
+            $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
1912
+            //Price by customer
1913
+            if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
1914
+                $urloption.='&socid='.$socid;
1915
+            }
1916
+            print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1917
+
1918
+            if (!empty($conf->variants->enabled)) {
1919
+                ?>
1920 1920
 				<script>
1921 1921
 
1922 1922
 					selected = <?php echo json_encode($selected_combinations) ?>;
@@ -1987,3871 +1987,3871 @@  discard block
 block discarded – undo
1987 1987
 					});
1988 1988
 				</script>
1989 1989
                 <?php
1990
-			}
1991
-			if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1992
-			else if ($hidelabel > 1) {
1993
-				$placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1994
-				if ($hidelabel == 2) {
1995
-					print img_picto($langs->trans("Search"), 'search');
1996
-				}
1997
-			}
1998
-			print '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1999
-			if ($hidelabel == 3) {
2000
-				print img_picto($langs->trans("Search"), 'search');
2001
-			}
2002
-		}
2003
-		else
2004
-		{
2005
-			print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);
2006
-		}
2007
-	}
2008
-
2009
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2010
-	/**
2011
-	 *	Return list of products for a customer
2012
-	 *
2013
-	 *	@param      int		$selected           Preselected product
2014
-	 *	@param      string	$htmlname           Name of select html
2015
-	 *  @param		string	$filtertype         Filter on product type (''=nofilter, 0=product, 1=service)
2016
-	 *	@param      int		$limit              Limit on number of returned lines
2017
-	 *	@param      int		$price_level        Level of price to show
2018
-	 * 	@param      string	$filterkey          Filter on product
2019
-	 *	@param		int		$status             -1=Return all products, 0=Products not on sell, 1=Products on sell
2020
-	 *  @param      int		$finished           Filter on finished field: 2=No filter
2021
-	 *  @param      int		$outputmode         0=HTML select string, 1=Array
2022
-	 *  @param      int		$socid     		    Thirdparty Id (to get also price dedicated to this customer)
2023
-	 *  @param		string	$showempty		    '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
2024
-	 * 	@param		int		$forcecombo		    Force to use combo box
2025
-	 *  @param      string  $morecss            Add more css on select
2026
-	 *  @param      int     $hidepriceinlabel   1=Hide prices in label
2027
-	 *  @param      string  $warehouseStatus    warehouse status filter, following comma separated filter options can be used
2028
-	 *										    'warehouseopen' = select products from open warehouses,
2029
-	 *										    'warehouseclosed' = select products from closed warehouses,
2030
-	 *										    'warehouseinternal' = select products from warehouses for internal correct/transfer only
2031
-	 *  @return     array    				    Array of keys for json
2032
-	 */
2033
-	function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='')
2034
-	{
2035
-        // phpcs:enable
2036
-		global $langs,$conf,$user,$db;
2037
-
2038
-		$out='';
2039
-		$outarray=array();
2040
-
2041
-		$warehouseStatusArray = array();
2042
-		if (! empty($warehouseStatus))
2043
-		{
2044
-			require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
2045
-			if (preg_match('/warehouseclosed/', $warehouseStatus))
2046
-			{
2047
-				$warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
2048
-			}
2049
-			if (preg_match('/warehouseopen/', $warehouseStatus))
2050
-			{
2051
-				$warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
2052
-			}
2053
-			if (preg_match('/warehouseinternal/', $warehouseStatus))
2054
-			{
2055
-				$warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
2056
-			}
2057
-		}
2058
-
2059
-		$selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression";
2060
-		(count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock";
2061
-
2062
-		$sql = "SELECT ";
2063
-		$sql.= $selectFields . $selectFieldsGrouped;
2064
-
2065
-		if (! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2066
-		{
2067
-			//Product category
2068
-			$sql.= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
2069
-						FROM ".MAIN_DB_PREFIX."categorie_product
2070
-						WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
2071
-						LIMIT 1
2072
-				) AS categorie_product_id ";
2073
-		}
2074
-
2075
-		//Price by customer
2076
-		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
2077
-		{
2078
-			$sql.=', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
2079
-			$sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
2080
-			$selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
2081
-		}
2082
-
2083
-		// Multilang : we add translation
2084
-		if (! empty($conf->global->MAIN_MULTILANGS))
2085
-		{
2086
-			$sql.= ", pl.label as label_translated";
2087
-			$selectFields.= ", label_translated";
2088
-		}
2089
-		// Price by quantity
2090
-		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
2091
-		{
2092
-			$sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
2093
-			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2094
-			$sql.= " ORDER BY date_price";
2095
-			$sql.= " DESC LIMIT 1) as price_rowid";
2096
-			$sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";	// price_by_qty is 1 if some prices by qty exists in subtable
2097
-			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2098
-			$sql.= " ORDER BY date_price";
2099
-			$sql.= " DESC LIMIT 1) as price_by_qty";
2100
-			$selectFields.= ", price_rowid, price_by_qty";
2101
-		}
2102
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2103
-		if (count($warehouseStatusArray))
2104
-		{
2105
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
2106
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid";
2107
-		}
2108
-
2109
-		// include search in supplier ref
2110
-		if(!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
2111
-		{
2112
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2113
-		}
2114
-
2115
-		//Price by customer
2116
-		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2117
-			$sql.=" LEFT JOIN  ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
2118
-		}
2119
-		// Multilang : we add translation
2120
-		if (! empty($conf->global->MAIN_MULTILANGS))
2121
-		{
2122
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
2123
-		}
2124
-
2125
-		if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2126
-			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
2127
-		}
2128
-
2129
-		$sql.= ' WHERE p.entity IN ('.getEntity('product').')';
2130
-		if (count($warehouseStatusArray))
2131
-		{
2132
-			$sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))';
2133
-		}
2134
-
2135
-		if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2136
-			$sql .= " AND pac.rowid IS NULL";
2137
-		}
2138
-
2139
-		if ($finished == 0)
2140
-		{
2141
-			$sql.= " AND p.finished = ".$finished;
2142
-		}
2143
-		elseif ($finished == 1)
2144
-		{
2145
-			$sql.= " AND p.finished = ".$finished;
2146
-			if ($status >= 0)  $sql.= " AND p.tosell = ".$status;
2147
-		}
2148
-		elseif ($status >= 0)
2149
-		{
2150
-			$sql.= " AND p.tosell = ".$status;
2151
-		}
2152
-		if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
2153
-		// Add criteria on ref/label
2154
-		if ($filterkey != '')
2155
-		{
2156
-			$sql.=' AND (';
2157
-			$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2158
-			// For natural search
2159
-			$scrit = explode(' ', $filterkey);
2160
-			$i=0;
2161
-			if (count($scrit) > 1) $sql.="(";
2162
-			foreach ($scrit as $crit)
2163
-			{
2164
-				if ($i > 0) $sql.=" AND ";
2165
-				$sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
2166
-				if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
2167
-				if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION))
2168
-				{
2169
-					$sql.=" OR p.description LIKE '".$db->escape($prefix.$crit)."%'";
2170
-					if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.description LIKE '".$db->escape($prefix.$crit)."%'";
2171
-				}
2172
-				if (! empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql.=" OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
2173
-				$sql.=")";
2174
-				$i++;
2175
-			}
2176
-			if (count($scrit) > 1) $sql.=")";
2177
-		  	if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
2178
-			$sql.=')';
2179
-		}
2180
-		if (count($warehouseStatusArray))
2181
-		{
2182
-			$sql.= ' GROUP BY'.$selectFields;
2183
-		}
2184
-
2185
-		//Sort by category
2186
-		if(! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2187
-		{
2188
-			$sql .= " ORDER BY categorie_product_id ";
2189
-			//ASC OR DESC order
2190
-			($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .="ASC" : $sql .="DESC";
2191
-		}
2192
-		else
2193
-		{
2194
-			$sql.= $db->order("p.ref");
2195
-		}
2196
-
2197
-		$sql.= $db->plimit($limit, 0);
2198
-
2199
-		// Build output string
2200
-		dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
2201
-		$result=$this->db->query($sql);
2202
-		if ($result)
2203
-		{
2204
-			require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2205
-			require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2206
-			$num = $this->db->num_rows($result);
2207
-
2208
-			$events=null;
2209
-
2210
-			if (! $forcecombo)
2211
-			{
2212
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2213
-				$out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
2214
-			}
2215
-
2216
-			$out.='<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
2217
-
2218
-			$textifempty='';
2219
-			// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
2220
-			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
2221
-			if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2222
-			{
2223
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
2224
-				else $textifempty.=$langs->trans("All");
2225
-			}
2226
-			if ($showempty) $out.='<option value="0" selected>'.$textifempty.'</option>';
2227
-
2228
-			$i = 0;
2229
-			while ($num && $i < $num)
2230
-			{
2231
-				$opt = '';
2232
-				$optJson = array();
2233
-				$objp = $this->db->fetch_object($result);
2234
-
2235
-				if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)
2236
-				{ // Price by quantity will return many prices for the same product
2237
-					$sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
2238
-					$sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
2239
-					$sql.= " WHERE fk_product_price=".$objp->price_rowid;
2240
-					$sql.= " ORDER BY quantity ASC";
2241
-
2242
-					dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
2243
-					$result2 = $this->db->query($sql);
2244
-					if ($result2)
2245
-					{
2246
-						$nb_prices = $this->db->num_rows($result2);
2247
-						$j = 0;
2248
-						while ($nb_prices && $j < $nb_prices) {
2249
-							$objp2 = $this->db->fetch_object($result2);
2250
-
2251
-							$objp->price_by_qty_rowid = $objp2->rowid;
2252
-							$objp->price_by_qty_price_base_type = $objp2->price_base_type;
2253
-							$objp->price_by_qty_quantity = $objp2->quantity;
2254
-							$objp->price_by_qty_unitprice = $objp2->unitprice;
2255
-							$objp->price_by_qty_remise_percent = $objp2->remise_percent;
2256
-							// For backward compatibility
2257
-							$objp->quantity = $objp2->quantity;
2258
-							$objp->price = $objp2->price;
2259
-							$objp->unitprice = $objp2->unitprice;
2260
-							$objp->remise_percent = $objp2->remise_percent;
2261
-							$objp->remise = $objp2->remise;
2262
-
2263
-							$this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel);
2264
-
2265
-							$j++;
2266
-
2267
-							// Add new entry
2268
-							// "key" value of json key array is used by jQuery automatically as selected value
2269
-							// "label" value of json key array is used by jQuery automatically as text for combo box
2270
-							$out.=$opt;
2271
-							array_push($outarray, $optJson);
2272
-						}
2273
-					}
2274
-				}
2275
-				else
2276
-				{
2277
-					if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
2278
-						$price_product = new Product($this->db);
2279
-						$price_product->fetch($objp->rowid, '', '', 1);
2280
-						$priceparser = new PriceParser($this->db);
2281
-						$price_result = $priceparser->parseProduct($price_product);
2282
-						if ($price_result >= 0) {
2283
-							$objp->price = $price_result;
2284
-							$objp->unitprice = $price_result;
2285
-							//Calculate the VAT
2286
-							$objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
2287
-							$objp->price_ttc = price2num($objp->price_ttc,'MU');
2288
-						}
2289
-					}
2290
-					$this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);
2291
-					// Add new entry
2292
-					// "key" value of json key array is used by jQuery automatically as selected value
2293
-					// "label" value of json key array is used by jQuery automatically as text for combo box
2294
-					$out.=$opt;
2295
-					array_push($outarray, $optJson);
2296
-				}
2297
-
2298
-				$i++;
2299
-			}
2300
-
2301
-			$out.='</select>';
2302
-
2303
-			$this->db->free($result);
2304
-
2305
-			if (empty($outputmode)) return $out;
2306
-			return $outarray;
2307
-		}
2308
-		else
2309
-		{
2310
-			dol_print_error($db);
2311
-		}
2312
-	}
2313
-
2314
-	/**
2315
-	 * constructProductListOption
2316
-	 *
2317
-	 * @param 	resultset	$objp			    Resultset of fetch
2318
-	 * @param 	string		$opt			    Option (var used for returned value in string option format)
2319
-	 * @param 	string		$optJson		    Option (var used for returned value in json format)
2320
-	 * @param 	int			$price_level	    Price level
2321
-	 * @param 	string		$selected		    Preselected value
2322
-	 * @param   int         $hidepriceinlabel   Hide price in label
2323
-	 * @return	void
2324
-	 */
2325
-	private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)
2326
-	{
2327
-		global $langs,$conf,$user,$db;
2328
-
2329
-		$outkey='';
2330
-		$outval='';
2331
-		$outref='';
2332
-		$outlabel='';
2333
-		$outdesc='';
2334
-		$outbarcode='';
2335
-		$outtype='';
2336
-		$outprice_ht='';
2337
-		$outprice_ttc='';
2338
-		$outpricebasetype='';
2339
-		$outtva_tx='';
2340
-		$outqty=1;
2341
-		$outdiscount=0;
2342
-
2343
-		$maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
2344
-
2345
-		$label=$objp->label;
2346
-		if (! empty($objp->label_translated)) $label=$objp->label_translated;
2347
-		if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2348
-
2349
-		$outkey=$objp->rowid;
2350
-		$outref=$objp->ref;
2351
-		$outlabel=$objp->label;
2352
-		$outdesc=$objp->description;
2353
-		$outbarcode=$objp->barcode;
2354
-
2355
-		$outtype=$objp->fk_product_type;
2356
-		$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2357
-		$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2358
-
2359
-		$opt = '<option value="'.$objp->rowid.'"';
2360
-		$opt.= ($objp->rowid == $selected)?' selected':'';
2361
-		if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)
2362
-		{
2363
-			$opt.= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
2364
-		}
2365
-		if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
2366
-		{
2367
-			if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
2368
-			else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
2369
-		}
2370
-		$opt.= '>';
2371
-		$opt.= $objp->ref;
2372
-		if ($outbarcode) $opt.=' ('.$outbarcode.')';
2373
-		$opt.=' - '.dol_trunc($label,$maxlengtharticle);
2374
-
2375
-		$objRef = $objp->ref;
2376
-		if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2377
-		$outval.=$objRef;
2378
-		if ($outbarcode) $outval.=' ('.$outbarcode.')';
2379
-		$outval.=' - '.dol_trunc($label,$maxlengtharticle);
2380
-
2381
-		$found=0;
2382
-
2383
-		// Multiprice
2384
-		// If we need a particular price level (from 1 to 6)
2385
-		if (empty($hidepriceinlabel) && $price_level >= 1 && (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2386
-		{
2387
-			$sql = "SELECT price, price_ttc, price_base_type, tva_tx";
2388
-			$sql.= " FROM ".MAIN_DB_PREFIX."product_price";
2389
-			$sql.= " WHERE fk_product='".$objp->rowid."'";
2390
-			$sql.= " AND entity IN (".getEntity('productprice').")";
2391
-			$sql.= " AND price_level=".$price_level;
2392
-			$sql.= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
2393
-			$sql.= " LIMIT 1";
2394
-
2395
-			dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
2396
-			$result2 = $this->db->query($sql);
2397
-			if ($result2)
2398
-			{
2399
-				$objp2 = $this->db->fetch_object($result2);
2400
-				if ($objp2)
2401
-				{
2402
-					$found=1;
2403
-					if ($objp2->price_base_type == 'HT')
2404
-					{
2405
-						$opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2406
-						$outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2407
-					}
2408
-					else
2409
-					{
2410
-						$opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2411
-						$outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2412
-					}
2413
-					$outprice_ht=price($objp2->price);
2414
-					$outprice_ttc=price($objp2->price_ttc);
2415
-					$outpricebasetype=$objp2->price_base_type;
2416
-					$outtva_tx=$objp2->tva_tx;
2417
-				}
2418
-			}
2419
-			else
2420
-			{
2421
-				dol_print_error($this->db);
2422
-			}
2423
-		}
2424
-
2425
-		// Price by quantity
2426
-		if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2427
-		{
2428
-			$found = 1;
2429
-			$outqty=$objp->quantity;
2430
-			$outdiscount=$objp->remise_percent;
2431
-			if ($objp->quantity == 1)
2432
-			{
2433
-				$opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/";
2434
-				$outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
2435
-				$opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2436
-				$outval.=$langs->transnoentities("Unit");
2437
-			}
2438
-			else
2439
-			{
2440
-				$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2441
-				$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2442
-				$opt.= $langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2443
-				$outval.=$langs->transnoentities("Units");
2444
-			}
2445
-
2446
-			$outprice_ht=price($objp->unitprice);
2447
-			$outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
2448
-			$outpricebasetype=$objp->price_base_type;
2449
-			$outtva_tx=$objp->tva_tx;
2450
-		}
2451
-		if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
2452
-		{
2453
-			$opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2454
-			$outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2455
-		}
2456
-		if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
2457
-		{
2458
-			$opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2459
-			$outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2460
-		}
2461
-
2462
-		// Price by customer
2463
-		if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
2464
-		{
2465
-			if (!empty($objp->idprodcustprice))
2466
-			{
2467
-				$found = 1;
2468
-
2469
-				if ($objp->custprice_base_type == 'HT')
2470
-				{
2471
-					$opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2472
-					$outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2473
-				}
2474
-				else
2475
-				{
2476
-					$opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2477
-					$outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2478
-				}
2479
-
2480
-				$outprice_ht=price($objp->custprice);
2481
-				$outprice_ttc=price($objp->custprice_ttc);
2482
-				$outpricebasetype=$objp->custprice_base_type;
2483
-				$outtva_tx=$objp->custtva_tx;
2484
-			}
2485
-		}
2486
-
2487
-		// If level no defined or multiprice not found, we used the default price
2488
-		if (empty($hidepriceinlabel) && ! $found)
2489
-		{
2490
-			if ($objp->price_base_type == 'HT')
2491
-			{
2492
-				$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2493
-				$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2494
-			}
2495
-			else
2496
-			{
2497
-				$opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2498
-				$outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2499
-			}
2500
-			$outprice_ht=price($objp->price);
2501
-			$outprice_ttc=price($objp->price_ttc);
2502
-			$outpricebasetype=$objp->price_base_type;
2503
-			$outtva_tx=$objp->tva_tx;
2504
-		}
2505
-
2506
-		if (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
2507
-		{
2508
-			$opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
2509
-
2510
-			if ($objp->stock > 0) {
2511
-				$outval.= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2512
-			}elseif ($objp->stock <= 0) {
2513
-				$outval.= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2514
-			}
2515
-		}
2516
-
2517
-		if ($outdurationvalue && $outdurationunit)
2518
-		{
2519
-			$da=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
2520
-			if (isset($da[$outdurationunit]))
2521
-			{
2522
-				$key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');
2523
-				$opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);
2524
-				$outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);
2525
-			}
2526
-		}
2527
-
2528
-		$opt.= "</option>\n";
2529
-		$optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);
2530
-	}
1990
+            }
1991
+            if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1992
+            else if ($hidelabel > 1) {
1993
+                $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1994
+                if ($hidelabel == 2) {
1995
+                    print img_picto($langs->trans("Search"), 'search');
1996
+                }
1997
+            }
1998
+            print '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1999
+            if ($hidelabel == 3) {
2000
+                print img_picto($langs->trans("Search"), 'search');
2001
+            }
2002
+        }
2003
+        else
2004
+        {
2005
+            print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);
2006
+        }
2007
+    }
2531 2008
 
2532 2009
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2533
-	/**
2534
-	 *	Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
2535
-	 *
2536
-	 *	@param	int		$socid			Id third party
2537
-	 *	@param  string	$selected       Preselected product
2538
-	 *	@param  string	$htmlname       Name of HTML Select
2539
-	 *  @param	string	$filtertype     Filter on product type (''=nofilter, 0=product, 1=service)
2540
-	 *	@param  string	$filtre			For a SQL filter
2541
-	 *	@param	array	$ajaxoptions	Options for ajax_autocompleter
2542
-	 *  @param	int		$hidelabel		Hide label (0=no, 1=yes)
2543
-	 *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2544
-	 *	@return	void
2545
-	 */
2546
-	function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0)
2547
-	{
2010
+    /**
2011
+     *	Return list of products for a customer
2012
+     *
2013
+     *	@param      int		$selected           Preselected product
2014
+     *	@param      string	$htmlname           Name of select html
2015
+     *  @param		string	$filtertype         Filter on product type (''=nofilter, 0=product, 1=service)
2016
+     *	@param      int		$limit              Limit on number of returned lines
2017
+     *	@param      int		$price_level        Level of price to show
2018
+     * 	@param      string	$filterkey          Filter on product
2019
+     *	@param		int		$status             -1=Return all products, 0=Products not on sell, 1=Products on sell
2020
+     *  @param      int		$finished           Filter on finished field: 2=No filter
2021
+     *  @param      int		$outputmode         0=HTML select string, 1=Array
2022
+     *  @param      int		$socid     		    Thirdparty Id (to get also price dedicated to this customer)
2023
+     *  @param		string	$showempty		    '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
2024
+     * 	@param		int		$forcecombo		    Force to use combo box
2025
+     *  @param      string  $morecss            Add more css on select
2026
+     *  @param      int     $hidepriceinlabel   1=Hide prices in label
2027
+     *  @param      string  $warehouseStatus    warehouse status filter, following comma separated filter options can be used
2028
+     *										    'warehouseopen' = select products from open warehouses,
2029
+     *										    'warehouseclosed' = select products from closed warehouses,
2030
+     *										    'warehouseinternal' = select products from warehouses for internal correct/transfer only
2031
+     *  @return     array    				    Array of keys for json
2032
+     */
2033
+    function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='')
2034
+    {
2548 2035
         // phpcs:enable
2549
-		global $langs,$conf;
2550
-		global $price_level, $status, $finished;
2551
-
2552
-		$selected_input_value='';
2553
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2554
-		{
2555
-			if ($selected > 0)
2556
-			{
2557
-				require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2558
-				$producttmpselect = new Product($this->db);
2559
-				$producttmpselect->fetch($selected);
2560
-				$selected_input_value=$producttmpselect->ref;
2561
-				unset($producttmpselect);
2562
-			}
2563
-
2564
-			// mode=2 means suppliers products
2565
-			$urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
2566
-			print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
2567
-			print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
2568
-		}
2569
-		else
2570
-		{
2571
-			print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);
2572
-		}
2573
-	}
2036
+        global $langs,$conf,$user,$db;
2574 2037
 
2575
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2576
-	/**
2577
-	 *	Return list of suppliers products
2578
-	 *
2579
-	 *	@param	int		$socid   		Id societe fournisseur (0 pour aucun filtre)
2580
-	 *	@param  int		$selected       Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
2581
-	 *	@param  string	$htmlname       Nom de la zone select
2582
-	 *  @param	string	$filtertype     Filter on product type (''=nofilter, 0=product, 1=service)
2583
-	 *	@param  string	$filtre         Pour filtre sql
2584
-	 *	@param  string	$filterkey      Filtre des produits
2585
-	 *  @param  int		$statut         -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)
2586
-	 *  @param  int		$outputmode     0=HTML select string, 1=Array
2587
-	 *  @param  int     $limit          Limit of line number
2588
-	 *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2589
-	 *  @return array           		Array of keys for json
2590
-	 */
2591
-	function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0)
2592
-	{
2593
-        // phpcs:enable
2594
-		global $langs,$conf,$db;
2595
-
2596
-		$out='';
2597
-		$outarray=array();
2598
-
2599
-		$langs->load('stocks');
2600
-
2601
-		$sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,";
2602
-		$sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
2603
-		$sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
2604
-		$sql.= " pfp.supplier_reputation";
2605
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2606
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2607
-		if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
2608
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2609
-		$sql.= " WHERE p.entity IN (".getEntity('product').")";
2610
-		$sql.= " AND p.tobuy = 1";
2611
-		if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
2612
-		if (! empty($filtre)) $sql.=" ".$filtre;
2613
-		// Add criteria on ref/label
2614
-		if ($filterkey != '')
2615
-		{
2616
-			$sql.=' AND (';
2617
-			$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2618
-			// For natural search
2619
-			$scrit = explode(' ', $filterkey);
2620
-			$i=0;
2621
-			if (count($scrit) > 1) $sql.="(";
2622
-			foreach ($scrit as $crit)
2623
-			{
2624
-				if ($i > 0) $sql.=" AND ";
2625
-				$sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')";
2626
-				$i++;
2627
-			}
2628
-			if (count($scrit) > 1) $sql.=")";
2629
-			if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
2630
-			$sql.=')';
2631
-		}
2632
-		$sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
2633
-		$sql.= $db->plimit($limit, 0);
2634
-
2635
-		// Build output string
2636
-
2637
-		dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
2638
-		$result=$this->db->query($sql);
2639
-		if ($result)
2640
-		{
2641
-			require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2642
-
2643
-			$num = $this->db->num_rows($result);
2644
-
2645
-			//$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">';	// remove select to have id same with combo and ajax
2646
-			$out.='<select class="flat maxwidthonsmartphone" id="'.$htmlname.'" name="'.$htmlname.'">';
2647
-			if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
2648
-			else $out.='<option value="0">&nbsp;</option>';
2649
-
2650
-			$i = 0;
2651
-			while ($i < $num)
2652
-			{
2653
-				$objp = $this->db->fetch_object($result);
2654
-
2655
-				$outkey=$objp->idprodfournprice;                                                    // id in table of price
2656
-				if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid;   // id of product
2657
-
2658
-				$outref=$objp->ref;
2659
-				$outval='';
2660
-				$outqty=1;
2661
-				$outdiscount=0;
2662
-				$outtype=$objp->fk_product_type;
2663
-				$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2664
-				$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2665
-
2666
-				$opt = '<option value="'.$outkey.'"';
2667
-				if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
2668
-				if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';
2669
-				if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
2670
-				{
2671
-					$opt.= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqpercent="'.$objp->remise_percent.'"';
2672
-				}
2673
-				$opt.= '>';
2674
-
2675
-				$objRef = $objp->ref;
2676
-				if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2677
-				$objRefFourn = $objp->ref_fourn;
2678
-				if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
2679
-				$label = $objp->label;
2680
-				if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2681
-
2682
-				$opt.=$objp->ref;
2683
-				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2684
-					$opt.=' ('.$objp->ref_fourn.')';
2685
-				$opt.=' - ';
2686
-				$outval.=$objRef;
2687
-				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2688
-					$outval.=' ('.$objRefFourn.')';
2689
-				$outval.=' - ';
2690
-				$opt.=dol_trunc($label, 72).' - ';
2691
-				$outval.=dol_trunc($label, 72).' - ';
2692
-
2693
-				if (! empty($objp->idprodfournprice))
2694
-				{
2695
-					$outqty=$objp->quantity;
2696
-					$outdiscount=$objp->remise_percent;
2697
-					if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2698
-						$prod_supplier = new ProductFournisseur($this->db);
2699
-						$prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
2700
-						$prod_supplier->id = $objp->fk_product;
2701
-						$prod_supplier->fourn_qty = $objp->quantity;
2702
-						$prod_supplier->fourn_tva_tx = $objp->tva_tx;
2703
-						$prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
2704
-						$priceparser = new PriceParser($this->db);
2705
-						$price_result = $priceparser->parseProductSupplier($prod_supplier);
2706
-						if ($price_result >= 0) {
2707
-							$objp->fprice = $price_result;
2708
-							if ($objp->quantity >= 1)
2709
-							{
2710
-								$objp->unitprice = $objp->fprice / $objp->quantity;
2711
-							}
2712
-						}
2713
-					}
2714
-					if ($objp->quantity == 1)
2715
-					{
2716
-						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2717
-						$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
2718
-						$opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2719
-						$outval.=$langs->transnoentities("Unit");
2720
-					}
2721
-					else
2722
-					{
2723
-						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2724
-						$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2725
-						$opt.= ' '.$langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2726
-						$outval.= ' '.$langs->transnoentities("Units");
2727
-					}
2038
+        $out='';
2039
+        $outarray=array();
2728 2040
 
2729
-					if ($objp->quantity >= 1)
2730
-					{
2731
-						$opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2732
-						$outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2733
-					}
2734
-					if ($objp->remise_percent >= 1)
2735
-					{
2736
-						$opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2737
-						$outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2738
-					}
2739
-					if ($objp->duration)
2740
-					{
2741
-						$opt .= " - ".$objp->duration;
2742
-						$outval.=" - ".$objp->duration;
2743
-					}
2744
-					if (! $socid)
2745
-					{
2746
-						$opt .= " - ".dol_trunc($objp->name,8);
2747
-						$outval.=" - ".dol_trunc($objp->name,8);
2748
-					}
2749
-					if ($objp->supplier_reputation)
2750
-					{
2751
-						//TODO dictionary
2752
-						$reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
2041
+        $warehouseStatusArray = array();
2042
+        if (! empty($warehouseStatus))
2043
+        {
2044
+            require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
2045
+            if (preg_match('/warehouseclosed/', $warehouseStatus))
2046
+            {
2047
+                $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
2048
+            }
2049
+            if (preg_match('/warehouseopen/', $warehouseStatus))
2050
+            {
2051
+                $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
2052
+            }
2053
+            if (preg_match('/warehouseinternal/', $warehouseStatus))
2054
+            {
2055
+                $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
2056
+            }
2057
+        }
2753 2058
 
2754
-						$opt .= " - ".$reputations[$objp->supplier_reputation];
2755
-						$outval.=" - ".$reputations[$objp->supplier_reputation];
2756
-					}
2757
-				}
2758
-				else
2759
-				{
2760
-					if (empty($alsoproductwithnosupplierprice))     // No supplier price defined for couple product/supplier
2761
-					{
2762
-						$opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2763
-						$outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2764
-					}
2765
-					else                                            // No supplier price defined for product, even on other suppliers
2766
-					{
2767
-						$opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2768
-						$outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2769
-					}
2770
-				}
2771
-				$opt .= "</option>\n";
2772
-
2773
-
2774
-				// Add new entry
2775
-				// "key" value of json key array is used by jQuery automatically as selected value
2776
-				// "label" value of json key array is used by jQuery automatically as text for combo box
2777
-				$out.=$opt;
2778
-				array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));
2779
-				// Exemple of var_dump $outarray
2780
-				// array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
2781
-				//           ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
2782
-				//      	 ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
2783
-				//}
2784
-				//var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
2785
-				//$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
2786
-				//var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
2787
-
2788
-				$i++;
2789
-			}
2790
-			$out.='</select>';
2791
-
2792
-			$this->db->free($result);
2793
-
2794
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2795
-			$out.=ajax_combobox($htmlname);
2796
-
2797
-			if (empty($outputmode)) return $out;
2798
-			return $outarray;
2799
-		}
2800
-		else
2801
-		{
2802
-			dol_print_error($this->db);
2803
-		}
2804
-	}
2059
+        $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression";
2060
+        (count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock";
2805 2061
 
2806
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2807
-	/**
2808
-	 *	Return list of suppliers prices for a product
2809
-	 *
2810
-	 *  @param	    int		$productid       	Id of product
2811
-	 *  @param      string	$htmlname        	Name of HTML field
2812
-	 *  @param      int		$selected_supplier  Pre-selected supplier if more than 1 result
2813
-	 *  @return	    void
2814
-	 */
2815
-	function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')
2816
-	{
2817
-        // phpcs:enable
2818
-		global $langs,$conf;
2819
-
2820
-		$langs->load('stocks');
2821
-
2822
-		$sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,";
2823
-		$sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
2824
-		$sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
2825
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2826
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2827
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2828
-		$sql.= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
2829
-		$sql.= " AND p.tobuy = 1";
2830
-		$sql.= " AND s.fournisseur = 1";
2831
-		$sql.= " AND p.rowid = ".$productid;
2832
-		$sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
2833
-
2834
-		dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
2835
-		$result=$this->db->query($sql);
2836
-
2837
-		if ($result)
2838
-		{
2839
-			$num = $this->db->num_rows($result);
2840
-
2841
-			$form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2842
-
2843
-			if (! $num)
2844
-			{
2845
-				$form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
2846
-			}
2847
-			else
2848
-			{
2849
-				require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2850
-				$form.= '<option value="0">&nbsp;</option>';
2851
-
2852
-				$i = 0;
2853
-				while ($i < $num)
2854
-				{
2855
-					$objp = $this->db->fetch_object($result);
2856
-
2857
-					$opt = '<option value="'.$objp->idprodfournprice.'"';
2858
-					//if there is only one supplier, preselect it
2859
-					if($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
2860
-						$opt .= ' selected';
2861
-					}
2862
-					$opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
2863
-
2864
-					if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2865
-						$prod_supplier = new ProductFournisseur($this->db);
2866
-						$prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
2867
-						$prod_supplier->id = $productid;
2868
-						$prod_supplier->fourn_qty = $objp->quantity;
2869
-						$prod_supplier->fourn_tva_tx = $objp->tva_tx;
2870
-						$prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
2871
-						$priceparser = new PriceParser($this->db);
2872
-						$price_result = $priceparser->parseProductSupplier($prod_supplier);
2873
-						if ($price_result >= 0) {
2874
-							$objp->fprice = $price_result;
2875
-							if ($objp->quantity >= 1)
2876
-							{
2877
-								$objp->unitprice = $objp->fprice / $objp->quantity;
2878
-							}
2879
-						}
2880
-					}
2881
-					if ($objp->quantity == 1)
2882
-					{
2883
-						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2884
-					}
2062
+        $sql = "SELECT ";
2063
+        $sql.= $selectFields . $selectFieldsGrouped;
2885 2064
 
2886
-					$opt.= $objp->quantity.' ';
2065
+        if (! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2066
+        {
2067
+            //Product category
2068
+            $sql.= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
2069
+						FROM ".MAIN_DB_PREFIX."categorie_product
2070
+						WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
2071
+						LIMIT 1
2072
+				) AS categorie_product_id ";
2073
+        }
2887 2074
 
2888
-					if ($objp->quantity == 1)
2889
-					{
2890
-						$opt.= $langs->trans("Unit");
2891
-					}
2892
-					else
2893
-					{
2894
-						$opt.= $langs->trans("Units");
2895
-					}
2896
-					if ($objp->quantity > 1)
2897
-					{
2898
-						$opt.=" - ";
2899
-						$opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
2900
-					}
2901
-					if ($objp->duration) $opt .= " - ".$objp->duration;
2902
-					$opt .= "</option>\n";
2903
-
2904
-					$form.= $opt;
2905
-					$i++;
2906
-				}
2907
-			}
2908
-
2909
-			$form.= '</select>';
2910
-			$this->db->free($result);
2911
-			return $form;
2912
-		}
2913
-		else
2914
-		{
2915
-			dol_print_error($this->db);
2916
-		}
2917
-	}
2075
+        //Price by customer
2076
+        if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
2077
+        {
2078
+            $sql.=', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
2079
+            $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
2080
+            $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
2081
+        }
2918 2082
 
2919
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2920
-	/**
2921
-	 *    Return list of delivery address
2922
-	 *
2923
-	 *    @param    string	$selected          	Id contact pre-selectionn
2924
-	 *    @param    int		$socid				Id of company
2925
-	 *    @param    string	$htmlname          	Name of HTML field
2926
-	 *    @param    int		$showempty         	Add an empty field
2927
-	 *    @return	integer|null
2928
-	 */
2929
-	function select_address($selected, $socid, $htmlname='address_id',$showempty=0)
2930
-	{
2931
-        // phpcs:enable
2932
-		// looking for users
2933
-		$sql = "SELECT a.rowid, a.label";
2934
-		$sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
2935
-		$sql .= " WHERE a.fk_soc = ".$socid;
2936
-		$sql .= " ORDER BY a.label ASC";
2937
-
2938
-		dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
2939
-		$resql=$this->db->query($sql);
2940
-		if ($resql)
2941
-		{
2942
-			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2943
-			if ($showempty) print '<option value="0">&nbsp;</option>';
2944
-			$num = $this->db->num_rows($resql);
2945
-			$i = 0;
2946
-			if ($num)
2947
-			{
2948
-				while ($i < $num)
2949
-				{
2950
-					$obj = $this->db->fetch_object($resql);
2951
-
2952
-					if ($selected && $selected == $obj->rowid)
2953
-					{
2954
-						print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
2955
-					}
2956
-					else
2957
-					{
2958
-						print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
2959
-					}
2960
-					$i++;
2961
-				}
2962
-			}
2963
-			print '</select>';
2964
-			return $num;
2965
-		}
2966
-		else
2967
-		{
2968
-			dol_print_error($this->db);
2969
-		}
2970
-	}
2083
+        // Multilang : we add translation
2084
+        if (! empty($conf->global->MAIN_MULTILANGS))
2085
+        {
2086
+            $sql.= ", pl.label as label_translated";
2087
+            $selectFields.= ", label_translated";
2088
+        }
2089
+        // Price by quantity
2090
+        if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
2091
+        {
2092
+            $sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
2093
+            if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2094
+            $sql.= " ORDER BY date_price";
2095
+            $sql.= " DESC LIMIT 1) as price_rowid";
2096
+            $sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";	// price_by_qty is 1 if some prices by qty exists in subtable
2097
+            if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2098
+            $sql.= " ORDER BY date_price";
2099
+            $sql.= " DESC LIMIT 1) as price_by_qty";
2100
+            $selectFields.= ", price_rowid, price_by_qty";
2101
+        }
2102
+        $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2103
+        if (count($warehouseStatusArray))
2104
+        {
2105
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
2106
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid";
2107
+        }
2971 2108
 
2109
+        // include search in supplier ref
2110
+        if(!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
2111
+        {
2112
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2113
+        }
2972 2114
 
2973
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2974
-	/**
2975
-	 *      Load into cache list of payment terms
2976
-	 *
2977
-	 *      @return     int             Nb of lines loaded, <0 if KO
2978
-	 */
2979
-	function load_cache_conditions_paiements()
2980
-	{
2981
-        // phpcs:enable
2982
-		global $langs;
2983
-
2984
-		$num = count($this->cache_conditions_paiements);
2985
-		if ($num > 0) return 0;    // Cache already loaded
2986
-
2987
-		dol_syslog(__METHOD__, LOG_DEBUG);
2988
-
2989
-		$sql = "SELECT rowid, code, libelle as label";
2990
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
2991
-		$sql.= " WHERE entity IN (".getEntity('c_payment_term').")";
2992
-		$sql.= " AND active > 0";
2993
-		$sql.= " ORDER BY sortorder";
2994
-
2995
-		$resql = $this->db->query($sql);
2996
-		if ($resql)
2997
-		{
2998
-			$num = $this->db->num_rows($resql);
2999
-			$i = 0;
3000
-			while ($i < $num)
3001
-			{
3002
-				$obj = $this->db->fetch_object($resql);
3003
-
3004
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3005
-				$label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:''));
3006
-				$this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
3007
-				$this->cache_conditions_paiements[$obj->rowid]['label']=$label;
3008
-				$i++;
3009
-			}
3010
-
3011
-			//$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1);		// We use the field sortorder of table
3012
-
3013
-			return $num;
3014
-		}
3015
-		else
3016
-		{
3017
-			dol_print_error($this->db);
3018
-			return -1;
3019
-		}
3020
-	}
2115
+        //Price by customer
2116
+        if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2117
+            $sql.=" LEFT JOIN  ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
2118
+        }
2119
+        // Multilang : we add translation
2120
+        if (! empty($conf->global->MAIN_MULTILANGS))
2121
+        {
2122
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
2123
+        }
3021 2124
 
3022
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3023
-	/**
3024
-	 *      Charge dans cache la liste des délais de livraison possibles
3025
-	 *
3026
-	 *      @return     int             Nb of lines loaded, <0 if KO
3027
-	 */
3028
-	function load_cache_availability()
3029
-	{
3030
-        // phpcs:enable
3031
-		global $langs;
3032
-
3033
-		$num = count($this->cache_availability);
3034
-		if ($num > 0) return 0;    // Cache already loaded
3035
-
3036
-		dol_syslog(__METHOD__, LOG_DEBUG);
3037
-
3038
-		$langs->load('propal');
3039
-
3040
-		$sql = "SELECT rowid, code, label";
3041
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
3042
-		$sql.= " WHERE active > 0";
3043
-
3044
-		$resql = $this->db->query($sql);
3045
-		if ($resql)
3046
-		{
3047
-			$num = $this->db->num_rows($resql);
3048
-			$i = 0;
3049
-			while ($i < $num)
3050
-			{
3051
-				$obj = $this->db->fetch_object($resql);
3052
-
3053
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3054
-				$label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
3055
-				$this->cache_availability[$obj->rowid]['code'] =$obj->code;
3056
-				$this->cache_availability[$obj->rowid]['label']=$label;
3057
-				$i++;
3058
-			}
3059
-
3060
-			$this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
3061
-
3062
-			return $num;
3063
-		}
3064
-		else
3065
-		{
3066
-			dol_print_error($this->db);
3067
-			return -1;
3068
-		}
3069
-	}
3070
-
3071
-	/**
3072
-	 *      Retourne la liste des types de delais de livraison possibles
3073
-	 *
3074
-	 *      @param	int		$selected        Id du type de delais pre-selectionne
3075
-	 *      @param  string	$htmlname        Nom de la zone select
3076
-	 *      @param  string	$filtertype      To add a filter
3077
-	 *		@param	int		$addempty		Add empty entry
3078
-	 *		@return	void
3079
-	 */
3080
-	function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)
3081
-	{
3082
-		global $langs,$user;
3083
-
3084
-		$this->load_cache_availability();
3085
-
3086
-		dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3087
-
3088
-		print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
3089
-		if ($addempty) print '<option value="0">&nbsp;</option>';
3090
-		foreach($this->cache_availability as $id => $arrayavailability)
3091
-		{
3092
-			if ($selected == $id)
3093
-			{
3094
-				print '<option value="'.$id.'" selected>';
3095
-			}
3096
-			else
3097
-			{
3098
-				print '<option value="'.$id.'">';
3099
-			}
3100
-			print $arrayavailability['label'];
3101
-			print '</option>';
3102
-		}
3103
-		print '</select>';
3104
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3105
-	}
3106
-
3107
-	/**
3108
-	 *      Load into cache cache_demand_reason, array of input reasons
3109
-	 *
3110
-	 *      @return     int             Nb of lines loaded, <0 if KO
3111
-	 */
3112
-	function loadCacheInputReason()
3113
-	{
3114
-		global $langs;
3115
-
3116
-		$num = count($this->cache_demand_reason);
3117
-		if ($num > 0) return 0;    // Cache already loaded
3118
-
3119
-		$sql = "SELECT rowid, code, label";
3120
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
3121
-		$sql.= " WHERE active > 0";
3122
-
3123
-		$resql = $this->db->query($sql);
3124
-		if ($resql)
3125
-		{
3126
-			$num = $this->db->num_rows($resql);
3127
-			$i = 0;
3128
-			$tmparray=array();
3129
-			while ($i < $num)
3130
-			{
3131
-				$obj = $this->db->fetch_object($resql);
3132
-
3133
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3134
-				$label=($obj->label!='-'?$obj->label:'');
3135
-				if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
3136
-				if ($langs->trans($obj->code) != $obj->code) $label=$langs->trans($obj->code);																// So translation key SRC_XXX will work
3137
-
3138
-				$tmparray[$obj->rowid]['id']   =$obj->rowid;
3139
-				$tmparray[$obj->rowid]['code'] =$obj->code;
3140
-				$tmparray[$obj->rowid]['label']=$label;
3141
-				$i++;
3142
-			}
3143
-
3144
-			$this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
3145
-
3146
-			unset($tmparray);
3147
-			return $num;
3148
-		}
3149
-		else
3150
-		{
3151
-			dol_print_error($this->db);
3152
-			return -1;
3153
-		}
3154
-	}
3155
-
3156
-	/**
3157
-	 *	Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
3158
-	 *  List found into table c_input_reason loaded by loadCacheInputReason
3159
-	 *
3160
-	 *  @param	int		$selected        Id or code of type origin to select by default
3161
-	 *  @param  string	$htmlname        Nom de la zone select
3162
-	 *  @param  string	$exclude         To exclude a code value (Example: SRC_PROP)
3163
-	 *	@param	int		$addempty		 Add an empty entry
3164
-	 *	@return	void
3165
-	 */
3166
-	function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
3167
-	{
3168
-		global $langs,$user;
3169
-
3170
-		$this->loadCacheInputReason();
3171
-
3172
-		print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3173
-		if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
3174
-		foreach($this->cache_demand_reason as $id => $arraydemandreason)
3175
-		{
3176
-			if ($arraydemandreason['code']==$exclude) continue;
3177
-
3178
-			if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
3179
-			{
3180
-				print '<option value="'.$arraydemandreason['id'].'" selected>';
3181
-			}
3182
-			else
3183
-			{
3184
-				print '<option value="'.$arraydemandreason['id'].'">';
3185
-			}
3186
-			$label=$arraydemandreason['label'];	// Translation of label was already done into the ->loadCacheInputReason
3187
-			print $langs->trans($label);
3188
-			print '</option>';
3189
-		}
3190
-		print '</select>';
3191
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3192
-	}
2125
+        if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2126
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
2127
+        }
3193 2128
 
3194
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3195
-	/**
3196
-	 *      Charge dans cache la liste des types de paiements possibles
3197
-	 *
3198
-	 *      @return     int                 Nb of lines loaded, <0 if KO
3199
-	 */
3200
-	function load_cache_types_paiements()
3201
-	{
3202
-        // phpcs:enable
3203
-		global $langs;
3204
-
3205
-		$num=count($this->cache_types_paiements);
3206
-		if ($num > 0) return $num;    // Cache already loaded
3207
-
3208
-		dol_syslog(__METHOD__, LOG_DEBUG);
3209
-
3210
-		$this->cache_types_paiements = array();
3211
-
3212
-		$sql = "SELECT id, code, libelle as label, type, active";
3213
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
3214
-		$sql.= " WHERE entity IN (".getEntity('c_paiement').")";
3215
-		//if ($active >= 0) $sql.= " AND active = ".$active;
3216
-
3217
-		$resql = $this->db->query($sql);
3218
-		if ($resql)
3219
-		{
3220
-			$num = $this->db->num_rows($resql);
3221
-			$i = 0;
3222
-			while ($i < $num)
3223
-			{
3224
-				$obj = $this->db->fetch_object($resql);
3225
-
3226
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3227
-				$label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
3228
-				$this->cache_types_paiements[$obj->id]['id'] =$obj->id;
3229
-				$this->cache_types_paiements[$obj->id]['code'] =$obj->code;
3230
-				$this->cache_types_paiements[$obj->id]['label']=$label;
3231
-				$this->cache_types_paiements[$obj->id]['type'] =$obj->type;
3232
-				$this->cache_types_paiements[$obj->id]['active'] =$obj->active;
3233
-				$i++;
3234
-			}
3235
-
3236
-			$this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
3237
-
3238
-			return $num;
3239
-		}
3240
-		else
3241
-		{
3242
-			dol_print_error($this->db);
3243
-			return -1;
3244
-		}
3245
-	}
2129
+        $sql.= ' WHERE p.entity IN ('.getEntity('product').')';
2130
+        if (count($warehouseStatusArray))
2131
+        {
2132
+            $sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))';
2133
+        }
3246 2134
 
2135
+        if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2136
+            $sql .= " AND pac.rowid IS NULL";
2137
+        }
3247 2138
 
3248
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3249
-	/**
3250
-	 *      Return list of payment modes.
3251
-	 *      Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
3252
-	 *      See instead to force the default value by the caller.
3253
-	 *
3254
-	 *      @param	int		$selected		Id of payment term to preselect by default
3255
-	 *      @param	string	$htmlname		Nom de la zone select
3256
-	 *      @param	int		$filtertype		Not used
3257
-	 *		@param	int		$addempty		Add an empty entry
3258
-	 * 		@param	int		$noinfoadmin		0=Add admin info, 1=Disable admin info
3259
-	 * 		@param	string	$morecss			Add more CSS on select tag
3260
-	 *		@return	void
3261
-	 */
3262
-	function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='')
3263
-	{
3264
-        // phpcs:enable
3265
-		global $langs, $user, $conf;
3266
-
3267
-		dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3268
-
3269
-		$this->load_cache_conditions_paiements();
3270
-
3271
-		// Set default value if not already set by caller
3272
-		if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
3273
-
3274
-		print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3275
-		if ($addempty) print '<option value="0">&nbsp;</option>';
3276
-		foreach($this->cache_conditions_paiements as $id => $arrayconditions)
3277
-		{
3278
-			if ($selected == $id)
3279
-			{
3280
-				print '<option value="'.$id.'" selected>';
3281
-			}
3282
-			else
3283
-			{
3284
-				print '<option value="'.$id.'">';
3285
-			}
3286
-			print $arrayconditions['label'];
3287
-			print '</option>';
3288
-		}
3289
-		print '</select>';
3290
-		if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3291
-	}
2139
+        if ($finished == 0)
2140
+        {
2141
+            $sql.= " AND p.finished = ".$finished;
2142
+        }
2143
+        elseif ($finished == 1)
2144
+        {
2145
+            $sql.= " AND p.finished = ".$finished;
2146
+            if ($status >= 0)  $sql.= " AND p.tosell = ".$status;
2147
+        }
2148
+        elseif ($status >= 0)
2149
+        {
2150
+            $sql.= " AND p.tosell = ".$status;
2151
+        }
2152
+        if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
2153
+        // Add criteria on ref/label
2154
+        if ($filterkey != '')
2155
+        {
2156
+            $sql.=' AND (';
2157
+            $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2158
+            // For natural search
2159
+            $scrit = explode(' ', $filterkey);
2160
+            $i=0;
2161
+            if (count($scrit) > 1) $sql.="(";
2162
+            foreach ($scrit as $crit)
2163
+            {
2164
+                if ($i > 0) $sql.=" AND ";
2165
+                $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
2166
+                if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
2167
+                if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION))
2168
+                {
2169
+                    $sql.=" OR p.description LIKE '".$db->escape($prefix.$crit)."%'";
2170
+                    if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.description LIKE '".$db->escape($prefix.$crit)."%'";
2171
+                }
2172
+                if (! empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql.=" OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
2173
+                $sql.=")";
2174
+                $i++;
2175
+            }
2176
+            if (count($scrit) > 1) $sql.=")";
2177
+                if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
2178
+            $sql.=')';
2179
+        }
2180
+        if (count($warehouseStatusArray))
2181
+        {
2182
+            $sql.= ' GROUP BY'.$selectFields;
2183
+        }
3292 2184
 
2185
+        //Sort by category
2186
+        if(! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2187
+        {
2188
+            $sql .= " ORDER BY categorie_product_id ";
2189
+            //ASC OR DESC order
2190
+            ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .="ASC" : $sql .="DESC";
2191
+        }
2192
+        else
2193
+        {
2194
+            $sql.= $db->order("p.ref");
2195
+        }
3293 2196
 
3294
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3295
-	/**
3296
-	 *      Return list of payment methods
3297
-	 *
3298
-	 *      @param	string	$selected       Id du mode de paiement pre-selectionne
3299
-	 *      @param  string	$htmlname       Nom de la zone select
3300
-	 *      @param  string	$filtertype     To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
3301
-	 *      @param  int		$format         0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
3302
-	 *      @param  int		$empty			1=peut etre vide, 0 sinon
3303
-	 * 		@param	int		$noadmininfo	0=Add admin info, 1=Disable admin info
3304
-	 *      @param  int		$maxlength      Max length of label
3305
-	 *      @param  int     $active         Active or not, -1 = all
3306
-	 *      @param  string  $morecss        Add more CSS on select tag
3307
-	 * 		@return	void
3308
-	 */
3309
-	function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=1, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')
3310
-	{
3311
-        // phpcs:enable
3312
-		global $langs,$user;
3313
-
3314
-		dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
3315
-
3316
-		$filterarray=array();
3317
-		if ($filtertype == 'CRDT')  	$filterarray=array(0,2,3);
3318
-		elseif ($filtertype == 'DBIT') 	$filterarray=array(1,2,3);
3319
-		elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
3320
-
3321
-		$this->load_cache_types_paiements();
3322
-
3323
-		print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3324
-		if ($empty) print '<option value="">&nbsp;</option>';
3325
-		foreach($this->cache_types_paiements as $id => $arraytypes)
3326
-		{
3327
-			// If not good status
3328
-			if ($active >= 0 && $arraytypes['active'] != $active) continue;
3329
-
3330
-			// On passe si on a demande de filtrer sur des modes de paiments particuliers
3331
-			if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
3332
-
3333
-			// We discard empty line if showempty is on because an empty line has already been output.
3334
-			if ($empty && empty($arraytypes['code'])) continue;
3335
-
3336
-			if ($format == 0) print '<option value="'.$id.'"';
3337
-			elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
3338
-			elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
3339
-			elseif ($format == 3) print '<option value="'.$id.'"';
3340
-			// Si selected est text, on compare avec code, sinon avec id
3341
-			if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
3342
-			elseif ($selected == $id) print ' selected';
3343
-			print '>';
3344
-			if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3345
-			elseif ($format == 1) $value=$arraytypes['code'];
3346
-			elseif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3347
-			elseif ($format == 3) $value=$arraytypes['code'];
3348
-			print $value?$value:'&nbsp;';
3349
-			print '</option>';
3350
-		}
3351
-		print '</select>';
3352
-		if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3353
-	}
3354
-
3355
-
3356
-	/**
3357
-	 *  Selection HT or TTC
3358
-	 *
3359
-	 *  @param	string	$selected       Id pre-selectionne
3360
-	 *  @param  string	$htmlname       Nom de la zone select
3361
-	 * 	@return	string					Code of HTML select to chose tax or not
3362
-	 */
3363
-	function selectPriceBaseType($selected='',$htmlname='price_base_type')
3364
-	{
3365
-		global $langs;
3366
-
3367
-		$return='';
3368
-
3369
-		$return.= '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3370
-		$options = array(
3371
-			'HT'=>$langs->trans("HT"),
3372
-			'TTC'=>$langs->trans("TTC")
3373
-		);
3374
-		foreach($options as $id => $value)
3375
-		{
3376
-			if ($selected == $id)
3377
-			{
3378
-				$return.= '<option value="'.$id.'" selected>'.$value;
3379
-			}
3380
-			else
3381
-			{
3382
-				$return.= '<option value="'.$id.'">'.$value;
3383
-			}
3384
-			$return.= '</option>';
3385
-		}
3386
-		$return.= '</select>';
3387
-
3388
-		return $return;
3389
-	}
3390
-
3391
-	/**
3392
-	 *  Return a HTML select list of shipping mode
3393
-	 *
3394
-	 *  @param	string	$selected          Id shipping mode pre-selected
3395
-	 *  @param  string	$htmlname          Name of select zone
3396
-	 *  @param  string	$filtre            To filter list
3397
-	 *  @param  int		$useempty          1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3398
-	 *  @param  string	$moreattrib        To add more attribute on select
3399
-	 * 	@return	void
3400
-	 */
3401
-	function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')
3402
-	{
3403
-		global $langs, $conf, $user;
3404
-
3405
-		$langs->load("admin");
3406
-		$langs->load("deliveries");
3407
-
3408
-		$sql = "SELECT rowid, code, libelle as label";
3409
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
3410
-		$sql.= " WHERE active > 0";
3411
-		if ($filtre) $sql.=" AND ".$filtre;
3412
-		$sql.= " ORDER BY libelle ASC";
3413
-
3414
-		dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
3415
-		$result = $this->db->query($sql);
3416
-		if ($result) {
3417
-			$num = $this->db->num_rows($result);
3418
-			$i = 0;
3419
-			if ($num) {
3420
-				print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3421
-				if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
3422
-					print '<option value="-1">&nbsp;</option>';
3423
-				}
3424
-				while ($i < $num) {
3425
-					$obj = $this->db->fetch_object($result);
3426
-					if ($selected == $obj->rowid) {
3427
-						print '<option value="'.$obj->rowid.'" selected>';
3428
-					} else {
3429
-						print '<option value="'.$obj->rowid.'">';
3430
-					}
3431
-					print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
3432
-					print '</option>';
3433
-					$i++;
3434
-				}
3435
-				print "</select>";
3436
-				if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3437
-			} else {
3438
-				print $langs->trans("NoShippingMethodDefined");
3439
-			}
3440
-		} else {
3441
-			dol_print_error($this->db);
3442
-		}
3443
-	}
3444
-
3445
-	/**
3446
-	 *    Display form to select shipping mode
3447
-	 *
3448
-	 *    @param	string	$page        Page
3449
-	 *    @param    int		$selected    Id of shipping mode
3450
-	 *    @param    string	$htmlname    Name of select html field
3451
-	 *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3452
-	 *    @return	void
3453
-	 */
3454
-	function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
3455
-	{
3456
-		global $langs, $db;
3457
-
3458
-		$langs->load("deliveries");
3459
-
3460
-		if ($htmlname != "none") {
3461
-			print '<form method="POST" action="'.$page.'">';
3462
-			print '<input type="hidden" name="action" value="setshippingmethod">';
3463
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
3464
-			$this->selectShippingMethod($selected, $htmlname, '', $addempty);
3465
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
3466
-			print '</form>';
3467
-		} else {
3468
-			if ($selected) {
3469
-				$code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
3470
-				print $langs->trans("SendingMethod".strtoupper($code));
3471
-			} else {
3472
-				print "&nbsp;";
3473
-			}
3474
-		}
3475
-	}
3476
-
3477
-	/**
3478
-	 * Creates HTML last in cycle situation invoices selector
3479
-	 *
3480
-	 * @param     string  $selected   		Preselected ID
3481
-	 * @param     int     $socid      		Company ID
3482
-	 *
3483
-	 * @return    string                     HTML select
3484
-	 */
3485
-	function selectSituationInvoices($selected = '', $socid = 0)
3486
-	{
3487
-		global $langs;
3488
-
3489
-		$langs->load('bills');
3490
-
3491
-		$opt = '<option value ="" selected></option>';
3492
-		$sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';
3493
-		$sql.= ' ORDER by situation_cycle_ref, situation_counter desc';
3494
-		$resql = $this->db->query($sql);
3495
-		if ($resql && $this->db->num_rows($resql) > 0) {
3496
-			// Last seen cycle
3497
-			$ref = 0;
3498
-			while ($obj = $this->db->fetch_object($resql)){
3499
-				//Same company ?
3500
-			    if ($socid == $obj->fk_soc) {
3501
-					//Same cycle ?
3502
-			        if ($obj->situation_cycle_ref != $ref) {
3503
-						// Just seen this cycle
3504
-			            $ref = $obj->situation_cycle_ref;
3505
-						//not final ?
3506
-			            if ($obj->situation_final != 1) {
3507
-							//Not prov?
3508
-			                if (substr($obj->ref, 1, 4) != 'PROV') {
3509
-			                    if ($selected == $obj->rowid) {
3510
-			                        $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
3511
-								} else {
3512
-								    $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
3513
-								}
3514
-							}
3515
-						}
3516
-					}
3517
-				}
3518
-			}
3519
-		}
3520
-		else
3521
-		{
3522
-				dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
3523
-		}
3524
-		if ($opt == '<option value ="" selected></option>')
3525
-		{
3526
-			$opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
3527
-		}
3528
-		return $opt;
3529
-	}
3530
-
3531
-	/**
3532
-	 *      Creates HTML units selector (code => label)
3533
-	 *
3534
-	 *      @param	string	$selected       Preselected Unit ID
3535
-	 *      @param  string	$htmlname       Select name
3536
-	 *      @param	int		$showempty		Add a nempty line
3537
-	 * 		@return	string                  HTML select
3538
-	 */
3539
-	function selectUnits($selected = '', $htmlname = 'units', $showempty=0)
3540
-	{
3541
-		global $langs;
3542
-
3543
-		$langs->load('products');
3544
-
3545
-		$return= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
3546
-
3547
-		$sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
3548
-		$sql.= ' WHERE active > 0';
3549
-
3550
-		$resql = $this->db->query($sql);
3551
-		if($resql && $this->db->num_rows($resql) > 0)
3552
-		{
3553
-			if ($showempty) $return .= '<option value="none"></option>';
3554
-
3555
-			while($res = $this->db->fetch_object($resql))
3556
-			{
3557
-			    $unitLabel = $res->label;
3558
-			    if (! empty($langs->tab_translate['unit'.$res->code]))	// check if Translation is available before
3559
-			    {
3560
-			        $unitLabel = $langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label;
3561
-			    }
3562
-
3563
-				if ($selected == $res->rowid)
3564
-				{
3565
-				    $return.='<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
3566
-				}
3567
-				else
3568
-				{
3569
-				    $return.='<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
3570
-				}
3571
-			}
3572
-			$return.='</select>';
3573
-		}
3574
-		return $return;
3575
-	}
2197
+        $sql.= $db->plimit($limit, 0);
3576 2198
 
3577
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3578
-	/**
3579
-	 *  Return a HTML select list of bank accounts
3580
-	 *
3581
-	 *  @param	string	$selected           Id account pre-selected
3582
-	 *  @param  string	$htmlname           Name of select zone
3583
-	 *  @param  int		$statut             Status of searched accounts (0=open, 1=closed, 2=both)
3584
-	 *  @param  string	$filtre             To filter list
3585
-	 *  @param  int		$useempty           1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3586
-	 *  @param  string	$moreattrib         To add more attribute on select
3587
-	 *  @param	int		$showcurrency		Show currency in label
3588
-	 * 	@return	int							<0 if error, Num of bank account found if OK (0, 1, 2, ...)
3589
-	 */
3590
-	function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0)
3591
-	{
3592
-        // phpcs:enable
3593
-		global $langs, $conf;
3594
-
3595
-		$langs->load("admin");
3596
-		$num = 0;
3597
-
3598
-		$sql = "SELECT rowid, label, bank, clos as status, currency_code";
3599
-		$sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
3600
-		$sql.= " WHERE entity IN (".getEntity('bank_account').")";
3601
-		if ($statut != 2) $sql.= " AND clos = '".$statut."'";
3602
-		if ($filtre) $sql.=" AND ".$filtre;
3603
-		$sql.= " ORDER BY label";
3604
-
3605
-		dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
3606
-		$result = $this->db->query($sql);
3607
-		if ($result)
3608
-		{
3609
-			$num = $this->db->num_rows($result);
3610
-			$i = 0;
3611
-			if ($num)
3612
-			{
3613
-				print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3614
-				if ($useempty == 1 || ($useempty == 2 && $num > 1))
3615
-				{
3616
-					print '<option value="-1">&nbsp;</option>';
3617
-				}
3618
-
3619
-				while ($i < $num)
3620
-				{
3621
-					$obj = $this->db->fetch_object($result);
3622
-					if ($selected == $obj->rowid)
3623
-					{
3624
-						print '<option value="'.$obj->rowid.'" selected>';
3625
-					}
3626
-					else
3627
-					{
3628
-						print '<option value="'.$obj->rowid.'">';
3629
-					}
3630
-					print trim($obj->label);
3631
-					if ($showcurrency) print ' ('.$obj->currency_code.')';
3632
-					if ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
3633
-					print '</option>';
3634
-					$i++;
3635
-				}
3636
-				print "</select>";
3637
-			}
3638
-			else
3639
-			{
3640
-				if ($statut == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
3641
-				else print '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
3642
-			}
3643
-		}
3644
-		else {
3645
-			dol_print_error($this->db);
3646
-		}
3647
-
3648
-		return $num;
3649
-	}
3650
-
3651
-	/**
3652
-	 *    Display form to select bank account
3653
-	 *
3654
-	 *    @param	string	$page        Page
3655
-	 *    @param    int		$selected    Id of bank account
3656
-	 *    @param    string	$htmlname    Name of select html field
3657
-	 *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3658
-	 *    @return	void
3659
-	 */
3660
-	function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
3661
-	{
3662
-		global $langs;
3663
-		if ($htmlname != "none") {
3664
-			print '<form method="POST" action="'.$page.'">';
3665
-			print '<input type="hidden" name="action" value="setbankaccount">';
3666
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
3667
-			$nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
3668
-			if ($nbaccountfound > 0) print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
3669
-			print '</form>';
3670
-		} else {
3671
-
3672
-			$langs->load('banks');
3673
-
3674
-			if ($selected) {
3675
-				require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
3676
-				$bankstatic=new Account($this->db);
3677
-				$result = $bankstatic->fetch($selected);
3678
-				if ($result) print $bankstatic->getNomUrl(1);
3679
-			} else {
3680
-				print "&nbsp;";
3681
-			}
3682
-		}
3683
-	}
2199
+        // Build output string
2200
+        dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
2201
+        $result=$this->db->query($sql);
2202
+        if ($result)
2203
+        {
2204
+            require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2205
+            require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2206
+            $num = $this->db->num_rows($result);
3684 2207
 
3685
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3686
-	/**
3687
-	 *    Return list of categories having choosed type
3688
-	 *
3689
-	 *    @param	string|int	$type				Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
3690
-	 *    @param    string		$selected    		Id of category preselected or 'auto' (autoselect category if there is only one element)
3691
-	 *    @param    string		$htmlname			HTML field name
3692
-	 *    @param    int			$maxlength      	Maximum length for labels
3693
-	 *    @param    int			$excludeafterid 	Exclude all categories after this leaf in category tree.
3694
-	 *    @param	int			$outputmode			0=HTML select string, 1=Array
3695
-	 *    @return	string
3696
-	 *    @see select_categories
3697
-	 */
3698
-	function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0)
3699
-	{
3700
-        // phpcs:enable
3701
-		global $conf, $langs;
3702
-		$langs->load("categories");
3703
-
3704
-		include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3705
-
3706
-		// For backward compatibility
3707
-		if (is_numeric($type))
3708
-		{
3709
-			dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
3710
-		}
3711
-
3712
-		if ($type === Categorie::TYPE_BANK_LINE)
3713
-		{
3714
-			// TODO Move this into common category feature
3715
-			$categids=array();
3716
-			$sql = "SELECT c.label, c.rowid";
3717
-			$sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
3718
-			$sql.= " WHERE entity = ".$conf->entity;
3719
-			$sql.= " ORDER BY c.label";
3720
-			$result = $this->db->query($sql);
3721
-			if ($result)
3722
-			{
3723
-				$num = $this->db->num_rows($result);
3724
-				$i = 0;
3725
-				while ($i < $num)
3726
-				{
3727
-					$objp = $this->db->fetch_object($result);
3728
-					if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
3729
-					$i++;
3730
-				}
3731
-				$this->db->free($result);
3732
-			}
3733
-			else dol_print_error($this->db);
3734
-		}
3735
-		else
3736
-		{
3737
-			$cat = new Categorie($this->db);
3738
-			$cate_arbo = $cat->get_full_arbo($type, $excludeafterid);
3739
-		}
3740
-
3741
-		$output = '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
3742
-		$outarray=array();
3743
-		if (is_array($cate_arbo))
3744
-		{
3745
-			if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
3746
-			else
3747
-			{
3748
-				$output.= '<option value="-1">&nbsp;</option>';
3749
-				foreach($cate_arbo as $key => $value)
3750
-				{
3751
-					if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
3752
-					{
3753
-						$add = 'selected ';
3754
-					}
3755
-					else
3756
-					{
3757
-						$add = '';
3758
-					}
3759
-					$output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
2208
+            $events=null;
3760 2209
 
3761
-					$outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
3762
-				}
3763
-			}
3764
-		}
3765
-		$output.= '</select>';
3766
-		$output.= "\n";
2210
+            if (! $forcecombo)
2211
+            {
2212
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2213
+                $out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
2214
+            }
3767 2215
 
3768
-		if ($outputmode) return $outarray;
3769
-		return $output;
3770
-	}
2216
+            $out.='<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
3771 2217
 
3772
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3773
-	/**
3774
-	 *     Show a confirmation HTML form or AJAX popup
3775
-	 *
3776
-	 *     @param	string		$page        	   	Url of page to call if confirmation is OK
3777
-	 *     @param	string		$title       	   	Title
3778
-	 *     @param	string		$question    	   	Question
3779
-	 *     @param 	string		$action      	   	Action
3780
-	 *	   @param	array		$formquestion	   	An array with forms complementary inputs
3781
-	 * 	   @param	string		$selectedchoice		"" or "no" or "yes"
3782
-	 * 	   @param	int			$useajax		   	0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx
3783
-	 *     @param	int			$height          	Force height of box
3784
-	 *     @param	int			$width				Force width of box
3785
-	 *     @return 	void
3786
-	 *     @deprecated
3787
-	 *     @see formconfirm()
3788
-	 */
3789
-	function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
3790
-	{
3791
-        // phpcs:enable
3792
-        dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
3793
-		print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
3794
-	}
3795
-
3796
-	/**
3797
-	 *     Show a confirmation HTML form or AJAX popup.
3798
-	 *     Easiest way to use this is with useajax=1.
3799
-	 *     If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
3800
-	 *     just after calling this method. For example:
3801
-	 *       print '<script type="text/javascript">'."\n";
3802
-	 *       print 'jQuery(document).ready(function() {'."\n";
3803
-	 *       print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
3804
-	 *       print '});'."\n";
3805
-	 *       print '</script>'."\n";
3806
-	 *
3807
-	 *     @param  	string		$page        	   	Url of page to call if confirmation is OK. Can contains paramaters (param 'action' and 'confirm' will be reformated)
3808
-	 *     @param	string		$title       	   	Title
3809
-	 *     @param	string		$question    	   	Question
3810
-	 *     @param 	string		$action      	   	Action
3811
-	 *	   @param  	array		$formquestion	   	An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
3812
-	 *												type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', ...
3813
-	 * 	   @param  	string		$selectedchoice  	'' or 'no', or 'yes' or '1' or '0'
3814
-	 * 	   @param  	int			$useajax		   	0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
3815
-	 *     @param  	int			$height          	Force height of box
3816
-	 *     @param	int			$width				Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
3817
-	 *     @param	int			$disableformtag		1=Disable form tag. Can be used if we are already inside a <form> section.
3818
-	 *     @return 	string      	    			HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
3819
-	 */
3820
-	function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=210, $width=500, $disableformtag=0)
3821
-	{
3822
-		global $langs,$conf;
3823
-		global $useglobalvars;
3824
-
3825
-		$more='';
3826
-		$formconfirm='';
3827
-		$inputok=array();
3828
-		$inputko=array();
3829
-
3830
-		// Clean parameters
3831
-		$newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
3832
-		if ($conf->browser->layout == 'phone') $width='95%';
3833
-
3834
-		if (is_array($formquestion) && ! empty($formquestion))
3835
-		{
3836
-			// First add hidden fields and value
3837
-			foreach ($formquestion as $key => $input)
3838
-			{
3839
-				if (is_array($input) && ! empty($input))
3840
-				{
3841
-					if ($input['type'] == 'hidden')
3842
-					{
3843
-						$more.='<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
3844
-					}
3845
-				}
3846
-			}
3847
-
3848
-			// Now add questions
3849
-			$more.='<table class="paddingtopbottomonly" width="100%">'."\n";
3850
-			if (! empty($formquestion['text'])) $more.='<tr><td colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
3851
-			foreach ($formquestion as $key => $input)
3852
-			{
3853
-				if (is_array($input) && ! empty($input))
3854
-				{
3855
-					$size=(! empty($input['size'])?' size="'.$input['size'].'"':'');
3856
-					$moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:'');
3857
-					$morecss=(! empty($input['morecss'])?' '.$input['morecss']:'');
3858
-
3859
-					if ($input['type'] == 'text')
3860
-					{
3861
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="text" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3862
-					}
3863
-					elseif ($input['type'] == 'password')
3864
-					{
3865
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="password" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3866
-					}
3867
-					elseif ($input['type'] == 'select')
3868
-					{
3869
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3870
-						if (! empty($input['label'])) $more.=$input['label'].'</td><td class="tdtop" align="left">';
3871
-						$more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss);
3872
-						$more.='</td></tr>'."\n";
3873
-					}
3874
-					elseif ($input['type'] == 'checkbox')
3875
-					{
3876
-						$more.='<tr>';
3877
-						$more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].' </td><td align="left">';
3878
-						$more.='<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
3879
-						if (! is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more.=' checked';
3880
-						if (is_bool($input['value']) && $input['value']) $more.=' checked';
3881
-						if (isset($input['disabled'])) $more.=' disabled';
3882
-						$more.=' /></td>';
3883
-						$more.='</tr>'."\n";
3884
-					}
3885
-					elseif ($input['type'] == 'radio')
3886
-					{
3887
-						$i=0;
3888
-						foreach($input['values'] as $selkey => $selval)
3889
-						{
3890
-							$more.='<tr>';
3891
-							if ($i==0) $more.='<td'.(empty($input['tdclass'])?' class="tdtop"':(' class="tdtop '.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3892
-							else $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>&nbsp;</td>';
3893
-							$more.='<td><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
3894
-							if ($input['disabled']) $more.=' disabled';
3895
-							$more.=' /> ';
3896
-							$more.=$selval;
3897
-							$more.='</td></tr>'."\n";
3898
-							$i++;
3899
-						}
3900
-					}
3901
-					elseif ($input['type'] == 'date')
3902
-					{
3903
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3904
-						$more.='<td align="left">';
3905
-						$more.=$this->selectDate($input['value'],$input['name'],0,0,0,'',1,0);
3906
-						$more.='</td></tr>'."\n";
3907
-						$formquestion[] = array('name'=>$input['name'].'day');
3908
-						$formquestion[] = array('name'=>$input['name'].'month');
3909
-						$formquestion[] = array('name'=>$input['name'].'year');
3910
-						$formquestion[] = array('name'=>$input['name'].'hour');
3911
-						$formquestion[] = array('name'=>$input['name'].'min');
3912
-					}
3913
-					elseif ($input['type'] == 'other')
3914
-					{
3915
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3916
-						if (! empty($input['label'])) $more.=$input['label'].'</td><td align="left">';
3917
-						$more.=$input['value'];
3918
-						$more.='</td></tr>'."\n";
3919
-					}
2218
+            $textifempty='';
2219
+            // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
2220
+            //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
2221
+            if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2222
+            {
2223
+                if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
2224
+                else $textifempty.=$langs->trans("All");
2225
+            }
2226
+            if ($showempty) $out.='<option value="0" selected>'.$textifempty.'</option>';
3920 2227
 
3921
-					elseif ($input['type'] == 'onecolumn')
3922
-					{
3923
-						$more.='<tr><td colspan="2" align="left">';
3924
-						$more.=$input['value'];
3925
-						$more.='</td></tr>'."\n";
3926
-					}
3927
-				}
3928
-			}
3929
-			$more.='</table>'."\n";
3930
-		}
3931
-
3932
-		// JQUI method dialog is broken with jmobile, we use standard HTML.
3933
-		// Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx
3934
-		// See page product/card.php for example
3935
-		if (! empty($conf->dol_use_jmobile)) $useajax=0;
3936
-		if (empty($conf->use_javascript_ajax)) $useajax=0;
3937
-
3938
-		if ($useajax)
3939
-		{
3940
-			$autoOpen=true;
3941
-			$dialogconfirm='dialog-confirm';
3942
-			$button='';
3943
-			if (! is_numeric($useajax))
3944
-			{
3945
-				$button=$useajax;
3946
-				$useajax=1;
3947
-				$autoOpen=false;
3948
-				$dialogconfirm.='-'.$button;
3949
-			}
3950
-			$pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';
3951
-			$pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':'');
3952
-			// Add input fields into list of fields to read during submit (inputok and inputko)
3953
-			if (is_array($formquestion))
3954
-			{
3955
-				foreach ($formquestion as $key => $input)
3956
-				{
3957
-					//print "xx ".$key." rr ".is_array($input)."<br>\n";
3958
-					if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
3959
-					if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
3960
-				}
3961
-			}
3962
-			// Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
3963
-			$formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
3964
-			if (! empty($more)) {
3965
-				$formconfirm.= '<div class="confirmquestions">'.$more.'</div>';
3966
-			}
3967
-			$formconfirm.= ($question ? '<div class="confirmmessage">'.img_help('','').' '.$question . '</div>': '');
3968
-			$formconfirm.= '</div>'."\n";
3969
-
3970
-			$formconfirm.= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
3971
-			$formconfirm.= '<script type="text/javascript">'."\n";
3972
-			$formconfirm.= 'jQuery(document).ready(function() {
3973
-            $(function() {
3974
-            	$( "#'.$dialogconfirm.'" ).dialog(
3975
-            	{
3976
-                    autoOpen: '.($autoOpen ? "true" : "false").',';
3977
-			if ($newselectedchoice == 'no')
3978
-			{
3979
-				$formconfirm.='
3980
-						open: function() {
3981
-            				$(this).parent().find("button.ui-button:eq(2)").focus();
3982
-						},';
3983
-			}
3984
-			$formconfirm.='
3985
-                    resizable: false,
3986
-                    height: "'.$height.'",
3987
-                    width: "'.$width.'",
3988
-                    modal: true,
3989
-                    closeOnEscape: false,
3990
-                    buttons: {
3991
-                        "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
3992
-                        	var options="";
3993
-                        	var inputok = '.json_encode($inputok).';
3994
-                         	var pageyes = "'.dol_escape_js(! empty($pageyes)?$pageyes:'').'";
3995
-                         	if (inputok.length>0) {
3996
-                         		$.each(inputok, function(i, inputname) {
3997
-                         			var more = "";
3998
-                         			if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
3999
-                         		    if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
4000
-                         			var inputvalue = $("#" + inputname + more).val();
4001
-                         			if (typeof inputvalue == "undefined") { inputvalue=""; }
4002
-                         			options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
4003
-                         		});
4004
-                         	}
4005
-                         	var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
4006
-                         	//alert(urljump);
4007
-            				if (pageyes.length > 0) { location.href = urljump; }
4008
-                            $(this).dialog("close");
4009
-                        },
4010
-                        "'.dol_escape_js($langs->transnoentities("No")).'": function() {
4011
-                        	var options = "";
4012
-                         	var inputko = '.json_encode($inputko).';
4013
-                         	var pageno="'.dol_escape_js(! empty($pageno)?$pageno:'').'";
4014
-                         	if (inputko.length>0) {
4015
-                         		$.each(inputko, function(i, inputname) {
4016
-                         			var more = "";
4017
-                         			if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
4018
-                         			var inputvalue = $("#" + inputname + more).val();
4019
-                         			if (typeof inputvalue == "undefined") { inputvalue=""; }
4020
-                         			options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
4021
-                         		});
4022
-                         	}
4023
-                         	var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
4024
-                         	//alert(urljump);
4025
-            				if (pageno.length > 0) { location.href = urljump; }
4026
-                            $(this).dialog("close");
2228
+            $i = 0;
2229
+            while ($num && $i < $num)
2230
+            {
2231
+                $opt = '';
2232
+                $optJson = array();
2233
+                $objp = $this->db->fetch_object($result);
2234
+
2235
+                if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)
2236
+                { // Price by quantity will return many prices for the same product
2237
+                    $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
2238
+                    $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
2239
+                    $sql.= " WHERE fk_product_price=".$objp->price_rowid;
2240
+                    $sql.= " ORDER BY quantity ASC";
2241
+
2242
+                    dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
2243
+                    $result2 = $this->db->query($sql);
2244
+                    if ($result2)
2245
+                    {
2246
+                        $nb_prices = $this->db->num_rows($result2);
2247
+                        $j = 0;
2248
+                        while ($nb_prices && $j < $nb_prices) {
2249
+                            $objp2 = $this->db->fetch_object($result2);
2250
+
2251
+                            $objp->price_by_qty_rowid = $objp2->rowid;
2252
+                            $objp->price_by_qty_price_base_type = $objp2->price_base_type;
2253
+                            $objp->price_by_qty_quantity = $objp2->quantity;
2254
+                            $objp->price_by_qty_unitprice = $objp2->unitprice;
2255
+                            $objp->price_by_qty_remise_percent = $objp2->remise_percent;
2256
+                            // For backward compatibility
2257
+                            $objp->quantity = $objp2->quantity;
2258
+                            $objp->price = $objp2->price;
2259
+                            $objp->unitprice = $objp2->unitprice;
2260
+                            $objp->remise_percent = $objp2->remise_percent;
2261
+                            $objp->remise = $objp2->remise;
2262
+
2263
+                            $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel);
2264
+
2265
+                            $j++;
2266
+
2267
+                            // Add new entry
2268
+                            // "key" value of json key array is used by jQuery automatically as selected value
2269
+                            // "label" value of json key array is used by jQuery automatically as text for combo box
2270
+                            $out.=$opt;
2271
+                            array_push($outarray, $optJson);
4027 2272
                         }
4028 2273
                     }
4029 2274
                 }
4030
-                );
4031
-
4032
-            	var button = "'.$button.'";
4033
-            	if (button.length > 0) {
4034
-                	$( "#" + button ).click(function() {
4035
-                		$("#'.$dialogconfirm.'").dialog("open");
4036
-        			});
2275
+                else
2276
+                {
2277
+                    if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
2278
+                        $price_product = new Product($this->db);
2279
+                        $price_product->fetch($objp->rowid, '', '', 1);
2280
+                        $priceparser = new PriceParser($this->db);
2281
+                        $price_result = $priceparser->parseProduct($price_product);
2282
+                        if ($price_result >= 0) {
2283
+                            $objp->price = $price_result;
2284
+                            $objp->unitprice = $price_result;
2285
+                            //Calculate the VAT
2286
+                            $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
2287
+                            $objp->price_ttc = price2num($objp->price_ttc,'MU');
2288
+                        }
2289
+                    }
2290
+                    $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);
2291
+                    // Add new entry
2292
+                    // "key" value of json key array is used by jQuery automatically as selected value
2293
+                    // "label" value of json key array is used by jQuery automatically as text for combo box
2294
+                    $out.=$opt;
2295
+                    array_push($outarray, $optJson);
4037 2296
                 }
4038
-            });
4039
-            });
4040
-            </script>';
4041
-			$formconfirm.= "<!-- end ajax formconfirm -->\n";
4042
-		}
4043
-		else
4044
-		{
4045
-			$formconfirm.= "\n<!-- begin formconfirm page=".$page." -->\n";
4046
-
4047
-			if (empty($disableformtag)) $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
4048 2297
 
4049
-			$formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
4050
-			if (empty($disableformtag)) $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
2298
+                $i++;
2299
+            }
4051 2300
 
4052
-			$formconfirm.= '<table width="100%" class="valid">'."\n";
2301
+            $out.='</select>';
4053 2302
 
4054
-			// Line title
4055
-			$formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
2303
+            $this->db->free($result);
4056 2304
 
4057
-			// Line form fields
4058
-			if ($more)
4059
-			{
4060
-				$formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
4061
-				$formconfirm.=$more;
4062
-				$formconfirm.='</td></tr>'."\n";
4063
-			}
2305
+            if (empty($outputmode)) return $out;
2306
+            return $outarray;
2307
+        }
2308
+        else
2309
+        {
2310
+            dol_print_error($db);
2311
+        }
2312
+    }
4064 2313
 
4065
-			// Line with question
4066
-			$formconfirm.= '<tr class="valid">';
4067
-			$formconfirm.= '<td class="valid">'.$question.'</td>';
4068
-			$formconfirm.= '<td class="valid">';
4069
-			$formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
4070
-			$formconfirm.= '</td>';
4071
-			$formconfirm.= '<td class="valid" align="center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
4072
-			$formconfirm.= '</tr>'."\n";
2314
+    /**
2315
+     * constructProductListOption
2316
+     *
2317
+     * @param 	resultset	$objp			    Resultset of fetch
2318
+     * @param 	string		$opt			    Option (var used for returned value in string option format)
2319
+     * @param 	string		$optJson		    Option (var used for returned value in json format)
2320
+     * @param 	int			$price_level	    Price level
2321
+     * @param 	string		$selected		    Preselected value
2322
+     * @param   int         $hidepriceinlabel   Hide price in label
2323
+     * @return	void
2324
+     */
2325
+    private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)
2326
+    {
2327
+        global $langs,$conf,$user,$db;
2328
+
2329
+        $outkey='';
2330
+        $outval='';
2331
+        $outref='';
2332
+        $outlabel='';
2333
+        $outdesc='';
2334
+        $outbarcode='';
2335
+        $outtype='';
2336
+        $outprice_ht='';
2337
+        $outprice_ttc='';
2338
+        $outpricebasetype='';
2339
+        $outtva_tx='';
2340
+        $outqty=1;
2341
+        $outdiscount=0;
2342
+
2343
+        $maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
2344
+
2345
+        $label=$objp->label;
2346
+        if (! empty($objp->label_translated)) $label=$objp->label_translated;
2347
+        if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2348
+
2349
+        $outkey=$objp->rowid;
2350
+        $outref=$objp->ref;
2351
+        $outlabel=$objp->label;
2352
+        $outdesc=$objp->description;
2353
+        $outbarcode=$objp->barcode;
2354
+
2355
+        $outtype=$objp->fk_product_type;
2356
+        $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2357
+        $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2358
+
2359
+        $opt = '<option value="'.$objp->rowid.'"';
2360
+        $opt.= ($objp->rowid == $selected)?' selected':'';
2361
+        if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)
2362
+        {
2363
+            $opt.= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
2364
+        }
2365
+        if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
2366
+        {
2367
+            if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
2368
+            else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
2369
+        }
2370
+        $opt.= '>';
2371
+        $opt.= $objp->ref;
2372
+        if ($outbarcode) $opt.=' ('.$outbarcode.')';
2373
+        $opt.=' - '.dol_trunc($label,$maxlengtharticle);
2374
+
2375
+        $objRef = $objp->ref;
2376
+        if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2377
+        $outval.=$objRef;
2378
+        if ($outbarcode) $outval.=' ('.$outbarcode.')';
2379
+        $outval.=' - '.dol_trunc($label,$maxlengtharticle);
2380
+
2381
+        $found=0;
2382
+
2383
+        // Multiprice
2384
+        // If we need a particular price level (from 1 to 6)
2385
+        if (empty($hidepriceinlabel) && $price_level >= 1 && (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2386
+        {
2387
+            $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
2388
+            $sql.= " FROM ".MAIN_DB_PREFIX."product_price";
2389
+            $sql.= " WHERE fk_product='".$objp->rowid."'";
2390
+            $sql.= " AND entity IN (".getEntity('productprice').")";
2391
+            $sql.= " AND price_level=".$price_level;
2392
+            $sql.= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
2393
+            $sql.= " LIMIT 1";
2394
+
2395
+            dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
2396
+            $result2 = $this->db->query($sql);
2397
+            if ($result2)
2398
+            {
2399
+                $objp2 = $this->db->fetch_object($result2);
2400
+                if ($objp2)
2401
+                {
2402
+                    $found=1;
2403
+                    if ($objp2->price_base_type == 'HT')
2404
+                    {
2405
+                        $opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2406
+                        $outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2407
+                    }
2408
+                    else
2409
+                    {
2410
+                        $opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2411
+                        $outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2412
+                    }
2413
+                    $outprice_ht=price($objp2->price);
2414
+                    $outprice_ttc=price($objp2->price_ttc);
2415
+                    $outpricebasetype=$objp2->price_base_type;
2416
+                    $outtva_tx=$objp2->tva_tx;
2417
+                }
2418
+            }
2419
+            else
2420
+            {
2421
+                dol_print_error($this->db);
2422
+            }
2423
+        }
4073 2424
 
4074
-			$formconfirm.= '</table>'."\n";
2425
+        // Price by quantity
2426
+        if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2427
+        {
2428
+            $found = 1;
2429
+            $outqty=$objp->quantity;
2430
+            $outdiscount=$objp->remise_percent;
2431
+            if ($objp->quantity == 1)
2432
+            {
2433
+                $opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/";
2434
+                $outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
2435
+                $opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2436
+                $outval.=$langs->transnoentities("Unit");
2437
+            }
2438
+            else
2439
+            {
2440
+                $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2441
+                $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2442
+                $opt.= $langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2443
+                $outval.=$langs->transnoentities("Units");
2444
+            }
4075 2445
 
4076
-			if (empty($disableformtag)) $formconfirm.= "</form>\n";
4077
-			$formconfirm.= '<br>';
2446
+            $outprice_ht=price($objp->unitprice);
2447
+            $outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
2448
+            $outpricebasetype=$objp->price_base_type;
2449
+            $outtva_tx=$objp->tva_tx;
2450
+        }
2451
+        if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
2452
+        {
2453
+            $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2454
+            $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2455
+        }
2456
+        if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
2457
+        {
2458
+            $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2459
+            $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2460
+        }
4078 2461
 
4079
-			$formconfirm.= "<!-- end formconfirm -->\n";
4080
-		}
2462
+        // Price by customer
2463
+        if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
2464
+        {
2465
+            if (!empty($objp->idprodcustprice))
2466
+            {
2467
+                $found = 1;
4081 2468
 
4082
-		return $formconfirm;
4083
-	}
2469
+                if ($objp->custprice_base_type == 'HT')
2470
+                {
2471
+                    $opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2472
+                    $outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2473
+                }
2474
+                else
2475
+                {
2476
+                    $opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2477
+                    $outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2478
+                }
4084 2479
 
2480
+                $outprice_ht=price($objp->custprice);
2481
+                $outprice_ttc=price($objp->custprice_ttc);
2482
+                $outpricebasetype=$objp->custprice_base_type;
2483
+                $outtva_tx=$objp->custtva_tx;
2484
+            }
2485
+        }
4085 2486
 
4086
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4087
-	/**
4088
-	 *    Show a form to select a project
4089
-	 *
4090
-	 *    @param	int		$page        		Page
4091
-	 *    @param	int		$socid       		Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
4092
-	 *    @param    int		$selected    		Id pre-selected project
4093
-	 *    @param    string	$htmlname    		Name of select field
4094
-	 *    @param	int		$discard_closed		Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
4095
-	 *    @param	int		$maxlength			Max length
4096
-	 *    @param	int		$forcefocus			Force focus on field (works with javascript only)
4097
-	 *    @param    int     $nooutput           No print is done. String is returned.
4098
-	 *    @return	string                      Return html content
4099
-	 */
4100
-	function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)
4101
-	{
4102
-        // phpcs:enable
4103
-		global $langs;
4104
-
4105
-		require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
4106
-		require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
4107
-
4108
-		$out='';
4109
-
4110
-		$formproject=new FormProjets($this->db);
4111
-
4112
-		$langs->load("project");
4113
-		if ($htmlname != "none")
4114
-		{
4115
-			$out.="\n";
4116
-			$out.='<form method="post" action="'.$page.'">';
4117
-			$out.='<input type="hidden" name="action" value="classin">';
4118
-			$out.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4119
-			$out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
4120
-			$out.='<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4121
-			$out.='</form>';
4122
-		}
4123
-		else
4124
-		{
4125
-			if ($selected)
4126
-			{
4127
-				$projet = new Project($this->db);
4128
-				$projet->fetch($selected);
4129
-				//print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
4130
-				$out.=$projet->getNomUrl(0,'',1);
4131
-			}
4132
-			else
4133
-			{
4134
-				$out.="&nbsp;";
4135
-			}
4136
-		}
4137
-
4138
-		if (empty($nooutput))
4139
-		{
4140
-			print $out;
4141
-			return '';
4142
-		}
4143
-		return $out;
4144
-	}
2487
+        // If level no defined or multiprice not found, we used the default price
2488
+        if (empty($hidepriceinlabel) && ! $found)
2489
+        {
2490
+            if ($objp->price_base_type == 'HT')
2491
+            {
2492
+                $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2493
+                $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2494
+            }
2495
+            else
2496
+            {
2497
+                $opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2498
+                $outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2499
+            }
2500
+            $outprice_ht=price($objp->price);
2501
+            $outprice_ttc=price($objp->price_ttc);
2502
+            $outpricebasetype=$objp->price_base_type;
2503
+            $outtva_tx=$objp->tva_tx;
2504
+        }
4145 2505
 
4146
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4147
-	/**
4148
-	 *	Show a form to select payment conditions
4149
-	 *
4150
-	 *  @param	int		$page        	Page
4151
-	 *  @param  string	$selected    	Id condition pre-selectionne
4152
-	 *  @param  string	$htmlname    	Name of select html field
4153
-	 *	@param	int		$addempty		Add empty entry
4154
-	 *  @return	void
4155
-	 */
4156
-	function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
4157
-	{
4158
-        // phpcs:enable
4159
-		global $langs;
4160
-		if ($htmlname != "none")
4161
-		{
4162
-			print '<form method="post" action="'.$page.'">';
4163
-			print '<input type="hidden" name="action" value="setconditions">';
4164
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4165
-			$this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
4166
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4167
-			print '</form>';
4168
-		}
4169
-		else
4170
-		{
4171
-			if ($selected)
4172
-			{
4173
-				$this->load_cache_conditions_paiements();
4174
-				print $this->cache_conditions_paiements[$selected]['label'];
4175
-			} else {
4176
-				print "&nbsp;";
4177
-			}
4178
-		}
4179
-	}
2506
+        if (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
2507
+        {
2508
+            $opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
4180 2509
 
4181
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4182
-	/**
4183
-	 *  Show a form to select a delivery delay
4184
-	 *
4185
-	 *  @param  int		$page        	Page
4186
-	 *  @param  string	$selected    	Id condition pre-selectionne
4187
-	 *  @param  string	$htmlname    	Name of select html field
4188
-	 *	@param	int		$addempty		Ajoute entree vide
4189
-	 *  @return	void
4190
-	 */
4191
-	function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
4192
-	{
4193
-        // phpcs:enable
4194
-		global $langs;
4195
-		if ($htmlname != "none")
4196
-		{
4197
-			print '<form method="post" action="'.$page.'">';
4198
-			print '<input type="hidden" name="action" value="setavailability">';
4199
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4200
-			$this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
4201
-			print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4202
-			print '</form>';
4203
-		}
4204
-		else
4205
-		{
4206
-			if ($selected)
4207
-			{
4208
-				$this->load_cache_availability();
4209
-				print $this->cache_availability[$selected]['label'];
4210
-			} else {
4211
-				print "&nbsp;";
4212
-			}
4213
-		}
4214
-	}
4215
-
4216
-	/**
4217
-	 *	Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
4218
-	 *  List found into table c_input_reason loaded by loadCacheInputReason
4219
-	 *
4220
-	 *  @param  string	$page        	Page
4221
-	 *  @param  string	$selected    	Id condition pre-selectionne
4222
-	 *  @param  string	$htmlname    	Name of select html field
4223
-	 *	@param	int		$addempty		Add empty entry
4224
-	 *  @return	void
4225
-	 */
4226
-	function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)
4227
-	{
4228
-		global $langs;
4229
-		if ($htmlname != "none")
4230
-		{
4231
-			print '<form method="post" action="'.$page.'">';
4232
-			print '<input type="hidden" name="action" value="setdemandreason">';
4233
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4234
-			$this->selectInputReason($selected,$htmlname,-1,$addempty);
4235
-			print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4236
-			print '</form>';
4237
-		}
4238
-		else
4239
-		{
4240
-			if ($selected)
4241
-			{
4242
-				$this->loadCacheInputReason();
4243
-				foreach ($this->cache_demand_reason as $key => $val)
4244
-				{
4245
-					if ($val['id'] == $selected)
4246
-					{
4247
-						print $val['label'];
4248
-						break;
4249
-					}
4250
-				}
4251
-			} else {
4252
-				print "&nbsp;";
4253
-			}
4254
-		}
4255
-	}
2510
+            if ($objp->stock > 0) {
2511
+                $outval.= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2512
+            }elseif ($objp->stock <= 0) {
2513
+                $outval.= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2514
+            }
2515
+        }
4256 2516
 
4257
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4258
-	/**
4259
-	 *    Show a form + html select a date
4260
-	 *
4261
-	 *    @param	string		$page        	Page
4262
-	 *    @param	string		$selected    	Date preselected
4263
-	 *    @param    string		$htmlname    	Html name of date input fields or 'none'
4264
-	 *    @param    int			$displayhour 	Display hour selector
4265
-	 *    @param    int			$displaymin		Display minutes selector
4266
-	 *    @param	int			$nooutput		1=No print output, return string
4267
-	 *    @return	string
4268
-	 *    @see		selectDate
4269
-	 */
4270
-	function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)
4271
-	{
4272
-        // phpcs:enable
4273
-		global $langs;
4274
-
4275
-		$ret='';
4276
-
4277
-		if ($htmlname != "none")
4278
-		{
4279
-			$ret.='<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
4280
-			$ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
4281
-			$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4282
-			$ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4283
-			$ret.='<tr><td>';
4284
-			$ret.=$this->selectDate($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0);
4285
-			$ret.='</td>';
4286
-			$ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4287
-			$ret.='</tr></table></form>';
4288
-		}
4289
-		else
4290
-		{
4291
-			if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
4292
-			else $ret.=dol_print_date($selected,'day');
4293
-		}
4294
-
4295
-		if (empty($nooutput)) print $ret;
4296
-		return $ret;
4297
-	}
2517
+        if ($outdurationvalue && $outdurationunit)
2518
+        {
2519
+            $da=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
2520
+            if (isset($da[$outdurationunit]))
2521
+            {
2522
+                $key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');
2523
+                $opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);
2524
+                $outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);
2525
+            }
2526
+        }
4298 2527
 
2528
+        $opt.= "</option>\n";
2529
+        $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);
2530
+    }
4299 2531
 
4300 2532
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4301
-	/**
4302
-	 *  Show a select form to choose a user
4303
-	 *
4304
-	 *  @param	string	$page        	Page
4305
-	 *  @param  string	$selected    	Id of user preselected
4306
-	 *  @param  string	$htmlname    	Name of input html field. If 'none', we just output the user link.
4307
-	 *  @param  array	$exclude		List of users id to exclude
4308
-	 *  @param  array	$include        List of users id to include
4309
-	 *  @return	void
4310
-	 */
4311
-	function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
4312
-	{
2533
+    /**
2534
+     *	Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
2535
+     *
2536
+     *	@param	int		$socid			Id third party
2537
+     *	@param  string	$selected       Preselected product
2538
+     *	@param  string	$htmlname       Name of HTML Select
2539
+     *  @param	string	$filtertype     Filter on product type (''=nofilter, 0=product, 1=service)
2540
+     *	@param  string	$filtre			For a SQL filter
2541
+     *	@param	array	$ajaxoptions	Options for ajax_autocompleter
2542
+     *  @param	int		$hidelabel		Hide label (0=no, 1=yes)
2543
+     *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2544
+     *	@return	void
2545
+     */
2546
+    function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0)
2547
+    {
4313 2548
         // phpcs:enable
4314
-		global $langs;
4315
-
4316
-		if ($htmlname != "none")
4317
-		{
4318
-			print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
4319
-			print '<input type="hidden" name="action" value="set'.$htmlname.'">';
4320
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4321
-			print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
4322
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4323
-			print '</form>';
4324
-		}
4325
-		else
4326
-		{
4327
-			if ($selected)
4328
-			{
4329
-				require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
4330
-				$theuser=new User($this->db);
4331
-				$theuser->fetch($selected);
4332
-				print $theuser->getNomUrl(1);
4333
-			} else {
4334
-				print "&nbsp;";
4335
-			}
4336
-		}
4337
-	}
2549
+        global $langs,$conf;
2550
+        global $price_level, $status, $finished;
4338 2551
 
2552
+        $selected_input_value='';
2553
+        if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2554
+        {
2555
+            if ($selected > 0)
2556
+            {
2557
+                require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2558
+                $producttmpselect = new Product($this->db);
2559
+                $producttmpselect->fetch($selected);
2560
+                $selected_input_value=$producttmpselect->ref;
2561
+                unset($producttmpselect);
2562
+            }
4339 2563
 
4340
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4341
-	/**
4342
-	 *    Show form with payment mode
4343
-	 *
4344
-	 *    @param	string	$page        	Page
4345
-	 *    @param    int		$selected    	Id mode pre-selectionne
4346
-	 *    @param    string	$htmlname    	Name of select html field
4347
-	 *    @param  	string	$filtertype		To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
4348
-	 *    @param    int     $active         Active or not, -1 = all
4349
-	 *    @return	void
4350
-	 */
4351
-	function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)
4352
-	{
4353
-        // phpcs:enable
4354
-		global $langs;
4355
-		if ($htmlname != "none")
4356
-		{
4357
-			print '<form method="POST" action="'.$page.'">';
4358
-			print '<input type="hidden" name="action" value="setmode">';
4359
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4360
-			$this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);
4361
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4362
-			print '</form>';
4363
-		}
4364
-		else
4365
-		{
4366
-			if ($selected)
4367
-			{
4368
-				$this->load_cache_types_paiements();
4369
-				print $this->cache_types_paiements[$selected]['label'];
4370
-			} else {
4371
-				print "&nbsp;";
4372
-			}
4373
-		}
4374
-	}
2564
+            // mode=2 means suppliers products
2565
+            $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
2566
+            print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
2567
+            print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
2568
+        }
2569
+        else
2570
+        {
2571
+            print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);
2572
+        }
2573
+    }
4375 2574
 
4376 2575
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4377
-	/**
4378
-	 *    Show form with multicurrency code
4379
-	 *
4380
-	 *    @param	string	$page        	Page
4381
-	 *    @param    string	$selected    	code pre-selectionne
4382
-	 *    @param    string	$htmlname    	Name of select html field
4383
-	 *    @return	void
4384
-	 */
4385
-	function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
4386
-	{
2576
+    /**
2577
+     *	Return list of suppliers products
2578
+     *
2579
+     *	@param	int		$socid   		Id societe fournisseur (0 pour aucun filtre)
2580
+     *	@param  int		$selected       Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
2581
+     *	@param  string	$htmlname       Nom de la zone select
2582
+     *  @param	string	$filtertype     Filter on product type (''=nofilter, 0=product, 1=service)
2583
+     *	@param  string	$filtre         Pour filtre sql
2584
+     *	@param  string	$filterkey      Filtre des produits
2585
+     *  @param  int		$statut         -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)
2586
+     *  @param  int		$outputmode     0=HTML select string, 1=Array
2587
+     *  @param  int     $limit          Limit of line number
2588
+     *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2589
+     *  @return array           		Array of keys for json
2590
+     */
2591
+    function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0)
2592
+    {
4387 2593
         // phpcs:enable
4388
-		global $langs;
4389
-		if ($htmlname != "none")
4390
-		{
4391
-			print '<form method="POST" action="'.$page.'">';
4392
-			print '<input type="hidden" name="action" value="setmulticurrencycode">';
4393
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4394
-			print $this->selectMultiCurrency($selected, $htmlname, 0);
4395
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4396
-			print '</form>';
4397
-		}
4398
-		else
4399
-		{
4400
-			dol_include_once('/core/lib/company.lib.php');
4401
-			print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
4402
-		}
4403
-	}
2594
+        global $langs,$conf,$db;
2595
+
2596
+        $out='';
2597
+        $outarray=array();
2598
+
2599
+        $langs->load('stocks');
2600
+
2601
+        $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,";
2602
+        $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
2603
+        $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
2604
+        $sql.= " pfp.supplier_reputation";
2605
+        $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2606
+        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2607
+        if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
2608
+        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2609
+        $sql.= " WHERE p.entity IN (".getEntity('product').")";
2610
+        $sql.= " AND p.tobuy = 1";
2611
+        if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
2612
+        if (! empty($filtre)) $sql.=" ".$filtre;
2613
+        // Add criteria on ref/label
2614
+        if ($filterkey != '')
2615
+        {
2616
+            $sql.=' AND (';
2617
+            $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2618
+            // For natural search
2619
+            $scrit = explode(' ', $filterkey);
2620
+            $i=0;
2621
+            if (count($scrit) > 1) $sql.="(";
2622
+            foreach ($scrit as $crit)
2623
+            {
2624
+                if ($i > 0) $sql.=" AND ";
2625
+                $sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')";
2626
+                $i++;
2627
+            }
2628
+            if (count($scrit) > 1) $sql.=")";
2629
+            if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
2630
+            $sql.=')';
2631
+        }
2632
+        $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
2633
+        $sql.= $db->plimit($limit, 0);
2634
+
2635
+        // Build output string
2636
+
2637
+        dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
2638
+        $result=$this->db->query($sql);
2639
+        if ($result)
2640
+        {
2641
+            require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2642
+
2643
+            $num = $this->db->num_rows($result);
2644
+
2645
+            //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">';	// remove select to have id same with combo and ajax
2646
+            $out.='<select class="flat maxwidthonsmartphone" id="'.$htmlname.'" name="'.$htmlname.'">';
2647
+            if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
2648
+            else $out.='<option value="0">&nbsp;</option>';
2649
+
2650
+            $i = 0;
2651
+            while ($i < $num)
2652
+            {
2653
+                $objp = $this->db->fetch_object($result);
2654
+
2655
+                $outkey=$objp->idprodfournprice;                                                    // id in table of price
2656
+                if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid;   // id of product
2657
+
2658
+                $outref=$objp->ref;
2659
+                $outval='';
2660
+                $outqty=1;
2661
+                $outdiscount=0;
2662
+                $outtype=$objp->fk_product_type;
2663
+                $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2664
+                $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2665
+
2666
+                $opt = '<option value="'.$outkey.'"';
2667
+                if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
2668
+                if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';
2669
+                if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
2670
+                {
2671
+                    $opt.= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqpercent="'.$objp->remise_percent.'"';
2672
+                }
2673
+                $opt.= '>';
2674
+
2675
+                $objRef = $objp->ref;
2676
+                if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2677
+                $objRefFourn = $objp->ref_fourn;
2678
+                if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
2679
+                $label = $objp->label;
2680
+                if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2681
+
2682
+                $opt.=$objp->ref;
2683
+                if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2684
+                    $opt.=' ('.$objp->ref_fourn.')';
2685
+                $opt.=' - ';
2686
+                $outval.=$objRef;
2687
+                if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2688
+                    $outval.=' ('.$objRefFourn.')';
2689
+                $outval.=' - ';
2690
+                $opt.=dol_trunc($label, 72).' - ';
2691
+                $outval.=dol_trunc($label, 72).' - ';
2692
+
2693
+                if (! empty($objp->idprodfournprice))
2694
+                {
2695
+                    $outqty=$objp->quantity;
2696
+                    $outdiscount=$objp->remise_percent;
2697
+                    if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2698
+                        $prod_supplier = new ProductFournisseur($this->db);
2699
+                        $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
2700
+                        $prod_supplier->id = $objp->fk_product;
2701
+                        $prod_supplier->fourn_qty = $objp->quantity;
2702
+                        $prod_supplier->fourn_tva_tx = $objp->tva_tx;
2703
+                        $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
2704
+                        $priceparser = new PriceParser($this->db);
2705
+                        $price_result = $priceparser->parseProductSupplier($prod_supplier);
2706
+                        if ($price_result >= 0) {
2707
+                            $objp->fprice = $price_result;
2708
+                            if ($objp->quantity >= 1)
2709
+                            {
2710
+                                $objp->unitprice = $objp->fprice / $objp->quantity;
2711
+                            }
2712
+                        }
2713
+                    }
2714
+                    if ($objp->quantity == 1)
2715
+                    {
2716
+                        $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2717
+                        $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
2718
+                        $opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2719
+                        $outval.=$langs->transnoentities("Unit");
2720
+                    }
2721
+                    else
2722
+                    {
2723
+                        $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2724
+                        $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2725
+                        $opt.= ' '.$langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2726
+                        $outval.= ' '.$langs->transnoentities("Units");
2727
+                    }
2728
+
2729
+                    if ($objp->quantity >= 1)
2730
+                    {
2731
+                        $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2732
+                        $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2733
+                    }
2734
+                    if ($objp->remise_percent >= 1)
2735
+                    {
2736
+                        $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2737
+                        $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2738
+                    }
2739
+                    if ($objp->duration)
2740
+                    {
2741
+                        $opt .= " - ".$objp->duration;
2742
+                        $outval.=" - ".$objp->duration;
2743
+                    }
2744
+                    if (! $socid)
2745
+                    {
2746
+                        $opt .= " - ".dol_trunc($objp->name,8);
2747
+                        $outval.=" - ".dol_trunc($objp->name,8);
2748
+                    }
2749
+                    if ($objp->supplier_reputation)
2750
+                    {
2751
+                        //TODO dictionary
2752
+                        $reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
2753
+
2754
+                        $opt .= " - ".$reputations[$objp->supplier_reputation];
2755
+                        $outval.=" - ".$reputations[$objp->supplier_reputation];
2756
+                    }
2757
+                }
2758
+                else
2759
+                {
2760
+                    if (empty($alsoproductwithnosupplierprice))     // No supplier price defined for couple product/supplier
2761
+                    {
2762
+                        $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2763
+                        $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2764
+                    }
2765
+                    else                                            // No supplier price defined for product, even on other suppliers
2766
+                    {
2767
+                        $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2768
+                        $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2769
+                    }
2770
+                }
2771
+                $opt .= "</option>\n";
2772
+
2773
+
2774
+                // Add new entry
2775
+                // "key" value of json key array is used by jQuery automatically as selected value
2776
+                // "label" value of json key array is used by jQuery automatically as text for combo box
2777
+                $out.=$opt;
2778
+                array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));
2779
+                // Exemple of var_dump $outarray
2780
+                // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
2781
+                //           ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
2782
+                //      	 ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
2783
+                //}
2784
+                //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
2785
+                //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
2786
+                //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
2787
+
2788
+                $i++;
2789
+            }
2790
+            $out.='</select>';
2791
+
2792
+            $this->db->free($result);
2793
+
2794
+            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2795
+            $out.=ajax_combobox($htmlname);
2796
+
2797
+            if (empty($outputmode)) return $out;
2798
+            return $outarray;
2799
+        }
2800
+        else
2801
+        {
2802
+            dol_print_error($this->db);
2803
+        }
2804
+    }
4404 2805
 
4405 2806
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4406
-	/**
4407
-	 *    Show form with multicurrency rate
4408
-	 *
4409
-	 *    @param	string	$page        	Page
4410
-	 *    @param    double	$rate	    	Current rate
4411
-	 *    @param    string	$htmlname    	Name of select html field
4412
-	 *    @param    string  $currency       Currency code to explain the rate
4413
-	 *    @return	void
4414
-	 */
4415
-	function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
4416
-	{
2807
+    /**
2808
+     *	Return list of suppliers prices for a product
2809
+     *
2810
+     *  @param	    int		$productid       	Id of product
2811
+     *  @param      string	$htmlname        	Name of HTML field
2812
+     *  @param      int		$selected_supplier  Pre-selected supplier if more than 1 result
2813
+     *  @return	    void
2814
+     */
2815
+    function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')
2816
+    {
4417 2817
         // phpcs:enable
4418
-		global $langs, $mysoc, $conf;
4419
-
4420
-		if ($htmlname != "none")
4421
-		{
4422
-			print '<form method="POST" action="'.$page.'">';
4423
-			print '<input type="hidden" name="action" value="setmulticurrencyrate">';
4424
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4425
-			print '<input type="text" name="'.$htmlname.'" value="'.(!empty($rate) ? price($rate) : 1).'" size="10" /> ';
4426
-			print '<select name="calculation_mode">';
4427
-			print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
4428
-			print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
4429
-			print '</select> ';
4430
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4431
-			print '</form>';
4432
-		}
4433
-		else
4434
-		{
4435
-			if (! empty($rate))
4436
-			{
4437
-				print price($rate, 1, $langs, 1, 0);
4438
-				if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
4439
-			}
4440
-			else
4441
-			{
4442
-				print 1;
4443
-			}
4444
-		}
4445
-	}
2818
+        global $langs,$conf;
2819
+
2820
+        $langs->load('stocks');
2821
+
2822
+        $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,";
2823
+        $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
2824
+        $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
2825
+        $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2826
+        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2827
+        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2828
+        $sql.= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
2829
+        $sql.= " AND p.tobuy = 1";
2830
+        $sql.= " AND s.fournisseur = 1";
2831
+        $sql.= " AND p.rowid = ".$productid;
2832
+        $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
2833
+
2834
+        dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
2835
+        $result=$this->db->query($sql);
2836
+
2837
+        if ($result)
2838
+        {
2839
+            $num = $this->db->num_rows($result);
2840
+
2841
+            $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2842
+
2843
+            if (! $num)
2844
+            {
2845
+                $form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
2846
+            }
2847
+            else
2848
+            {
2849
+                require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2850
+                $form.= '<option value="0">&nbsp;</option>';
2851
+
2852
+                $i = 0;
2853
+                while ($i < $num)
2854
+                {
2855
+                    $objp = $this->db->fetch_object($result);
2856
+
2857
+                    $opt = '<option value="'.$objp->idprodfournprice.'"';
2858
+                    //if there is only one supplier, preselect it
2859
+                    if($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
2860
+                        $opt .= ' selected';
2861
+                    }
2862
+                    $opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
2863
+
2864
+                    if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2865
+                        $prod_supplier = new ProductFournisseur($this->db);
2866
+                        $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
2867
+                        $prod_supplier->id = $productid;
2868
+                        $prod_supplier->fourn_qty = $objp->quantity;
2869
+                        $prod_supplier->fourn_tva_tx = $objp->tva_tx;
2870
+                        $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
2871
+                        $priceparser = new PriceParser($this->db);
2872
+                        $price_result = $priceparser->parseProductSupplier($prod_supplier);
2873
+                        if ($price_result >= 0) {
2874
+                            $objp->fprice = $price_result;
2875
+                            if ($objp->quantity >= 1)
2876
+                            {
2877
+                                $objp->unitprice = $objp->fprice / $objp->quantity;
2878
+                            }
2879
+                        }
2880
+                    }
2881
+                    if ($objp->quantity == 1)
2882
+                    {
2883
+                        $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2884
+                    }
2885
+
2886
+                    $opt.= $objp->quantity.' ';
2887
+
2888
+                    if ($objp->quantity == 1)
2889
+                    {
2890
+                        $opt.= $langs->trans("Unit");
2891
+                    }
2892
+                    else
2893
+                    {
2894
+                        $opt.= $langs->trans("Units");
2895
+                    }
2896
+                    if ($objp->quantity > 1)
2897
+                    {
2898
+                        $opt.=" - ";
2899
+                        $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
2900
+                    }
2901
+                    if ($objp->duration) $opt .= " - ".$objp->duration;
2902
+                    $opt .= "</option>\n";
2903
+
2904
+                    $form.= $opt;
2905
+                    $i++;
2906
+                }
2907
+            }
4446 2908
 
2909
+            $form.= '</select>';
2910
+            $this->db->free($result);
2911
+            return $form;
2912
+        }
2913
+        else
2914
+        {
2915
+            dol_print_error($this->db);
2916
+        }
2917
+    }
4447 2918
 
4448 2919
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4449
-	/**
4450
-	 *	Show a select box with available absolute discounts
4451
-	 *
4452
-	 *  @param  string	$page        	Page URL where form is shown
4453
-	 *  @param  int		$selected    	Value pre-selected
4454
-	 *	@param  string	$htmlname    	Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
4455
-	 *	@param	int		$socid			Third party id
4456
-	 * 	@param	float	$amount			Total amount available
4457
-	 * 	@param	string	$filter			SQL filter on discounts
4458
-	 * 	@param	int		$maxvalue		Max value for lines that can be selected
4459
-	 *  @param  string	$more           More string to add
4460
-	 *  @param  int     $hidelist       1=Hide list
4461
-	 *  @param	int		$discount_type	0 => customer discount, 1 => supplier discount
4462
-	 *  @return	void
4463
-	 */
4464
-	function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0)
4465
-	{
2920
+    /**
2921
+     *    Return list of delivery address
2922
+     *
2923
+     *    @param    string	$selected          	Id contact pre-selectionn
2924
+     *    @param    int		$socid				Id of company
2925
+     *    @param    string	$htmlname          	Name of HTML field
2926
+     *    @param    int		$showempty         	Add an empty field
2927
+     *    @return	integer|null
2928
+     */
2929
+    function select_address($selected, $socid, $htmlname='address_id',$showempty=0)
2930
+    {
4466 2931
         // phpcs:enable
4467
-		global $conf,$langs;
4468
-		if ($htmlname != "none")
4469
-		{
4470
-			print '<form method="post" action="'.$page.'">';
4471
-			print '<input type="hidden" name="action" value="setabsolutediscount">';
4472
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4473
-			print '<div class="inline-block">';
4474
-			if(! empty($discount_type)) {
4475
-				if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4476
-				{
4477
-					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier';    // If we want deposit to be substracted to payments only and not to total of final invoice
4478
-					else $translationKey = 'HasCreditNoteFromSupplier';
4479
-				}
4480
-				else
4481
-				{
4482
-					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
4483
-					else $translationKey = 'HasCreditNoteFromSupplier';
4484
-				}
4485
-			} else {
4486
-				if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4487
-				{
4488
-					if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount';    // If we want deposit to be substracted to payments only and not to total of final invoice
4489
-					else $translationKey = 'CompanyHasCreditNote';
4490
-				}
4491
-				else
4492
-				{
4493
-					if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
4494
-					else $translationKey = 'CompanyHasCreditNote';
4495
-				}
4496
-			}
4497
-			print $langs->trans($translationKey,price($amount,0,$langs,0,0,-1,$conf->currency));
4498
-			if (empty($hidelist)) print ': ';
4499
-			print '</div>';
4500
-			if (empty($hidelist))
4501
-			{
4502
-				print '<div class="inline-block" style="padding-right: 10px">';
4503
-				$newfilter = 'discount_type='.intval($discount_type);
4504
-				if(! empty($discount_type)) {
4505
-					$newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
4506
-				} else {
4507
-					$newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
4508
-				}
4509
-				if ($filter) $newfilter.=' AND ('.$filter.')';
4510
-				$nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
4511
-				if ($nbqualifiedlines > 0)
4512
-				{
4513
-					print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
4514
-					if(! empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
4515
-						print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4516
-					if(empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
4517
-						print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4518
-
4519
-					print '>';
4520
-				}
4521
-				print '</div>';
4522
-			}
4523
-			if ($more)
4524
-			{
4525
-				print '<div class="inline-block">';
4526
-				print $more;
4527
-				print '</div>';
4528
-			}
4529
-			print '</form>';
4530
-		}
4531
-		else
4532
-		{
4533
-			if ($selected)
4534
-			{
4535
-				print $selected;
4536
-			}
4537
-			else
4538
-			{
4539
-				print "0";
4540
-			}
4541
-		}
4542
-	}
2932
+        // looking for users
2933
+        $sql = "SELECT a.rowid, a.label";
2934
+        $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
2935
+        $sql .= " WHERE a.fk_soc = ".$socid;
2936
+        $sql .= " ORDER BY a.label ASC";
2937
+
2938
+        dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
2939
+        $resql=$this->db->query($sql);
2940
+        if ($resql)
2941
+        {
2942
+            print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2943
+            if ($showempty) print '<option value="0">&nbsp;</option>';
2944
+            $num = $this->db->num_rows($resql);
2945
+            $i = 0;
2946
+            if ($num)
2947
+            {
2948
+                while ($i < $num)
2949
+                {
2950
+                    $obj = $this->db->fetch_object($resql);
2951
+
2952
+                    if ($selected && $selected == $obj->rowid)
2953
+                    {
2954
+                        print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
2955
+                    }
2956
+                    else
2957
+                    {
2958
+                        print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
2959
+                    }
2960
+                    $i++;
2961
+                }
2962
+            }
2963
+            print '</select>';
2964
+            return $num;
2965
+        }
2966
+        else
2967
+        {
2968
+            dol_print_error($this->db);
2969
+        }
2970
+    }
4543 2971
 
4544 2972
 
4545 2973
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4546
-	/**
4547
-	 *    Show forms to select a contact
4548
-	 *
4549
-	 *    @param	string		$page        	Page
4550
-	 *    @param	Societe		$societe		Filter on third party
4551
-	 *    @param    int			$selected    	Id contact pre-selectionne
4552
-	 *    @param    string		$htmlname    	Name of HTML select. If 'none', we just show contact link.
4553
-	 *    @return	void
4554
-	 */
4555
-	function form_contacts($page, $societe, $selected='', $htmlname='contactid')
4556
-	{
2974
+    /**
2975
+     *      Load into cache list of payment terms
2976
+     *
2977
+     *      @return     int             Nb of lines loaded, <0 if KO
2978
+     */
2979
+    function load_cache_conditions_paiements()
2980
+    {
4557 2981
         // phpcs:enable
4558
-		global $langs, $conf;
4559
-
4560
-		if ($htmlname != "none")
4561
-		{
4562
-			print '<form method="post" action="'.$page.'">';
4563
-			print '<input type="hidden" name="action" value="set_contact">';
4564
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4565
-			print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4566
-			print '<tr><td>';
4567
-			$num=$this->select_contacts($societe->id, $selected, $htmlname);
4568
-			if ($num==0)
4569
-			{
4570
-				$addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
4571
-				print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
4572
-			}
4573
-			print '</td>';
4574
-			print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4575
-			print '</tr></table></form>';
4576
-		}
4577
-		else
4578
-		{
4579
-			if ($selected)
4580
-			{
4581
-				require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
4582
-				$contact=new Contact($this->db);
4583
-				$contact->fetch($selected);
4584
-				print $contact->getFullName($langs);
4585
-			} else {
4586
-				print "&nbsp;";
4587
-			}
4588
-		}
4589
-	}
2982
+        global $langs;
2983
+
2984
+        $num = count($this->cache_conditions_paiements);
2985
+        if ($num > 0) return 0;    // Cache already loaded
2986
+
2987
+        dol_syslog(__METHOD__, LOG_DEBUG);
2988
+
2989
+        $sql = "SELECT rowid, code, libelle as label";
2990
+        $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
2991
+        $sql.= " WHERE entity IN (".getEntity('c_payment_term').")";
2992
+        $sql.= " AND active > 0";
2993
+        $sql.= " ORDER BY sortorder";
2994
+
2995
+        $resql = $this->db->query($sql);
2996
+        if ($resql)
2997
+        {
2998
+            $num = $this->db->num_rows($resql);
2999
+            $i = 0;
3000
+            while ($i < $num)
3001
+            {
3002
+                $obj = $this->db->fetch_object($resql);
3003
+
3004
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3005
+                $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:''));
3006
+                $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
3007
+                $this->cache_conditions_paiements[$obj->rowid]['label']=$label;
3008
+                $i++;
3009
+            }
3010
+
3011
+            //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1);		// We use the field sortorder of table
3012
+
3013
+            return $num;
3014
+        }
3015
+        else
3016
+        {
3017
+            dol_print_error($this->db);
3018
+            return -1;
3019
+        }
3020
+    }
4590 3021
 
4591 3022
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4592
-	/**
4593
-	 *  Output html select to select thirdparty
4594
-	 *
4595
-	 *  @param	string	$page       	Page
4596
-	 *  @param  string	$selected   	Id preselected
4597
-	 *  @param  string	$htmlname		Name of HTML select
4598
-	 *  @param  string	$filter         optional filters criteras
4599
-	 *	@param	int		$showempty		Add an empty field
4600
-	 * 	@param	int		$showtype		Show third party type in combolist (customer, prospect or supplier)
4601
-	 * 	@param	int		$forcecombo		Force to use combo box
4602
-	 *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
4603
-	 *  @param  int     $nooutput       No print output. Return it only.
4604
-	 *  @return	void
4605
-	 */
4606
-	function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array(), $nooutput=0)
4607
-	{
3023
+    /**
3024
+     *      Charge dans cache la liste des délais de livraison possibles
3025
+     *
3026
+     *      @return     int             Nb of lines loaded, <0 if KO
3027
+     */
3028
+    function load_cache_availability()
3029
+    {
4608 3030
         // phpcs:enable
4609
-		global $langs;
4610
-
4611
-		$out = '';
4612
-		if ($htmlname != "none")
4613
-		{
4614
-			$out.='<form method="post" action="'.$page.'">';
4615
-			$out.= '<input type="hidden" name="action" value="set_thirdparty">';
4616
-			$out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4617
-			$out.= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
4618
-			$out.= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4619
-			$out.= '</form>';
4620
-		}
4621
-		else
4622
-		{
4623
-			if ($selected)
4624
-			{
4625
-				require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
4626
-				$soc = new Societe($this->db);
4627
-				$soc->fetch($selected);
4628
-				$out.= $soc->getNomUrl($langs);
4629
-			}
4630
-			else
4631
-			{
4632
-				$out.= "&nbsp;";
4633
-			}
4634
-		}
4635
-
4636
-		if ($nooutput) return $out;
4637
-		else print $out;
4638
-	}
3031
+        global $langs;
3032
+
3033
+        $num = count($this->cache_availability);
3034
+        if ($num > 0) return 0;    // Cache already loaded
3035
+
3036
+        dol_syslog(__METHOD__, LOG_DEBUG);
3037
+
3038
+        $langs->load('propal');
3039
+
3040
+        $sql = "SELECT rowid, code, label";
3041
+        $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
3042
+        $sql.= " WHERE active > 0";
3043
+
3044
+        $resql = $this->db->query($sql);
3045
+        if ($resql)
3046
+        {
3047
+            $num = $this->db->num_rows($resql);
3048
+            $i = 0;
3049
+            while ($i < $num)
3050
+            {
3051
+                $obj = $this->db->fetch_object($resql);
3052
+
3053
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3054
+                $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
3055
+                $this->cache_availability[$obj->rowid]['code'] =$obj->code;
3056
+                $this->cache_availability[$obj->rowid]['label']=$label;
3057
+                $i++;
3058
+            }
3059
+
3060
+            $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
3061
+
3062
+            return $num;
3063
+        }
3064
+        else
3065
+        {
3066
+            dol_print_error($this->db);
3067
+            return -1;
3068
+        }
3069
+    }
3070
+
3071
+    /**
3072
+     *      Retourne la liste des types de delais de livraison possibles
3073
+     *
3074
+     *      @param	int		$selected        Id du type de delais pre-selectionne
3075
+     *      @param  string	$htmlname        Nom de la zone select
3076
+     *      @param  string	$filtertype      To add a filter
3077
+     *		@param	int		$addempty		Add empty entry
3078
+     *		@return	void
3079
+     */
3080
+    function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)
3081
+    {
3082
+        global $langs,$user;
3083
+
3084
+        $this->load_cache_availability();
3085
+
3086
+        dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3087
+
3088
+        print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
3089
+        if ($addempty) print '<option value="0">&nbsp;</option>';
3090
+        foreach($this->cache_availability as $id => $arrayavailability)
3091
+        {
3092
+            if ($selected == $id)
3093
+            {
3094
+                print '<option value="'.$id.'" selected>';
3095
+            }
3096
+            else
3097
+            {
3098
+                print '<option value="'.$id.'">';
3099
+            }
3100
+            print $arrayavailability['label'];
3101
+            print '</option>';
3102
+        }
3103
+        print '</select>';
3104
+        if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3105
+    }
3106
+
3107
+    /**
3108
+     *      Load into cache cache_demand_reason, array of input reasons
3109
+     *
3110
+     *      @return     int             Nb of lines loaded, <0 if KO
3111
+     */
3112
+    function loadCacheInputReason()
3113
+    {
3114
+        global $langs;
3115
+
3116
+        $num = count($this->cache_demand_reason);
3117
+        if ($num > 0) return 0;    // Cache already loaded
3118
+
3119
+        $sql = "SELECT rowid, code, label";
3120
+        $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
3121
+        $sql.= " WHERE active > 0";
3122
+
3123
+        $resql = $this->db->query($sql);
3124
+        if ($resql)
3125
+        {
3126
+            $num = $this->db->num_rows($resql);
3127
+            $i = 0;
3128
+            $tmparray=array();
3129
+            while ($i < $num)
3130
+            {
3131
+                $obj = $this->db->fetch_object($resql);
3132
+
3133
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3134
+                $label=($obj->label!='-'?$obj->label:'');
3135
+                if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
3136
+                if ($langs->trans($obj->code) != $obj->code) $label=$langs->trans($obj->code);																// So translation key SRC_XXX will work
3137
+
3138
+                $tmparray[$obj->rowid]['id']   =$obj->rowid;
3139
+                $tmparray[$obj->rowid]['code'] =$obj->code;
3140
+                $tmparray[$obj->rowid]['label']=$label;
3141
+                $i++;
3142
+            }
3143
+
3144
+            $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
3145
+
3146
+            unset($tmparray);
3147
+            return $num;
3148
+        }
3149
+        else
3150
+        {
3151
+            dol_print_error($this->db);
3152
+            return -1;
3153
+        }
3154
+    }
3155
+
3156
+    /**
3157
+     *	Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
3158
+     *  List found into table c_input_reason loaded by loadCacheInputReason
3159
+     *
3160
+     *  @param	int		$selected        Id or code of type origin to select by default
3161
+     *  @param  string	$htmlname        Nom de la zone select
3162
+     *  @param  string	$exclude         To exclude a code value (Example: SRC_PROP)
3163
+     *	@param	int		$addempty		 Add an empty entry
3164
+     *	@return	void
3165
+     */
3166
+    function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
3167
+    {
3168
+        global $langs,$user;
3169
+
3170
+        $this->loadCacheInputReason();
3171
+
3172
+        print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3173
+        if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
3174
+        foreach($this->cache_demand_reason as $id => $arraydemandreason)
3175
+        {
3176
+            if ($arraydemandreason['code']==$exclude) continue;
3177
+
3178
+            if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
3179
+            {
3180
+                print '<option value="'.$arraydemandreason['id'].'" selected>';
3181
+            }
3182
+            else
3183
+            {
3184
+                print '<option value="'.$arraydemandreason['id'].'">';
3185
+            }
3186
+            $label=$arraydemandreason['label'];	// Translation of label was already done into the ->loadCacheInputReason
3187
+            print $langs->trans($label);
3188
+            print '</option>';
3189
+        }
3190
+        print '</select>';
3191
+        if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3192
+    }
4639 3193
 
4640 3194
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4641
-	/**
4642
-	 *    Retourne la liste des devises, dans la langue de l'utilisateur
4643
-	 *
4644
-	 *    @param	string	$selected    preselected currency code
4645
-	 *    @param    string	$htmlname    name of HTML select list
4646
-     *    @deprecated
4647
-	 *    @return	void
4648
-	 */
4649
-	function select_currency($selected='',$htmlname='currency_id')
4650
-	{
3195
+    /**
3196
+     *      Charge dans cache la liste des types de paiements possibles
3197
+     *
3198
+     *      @return     int                 Nb of lines loaded, <0 if KO
3199
+     */
3200
+    function load_cache_types_paiements()
3201
+    {
4651 3202
         // phpcs:enable
4652
-		print $this->selectCurrency($selected,$htmlname);
4653
-	}
4654
-
4655
-	/**
4656
-	 *  Retourne la liste des devises, dans la langue de l'utilisateur
4657
-	 *
4658
-	 *  @param	string	$selected    preselected currency code
4659
-	 *  @param  string	$htmlname    name of HTML select list
4660
-	 * 	@return	string
4661
-	 */
4662
-	function selectCurrency($selected='',$htmlname='currency_id')
4663
-	{
4664
-		global $conf,$langs,$user;
4665
-
4666
-		$langs->loadCacheCurrencies('');
4667
-
4668
-		$out='';
4669
-
4670
-		if ($selected=='euro' || $selected=='euros') $selected='EUR';   // Pour compatibilite
4671
-
4672
-		$out.= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
4673
-		foreach ($langs->cache_currencies as $code_iso => $currency)
4674
-		{
4675
-			if ($selected && $selected == $code_iso)
4676
-			{
4677
-				$out.= '<option value="'.$code_iso.'" selected>';
4678
-			}
4679
-			else
4680
-			{
4681
-				$out.= '<option value="'.$code_iso.'">';
4682
-			}
4683
-			$out.= $currency['label'];
4684
-			$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4685
-			$out.= '</option>';
4686
-		}
4687
-		$out.= '</select>';
4688
-		if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
4689
-
4690
-		// Make select dynamic
4691
-		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4692
-		$out .= ajax_combobox($htmlname);
4693
-
4694
-		return $out;
4695
-	}
4696
-
4697
-	/**
4698
-	 *	Return array of currencies in user language
4699
-	 *
4700
-	 *  @param	string	$selected    preselected currency code
4701
-	 *  @param  string	$htmlname    name of HTML select list
4702
-	 *  @param  integer	$useempty    1=Add empty line
4703
-	 * 	@return	string
4704
-	 */
4705
-	function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)
4706
-	{
4707
-		global $db,$conf,$langs,$user;
4708
-
4709
-		$langs->loadCacheCurrencies('');        // Load ->cache_currencies
4710
-
4711
-		$TCurrency = array();
4712
-
4713
-		$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
4714
-		$sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
4715
-		$resql = $db->query($sql);
4716
-		if ($resql)
4717
-		{
4718
-			while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
4719
-		}
4720
-
4721
-		$out='';
4722
-		$out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
4723
-		if ($useempty) $out .= '<option value=""></option>';
4724
-		// If company current currency not in table, we add it into list. Should always be available.
4725
-		if (! in_array($conf->currency, $TCurrency))
4726
-		{
4727
-			$TCurrency[$conf->currency] = $conf->currency;
4728
-		}
4729
-		if (count($TCurrency) > 0)
4730
-		{
4731
-			foreach ($langs->cache_currencies as $code_iso => $currency)
4732
-			{
4733
-				if (isset($TCurrency[$code_iso]))
4734
-				{
4735
-					if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
4736
-					else $out.= '<option value="'.$code_iso.'">';
4737
-
4738
-					$out.= $currency['label'];
4739
-					$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4740
-					$out.= '</option>';
4741
-				}
4742
-			}
4743
-		}
4744
-
4745
-		$out.= '</select>';
4746
-		// Make select dynamic
4747
-		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4748
-		$out.= ajax_combobox($htmlname);
4749
-
4750
-		return $out;
4751
-	}
3203
+        global $langs;
3204
+
3205
+        $num=count($this->cache_types_paiements);
3206
+        if ($num > 0) return $num;    // Cache already loaded
3207
+
3208
+        dol_syslog(__METHOD__, LOG_DEBUG);
3209
+
3210
+        $this->cache_types_paiements = array();
3211
+
3212
+        $sql = "SELECT id, code, libelle as label, type, active";
3213
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
3214
+        $sql.= " WHERE entity IN (".getEntity('c_paiement').")";
3215
+        //if ($active >= 0) $sql.= " AND active = ".$active;
3216
+
3217
+        $resql = $this->db->query($sql);
3218
+        if ($resql)
3219
+        {
3220
+            $num = $this->db->num_rows($resql);
3221
+            $i = 0;
3222
+            while ($i < $num)
3223
+            {
3224
+                $obj = $this->db->fetch_object($resql);
3225
+
3226
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3227
+                $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
3228
+                $this->cache_types_paiements[$obj->id]['id'] =$obj->id;
3229
+                $this->cache_types_paiements[$obj->id]['code'] =$obj->code;
3230
+                $this->cache_types_paiements[$obj->id]['label']=$label;
3231
+                $this->cache_types_paiements[$obj->id]['type'] =$obj->type;
3232
+                $this->cache_types_paiements[$obj->id]['active'] =$obj->active;
3233
+                $i++;
3234
+            }
3235
+
3236
+            $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
3237
+
3238
+            return $num;
3239
+        }
3240
+        else
3241
+        {
3242
+            dol_print_error($this->db);
3243
+            return -1;
3244
+        }
3245
+    }
3246
+
4752 3247
 
4753 3248
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4754
-	/**
4755
-	 *	Load into the cache vat rates of a country
4756
-	 *
4757
-	 *	@param	string	$country_code		Country code with quotes ("'CA'", or "'CA,IN,...'")
4758
-	 *	@return	int							Nb of loaded lines, 0 if already loaded, <0 if KO
4759
-	 */
4760
-	function load_cache_vatrates($country_code)
4761
-	{
3249
+    /**
3250
+     *      Return list of payment modes.
3251
+     *      Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
3252
+     *      See instead to force the default value by the caller.
3253
+     *
3254
+     *      @param	int		$selected		Id of payment term to preselect by default
3255
+     *      @param	string	$htmlname		Nom de la zone select
3256
+     *      @param	int		$filtertype		Not used
3257
+     *		@param	int		$addempty		Add an empty entry
3258
+     * 		@param	int		$noinfoadmin		0=Add admin info, 1=Disable admin info
3259
+     * 		@param	string	$morecss			Add more CSS on select tag
3260
+     *		@return	void
3261
+     */
3262
+    function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='')
3263
+    {
4762 3264
         // phpcs:enable
4763
-		global $langs;
4764
-
4765
-		$num = count($this->cache_vatrates);
4766
-		if ($num > 0) return $num;    // Cache already loaded
4767
-
4768
-		dol_syslog(__METHOD__, LOG_DEBUG);
4769
-
4770
-		$sql  = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
4771
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4772
-		$sql.= " WHERE t.fk_pays = c.rowid";
4773
-		$sql.= " AND t.active > 0";
4774
-		$sql.= " AND c.code IN (".$country_code.")";
4775
-		$sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
4776
-
4777
-		$resql=$this->db->query($sql);
4778
-		if ($resql)
4779
-		{
4780
-			$num = $this->db->num_rows($resql);
4781
-			if ($num)
4782
-			{
4783
-				for ($i = 0; $i < $num; $i++)
4784
-				{
4785
-					$obj = $this->db->fetch_object($resql);
4786
-					$this->cache_vatrates[$i]['rowid']	= $obj->rowid;
4787
-					$this->cache_vatrates[$i]['code']	= $obj->code;
4788
-					$this->cache_vatrates[$i]['txtva']	= $obj->taux;
4789
-					$this->cache_vatrates[$i]['nprtva']	= $obj->recuperableonly;
4790
-					$this->cache_vatrates[$i]['localtax1']	    = $obj->localtax1;
4791
-					$this->cache_vatrates[$i]['localtax1_type']	= $obj->localtax1_type;
4792
-					$this->cache_vatrates[$i]['localtax2']	    = $obj->localtax2;
4793
-					$this->cache_vatrates[$i]['localtax2_type']	= $obj->localtax1_type;
4794
-
4795
-					$this->cache_vatrates[$i]['label']	= $obj->taux.'%'.($obj->code?' ('.$obj->code.')':'');   // Label must contains only 0-9 , . % or *
4796
-					$this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4797
-					$positiverates='';
4798
-					if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;
4799
-					if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;
4800
-					if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;
4801
-					if (empty($positiverates)) $positiverates='0';
4802
-					$this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4803
-				}
4804
-
4805
-				return $num;
4806
-			}
4807
-			else
4808
-			{
4809
-				$this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
4810
-				return -1;
4811
-			}
4812
-		}
4813
-		else
4814
-		{
4815
-			$this->error = '<font class="error">'.$this->db->error().'</font>';
4816
-			return -2;
4817
-		}
4818
-	}
3265
+        global $langs, $user, $conf;
3266
+
3267
+        dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3268
+
3269
+        $this->load_cache_conditions_paiements();
3270
+
3271
+        // Set default value if not already set by caller
3272
+        if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
3273
+
3274
+        print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3275
+        if ($addempty) print '<option value="0">&nbsp;</option>';
3276
+        foreach($this->cache_conditions_paiements as $id => $arrayconditions)
3277
+        {
3278
+            if ($selected == $id)
3279
+            {
3280
+                print '<option value="'.$id.'" selected>';
3281
+            }
3282
+            else
3283
+            {
3284
+                print '<option value="'.$id.'">';
3285
+            }
3286
+            print $arrayconditions['label'];
3287
+            print '</option>';
3288
+        }
3289
+        print '</select>';
3290
+        if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3291
+    }
3292
+
4819 3293
 
4820 3294
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4821
-	/**
4822
-	 *  Output an HTML select vat rate.
4823
-	 *  The name of this function should be selectVat. We keep bad name for compatibility purpose.
4824
-	 *
4825
-	 *  @param	string	      $htmlname           Name of HTML select field
4826
-	 *  @param  float|string  $selectedrate       Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
4827
-	 *  @param  Societe	      $societe_vendeuse   Thirdparty seller
4828
-	 *  @param  Societe	      $societe_acheteuse  Thirdparty buyer
4829
-	 *  @param  int		      $idprod             Id product. O if unknown of NA.
4830
-	 *  @param  int		      $info_bits          Miscellaneous information on line (1 for NPR)
4831
-	 *  @param  int|string    $type               ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
4832
-	 *                  		                  Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
4833
-	 *                  					      Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
4834
-	 *                  					      Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
4835
-	 *                                            Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
4836
-	 *                                            Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
4837
-	 *                  					      Sinon la TVA proposee par defaut=0. Fin de regle.
4838
-	 *  @param	bool	     $options_only		  Return HTML options lines only (for ajax treatment)
4839
-	 *  @param  int          $mode                0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key
4840
-	 *  @return	string
4841
-	 */
4842
-	function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)
4843
-	{
3295
+    /**
3296
+     *      Return list of payment methods
3297
+     *
3298
+     *      @param	string	$selected       Id du mode de paiement pre-selectionne
3299
+     *      @param  string	$htmlname       Nom de la zone select
3300
+     *      @param  string	$filtertype     To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
3301
+     *      @param  int		$format         0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
3302
+     *      @param  int		$empty			1=peut etre vide, 0 sinon
3303
+     * 		@param	int		$noadmininfo	0=Add admin info, 1=Disable admin info
3304
+     *      @param  int		$maxlength      Max length of label
3305
+     *      @param  int     $active         Active or not, -1 = all
3306
+     *      @param  string  $morecss        Add more CSS on select tag
3307
+     * 		@return	void
3308
+     */
3309
+    function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=1, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')
3310
+    {
4844 3311
         // phpcs:enable
4845
-		global $langs,$conf,$mysoc;
4846
-
4847
-		$langs->load('errors');
4848
-
4849
-		$return='';
4850
-
4851
-		// Define defaultnpr, defaultttx and defaultcode
4852
-		$defaultnpr=($info_bits & 0x01);
4853
-		$defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
4854
-		$defaulttx=str_replace('*','',$selectedrate);
4855
-		$defaultcode='';
4856
-		if (preg_match('/\((.*)\)/', $defaulttx, $reg))
4857
-		{
4858
-			$defaultcode=$reg[1];
4859
-			$defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4860
-		}
4861
-		//var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
4862
-
4863
-		// Check parameters
4864
-		if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
4865
-		{
4866
-			if ($societe_vendeuse->id == $mysoc->id)
4867
-			{
4868
-				$return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
4869
-			}
4870
-			else
4871
-			{
4872
-				$return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
4873
-			}
4874
-			return $return;
4875
-		}
4876
-
4877
-		//var_dump($societe_acheteuse);
4878
-		//print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->country_code." buyer=".$societe_acheteuse->country_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type";
4879
-		//exit;
4880
-
4881
-		// Define list of countries to use to search VAT rates to show
4882
-		// First we defined code_country to use to find list
4883
-		if (is_object($societe_vendeuse))
4884
-		{
4885
-			$code_country="'".$societe_vendeuse->country_code."'";
4886
-		}
4887
-		else
4888
-		{
4889
-			$code_country="'".$mysoc->country_code."'";   // Pour compatibilite ascendente
4890
-		}
4891
-		if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))    // If option to have vat for end customer for services is on
4892
-		{
4893
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4894
-			if (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany())))
4895
-			{
4896
-				// We also add the buyer
4897
-				if (is_numeric($type))
4898
-				{
4899
-					if ($type == 1) // We know product is a service
4900
-					{
4901
-						$code_country.=",'".$societe_acheteuse->country_code."'";
4902
-					}
4903
-				}
4904
-				else if (! $idprod)  // We don't know type of product
4905
-				{
4906
-					$code_country.=",'".$societe_acheteuse->country_code."'";
4907
-				}
4908
-				else
4909
-				{
4910
-					$prodstatic=new Product($this->db);
4911
-					$prodstatic->fetch($idprod);
4912
-					if ($prodstatic->type == Product::TYPE_SERVICE)   // We know product is a service
4913
-					{
4914
-						$code_country.=",'".$societe_acheteuse->country_code."'";
4915
-					}
4916
-				}
4917
-			}
4918
-		}
4919
-
4920
-		// Now we get list
4921
-		$num = $this->load_cache_vatrates($code_country);   // If no vat defined, return -1 with message into this->error
4922
-
4923
-		if ($num > 0)
4924
-		{
4925
-			// Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
4926
-			if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4927
-			{
4928
-				$tmpthirdparty=new Societe($this->db);
4929
-				$defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4930
-				$defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4931
-		        if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
4932
-			        $defaultcode=$reg[1];
4933
-			        $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4934
-		        }
4935
-				if (empty($defaulttx)) $defaultnpr=0;
4936
-			}
4937
-
4938
-			// Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
4939
-			// Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
4940
-			if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4941
-			{
4942
-				if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
4943
-				else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
4944
-			}
4945
-
4946
-			// Disabled if seller is not subject to VAT
4947
-			$disabled=false; $title='';
4948
-			if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
4949
-			{
4950
-				// Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses
4951
-				if (empty($conf->global->OVERRIDE_VAT_FOR_EXPENSE_REPORT))
4952
-				{
4953
-					$title=' title="'.$langs->trans('VATIsNotUsed').'"';
4954
-					$disabled=true;
4955
-				}
4956
-			}
4957
-
4958
-			if (! $options_only) $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
4959
-
4960
-			$selectedfound=false;
4961
-			foreach ($this->cache_vatrates as $rate)
4962
-			{
4963
-				// Keep only 0 if seller is not subject to VAT
4964
-				if ($disabled && $rate['txtva'] != 0) continue;
4965
-
4966
-				// Define key to use into select list
4967
-				$key = $rate['txtva'];
4968
-				$key.= $rate['nprtva'] ? '*': '';
4969
-				if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';
4970
-				if ($mode < 0) $key = $rate['rowid'];
4971
-
4972
-				$return.= '<option value="'.$key.'"';
4973
-				if (! $selectedfound)
4974
-				{
4975
-					if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
4976
-					{
4977
-						if ($defaultcode == $rate['code'])
4978
-						{
4979
-							$return.= ' selected';
4980
-							$selectedfound=true;
4981
-						}
4982
-					}
4983
-					elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
4984
-			   		{
4985
-			   			$return.= ' selected';
4986
-			   			$selectedfound=true;
4987
-					}
4988
-				}
4989
-				$return.= '>';
4990
-				//if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
4991
-				if ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
4992
-				{
4993
-					$return.= $rate['labelpositiverates'];
4994
-				}
4995
-				else
4996
-				{
4997
-					$return.= vatrate($rate['label']);
4998
-				}
4999
-				//$return.=($rate['code']?' '.$rate['code']:'');
5000
-				$return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': '';         // We show the *  (old behaviour only if new vat code is not used)
5001
-
5002
-				$return.= '</option>';
5003
-			}
5004
-
5005
-			if (! $options_only) $return.= '</select>';
5006
-		}
5007
-		else
5008
-		{
5009
-			$return.= $this->error;
5010
-		}
5011
-
5012
-		$this->num = $num;
5013
-		return $return;
5014
-	}
3312
+        global $langs,$user;
3313
+
3314
+        dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
3315
+
3316
+        $filterarray=array();
3317
+        if ($filtertype == 'CRDT')  	$filterarray=array(0,2,3);
3318
+        elseif ($filtertype == 'DBIT') 	$filterarray=array(1,2,3);
3319
+        elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
3320
+
3321
+        $this->load_cache_types_paiements();
3322
+
3323
+        print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3324
+        if ($empty) print '<option value="">&nbsp;</option>';
3325
+        foreach($this->cache_types_paiements as $id => $arraytypes)
3326
+        {
3327
+            // If not good status
3328
+            if ($active >= 0 && $arraytypes['active'] != $active) continue;
3329
+
3330
+            // On passe si on a demande de filtrer sur des modes de paiments particuliers
3331
+            if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
3332
+
3333
+            // We discard empty line if showempty is on because an empty line has already been output.
3334
+            if ($empty && empty($arraytypes['code'])) continue;
3335
+
3336
+            if ($format == 0) print '<option value="'.$id.'"';
3337
+            elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
3338
+            elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
3339
+            elseif ($format == 3) print '<option value="'.$id.'"';
3340
+            // Si selected est text, on compare avec code, sinon avec id
3341
+            if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
3342
+            elseif ($selected == $id) print ' selected';
3343
+            print '>';
3344
+            if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3345
+            elseif ($format == 1) $value=$arraytypes['code'];
3346
+            elseif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3347
+            elseif ($format == 3) $value=$arraytypes['code'];
3348
+            print $value?$value:'&nbsp;';
3349
+            print '</option>';
3350
+        }
3351
+        print '</select>';
3352
+        if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3353
+    }
3354
+
3355
+
3356
+    /**
3357
+     *  Selection HT or TTC
3358
+     *
3359
+     *  @param	string	$selected       Id pre-selectionne
3360
+     *  @param  string	$htmlname       Nom de la zone select
3361
+     * 	@return	string					Code of HTML select to chose tax or not
3362
+     */
3363
+    function selectPriceBaseType($selected='',$htmlname='price_base_type')
3364
+    {
3365
+        global $langs;
3366
+
3367
+        $return='';
3368
+
3369
+        $return.= '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3370
+        $options = array(
3371
+            'HT'=>$langs->trans("HT"),
3372
+            'TTC'=>$langs->trans("TTC")
3373
+        );
3374
+        foreach($options as $id => $value)
3375
+        {
3376
+            if ($selected == $id)
3377
+            {
3378
+                $return.= '<option value="'.$id.'" selected>'.$value;
3379
+            }
3380
+            else
3381
+            {
3382
+                $return.= '<option value="'.$id.'">'.$value;
3383
+            }
3384
+            $return.= '</option>';
3385
+        }
3386
+        $return.= '</select>';
3387
+
3388
+        return $return;
3389
+    }
3390
+
3391
+    /**
3392
+     *  Return a HTML select list of shipping mode
3393
+     *
3394
+     *  @param	string	$selected          Id shipping mode pre-selected
3395
+     *  @param  string	$htmlname          Name of select zone
3396
+     *  @param  string	$filtre            To filter list
3397
+     *  @param  int		$useempty          1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3398
+     *  @param  string	$moreattrib        To add more attribute on select
3399
+     * 	@return	void
3400
+     */
3401
+    function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')
3402
+    {
3403
+        global $langs, $conf, $user;
3404
+
3405
+        $langs->load("admin");
3406
+        $langs->load("deliveries");
3407
+
3408
+        $sql = "SELECT rowid, code, libelle as label";
3409
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
3410
+        $sql.= " WHERE active > 0";
3411
+        if ($filtre) $sql.=" AND ".$filtre;
3412
+        $sql.= " ORDER BY libelle ASC";
3413
+
3414
+        dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
3415
+        $result = $this->db->query($sql);
3416
+        if ($result) {
3417
+            $num = $this->db->num_rows($result);
3418
+            $i = 0;
3419
+            if ($num) {
3420
+                print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3421
+                if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
3422
+                    print '<option value="-1">&nbsp;</option>';
3423
+                }
3424
+                while ($i < $num) {
3425
+                    $obj = $this->db->fetch_object($result);
3426
+                    if ($selected == $obj->rowid) {
3427
+                        print '<option value="'.$obj->rowid.'" selected>';
3428
+                    } else {
3429
+                        print '<option value="'.$obj->rowid.'">';
3430
+                    }
3431
+                    print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
3432
+                    print '</option>';
3433
+                    $i++;
3434
+                }
3435
+                print "</select>";
3436
+                if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3437
+            } else {
3438
+                print $langs->trans("NoShippingMethodDefined");
3439
+            }
3440
+        } else {
3441
+            dol_print_error($this->db);
3442
+        }
3443
+    }
3444
+
3445
+    /**
3446
+     *    Display form to select shipping mode
3447
+     *
3448
+     *    @param	string	$page        Page
3449
+     *    @param    int		$selected    Id of shipping mode
3450
+     *    @param    string	$htmlname    Name of select html field
3451
+     *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3452
+     *    @return	void
3453
+     */
3454
+    function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
3455
+    {
3456
+        global $langs, $db;
3457
+
3458
+        $langs->load("deliveries");
3459
+
3460
+        if ($htmlname != "none") {
3461
+            print '<form method="POST" action="'.$page.'">';
3462
+            print '<input type="hidden" name="action" value="setshippingmethod">';
3463
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
3464
+            $this->selectShippingMethod($selected, $htmlname, '', $addempty);
3465
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
3466
+            print '</form>';
3467
+        } else {
3468
+            if ($selected) {
3469
+                $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
3470
+                print $langs->trans("SendingMethod".strtoupper($code));
3471
+            } else {
3472
+                print "&nbsp;";
3473
+            }
3474
+        }
3475
+    }
3476
+
3477
+    /**
3478
+     * Creates HTML last in cycle situation invoices selector
3479
+     *
3480
+     * @param     string  $selected   		Preselected ID
3481
+     * @param     int     $socid      		Company ID
3482
+     *
3483
+     * @return    string                     HTML select
3484
+     */
3485
+    function selectSituationInvoices($selected = '', $socid = 0)
3486
+    {
3487
+        global $langs;
3488
+
3489
+        $langs->load('bills');
3490
+
3491
+        $opt = '<option value ="" selected></option>';
3492
+        $sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';
3493
+        $sql.= ' ORDER by situation_cycle_ref, situation_counter desc';
3494
+        $resql = $this->db->query($sql);
3495
+        if ($resql && $this->db->num_rows($resql) > 0) {
3496
+            // Last seen cycle
3497
+            $ref = 0;
3498
+            while ($obj = $this->db->fetch_object($resql)){
3499
+                //Same company ?
3500
+                if ($socid == $obj->fk_soc) {
3501
+                    //Same cycle ?
3502
+                    if ($obj->situation_cycle_ref != $ref) {
3503
+                        // Just seen this cycle
3504
+                        $ref = $obj->situation_cycle_ref;
3505
+                        //not final ?
3506
+                        if ($obj->situation_final != 1) {
3507
+                            //Not prov?
3508
+                            if (substr($obj->ref, 1, 4) != 'PROV') {
3509
+                                if ($selected == $obj->rowid) {
3510
+                                    $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
3511
+                                } else {
3512
+                                    $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
3513
+                                }
3514
+                            }
3515
+                        }
3516
+                    }
3517
+                }
3518
+            }
3519
+        }
3520
+        else
3521
+        {
3522
+                dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
3523
+        }
3524
+        if ($opt == '<option value ="" selected></option>')
3525
+        {
3526
+            $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
3527
+        }
3528
+        return $opt;
3529
+    }
3530
+
3531
+    /**
3532
+     *      Creates HTML units selector (code => label)
3533
+     *
3534
+     *      @param	string	$selected       Preselected Unit ID
3535
+     *      @param  string	$htmlname       Select name
3536
+     *      @param	int		$showempty		Add a nempty line
3537
+     * 		@return	string                  HTML select
3538
+     */
3539
+    function selectUnits($selected = '', $htmlname = 'units', $showempty=0)
3540
+    {
3541
+        global $langs;
3542
+
3543
+        $langs->load('products');
3544
+
3545
+        $return= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
3546
+
3547
+        $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
3548
+        $sql.= ' WHERE active > 0';
3549
+
3550
+        $resql = $this->db->query($sql);
3551
+        if($resql && $this->db->num_rows($resql) > 0)
3552
+        {
3553
+            if ($showempty) $return .= '<option value="none"></option>';
3554
+
3555
+            while($res = $this->db->fetch_object($resql))
3556
+            {
3557
+                $unitLabel = $res->label;
3558
+                if (! empty($langs->tab_translate['unit'.$res->code]))	// check if Translation is available before
3559
+                {
3560
+                    $unitLabel = $langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label;
3561
+                }
3562
+
3563
+                if ($selected == $res->rowid)
3564
+                {
3565
+                    $return.='<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
3566
+                }
3567
+                else
3568
+                {
3569
+                    $return.='<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
3570
+                }
3571
+            }
3572
+            $return.='</select>';
3573
+        }
3574
+        return $return;
3575
+    }
3576
+
3577
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3578
+    /**
3579
+     *  Return a HTML select list of bank accounts
3580
+     *
3581
+     *  @param	string	$selected           Id account pre-selected
3582
+     *  @param  string	$htmlname           Name of select zone
3583
+     *  @param  int		$statut             Status of searched accounts (0=open, 1=closed, 2=both)
3584
+     *  @param  string	$filtre             To filter list
3585
+     *  @param  int		$useempty           1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3586
+     *  @param  string	$moreattrib         To add more attribute on select
3587
+     *  @param	int		$showcurrency		Show currency in label
3588
+     * 	@return	int							<0 if error, Num of bank account found if OK (0, 1, 2, ...)
3589
+     */
3590
+    function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0)
3591
+    {
3592
+        // phpcs:enable
3593
+        global $langs, $conf;
3594
+
3595
+        $langs->load("admin");
3596
+        $num = 0;
3597
+
3598
+        $sql = "SELECT rowid, label, bank, clos as status, currency_code";
3599
+        $sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
3600
+        $sql.= " WHERE entity IN (".getEntity('bank_account').")";
3601
+        if ($statut != 2) $sql.= " AND clos = '".$statut."'";
3602
+        if ($filtre) $sql.=" AND ".$filtre;
3603
+        $sql.= " ORDER BY label";
3604
+
3605
+        dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
3606
+        $result = $this->db->query($sql);
3607
+        if ($result)
3608
+        {
3609
+            $num = $this->db->num_rows($result);
3610
+            $i = 0;
3611
+            if ($num)
3612
+            {
3613
+                print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3614
+                if ($useempty == 1 || ($useempty == 2 && $num > 1))
3615
+                {
3616
+                    print '<option value="-1">&nbsp;</option>';
3617
+                }
3618
+
3619
+                while ($i < $num)
3620
+                {
3621
+                    $obj = $this->db->fetch_object($result);
3622
+                    if ($selected == $obj->rowid)
3623
+                    {
3624
+                        print '<option value="'.$obj->rowid.'" selected>';
3625
+                    }
3626
+                    else
3627
+                    {
3628
+                        print '<option value="'.$obj->rowid.'">';
3629
+                    }
3630
+                    print trim($obj->label);
3631
+                    if ($showcurrency) print ' ('.$obj->currency_code.')';
3632
+                    if ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
3633
+                    print '</option>';
3634
+                    $i++;
3635
+                }
3636
+                print "</select>";
3637
+            }
3638
+            else
3639
+            {
3640
+                if ($statut == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
3641
+                else print '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
3642
+            }
3643
+        }
3644
+        else {
3645
+            dol_print_error($this->db);
3646
+        }
3647
+
3648
+        return $num;
3649
+    }
3650
+
3651
+    /**
3652
+     *    Display form to select bank account
3653
+     *
3654
+     *    @param	string	$page        Page
3655
+     *    @param    int		$selected    Id of bank account
3656
+     *    @param    string	$htmlname    Name of select html field
3657
+     *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3658
+     *    @return	void
3659
+     */
3660
+    function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
3661
+    {
3662
+        global $langs;
3663
+        if ($htmlname != "none") {
3664
+            print '<form method="POST" action="'.$page.'">';
3665
+            print '<input type="hidden" name="action" value="setbankaccount">';
3666
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
3667
+            $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
3668
+            if ($nbaccountfound > 0) print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
3669
+            print '</form>';
3670
+        } else {
3671
+
3672
+            $langs->load('banks');
3673
+
3674
+            if ($selected) {
3675
+                require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
3676
+                $bankstatic=new Account($this->db);
3677
+                $result = $bankstatic->fetch($selected);
3678
+                if ($result) print $bankstatic->getNomUrl(1);
3679
+            } else {
3680
+                print "&nbsp;";
3681
+            }
3682
+        }
3683
+    }
3684
+
3685
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3686
+    /**
3687
+     *    Return list of categories having choosed type
3688
+     *
3689
+     *    @param	string|int	$type				Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
3690
+     *    @param    string		$selected    		Id of category preselected or 'auto' (autoselect category if there is only one element)
3691
+     *    @param    string		$htmlname			HTML field name
3692
+     *    @param    int			$maxlength      	Maximum length for labels
3693
+     *    @param    int			$excludeafterid 	Exclude all categories after this leaf in category tree.
3694
+     *    @param	int			$outputmode			0=HTML select string, 1=Array
3695
+     *    @return	string
3696
+     *    @see select_categories
3697
+     */
3698
+    function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0)
3699
+    {
3700
+        // phpcs:enable
3701
+        global $conf, $langs;
3702
+        $langs->load("categories");
3703
+
3704
+        include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3705
+
3706
+        // For backward compatibility
3707
+        if (is_numeric($type))
3708
+        {
3709
+            dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
3710
+        }
3711
+
3712
+        if ($type === Categorie::TYPE_BANK_LINE)
3713
+        {
3714
+            // TODO Move this into common category feature
3715
+            $categids=array();
3716
+            $sql = "SELECT c.label, c.rowid";
3717
+            $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
3718
+            $sql.= " WHERE entity = ".$conf->entity;
3719
+            $sql.= " ORDER BY c.label";
3720
+            $result = $this->db->query($sql);
3721
+            if ($result)
3722
+            {
3723
+                $num = $this->db->num_rows($result);
3724
+                $i = 0;
3725
+                while ($i < $num)
3726
+                {
3727
+                    $objp = $this->db->fetch_object($result);
3728
+                    if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
3729
+                    $i++;
3730
+                }
3731
+                $this->db->free($result);
3732
+            }
3733
+            else dol_print_error($this->db);
3734
+        }
3735
+        else
3736
+        {
3737
+            $cat = new Categorie($this->db);
3738
+            $cate_arbo = $cat->get_full_arbo($type, $excludeafterid);
3739
+        }
3740
+
3741
+        $output = '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
3742
+        $outarray=array();
3743
+        if (is_array($cate_arbo))
3744
+        {
3745
+            if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
3746
+            else
3747
+            {
3748
+                $output.= '<option value="-1">&nbsp;</option>';
3749
+                foreach($cate_arbo as $key => $value)
3750
+                {
3751
+                    if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
3752
+                    {
3753
+                        $add = 'selected ';
3754
+                    }
3755
+                    else
3756
+                    {
3757
+                        $add = '';
3758
+                    }
3759
+                    $output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
3760
+
3761
+                    $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
3762
+                }
3763
+            }
3764
+        }
3765
+        $output.= '</select>';
3766
+        $output.= "\n";
3767
+
3768
+        if ($outputmode) return $outarray;
3769
+        return $output;
3770
+    }
3771
+
3772
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3773
+    /**
3774
+     *     Show a confirmation HTML form or AJAX popup
3775
+     *
3776
+     *     @param	string		$page        	   	Url of page to call if confirmation is OK
3777
+     *     @param	string		$title       	   	Title
3778
+     *     @param	string		$question    	   	Question
3779
+     *     @param 	string		$action      	   	Action
3780
+     *	   @param	array		$formquestion	   	An array with forms complementary inputs
3781
+     * 	   @param	string		$selectedchoice		"" or "no" or "yes"
3782
+     * 	   @param	int			$useajax		   	0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx
3783
+     *     @param	int			$height          	Force height of box
3784
+     *     @param	int			$width				Force width of box
3785
+     *     @return 	void
3786
+     *     @deprecated
3787
+     *     @see formconfirm()
3788
+     */
3789
+    function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
3790
+    {
3791
+        // phpcs:enable
3792
+        dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
3793
+        print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
3794
+    }
3795
+
3796
+    /**
3797
+     *     Show a confirmation HTML form or AJAX popup.
3798
+     *     Easiest way to use this is with useajax=1.
3799
+     *     If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
3800
+     *     just after calling this method. For example:
3801
+     *       print '<script type="text/javascript">'."\n";
3802
+     *       print 'jQuery(document).ready(function() {'."\n";
3803
+     *       print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
3804
+     *       print '});'."\n";
3805
+     *       print '</script>'."\n";
3806
+     *
3807
+     *     @param  	string		$page        	   	Url of page to call if confirmation is OK. Can contains paramaters (param 'action' and 'confirm' will be reformated)
3808
+     *     @param	string		$title       	   	Title
3809
+     *     @param	string		$question    	   	Question
3810
+     *     @param 	string		$action      	   	Action
3811
+     *	   @param  	array		$formquestion	   	An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
3812
+     *												type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', ...
3813
+     * 	   @param  	string		$selectedchoice  	'' or 'no', or 'yes' or '1' or '0'
3814
+     * 	   @param  	int			$useajax		   	0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
3815
+     *     @param  	int			$height          	Force height of box
3816
+     *     @param	int			$width				Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
3817
+     *     @param	int			$disableformtag		1=Disable form tag. Can be used if we are already inside a <form> section.
3818
+     *     @return 	string      	    			HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
3819
+     */
3820
+    function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=210, $width=500, $disableformtag=0)
3821
+    {
3822
+        global $langs,$conf;
3823
+        global $useglobalvars;
3824
+
3825
+        $more='';
3826
+        $formconfirm='';
3827
+        $inputok=array();
3828
+        $inputko=array();
3829
+
3830
+        // Clean parameters
3831
+        $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
3832
+        if ($conf->browser->layout == 'phone') $width='95%';
3833
+
3834
+        if (is_array($formquestion) && ! empty($formquestion))
3835
+        {
3836
+            // First add hidden fields and value
3837
+            foreach ($formquestion as $key => $input)
3838
+            {
3839
+                if (is_array($input) && ! empty($input))
3840
+                {
3841
+                    if ($input['type'] == 'hidden')
3842
+                    {
3843
+                        $more.='<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
3844
+                    }
3845
+                }
3846
+            }
3847
+
3848
+            // Now add questions
3849
+            $more.='<table class="paddingtopbottomonly" width="100%">'."\n";
3850
+            if (! empty($formquestion['text'])) $more.='<tr><td colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
3851
+            foreach ($formquestion as $key => $input)
3852
+            {
3853
+                if (is_array($input) && ! empty($input))
3854
+                {
3855
+                    $size=(! empty($input['size'])?' size="'.$input['size'].'"':'');
3856
+                    $moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:'');
3857
+                    $morecss=(! empty($input['morecss'])?' '.$input['morecss']:'');
3858
+
3859
+                    if ($input['type'] == 'text')
3860
+                    {
3861
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="text" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3862
+                    }
3863
+                    elseif ($input['type'] == 'password')
3864
+                    {
3865
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="password" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3866
+                    }
3867
+                    elseif ($input['type'] == 'select')
3868
+                    {
3869
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3870
+                        if (! empty($input['label'])) $more.=$input['label'].'</td><td class="tdtop" align="left">';
3871
+                        $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss);
3872
+                        $more.='</td></tr>'."\n";
3873
+                    }
3874
+                    elseif ($input['type'] == 'checkbox')
3875
+                    {
3876
+                        $more.='<tr>';
3877
+                        $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].' </td><td align="left">';
3878
+                        $more.='<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
3879
+                        if (! is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more.=' checked';
3880
+                        if (is_bool($input['value']) && $input['value']) $more.=' checked';
3881
+                        if (isset($input['disabled'])) $more.=' disabled';
3882
+                        $more.=' /></td>';
3883
+                        $more.='</tr>'."\n";
3884
+                    }
3885
+                    elseif ($input['type'] == 'radio')
3886
+                    {
3887
+                        $i=0;
3888
+                        foreach($input['values'] as $selkey => $selval)
3889
+                        {
3890
+                            $more.='<tr>';
3891
+                            if ($i==0) $more.='<td'.(empty($input['tdclass'])?' class="tdtop"':(' class="tdtop '.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3892
+                            else $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>&nbsp;</td>';
3893
+                            $more.='<td><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
3894
+                            if ($input['disabled']) $more.=' disabled';
3895
+                            $more.=' /> ';
3896
+                            $more.=$selval;
3897
+                            $more.='</td></tr>'."\n";
3898
+                            $i++;
3899
+                        }
3900
+                    }
3901
+                    elseif ($input['type'] == 'date')
3902
+                    {
3903
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3904
+                        $more.='<td align="left">';
3905
+                        $more.=$this->selectDate($input['value'],$input['name'],0,0,0,'',1,0);
3906
+                        $more.='</td></tr>'."\n";
3907
+                        $formquestion[] = array('name'=>$input['name'].'day');
3908
+                        $formquestion[] = array('name'=>$input['name'].'month');
3909
+                        $formquestion[] = array('name'=>$input['name'].'year');
3910
+                        $formquestion[] = array('name'=>$input['name'].'hour');
3911
+                        $formquestion[] = array('name'=>$input['name'].'min');
3912
+                    }
3913
+                    elseif ($input['type'] == 'other')
3914
+                    {
3915
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3916
+                        if (! empty($input['label'])) $more.=$input['label'].'</td><td align="left">';
3917
+                        $more.=$input['value'];
3918
+                        $more.='</td></tr>'."\n";
3919
+                    }
3920
+
3921
+                    elseif ($input['type'] == 'onecolumn')
3922
+                    {
3923
+                        $more.='<tr><td colspan="2" align="left">';
3924
+                        $more.=$input['value'];
3925
+                        $more.='</td></tr>'."\n";
3926
+                    }
3927
+                }
3928
+            }
3929
+            $more.='</table>'."\n";
3930
+        }
3931
+
3932
+        // JQUI method dialog is broken with jmobile, we use standard HTML.
3933
+        // Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx
3934
+        // See page product/card.php for example
3935
+        if (! empty($conf->dol_use_jmobile)) $useajax=0;
3936
+        if (empty($conf->use_javascript_ajax)) $useajax=0;
3937
+
3938
+        if ($useajax)
3939
+        {
3940
+            $autoOpen=true;
3941
+            $dialogconfirm='dialog-confirm';
3942
+            $button='';
3943
+            if (! is_numeric($useajax))
3944
+            {
3945
+                $button=$useajax;
3946
+                $useajax=1;
3947
+                $autoOpen=false;
3948
+                $dialogconfirm.='-'.$button;
3949
+            }
3950
+            $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';
3951
+            $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':'');
3952
+            // Add input fields into list of fields to read during submit (inputok and inputko)
3953
+            if (is_array($formquestion))
3954
+            {
3955
+                foreach ($formquestion as $key => $input)
3956
+                {
3957
+                    //print "xx ".$key." rr ".is_array($input)."<br>\n";
3958
+                    if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
3959
+                    if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
3960
+                }
3961
+            }
3962
+            // Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
3963
+            $formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
3964
+            if (! empty($more)) {
3965
+                $formconfirm.= '<div class="confirmquestions">'.$more.'</div>';
3966
+            }
3967
+            $formconfirm.= ($question ? '<div class="confirmmessage">'.img_help('','').' '.$question . '</div>': '');
3968
+            $formconfirm.= '</div>'."\n";
3969
+
3970
+            $formconfirm.= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
3971
+            $formconfirm.= '<script type="text/javascript">'."\n";
3972
+            $formconfirm.= 'jQuery(document).ready(function() {
3973
+            $(function() {
3974
+            	$( "#'.$dialogconfirm.'" ).dialog(
3975
+            	{
3976
+                    autoOpen: '.($autoOpen ? "true" : "false").',';
3977
+            if ($newselectedchoice == 'no')
3978
+            {
3979
+                $formconfirm.='
3980
+						open: function() {
3981
+            				$(this).parent().find("button.ui-button:eq(2)").focus();
3982
+						},';
3983
+            }
3984
+            $formconfirm.='
3985
+                    resizable: false,
3986
+                    height: "'.$height.'",
3987
+                    width: "'.$width.'",
3988
+                    modal: true,
3989
+                    closeOnEscape: false,
3990
+                    buttons: {
3991
+                        "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
3992
+                        	var options="";
3993
+                        	var inputok = '.json_encode($inputok).';
3994
+                         	var pageyes = "'.dol_escape_js(! empty($pageyes)?$pageyes:'').'";
3995
+                         	if (inputok.length>0) {
3996
+                         		$.each(inputok, function(i, inputname) {
3997
+                         			var more = "";
3998
+                         			if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
3999
+                         		    if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
4000
+                         			var inputvalue = $("#" + inputname + more).val();
4001
+                         			if (typeof inputvalue == "undefined") { inputvalue=""; }
4002
+                         			options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
4003
+                         		});
4004
+                         	}
4005
+                         	var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
4006
+                         	//alert(urljump);
4007
+            				if (pageyes.length > 0) { location.href = urljump; }
4008
+                            $(this).dialog("close");
4009
+                        },
4010
+                        "'.dol_escape_js($langs->transnoentities("No")).'": function() {
4011
+                        	var options = "";
4012
+                         	var inputko = '.json_encode($inputko).';
4013
+                         	var pageno="'.dol_escape_js(! empty($pageno)?$pageno:'').'";
4014
+                         	if (inputko.length>0) {
4015
+                         		$.each(inputko, function(i, inputname) {
4016
+                         			var more = "";
4017
+                         			if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
4018
+                         			var inputvalue = $("#" + inputname + more).val();
4019
+                         			if (typeof inputvalue == "undefined") { inputvalue=""; }
4020
+                         			options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
4021
+                         		});
4022
+                         	}
4023
+                         	var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
4024
+                         	//alert(urljump);
4025
+            				if (pageno.length > 0) { location.href = urljump; }
4026
+                            $(this).dialog("close");
4027
+                        }
4028
+                    }
4029
+                }
4030
+                );
4031
+
4032
+            	var button = "'.$button.'";
4033
+            	if (button.length > 0) {
4034
+                	$( "#" + button ).click(function() {
4035
+                		$("#'.$dialogconfirm.'").dialog("open");
4036
+        			});
4037
+                }
4038
+            });
4039
+            });
4040
+            </script>';
4041
+            $formconfirm.= "<!-- end ajax formconfirm -->\n";
4042
+        }
4043
+        else
4044
+        {
4045
+            $formconfirm.= "\n<!-- begin formconfirm page=".$page." -->\n";
4046
+
4047
+            if (empty($disableformtag)) $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
4048
+
4049
+            $formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
4050
+            if (empty($disableformtag)) $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
4051
+
4052
+            $formconfirm.= '<table width="100%" class="valid">'."\n";
4053
+
4054
+            // Line title
4055
+            $formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
4056
+
4057
+            // Line form fields
4058
+            if ($more)
4059
+            {
4060
+                $formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
4061
+                $formconfirm.=$more;
4062
+                $formconfirm.='</td></tr>'."\n";
4063
+            }
4064
+
4065
+            // Line with question
4066
+            $formconfirm.= '<tr class="valid">';
4067
+            $formconfirm.= '<td class="valid">'.$question.'</td>';
4068
+            $formconfirm.= '<td class="valid">';
4069
+            $formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
4070
+            $formconfirm.= '</td>';
4071
+            $formconfirm.= '<td class="valid" align="center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
4072
+            $formconfirm.= '</tr>'."\n";
4073
+
4074
+            $formconfirm.= '</table>'."\n";
4075
+
4076
+            if (empty($disableformtag)) $formconfirm.= "</form>\n";
4077
+            $formconfirm.= '<br>';
4078
+
4079
+            $formconfirm.= "<!-- end formconfirm -->\n";
4080
+        }
4081
+
4082
+        return $formconfirm;
4083
+    }
4084
+
4085
+
4086
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4087
+    /**
4088
+     *    Show a form to select a project
4089
+     *
4090
+     *    @param	int		$page        		Page
4091
+     *    @param	int		$socid       		Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
4092
+     *    @param    int		$selected    		Id pre-selected project
4093
+     *    @param    string	$htmlname    		Name of select field
4094
+     *    @param	int		$discard_closed		Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
4095
+     *    @param	int		$maxlength			Max length
4096
+     *    @param	int		$forcefocus			Force focus on field (works with javascript only)
4097
+     *    @param    int     $nooutput           No print is done. String is returned.
4098
+     *    @return	string                      Return html content
4099
+     */
4100
+    function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)
4101
+    {
4102
+        // phpcs:enable
4103
+        global $langs;
4104
+
4105
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
4106
+        require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
4107
+
4108
+        $out='';
4109
+
4110
+        $formproject=new FormProjets($this->db);
4111
+
4112
+        $langs->load("project");
4113
+        if ($htmlname != "none")
4114
+        {
4115
+            $out.="\n";
4116
+            $out.='<form method="post" action="'.$page.'">';
4117
+            $out.='<input type="hidden" name="action" value="classin">';
4118
+            $out.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4119
+            $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
4120
+            $out.='<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4121
+            $out.='</form>';
4122
+        }
4123
+        else
4124
+        {
4125
+            if ($selected)
4126
+            {
4127
+                $projet = new Project($this->db);
4128
+                $projet->fetch($selected);
4129
+                //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
4130
+                $out.=$projet->getNomUrl(0,'',1);
4131
+            }
4132
+            else
4133
+            {
4134
+                $out.="&nbsp;";
4135
+            }
4136
+        }
4137
+
4138
+        if (empty($nooutput))
4139
+        {
4140
+            print $out;
4141
+            return '';
4142
+        }
4143
+        return $out;
4144
+    }
4145
+
4146
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4147
+    /**
4148
+     *	Show a form to select payment conditions
4149
+     *
4150
+     *  @param	int		$page        	Page
4151
+     *  @param  string	$selected    	Id condition pre-selectionne
4152
+     *  @param  string	$htmlname    	Name of select html field
4153
+     *	@param	int		$addempty		Add empty entry
4154
+     *  @return	void
4155
+     */
4156
+    function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
4157
+    {
4158
+        // phpcs:enable
4159
+        global $langs;
4160
+        if ($htmlname != "none")
4161
+        {
4162
+            print '<form method="post" action="'.$page.'">';
4163
+            print '<input type="hidden" name="action" value="setconditions">';
4164
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4165
+            $this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
4166
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4167
+            print '</form>';
4168
+        }
4169
+        else
4170
+        {
4171
+            if ($selected)
4172
+            {
4173
+                $this->load_cache_conditions_paiements();
4174
+                print $this->cache_conditions_paiements[$selected]['label'];
4175
+            } else {
4176
+                print "&nbsp;";
4177
+            }
4178
+        }
4179
+    }
4180
+
4181
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4182
+    /**
4183
+     *  Show a form to select a delivery delay
4184
+     *
4185
+     *  @param  int		$page        	Page
4186
+     *  @param  string	$selected    	Id condition pre-selectionne
4187
+     *  @param  string	$htmlname    	Name of select html field
4188
+     *	@param	int		$addempty		Ajoute entree vide
4189
+     *  @return	void
4190
+     */
4191
+    function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
4192
+    {
4193
+        // phpcs:enable
4194
+        global $langs;
4195
+        if ($htmlname != "none")
4196
+        {
4197
+            print '<form method="post" action="'.$page.'">';
4198
+            print '<input type="hidden" name="action" value="setavailability">';
4199
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4200
+            $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
4201
+            print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4202
+            print '</form>';
4203
+        }
4204
+        else
4205
+        {
4206
+            if ($selected)
4207
+            {
4208
+                $this->load_cache_availability();
4209
+                print $this->cache_availability[$selected]['label'];
4210
+            } else {
4211
+                print "&nbsp;";
4212
+            }
4213
+        }
4214
+    }
4215
+
4216
+    /**
4217
+     *	Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
4218
+     *  List found into table c_input_reason loaded by loadCacheInputReason
4219
+     *
4220
+     *  @param  string	$page        	Page
4221
+     *  @param  string	$selected    	Id condition pre-selectionne
4222
+     *  @param  string	$htmlname    	Name of select html field
4223
+     *	@param	int		$addempty		Add empty entry
4224
+     *  @return	void
4225
+     */
4226
+    function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)
4227
+    {
4228
+        global $langs;
4229
+        if ($htmlname != "none")
4230
+        {
4231
+            print '<form method="post" action="'.$page.'">';
4232
+            print '<input type="hidden" name="action" value="setdemandreason">';
4233
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4234
+            $this->selectInputReason($selected,$htmlname,-1,$addempty);
4235
+            print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4236
+            print '</form>';
4237
+        }
4238
+        else
4239
+        {
4240
+            if ($selected)
4241
+            {
4242
+                $this->loadCacheInputReason();
4243
+                foreach ($this->cache_demand_reason as $key => $val)
4244
+                {
4245
+                    if ($val['id'] == $selected)
4246
+                    {
4247
+                        print $val['label'];
4248
+                        break;
4249
+                    }
4250
+                }
4251
+            } else {
4252
+                print "&nbsp;";
4253
+            }
4254
+        }
4255
+    }
4256
+
4257
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4258
+    /**
4259
+     *    Show a form + html select a date
4260
+     *
4261
+     *    @param	string		$page        	Page
4262
+     *    @param	string		$selected    	Date preselected
4263
+     *    @param    string		$htmlname    	Html name of date input fields or 'none'
4264
+     *    @param    int			$displayhour 	Display hour selector
4265
+     *    @param    int			$displaymin		Display minutes selector
4266
+     *    @param	int			$nooutput		1=No print output, return string
4267
+     *    @return	string
4268
+     *    @see		selectDate
4269
+     */
4270
+    function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)
4271
+    {
4272
+        // phpcs:enable
4273
+        global $langs;
4274
+
4275
+        $ret='';
4276
+
4277
+        if ($htmlname != "none")
4278
+        {
4279
+            $ret.='<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
4280
+            $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
4281
+            $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4282
+            $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4283
+            $ret.='<tr><td>';
4284
+            $ret.=$this->selectDate($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0);
4285
+            $ret.='</td>';
4286
+            $ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4287
+            $ret.='</tr></table></form>';
4288
+        }
4289
+        else
4290
+        {
4291
+            if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
4292
+            else $ret.=dol_print_date($selected,'day');
4293
+        }
4294
+
4295
+        if (empty($nooutput)) print $ret;
4296
+        return $ret;
4297
+    }
4298
+
4299
+
4300
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4301
+    /**
4302
+     *  Show a select form to choose a user
4303
+     *
4304
+     *  @param	string	$page        	Page
4305
+     *  @param  string	$selected    	Id of user preselected
4306
+     *  @param  string	$htmlname    	Name of input html field. If 'none', we just output the user link.
4307
+     *  @param  array	$exclude		List of users id to exclude
4308
+     *  @param  array	$include        List of users id to include
4309
+     *  @return	void
4310
+     */
4311
+    function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
4312
+    {
4313
+        // phpcs:enable
4314
+        global $langs;
4315
+
4316
+        if ($htmlname != "none")
4317
+        {
4318
+            print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
4319
+            print '<input type="hidden" name="action" value="set'.$htmlname.'">';
4320
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4321
+            print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
4322
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4323
+            print '</form>';
4324
+        }
4325
+        else
4326
+        {
4327
+            if ($selected)
4328
+            {
4329
+                require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
4330
+                $theuser=new User($this->db);
4331
+                $theuser->fetch($selected);
4332
+                print $theuser->getNomUrl(1);
4333
+            } else {
4334
+                print "&nbsp;";
4335
+            }
4336
+        }
4337
+    }
4338
+
4339
+
4340
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4341
+    /**
4342
+     *    Show form with payment mode
4343
+     *
4344
+     *    @param	string	$page        	Page
4345
+     *    @param    int		$selected    	Id mode pre-selectionne
4346
+     *    @param    string	$htmlname    	Name of select html field
4347
+     *    @param  	string	$filtertype		To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
4348
+     *    @param    int     $active         Active or not, -1 = all
4349
+     *    @return	void
4350
+     */
4351
+    function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)
4352
+    {
4353
+        // phpcs:enable
4354
+        global $langs;
4355
+        if ($htmlname != "none")
4356
+        {
4357
+            print '<form method="POST" action="'.$page.'">';
4358
+            print '<input type="hidden" name="action" value="setmode">';
4359
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4360
+            $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);
4361
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4362
+            print '</form>';
4363
+        }
4364
+        else
4365
+        {
4366
+            if ($selected)
4367
+            {
4368
+                $this->load_cache_types_paiements();
4369
+                print $this->cache_types_paiements[$selected]['label'];
4370
+            } else {
4371
+                print "&nbsp;";
4372
+            }
4373
+        }
4374
+    }
4375
+
4376
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4377
+    /**
4378
+     *    Show form with multicurrency code
4379
+     *
4380
+     *    @param	string	$page        	Page
4381
+     *    @param    string	$selected    	code pre-selectionne
4382
+     *    @param    string	$htmlname    	Name of select html field
4383
+     *    @return	void
4384
+     */
4385
+    function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
4386
+    {
4387
+        // phpcs:enable
4388
+        global $langs;
4389
+        if ($htmlname != "none")
4390
+        {
4391
+            print '<form method="POST" action="'.$page.'">';
4392
+            print '<input type="hidden" name="action" value="setmulticurrencycode">';
4393
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4394
+            print $this->selectMultiCurrency($selected, $htmlname, 0);
4395
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4396
+            print '</form>';
4397
+        }
4398
+        else
4399
+        {
4400
+            dol_include_once('/core/lib/company.lib.php');
4401
+            print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
4402
+        }
4403
+    }
4404
+
4405
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4406
+    /**
4407
+     *    Show form with multicurrency rate
4408
+     *
4409
+     *    @param	string	$page        	Page
4410
+     *    @param    double	$rate	    	Current rate
4411
+     *    @param    string	$htmlname    	Name of select html field
4412
+     *    @param    string  $currency       Currency code to explain the rate
4413
+     *    @return	void
4414
+     */
4415
+    function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
4416
+    {
4417
+        // phpcs:enable
4418
+        global $langs, $mysoc, $conf;
4419
+
4420
+        if ($htmlname != "none")
4421
+        {
4422
+            print '<form method="POST" action="'.$page.'">';
4423
+            print '<input type="hidden" name="action" value="setmulticurrencyrate">';
4424
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4425
+            print '<input type="text" name="'.$htmlname.'" value="'.(!empty($rate) ? price($rate) : 1).'" size="10" /> ';
4426
+            print '<select name="calculation_mode">';
4427
+            print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
4428
+            print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
4429
+            print '</select> ';
4430
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4431
+            print '</form>';
4432
+        }
4433
+        else
4434
+        {
4435
+            if (! empty($rate))
4436
+            {
4437
+                print price($rate, 1, $langs, 1, 0);
4438
+                if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
4439
+            }
4440
+            else
4441
+            {
4442
+                print 1;
4443
+            }
4444
+        }
4445
+    }
4446
+
4447
+
4448
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4449
+    /**
4450
+     *	Show a select box with available absolute discounts
4451
+     *
4452
+     *  @param  string	$page        	Page URL where form is shown
4453
+     *  @param  int		$selected    	Value pre-selected
4454
+     *	@param  string	$htmlname    	Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
4455
+     *	@param	int		$socid			Third party id
4456
+     * 	@param	float	$amount			Total amount available
4457
+     * 	@param	string	$filter			SQL filter on discounts
4458
+     * 	@param	int		$maxvalue		Max value for lines that can be selected
4459
+     *  @param  string	$more           More string to add
4460
+     *  @param  int     $hidelist       1=Hide list
4461
+     *  @param	int		$discount_type	0 => customer discount, 1 => supplier discount
4462
+     *  @return	void
4463
+     */
4464
+    function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0)
4465
+    {
4466
+        // phpcs:enable
4467
+        global $conf,$langs;
4468
+        if ($htmlname != "none")
4469
+        {
4470
+            print '<form method="post" action="'.$page.'">';
4471
+            print '<input type="hidden" name="action" value="setabsolutediscount">';
4472
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4473
+            print '<div class="inline-block">';
4474
+            if(! empty($discount_type)) {
4475
+                if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4476
+                {
4477
+                    if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier';    // If we want deposit to be substracted to payments only and not to total of final invoice
4478
+                    else $translationKey = 'HasCreditNoteFromSupplier';
4479
+                }
4480
+                else
4481
+                {
4482
+                    if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
4483
+                    else $translationKey = 'HasCreditNoteFromSupplier';
4484
+                }
4485
+            } else {
4486
+                if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4487
+                {
4488
+                    if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount';    // If we want deposit to be substracted to payments only and not to total of final invoice
4489
+                    else $translationKey = 'CompanyHasCreditNote';
4490
+                }
4491
+                else
4492
+                {
4493
+                    if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
4494
+                    else $translationKey = 'CompanyHasCreditNote';
4495
+                }
4496
+            }
4497
+            print $langs->trans($translationKey,price($amount,0,$langs,0,0,-1,$conf->currency));
4498
+            if (empty($hidelist)) print ': ';
4499
+            print '</div>';
4500
+            if (empty($hidelist))
4501
+            {
4502
+                print '<div class="inline-block" style="padding-right: 10px">';
4503
+                $newfilter = 'discount_type='.intval($discount_type);
4504
+                if(! empty($discount_type)) {
4505
+                    $newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
4506
+                } else {
4507
+                    $newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
4508
+                }
4509
+                if ($filter) $newfilter.=' AND ('.$filter.')';
4510
+                $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
4511
+                if ($nbqualifiedlines > 0)
4512
+                {
4513
+                    print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
4514
+                    if(! empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
4515
+                        print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4516
+                    if(empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
4517
+                        print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4518
+
4519
+                    print '>';
4520
+                }
4521
+                print '</div>';
4522
+            }
4523
+            if ($more)
4524
+            {
4525
+                print '<div class="inline-block">';
4526
+                print $more;
4527
+                print '</div>';
4528
+            }
4529
+            print '</form>';
4530
+        }
4531
+        else
4532
+        {
4533
+            if ($selected)
4534
+            {
4535
+                print $selected;
4536
+            }
4537
+            else
4538
+            {
4539
+                print "0";
4540
+            }
4541
+        }
4542
+    }
4543
+
4544
+
4545
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4546
+    /**
4547
+     *    Show forms to select a contact
4548
+     *
4549
+     *    @param	string		$page        	Page
4550
+     *    @param	Societe		$societe		Filter on third party
4551
+     *    @param    int			$selected    	Id contact pre-selectionne
4552
+     *    @param    string		$htmlname    	Name of HTML select. If 'none', we just show contact link.
4553
+     *    @return	void
4554
+     */
4555
+    function form_contacts($page, $societe, $selected='', $htmlname='contactid')
4556
+    {
4557
+        // phpcs:enable
4558
+        global $langs, $conf;
4559
+
4560
+        if ($htmlname != "none")
4561
+        {
4562
+            print '<form method="post" action="'.$page.'">';
4563
+            print '<input type="hidden" name="action" value="set_contact">';
4564
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4565
+            print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4566
+            print '<tr><td>';
4567
+            $num=$this->select_contacts($societe->id, $selected, $htmlname);
4568
+            if ($num==0)
4569
+            {
4570
+                $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
4571
+                print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
4572
+            }
4573
+            print '</td>';
4574
+            print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4575
+            print '</tr></table></form>';
4576
+        }
4577
+        else
4578
+        {
4579
+            if ($selected)
4580
+            {
4581
+                require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
4582
+                $contact=new Contact($this->db);
4583
+                $contact->fetch($selected);
4584
+                print $contact->getFullName($langs);
4585
+            } else {
4586
+                print "&nbsp;";
4587
+            }
4588
+        }
4589
+    }
4590
+
4591
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4592
+    /**
4593
+     *  Output html select to select thirdparty
4594
+     *
4595
+     *  @param	string	$page       	Page
4596
+     *  @param  string	$selected   	Id preselected
4597
+     *  @param  string	$htmlname		Name of HTML select
4598
+     *  @param  string	$filter         optional filters criteras
4599
+     *	@param	int		$showempty		Add an empty field
4600
+     * 	@param	int		$showtype		Show third party type in combolist (customer, prospect or supplier)
4601
+     * 	@param	int		$forcecombo		Force to use combo box
4602
+     *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
4603
+     *  @param  int     $nooutput       No print output. Return it only.
4604
+     *  @return	void
4605
+     */
4606
+    function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array(), $nooutput=0)
4607
+    {
4608
+        // phpcs:enable
4609
+        global $langs;
4610
+
4611
+        $out = '';
4612
+        if ($htmlname != "none")
4613
+        {
4614
+            $out.='<form method="post" action="'.$page.'">';
4615
+            $out.= '<input type="hidden" name="action" value="set_thirdparty">';
4616
+            $out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4617
+            $out.= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
4618
+            $out.= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4619
+            $out.= '</form>';
4620
+        }
4621
+        else
4622
+        {
4623
+            if ($selected)
4624
+            {
4625
+                require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
4626
+                $soc = new Societe($this->db);
4627
+                $soc->fetch($selected);
4628
+                $out.= $soc->getNomUrl($langs);
4629
+            }
4630
+            else
4631
+            {
4632
+                $out.= "&nbsp;";
4633
+            }
4634
+        }
4635
+
4636
+        if ($nooutput) return $out;
4637
+        else print $out;
4638
+    }
4639
+
4640
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4641
+    /**
4642
+     *    Retourne la liste des devises, dans la langue de l'utilisateur
4643
+     *
4644
+     *    @param	string	$selected    preselected currency code
4645
+     *    @param    string	$htmlname    name of HTML select list
4646
+     *    @deprecated
4647
+     *    @return	void
4648
+     */
4649
+    function select_currency($selected='',$htmlname='currency_id')
4650
+    {
4651
+        // phpcs:enable
4652
+        print $this->selectCurrency($selected,$htmlname);
4653
+    }
4654
+
4655
+    /**
4656
+     *  Retourne la liste des devises, dans la langue de l'utilisateur
4657
+     *
4658
+     *  @param	string	$selected    preselected currency code
4659
+     *  @param  string	$htmlname    name of HTML select list
4660
+     * 	@return	string
4661
+     */
4662
+    function selectCurrency($selected='',$htmlname='currency_id')
4663
+    {
4664
+        global $conf,$langs,$user;
4665
+
4666
+        $langs->loadCacheCurrencies('');
4667
+
4668
+        $out='';
4669
+
4670
+        if ($selected=='euro' || $selected=='euros') $selected='EUR';   // Pour compatibilite
4671
+
4672
+        $out.= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
4673
+        foreach ($langs->cache_currencies as $code_iso => $currency)
4674
+        {
4675
+            if ($selected && $selected == $code_iso)
4676
+            {
4677
+                $out.= '<option value="'.$code_iso.'" selected>';
4678
+            }
4679
+            else
4680
+            {
4681
+                $out.= '<option value="'.$code_iso.'">';
4682
+            }
4683
+            $out.= $currency['label'];
4684
+            $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4685
+            $out.= '</option>';
4686
+        }
4687
+        $out.= '</select>';
4688
+        if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
4689
+
4690
+        // Make select dynamic
4691
+        include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4692
+        $out .= ajax_combobox($htmlname);
4693
+
4694
+        return $out;
4695
+    }
4696
+
4697
+    /**
4698
+     *	Return array of currencies in user language
4699
+     *
4700
+     *  @param	string	$selected    preselected currency code
4701
+     *  @param  string	$htmlname    name of HTML select list
4702
+     *  @param  integer	$useempty    1=Add empty line
4703
+     * 	@return	string
4704
+     */
4705
+    function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)
4706
+    {
4707
+        global $db,$conf,$langs,$user;
4708
+
4709
+        $langs->loadCacheCurrencies('');        // Load ->cache_currencies
4710
+
4711
+        $TCurrency = array();
4712
+
4713
+        $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
4714
+        $sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
4715
+        $resql = $db->query($sql);
4716
+        if ($resql)
4717
+        {
4718
+            while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
4719
+        }
4720
+
4721
+        $out='';
4722
+        $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
4723
+        if ($useempty) $out .= '<option value=""></option>';
4724
+        // If company current currency not in table, we add it into list. Should always be available.
4725
+        if (! in_array($conf->currency, $TCurrency))
4726
+        {
4727
+            $TCurrency[$conf->currency] = $conf->currency;
4728
+        }
4729
+        if (count($TCurrency) > 0)
4730
+        {
4731
+            foreach ($langs->cache_currencies as $code_iso => $currency)
4732
+            {
4733
+                if (isset($TCurrency[$code_iso]))
4734
+                {
4735
+                    if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
4736
+                    else $out.= '<option value="'.$code_iso.'">';
4737
+
4738
+                    $out.= $currency['label'];
4739
+                    $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4740
+                    $out.= '</option>';
4741
+                }
4742
+            }
4743
+        }
4744
+
4745
+        $out.= '</select>';
4746
+        // Make select dynamic
4747
+        include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4748
+        $out.= ajax_combobox($htmlname);
4749
+
4750
+        return $out;
4751
+    }
4752
+
4753
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4754
+    /**
4755
+     *	Load into the cache vat rates of a country
4756
+     *
4757
+     *	@param	string	$country_code		Country code with quotes ("'CA'", or "'CA,IN,...'")
4758
+     *	@return	int							Nb of loaded lines, 0 if already loaded, <0 if KO
4759
+     */
4760
+    function load_cache_vatrates($country_code)
4761
+    {
4762
+        // phpcs:enable
4763
+        global $langs;
4764
+
4765
+        $num = count($this->cache_vatrates);
4766
+        if ($num > 0) return $num;    // Cache already loaded
4767
+
4768
+        dol_syslog(__METHOD__, LOG_DEBUG);
4769
+
4770
+        $sql  = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
4771
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4772
+        $sql.= " WHERE t.fk_pays = c.rowid";
4773
+        $sql.= " AND t.active > 0";
4774
+        $sql.= " AND c.code IN (".$country_code.")";
4775
+        $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
4776
+
4777
+        $resql=$this->db->query($sql);
4778
+        if ($resql)
4779
+        {
4780
+            $num = $this->db->num_rows($resql);
4781
+            if ($num)
4782
+            {
4783
+                for ($i = 0; $i < $num; $i++)
4784
+                {
4785
+                    $obj = $this->db->fetch_object($resql);
4786
+                    $this->cache_vatrates[$i]['rowid']	= $obj->rowid;
4787
+                    $this->cache_vatrates[$i]['code']	= $obj->code;
4788
+                    $this->cache_vatrates[$i]['txtva']	= $obj->taux;
4789
+                    $this->cache_vatrates[$i]['nprtva']	= $obj->recuperableonly;
4790
+                    $this->cache_vatrates[$i]['localtax1']	    = $obj->localtax1;
4791
+                    $this->cache_vatrates[$i]['localtax1_type']	= $obj->localtax1_type;
4792
+                    $this->cache_vatrates[$i]['localtax2']	    = $obj->localtax2;
4793
+                    $this->cache_vatrates[$i]['localtax2_type']	= $obj->localtax1_type;
4794
+
4795
+                    $this->cache_vatrates[$i]['label']	= $obj->taux.'%'.($obj->code?' ('.$obj->code.')':'');   // Label must contains only 0-9 , . % or *
4796
+                    $this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4797
+                    $positiverates='';
4798
+                    if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;
4799
+                    if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;
4800
+                    if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;
4801
+                    if (empty($positiverates)) $positiverates='0';
4802
+                    $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4803
+                }
4804
+
4805
+                return $num;
4806
+            }
4807
+            else
4808
+            {
4809
+                $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
4810
+                return -1;
4811
+            }
4812
+        }
4813
+        else
4814
+        {
4815
+            $this->error = '<font class="error">'.$this->db->error().'</font>';
4816
+            return -2;
4817
+        }
4818
+    }
4819
+
4820
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4821
+    /**
4822
+     *  Output an HTML select vat rate.
4823
+     *  The name of this function should be selectVat. We keep bad name for compatibility purpose.
4824
+     *
4825
+     *  @param	string	      $htmlname           Name of HTML select field
4826
+     *  @param  float|string  $selectedrate       Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
4827
+     *  @param  Societe	      $societe_vendeuse   Thirdparty seller
4828
+     *  @param  Societe	      $societe_acheteuse  Thirdparty buyer
4829
+     *  @param  int		      $idprod             Id product. O if unknown of NA.
4830
+     *  @param  int		      $info_bits          Miscellaneous information on line (1 for NPR)
4831
+     *  @param  int|string    $type               ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
4832
+     *                  		                  Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
4833
+     *                  					      Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
4834
+     *                  					      Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
4835
+     *                                            Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
4836
+     *                                            Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
4837
+     *                  					      Sinon la TVA proposee par defaut=0. Fin de regle.
4838
+     *  @param	bool	     $options_only		  Return HTML options lines only (for ajax treatment)
4839
+     *  @param  int          $mode                0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key
4840
+     *  @return	string
4841
+     */
4842
+    function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)
4843
+    {
4844
+        // phpcs:enable
4845
+        global $langs,$conf,$mysoc;
4846
+
4847
+        $langs->load('errors');
4848
+
4849
+        $return='';
4850
+
4851
+        // Define defaultnpr, defaultttx and defaultcode
4852
+        $defaultnpr=($info_bits & 0x01);
4853
+        $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
4854
+        $defaulttx=str_replace('*','',$selectedrate);
4855
+        $defaultcode='';
4856
+        if (preg_match('/\((.*)\)/', $defaulttx, $reg))
4857
+        {
4858
+            $defaultcode=$reg[1];
4859
+            $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4860
+        }
4861
+        //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
4862
+
4863
+        // Check parameters
4864
+        if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
4865
+        {
4866
+            if ($societe_vendeuse->id == $mysoc->id)
4867
+            {
4868
+                $return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
4869
+            }
4870
+            else
4871
+            {
4872
+                $return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
4873
+            }
4874
+            return $return;
4875
+        }
4876
+
4877
+        //var_dump($societe_acheteuse);
4878
+        //print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->country_code." buyer=".$societe_acheteuse->country_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type";
4879
+        //exit;
4880
+
4881
+        // Define list of countries to use to search VAT rates to show
4882
+        // First we defined code_country to use to find list
4883
+        if (is_object($societe_vendeuse))
4884
+        {
4885
+            $code_country="'".$societe_vendeuse->country_code."'";
4886
+        }
4887
+        else
4888
+        {
4889
+            $code_country="'".$mysoc->country_code."'";   // Pour compatibilite ascendente
4890
+        }
4891
+        if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))    // If option to have vat for end customer for services is on
4892
+        {
4893
+            require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4894
+            if (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany())))
4895
+            {
4896
+                // We also add the buyer
4897
+                if (is_numeric($type))
4898
+                {
4899
+                    if ($type == 1) // We know product is a service
4900
+                    {
4901
+                        $code_country.=",'".$societe_acheteuse->country_code."'";
4902
+                    }
4903
+                }
4904
+                else if (! $idprod)  // We don't know type of product
4905
+                {
4906
+                    $code_country.=",'".$societe_acheteuse->country_code."'";
4907
+                }
4908
+                else
4909
+                {
4910
+                    $prodstatic=new Product($this->db);
4911
+                    $prodstatic->fetch($idprod);
4912
+                    if ($prodstatic->type == Product::TYPE_SERVICE)   // We know product is a service
4913
+                    {
4914
+                        $code_country.=",'".$societe_acheteuse->country_code."'";
4915
+                    }
4916
+                }
4917
+            }
4918
+        }
4919
+
4920
+        // Now we get list
4921
+        $num = $this->load_cache_vatrates($code_country);   // If no vat defined, return -1 with message into this->error
4922
+
4923
+        if ($num > 0)
4924
+        {
4925
+            // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
4926
+            if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4927
+            {
4928
+                $tmpthirdparty=new Societe($this->db);
4929
+                $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4930
+                $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4931
+                if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
4932
+                    $defaultcode=$reg[1];
4933
+                    $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4934
+                }
4935
+                if (empty($defaulttx)) $defaultnpr=0;
4936
+            }
4937
+
4938
+            // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
4939
+            // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
4940
+            if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4941
+            {
4942
+                if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
4943
+                else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
4944
+            }
4945
+
4946
+            // Disabled if seller is not subject to VAT
4947
+            $disabled=false; $title='';
4948
+            if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
4949
+            {
4950
+                // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses
4951
+                if (empty($conf->global->OVERRIDE_VAT_FOR_EXPENSE_REPORT))
4952
+                {
4953
+                    $title=' title="'.$langs->trans('VATIsNotUsed').'"';
4954
+                    $disabled=true;
4955
+                }
4956
+            }
4957
+
4958
+            if (! $options_only) $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
4959
+
4960
+            $selectedfound=false;
4961
+            foreach ($this->cache_vatrates as $rate)
4962
+            {
4963
+                // Keep only 0 if seller is not subject to VAT
4964
+                if ($disabled && $rate['txtva'] != 0) continue;
4965
+
4966
+                // Define key to use into select list
4967
+                $key = $rate['txtva'];
4968
+                $key.= $rate['nprtva'] ? '*': '';
4969
+                if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';
4970
+                if ($mode < 0) $key = $rate['rowid'];
4971
+
4972
+                $return.= '<option value="'.$key.'"';
4973
+                if (! $selectedfound)
4974
+                {
4975
+                    if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
4976
+                    {
4977
+                        if ($defaultcode == $rate['code'])
4978
+                        {
4979
+                            $return.= ' selected';
4980
+                            $selectedfound=true;
4981
+                        }
4982
+                    }
4983
+                    elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
4984
+                        {
4985
+                            $return.= ' selected';
4986
+                            $selectedfound=true;
4987
+                    }
4988
+                }
4989
+                $return.= '>';
4990
+                //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
4991
+                if ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
4992
+                {
4993
+                    $return.= $rate['labelpositiverates'];
4994
+                }
4995
+                else
4996
+                {
4997
+                    $return.= vatrate($rate['label']);
4998
+                }
4999
+                //$return.=($rate['code']?' '.$rate['code']:'');
5000
+                $return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': '';         // We show the *  (old behaviour only if new vat code is not used)
5001
+
5002
+                $return.= '</option>';
5003
+            }
5004
+
5005
+            if (! $options_only) $return.= '</select>';
5006
+        }
5007
+        else
5008
+        {
5009
+            $return.= $this->error;
5010
+        }
5011
+
5012
+        $this->num = $num;
5013
+        return $return;
5014
+    }
5015
+
5016
+
5017
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
5018
+    /**
5019
+     *  Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
5020
+     *  Fields are preselected with :
5021
+     *            	- set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
5022
+     *            	- local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
5023
+     *            	- Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
5024
+     *
5025
+     *	@param	timestamp	$set_time 		Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
5026
+     *	@param	string		$prefix			Prefix for fields name
5027
+     *	@param	int			$h				1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
5028
+     *	@param	int			$m				1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
5029
+     *	@param	int			$empty			0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
5030
+     *	@param	string		$form_name 		Not used
5031
+     *	@param	int			$d				1=Show days, month, years
5032
+     * 	@param	int			$addnowlink		Add a link "Now"
5033
+     * 	@param	int			$nooutput		Do not output html string but return it
5034
+     * 	@param 	int			$disabled		Disable input fields
5035
+     *  @param  int			$fullday        When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
5036
+     *  @param	string		$addplusone		Add a link "+1 hour". Value must be name of another select_date field.
5037
+     *  @param  datetime    $adddateof      Add a link "Date of invoice" using the following date.
5038
+     *  @return	string|void					Nothing or string if nooutput is 1
5039
+     *  @deprecated
5040
+     *  @see    form_date, select_month, select_year, select_dayofweek
5041
+     */
5042
+    function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5043
+    {
5044
+        // phpcs:enable
5045
+        $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
5046
+        if (! empty($nooutput)) {
5047
+            return $retstring;
5048
+        }
5049
+        print $retstring;
5050
+        return;
5051
+    }
5052
+
5053
+    /**
5054
+     *  Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
5055
+     *  Fields are preselected with :
5056
+     *              - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
5057
+     *              - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
5058
+     *              - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
5059
+     *
5060
+     *  @param  timestamp   $set_time       Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
5061
+     *  @param	string		$prefix			Prefix for fields name
5062
+     *  @param	int			$h				1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
5063
+     *	@param	int			$m				1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
5064
+     *	@param	int			$empty			0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
5065
+     *	@param	string		$form_name 		Not used
5066
+     *	@param	int			$d				1=Show days, month, years
5067
+     * 	@param	int			$addnowlink		Add a link "Now"
5068
+     * 	@param 	int			$disabled		Disable input fields
5069
+     *  @param  int			$fullday        When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
5070
+     *  @param	string		$addplusone		Add a link "+1 hour". Value must be name of another selectDate field.
5071
+     *  @param  datetime    $adddateof      Add a link "Date of invoice" using the following date.
5072
+     * 	@return string                      Html for selectDate
5073
+     *  @see    form_date, select_month, select_year, select_dayofweek
5074
+     */
5075
+    function selectDate($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5076
+    {
5077
+        global $conf,$langs;
5078
+
5079
+        $retstring='';
5080
+
5081
+        if ($prefix=='') $prefix='re';
5082
+        if ($h == '') $h=0;
5083
+        if ($m == '') $m=0;
5084
+        $emptydate=0;
5085
+        $emptyhours=0;
5086
+        if ($empty == 1) { $emptydate=1; $emptyhours=1; }
5087
+        if ($empty == 2) { $emptydate=0; $emptyhours=1; }
5088
+        $orig_set_time=$set_time;
5089
+
5090
+        if ($set_time === '' && $emptydate == 0)
5091
+        {
5092
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5093
+            $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone
5094
+        }
5095
+
5096
+        // Analysis of the pre-selection date
5097
+        if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))	// deprecated usage
5098
+        {
5099
+            // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
5100
+            $syear	= (! empty($reg[1])?$reg[1]:'');
5101
+            $smonth	= (! empty($reg[2])?$reg[2]:'');
5102
+            $sday	= (! empty($reg[3])?$reg[3]:'');
5103
+            $shour	= (! empty($reg[4])?$reg[4]:'');
5104
+            $smin	= (! empty($reg[5])?$reg[5]:'');
5105
+        }
5106
+        elseif (strval($set_time) != '' && $set_time != -1)
5107
+        {
5108
+            // set_time est un timestamps (0 possible)
5109
+            $syear = dol_print_date($set_time, "%Y");
5110
+            $smonth = dol_print_date($set_time, "%m");
5111
+            $sday = dol_print_date($set_time, "%d");
5112
+            if ($orig_set_time != '')
5113
+            {
5114
+                $shour = dol_print_date($set_time, "%H");
5115
+                $smin = dol_print_date($set_time, "%M");
5116
+                $ssec = dol_print_date($set_time, "%S");
5117
+            }
5118
+            else
5119
+            {
5120
+                $shour = '';
5121
+                $smin = '';
5122
+                $ssec = '';
5123
+            }
5124
+        }
5125
+        else
5126
+        {
5127
+            // Date est '' ou vaut -1
5128
+            $syear = '';
5129
+            $smonth = '';
5130
+            $sday = '';
5131
+            $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
5132
+            $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
5133
+            $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
5134
+        }
5135
+        if ($h == 3) $shour = '';
5136
+        if ($m == 3) $smin = '';
5137
+
5138
+        // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
5139
+        $usecalendar='combo';
5140
+        if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
5141
+            $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR);
5142
+        }
5143
+
5144
+        if ($d)
5145
+        {
5146
+            // Show date with popup
5147
+            if ($usecalendar != 'combo')
5148
+            {
5149
+                $formated_date='';
5150
+                //print "e".$set_time." t ".$conf->format_date_short;
5151
+                if (strval($set_time) != '' && $set_time != -1)
5152
+                {
5153
+                    //$formated_date=dol_print_date($set_time,$conf->format_date_short);
5154
+                    $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput"));  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5155
+                }
5156
+
5157
+                // Calendrier popup version eldy
5158
+                if ($usecalendar == "eldy")
5159
+                {
5160
+                    // Zone de saisie manuelle de la date
5161
+                    $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5162
+                    $retstring.=($disabled?' disabled':'');
5163
+                    $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5164
+                    $retstring.='>';
5165
+
5166
+                    // Icone calendrier
5167
+                    if (! $disabled)
5168
+                    {
5169
+                        $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
5170
+                        $base=DOL_URL_ROOT.'/core/';
5171
+                        $retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
5172
+                        $retstring.='>'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
5173
+                    }
5174
+                    else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5175
+
5176
+                    $retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5177
+                    $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5178
+                    $retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5179
+                }
5180
+                elseif ($usecalendar == 'jquery')
5181
+                {
5182
+                    if (! $disabled)
5183
+                    {
5184
+                        // Output javascript for datepicker
5185
+                        $retstring.="<script type='text/javascript'>";
5186
+                        $retstring.="$(function(){ $('#".$prefix."').datepicker({
5187
+							dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
5188
+							autoclose: true,
5189
+							todayHighlight: true,";
5190
+                            if (! empty($conf->dol_use_jmobile))
5191
+                            {
5192
+                                $retstring.="
5193
+								beforeShow: function (input, datePicker) {
5194
+									input.disabled = true;
5195
+								},
5196
+								onClose: function (dateText, datePicker) {
5197
+									this.disabled = false;
5198
+								},
5199
+								";
5200
+                            }
5201
+                            // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
5202
+                            if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))
5203
+                            {
5204
+                            $retstring.="
5205
+								showOn: 'button',
5206
+								buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
5207
+								buttonImageOnly: true";
5208
+                            }
5209
+                            $retstring.="
5210
+							}) });";
5211
+                        $retstring.="</script>";
5212
+                    }
5213
+
5214
+                    // Zone de saisie manuelle de la date
5215
+                    $retstring.='<div class="nowrap inline-block">';
5216
+                    $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5217
+                    $retstring.=($disabled?' disabled':'');
5218
+                    $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5219
+                    $retstring.='>';
5220
+
5221
+                    // Icone calendrier
5222
+                    if (! $disabled)
5223
+                    {
5224
+                        /* Not required. Managed by option buttonImage of jquery
5225
+                		$retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
5226
+                		$retstring.="<script type='text/javascript'>";
5227
+                		$retstring.="jQuery(document).ready(function() {";
5228
+                		$retstring.='	jQuery("#'.$prefix.'id").click(function() {';
5229
+                		$retstring.="    	jQuery('#".$prefix."').focus();";
5230
+                		$retstring.='    });';
5231
+                		$retstring.='});';
5232
+                		$retstring.="</script>";*/
5233
+                    }
5234
+                    else
5235
+                    {
5236
+                        $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5237
+                    }
5238
+
5239
+                    $retstring.='</div>';
5240
+                    $retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5241
+                    $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5242
+                    $retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5243
+                }
5244
+                else
5245
+                {
5246
+                    $retstring.="Bad value of MAIN_POPUP_CALENDAR";
5247
+                }
5248
+            }
5249
+            // Show date with combo selects
5250
+            else
5251
+            {
5252
+                //$retstring.='<div class="inline-block">';
5253
+                // Day
5254
+                $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
5255
+
5256
+                if ($emptydate || $set_time == -1)
5257
+                {
5258
+                    $retstring.='<option value="0" selected>&nbsp;</option>';
5259
+                }
5260
+
5261
+                for ($day = 1 ; $day <= 31; $day++)
5262
+                {
5263
+                    $retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
5264
+                }
5265
+
5266
+                $retstring.="</select>";
5267
+
5268
+                $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
5269
+                if ($emptydate || $set_time == -1)
5270
+                {
5271
+                    $retstring.='<option value="0" selected>&nbsp;</option>';
5272
+                }
5273
+
5274
+                // Month
5275
+                for ($month = 1 ; $month <= 12 ; $month++)
5276
+                {
5277
+                    $retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
5278
+                    $retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
5279
+                    $retstring.="</option>";
5280
+                }
5281
+                $retstring.="</select>";
5282
+
5283
+                // Year
5284
+                if ($emptydate || $set_time == -1)
5285
+                {
5286
+                    $retstring.='<input'.($disabled?' disabled':'').' placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" class="flat maxwidth50imp valignmiddle" type="number" min="0" max="3000" maxlength="4" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">';
5287
+                }
5288
+                else
5289
+                {
5290
+                    $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
5291
+
5292
+                    for ($year = $syear - 10; $year < $syear + 10 ; $year++)
5293
+                    {
5294
+                        $retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
5295
+                    }
5296
+                    $retstring.="</select>\n";
5297
+                }
5298
+                //$retstring.='</div>';
5299
+            }
5300
+        }
5301
+
5302
+        if ($d && $h) $retstring.=($h==2?'<br>':' ');
5303
+
5304
+        if ($h)
5305
+        {
5306
+            // Show hour
5307
+            $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
5308
+            if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5309
+            for ($hour = 0; $hour < 24; $hour++)
5310
+            {
5311
+                if (strlen($hour) < 2) $hour = "0" . $hour;
5312
+                $retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
5313
+            }
5314
+            $retstring.='</select>';
5315
+            if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
5316
+        }
5317
+
5318
+        if ($m)
5319
+        {
5320
+            // Show minutes
5321
+            $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
5322
+            if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5323
+            for ($min = 0; $min < 60 ; $min++)
5324
+            {
5325
+                if (strlen($min) < 2) $min = "0" . $min;
5326
+                $retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
5327
+            }
5328
+            $retstring.='</select>';
5329
+
5330
+            $retstring.='<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
5331
+        }
5332
+
5333
+        // Add a "Now" link
5334
+        if ($conf->use_javascript_ajax && $addnowlink)
5335
+        {
5336
+            // Script which will be inserted in the onClick of the "Now" link
5337
+            $reset_scripts = "";
5338
+
5339
+            // Generate the date part, depending on the use or not of the javascript calendar
5340
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5341
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5342
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5343
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5344
+            /*if ($usecalendar == "eldy")
5345
+            {
5346
+                $base=DOL_URL_ROOT.'/core/';
5347
+                $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
5348
+            }
5349
+            else
5350
+            {
5351
+                $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
5352
+                $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
5353
+                $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
5354
+            }*/
5355
+            // Update the hour part
5356
+            if ($h)
5357
+            {
5358
+                if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5359
+                //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
5360
+                $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5361
+                if ($fullday) $reset_scripts .= ' } ';
5362
+            }
5363
+            // Update the minute part
5364
+            if ($m)
5365
+            {
5366
+                if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5367
+                //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
5368
+                $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5369
+                if ($fullday) $reset_scripts .= ' } ';
5370
+            }
5371
+            // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5372
+            if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5373
+            {
5374
+                $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
5375
+                $retstring.=$langs->trans("Now");
5376
+                $retstring.='</button> ';
5377
+            }
5378
+        }
5379
+
5380
+        // Add a "Plus one hour" link
5381
+        if ($conf->use_javascript_ajax && $addplusone)
5382
+        {
5383
+            // Script which will be inserted in the onClick of the "Add plusone" link
5384
+            $reset_scripts = "";
5385
+
5386
+            // Generate the date part, depending on the use or not of the javascript calendar
5387
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5388
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5389
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5390
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5391
+            // Update the hour part
5392
+            if ($h)
5393
+            {
5394
+                if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5395
+                $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5396
+                if ($fullday) $reset_scripts .= ' } ';
5397
+            }
5398
+            // Update the minute part
5399
+            if ($m)
5400
+            {
5401
+                if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5402
+                $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5403
+                if ($fullday) $reset_scripts .= ' } ';
5404
+            }
5405
+            // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5406
+            if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5407
+            {
5408
+                $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
5409
+                $retstring.=$langs->trans("DateStartPlusOne");
5410
+                $retstring.='</button> ';
5411
+            }
5412
+        }
5413
+
5414
+        // Add a "Plus one hour" link
5415
+        if ($conf->use_javascript_ajax && $adddateof)
5416
+        {
5417
+            $tmparray=dol_getdate($adddateof);
5418
+            $retstring.=' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof,'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$langs->trans("DateInvoice").'</a>';
5419
+        }
5420
+
5421
+        return $retstring;
5422
+    }
5423
+
5424
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
5425
+    /**
5426
+     *	Function to show a form to select a duration on a page
5427
+     *
5428
+     *	@param	string	$prefix   		Prefix for input fields
5429
+     *	@param  int	$iSecond  		    Default preselected duration (number of seconds or '')
5430
+     * 	@param	int	$disabled           Disable the combo box
5431
+     * 	@param	string	$typehour		If 'select' then input hour and input min is a combo,
5432
+     *						            if 'text' input hour is in text and input min is a text,
5433
+     *						            if 'textselect' input hour is in text and input min is a combo
5434
+     *  @param	integer	$minunderhours	If 1, show minutes selection under the hours
5435
+     * 	@param	int	$nooutput		    Do not output html string but return it
5436
+     *  @return	string|void
5437
+     */
5438
+    function select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)
5439
+    {
5440
+        // phpcs:enable
5441
+        global $langs;
5442
+
5443
+        $retstring='';
5444
+
5445
+        $hourSelected=0; $minSelected=0;
5446
+
5447
+        // Hours
5448
+        if ($iSecond != '')
5449
+        {
5450
+            require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5451
+
5452
+            $hourSelected = convertSecondToTime($iSecond,'allhour');
5453
+            $minSelected = convertSecondToTime($iSecond,'min');
5454
+        }
5455
+
5456
+        if ($typehour=='select' )
5457
+        {
5458
+            $retstring.='<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
5459
+            for ($hour = 0; $hour < 25; $hour++)	// For a duration, we allow 24 hours
5460
+            {
5461
+                $retstring.='<option value="'.$hour.'"';
5462
+                if ($hourSelected == $hour)
5463
+                {
5464
+                    $retstring.=" selected";
5465
+                }
5466
+                $retstring.=">".$hour."</option>";
5467
+            }
5468
+            $retstring.="</select>";
5469
+        }
5470
+        elseif ($typehour=='text' || $typehour=='textselect')
5471
+        {
5472
+            $retstring.='<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '')?((int) $hourSelected):'').'">';
5473
+        }
5474
+        else return 'BadValueForParameterTypeHour';
5475
+
5476
+        if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');
5477
+        else $retstring.='<span class="hideonsmartphone">:</span>';
5478
+
5479
+        // Minutes
5480
+        if ($minunderhours) $retstring.='<br>';
5481
+        else $retstring.='<span class="hideonsmartphone">&nbsp;</span>';
5482
+
5483
+        if ($typehour=='select' || $typehour=='textselect')
5484
+        {
5485
+            $retstring.='<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled?' disabled':'').'>';
5486
+            for ($min = 0; $min <= 55; $min=$min+5)
5487
+            {
5488
+                $retstring.='<option value="'.$min.'"';
5489
+                if ($minSelected == $min) $retstring.=' selected';
5490
+                $retstring.='>'.$min.'</option>';
5491
+            }
5492
+            $retstring.="</select>";
5493
+        }
5494
+        elseif ($typehour=='text' )
5495
+        {
5496
+            $retstring.='<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '')?((int) $minSelected):'').'">';
5497
+        }
5498
+
5499
+        if ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');
5500
+
5501
+        //$retstring.="&nbsp;";
5502
+
5503
+        if (! empty($nooutput)) return $retstring;
5504
+
5505
+        print $retstring;
5506
+        return;
5507
+    }
5508
+
5509
+
5510
+    /**
5511
+     * Generic method to select a component from a combo list.
5512
+     * This is the generic method that will replace all specific existing methods.
5513
+     *
5514
+     * @param 	string			$objectdesc			Objectclassname:Objectclasspath
5515
+     * @param	string			$htmlname			Name of HTML select component
5516
+     * @param	int				$preselectedvalue	Preselected value (ID of element)
5517
+     * @param	string			$showempty			''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
5518
+     * @param	string			$searchkey			Search criteria
5519
+     * @param	string			$placeholder		Place holder
5520
+     * @param	string			$morecss			More CSS
5521
+     * @param	string			$moreparams			More params provided to ajax call
5522
+     * @param	int				$forcecombo			Force to load all values and output a standard combobox (with no beautification)
5523
+     * @return	string								Return HTML string
5524
+     * @see selectForFormsList select_thirdparty
5525
+     */
5526
+    function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0)
5527
+    {
5528
+        global $conf, $user;
5529
+
5530
+        $objecttmp = null;
5531
+
5532
+        $InfoFieldList = explode(":", $objectdesc);
5533
+        $classname=$InfoFieldList[0];
5534
+        $classpath=$InfoFieldList[1];
5535
+        if (! empty($classpath))
5536
+        {
5537
+            dol_include_once($classpath);
5538
+            if ($classname && class_exists($classname))
5539
+            {
5540
+                $objecttmp = new $classname($this->db);
5541
+            }
5542
+        }
5543
+        if (! is_object($objecttmp))
5544
+        {
5545
+            dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
5546
+            return 'Error bad setup of type for field '.join(',', $InfoFieldList);
5547
+        }
5548
+
5549
+        $prefixforautocompletemode=$objecttmp->element;
5550
+        if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5551
+        $confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5552
+
5553
+        dol_syslog(get_class($this)."::selectForForms", LOG_DEBUG);
5554
+
5555
+        $out='';
5556
+        if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->$confkeyforautocompletemode) && ! $forcecombo)
5557
+        {
5558
+            $objectdesc=$classname.':'.$classpath;
5559
+            $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
5560
+            //if ($objecttmp->element == 'societe') $urlforajaxcall = DOL_URL_ROOT.'/societe/ajax/company.php';
5561
+
5562
+            // No immediate load of all database
5563
+            $urloption='htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams?$moreparams:'');
5564
+            // Activate the auto complete using ajax call.
5565
+            $out.=  ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
5566
+            $out.= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
5567
+            if ($placeholder) $placeholder=' placeholder="'.$placeholder.'"';
5568
+            $out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$preselectedvalue.'"'.$placeholder.' />';
5569
+        }
5570
+        else
5571
+        {
5572
+            // Immediate load of all database
5573
+            $out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);
5574
+        }
5575
+
5576
+        return $out;
5577
+    }
5578
+
5579
+    /**
5580
+     * Output html form to select an object.
5581
+     * Note, this function is called by selectForForms or by ajax selectobject.php
5582
+     *
5583
+     * @param 	Object			$objecttmp			Object
5584
+     * @param	string			$htmlname			Name of HTML select component
5585
+     * @param	int				$preselectedvalue	Preselected value (ID of element)
5586
+     * @param	string			$showempty			''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
5587
+     * @param	string			$searchkey			Search value
5588
+     * @param	string			$placeholder		Place holder
5589
+     * @param	string			$morecss			More CSS
5590
+     * @param	string			$moreparams			More params provided to ajax call
5591
+     * @param	int				$forcecombo			Force to load all values and output a standard combobox (with no beautification)
5592
+     * @param	int				$outputmode			0=HTML select string, 1=Array
5593
+     * @return	string								Return HTML string
5594
+     * @see selectForForms
5595
+     */
5596
+    function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0)
5597
+    {
5598
+        global $conf, $langs, $user;
5599
+
5600
+        $prefixforautocompletemode=$objecttmp->element;
5601
+        if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5602
+        $confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5603
+
5604
+        $fieldstoshow='t.ref';
5605
+        if (! empty($objecttmp->fields))	// For object that declare it, it is better to use declared fields ( like societe, contact, ...)
5606
+        {
5607
+            $tmpfieldstoshow='';
5608
+            foreach($objecttmp->fields as $key => $val)
5609
+            {
5610
+                if ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;
5611
+            }
5612
+            if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
5613
+        }
5614
+
5615
+        $out='';
5616
+        $outarray=array();
5617
+
5618
+        $num=0;
5619
+
5620
+        // Search data
5621
+        $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX .$objecttmp->table_element." as t";
5622
+        if ($objecttmp->ismultientitymanaged == 2)
5623
+            if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
5624
+        $sql.= " WHERE 1=1";
5625
+        if(! empty($objecttmp->ismultientitymanaged)) $sql.= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
5626
+        if ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id))
5627
+        {
5628
+            if ($objecttmp->element == 'societe') $sql.= " AND t.rowid = ".$user->societe_id;
5629
+                else $sql.= " AND t.fk_soc = ".$user->societe_id;
5630
+        }
5631
+        if ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);
5632
+        if ($objecttmp->ismultientitymanaged == 2)
5633
+            if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND t.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
5634
+        $sql.=$this->db->order($fieldstoshow,"ASC");
5635
+        //$sql.=$this->db->plimit($limit, 0);
5636
+
5637
+        // Build output string
5638
+        $resql=$this->db->query($sql);
5639
+        if ($resql)
5640
+        {
5641
+            if (! $forcecombo)
5642
+            {
5643
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5644
+                $out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);
5645
+            }
5646
+
5647
+            // Construct $out and $outarray
5648
+            $out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparams?' '.$moreparams:'').' name="'.$htmlname.'">'."\n";
5649
+
5650
+            // Warning: Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'. Seems it is no more true with selec2 v4
5651
+            $textifempty='&nbsp;';
5652
+
5653
+            //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
5654
+            if (! empty($conf->global->$confkeyforautocompletemode))
5655
+            {
5656
+                if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
5657
+                else $textifempty.=$langs->trans("All");
5658
+            }
5659
+            if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
5660
+
5661
+            $num = $this->db->num_rows($resql);
5662
+            $i = 0;
5663
+            if ($num)
5664
+            {
5665
+                while ($i < $num)
5666
+                {
5667
+                    $obj = $this->db->fetch_object($resql);
5668
+                    $label='';
5669
+                    $tmparray=explode(',', $fieldstoshow);
5670
+                    foreach($tmparray as $key => $val)
5671
+                    {
5672
+                        $val = preg_replace('/t\./','',$val);
5673
+                        $label .= (($label && $obj->$val)?' - ':'').$obj->$val;
5674
+                    }
5675
+                    if (empty($outputmode))
5676
+                    {
5677
+                        if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
5678
+                        {
5679
+                            $out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
5680
+                        }
5681
+                        else
5682
+                        {
5683
+                            $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
5684
+                        }
5685
+                    }
5686
+                    else
5687
+                    {
5688
+                        array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
5689
+                    }
5690
+
5691
+                    $i++;
5692
+                    if (($i % 10) == 0) $out.="\n";
5693
+                }
5694
+            }
5695
+
5696
+            $out.= '</select>'."\n";
5697
+        }
5698
+        else
5699
+        {
5700
+            dol_print_error($this->db);
5701
+        }
5702
+
5703
+        $this->result=array('nbofelement'=>$num);
5704
+
5705
+        if ($outputmode) return $outarray;
5706
+        return $out;
5707
+    }
5015 5708
 
5016 5709
 
5017
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
5018 5710
     /**
5019
-     *  Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
5020
-	 *  Fields are preselected with :
5021
-	 *            	- set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
5022
-	 *            	- local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
5023
-	 *            	- Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
5024
-	 *
5025
-	 *	@param	timestamp	$set_time 		Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
5026
-	 *	@param	string		$prefix			Prefix for fields name
5027
-	 *	@param	int			$h				1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
5028
-	 *	@param	int			$m				1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
5029
-	 *	@param	int			$empty			0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
5030
-	 *	@param	string		$form_name 		Not used
5031
-	 *	@param	int			$d				1=Show days, month, years
5032
-	 * 	@param	int			$addnowlink		Add a link "Now"
5033
-	 * 	@param	int			$nooutput		Do not output html string but return it
5034
-	 * 	@param 	int			$disabled		Disable input fields
5035
-	 *  @param  int			$fullday        When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
5036
-	 *  @param	string		$addplusone		Add a link "+1 hour". Value must be name of another select_date field.
5037
-	 *  @param  datetime    $adddateof      Add a link "Date of invoice" using the following date.
5038
-	 *  @return	string|void					Nothing or string if nooutput is 1
5039
-     *  @deprecated
5040
-	 *  @see    form_date, select_month, select_year, select_dayofweek
5041
-	 */
5042
-    function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5711
+     *	Return a HTML select string, built from an array of key+value.
5712
+     *  Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
5713
+     *
5714
+     *	@param	string			$htmlname			Name of html select area. Must start with "multi" if this is a multiselect
5715
+     *	@param	array			$array				Array (key => value)
5716
+     *	@param	string|string[]	$id					Preselected key or preselected keys for multiselect
5717
+     *	@param	int|string		$show_empty			0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.
5718
+     *	@param	int				$key_in_label		1 to show key into label with format "[key] value"
5719
+     *	@param	int				$value_as_key		1 to use value as key
5720
+     *	@param  string			$moreparam			Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
5721
+     *	@param  int				$translate			1=Translate and encode value
5722
+     * 	@param	int				$maxlen				Length maximum for labels
5723
+     * 	@param	int				$disabled			Html select box is disabled
5724
+     *  @param	string			$sort				'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
5725
+     *  @param	string			$morecss			Add more class to css styles
5726
+     *  @param	int				$addjscombo			Add js combo
5727
+     *  @param  string          $moreparamonempty	Add more param on the empty option line. Not used if show_empty not set
5728
+     *  @param  int             $disablebademail	Check if an email is found into value and if not disable and colorize entry
5729
+     *  @param  int             $nohtmlescape		No html escaping.
5730
+     * 	@return	string								HTML select string.
5731
+     *  @see multiselectarray
5732
+     */
5733
+    static function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='', $addjscombo=0, $moreparamonempty='',$disablebademail=0, $nohtmlescape=0)
5043 5734
     {
5044
-        // phpcs:enable
5045
-        $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
5046
-        if (! empty($nooutput)) {
5047
-            return $retstring;
5735
+        global $conf, $langs;
5736
+
5737
+        // Do we want a multiselect ?
5738
+        //$jsbeautify = 0;
5739
+        //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
5740
+        $jsbeautify = 1;
5741
+
5742
+        if ($value_as_key) $array=array_combine($array, $array);
5743
+
5744
+        $out='';
5745
+
5746
+        // Add code for jquery to use multiselect
5747
+        if ($addjscombo && $jsbeautify)
5748
+        {
5749
+            $minLengthToAutocomplete=0;
5750
+            $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
5751
+
5752
+            // Enhance with select2
5753
+            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5754
+            $out .= ajax_combobox($htmlname);
5048 5755
         }
5049
-        print $retstring;
5050
-        return;
5051
-    }
5052 5756
 
5053
-    /**
5054
-     *  Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
5055
-	 *  Fields are preselected with :
5056
-	 *              - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
5057
-	 *              - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
5058
-	 *              - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
5059
-	 *
5060
-	 *  @param  timestamp   $set_time       Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
5061
-	 *  @param	string		$prefix			Prefix for fields name
5062
-	 *  @param	int			$h				1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
5063
-	 *	@param	int			$m				1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
5064
-	 *	@param	int			$empty			0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
5065
-	 *	@param	string		$form_name 		Not used
5066
-	 *	@param	int			$d				1=Show days, month, years
5067
-	 * 	@param	int			$addnowlink		Add a link "Now"
5068
-	 * 	@param 	int			$disabled		Disable input fields
5069
-	 *  @param  int			$fullday        When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
5070
-	 *  @param	string		$addplusone		Add a link "+1 hour". Value must be name of another selectDate field.
5071
-	 *  @param  datetime    $adddateof      Add a link "Date of invoice" using the following date.
5072
-	 * 	@return string                      Html for selectDate
5073
-	 *  @see    form_date, select_month, select_year, select_dayofweek
5074
-	 */
5075
-	function selectDate($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5076
-	{
5077
-		global $conf,$langs;
5078
-
5079
-		$retstring='';
5080
-
5081
-		if ($prefix=='') $prefix='re';
5082
-		if ($h == '') $h=0;
5083
-		if ($m == '') $m=0;
5084
-		$emptydate=0;
5085
-		$emptyhours=0;
5086
-		if ($empty == 1) { $emptydate=1; $emptyhours=1; }
5087
-		if ($empty == 2) { $emptydate=0; $emptyhours=1; }
5088
-		$orig_set_time=$set_time;
5089
-
5090
-		if ($set_time === '' && $emptydate == 0)
5091
-		{
5092
-			include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5093
-			$set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone
5094
-		}
5095
-
5096
-		// Analysis of the pre-selection date
5097
-		if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))	// deprecated usage
5098
-		{
5099
-			// Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
5100
-			$syear	= (! empty($reg[1])?$reg[1]:'');
5101
-			$smonth	= (! empty($reg[2])?$reg[2]:'');
5102
-			$sday	= (! empty($reg[3])?$reg[3]:'');
5103
-			$shour	= (! empty($reg[4])?$reg[4]:'');
5104
-			$smin	= (! empty($reg[5])?$reg[5]:'');
5105
-		}
5106
-		elseif (strval($set_time) != '' && $set_time != -1)
5107
-		{
5108
-			// set_time est un timestamps (0 possible)
5109
-			$syear = dol_print_date($set_time, "%Y");
5110
-			$smonth = dol_print_date($set_time, "%m");
5111
-			$sday = dol_print_date($set_time, "%d");
5112
-			if ($orig_set_time != '')
5113
-			{
5114
-				$shour = dol_print_date($set_time, "%H");
5115
-				$smin = dol_print_date($set_time, "%M");
5116
-				$ssec = dol_print_date($set_time, "%S");
5117
-			}
5118
-			else
5119
-			{
5120
-				$shour = '';
5121
-				$smin = '';
5122
-				$ssec = '';
5123
-			}
5124
-		}
5125
-		else
5126
-		{
5127
-			// Date est '' ou vaut -1
5128
-			$syear = '';
5129
-			$smonth = '';
5130
-			$sday = '';
5131
-			$shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
5132
-			$smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
5133
-			$ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
5134
-		}
5135
-		if ($h == 3) $shour = '';
5136
-		if ($m == 3) $smin = '';
5137
-
5138
-		// You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
5139
-		$usecalendar='combo';
5140
-		if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
5141
-			$usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR);
5142
-		}
5143
-
5144
-		if ($d)
5145
-		{
5146
-			// Show date with popup
5147
-			if ($usecalendar != 'combo')
5148
-			{
5149
-				$formated_date='';
5150
-				//print "e".$set_time." t ".$conf->format_date_short;
5151
-				if (strval($set_time) != '' && $set_time != -1)
5152
-				{
5153
-					//$formated_date=dol_print_date($set_time,$conf->format_date_short);
5154
-					$formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput"));  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5155
-				}
5156
-
5157
-				// Calendrier popup version eldy
5158
-				if ($usecalendar == "eldy")
5159
-				{
5160
-					// Zone de saisie manuelle de la date
5161
-					$retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5162
-					$retstring.=($disabled?' disabled':'');
5163
-					$retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5164
-					$retstring.='>';
5165
-
5166
-					// Icone calendrier
5167
-					if (! $disabled)
5168
-					{
5169
-						$retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
5170
-						$base=DOL_URL_ROOT.'/core/';
5171
-						$retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
5172
-						$retstring.='>'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
5173
-					}
5174
-					else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5175
-
5176
-					$retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5177
-					$retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5178
-					$retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5179
-				}
5180
-				elseif ($usecalendar == 'jquery')
5181
-				{
5182
-					if (! $disabled)
5183
-					{
5184
-						// Output javascript for datepicker
5185
-						$retstring.="<script type='text/javascript'>";
5186
-						$retstring.="$(function(){ $('#".$prefix."').datepicker({
5187
-							dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
5188
-							autoclose: true,
5189
-							todayHighlight: true,";
5190
-							if (! empty($conf->dol_use_jmobile))
5191
-							{
5192
-								$retstring.="
5193
-								beforeShow: function (input, datePicker) {
5194
-									input.disabled = true;
5195
-								},
5196
-								onClose: function (dateText, datePicker) {
5197
-									this.disabled = false;
5198
-								},
5199
-								";
5200
-							}
5201
-							// Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
5202
-							if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))
5203
-							{
5204
-							$retstring.="
5205
-								showOn: 'button',
5206
-								buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
5207
-								buttonImageOnly: true";
5208
-							}
5209
-							$retstring.="
5210
-							}) });";
5211
-						$retstring.="</script>";
5212
-					}
5757
+        $out.='<select id="'.preg_replace('/^\./','',$htmlname).'" '.($disabled?'disabled ':'').'class="flat '.(preg_replace('/^\./','',$htmlname)).($morecss?' '.$morecss:'').'"';
5758
+        $out.=' name="'.preg_replace('/^\./','',$htmlname).'" '.($moreparam?$moreparam:'');
5759
+        $out.='>';
5213 5760
 
5214
-					// Zone de saisie manuelle de la date
5215
-					$retstring.='<div class="nowrap inline-block">';
5216
-					$retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5217
-					$retstring.=($disabled?' disabled':'');
5218
-					$retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5219
-					$retstring.='>';
5220
-
5221
-					// Icone calendrier
5222
-					if (! $disabled)
5223
-					{
5224
-						/* Not required. Managed by option buttonImage of jquery
5225
-                		$retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
5226
-                		$retstring.="<script type='text/javascript'>";
5227
-                		$retstring.="jQuery(document).ready(function() {";
5228
-                		$retstring.='	jQuery("#'.$prefix.'id").click(function() {';
5229
-                		$retstring.="    	jQuery('#".$prefix."').focus();";
5230
-                		$retstring.='    });';
5231
-                		$retstring.='});';
5232
-                		$retstring.="</script>";*/
5233
-					}
5234
-					else
5235
-					{
5236
-						$retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5237
-					}
5761
+        if ($show_empty)
5762
+        {
5763
+            $textforempty=' ';
5764
+            if (! empty($conf->use_javascript_ajax)) $textforempty='&nbsp;';	// If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
5765
+            if (! is_numeric($show_empty)) $textforempty=$show_empty;
5766
+            $out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
5767
+        }
5238 5768
 
5239
-					$retstring.='</div>';
5240
-					$retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5241
-					$retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5242
-					$retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5243
-				}
5244
-				else
5245
-				{
5246
-					$retstring.="Bad value of MAIN_POPUP_CALENDAR";
5247
-				}
5248
-			}
5249
-			// Show date with combo selects
5250
-			else
5251
-			{
5252
-				//$retstring.='<div class="inline-block">';
5253
-				// Day
5254
-				$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
5255
-
5256
-				if ($emptydate || $set_time == -1)
5257
-				{
5258
-					$retstring.='<option value="0" selected>&nbsp;</option>';
5259
-				}
5260
-
5261
-				for ($day = 1 ; $day <= 31; $day++)
5262
-				{
5263
-					$retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
5264
-				}
5265
-
5266
-				$retstring.="</select>";
5267
-
5268
-				$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
5269
-				if ($emptydate || $set_time == -1)
5270
-				{
5271
-					$retstring.='<option value="0" selected>&nbsp;</option>';
5272
-				}
5273
-
5274
-				// Month
5275
-				for ($month = 1 ; $month <= 12 ; $month++)
5276
-				{
5277
-					$retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
5278
-					$retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
5279
-					$retstring.="</option>";
5280
-				}
5281
-				$retstring.="</select>";
5282
-
5283
-				// Year
5284
-				if ($emptydate || $set_time == -1)
5285
-				{
5286
-					$retstring.='<input'.($disabled?' disabled':'').' placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" class="flat maxwidth50imp valignmiddle" type="number" min="0" max="3000" maxlength="4" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">';
5287
-				}
5288
-				else
5289
-				{
5290
-					$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
5291
-
5292
-					for ($year = $syear - 10; $year < $syear + 10 ; $year++)
5293
-					{
5294
-						$retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
5295
-					}
5296
-					$retstring.="</select>\n";
5297
-				}
5298
-				//$retstring.='</div>';
5299
-			}
5300
-		}
5301
-
5302
-		if ($d && $h) $retstring.=($h==2?'<br>':' ');
5303
-
5304
-		if ($h)
5305
-		{
5306
-			// Show hour
5307
-			$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
5308
-			if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5309
-			for ($hour = 0; $hour < 24; $hour++)
5310
-			{
5311
-				if (strlen($hour) < 2) $hour = "0" . $hour;
5312
-				$retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
5313
-			}
5314
-			$retstring.='</select>';
5315
-			if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
5316
-		}
5317
-
5318
-		if ($m)
5319
-		{
5320
-			// Show minutes
5321
-			$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
5322
-			if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5323
-			for ($min = 0; $min < 60 ; $min++)
5324
-			{
5325
-				if (strlen($min) < 2) $min = "0" . $min;
5326
-				$retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
5327
-			}
5328
-			$retstring.='</select>';
5329
-
5330
-			$retstring.='<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
5331
-		}
5332
-
5333
-		// Add a "Now" link
5334
-		if ($conf->use_javascript_ajax && $addnowlink)
5335
-		{
5336
-			// Script which will be inserted in the onClick of the "Now" link
5337
-			$reset_scripts = "";
5338
-
5339
-			// Generate the date part, depending on the use or not of the javascript calendar
5340
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5341
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5342
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5343
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5344
-			/*if ($usecalendar == "eldy")
5769
+        if (is_array($array))
5770
+        {
5771
+            // Translate
5772
+            if ($translate)
5345 5773
             {
5346
-                $base=DOL_URL_ROOT.'/core/';
5347
-                $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
5774
+                foreach($array as $key => $value)
5775
+                {
5776
+                    $array[$key]=$langs->trans($value);
5777
+                }
5348 5778
             }
5349
-            else
5779
+
5780
+            // Sort
5781
+            if ($sort == 'ASC') asort($array);
5782
+            elseif ($sort == 'DESC') arsort($array);
5783
+
5784
+            foreach($array as $key => $value)
5350 5785
             {
5351
-                $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
5352
-                $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
5353
-                $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
5354
-            }*/
5355
-			// Update the hour part
5356
-			if ($h)
5357
-			{
5358
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5359
-				//$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
5360
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5361
-				if ($fullday) $reset_scripts .= ' } ';
5362
-			}
5363
-			// Update the minute part
5364
-			if ($m)
5365
-			{
5366
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5367
-				//$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
5368
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5369
-				if ($fullday) $reset_scripts .= ' } ';
5370
-			}
5371
-			// If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5372
-			if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5373
-			{
5374
-				$retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
5375
-				$retstring.=$langs->trans("Now");
5376
-				$retstring.='</button> ';
5377
-			}
5378
-		}
5379
-
5380
-		// Add a "Plus one hour" link
5381
-		if ($conf->use_javascript_ajax && $addplusone)
5382
-		{
5383
-			// Script which will be inserted in the onClick of the "Add plusone" link
5384
-			$reset_scripts = "";
5385
-
5386
-			// Generate the date part, depending on the use or not of the javascript calendar
5387
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5388
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5389
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5390
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5391
-			// Update the hour part
5392
-			if ($h)
5393
-			{
5394
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5395
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5396
-				if ($fullday) $reset_scripts .= ' } ';
5397
-			}
5398
-			// Update the minute part
5399
-			if ($m)
5400
-			{
5401
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5402
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5403
-				if ($fullday) $reset_scripts .= ' } ';
5404
-			}
5405
-			// If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5406
-			if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5407
-			{
5408
-				$retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
5409
-				$retstring.=$langs->trans("DateStartPlusOne");
5410
-				$retstring.='</button> ';
5411
-			}
5412
-		}
5413
-
5414
-		// Add a "Plus one hour" link
5415
-		if ($conf->use_javascript_ajax && $adddateof)
5416
-		{
5417
-			$tmparray=dol_getdate($adddateof);
5418
-			$retstring.=' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof,'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$langs->trans("DateInvoice").'</a>';
5419
-		}
5420
-
5421
-		return $retstring;
5422
-	}
5786
+                $disabled=''; $style='';
5787
+                if (! empty($disablebademail))
5788
+                {
5789
+                    if (! preg_match('/&lt;.+@.+&gt;/', $value))
5790
+                    {
5791
+                        //$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);
5792
+                        $disabled=' disabled';
5793
+                        $style=' class="warning"';
5794
+                    }
5795
+                }
5423 5796
 
5424
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
5425
-	/**
5426
-	 *	Function to show a form to select a duration on a page
5427
-	 *
5428
-	 *	@param	string	$prefix   		Prefix for input fields
5429
-	 *	@param  int	$iSecond  		    Default preselected duration (number of seconds or '')
5430
-	 * 	@param	int	$disabled           Disable the combo box
5431
-	 * 	@param	string	$typehour		If 'select' then input hour and input min is a combo,
5432
-	 *						            if 'text' input hour is in text and input min is a text,
5433
-	 *						            if 'textselect' input hour is in text and input min is a combo
5434
-	 *  @param	integer	$minunderhours	If 1, show minutes selection under the hours
5435
-	 * 	@param	int	$nooutput		    Do not output html string but return it
5436
-	 *  @return	string|void
5437
-	 */
5438
-	function select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)
5439
-	{
5440
-        // phpcs:enable
5441
-		global $langs;
5442
-
5443
-		$retstring='';
5444
-
5445
-		$hourSelected=0; $minSelected=0;
5446
-
5447
-		// Hours
5448
-		if ($iSecond != '')
5449
-		{
5450
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5451
-
5452
-			$hourSelected = convertSecondToTime($iSecond,'allhour');
5453
-			$minSelected = convertSecondToTime($iSecond,'min');
5454
-		}
5455
-
5456
-		if ($typehour=='select' )
5457
-		{
5458
-			$retstring.='<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
5459
-			for ($hour = 0; $hour < 25; $hour++)	// For a duration, we allow 24 hours
5460
-			{
5461
-				$retstring.='<option value="'.$hour.'"';
5462
-				if ($hourSelected == $hour)
5463
-				{
5464
-					$retstring.=" selected";
5465
-				}
5466
-				$retstring.=">".$hour."</option>";
5467
-			}
5468
-			$retstring.="</select>";
5469
-		}
5470
-		elseif ($typehour=='text' || $typehour=='textselect')
5471
-		{
5472
-			$retstring.='<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '')?((int) $hourSelected):'').'">';
5473
-		}
5474
-		else return 'BadValueForParameterTypeHour';
5475
-
5476
-		if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');
5477
-		else $retstring.='<span class="hideonsmartphone">:</span>';
5478
-
5479
-		// Minutes
5480
-		if ($minunderhours) $retstring.='<br>';
5481
-		else $retstring.='<span class="hideonsmartphone">&nbsp;</span>';
5482
-
5483
-		if ($typehour=='select' || $typehour=='textselect')
5484
-		{
5485
-			$retstring.='<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled?' disabled':'').'>';
5486
-			for ($min = 0; $min <= 55; $min=$min+5)
5487
-			{
5488
-				$retstring.='<option value="'.$min.'"';
5489
-				if ($minSelected == $min) $retstring.=' selected';
5490
-				$retstring.='>'.$min.'</option>';
5491
-			}
5492
-			$retstring.="</select>";
5493
-		}
5494
-		elseif ($typehour=='text' )
5495
-		{
5496
-			$retstring.='<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '')?((int) $minSelected):'').'">';
5497
-		}
5498
-
5499
-		if ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');
5500
-
5501
-		//$retstring.="&nbsp;";
5502
-
5503
-		if (! empty($nooutput)) return $retstring;
5504
-
5505
-		print $retstring;
5506
-		return;
5507
-	}
5508
-
5509
-
5510
-	/**
5511
-	 * Generic method to select a component from a combo list.
5512
-	 * This is the generic method that will replace all specific existing methods.
5513
-	 *
5514
-	 * @param 	string			$objectdesc			Objectclassname:Objectclasspath
5515
-	 * @param	string			$htmlname			Name of HTML select component
5516
-	 * @param	int				$preselectedvalue	Preselected value (ID of element)
5517
-	 * @param	string			$showempty			''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
5518
-	 * @param	string			$searchkey			Search criteria
5519
-	 * @param	string			$placeholder		Place holder
5520
-	 * @param	string			$morecss			More CSS
5521
-	 * @param	string			$moreparams			More params provided to ajax call
5522
-	 * @param	int				$forcecombo			Force to load all values and output a standard combobox (with no beautification)
5523
-	 * @return	string								Return HTML string
5524
-	 * @see selectForFormsList select_thirdparty
5525
-	 */
5526
-	function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0)
5527
-	{
5528
-		global $conf, $user;
5529
-
5530
-		$objecttmp = null;
5531
-
5532
-		$InfoFieldList = explode(":", $objectdesc);
5533
-		$classname=$InfoFieldList[0];
5534
-		$classpath=$InfoFieldList[1];
5535
-		if (! empty($classpath))
5536
-		{
5537
-			dol_include_once($classpath);
5538
-			if ($classname && class_exists($classname))
5539
-			{
5540
-				$objecttmp = new $classname($this->db);
5541
-			}
5542
-		}
5543
-		if (! is_object($objecttmp))
5544
-		{
5545
-			dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
5546
-			return 'Error bad setup of type for field '.join(',', $InfoFieldList);
5547
-		}
5548
-
5549
-		$prefixforautocompletemode=$objecttmp->element;
5550
-		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5551
-		$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5552
-
5553
-		dol_syslog(get_class($this)."::selectForForms", LOG_DEBUG);
5554
-
5555
-		$out='';
5556
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->$confkeyforautocompletemode) && ! $forcecombo)
5557
-		{
5558
-			$objectdesc=$classname.':'.$classpath;
5559
-			$urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
5560
-			//if ($objecttmp->element == 'societe') $urlforajaxcall = DOL_URL_ROOT.'/societe/ajax/company.php';
5561
-
5562
-			// No immediate load of all database
5563
-			$urloption='htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams?$moreparams:'');
5564
-			// Activate the auto complete using ajax call.
5565
-			$out.=  ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
5566
-			$out.= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
5567
-			if ($placeholder) $placeholder=' placeholder="'.$placeholder.'"';
5568
-			$out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$preselectedvalue.'"'.$placeholder.' />';
5569
-		}
5570
-		else
5571
-		{
5572
-			// Immediate load of all database
5573
-			$out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);
5574
-		}
5575
-
5576
-		return $out;
5577
-	}
5578
-
5579
-	/**
5580
-	 * Output html form to select an object.
5581
-	 * Note, this function is called by selectForForms or by ajax selectobject.php
5582
-	 *
5583
-	 * @param 	Object			$objecttmp			Object
5584
-	 * @param	string			$htmlname			Name of HTML select component
5585
-	 * @param	int				$preselectedvalue	Preselected value (ID of element)
5586
-	 * @param	string			$showempty			''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
5587
-	 * @param	string			$searchkey			Search value
5588
-	 * @param	string			$placeholder		Place holder
5589
-	 * @param	string			$morecss			More CSS
5590
-	 * @param	string			$moreparams			More params provided to ajax call
5591
-	 * @param	int				$forcecombo			Force to load all values and output a standard combobox (with no beautification)
5592
-	 * @param	int				$outputmode			0=HTML select string, 1=Array
5593
-	 * @return	string								Return HTML string
5594
-	 * @see selectForForms
5595
-	 */
5596
-	function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0)
5597
-	{
5598
-		global $conf, $langs, $user;
5599
-
5600
-		$prefixforautocompletemode=$objecttmp->element;
5601
-		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5602
-		$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5603
-
5604
-		$fieldstoshow='t.ref';
5605
-		if (! empty($objecttmp->fields))	// For object that declare it, it is better to use declared fields ( like societe, contact, ...)
5606
-		{
5607
-			$tmpfieldstoshow='';
5608
-			foreach($objecttmp->fields as $key => $val)
5609
-			{
5610
-				if ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;
5611
-			}
5612
-			if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
5613
-		}
5614
-
5615
-		$out='';
5616
-		$outarray=array();
5617
-
5618
-		$num=0;
5619
-
5620
-		// Search data
5621
-		$sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX .$objecttmp->table_element." as t";
5622
-		if ($objecttmp->ismultientitymanaged == 2)
5623
-			if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
5624
-		$sql.= " WHERE 1=1";
5625
-		if(! empty($objecttmp->ismultientitymanaged)) $sql.= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
5626
-		if ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id))
5627
-		{
5628
-			if ($objecttmp->element == 'societe') $sql.= " AND t.rowid = ".$user->societe_id;
5629
-				else $sql.= " AND t.fk_soc = ".$user->societe_id;
5630
-		}
5631
-		if ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);
5632
-		if ($objecttmp->ismultientitymanaged == 2)
5633
-			if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND t.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
5634
-		$sql.=$this->db->order($fieldstoshow,"ASC");
5635
-		//$sql.=$this->db->plimit($limit, 0);
5636
-
5637
-		// Build output string
5638
-		$resql=$this->db->query($sql);
5639
-		if ($resql)
5640
-		{
5641
-			if (! $forcecombo)
5642
-			{
5643
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5644
-				$out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);
5645
-			}
5646
-
5647
-			// Construct $out and $outarray
5648
-			$out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparams?' '.$moreparams:'').' name="'.$htmlname.'">'."\n";
5649
-
5650
-			// Warning: Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'. Seems it is no more true with selec2 v4
5651
-			$textifempty='&nbsp;';
5652
-
5653
-			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
5654
-			if (! empty($conf->global->$confkeyforautocompletemode))
5655
-			{
5656
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
5657
-				else $textifempty.=$langs->trans("All");
5658
-			}
5659
-			if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
5660
-
5661
-			$num = $this->db->num_rows($resql);
5662
-			$i = 0;
5663
-			if ($num)
5664
-			{
5665
-				while ($i < $num)
5666
-				{
5667
-					$obj = $this->db->fetch_object($resql);
5668
-					$label='';
5669
-					$tmparray=explode(',', $fieldstoshow);
5670
-					foreach($tmparray as $key => $val)
5671
-					{
5672
-						$val = preg_replace('/t\./','',$val);
5673
-						$label .= (($label && $obj->$val)?' - ':'').$obj->$val;
5674
-					}
5675
-					if (empty($outputmode))
5676
-					{
5677
-						if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
5678
-						{
5679
-							$out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
5680
-						}
5681
-						else
5682
-						{
5683
-							$out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
5684
-						}
5685
-					}
5686
-					else
5687
-					{
5688
-						array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
5689
-					}
5797
+                if ($key_in_label)
5798
+                {
5799
+                    if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
5800
+                    else $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
5801
+                }
5802
+                else
5803
+                {
5804
+                    if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
5805
+                    else $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
5806
+                    if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
5807
+                }
5690 5808
 
5691
-					$i++;
5692
-					if (($i % 10) == 0) $out.="\n";
5693
-				}
5694
-			}
5695
-
5696
-			$out.= '</select>'."\n";
5697
-		}
5698
-		else
5699
-		{
5700
-			dol_print_error($this->db);
5701
-		}
5702
-
5703
-		$this->result=array('nbofelement'=>$num);
5704
-
5705
-		if ($outputmode) return $outarray;
5706
-		return $out;
5707
-	}
5708
-
5709
-
5710
-	/**
5711
-	 *	Return a HTML select string, built from an array of key+value.
5712
-	 *  Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
5713
-	 *
5714
-	 *	@param	string			$htmlname			Name of html select area. Must start with "multi" if this is a multiselect
5715
-	 *	@param	array			$array				Array (key => value)
5716
-	 *	@param	string|string[]	$id					Preselected key or preselected keys for multiselect
5717
-	 *	@param	int|string		$show_empty			0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.
5718
-	 *	@param	int				$key_in_label		1 to show key into label with format "[key] value"
5719
-	 *	@param	int				$value_as_key		1 to use value as key
5720
-	 *	@param  string			$moreparam			Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
5721
-	 *	@param  int				$translate			1=Translate and encode value
5722
-	 * 	@param	int				$maxlen				Length maximum for labels
5723
-	 * 	@param	int				$disabled			Html select box is disabled
5724
-	 *  @param	string			$sort				'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
5725
-	 *  @param	string			$morecss			Add more class to css styles
5726
-	 *  @param	int				$addjscombo			Add js combo
5727
-	 *  @param  string          $moreparamonempty	Add more param on the empty option line. Not used if show_empty not set
5728
-	 *  @param  int             $disablebademail	Check if an email is found into value and if not disable and colorize entry
5729
-	 *  @param  int             $nohtmlescape		No html escaping.
5730
-	 * 	@return	string								HTML select string.
5731
-	 *  @see multiselectarray
5732
-	 */
5733
-	static function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='', $addjscombo=0, $moreparamonempty='',$disablebademail=0, $nohtmlescape=0)
5734
-	{
5735
-		global $conf, $langs;
5736
-
5737
-		// Do we want a multiselect ?
5738
-		//$jsbeautify = 0;
5739
-		//if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
5740
-		$jsbeautify = 1;
5741
-
5742
-		if ($value_as_key) $array=array_combine($array, $array);
5743
-
5744
-		$out='';
5745
-
5746
-		// Add code for jquery to use multiselect
5747
-		if ($addjscombo && $jsbeautify)
5748
-		{
5749
-			$minLengthToAutocomplete=0;
5750
-			$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
5751
-
5752
-			// Enhance with select2
5753
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5754
-			$out .= ajax_combobox($htmlname);
5755
-		}
5756
-
5757
-		$out.='<select id="'.preg_replace('/^\./','',$htmlname).'" '.($disabled?'disabled ':'').'class="flat '.(preg_replace('/^\./','',$htmlname)).($morecss?' '.$morecss:'').'"';
5758
-		$out.=' name="'.preg_replace('/^\./','',$htmlname).'" '.($moreparam?$moreparam:'');
5759
-		$out.='>';
5760
-
5761
-		if ($show_empty)
5762
-		{
5763
-			$textforempty=' ';
5764
-			if (! empty($conf->use_javascript_ajax)) $textforempty='&nbsp;';	// If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
5765
-			if (! is_numeric($show_empty)) $textforempty=$show_empty;
5766
-			$out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
5767
-		}
5768
-
5769
-		if (is_array($array))
5770
-		{
5771
-			// Translate
5772
-			if ($translate)
5773
-			{
5774
-				foreach($array as $key => $value)
5775
-				{
5776
-					$array[$key]=$langs->trans($value);
5777
-				}
5778
-			}
5779
-
5780
-			// Sort
5781
-			if ($sort == 'ASC') asort($array);
5782
-			elseif ($sort == 'DESC') arsort($array);
5783
-
5784
-			foreach($array as $key => $value)
5785
-			{
5786
-				$disabled=''; $style='';
5787
-				if (! empty($disablebademail))
5788
-				{
5789
-					if (! preg_match('/&lt;.+@.+&gt;/', $value))
5790
-					{
5791
-						//$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);
5792
-						$disabled=' disabled';
5793
-						$style=' class="warning"';
5794
-					}
5795
-				}
5796
-
5797
-				if ($key_in_label)
5798
-				{
5799
-					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
5800
-					else $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
5801
-				}
5802
-				else
5803
-				{
5804
-					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
5805
-					else $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
5806
-					if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
5807
-				}
5808
-
5809
-				$out.='<option value="'.$key.'"';
5810
-				$out.=$style.$disabled;
5811
-				if ($id != '' && $id == $key && ! $disabled) $out.=' selected';		// To preselect a value
5812
-				if ($nohtmlescape) $out.=' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
5813
-				$out.='>';
5814
-				//var_dump($selectOptionValue);
5815
-				$out.=$selectOptionValue;
5816
-				$out.="</option>\n";
5817
-			}
5818
-		}
5819
-
5820
-		$out.="</select>";
5821
-		return $out;
5822
-	}
5823
-
5824
-
5825
-	/**
5826
-	 *	Return a HTML select string, built from an array of key+value, but content returned into select come from an Ajax call of an URL.
5827
-	 *  Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
5828
-	 *
5829
-	 *	@param	string	$htmlname       		Name of html select area
5830
-	 *	@param	string	$url					Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
5831
-	 *	@param	string	$id             		Preselected key
5832
-	 *	@param  string	$moreparam      		Add more parameters onto the select tag
5833
-	 *	@param  string	$moreparamtourl 		Add more parameters onto the Ajax called URL
5834
-	 * 	@param	int		$disabled				Html select box is disabled
5835
-	 *  @param	int		$minimumInputLength		Minimum Input Length
5836
-	 *  @param	string	$morecss				Add more class to css styles
5837
-	 *  @param  int     $callurlonselect        If set to 1, some code is added so an url return by the ajax is called when value is selected.
5838
-	 *  @param  string  $placeholder            String to use as placeholder
5839
-	 *  @param  integer $acceptdelayedhtml      1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
5840
-	 * 	@return	string   						HTML select string
5841
-	 *  @see selectArrayFilter, ajax_combobox in ajax.lib.php
5842
-	 */
5843
-	static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5844
-	{
5845
-		global $conf, $langs;
5846
-		global $delayedhtmlcontent;
5847
-
5848
-		// TODO Use an internal dolibarr component instead of select2
5849
-		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5850
-
5851
-		$out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"></select>';
5852
-
5853
-		$tmpplugin='select2';
5854
-		$outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5809
+                $out.='<option value="'.$key.'"';
5810
+                $out.=$style.$disabled;
5811
+                if ($id != '' && $id == $key && ! $disabled) $out.=' selected';		// To preselect a value
5812
+                if ($nohtmlescape) $out.=' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
5813
+                $out.='>';
5814
+                //var_dump($selectOptionValue);
5815
+                $out.=$selectOptionValue;
5816
+                $out.="</option>\n";
5817
+            }
5818
+        }
5819
+
5820
+        $out.="</select>";
5821
+        return $out;
5822
+    }
5823
+
5824
+
5825
+    /**
5826
+     *	Return a HTML select string, built from an array of key+value, but content returned into select come from an Ajax call of an URL.
5827
+     *  Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
5828
+     *
5829
+     *	@param	string	$htmlname       		Name of html select area
5830
+     *	@param	string	$url					Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
5831
+     *	@param	string	$id             		Preselected key
5832
+     *	@param  string	$moreparam      		Add more parameters onto the select tag
5833
+     *	@param  string	$moreparamtourl 		Add more parameters onto the Ajax called URL
5834
+     * 	@param	int		$disabled				Html select box is disabled
5835
+     *  @param	int		$minimumInputLength		Minimum Input Length
5836
+     *  @param	string	$morecss				Add more class to css styles
5837
+     *  @param  int     $callurlonselect        If set to 1, some code is added so an url return by the ajax is called when value is selected.
5838
+     *  @param  string  $placeholder            String to use as placeholder
5839
+     *  @param  integer $acceptdelayedhtml      1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
5840
+     * 	@return	string   						HTML select string
5841
+     *  @see selectArrayFilter, ajax_combobox in ajax.lib.php
5842
+     */
5843
+    static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5844
+    {
5845
+        global $conf, $langs;
5846
+        global $delayedhtmlcontent;
5847
+
5848
+        // TODO Use an internal dolibarr component instead of select2
5849
+        if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5850
+
5851
+        $out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"></select>';
5852
+
5853
+        $tmpplugin='select2';
5854
+        $outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5855 5855
 	    	<script type="text/javascript">
5856 5856
 	    	$(document).ready(function () {
5857 5857
 
@@ -5913,57 +5913,57 @@  discard block
 block discarded – undo
5913 5913
     	   });
5914 5914
 	       </script>';
5915 5915
 
5916
-		if ($acceptdelayedhtml)
5917
-		{
5918
-			$delayedhtmlcontent.=$outdelayed;
5919
-		}
5920
-		else
5921
-		{
5922
-			$out.=$outdelayed;
5923
-		}
5924
-		return $out;
5925
-	}
5926
-
5927
-	/**
5928
-	 *	Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
5929
-	 *  Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
5930
-	 *
5931
-	 *	@param	string	$htmlname       		Name of html select area
5932
-	 *	@param	string	$array					Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
5933
-	 *	@param	string	$id             		Preselected key
5934
-	 *	@param  string	$moreparam      		Add more parameters onto the select tag
5935
-	 *	@param	int		$disableFiltering		If set to 1, results are not filtered with searched string
5936
-	 * 	@param	int		$disabled				Html select box is disabled
5937
-	 *  @param	int		$minimumInputLength		Minimum Input Length
5938
-	 *  @param	string	$morecss				Add more class to css styles
5939
-	 *  @param  int     $callurlonselect        If set to 1, some code is added so an url return by the ajax is called when value is selected.
5940
-	 *  @param  string  $placeholder            String to use as placeholder
5941
-	 *  @param  integer $acceptdelayedhtml      1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
5942
-	 * 	@return	string   						HTML select string
5943
-	 *  @see selectArrayAjax, ajax_combobox in ajax.lib.php
5944
-	 */
5945
-	static function selectArrayFilter($htmlname, $array, $id='', $moreparam='', $disableFiltering=0, $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5946
-	{
5947
-		global $conf, $langs;
5948
-		global $delayedhtmlcontent;
5949
-
5950
-		// TODO Use an internal dolibarr component instead of select2
5951
-		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5952
-
5953
-		$out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"><option></option></select>';
5954
-
5955
-		$formattedarrayresult = array();
5956
-
5957
-		foreach($array as $key => $value) {
5958
-			$o = new stdClass();
5959
-			$o->id = $key;
5960
-			$o->text = $value['text'];
5961
-			$o->url = $value['url'];
5962
-			$formattedarrayresult[] = $o;
5963
-		}
5964
-
5965
-		$tmpplugin='select2';
5966
-		$outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5916
+        if ($acceptdelayedhtml)
5917
+        {
5918
+            $delayedhtmlcontent.=$outdelayed;
5919
+        }
5920
+        else
5921
+        {
5922
+            $out.=$outdelayed;
5923
+        }
5924
+        return $out;
5925
+    }
5926
+
5927
+    /**
5928
+     *	Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
5929
+     *  Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
5930
+     *
5931
+     *	@param	string	$htmlname       		Name of html select area
5932
+     *	@param	string	$array					Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
5933
+     *	@param	string	$id             		Preselected key
5934
+     *	@param  string	$moreparam      		Add more parameters onto the select tag
5935
+     *	@param	int		$disableFiltering		If set to 1, results are not filtered with searched string
5936
+     * 	@param	int		$disabled				Html select box is disabled
5937
+     *  @param	int		$minimumInputLength		Minimum Input Length
5938
+     *  @param	string	$morecss				Add more class to css styles
5939
+     *  @param  int     $callurlonselect        If set to 1, some code is added so an url return by the ajax is called when value is selected.
5940
+     *  @param  string  $placeholder            String to use as placeholder
5941
+     *  @param  integer $acceptdelayedhtml      1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
5942
+     * 	@return	string   						HTML select string
5943
+     *  @see selectArrayAjax, ajax_combobox in ajax.lib.php
5944
+     */
5945
+    static function selectArrayFilter($htmlname, $array, $id='', $moreparam='', $disableFiltering=0, $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5946
+    {
5947
+        global $conf, $langs;
5948
+        global $delayedhtmlcontent;
5949
+
5950
+        // TODO Use an internal dolibarr component instead of select2
5951
+        if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5952
+
5953
+        $out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"><option></option></select>';
5954
+
5955
+        $formattedarrayresult = array();
5956
+
5957
+        foreach($array as $key => $value) {
5958
+            $o = new stdClass();
5959
+            $o->id = $key;
5960
+            $o->text = $value['text'];
5961
+            $o->url = $value['url'];
5962
+            $formattedarrayresult[] = $o;
5963
+        }
5964
+
5965
+        $tmpplugin='select2';
5966
+        $outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5967 5967
 			<script type="text/javascript">
5968 5968
 			$(document).ready(function () {
5969 5969
 				var data = '.json_encode($formattedarrayresult).';
@@ -5984,31 +5984,31 @@  discard block
 block discarded – undo
5984 5984
 
5985 5985
 						if(! data.id) return null;';
5986 5986
 
5987
-		if($callurlonselect) {
5988
-			$outdelayed.='
5987
+        if($callurlonselect) {
5988
+            $outdelayed.='
5989 5989
 
5990 5990
 						var urlBase = data.url;
5991 5991
 						var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
5992 5992
 						/* console.log("params.term="+params.term); */
5993 5993
 						/* console.log("params.term encoded="+encodeURIComponent(params.term)); */
5994 5994
 						saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term);';
5995
-		}
5995
+        }
5996 5996
 
5997
-		if(! $disableFiltering) {
5998
-			$outdelayed.='
5997
+        if(! $disableFiltering) {
5998
+            $outdelayed.='
5999 5999
 
6000 6000
 						if(data.text.match(new RegExp(params.term))) {
6001 6001
 							return data;
6002 6002
 						}
6003 6003
 
6004 6004
 						return null;';
6005
-		} else {
6006
-			$outdelayed.='
6005
+        } else {
6006
+            $outdelayed.='
6007 6007
 
6008 6008
 						return data;';
6009
-		}
6009
+        }
6010 6010
 
6011
-		$outdelayed.='
6011
+        $outdelayed.='
6012 6012
 					}
6013 6013
 				});
6014 6014
 
@@ -6031,73 +6031,73 @@  discard block
 block discarded – undo
6031 6031
 			});
6032 6032
 			</script>';
6033 6033
 
6034
-		if ($acceptdelayedhtml)
6035
-		{
6036
-			$delayedhtmlcontent.=$outdelayed;
6037
-		}
6038
-		else
6039
-		{
6040
-			$out.=$outdelayed;
6041
-		}
6042
-		return $out;
6043
-	}
6044
-
6045
-	/**
6046
-	 *	Show a multiselect form from an array.
6047
-	 *
6048
-	 *	@param	string	$htmlname		Name of select
6049
-	 *	@param	array	$array			Array with key+value
6050
-	 *	@param	array	$selected		Array with key+value preselected
6051
-	 *	@param	int		$key_in_label   1 pour afficher la key dans la valeur "[key] value"
6052
-	 *	@param	int		$value_as_key   1 to use value as key
6053
-	 *	@param  string	$morecss        Add more css style
6054
-	 *	@param  int		$translate		Translate and encode value
6055
-	 *  @param	int		$width			Force width of select box. May be used only when using jquery couch. Example: 250, 95%
6056
-	 *  @param	string	$moreattrib		Add more options on select component. Example: 'disabled'
6057
-	 *  @param	string	$elemtype		Type of element we show ('category', ...)
6058
-	 *  @param	string	$placeholder	String to use as placeholder
6059
-	 *  @param	int		$addjscombo		Add js combo
6060
-	 *	@return	string					HTML multiselect string
6061
-	 *  @see selectarray
6062
-	 */
6063
-	static function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='', $elemtype='', $placeholder='', $addjscombo=1)
6064
-	{
6065
-		global $conf, $langs;
6066
-
6067
-		$out = '';
6068
-
6069
-
6070
-		// Add code for jquery to use multiselect
6071
-		if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
6072
-		{
6073
-			$out.="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
6034
+        if ($acceptdelayedhtml)
6035
+        {
6036
+            $delayedhtmlcontent.=$outdelayed;
6037
+        }
6038
+        else
6039
+        {
6040
+            $out.=$outdelayed;
6041
+        }
6042
+        return $out;
6043
+    }
6044
+
6045
+    /**
6046
+     *	Show a multiselect form from an array.
6047
+     *
6048
+     *	@param	string	$htmlname		Name of select
6049
+     *	@param	array	$array			Array with key+value
6050
+     *	@param	array	$selected		Array with key+value preselected
6051
+     *	@param	int		$key_in_label   1 pour afficher la key dans la valeur "[key] value"
6052
+     *	@param	int		$value_as_key   1 to use value as key
6053
+     *	@param  string	$morecss        Add more css style
6054
+     *	@param  int		$translate		Translate and encode value
6055
+     *  @param	int		$width			Force width of select box. May be used only when using jquery couch. Example: 250, 95%
6056
+     *  @param	string	$moreattrib		Add more options on select component. Example: 'disabled'
6057
+     *  @param	string	$elemtype		Type of element we show ('category', ...)
6058
+     *  @param	string	$placeholder	String to use as placeholder
6059
+     *  @param	int		$addjscombo		Add js combo
6060
+     *	@return	string					HTML multiselect string
6061
+     *  @see selectarray
6062
+     */
6063
+    static function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='', $elemtype='', $placeholder='', $addjscombo=1)
6064
+    {
6065
+        global $conf, $langs;
6066
+
6067
+        $out = '';
6068
+
6069
+
6070
+        // Add code for jquery to use multiselect
6071
+        if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
6072
+        {
6073
+            $out.="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
6074 6074
 						<script type="text/javascript">'."\n";
6075
-			if ($addjscombo == 1)
6076
-			{
6077
-				$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
6078
-				$out.=	'function formatResult(record) {'."\n";
6079
-				if ($elemtype == 'category')
6080
-				{
6081
-					$out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6075
+            if ($addjscombo == 1)
6076
+            {
6077
+                $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
6078
+                $out.=	'function formatResult(record) {'."\n";
6079
+                if ($elemtype == 'category')
6080
+                {
6081
+                    $out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6082 6082
 									  	return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
6083
-				}
6084
-				else
6085
-				{
6086
-					$out.='return record.text;';
6087
-				}
6088
-				$out.=	'};'."\n";
6089
-				$out.=	'function formatSelection(record) {'."\n";
6090
-				if ($elemtype == 'category')
6091
-				{
6092
-					$out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6083
+                }
6084
+                else
6085
+                {
6086
+                    $out.='return record.text;';
6087
+                }
6088
+                $out.=	'};'."\n";
6089
+                $out.=	'function formatSelection(record) {'."\n";
6090
+                if ($elemtype == 'category')
6091
+                {
6092
+                    $out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6093 6093
 									  	return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
6094
-				}
6095
-				else
6096
-				{
6097
-					$out.='return record.text;';
6098
-				}
6099
-				$out.=	'};'."\n";
6100
-				$out.=	'$(document).ready(function () {
6094
+                }
6095
+                else
6096
+                {
6097
+                    $out.='return record.text;';
6098
+                }
6099
+                $out.=	'};'."\n";
6100
+                $out.=	'$(document).ready(function () {
6101 6101
 							$(\'#'.$htmlname.'\').'.$tmpplugin.'({
6102 6102
 								dir: \'ltr\',
6103 6103
 								// Specify format function for dropdown item
@@ -6108,12 +6108,12 @@  discard block
 block discarded – undo
6108 6108
 							 	templateResult: formatSelection		/* For 4.0 */
6109 6109
 							});
6110 6110
 						});'."\n";
6111
-			}
6112
-			elseif ($addjscombo == 2)
6113
-			{
6114
-				// Add other js lib
6115
-				// ...
6116
-				$out.= '$(document).ready(function () {
6111
+            }
6112
+            elseif ($addjscombo == 2)
6113
+            {
6114
+                // Add other js lib
6115
+                // ...
6116
+                $out.= '$(document).ready(function () {
6117 6117
 							$(\'#'.$htmlname.'\').multiSelect({
6118 6118
 								containerHTML: \'<div class="multi-select-container">\',
6119 6119
 								menuHTML: \'<div class="multi-select-menu">\',
@@ -6123,91 +6123,91 @@  discard block
 block discarded – undo
6123 6123
 								noneText: \''.$placeholder.'\'
6124 6124
 							});
6125 6125
 						})';
6126
-			}
6127
-			$out.=	'</script>';
6128
-		}
6129
-
6130
-		// Try also magic suggest
6131
-
6132
-		$out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
6133
-		if (is_array($array) && ! empty($array))
6134
-		{
6135
-			if ($value_as_key) $array=array_combine($array, $array);
6136
-
6137
-			if (! empty($array))
6138
-			{
6139
-				foreach ($array as $key => $value)
6140
-				{
6141
-					$out.= '<option value="'.$key.'"';
6142
-					if (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))
6143
-					{
6144
-						$out.= ' selected';
6145
-					}
6146
-					$out.= '>';
6147
-
6148
-					$newval = ($translate ? $langs->trans($value) : $value);
6149
-					$newval = ($key_in_label ? $key.' - '.$newval : $newval);
6150
-					$out.= dol_htmlentitiesbr($newval);
6151
-					$out.= '</option>'."\n";
6152
-				}
6153
-			}
6154
-		}
6155
-		$out.= '</select>'."\n";
6156
-
6157
-		return $out;
6158
-	}
6159
-
6160
-
6161
-	/**
6162
-	 *	Show a multiselect dropbox from an array.
6163
-	 *
6164
-	 *	@param	string	$htmlname		Name of HTML field
6165
-	 *	@param	array	$array			Array with array of fields we could show. This array may be modified according to setup of user.
6166
-	 *  @param  string  $varpage        Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
6167
-	 *	@return	string					HTML multiselect string
6168
-	 *  @see selectarray
6169
-	 */
6170
-	static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
6171
-	{
6172
-		global $conf,$langs,$user;
6173
-
6174
-		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
6175
-
6176
-		$tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
6177
-		if (! empty($user->conf->$tmpvar))
6178
-		{
6179
-			$tmparray=explode(',', $user->conf->$tmpvar);
6180
-			foreach($array as $key => $val)
6181
-			{
6182
-				//var_dump($key);
6183
-				//var_dump($tmparray);
6184
-				if (in_array($key, $tmparray)) $array[$key]['checked']=1;
6185
-				else $array[$key]['checked']=0;
6186
-			}
6187
-		}
6188
-		//var_dump($array);
6189
-
6190
-		$lis='';
6191
-		$listcheckedstring='';
6192
-
6193
-		foreach($array as $key => $val)
6194
-		{
6195
-		   /* var_dump($val);
6126
+            }
6127
+            $out.=	'</script>';
6128
+        }
6129
+
6130
+        // Try also magic suggest
6131
+
6132
+        $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
6133
+        if (is_array($array) && ! empty($array))
6134
+        {
6135
+            if ($value_as_key) $array=array_combine($array, $array);
6136
+
6137
+            if (! empty($array))
6138
+            {
6139
+                foreach ($array as $key => $value)
6140
+                {
6141
+                    $out.= '<option value="'.$key.'"';
6142
+                    if (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))
6143
+                    {
6144
+                        $out.= ' selected';
6145
+                    }
6146
+                    $out.= '>';
6147
+
6148
+                    $newval = ($translate ? $langs->trans($value) : $value);
6149
+                    $newval = ($key_in_label ? $key.' - '.$newval : $newval);
6150
+                    $out.= dol_htmlentitiesbr($newval);
6151
+                    $out.= '</option>'."\n";
6152
+                }
6153
+            }
6154
+        }
6155
+        $out.= '</select>'."\n";
6156
+
6157
+        return $out;
6158
+    }
6159
+
6160
+
6161
+    /**
6162
+     *	Show a multiselect dropbox from an array.
6163
+     *
6164
+     *	@param	string	$htmlname		Name of HTML field
6165
+     *	@param	array	$array			Array with array of fields we could show. This array may be modified according to setup of user.
6166
+     *  @param  string  $varpage        Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
6167
+     *	@return	string					HTML multiselect string
6168
+     *  @see selectarray
6169
+     */
6170
+    static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
6171
+    {
6172
+        global $conf,$langs,$user;
6173
+
6174
+        if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
6175
+
6176
+        $tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
6177
+        if (! empty($user->conf->$tmpvar))
6178
+        {
6179
+            $tmparray=explode(',', $user->conf->$tmpvar);
6180
+            foreach($array as $key => $val)
6181
+            {
6182
+                //var_dump($key);
6183
+                //var_dump($tmparray);
6184
+                if (in_array($key, $tmparray)) $array[$key]['checked']=1;
6185
+                else $array[$key]['checked']=0;
6186
+            }
6187
+        }
6188
+        //var_dump($array);
6189
+
6190
+        $lis='';
6191
+        $listcheckedstring='';
6192
+
6193
+        foreach($array as $key => $val)
6194
+        {
6195
+            /* var_dump($val);
6196 6196
             var_dump(array_key_exists('enabled', $val));
6197 6197
             var_dump(!$val['enabled']);*/
6198
-		   if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
6199
-		   {
6200
-			   unset($array[$key]);     // We don't want this field
6201
-			   continue;
6202
-		   }
6203
-		   if ($val['label'])
6204
-		   {
6205
-		   	$lis.='<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
6206
-			   $listcheckedstring.=(empty($val['checked'])?'':$key.',');
6207
-		   }
6208
-		}
6209
-
6210
-		$out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
6198
+            if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
6199
+            {
6200
+                unset($array[$key]);     // We don't want this field
6201
+                continue;
6202
+            }
6203
+            if ($val['label'])
6204
+            {
6205
+                $lis.='<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
6206
+                $listcheckedstring.=(empty($val['checked'])?'':$key.',');
6207
+            }
6208
+        }
6209
+
6210
+        $out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
6211 6211
 
6212 6212
         <dl class="dropdown">
6213 6213
             <dt>
@@ -6225,355 +6225,355 @@  discard block
 block discarded – undo
6225 6225
             </dd>
6226 6226
         </dl>
6227 6227
 
6228
-        <script type="text/javascript">
6229
-          jQuery(document).ready(function () {
6230
-              $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
6231
-                  console.log("A new field was added/removed")
6232
-                  $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\')
6233
-                  var title = $(this).val() + ",";
6234
-                  if ($(this).is(\':checked\')) {
6235
-                      $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
6236
-                  }
6237
-                  else {
6238
-                      $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
6239
-                  }
6240
-                  // Now, we submit page
6241
-                  $(this).parents(\'form:first\').submit();
6242
-              });
6243
-           });
6244
-        </script>
6228
+        <script type="text/javascript">
6229
+          jQuery(document).ready(function () {
6230
+              $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
6231
+                  console.log("A new field was added/removed")
6232
+                  $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\')
6233
+                  var title = $(this).val() + ",";
6234
+                  if ($(this).is(\':checked\')) {
6235
+                      $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
6236
+                  }
6237
+                  else {
6238
+                      $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
6239
+                  }
6240
+                  // Now, we submit page
6241
+                  $(this).parents(\'form:first\').submit();
6242
+              });
6243
+           });
6244
+        </script>
6245
+
6246
+        ';
6247
+        return $out;
6248
+    }
6249
+
6250
+    /**
6251
+     * 	Render list of categories linked to object with id $id and type $type
6252
+     *
6253
+     * 	@param		int		$id				Id of object
6254
+     * 	@param		string	$type			Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
6255
+     *  @param		int		$rendermode		0=Default, use multiselect. 1=Emulate multiselect (recommended)
6256
+     * 	@return		string					String with categories
6257
+     */
6258
+    function showCategories($id, $type, $rendermode=0)
6259
+    {
6260
+        global $db;
6261
+
6262
+        include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
6263
+
6264
+        $cat = new Categorie($db);
6265
+        $categories = $cat->containing($id, $type);
6266
+
6267
+        if ($rendermode == 1)
6268
+        {
6269
+            $toprint = array();
6270
+            foreach($categories as $c)
6271
+            {
6272
+                $ways = $c->print_all_ways();       // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
6273
+                foreach($ways as $way)
6274
+                {
6275
+                    $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color?' style="background: #'.$c->color.';"':' style="background: #aaa"').'>'.img_object('','category').' '.$way.'</li>';
6276
+                }
6277
+            }
6278
+            return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6279
+        }
6280
+
6281
+        if ($rendermode == 0)
6282
+        {
6283
+            $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
6284
+            foreach($categories as $c) {
6285
+                $arrayselected[] = $c->id;
6286
+            }
6287
+
6288
+            return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
6289
+        }
6290
+
6291
+        return 'ErrorBadValueForParameterRenderMode';	// Should not happened
6292
+    }
6293
+
6294
+
6295
+    /**
6296
+     *  Show linked object block.
6297
+     *
6298
+     *  @param	CommonObject	$object		      Object we want to show links to
6299
+     *  @param  string          $morehtmlright    More html to show on right of title
6300
+     *  @param  array           $compatibleImportElementsList  Array of compatibles elements object for "import from" action
6301
+     *  @return	int							      <0 if KO, >=0 if OK
6302
+     */
6303
+    function showLinkedObjectBlock($object, $morehtmlright='',$compatibleImportElementsList=false)
6304
+    {
6305
+        global $conf,$langs,$hookmanager;
6306
+        global $bc;
6307
+
6308
+        $object->fetchObjectLinked();
6309
+
6310
+        // Bypass the default method
6311
+        $hookmanager->initHooks(array('commonobject'));
6312
+        $parameters=array(
6313
+            'morehtmlright' => $morehtmlright,
6314
+            'compatibleImportElementsList' =>& $compatibleImportElementsList,
6315
+        );
6316
+        $reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6317
+
6318
+        if (empty($reshook))
6319
+        {
6320
+            $nbofdifferenttypes = count($object->linkedObjects);
6321
+
6322
+            print '<!-- showLinkedObjectBlock -->';
6323
+            print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
6324
+
6325
+
6326
+            print '<div class="div-table-responsive-no-min">';
6327
+            print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'"  data-elementid="'.$object->id.'"   >';
6328
+
6329
+            print '<tr class="liste_titre">';
6330
+            print '<td>'.$langs->trans("Type").'</td>';
6331
+            print '<td>'.$langs->trans("Ref").'</td>';
6332
+            print '<td align="center"></td>';
6333
+            print '<td align="center">'.$langs->trans("Date").'</td>';
6334
+            print '<td align="right">'.$langs->trans("AmountHTShort").'</td>';
6335
+            print '<td align="right">'.$langs->trans("Status").'</td>';
6336
+            print '<td></td>';
6337
+            print '</tr>';
6338
+
6339
+            $nboftypesoutput=0;
6340
+
6341
+            foreach($object->linkedObjects as $objecttype => $objects)
6342
+            {
6343
+                $tplpath = $element = $subelement = $objecttype;
6344
+
6345
+                // to display inport button on tpl
6346
+                $showImportButton=false;
6347
+                if(!empty($compatibleImportElementsList) && in_array($element,$compatibleImportElementsList)){
6348
+                    $showImportButton=true;
6349
+                }
6350
+
6351
+                if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
6352
+                {
6353
+                    $element = $regs[1];
6354
+                    $subelement = $regs[2];
6355
+                    $tplpath = $element.'/'.$subelement;
6356
+                }
6357
+                $tplname='linkedobjectblock';
6358
+
6359
+                // To work with non standard path
6360
+                if ($objecttype == 'facture')          {
6361
+                    $tplpath = 'compta/'.$element;
6362
+                    if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6363
+                }
6364
+                else if ($objecttype == 'facturerec')          {
6365
+                    $tplpath = 'compta/facture';
6366
+                    $tplname = 'linkedobjectblockForRec';
6367
+                    if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6368
+                }
6369
+                else if ($objecttype == 'propal')           {
6370
+                    $tplpath = 'comm/'.$element;
6371
+                    if (empty($conf->propal->enabled)) continue;	// Do not show if module disabled
6372
+                }
6373
+                else if ($objecttype == 'supplier_proposal')           {
6374
+                    if (empty($conf->supplier_proposal->enabled)) continue;	// Do not show if module disabled
6375
+                }
6376
+                else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
6377
+                    $tplpath = 'expedition';
6378
+                    if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6379
+                }
6380
+                else if ($objecttype == 'reception') {
6381
+                    $tplpath = 'reception';
6382
+                    if (empty($conf->reception->enabled)) continue;	// Do not show if module disabled
6383
+                }
6384
+                else if ($objecttype == 'delivery')         {
6385
+                    $tplpath = 'livraison';
6386
+                    if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6387
+                }
6388
+                else if ($objecttype == 'invoice_supplier') {
6389
+                    $tplpath = 'fourn/facture';
6390
+                }
6391
+                else if ($objecttype == 'order_supplier')   {
6392
+                    $tplpath = 'fourn/commande';
6393
+                }
6394
+                else if ($objecttype == 'expensereport')   {
6395
+                    $tplpath = 'expensereport';
6396
+                }
6397
+                else if ($objecttype == 'subscription')   {
6398
+                    $tplpath = 'adherents';
6399
+                }
6400
+
6401
+                global $linkedObjectBlock;
6402
+                $linkedObjectBlock = $objects;
6403
+
6404
+
6405
+                // Output template part (modules that overwrite templates must declare this into descriptor)
6406
+                $dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
6407
+                foreach($dirtpls as $reldir)
6408
+                {
6409
+                    if ($nboftypesoutput == ($nbofdifferenttypes - 1))    // No more type to show after
6410
+                    {
6411
+                        global $noMoreLinkedObjectBlockAfter;
6412
+                        $noMoreLinkedObjectBlockAfter=1;
6413
+                    }
6414
+
6415
+                    $res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
6416
+                    if ($res)
6417
+                    {
6418
+                        $nboftypesoutput++;
6419
+                        break;
6420
+                    }
6421
+                }
6422
+            }
6423
+
6424
+            if (! $nboftypesoutput)
6425
+            {
6426
+                print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
6427
+            }
6428
+
6429
+            print '</table>';
6430
+
6431
+            if(!empty($compatibleImportElementsList))
6432
+            {
6433
+                $res=@include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
6434
+            }
6435
+
6436
+
6437
+            print '</div>';
6438
+
6439
+            return $nbofdifferenttypes;
6440
+        }
6441
+    }
6442
+
6443
+    /**
6444
+     *  Show block with links to link to other objects.
6445
+     *
6446
+     *  @param	CommonObject	$object				Object we want to show links to
6447
+     *  @param	array			$restrictlinksto	Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
6448
+     *  @param	array			$excludelinksto		Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
6449
+     *  @return	string								<0 if KO, >0 if OK
6450
+     */
6451
+    function showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())
6452
+    {
6453
+        global $conf, $langs, $hookmanager;
6454
+        global $bc;
6455
+
6456
+        $linktoelem='';
6457
+        $linktoelemlist='';
6458
+        $listofidcompanytoscan='';
6459
+
6460
+        if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
6461
+
6462
+        $possiblelinks=array();
6463
+        if (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)
6464
+        {
6465
+            $listofidcompanytoscan=$object->thirdparty->id;
6466
+            if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;
6467
+            if (($object->fk_project > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
6468
+            {
6469
+                include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
6470
+                $tmpproject=new Project($this->db);
6471
+                $tmpproject->fetch($object->fk_project);
6472
+                if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan.=','.$tmpproject->socid;
6473
+                unset($tmpproject);
6474
+            }
6475
+
6476
+            $possiblelinks=array(
6477
+                'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),
6478
+                'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),
6479
+                'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6480
+                'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6481
+                'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
6482
+                'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),
6483
+                'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled , 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
6484
+                'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled , 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
6485
+                'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled , 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')')
6486
+            );
6487
+        }
6488
+
6489
+        global $action;
6245 6490
 
6246
-        ';
6247
-		return $out;
6248
-	}
6249
-
6250
-	/**
6251
-	 * 	Render list of categories linked to object with id $id and type $type
6252
-	 *
6253
-	 * 	@param		int		$id				Id of object
6254
-	 * 	@param		string	$type			Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
6255
-	 *  @param		int		$rendermode		0=Default, use multiselect. 1=Emulate multiselect (recommended)
6256
-	 * 	@return		string					String with categories
6257
-	 */
6258
-	function showCategories($id, $type, $rendermode=0)
6259
-	{
6260
-		global $db;
6261
-
6262
-		include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
6263
-
6264
-		$cat = new Categorie($db);
6265
-		$categories = $cat->containing($id, $type);
6266
-
6267
-		if ($rendermode == 1)
6268
-		{
6269
-			$toprint = array();
6270
-			foreach($categories as $c)
6271
-			{
6272
-				$ways = $c->print_all_ways();       // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
6273
-				foreach($ways as $way)
6274
-				{
6275
-					$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color?' style="background: #'.$c->color.';"':' style="background: #aaa"').'>'.img_object('','category').' '.$way.'</li>';
6276
-				}
6277
-			}
6278
-			return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6279
-		}
6280
-
6281
-		if ($rendermode == 0)
6282
-		{
6283
-			$cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
6284
-			foreach($categories as $c) {
6285
-				$arrayselected[] = $c->id;
6286
-			}
6287
-
6288
-			return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
6289
-		}
6290
-
6291
-		return 'ErrorBadValueForParameterRenderMode';	// Should not happened
6292
-	}
6293
-
6294
-
6295
-	/**
6296
-	 *  Show linked object block.
6297
-	 *
6298
-	 *  @param	CommonObject	$object		      Object we want to show links to
6299
-	 *  @param  string          $morehtmlright    More html to show on right of title
6300
-	 *  @param  array           $compatibleImportElementsList  Array of compatibles elements object for "import from" action
6301
-	 *  @return	int							      <0 if KO, >=0 if OK
6302
-	 */
6303
-	function showLinkedObjectBlock($object, $morehtmlright='',$compatibleImportElementsList=false)
6304
-	{
6305
-		global $conf,$langs,$hookmanager;
6306
-		global $bc;
6307
-
6308
-		$object->fetchObjectLinked();
6309
-
6310
-		// Bypass the default method
6311
-		$hookmanager->initHooks(array('commonobject'));
6312
-		$parameters=array(
6313
-			'morehtmlright' => $morehtmlright,
6314
-		    'compatibleImportElementsList' =>& $compatibleImportElementsList,
6315
-		);
6316
-		$reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6317
-
6318
-		if (empty($reshook))
6319
-		{
6320
-			$nbofdifferenttypes = count($object->linkedObjects);
6321
-
6322
-			print '<!-- showLinkedObjectBlock -->';
6323
-			print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
6324
-
6325
-
6326
-			print '<div class="div-table-responsive-no-min">';
6327
-			print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'"  data-elementid="'.$object->id.'"   >';
6328
-
6329
-			print '<tr class="liste_titre">';
6330
-			print '<td>'.$langs->trans("Type").'</td>';
6331
-			print '<td>'.$langs->trans("Ref").'</td>';
6332
-			print '<td align="center"></td>';
6333
-			print '<td align="center">'.$langs->trans("Date").'</td>';
6334
-			print '<td align="right">'.$langs->trans("AmountHTShort").'</td>';
6335
-			print '<td align="right">'.$langs->trans("Status").'</td>';
6336
-			print '<td></td>';
6337
-			print '</tr>';
6338
-
6339
-			$nboftypesoutput=0;
6340
-
6341
-			foreach($object->linkedObjects as $objecttype => $objects)
6342
-			{
6343
-				$tplpath = $element = $subelement = $objecttype;
6344
-
6345
-				// to display inport button on tpl
6346
-				$showImportButton=false;
6347
-				if(!empty($compatibleImportElementsList) && in_array($element,$compatibleImportElementsList)){
6348
-				    $showImportButton=true;
6349
-				}
6350
-
6351
-				if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
6352
-				{
6353
-					$element = $regs[1];
6354
-					$subelement = $regs[2];
6355
-					$tplpath = $element.'/'.$subelement;
6356
-				}
6357
-				$tplname='linkedobjectblock';
6358
-
6359
-				// To work with non standard path
6360
-				if ($objecttype == 'facture')          {
6361
-					$tplpath = 'compta/'.$element;
6362
-					if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6363
-				}
6364
-				else if ($objecttype == 'facturerec')          {
6365
-					$tplpath = 'compta/facture';
6366
-					$tplname = 'linkedobjectblockForRec';
6367
-					if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6368
-				}
6369
-				else if ($objecttype == 'propal')           {
6370
-					$tplpath = 'comm/'.$element;
6371
-					if (empty($conf->propal->enabled)) continue;	// Do not show if module disabled
6372
-				}
6373
-				else if ($objecttype == 'supplier_proposal')           {
6374
-					if (empty($conf->supplier_proposal->enabled)) continue;	// Do not show if module disabled
6375
-				}
6376
-				else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
6377
-					$tplpath = 'expedition';
6378
-					if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6379
-				}
6380
-        		else if ($objecttype == 'reception') {
6381
-        			$tplpath = 'reception';
6382
-        			if (empty($conf->reception->enabled)) continue;	// Do not show if module disabled
6383
-        		}
6384
-				else if ($objecttype == 'delivery')         {
6385
-					$tplpath = 'livraison';
6386
-					if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6387
-				}
6388
-				else if ($objecttype == 'invoice_supplier') {
6389
-					$tplpath = 'fourn/facture';
6390
-				}
6391
-				else if ($objecttype == 'order_supplier')   {
6392
-					$tplpath = 'fourn/commande';
6393
-				}
6394
-				else if ($objecttype == 'expensereport')   {
6395
-					$tplpath = 'expensereport';
6396
-				}
6397
-				else if ($objecttype == 'subscription')   {
6398
-					$tplpath = 'adherents';
6399
-				}
6400
-
6401
-				global $linkedObjectBlock;
6402
-				$linkedObjectBlock = $objects;
6403
-
6404
-
6405
-				// Output template part (modules that overwrite templates must declare this into descriptor)
6406
-				$dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
6407
-				foreach($dirtpls as $reldir)
6408
-				{
6409
-					if ($nboftypesoutput == ($nbofdifferenttypes - 1))    // No more type to show after
6410
-					{
6411
-						global $noMoreLinkedObjectBlockAfter;
6412
-						$noMoreLinkedObjectBlockAfter=1;
6413
-					}
6491
+        // Can complete the possiblelink array
6492
+        $hookmanager->initHooks(array('commonobject'));
6493
+        $parameters=array('listofidcompanytoscan' => $listofidcompanytoscan);
6494
+        $reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6495
+        if (empty($reshook))
6496
+        {
6497
+            if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6498
+            {
6499
+                $possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);
6500
+            }
6501
+        }
6502
+        else if ($reshook > 0)
6503
+        {
6504
+            if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6505
+            {
6506
+                $possiblelinks=$hookmanager->resArray;
6507
+            }
6508
+        }
6414 6509
 
6415
-					$res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
6416
-					if ($res)
6417
-					{
6418
-						$nboftypesoutput++;
6419
-						break;
6420
-					}
6421
-				}
6422
-			}
6423
-
6424
-			if (! $nboftypesoutput)
6425
-			{
6426
-				print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
6427
-			}
6428
-
6429
-			print '</table>';
6430
-
6431
-			if(!empty($compatibleImportElementsList))
6432
-			{
6433
-			    $res=@include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
6434
-			}
6435
-
6436
-
6437
-			print '</div>';
6438
-
6439
-			return $nbofdifferenttypes;
6440
-		}
6441
-	}
6442
-
6443
-	/**
6444
-	 *  Show block with links to link to other objects.
6445
-	 *
6446
-	 *  @param	CommonObject	$object				Object we want to show links to
6447
-	 *  @param	array			$restrictlinksto	Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
6448
-	 *  @param	array			$excludelinksto		Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
6449
-	 *  @return	string								<0 if KO, >0 if OK
6450
-	 */
6451
-	function showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())
6452
-	{
6453
-		global $conf, $langs, $hookmanager;
6454
-		global $bc;
6455
-
6456
-		$linktoelem='';
6457
-		$linktoelemlist='';
6458
-		$listofidcompanytoscan='';
6459
-
6460
-		if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
6461
-
6462
-		$possiblelinks=array();
6463
-		if (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)
6464
-		{
6465
-			$listofidcompanytoscan=$object->thirdparty->id;
6466
-			if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;
6467
-			if (($object->fk_project > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
6468
-			{
6469
-				include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
6470
-				$tmpproject=new Project($this->db);
6471
-				$tmpproject->fetch($object->fk_project);
6472
-				if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan.=','.$tmpproject->socid;
6473
-				unset($tmpproject);
6474
-			}
6475
-
6476
-			$possiblelinks=array(
6477
-				'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),
6478
-				'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),
6479
-				'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6480
-				'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6481
-				'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
6482
-				'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),
6483
-				'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled , 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
6484
-				'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled , 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
6485
-				'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled , 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')')
6486
-			);
6487
-		}
6488
-
6489
-		global $action;
6490
-
6491
-		// Can complete the possiblelink array
6492
-		$hookmanager->initHooks(array('commonobject'));
6493
-		$parameters=array('listofidcompanytoscan' => $listofidcompanytoscan);
6494
-		$reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6495
-		if (empty($reshook))
6496
-		{
6497
-			if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6498
-			{
6499
-				$possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);
6500
-			}
6501
-		}
6502
-		else if ($reshook > 0)
6503
-		{
6504
-			if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6505
-			{
6506
-				$possiblelinks=$hookmanager->resArray;
6507
-			}
6508
-		}
6509
-
6510
-		foreach($possiblelinks as $key => $possiblelink)
6511
-		{
6512
-			$num = 0;
6513
-
6514
-			if (empty($possiblelink['enabled'])) continue;
6515
-
6516
-			if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))
6517
-			{
6518
-				print '<div id="'.$key.'list"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
6519
-				$sql = $possiblelink['sql'];
6520
-
6521
-				$resqllist = $this->db->query($sql);
6522
-				if ($resqllist)
6523
-				{
6524
-					$num = $this->db->num_rows($resqllist);
6525
-					$i = 0;
6526
-
6527
-					print '<br><form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
6528
-					print '<input type="hidden" name="id" value="'.$object->id.'">';
6529
-					print '<input type="hidden" name="action" value="addlink">';
6530
-					print '<input type="hidden" name="addlink" value="'.$key.'">';
6531
-					print '<table class="noborder">';
6532
-					print '<tr class="liste_titre">';
6533
-					print '<td class="nowrap"></td>';
6534
-					print '<td align="center">' . $langs->trans("Ref") . '</td>';
6535
-					print '<td align="left">' . $langs->trans("RefCustomer") . '</td>';
6536
-					print '<td align="right">' . $langs->trans("AmountHTShort") . '</td>';
6537
-					print '<td align="left">' . $langs->trans("Company") . '</td>';
6538
-					print '</tr>';
6539
-					while ($i < $num)
6540
-					{
6541
-						$objp = $this->db->fetch_object($resqllist);
6542
-
6543
-						print '<tr class="oddeven">';
6544
-						print '<td aling="left">';
6545
-						print '<input type="radio" name="idtolinkto" value=' . $objp->rowid . '>';
6546
-						print '</td>';
6547
-						print '<td align="center">' . $objp->ref . '</td>';
6548
-						print '<td>' . $objp->ref_client . '</td>';
6549
-						print '<td align="right">' . price($objp->total_ht) . '</td>';
6550
-						print '<td>' . $objp->name . '</td>';
6551
-						print '</tr>';
6552
-						$i++;
6553
-					}
6554
-					print '</table>';
6555
-					print '<div class="center"><input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
6556
-
6557
-					print '</form>';
6558
-					$this->db->free($resqllist);
6559
-				} else {
6560
-					dol_print_error($this->db);
6561
-				}
6562
-				print '</div>';
6563
-				if ($num > 0)
6564
-				{
6565
-				}
6566
-
6567
-				//$linktoelem.=($linktoelem?' &nbsp; ':'');
6568
-				if ($num > 0) $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
6569
-				//else $linktoelem.=$langs->trans($possiblelink['label']);
6570
-				else $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
6571
-			}
6572
-		}
6573
-
6574
-		if ($linktoelemlist)
6575
-		{
6576
-			$linktoelem='
6510
+        foreach($possiblelinks as $key => $possiblelink)
6511
+        {
6512
+            $num = 0;
6513
+
6514
+            if (empty($possiblelink['enabled'])) continue;
6515
+
6516
+            if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))
6517
+            {
6518
+                print '<div id="'.$key.'list"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
6519
+                $sql = $possiblelink['sql'];
6520
+
6521
+                $resqllist = $this->db->query($sql);
6522
+                if ($resqllist)
6523
+                {
6524
+                    $num = $this->db->num_rows($resqllist);
6525
+                    $i = 0;
6526
+
6527
+                    print '<br><form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
6528
+                    print '<input type="hidden" name="id" value="'.$object->id.'">';
6529
+                    print '<input type="hidden" name="action" value="addlink">';
6530
+                    print '<input type="hidden" name="addlink" value="'.$key.'">';
6531
+                    print '<table class="noborder">';
6532
+                    print '<tr class="liste_titre">';
6533
+                    print '<td class="nowrap"></td>';
6534
+                    print '<td align="center">' . $langs->trans("Ref") . '</td>';
6535
+                    print '<td align="left">' . $langs->trans("RefCustomer") . '</td>';
6536
+                    print '<td align="right">' . $langs->trans("AmountHTShort") . '</td>';
6537
+                    print '<td align="left">' . $langs->trans("Company") . '</td>';
6538
+                    print '</tr>';
6539
+                    while ($i < $num)
6540
+                    {
6541
+                        $objp = $this->db->fetch_object($resqllist);
6542
+
6543
+                        print '<tr class="oddeven">';
6544
+                        print '<td aling="left">';
6545
+                        print '<input type="radio" name="idtolinkto" value=' . $objp->rowid . '>';
6546
+                        print '</td>';
6547
+                        print '<td align="center">' . $objp->ref . '</td>';
6548
+                        print '<td>' . $objp->ref_client . '</td>';
6549
+                        print '<td align="right">' . price($objp->total_ht) . '</td>';
6550
+                        print '<td>' . $objp->name . '</td>';
6551
+                        print '</tr>';
6552
+                        $i++;
6553
+                    }
6554
+                    print '</table>';
6555
+                    print '<div class="center"><input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
6556
+
6557
+                    print '</form>';
6558
+                    $this->db->free($resqllist);
6559
+                } else {
6560
+                    dol_print_error($this->db);
6561
+                }
6562
+                print '</div>';
6563
+                if ($num > 0)
6564
+                {
6565
+                }
6566
+
6567
+                //$linktoelem.=($linktoelem?' &nbsp; ':'');
6568
+                if ($num > 0) $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
6569
+                //else $linktoelem.=$langs->trans($possiblelink['label']);
6570
+                else $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
6571
+            }
6572
+        }
6573
+
6574
+        if ($linktoelemlist)
6575
+        {
6576
+            $linktoelem='
6577 6577
     		<dl class="dropdown" id="linktoobjectname">
6578 6578
     		<dt><a href="#linktoobjectname">'.$langs->trans("LinkTo").'...</a></dt>
6579 6579
     		<dd>
@@ -6583,13 +6583,13 @@  discard block
 block discarded – undo
6583 6583
     		</div>
6584 6584
     		</dd>
6585 6585
     		</dl>';
6586
-		}
6587
-		else
6588
-		{
6589
-			$linktoelem='';
6590
-		}
6586
+        }
6587
+        else
6588
+        {
6589
+            $linktoelem='';
6590
+        }
6591 6591
 
6592
-		print '<!-- Add js to show linkto box -->
6592
+        print '<!-- Add js to show linkto box -->
6593 6593
 				<script type="text/javascript" language="javascript">
6594 6594
 				jQuery(document).ready(function() {
6595 6595
 					jQuery(".linkto").click(function() {
@@ -6601,584 +6601,584 @@  discard block
 block discarded – undo
6601 6601
 				</script>
6602 6602
 		';
6603 6603
 
6604
-		return $linktoelem;
6605
-	}
6606
-
6607
-	/**
6608
-	 *	Return an html string with a select combo box to choose yes or no
6609
-	 *
6610
-	 *	@param	string		$htmlname		Name of html select field
6611
-	 *	@param	string		$value			Pre-selected value
6612
-	 *	@param	int			$option			0 return yes/no, 1 return 1/0
6613
-	 *	@param	bool		$disabled		true or false
6614
-	 *  @param	int      	$useempty		1=Add empty line
6615
-	 *	@return	string						See option
6616
-	 */
6617
-	function selectyesno($htmlname, $value='', $option=0, $disabled=false, $useempty=0)
6618
-	{
6619
-		global $langs;
6620
-
6621
-		$yes="yes"; $no="no";
6622
-		if ($option)
6623
-		{
6624
-			$yes="1";
6625
-			$no="0";
6626
-		}
6627
-
6628
-		$disabled = ($disabled ? ' disabled' : '');
6629
-
6630
-		$resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
6631
-		if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'>&nbsp;</option>'."\n";
6632
-		if (("$value" == 'yes') || ($value == 1))
6633
-		{
6634
-			$resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
6635
-			$resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
6636
-		}
6637
-		else
6638
-	   {
6639
-	   		$selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
6640
-			$resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
6641
-			$resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
6642
-		}
6643
-		$resultyesno .= '</select>'."\n";
6644
-		return $resultyesno;
6645
-	}
6604
+        return $linktoelem;
6605
+    }
6606
+
6607
+    /**
6608
+     *	Return an html string with a select combo box to choose yes or no
6609
+     *
6610
+     *	@param	string		$htmlname		Name of html select field
6611
+     *	@param	string		$value			Pre-selected value
6612
+     *	@param	int			$option			0 return yes/no, 1 return 1/0
6613
+     *	@param	bool		$disabled		true or false
6614
+     *  @param	int      	$useempty		1=Add empty line
6615
+     *	@return	string						See option
6616
+     */
6617
+    function selectyesno($htmlname, $value='', $option=0, $disabled=false, $useempty=0)
6618
+    {
6619
+        global $langs;
6620
+
6621
+        $yes="yes"; $no="no";
6622
+        if ($option)
6623
+        {
6624
+            $yes="1";
6625
+            $no="0";
6626
+        }
6627
+
6628
+        $disabled = ($disabled ? ' disabled' : '');
6629
+
6630
+        $resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
6631
+        if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'>&nbsp;</option>'."\n";
6632
+        if (("$value" == 'yes') || ($value == 1))
6633
+        {
6634
+            $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
6635
+            $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
6636
+        }
6637
+        else
6638
+        {
6639
+                $selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
6640
+            $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
6641
+            $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
6642
+        }
6643
+        $resultyesno .= '</select>'."\n";
6644
+        return $resultyesno;
6645
+    }
6646 6646
 
6647 6647
 
6648 6648
 
6649 6649
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
6650
-	/**
6651
-	 *  Return list of export templates
6652
-	 *
6653
-	 *  @param	string	$selected          Id modele pre-selectionne
6654
-	 *  @param  string	$htmlname          Name of HTML select
6655
-	 *  @param  string	$type              Type of searched templates
6656
-	 *  @param  int		$useempty          Affiche valeur vide dans liste
6657
-	 *  @return	void
6658
-	 */
6659
-	function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
6660
-	{
6650
+    /**
6651
+     *  Return list of export templates
6652
+     *
6653
+     *  @param	string	$selected          Id modele pre-selectionne
6654
+     *  @param  string	$htmlname          Name of HTML select
6655
+     *  @param  string	$type              Type of searched templates
6656
+     *  @param  int		$useempty          Affiche valeur vide dans liste
6657
+     *  @return	void
6658
+     */
6659
+    function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
6660
+    {
6661 6661
         // phpcs:enable
6662
-		$sql = "SELECT rowid, label";
6663
-		$sql.= " FROM ".MAIN_DB_PREFIX."export_model";
6664
-		$sql.= " WHERE type = '".$type."'";
6665
-		$sql.= " ORDER BY rowid";
6666
-		$result = $this->db->query($sql);
6667
-		if ($result)
6668
-		{
6669
-			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
6670
-			if ($useempty)
6671
-			{
6672
-				print '<option value="-1">&nbsp;</option>';
6673
-			}
6674
-
6675
-			$num = $this->db->num_rows($result);
6676
-			$i = 0;
6677
-			while ($i < $num)
6678
-			{
6679
-				$obj = $this->db->fetch_object($result);
6680
-				if ($selected == $obj->rowid)
6681
-				{
6682
-					print '<option value="'.$obj->rowid.'" selected>';
6683
-				}
6684
-				else
6685
-				{
6686
-					print '<option value="'.$obj->rowid.'">';
6687
-				}
6688
-				print $obj->label;
6689
-				print '</option>';
6690
-				$i++;
6691
-			}
6692
-			print "</select>";
6693
-		}
6694
-		else {
6695
-			dol_print_error($this->db);
6696
-		}
6697
-	}
6698
-
6699
-	/**
6700
-	 *    Return a HTML area with the reference of object and a navigation bar for a business object
6701
-	 *    Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
6702
-	 *
6703
-	 *    @param	object	$object			Object to show.
6704
-	 *    @param	string	$paramid   		Name of parameter to use to name the id into the URL next/previous link.
6705
-	 *    @param	string	$morehtml  		More html content to output just before the nav bar.
6706
-	 *    @param	int		$shownav	  	Show Condition (navigation is shown if value is 1).
6707
-	 *    @param	string	$fieldid   		Name of field id into database to use for select next and previous (we make the select max and min on this field compared to $object->ref). Use 'none' to disable next/prev.
6708
-	 *    @param	string	$fieldref   	Name of field ref of object (object->ref) to show or 'none' to not show ref.
6709
-	 *    @param	string	$morehtmlref  	More html to show after ref.
6710
-	 *    @param	string	$moreparam  	More param to add in nav link url. Must start with '&...'.
6711
-	 *	  @param	int		$nodbprefix		Do not include DB prefix to forge table name.
6712
-	 *	  @param	string	$morehtmlleft	More html code to show before ref.
6713
-	 *	  @param	string	$morehtmlstatus	More html code to show under navigation arrows (status place).
6714
-	 *	  @param	string	$morehtmlright	More html code to show after ref.
6715
-	 * 	  @return	string    				Portion HTML with ref + navigation buttons
6716
-	 */
6717
-	function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')
6718
-	{
6719
-		global $langs,$conf,$hookmanager;
6720
-
6721
-		$ret='';
6722
-		if (empty($fieldid))  $fieldid='rowid';
6723
-		if (empty($fieldref)) $fieldref='ref';
6724
-
6725
-		// Add where from hooks
6726
-		if (is_object($hookmanager))
6727
-		{
6728
-			$parameters=array();
6729
-			$reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters, $object);    // Note that $action and $object may have been modified by hook
6730
-			$object->next_prev_filter.=$hookmanager->resPrint;
6731
-		}
6732
-		$previous_ref = $next_ref = '';
6733
-		if ($shownav)
6734
-		{
6735
-			//print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
6736
-			$object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''), $fieldid, $nodbprefix);
6737
-
6738
-			$navurl = $_SERVER["PHP_SELF"];
6739
-			// Special case for project/task page
6740
-			if ($paramid == 'project_ref')
6741
-			{
6742
-				$navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/','/tasks.php',$navurl);
6743
-				$paramid='ref';
6744
-			}
6745
-
6746
-			// accesskey is for Windows or Linux:  ALT + key for chrome, ALT + SHIFT + KEY for firefox
6747
-			// accesskey is for Mac:               CTRL + key for all browsers
6748
-			$stringforfirstkey = $langs->trans("KeyboardShortcut");
6749
-			if ($conf->browser->name == 'chrome')
6750
-			{
6751
-				$stringforfirstkey .= ' ALT +';
6752
-			}
6753
-			elseif ($conf->browser->name == 'firefox')
6754
-			{
6755
-				$stringforfirstkey .= ' ALT + SHIFT +';
6756
-			}
6757
-			else
6758
-			{
6759
-				$stringforfirstkey .= ' CTL +';
6760
-			}
6761
-
6762
-			$previous_ref = $object->ref_previous?'<a accesskey="p" title="'.$stringforfirstkey.' p" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'"><i class="fa fa-chevron-left"></i></a>':'<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
6763
-			$next_ref     = $object->ref_next?'<a accesskey="n" title="'.$stringforfirstkey.' n" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'"><i class="fa fa-chevron-right"></i></a>':'<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
6764
-		}
6765
-
6766
-		//print "xx".$previous_ref."x".$next_ref;
6767
-		$ret.='<!-- Start banner content --><div style="vertical-align: middle">';
6768
-
6769
-		// Right part of banner
6770
-		if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
6771
-
6772
-		if ($previous_ref || $next_ref || $morehtml)
6773
-		{
6774
-			$ret.='<div class="pagination paginationref"><ul class="right">';
6775
-		}
6776
-		if ($morehtml)
6777
-		{
6778
-			$ret.='<li class="noborder litext">'.$morehtml.'</li>';
6779
-		}
6780
-		if ($shownav && ($previous_ref || $next_ref))
6781
-		{
6782
-			$ret.='<li class="pagination">'.$previous_ref.'</li>';
6783
-			$ret.='<li class="pagination">'.$next_ref.'</li>';
6784
-		}
6785
-		if ($previous_ref || $next_ref || $morehtml)
6786
-		{
6787
-			$ret.='</ul></div>';
6788
-		}
6789
-
6790
-		$parameters=array();
6791
-		$reshook=$hookmanager->executeHooks('moreHtmlStatus',$parameters, $object);    // Note that $action and $object may have been modified by hook
6792
-		if (empty($reshook)) $morehtmlstatus.=$hookmanager->resPrint;
6793
-		else $morehtmlstatus=$hookmanager->resPrint;
6794
-		if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
6795
-
6796
-		$parameters = array();
6797
-		$reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
6798
-		if (empty($reshook)) $morehtmlref.=$hookmanager->resPrint;
6799
-		elseif ($reshook > 0) $morehtmlref=$hookmanager->resPrint;
6800
-
6801
-		// Left part of banner
6802
-		if ($morehtmlleft)
6803
-		{
6804
-			if ($conf->browser->layout == 'phone') $ret.='<div class="floatleft">'.$morehtmlleft.'</div>';    // class="center" to have photo in middle
6805
-			else $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
6806
-		}
6807
-
6808
-		//if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
6809
-		$ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
6810
-
6811
-		// For thirdparty, contact, user, member, the ref is the id, so we show something else
6812
-		if ($object->element == 'societe')
6813
-		{
6814
-			$ret.=dol_htmlentities($object->name);
6815
-		}
6816
-		else if ($object->element == 'member')
6817
-		{
6818
-			$ret.=$object->ref.'<br>';
6819
-			$fullname=$object->getFullName($langs);
6820
-			if ($object->morphy == 'mor' && $object->societe) {
6821
-				$ret.= dol_htmlentities($object->societe) . ((! empty($fullname) && $object->societe != $fullname)?' ('.dol_htmlentities($fullname).')':'');
6822
-			} else {
6823
-				$ret.= dol_htmlentities($fullname) . ((! empty($object->societe) && $object->societe != $fullname)?' ('.dol_htmlentities($object->societe).')':'');
6824
-			}
6825
-		}
6826
-		else if (in_array($object->element, array('contact', 'user', 'usergroup')))
6827
-		{
6828
-			$ret.=dol_htmlentities($object->getFullName($langs));
6829
-		}
6830
-		else if (in_array($object->element, array('action', 'agenda')))
6831
-		{
6832
-			$ret.=$object->ref.'<br>'.$object->label;
6833
-		}
6834
-		else if (in_array($object->element, array('adherent_type')))
6835
-		{
6836
-			$ret.=$object->label;
6837
-		}
6838
-		else if ($object->element == 'ecm_directories')
6839
-		{
6840
-			$ret.='';
6841
-		}
6842
-		else if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);
6843
-
6844
-
6845
-		if ($morehtmlref)
6846
-		{
6847
-			$ret.=' '.$morehtmlref;
6848
-		}
6849
-		$ret.='</div>';
6850
-
6851
-		$ret.='</div><!-- End banner content -->';
6852
-
6853
-		return $ret;
6854
-	}
6855
-
6856
-
6857
-	/**
6858
-	 *    	Return HTML code to output a barcode
6859
-	 *
6860
-	 *     	@param	Object	$object		Object containing data to retrieve file name
6861
-	 * 		@param	int		$width			Width of photo
6862
-	 * 	  	@return string    				HTML code to output barcode
6863
-	 */
6864
-	function showbarcode(&$object,$width=100)
6865
-	{
6866
-		global $conf;
6867
-
6868
-		//Check if barcode is filled in the card
6869
-		if (empty($object->barcode)) return '';
6870
-
6871
-		// Complete object if not complete
6872
-		if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
6873
-		{
6874
-			$result = $object->fetch_barcode();
6875
-			//Check if fetch_barcode() failed
6876
-			if ($result < 1) return '<!-- ErrorFetchBarcode -->';
6877
-		}
6878
-
6879
-		// Barcode image
6880
-		$url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
6881
-		$out ='<!-- url barcode = '.$url.' -->';
6882
-		$out.='<img src="'.$url.'">';
6883
-		return $out;
6884
-	}
6885
-
6886
-	/**
6887
-	 *    	Return HTML code to output a photo
6888
-	 *
6889
-	 *    	@param	string		$modulepart			Key to define module concerned ('societe', 'userphoto', 'memberphoto')
6890
-	 *     	@param  object		$object				Object containing data to retrieve file name
6891
-	 * 		@param	int			$width				Width of photo
6892
-	 * 		@param	int			$height				Height of photo (auto if 0)
6893
-	 * 		@param	int			$caneditfield		Add edit fields
6894
-	 * 		@param	string		$cssclass			CSS name to use on img for photo
6895
-	 * 		@param	string		$imagesize		    'mini', 'small' or '' (original)
6896
-	 *      @param  int         $addlinktofullsize  Add link to fullsize image
6897
-	 *      @param  int         $cache              1=Accept to use image in cache
6898
-	 *      @param	string		$forcecapture		Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if empty.
6899
-	 * 	  	@return string    						HTML code to output photo
6900
-	 */
6901
-	static function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='')
6902
-	{
6903
-		global $conf,$langs;
6904
-
6905
-		$entity = (! empty($object->entity) ? $object->entity : $conf->entity);
6906
-		$id = (! empty($object->id) ? $object->id : $object->rowid);
6907
-
6908
-		$ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';$capture='';
6909
-		if ($modulepart=='societe')
6910
-		{
6911
-			$dir=$conf->societe->multidir_output[$entity];
6912
-			if (! empty($object->logo))
6913
-			{
6914
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini');             // getImageFileNameForSize include the thumbs
6915
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
6916
-				else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6917
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6918
-			}
6919
-			$email=$object->email;
6920
-		}
6921
-		else if ($modulepart=='contact')
6922
-		{
6923
-			$dir=$conf->societe->multidir_output[$entity].'/contact';
6924
-			if (! empty($object->photo))
6925
-			{
6926
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
6927
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
6928
-				else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6929
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6930
-			}
6931
-			$email=$object->email;
6932
-			$capture='user';
6933
-		}
6934
-		else if ($modulepart=='userphoto')
6935
-		{
6936
-			$dir=$conf->user->dir_output;
6937
-			if (! empty($object->photo))
6938
-			{
6939
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
6940
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
6941
-				else $file=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6942
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6943
-			}
6944
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6945
-			$email=$object->email;
6946
-			$capture='user';
6947
-		}
6948
-		else if ($modulepart=='memberphoto')
6949
-		{
6950
-			$dir=$conf->adherent->dir_output;
6951
-			if (! empty($object->photo))
6952
-			{
6953
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
6954
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
6955
-				else $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6956
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6957
-			}
6958
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6959
-			$email=$object->email;
6960
-			$capture='user';
6961
-		}
6962
-		else
6963
-		{
6964
-			// Generic case to show photos
6965
-			$dir=$conf->$modulepart->dir_output;
6966
-			if (! empty($object->photo))
6967
-			{
6968
-				if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
6969
-				else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
6970
-				else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6971
-				$originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6972
-			}
6973
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6974
-			$email=$object->email;
6975
-		}
6976
-
6977
-		if ($forcecapture) $capture = $forcecapture;
6978
-
6979
-		if ($dir)
6980
-		{
6981
-			if ($file && file_exists($dir."/".$file))
6982
-			{
6983
-				if ($addlinktofullsize)
6984
-				{
6985
-					$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6986
-					if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6987
-					else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6988
-				}
6989
-				$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'">';
6990
-				if ($addlinktofullsize) $ret.='</a>';
6991
-			}
6992
-			else if ($altfile && file_exists($dir."/".$altfile))
6993
-			{
6994
-				if ($addlinktofullsize)
6995
-				{
6996
-					$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6997
-					if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6998
-					else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6999
-				}
7000
-				$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo alt" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" class="'.$cssclass.'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'">';
7001
-				if ($addlinktofullsize) $ret.='</a>';
7002
-			}
7003
-			else
7004
-			{
7005
-				$nophoto='/public/theme/common/nophoto.png';
7006
-				if (in_array($modulepart,array('userphoto','contact')))	// For module that are "physical" users
7007
-				{
7008
-					$nophoto='/public/theme/common/user_anonymous.png';
7009
-					if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
7010
-					if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
7011
-				}
7012
-
7013
-				if (! empty($conf->gravatar->enabled) && $email)
7014
-				{
7015
-					/**
7016
-					 * @see https://gravatar.com/site/implement/images/php/
7017
-					 */
7018
-					global $dolibarr_main_url_root;
7019
-					$ret.='<!-- Put link to gravatar -->';
7020
-					//$defaultimg=urlencode(dol_buildpath($nophoto,3));
7021
-					$defaultimg='mm';
7022
-					$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.$defaultimg.'">';	// gravatar need md5 hash
7023
-				}
7024
-				else
7025
-				{
7026
-					$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
7027
-				}
7028
-			}
7029
-
7030
-			if ($caneditfield)
7031
-			{
7032
-				if ($object->photo) $ret.="<br>\n";
7033
-				$ret.='<table class="nobordernopadding centpercent">';
7034
-				if ($object->photo) $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
7035
-				$ret.='<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"'.($capture?' capture="'.$capture.'"':'').'></td></tr>';
7036
-				$ret.='</table>';
7037
-			}
7038
-		}
7039
-		else dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
7040
-
7041
-		return $ret;
7042
-	}
6662
+        $sql = "SELECT rowid, label";
6663
+        $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
6664
+        $sql.= " WHERE type = '".$type."'";
6665
+        $sql.= " ORDER BY rowid";
6666
+        $result = $this->db->query($sql);
6667
+        if ($result)
6668
+        {
6669
+            print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
6670
+            if ($useempty)
6671
+            {
6672
+                print '<option value="-1">&nbsp;</option>';
6673
+            }
6674
+
6675
+            $num = $this->db->num_rows($result);
6676
+            $i = 0;
6677
+            while ($i < $num)
6678
+            {
6679
+                $obj = $this->db->fetch_object($result);
6680
+                if ($selected == $obj->rowid)
6681
+                {
6682
+                    print '<option value="'.$obj->rowid.'" selected>';
6683
+                }
6684
+                else
6685
+                {
6686
+                    print '<option value="'.$obj->rowid.'">';
6687
+                }
6688
+                print $obj->label;
6689
+                print '</option>';
6690
+                $i++;
6691
+            }
6692
+            print "</select>";
6693
+        }
6694
+        else {
6695
+            dol_print_error($this->db);
6696
+        }
6697
+    }
6698
+
6699
+    /**
6700
+     *    Return a HTML area with the reference of object and a navigation bar for a business object
6701
+     *    Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
6702
+     *
6703
+     *    @param	object	$object			Object to show.
6704
+     *    @param	string	$paramid   		Name of parameter to use to name the id into the URL next/previous link.
6705
+     *    @param	string	$morehtml  		More html content to output just before the nav bar.
6706
+     *    @param	int		$shownav	  	Show Condition (navigation is shown if value is 1).
6707
+     *    @param	string	$fieldid   		Name of field id into database to use for select next and previous (we make the select max and min on this field compared to $object->ref). Use 'none' to disable next/prev.
6708
+     *    @param	string	$fieldref   	Name of field ref of object (object->ref) to show or 'none' to not show ref.
6709
+     *    @param	string	$morehtmlref  	More html to show after ref.
6710
+     *    @param	string	$moreparam  	More param to add in nav link url. Must start with '&...'.
6711
+     *	  @param	int		$nodbprefix		Do not include DB prefix to forge table name.
6712
+     *	  @param	string	$morehtmlleft	More html code to show before ref.
6713
+     *	  @param	string	$morehtmlstatus	More html code to show under navigation arrows (status place).
6714
+     *	  @param	string	$morehtmlright	More html code to show after ref.
6715
+     * 	  @return	string    				Portion HTML with ref + navigation buttons
6716
+     */
6717
+    function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')
6718
+    {
6719
+        global $langs,$conf,$hookmanager;
6720
+
6721
+        $ret='';
6722
+        if (empty($fieldid))  $fieldid='rowid';
6723
+        if (empty($fieldref)) $fieldref='ref';
6724
+
6725
+        // Add where from hooks
6726
+        if (is_object($hookmanager))
6727
+        {
6728
+            $parameters=array();
6729
+            $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters, $object);    // Note that $action and $object may have been modified by hook
6730
+            $object->next_prev_filter.=$hookmanager->resPrint;
6731
+        }
6732
+        $previous_ref = $next_ref = '';
6733
+        if ($shownav)
6734
+        {
6735
+            //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
6736
+            $object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''), $fieldid, $nodbprefix);
6737
+
6738
+            $navurl = $_SERVER["PHP_SELF"];
6739
+            // Special case for project/task page
6740
+            if ($paramid == 'project_ref')
6741
+            {
6742
+                $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/','/tasks.php',$navurl);
6743
+                $paramid='ref';
6744
+            }
6745
+
6746
+            // accesskey is for Windows or Linux:  ALT + key for chrome, ALT + SHIFT + KEY for firefox
6747
+            // accesskey is for Mac:               CTRL + key for all browsers
6748
+            $stringforfirstkey = $langs->trans("KeyboardShortcut");
6749
+            if ($conf->browser->name == 'chrome')
6750
+            {
6751
+                $stringforfirstkey .= ' ALT +';
6752
+            }
6753
+            elseif ($conf->browser->name == 'firefox')
6754
+            {
6755
+                $stringforfirstkey .= ' ALT + SHIFT +';
6756
+            }
6757
+            else
6758
+            {
6759
+                $stringforfirstkey .= ' CTL +';
6760
+            }
6761
+
6762
+            $previous_ref = $object->ref_previous?'<a accesskey="p" title="'.$stringforfirstkey.' p" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'"><i class="fa fa-chevron-left"></i></a>':'<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
6763
+            $next_ref     = $object->ref_next?'<a accesskey="n" title="'.$stringforfirstkey.' n" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'"><i class="fa fa-chevron-right"></i></a>':'<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
6764
+        }
6765
+
6766
+        //print "xx".$previous_ref."x".$next_ref;
6767
+        $ret.='<!-- Start banner content --><div style="vertical-align: middle">';
6768
+
6769
+        // Right part of banner
6770
+        if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
6771
+
6772
+        if ($previous_ref || $next_ref || $morehtml)
6773
+        {
6774
+            $ret.='<div class="pagination paginationref"><ul class="right">';
6775
+        }
6776
+        if ($morehtml)
6777
+        {
6778
+            $ret.='<li class="noborder litext">'.$morehtml.'</li>';
6779
+        }
6780
+        if ($shownav && ($previous_ref || $next_ref))
6781
+        {
6782
+            $ret.='<li class="pagination">'.$previous_ref.'</li>';
6783
+            $ret.='<li class="pagination">'.$next_ref.'</li>';
6784
+        }
6785
+        if ($previous_ref || $next_ref || $morehtml)
6786
+        {
6787
+            $ret.='</ul></div>';
6788
+        }
6789
+
6790
+        $parameters=array();
6791
+        $reshook=$hookmanager->executeHooks('moreHtmlStatus',$parameters, $object);    // Note that $action and $object may have been modified by hook
6792
+        if (empty($reshook)) $morehtmlstatus.=$hookmanager->resPrint;
6793
+        else $morehtmlstatus=$hookmanager->resPrint;
6794
+        if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
6795
+
6796
+        $parameters = array();
6797
+        $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
6798
+        if (empty($reshook)) $morehtmlref.=$hookmanager->resPrint;
6799
+        elseif ($reshook > 0) $morehtmlref=$hookmanager->resPrint;
6800
+
6801
+        // Left part of banner
6802
+        if ($morehtmlleft)
6803
+        {
6804
+            if ($conf->browser->layout == 'phone') $ret.='<div class="floatleft">'.$morehtmlleft.'</div>';    // class="center" to have photo in middle
6805
+            else $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
6806
+        }
6807
+
6808
+        //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
6809
+        $ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
6810
+
6811
+        // For thirdparty, contact, user, member, the ref is the id, so we show something else
6812
+        if ($object->element == 'societe')
6813
+        {
6814
+            $ret.=dol_htmlentities($object->name);
6815
+        }
6816
+        else if ($object->element == 'member')
6817
+        {
6818
+            $ret.=$object->ref.'<br>';
6819
+            $fullname=$object->getFullName($langs);
6820
+            if ($object->morphy == 'mor' && $object->societe) {
6821
+                $ret.= dol_htmlentities($object->societe) . ((! empty($fullname) && $object->societe != $fullname)?' ('.dol_htmlentities($fullname).')':'');
6822
+            } else {
6823
+                $ret.= dol_htmlentities($fullname) . ((! empty($object->societe) && $object->societe != $fullname)?' ('.dol_htmlentities($object->societe).')':'');
6824
+            }
6825
+        }
6826
+        else if (in_array($object->element, array('contact', 'user', 'usergroup')))
6827
+        {
6828
+            $ret.=dol_htmlentities($object->getFullName($langs));
6829
+        }
6830
+        else if (in_array($object->element, array('action', 'agenda')))
6831
+        {
6832
+            $ret.=$object->ref.'<br>'.$object->label;
6833
+        }
6834
+        else if (in_array($object->element, array('adherent_type')))
6835
+        {
6836
+            $ret.=$object->label;
6837
+        }
6838
+        else if ($object->element == 'ecm_directories')
6839
+        {
6840
+            $ret.='';
6841
+        }
6842
+        else if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);
6843
+
6844
+
6845
+        if ($morehtmlref)
6846
+        {
6847
+            $ret.=' '.$morehtmlref;
6848
+        }
6849
+        $ret.='</div>';
6850
+
6851
+        $ret.='</div><!-- End banner content -->';
6852
+
6853
+        return $ret;
6854
+    }
6855
+
6856
+
6857
+    /**
6858
+     *    	Return HTML code to output a barcode
6859
+     *
6860
+     *     	@param	Object	$object		Object containing data to retrieve file name
6861
+     * 		@param	int		$width			Width of photo
6862
+     * 	  	@return string    				HTML code to output barcode
6863
+     */
6864
+    function showbarcode(&$object,$width=100)
6865
+    {
6866
+        global $conf;
6867
+
6868
+        //Check if barcode is filled in the card
6869
+        if (empty($object->barcode)) return '';
6870
+
6871
+        // Complete object if not complete
6872
+        if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
6873
+        {
6874
+            $result = $object->fetch_barcode();
6875
+            //Check if fetch_barcode() failed
6876
+            if ($result < 1) return '<!-- ErrorFetchBarcode -->';
6877
+        }
6878
+
6879
+        // Barcode image
6880
+        $url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
6881
+        $out ='<!-- url barcode = '.$url.' -->';
6882
+        $out.='<img src="'.$url.'">';
6883
+        return $out;
6884
+    }
6885
+
6886
+    /**
6887
+     *    	Return HTML code to output a photo
6888
+     *
6889
+     *    	@param	string		$modulepart			Key to define module concerned ('societe', 'userphoto', 'memberphoto')
6890
+     *     	@param  object		$object				Object containing data to retrieve file name
6891
+     * 		@param	int			$width				Width of photo
6892
+     * 		@param	int			$height				Height of photo (auto if 0)
6893
+     * 		@param	int			$caneditfield		Add edit fields
6894
+     * 		@param	string		$cssclass			CSS name to use on img for photo
6895
+     * 		@param	string		$imagesize		    'mini', 'small' or '' (original)
6896
+     *      @param  int         $addlinktofullsize  Add link to fullsize image
6897
+     *      @param  int         $cache              1=Accept to use image in cache
6898
+     *      @param	string		$forcecapture		Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if empty.
6899
+     * 	  	@return string    						HTML code to output photo
6900
+     */
6901
+    static function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='')
6902
+    {
6903
+        global $conf,$langs;
6904
+
6905
+        $entity = (! empty($object->entity) ? $object->entity : $conf->entity);
6906
+        $id = (! empty($object->id) ? $object->id : $object->rowid);
6907
+
6908
+        $ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';$capture='';
6909
+        if ($modulepart=='societe')
6910
+        {
6911
+            $dir=$conf->societe->multidir_output[$entity];
6912
+            if (! empty($object->logo))
6913
+            {
6914
+                if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini');             // getImageFileNameForSize include the thumbs
6915
+                else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
6916
+                else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6917
+                $originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6918
+            }
6919
+            $email=$object->email;
6920
+        }
6921
+        else if ($modulepart=='contact')
6922
+        {
6923
+            $dir=$conf->societe->multidir_output[$entity].'/contact';
6924
+            if (! empty($object->photo))
6925
+            {
6926
+                if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
6927
+                else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
6928
+                else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6929
+                $originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6930
+            }
6931
+            $email=$object->email;
6932
+            $capture='user';
6933
+        }
6934
+        else if ($modulepart=='userphoto')
6935
+        {
6936
+            $dir=$conf->user->dir_output;
6937
+            if (! empty($object->photo))
6938
+            {
6939
+                if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
6940
+                else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
6941
+                else $file=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6942
+                $originalfile=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6943
+            }
6944
+            if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6945
+            $email=$object->email;
6946
+            $capture='user';
6947
+        }
6948
+        else if ($modulepart=='memberphoto')
6949
+        {
6950
+            $dir=$conf->adherent->dir_output;
6951
+            if (! empty($object->photo))
6952
+            {
6953
+                if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
6954
+                else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
6955
+                else $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6956
+                $originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6957
+            }
6958
+            if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6959
+            $email=$object->email;
6960
+            $capture='user';
6961
+        }
6962
+        else
6963
+        {
6964
+            // Generic case to show photos
6965
+            $dir=$conf->$modulepart->dir_output;
6966
+            if (! empty($object->photo))
6967
+            {
6968
+                if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
6969
+                else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
6970
+                else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6971
+                $originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6972
+            }
6973
+            if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6974
+            $email=$object->email;
6975
+        }
6976
+
6977
+        if ($forcecapture) $capture = $forcecapture;
6978
+
6979
+        if ($dir)
6980
+        {
6981
+            if ($file && file_exists($dir."/".$file))
6982
+            {
6983
+                if ($addlinktofullsize)
6984
+                {
6985
+                    $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6986
+                    if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6987
+                    else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6988
+                }
6989
+                $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'">';
6990
+                if ($addlinktofullsize) $ret.='</a>';
6991
+            }
6992
+            else if ($altfile && file_exists($dir."/".$altfile))
6993
+            {
6994
+                if ($addlinktofullsize)
6995
+                {
6996
+                    $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6997
+                    if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6998
+                    else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6999
+                }
7000
+                $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo alt" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" class="'.$cssclass.'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'">';
7001
+                if ($addlinktofullsize) $ret.='</a>';
7002
+            }
7003
+            else
7004
+            {
7005
+                $nophoto='/public/theme/common/nophoto.png';
7006
+                if (in_array($modulepart,array('userphoto','contact')))	// For module that are "physical" users
7007
+                {
7008
+                    $nophoto='/public/theme/common/user_anonymous.png';
7009
+                    if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
7010
+                    if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
7011
+                }
7012
+
7013
+                if (! empty($conf->gravatar->enabled) && $email)
7014
+                {
7015
+                    /**
7016
+                     * @see https://gravatar.com/site/implement/images/php/
7017
+                     */
7018
+                    global $dolibarr_main_url_root;
7019
+                    $ret.='<!-- Put link to gravatar -->';
7020
+                    //$defaultimg=urlencode(dol_buildpath($nophoto,3));
7021
+                    $defaultimg='mm';
7022
+                    $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.$defaultimg.'">';	// gravatar need md5 hash
7023
+                }
7024
+                else
7025
+                {
7026
+                    $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
7027
+                }
7028
+            }
7029
+
7030
+            if ($caneditfield)
7031
+            {
7032
+                if ($object->photo) $ret.="<br>\n";
7033
+                $ret.='<table class="nobordernopadding centpercent">';
7034
+                if ($object->photo) $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
7035
+                $ret.='<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"'.($capture?' capture="'.$capture.'"':'').'></td></tr>';
7036
+                $ret.='</table>';
7037
+            }
7038
+        }
7039
+        else dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
7040
+
7041
+        return $ret;
7042
+    }
7043 7043
 
7044 7044
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
7045
-	/**
7046
-	 *	Return select list of groups
7047
-	 *
7048
-	 *  @param	string	$selected       Id group preselected
7049
-	 *  @param  string	$htmlname       Field name in form
7050
-	 *  @param  int		$show_empty     0=liste sans valeur nulle, 1=ajoute valeur inconnue
7051
-	 *  @param  string	$exclude        Array list of groups id to exclude
7052
-	 * 	@param	int		$disabled		If select list must be disabled
7053
-	 *  @param  string	$include        Array list of groups id to include
7054
-	 * 	@param	int		$enableonly		Array list of groups id to be enabled. All other must be disabled
7055
-	 * 	@param	string	$force_entity	'0' or Ids of environment to force
7056
-	 * 	@param	bool	$multiple		add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
7057
-	 *  @return	string
7058
-	 *  @see select_dolusers
7059
-	 */
7060
-	function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity='0', $multiple=false)
7061
-	{
7045
+    /**
7046
+     *	Return select list of groups
7047
+     *
7048
+     *  @param	string	$selected       Id group preselected
7049
+     *  @param  string	$htmlname       Field name in form
7050
+     *  @param  int		$show_empty     0=liste sans valeur nulle, 1=ajoute valeur inconnue
7051
+     *  @param  string	$exclude        Array list of groups id to exclude
7052
+     * 	@param	int		$disabled		If select list must be disabled
7053
+     *  @param  string	$include        Array list of groups id to include
7054
+     * 	@param	int		$enableonly		Array list of groups id to be enabled. All other must be disabled
7055
+     * 	@param	string	$force_entity	'0' or Ids of environment to force
7056
+     * 	@param	bool	$multiple		add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
7057
+     *  @return	string
7058
+     *  @see select_dolusers
7059
+     */
7060
+    function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity='0', $multiple=false)
7061
+    {
7062 7062
         // phpcs:enable
7063
-		global $conf,$user,$langs;
7064
-
7065
-		// Permettre l'exclusion de groupes
7066
-		if (is_array($exclude))	$excludeGroups = implode("','",$exclude);
7067
-		// Permettre l'inclusion de groupes
7068
-		if (is_array($include))	$includeGroups = implode("','",$include);
7069
-
7070
-		if (!is_array($selected)) $selected = array($selected);
7071
-
7072
-		$out='';
7073
-
7074
-		// On recherche les groupes
7075
-		$sql = "SELECT ug.rowid, ug.nom as name";
7076
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7077
-		{
7078
-			$sql.= ", e.label";
7079
-		}
7080
-		$sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
7081
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7082
-		{
7083
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
7084
-			if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
7085
-			else $sql.= " WHERE ug.entity IS NOT NULL";
7086
-		}
7087
-		else
7088
-		{
7089
-			$sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
7090
-		}
7091
-		if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
7092
-		if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
7093
-		$sql.= " ORDER BY ug.nom ASC";
7094
-
7095
-		dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
7096
-		$resql=$this->db->query($sql);
7097
-		if ($resql)
7098
-		{
7099
-			// Enhance with select2
7100
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
7101
-		   	$out .= ajax_combobox($htmlname);
7102
-
7103
-			$out.= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
7104
-
7105
-			$num = $this->db->num_rows($resql);
7106
-			$i = 0;
7107
-			if ($num)
7108
-			{
7109
-				if ($show_empty && !$multiple) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'>&nbsp;</option>'."\n";
7110
-
7111
-				while ($i < $num)
7112
-				{
7113
-					$obj = $this->db->fetch_object($resql);
7114
-					$disableline=0;
7115
-					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
7116
-
7117
-					$out.= '<option value="'.$obj->rowid.'"';
7118
-					if ($disableline) $out.= ' disabled';
7119
-					if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (! is_object($selected[0]) && in_array($obj->rowid,$selected) ))
7120
-					{
7121
-						$out.= ' selected';
7122
-					}
7123
-					$out.= '>';
7063
+        global $conf,$user,$langs;
7124 7064
 
7125
-					$out.= $obj->name;
7126
-					if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
7127
-					{
7128
-						$out.= " (".$obj->label.")";
7129
-					}
7065
+        // Permettre l'exclusion de groupes
7066
+        if (is_array($exclude))	$excludeGroups = implode("','",$exclude);
7067
+        // Permettre l'inclusion de groupes
7068
+        if (is_array($include))	$includeGroups = implode("','",$include);
7069
+
7070
+        if (!is_array($selected)) $selected = array($selected);
7071
+
7072
+        $out='';
7073
+
7074
+        // On recherche les groupes
7075
+        $sql = "SELECT ug.rowid, ug.nom as name";
7076
+        if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7077
+        {
7078
+            $sql.= ", e.label";
7079
+        }
7080
+        $sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
7081
+        if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7082
+        {
7083
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
7084
+            if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
7085
+            else $sql.= " WHERE ug.entity IS NOT NULL";
7086
+        }
7087
+        else
7088
+        {
7089
+            $sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
7090
+        }
7091
+        if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
7092
+        if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
7093
+        $sql.= " ORDER BY ug.nom ASC";
7094
+
7095
+        dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
7096
+        $resql=$this->db->query($sql);
7097
+        if ($resql)
7098
+        {
7099
+            // Enhance with select2
7100
+            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
7101
+                $out .= ajax_combobox($htmlname);
7102
+
7103
+            $out.= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
7104
+
7105
+            $num = $this->db->num_rows($resql);
7106
+            $i = 0;
7107
+            if ($num)
7108
+            {
7109
+                if ($show_empty && !$multiple) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'>&nbsp;</option>'."\n";
7110
+
7111
+                while ($i < $num)
7112
+                {
7113
+                    $obj = $this->db->fetch_object($resql);
7114
+                    $disableline=0;
7115
+                    if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
7116
+
7117
+                    $out.= '<option value="'.$obj->rowid.'"';
7118
+                    if ($disableline) $out.= ' disabled';
7119
+                    if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (! is_object($selected[0]) && in_array($obj->rowid,$selected) ))
7120
+                    {
7121
+                        $out.= ' selected';
7122
+                    }
7123
+                    $out.= '>';
7124
+
7125
+                    $out.= $obj->name;
7126
+                    if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
7127
+                    {
7128
+                        $out.= " (".$obj->label.")";
7129
+                    }
7130
+
7131
+                    $out.= '</option>';
7132
+                    $i++;
7133
+                }
7134
+            }
7135
+            else
7136
+            {
7137
+                if ($show_empty) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'></option>'."\n";
7138
+                $out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
7139
+            }
7140
+            $out.= '</select>';
7141
+        }
7142
+        else
7143
+        {
7144
+            dol_print_error($this->db);
7145
+        }
7146
+
7147
+        return $out;
7148
+    }
7149
+
7150
+
7151
+    /**
7152
+     *	Return HTML to show the search and clear seach button
7153
+     *
7154
+     *  @return	string
7155
+     */
7156
+    function showFilterButtons()
7157
+    {
7158
+        global $conf, $langs;
7159
+
7160
+        $out='<div class="nowrap">';
7161
+        $out.='<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
7162
+        $out.='<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
7163
+        $out.='</div>';
7164
+
7165
+        return $out;
7166
+    }
7167
+
7168
+    /**
7169
+     *	Return HTML to show the search and clear seach button
7170
+     *
7171
+     *  @param  string  $cssclass                  CSS class
7172
+     *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7173
+     *  @return	string
7174
+     */
7175
+    function showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)
7176
+    {
7177
+        global $conf, $langs;
7130 7178
 
7131
-					$out.= '</option>';
7132
-					$i++;
7133
-				}
7134
-			}
7135
-			else
7136
-			{
7137
-				if ($show_empty) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'></option>'."\n";
7138
-				$out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
7139
-			}
7140
-			$out.= '</select>';
7141
-		}
7142
-		else
7143
-		{
7144
-			dol_print_error($this->db);
7145
-		}
7146
-
7147
-		return $out;
7148
-	}
7149
-
7150
-
7151
-	/**
7152
-	 *	Return HTML to show the search and clear seach button
7153
-	 *
7154
-	 *  @return	string
7155
-	 */
7156
-	function showFilterButtons()
7157
-	{
7158
-		global $conf, $langs;
7159
-
7160
-		$out='<div class="nowrap">';
7161
-		$out.='<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
7162
-		$out.='<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
7163
-		$out.='</div>';
7164
-
7165
-		return $out;
7166
-	}
7167
-
7168
-	/**
7169
-	 *	Return HTML to show the search and clear seach button
7170
-	 *
7171
-	 *  @param  string  $cssclass                  CSS class
7172
-	 *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7173
-	 *  @return	string
7174
-	 */
7175
-	function showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)
7176
-	{
7177
-		global $conf, $langs;
7178
-
7179
-		$out='';
7180
-		if (! empty($conf->use_javascript_ajax)) $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
7181
-		$out.='<script type="text/javascript">
7179
+        $out='';
7180
+        if (! empty($conf->use_javascript_ajax)) $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
7181
+        $out.='<script type="text/javascript">
7182 7182
             $(document).ready(function() {
7183 7183
             	$("#checkallactions").click(function() {
7184 7184
                     if($(this).is(\':checked\')){
@@ -7190,8 +7190,8 @@  discard block
 block discarded – undo
7190 7190
                         console.log("We uncheck all");
7191 7191
                 		$(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
7192 7192
                     }'."\n";
7193
-		if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
7194
-		$out.='         });
7193
+        if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
7194
+        $out.='         });
7195 7195
 
7196 7196
         	$(".checkforselect").change(function() {
7197 7197
 				$(this).closest("tr").toggleClass("highlight", this.checked);
@@ -7200,78 +7200,78 @@  discard block
 block discarded – undo
7200 7200
  	});
7201 7201
     </script>';
7202 7202
 
7203
-		return $out;
7204
-	}
7205
-
7206
-	/**
7207
-	 *	Return HTML to show the search and clear seach button
7208
-	 *
7209
-	 *  @param	int  	$addcheckuncheckall        Add the check all/uncheck all checkbox (use javascript) and code to manage this
7210
-	 *  @param  string  $cssclass                  CSS class
7211
-	 *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7212
-	 *  @return	string
7213
-	 */
7214
-	function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
7215
-	{
7216
-		$out.=$this->showFilterButtons();
7217
-		if ($addcheckuncheckall)
7218
-		{
7219
-			$out.=$this->showCheckAddButtons($cssclass, $calljsfunction);
7220
-		}
7221
-		return $out;
7222
-	}
7223
-
7224
-	/**
7225
-	 * Return HTML to show the select of expense categories
7226
-	 *
7227
-	 * @param	string	$selected              preselected category
7228
-	 * @param	string	$htmlname              name of HTML select list
7229
-	 * @param	integer	$useempty              1=Add empty line
7230
-	 * @param	array	$excludeid             id to exclude
7231
-	 * @param	string	$target                htmlname of target select to bind event
7232
-	 * @param	int		$default_selected      default category to select if fk_c_type_fees change = EX_KME
7233
-	 * @param	array	$params                param to give
7234
-	 * @return	string
7235
-	 */
7236
-	function selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array())
7237
-	{
7238
-		global $db, $conf, $langs, $user;
7239
-
7240
-		$sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
7241
-		$sql.= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
7242
-		if (!empty($excludeid)) $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
7243
-		$sql.= ' ORDER BY label';
7244
-
7245
-		$resql = $db->query($sql);
7246
-		if ($resql)
7247
-		{
7248
-			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7249
-			if ($useempty) $out.= '<option value="0">&nbsp;</option>';
7250
-
7251
-			while ($obj = $db->fetch_object($resql))
7252
-			{
7253
-				$out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
7254
-			}
7255
-			$out.= '</select>';
7256
-			if (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
7257
-
7258
-			if (!empty($target))
7259
-			{
7260
-				$sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
7261
-				$resql = $db->query($sql);
7262
-				if ($resql)
7263
-				{
7264
-					if ($db->num_rows($resql) > 0)
7265
-					{
7266
-						$obj = $db->fetch_object($resql);
7267
-						$out.= '<script type="text/javascript">
7203
+        return $out;
7204
+    }
7205
+
7206
+    /**
7207
+     *	Return HTML to show the search and clear seach button
7208
+     *
7209
+     *  @param	int  	$addcheckuncheckall        Add the check all/uncheck all checkbox (use javascript) and code to manage this
7210
+     *  @param  string  $cssclass                  CSS class
7211
+     *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7212
+     *  @return	string
7213
+     */
7214
+    function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
7215
+    {
7216
+        $out.=$this->showFilterButtons();
7217
+        if ($addcheckuncheckall)
7218
+        {
7219
+            $out.=$this->showCheckAddButtons($cssclass, $calljsfunction);
7220
+        }
7221
+        return $out;
7222
+    }
7223
+
7224
+    /**
7225
+     * Return HTML to show the select of expense categories
7226
+     *
7227
+     * @param	string	$selected              preselected category
7228
+     * @param	string	$htmlname              name of HTML select list
7229
+     * @param	integer	$useempty              1=Add empty line
7230
+     * @param	array	$excludeid             id to exclude
7231
+     * @param	string	$target                htmlname of target select to bind event
7232
+     * @param	int		$default_selected      default category to select if fk_c_type_fees change = EX_KME
7233
+     * @param	array	$params                param to give
7234
+     * @return	string
7235
+     */
7236
+    function selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array())
7237
+    {
7238
+        global $db, $conf, $langs, $user;
7239
+
7240
+        $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
7241
+        $sql.= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
7242
+        if (!empty($excludeid)) $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
7243
+        $sql.= ' ORDER BY label';
7244
+
7245
+        $resql = $db->query($sql);
7246
+        if ($resql)
7247
+        {
7248
+            $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7249
+            if ($useempty) $out.= '<option value="0">&nbsp;</option>';
7250
+
7251
+            while ($obj = $db->fetch_object($resql))
7252
+            {
7253
+                $out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
7254
+            }
7255
+            $out.= '</select>';
7256
+            if (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
7257
+
7258
+            if (!empty($target))
7259
+            {
7260
+                $sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
7261
+                $resql = $db->query($sql);
7262
+                if ($resql)
7263
+                {
7264
+                    if ($db->num_rows($resql) > 0)
7265
+                    {
7266
+                        $obj = $db->fetch_object($resql);
7267
+                        $out.= '<script type="text/javascript">
7268 7268
 							$(function() {
7269 7269
 								$("select[name='.$target.']").on("change", function() {
7270 7270
 									var current_val = $(this).val();
7271 7271
 									if (current_val == '.$obj->id.') {';
7272
-						if (!empty($default_selected) || !empty($selected)) $out.= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
7272
+                        if (!empty($default_selected) || !empty($selected)) $out.= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
7273 7273
 
7274
-						$out.= '
7274
+                        $out.= '
7275 7275
 										$("select[name='.$htmlname.']").change();
7276 7276
 									}
7277 7277
 								});
@@ -7302,92 +7302,92 @@  discard block
 block discarded – undo
7302 7302
 								});
7303 7303
 							});
7304 7304
 						</script>';
7305
-					}
7306
-				}
7307
-			}
7308
-		}
7309
-		else
7310
-		{
7311
-			dol_print_error($db);
7312
-		}
7313
-
7314
-		return $out;
7315
-	}
7316
-
7317
-	/**
7318
-	 * Return HTML to show the select ranges of expense range
7319
-	 *
7320
-	 * @param	string	$selected    preselected category
7321
-	 * @param	string	$htmlname    name of HTML select list
7322
-	 * @param	integer	$useempty    1=Add empty line
7323
-	 * @return	string
7324
-	 */
7325
-	function selectExpenseRanges($selected='', $htmlname='fk_range', $useempty=0)
7326
-	{
7327
-		global $db,$conf,$langs;
7328
-
7329
-		$sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
7330
-		$sql.= ' WHERE entity = '.$conf->entity.' AND active = 1';
7331
-
7332
-		$resql = $db->query($sql);
7333
-		if ($resql)
7334
-		{
7335
-			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7336
-			if ($useempty) $out.= '<option value="0"></option>';
7337
-
7338
-			while ($obj = $db->fetch_object($resql))
7339
-			{
7340
-				$out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
7341
-			}
7342
-			$out.= '</select>';
7343
-		}
7344
-		else
7345
-		{
7346
-			dol_print_error($db);
7347
-		}
7348
-
7349
-		return $out;
7350
-	}
7351
-
7352
-	/**
7353
-	 * Return HTML to show a select of expense
7354
-	 *
7355
-	 * @param	string	$selected    preselected category
7356
-	 * @param	string	$htmlname    name of HTML select list
7357
-	 * @param	integer	$useempty    1=Add empty choice
7358
-	 * @param	integer	$allchoice   1=Add all choice
7359
-	 * @param	integer	$useid       0=use 'code' as key, 1=use 'id' as key
7360
-	 * @return	string
7361
-	 */
7362
-	function selectExpense($selected='', $htmlname='fk_c_type_fees', $useempty=0, $allchoice=1, $useid=0)
7363
-	{
7364
-		global $db,$langs;
7365
-
7366
-		$sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
7367
-		$sql.= ' WHERE active = 1';
7368
-
7369
-		$resql = $db->query($sql);
7370
-		if ($resql)
7371
-		{
7372
-			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7373
-			if ($useempty) $out.= '<option value="0"></option>';
7374
-			if ($allchoice) $out.= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
7375
-
7376
-			$field = 'code';
7377
-			if ($useid) $field = 'id';
7378
-
7379
-			while ($obj = $db->fetch_object($resql))
7380
-			{
7381
-				$key = $langs->trans($obj->code);
7382
-				$out.= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
7383
-			}
7384
-			$out.= '</select>';
7385
-		}
7386
-		else
7387
-		{
7388
-			dol_print_error($db);
7389
-		}
7390
-
7391
-		return $out;
7392
-	}
7305
+                    }
7306
+                }
7307
+            }
7308
+        }
7309
+        else
7310
+        {
7311
+            dol_print_error($db);
7312
+        }
7313
+
7314
+        return $out;
7315
+    }
7316
+
7317
+    /**
7318
+     * Return HTML to show the select ranges of expense range
7319
+     *
7320
+     * @param	string	$selected    preselected category
7321
+     * @param	string	$htmlname    name of HTML select list
7322
+     * @param	integer	$useempty    1=Add empty line
7323
+     * @return	string
7324
+     */
7325
+    function selectExpenseRanges($selected='', $htmlname='fk_range', $useempty=0)
7326
+    {
7327
+        global $db,$conf,$langs;
7328
+
7329
+        $sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
7330
+        $sql.= ' WHERE entity = '.$conf->entity.' AND active = 1';
7331
+
7332
+        $resql = $db->query($sql);
7333
+        if ($resql)
7334
+        {
7335
+            $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7336
+            if ($useempty) $out.= '<option value="0"></option>';
7337
+
7338
+            while ($obj = $db->fetch_object($resql))
7339
+            {
7340
+                $out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
7341
+            }
7342
+            $out.= '</select>';
7343
+        }
7344
+        else
7345
+        {
7346
+            dol_print_error($db);
7347
+        }
7348
+
7349
+        return $out;
7350
+    }
7351
+
7352
+    /**
7353
+     * Return HTML to show a select of expense
7354
+     *
7355
+     * @param	string	$selected    preselected category
7356
+     * @param	string	$htmlname    name of HTML select list
7357
+     * @param	integer	$useempty    1=Add empty choice
7358
+     * @param	integer	$allchoice   1=Add all choice
7359
+     * @param	integer	$useid       0=use 'code' as key, 1=use 'id' as key
7360
+     * @return	string
7361
+     */
7362
+    function selectExpense($selected='', $htmlname='fk_c_type_fees', $useempty=0, $allchoice=1, $useid=0)
7363
+    {
7364
+        global $db,$langs;
7365
+
7366
+        $sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
7367
+        $sql.= ' WHERE active = 1';
7368
+
7369
+        $resql = $db->query($sql);
7370
+        if ($resql)
7371
+        {
7372
+            $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7373
+            if ($useempty) $out.= '<option value="0"></option>';
7374
+            if ($allchoice) $out.= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
7375
+
7376
+            $field = 'code';
7377
+            if ($useid) $field = 'id';
7378
+
7379
+            while ($obj = $db->fetch_object($resql))
7380
+            {
7381
+                $key = $langs->trans($obj->code);
7382
+                $out.= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
7383
+            }
7384
+            $out.= '</select>';
7385
+        }
7386
+        else
7387
+        {
7388
+            dol_print_error($db);
7389
+        }
7390
+
7391
+        return $out;
7392
+    }
7393 7393
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formadmin.class.php 1 patch
Indentation   +268 added lines, -268 removed lines patch added patch discarded remove patch
@@ -29,100 +29,100 @@  discard block
 block discarded – undo
29 29
  */
30 30
 class FormAdmin
31 31
 {
32
-	var $db;
33
-	var $error;
32
+    var $db;
33
+    var $error;
34 34
 
35 35
 
36
-	/**
37
-	 *	Constructor
38
-	 *
39
-	 *  @param		DoliDB		$db      Database handler
40
-	 */
41
-	function __construct($db)
42
-	{
43
-		$this->db = $db;
44
-	}
36
+    /**
37
+     *	Constructor
38
+     *
39
+     *  @param		DoliDB		$db      Database handler
40
+     */
41
+    function __construct($db)
42
+    {
43
+        $this->db = $db;
44
+    }
45 45
 
46 46
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
47
-	/**
48
-	 *    	Return html select list with available languages (key='en_US', value='United States' for example)
49
-	 *
50
-	 *    	@param      string		$selected       Language pre-selected
51
-	 *    	@param      string		$htmlname       Name of HTML select
52
-	 *    	@param      int			$showauto       Show 'auto' choice
53
-	 * 		@param		array		$filter			Array of keys to exclude in list
54
-	 * 		@param		string		$showempty		'1'=Add empty value or string to show
55
-	 *      @param      int			$showwarning    Show a warning if language is not complete
56
-	 *      @param		int			$disabled		Disable edit of select
57
-	 *      @param		string		$morecss		Add more css styles
58
-	 *      @param      int         $showcode       1=Add language code into label at begining, 2=Add language code into label at end
59
-	 *      @param		int			$forcecombo		Force to use combo box (so no ajax beautify effect)
60
-	 *      @return		string						Return HTML select string with list of languages
47
+    /**
48
+     *    	Return html select list with available languages (key='en_US', value='United States' for example)
49
+     *
50
+     *    	@param      string		$selected       Language pre-selected
51
+     *    	@param      string		$htmlname       Name of HTML select
52
+     *    	@param      int			$showauto       Show 'auto' choice
53
+     * 		@param		array		$filter			Array of keys to exclude in list
54
+     * 		@param		string		$showempty		'1'=Add empty value or string to show
55
+     *      @param      int			$showwarning    Show a warning if language is not complete
56
+     *      @param		int			$disabled		Disable edit of select
57
+     *      @param		string		$morecss		Add more css styles
58
+     *      @param      int         $showcode       1=Add language code into label at begining, 2=Add language code into label at end
59
+     *      @param		int			$forcecombo		Force to use combo box (so no ajax beautify effect)
60
+     *      @return		string						Return HTML select string with list of languages
61 61
      */
62
-	function select_language($selected='', $htmlname='lang_id', $showauto=0, $filter=null, $showempty='', $showwarning=0, $disabled=0, $morecss='', $showcode=0, $forcecombo=0)
63
-	{
64
-		// phpcs:enable
65
-		global $langs;
66
-
67
-		$langs_available=$langs->get_available_languages(DOL_DOCUMENT_ROOT,12);
68
-
69
-		$out='';
70
-
71
-		$out.= '<select class="flat'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').'>';
72
-		if ($showempty)
73
-		{
74
-			$out.= '<option value="0"';
75
-			if ($selected == '') $out.= ' selected';
76
-			$out.= '>';
77
-			if ($showempty != '1') $out.=$showempty;
78
-			else $out.='&nbsp;';
79
-			$out.='</option>';
80
-		}
81
-		if ($showauto)
82
-		{
83
-			$out.= '<option value="auto"';
84
-			if ($selected == 'auto') $out.= ' selected';
85
-			$out.= '>'.$langs->trans("AutoDetectLang").'</option>';
86
-		}
87
-
88
-		asort($langs_available);
89
-
90
-		foreach ($langs_available as $key => $value)
91
-		{
92
-			$valuetoshow=$value;
93
-			if ($showcode == 1) $valuetoshow=$key.' - '.$value;
94
-			if ($showcode == 2) $valuetoshow=$value.' ('.$key.')';
95
-
96
-			if ($filter && is_array($filter))
97
-			{
98
-				if ( ! array_key_exists($key, $filter))
99
-				{
100
-					$out.= '<option value="'.$key.'">'.$valuetoshow.'</option>';
101
-				}
102
-			}
103
-			else if ($selected == $key)
104
-			{
105
-				$out.= '<option value="'.$key.'" selected>'.$valuetoshow.'</option>';
106
-			}
107
-			else
108
-			{
109
-				$out.= '<option value="'.$key.'">'.$valuetoshow.'</option>';
110
-			}
111
-		}
112
-		$out.= '</select>';
113
-
114
-		// Make select dynamic
115
-		if (! $forcecombo)
116
-		{
117
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
118
-			$out.= ajax_combobox($htmlname);
119
-		}
120
-
121
-		return $out;
122
-	}
62
+    function select_language($selected='', $htmlname='lang_id', $showauto=0, $filter=null, $showempty='', $showwarning=0, $disabled=0, $morecss='', $showcode=0, $forcecombo=0)
63
+    {
64
+        // phpcs:enable
65
+        global $langs;
66
+
67
+        $langs_available=$langs->get_available_languages(DOL_DOCUMENT_ROOT,12);
68
+
69
+        $out='';
70
+
71
+        $out.= '<select class="flat'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').'>';
72
+        if ($showempty)
73
+        {
74
+            $out.= '<option value="0"';
75
+            if ($selected == '') $out.= ' selected';
76
+            $out.= '>';
77
+            if ($showempty != '1') $out.=$showempty;
78
+            else $out.='&nbsp;';
79
+            $out.='</option>';
80
+        }
81
+        if ($showauto)
82
+        {
83
+            $out.= '<option value="auto"';
84
+            if ($selected == 'auto') $out.= ' selected';
85
+            $out.= '>'.$langs->trans("AutoDetectLang").'</option>';
86
+        }
87
+
88
+        asort($langs_available);
89
+
90
+        foreach ($langs_available as $key => $value)
91
+        {
92
+            $valuetoshow=$value;
93
+            if ($showcode == 1) $valuetoshow=$key.' - '.$value;
94
+            if ($showcode == 2) $valuetoshow=$value.' ('.$key.')';
95
+
96
+            if ($filter && is_array($filter))
97
+            {
98
+                if ( ! array_key_exists($key, $filter))
99
+                {
100
+                    $out.= '<option value="'.$key.'">'.$valuetoshow.'</option>';
101
+                }
102
+            }
103
+            else if ($selected == $key)
104
+            {
105
+                $out.= '<option value="'.$key.'" selected>'.$valuetoshow.'</option>';
106
+            }
107
+            else
108
+            {
109
+                $out.= '<option value="'.$key.'">'.$valuetoshow.'</option>';
110
+            }
111
+        }
112
+        $out.= '</select>';
113
+
114
+        // Make select dynamic
115
+        if (! $forcecombo)
116
+        {
117
+            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
118
+            $out.= ajax_combobox($htmlname);
119
+        }
120
+
121
+        return $out;
122
+    }
123 123
 
124 124
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
125
-	/**
125
+    /**
126 126
      *    Return list of available menus (eldy_backoffice, ...)
127 127
      *
128 128
      *    @param	string		$selected        Preselected menu value
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
      */
134 134
     function select_menu($selected, $htmlname, $dirmenuarray, $moreattrib='')
135 135
     {
136
-		// phpcs:enable
136
+        // phpcs:enable
137 137
         global $langs,$conf;
138 138
 
139 139
         // Clean parameters
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
         // Check parameters
143 143
         if (! is_array($dirmenuarray)) return -1;
144 144
 
145
-		$menuarray=array();
145
+        $menuarray=array();
146 146
         foreach ($conf->file->dol_document_root as $dirroot)
147 147
         {
148 148
             foreach($dirmenuarray as $dirtoscan)
@@ -151,65 +151,65 @@  discard block
 block discarded – undo
151 151
                 //print $dir.'<br>';
152 152
                 if (is_dir($dir))
153 153
                 {
154
-    	            $handle=opendir($dir);
155
-    	            if (is_resource($handle))
156
-    	            {
157
-    	                while (($file = readdir($handle))!==false)
158
-    	                {
159
-    	                    if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && substr($file, 0, 5) != 'index')
160
-    	                    {
161
-    	                        if (preg_match('/lib\.php$/i',$file)) continue;	// We exclude library files
162
-    	                        if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i',$file)) continue;		// We exclude all menu manager files
163
-    	                        if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i',$file)) continue;	// We exclude all menu manager files
164
-    	                        if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i',$file)) continue;	// We exclude all menu manager files
165
-
166
-    	                        $filelib=preg_replace('/\.php$/i','',$file);
167
-    	        				$prefix='';
168
-    	        				// 0=Recommanded, 1=Experimental, 2=Developpement, 3=Other
169
-    	        				if (preg_match('/^eldy/i',$file)) $prefix='0';
154
+                    $handle=opendir($dir);
155
+                    if (is_resource($handle))
156
+                    {
157
+                        while (($file = readdir($handle))!==false)
158
+                        {
159
+                            if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && substr($file, 0, 5) != 'index')
160
+                            {
161
+                                if (preg_match('/lib\.php$/i',$file)) continue;	// We exclude library files
162
+                                if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i',$file)) continue;		// We exclude all menu manager files
163
+                                if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i',$file)) continue;	// We exclude all menu manager files
164
+                                if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i',$file)) continue;	// We exclude all menu manager files
165
+
166
+                                $filelib=preg_replace('/\.php$/i','',$file);
167
+                                $prefix='';
168
+                                // 0=Recommanded, 1=Experimental, 2=Developpement, 3=Other
169
+                                if (preg_match('/^eldy/i',$file)) $prefix='0';
170 170
                                 else if (preg_match('/^smartphone/i',$file)) $prefix='2';
171
-    	        				else $prefix='3';
172
-
173
-    	                        if ($file == $selected)
174
-    	                        {
175
-    	        					$menuarray[$prefix.'_'.$file]='<option value="'.$file.'" selected>'.$filelib.'</option>';
176
-    	                        }
177
-    	                        else
178
-    	                        {
179
-    	                            $menuarray[$prefix.'_'.$file]='<option value="'.$file.'">'.$filelib.'</option>';
180
-    	                        }
181
-    	                    }
182
-    	                }
183
-    	                closedir($handle);
184
-    	            }
171
+                                else $prefix='3';
172
+
173
+                                if ($file == $selected)
174
+                                {
175
+                                    $menuarray[$prefix.'_'.$file]='<option value="'.$file.'" selected>'.$filelib.'</option>';
176
+                                }
177
+                                else
178
+                                {
179
+                                    $menuarray[$prefix.'_'.$file]='<option value="'.$file.'">'.$filelib.'</option>';
180
+                                }
181
+                            }
182
+                        }
183
+                        closedir($handle);
184
+                    }
185 185
                 }
186 186
             }
187 187
         }
188
-		ksort($menuarray);
188
+        ksort($menuarray);
189 189
 
190
-		// Output combo list of menus
190
+        // Output combo list of menus
191 191
         print '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
192 192
         $oldprefix='';
193
-		foreach ($menuarray as $key => $val)
194
-		{
195
-			$tab=explode('_',$key);
196
-			$newprefix=$tab[0];
197
-			if ($newprefix=='1' && ($conf->global->MAIN_FEATURES_LEVEL < 1)) continue;
198
-			if ($newprefix=='2' && ($conf->global->MAIN_FEATURES_LEVEL < 2)) continue;
199
-			if ($newprefix != $oldprefix)	// Add separators
200
-			{
201
-				// Affiche titre
202
-				print '<option value="-1" disabled>';
203
-				if ($newprefix=='0') print '-- '.$langs->trans("VersionRecommanded").' --';
193
+        foreach ($menuarray as $key => $val)
194
+        {
195
+            $tab=explode('_',$key);
196
+            $newprefix=$tab[0];
197
+            if ($newprefix=='1' && ($conf->global->MAIN_FEATURES_LEVEL < 1)) continue;
198
+            if ($newprefix=='2' && ($conf->global->MAIN_FEATURES_LEVEL < 2)) continue;
199
+            if ($newprefix != $oldprefix)	// Add separators
200
+            {
201
+                // Affiche titre
202
+                print '<option value="-1" disabled>';
203
+                if ($newprefix=='0') print '-- '.$langs->trans("VersionRecommanded").' --';
204 204
                 if ($newprefix=='1') print '-- '.$langs->trans("VersionExperimental").' --';
205
-				if ($newprefix=='2') print '-- '.$langs->trans("VersionDevelopment").' --';
206
-				if ($newprefix=='3') print '-- '.$langs->trans("Other").' --';
207
-				print '</option>';
208
-				$oldprefix=$newprefix;
209
-			}
210
-			print $val."\n";	// Show menu entry
211
-		}
212
-		print '</select>';
205
+                if ($newprefix=='2') print '-- '.$langs->trans("VersionDevelopment").' --';
206
+                if ($newprefix=='3') print '-- '.$langs->trans("Other").' --';
207
+                print '</option>';
208
+                $oldprefix=$newprefix;
209
+            }
210
+            print $val."\n";	// Show menu entry
211
+        }
212
+        print '</select>';
213 213
     }
214 214
 
215 215
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -223,65 +223,65 @@  discard block
 block discarded – undo
223 223
      */
224 224
     function select_menu_families($selected, $htmlname, $dirmenuarray)
225 225
     {
226
-		// phpcs:enable
227
-		global $langs,$conf;
226
+        // phpcs:enable
227
+        global $langs,$conf;
228 228
 
229 229
         //$expdevmenu=array('smartphone_backoffice.php','smartphone_frontoffice.php');  // Menu to disable if $conf->global->MAIN_FEATURES_LEVEL is not set
230
-		$expdevmenu=array();
230
+        $expdevmenu=array();
231 231
 
232
-		$menuarray=array();
232
+        $menuarray=array();
233 233
 
234
-		foreach($dirmenuarray as $dirmenu)
235
-		{
234
+        foreach($dirmenuarray as $dirmenu)
235
+        {
236 236
             foreach ($conf->file->dol_document_root as $dirroot)
237 237
             {
238 238
                 $dir=$dirroot.$dirmenu;
239 239
                 if (is_dir($dir))
240 240
                 {
241
-	                $handle=opendir($dir);
242
-	                if (is_resource($handle))
243
-	                {
244
-	        			while (($file = readdir($handle))!==false)
245
-	        			{
246
-	        				if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')
247
-	        				{
248
-	        					$filelib=preg_replace('/(_backoffice|_frontoffice)?\.php$/i','',$file);
249
-	        					if (preg_match('/^index/i',$filelib)) continue;
250
-	        					if (preg_match('/^default/i',$filelib)) continue;
251
-	        					if (preg_match('/^empty/i',$filelib)) continue;
252
-	        					if (preg_match('/\.lib/i',$filelib)) continue;
253
-	        					if (empty($conf->global->MAIN_FEATURES_LEVEL) && in_array($file,$expdevmenu)) continue;
254
-
255
-	        					$menuarray[$filelib]=1;
256
-	        				}
257
-	        				$menuarray['all']=1;
258
-	        			}
259
-	        			closedir($handle);
260
-	                }
241
+                    $handle=opendir($dir);
242
+                    if (is_resource($handle))
243
+                    {
244
+                        while (($file = readdir($handle))!==false)
245
+                        {
246
+                            if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')
247
+                            {
248
+                                $filelib=preg_replace('/(_backoffice|_frontoffice)?\.php$/i','',$file);
249
+                                if (preg_match('/^index/i',$filelib)) continue;
250
+                                if (preg_match('/^default/i',$filelib)) continue;
251
+                                if (preg_match('/^empty/i',$filelib)) continue;
252
+                                if (preg_match('/\.lib/i',$filelib)) continue;
253
+                                if (empty($conf->global->MAIN_FEATURES_LEVEL) && in_array($file,$expdevmenu)) continue;
254
+
255
+                                $menuarray[$filelib]=1;
256
+                            }
257
+                            $menuarray['all']=1;
258
+                        }
259
+                        closedir($handle);
260
+                    }
261 261
                 }
262 262
             }
263
-		}
263
+        }
264 264
 
265
-		ksort($menuarray);
265
+        ksort($menuarray);
266 266
 
267
-		// Affichage liste deroulante des menus
267
+        // Affichage liste deroulante des menus
268 268
         print '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
269 269
         $oldprefix='';
270
-		foreach ($menuarray as $key => $val)
271
-		{
272
-			$tab=explode('_',$key);
273
-			$newprefix=$tab[0];
274
-			print '<option value="'.$key.'"';
270
+        foreach ($menuarray as $key => $val)
271
+        {
272
+            $tab=explode('_',$key);
273
+            $newprefix=$tab[0];
274
+            print '<option value="'.$key.'"';
275 275
             if ($key == $selected)
276
-			{
277
-				print '	selected';
278
-			}
279
-			print '>';
280
-			if ($key == 'all') print $langs->trans("AllMenus");
281
-			else print $key;
282
-			print '</option>'."\n";
283
-		}
284
-		print '</select>';
276
+            {
277
+                print '	selected';
278
+            }
279
+            print '>';
280
+            if ($key == 'all') print $langs->trans("AllMenus");
281
+            else print $key;
282
+            print '</option>'."\n";
283
+        }
284
+        print '</select>';
285 285
     }
286 286
 
287 287
 
@@ -295,70 +295,70 @@  discard block
 block discarded – undo
295 295
      */
296 296
     function select_timezone($selected,$htmlname)
297 297
     {
298
-		// phpcs:enable
299
-		global $langs,$conf;
298
+        // phpcs:enable
299
+        global $langs,$conf;
300 300
 
301 301
         print '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
302
-		print '<option value="-1">&nbsp;</option>';
303
-
304
-		$arraytz=array(
305
-			"Pacific/Midway"=>"GMT-11:00",
306
-			"Pacific/Fakaofo"=>"GMT-10:00",
307
-			"America/Anchorage"=>"GMT-09:00",
308
-			"America/Los_Angeles"=>"GMT-08:00",
309
-			"America/Dawson_Creek"=>"GMT-07:00",
310
-			"America/Chicago"=>"GMT-06:00",
311
-			"America/Bogota"=>"GMT-05:00",
312
-			"America/Anguilla"=>"GMT-04:00",
313
-			"America/Araguaina"=>"GMT-03:00",
314
-			"America/Noronha"=>"GMT-02:00",
315
-			"Atlantic/Azores"=>"GMT-01:00",
316
-			"Africa/Abidjan"=>"GMT+00:00",
317
-			"Europe/Paris"=>"GMT+01:00",
318
-			"Europe/Helsinki"=>"GMT+02:00",
319
-			"Europe/Moscow"=>"GMT+03:00",
320
-			"Asia/Dubai"=>"GMT+04:00",
321
-			"Asia/Karachi"=>"GMT+05:00",
322
-			"Indian/Chagos"=>"GMT+06:00",
323
-			"Asia/Jakarta"=>"GMT+07:00",
324
-			"Asia/Hong_Kong"=>"GMT+08:00",
325
-			"Asia/Tokyo"=>"GMT+09:00",
326
-			"Australia/Sydney"=>"GMT+10:00",
327
-			"Pacific/Noumea"=>"GMT+11:00",
328
-			"Pacific/Auckland"=>"GMT+12:00",
329
-			"Pacific/Enderbury"=>"GMT+13:00"
330
-		);
331
-		foreach ($arraytz as $lib => $gmt)
332
-		{
333
-			print '<option value="'.$lib.'"';
334
-			if ($selected == $lib || $selected == $gmt) print ' selected';
335
-			print '>'.$gmt.'</option>'."\n";
336
-		}
337
-		print '</select>';
338
-	}
302
+        print '<option value="-1">&nbsp;</option>';
303
+
304
+        $arraytz=array(
305
+            "Pacific/Midway"=>"GMT-11:00",
306
+            "Pacific/Fakaofo"=>"GMT-10:00",
307
+            "America/Anchorage"=>"GMT-09:00",
308
+            "America/Los_Angeles"=>"GMT-08:00",
309
+            "America/Dawson_Creek"=>"GMT-07:00",
310
+            "America/Chicago"=>"GMT-06:00",
311
+            "America/Bogota"=>"GMT-05:00",
312
+            "America/Anguilla"=>"GMT-04:00",
313
+            "America/Araguaina"=>"GMT-03:00",
314
+            "America/Noronha"=>"GMT-02:00",
315
+            "Atlantic/Azores"=>"GMT-01:00",
316
+            "Africa/Abidjan"=>"GMT+00:00",
317
+            "Europe/Paris"=>"GMT+01:00",
318
+            "Europe/Helsinki"=>"GMT+02:00",
319
+            "Europe/Moscow"=>"GMT+03:00",
320
+            "Asia/Dubai"=>"GMT+04:00",
321
+            "Asia/Karachi"=>"GMT+05:00",
322
+            "Indian/Chagos"=>"GMT+06:00",
323
+            "Asia/Jakarta"=>"GMT+07:00",
324
+            "Asia/Hong_Kong"=>"GMT+08:00",
325
+            "Asia/Tokyo"=>"GMT+09:00",
326
+            "Australia/Sydney"=>"GMT+10:00",
327
+            "Pacific/Noumea"=>"GMT+11:00",
328
+            "Pacific/Auckland"=>"GMT+12:00",
329
+            "Pacific/Enderbury"=>"GMT+13:00"
330
+        );
331
+        foreach ($arraytz as $lib => $gmt)
332
+        {
333
+            print '<option value="'.$lib.'"';
334
+            if ($selected == $lib || $selected == $gmt) print ' selected';
335
+            print '>'.$gmt.'</option>'."\n";
336
+        }
337
+        print '</select>';
338
+    }
339 339
 
340 340
 
341 341
 
342 342
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
343
-	/**
344
-	 *  Return html select list with available languages (key='en_US', value='United States' for example)
345
-	 *
346
-	 *  @param      string	$selected       Paper format pre-selected
347
-	 *  @param      string	$htmlname       Name of HTML select field
348
-	 * 	@param		string	$filter			Value to filter on code
349
-	 * 	@param		int		$showempty		Add empty value
350
-	 * 	@return		string					Return HTML output
351
-	 */
352
-	function select_paper_format($selected='',$htmlname='paperformat_id',$filter=0,$showempty=0)
353
-	{
354
-		// phpcs:enable
355
-		global $langs;
356
-
357
-		$langs->load("dict");
358
-
359
-		$sql = "SELECT code, label, width, height, unit";
360
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_paper_format";
361
-		$sql.= " WHERE active=1";
343
+    /**
344
+     *  Return html select list with available languages (key='en_US', value='United States' for example)
345
+     *
346
+     *  @param      string	$selected       Paper format pre-selected
347
+     *  @param      string	$htmlname       Name of HTML select field
348
+     * 	@param		string	$filter			Value to filter on code
349
+     * 	@param		int		$showempty		Add empty value
350
+     * 	@return		string					Return HTML output
351
+     */
352
+    function select_paper_format($selected='',$htmlname='paperformat_id',$filter=0,$showempty=0)
353
+    {
354
+        // phpcs:enable
355
+        global $langs;
356
+
357
+        $langs->load("dict");
358
+
359
+        $sql = "SELECT code, label, width, height, unit";
360
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_paper_format";
361
+        $sql.= " WHERE active=1";
362 362
         if ($filter) $sql.=" AND code LIKE '%".$this->db->escape($filter)."%'";
363 363
 
364 364
         $resql=$this->db->query($sql);
@@ -377,32 +377,32 @@  discard block
 block discarded – undo
377 377
             }
378 378
         }
379 379
         else
380
-		{
381
-			dol_print_error($this->db);
382
-			return '';
383
-		}
384
-		$out='';
385
-
386
-		$out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
387
-		if ($showempty)
388
-		{
389
-			$out.= '<option value=""';
390
-			if ($selected == '') $out.= ' selected';
391
-			$out.= '>&nbsp;</option>';
392
-		}
393
-		foreach ($paperformat as $key => $value)
394
-		{
380
+        {
381
+            dol_print_error($this->db);
382
+            return '';
383
+        }
384
+        $out='';
385
+
386
+        $out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
387
+        if ($showempty)
388
+        {
389
+            $out.= '<option value=""';
390
+            if ($selected == '') $out.= ' selected';
391
+            $out.= '>&nbsp;</option>';
392
+        }
393
+        foreach ($paperformat as $key => $value)
394
+        {
395 395
             if ($selected == $key)
396
-			{
397
-				$out.= '<option value="'.$key.'" selected>'.$value.'</option>';
398
-			}
399
-			else
400
-			{
401
-				$out.= '<option value="'.$key.'">'.$value.'</option>';
402
-			}
403
-		}
404
-		$out.= '</select>';
405
-
406
-		return $out;
407
-	}
396
+            {
397
+                $out.= '<option value="'.$key.'" selected>'.$value.'</option>';
398
+            }
399
+            else
400
+            {
401
+                $out.= '<option value="'.$key.'">'.$value.'</option>';
402
+            }
403
+        }
404
+        $out.= '</select>';
405
+
406
+        return $out;
407
+    }
408 408
 }
Please login to merge, or discard this patch.