dolibarr  17.0.3
html.form.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
5  * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
7  * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
9  * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>
10  * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
11  * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
12  * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
13  * Copyright (C) 2010-2021 Philippe Grand <philippe.grand@atoo-net.com>
14  * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
15  * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
16  * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
17  * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
18  * Copyright (C) 2014-2020 Alexandre Spangaro <aspangaro@open-dsi.fr>
19  * Copyright (C) 2018-2022 Ferran Marcet <fmarcet@2byte.es>
20  * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
21  * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
22  * Copyright (C) 2018 Christophe Battarel <christophe@altairis.fr>
23  * Copyright (C) 2018 Josep Lluis Amador <joseplluis@lliuretic.cat>
24  * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
25  *
26  * This program is free software; you can redistribute it and/or modify
27  * it under the terms of the GNU General Public License as published by
28  * the Free Software Foundation; either version 3 of the License, or
29  * (at your option) any later version.
30  *
31  * This program is distributed in the hope that it will be useful,
32  * but WITHOUT ANY WARRANTY; without even the implied warranty of
33  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34  * GNU General Public License for more details.
35  *
36  * You should have received a copy of the GNU General Public License
37  * along with this program. If not, see <https://www.gnu.org/licenses/>.
38  */
39 
53 class Form
54 {
58  public $db;
59 
63  public $error = '';
64 
68  public $errors = array();
69 
70  public $num;
71 
72  // Cache arrays
73  public $cache_types_paiements = array();
74  public $cache_conditions_paiements = array();
75  public $cache_transport_mode = array();
76  public $cache_availability = array();
77  public $cache_demand_reason = array();
78  public $cache_types_fees = array();
79  public $cache_vatrates = array();
80 
81 
87  public function __construct($db)
88  {
89  $this->db = $db;
90  }
91 
108  public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
109  {
110  global $conf, $langs;
111 
112  $ret = '';
113 
114  // TODO change for compatibility
115  if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
116  if (!empty($perm)) {
117  $tmp = explode(':', $typeofdata);
118  $ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
119  if ($fieldrequired) {
120  $ret .= '<span class="fieldrequired">';
121  }
122  if ($help) {
123  $ret .= $this->textwithpicto($langs->trans($text), $help);
124  } else {
125  $ret .= $langs->trans($text);
126  }
127  if ($fieldrequired) {
128  $ret .= '</span>';
129  }
130  $ret .= '</div>'."\n";
131  } else {
132  if ($fieldrequired) {
133  $ret .= '<span class="fieldrequired">';
134  }
135  if ($help) {
136  $ret .= $this->textwithpicto($langs->trans($text), $help);
137  } else {
138  $ret .= $langs->trans($text);
139  }
140  if ($fieldrequired) {
141  $ret .= '</span>';
142  }
143  }
144  } else {
145  if (empty($notabletag) && $perm) {
146  $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
147  }
148  if ($fieldrequired) {
149  $ret .= '<span class="fieldrequired">';
150  }
151  if ($help) {
152  $ret .= $this->textwithpicto($langs->trans($text), $help);
153  } else {
154  $ret .= $langs->trans($text);
155  }
156  if ($fieldrequired) {
157  $ret .= '</span>';
158  }
159  if (!empty($notabletag)) {
160  $ret .= ' ';
161  }
162  if (empty($notabletag) && $perm) {
163  $ret .= '</td>';
164  }
165  if (empty($notabletag) && $perm) {
166  $ret .= '<td class="right">';
167  }
168  if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
169  $ret .= '<a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&token='.newToken().'&'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
170  }
171  if (!empty($notabletag) && $notabletag == 1) {
172  $ret .= ' : ';
173  }
174  if (!empty($notabletag) && $notabletag == 3) {
175  $ret .= ' ';
176  }
177  if (empty($notabletag) && $perm) {
178  $ret .= '</td>';
179  }
180  if (empty($notabletag) && $perm) {
181  $ret .= '</tr></table>';
182  }
183  }
184 
185  return $ret;
186  }
187 
207  public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id', $gm = 'auto')
208  {
209  global $conf, $langs;
210 
211  $ret = '';
212 
213  // Check parameters
214  if (empty($typeofdata)) {
215  return 'ErrorBadParameter typeofdata is empty';
216  }
217  // Clean paramater $typeofdata
218  if ($typeofdata == 'datetime') {
219  $typeofdata = 'dayhour';
220  }
221  $reg = array();
222  if (preg_match('/^(\w+)\((\d+)\)$/', $typeofdata, $reg)) {
223  if ($reg[1] == 'varchar') {
224  $typeofdata = 'string';
225  } elseif ($reg[1] == 'int') {
226  $typeofdata = 'numeric';
227  } else {
228  return 'ErrorBadParameter '.$typeofdata;
229  }
230  }
231 
232  // When option to edit inline is activated
233  if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
234  $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
235  } else {
236  $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
237  if ($editmode) {
238  $ret .= "\n";
239  $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
240  $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
241  $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
242  $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
243  if (empty($notabletag)) {
244  $ret .= '<table class="nobordernopadding centpercent">';
245  }
246  if (empty($notabletag)) {
247  $ret .= '<tr><td>';
248  }
249  if (preg_match('/^(string|safehtmlstring|email|url)/', $typeofdata)) {
250  $tmp = explode(':', $typeofdata);
251  $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.(empty($tmp[1]) ? '' : ' size="'.$tmp[1].'"').' autofocus>';
252  } elseif (preg_match('/^(integer)/', $typeofdata)) {
253  $tmp = explode(':', $typeofdata);
254  $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
255  $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.$valuetoshow.'"'.(empty($tmp[1]) ? '' : ' size="'.$tmp[1].'"').' autofocus>';
256  } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
257  $tmp = explode(':', $typeofdata);
258  $valuetoshow = price2num($editvalue ? $editvalue : $value);
259  $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ? price($valuetoshow) : '').'"'.(empty($tmp[1]) ? '' : ' size="'.$tmp[1].'"').' autofocus>';
260  } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
261  $tmp = explode(':', $typeofdata);
262  $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
263  } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
264  $tmp = explode(':', $typeofdata);
265  $cols = (empty($tmp[2]) ? '' : $tmp[2]);
266  $morealt = '';
267  if (preg_match('/%/', $cols)) {
268  $morealt = ' style="width: '.$cols.'"';
269  $cols = '';
270  }
271 
272  $valuetoshow = ($editvalue ? $editvalue : $value);
273  $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.(empty($tmp[1]) ? '20' : $tmp[1]).'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
274  // textarea convert automatically entities chars into simple chars.
275  // So we convert & into &amp; so a string like 'a &lt; <b>b</b><br>é<br>&lt;script&gt;alert('X');&lt;script&gt;' stay a correct html and is not converted by textarea component when wysiwig is off.
276  $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
277  $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
278  $ret .= '</textarea>';
279  } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
280  $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
281  } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
282  $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
283  } elseif (preg_match('/^select;/', $typeofdata)) {
284  $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
285  $arraylist = array();
286  foreach ($arraydata as $val) {
287  $tmp = explode(':', $val);
288  $tmpkey = str_replace('|', ':', $tmp[0]);
289  $arraylist[$tmpkey] = $tmp[1];
290  }
291  $ret .= $this->selectarray($htmlname, $arraylist, $value);
292  } elseif (preg_match('/^ckeditor/', $typeofdata)) {
293  $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
294  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
295  $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), (empty($tmp[2]) ? '' : $tmp[2]), (empty($tmp[3]) ? '100' : $tmp[3]), (empty($tmp[1]) ? 'dolibarr_notes' : $tmp[1]), 'In', (empty($tmp[5]) ? 0 : $tmp[5]), (isset($tmp[8]) ? ($tmp[8] ? true : false) : true), true, (empty($tmp[6]) ? '20' : $tmp[6]), (empty($tmp[7]) ? '100' : $tmp[7]));
296  $ret .= $doleditor->Create(1);
297  }
298  if (empty($notabletag)) {
299  $ret .= '</td>';
300  }
301 
302  // Button save-cancel
303  if (empty($notabletag)) {
304  $ret .= '<td class="left">';
305  }
306  //else $ret.='<div class="clearboth"></div>';
307  $ret .= '<input type="submit" class="smallpaddingimp button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
308  if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
309  $ret .= '<br>'."\n";
310  }
311  $ret .= '<input type="submit" class="smallpaddingimp button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
312  if (empty($notabletag)) {
313  $ret .= '</td>';
314  }
315 
316  if (empty($notabletag)) {
317  $ret .= '</tr></table>'."\n";
318  }
319  $ret .= '</form>'."\n";
320  } else {
321  if (preg_match('/^(email)/', $typeofdata)) {
322  $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
323  } elseif (preg_match('/^url/', $typeofdata)) {
324  $ret .= dol_print_url($value, '_blank', 32, 1);
325  } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
326  $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
327  } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
328  $tmp = explode(':', $typeofdata);
329  $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
330  } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
331  $ret .= dol_htmlentitiesbr($value);
332  } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
333  $ret .= dol_string_onlythesehtmltags($value);
334  } elseif (preg_match('/^restricthtml/', $typeofdata)) {
335  $ret .= dol_string_onlythesehtmltags($value);
336  } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
337  $ret .= '<span class="valuedate">'.dol_print_date($value, 'day', $gm).'</span>';
338  } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
339  $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour', $gm).'</span>';
340  } elseif (preg_match('/^select;/', $typeofdata)) {
341  $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
342  $arraylist = array();
343  foreach ($arraydata as $val) {
344  $tmp = explode(':', $val);
345  $arraylist[$tmp[0]] = $tmp[1];
346  }
347  $ret .= $arraylist[$value];
348  if ($htmlname == 'fk_product_type') {
349  if ($value == 0) {
350  $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
351  } else {
352  $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
353  }
354  }
355  } elseif (preg_match('/^ckeditor/', $typeofdata)) {
356  $tmpcontent = dol_htmlentitiesbr($value);
357  if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
358  $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
359  $firstline = preg_replace('/[\n\r].*/', '', $firstline);
360  $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
361  }
362  // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
363  // clean data from some dangerous html
364  $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
365  } else {
366  $ret .= dol_escape_htmltag($value);
367  }
368 
369  if ($formatfunc && method_exists($object, $formatfunc)) {
370  $ret = $object->$formatfunc($ret);
371  }
372  }
373  }
374  return $ret;
375  }
376 
388  public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
389  {
390  global $conf, $langs, $extralanguages;
391 
392  $result = '';
393 
394  // List of extra languages
395  $arrayoflangcode = array();
396  if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
397  $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
398  }
399 
400  if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
401  if (!is_object($extralanguages)) {
402  include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
403  $extralanguages = new ExtraLanguages($this->db);
404  }
405  $extralanguages->fetch_name_extralanguages('societe');
406 
407  if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
408  return ''; // No extralang field to show
409  }
410 
411  $result .= '<!-- Widget for translation -->'."\n";
412  $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
413  $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
414  $result .= $s;
415  $result .= '</div>';
416 
417  $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
418 
419  $resultforextrlang = '';
420  foreach ($arrayoflangcode as $langcode) {
421  $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
422  if (empty($valuetoshow)) {
423  $object->fetchValuesForExtraLanguages();
424  //var_dump($object->array_languages);
425  $valuetoshow = $object->array_languages[$fieldname][$langcode];
426  }
427 
428  $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
429  $resultforextrlang .= $s;
430 
431  // TODO Use the showInputField() method of ExtraLanguages object
432  if ($typeofdata == 'textarea') {
433  $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
434  $resultforextrlang .= $valuetoshow;
435  $resultforextrlang .= '</textarea>';
436  } else {
437  $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
438  }
439  }
440  $result .= $resultforextrlang;
441 
442  $result .= '</div>';
443  $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
444  }
445 
446  return $result;
447  }
448 
462  protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
463  {
464  global $conf;
465 
466  $out = '';
467 
468  // Check parameters
469  if (preg_match('/^text/', $inputType)) {
470  $value = dol_nl2br($value);
471  } elseif (preg_match('/^numeric/', $inputType)) {
472  $value = price($value);
473  } elseif ($inputType == 'day' || $inputType == 'datepicker') {
474  $value = dol_print_date($value, 'day');
475  }
476 
477  if ($condition) {
478  $element = false;
479  $table_element = false;
480  $fk_element = false;
481  $loadmethod = false;
482  $savemethod = false;
483  $ext_element = false;
484  $button_only = false;
485  $inputOption = '';
486  $rows = '';
487  $cols = '';
488 
489  if (is_object($object)) {
490  $element = $object->element;
491  $table_element = $object->table_element;
492  $fk_element = $object->id;
493  }
494 
495  if (is_object($extObject)) {
496  $ext_element = $extObject->element;
497  }
498 
499  if (preg_match('/^(string|email|numeric)/', $inputType)) {
500  $tmp = explode(':', $inputType);
501  $inputType = $tmp[0];
502  if (!empty($tmp[1])) {
503  $inputOption = $tmp[1];
504  }
505  if (!empty($tmp[2])) {
506  $savemethod = $tmp[2];
507  }
508  $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
509  } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
510  $tmp = explode(':', $inputType);
511  $inputType = $tmp[0];
512  if (!empty($tmp[1])) {
513  $inputOption = $tmp[1];
514  }
515  if (!empty($tmp[2])) {
516  $savemethod = $tmp[2];
517  }
518 
519  $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
520  } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
521  $tmp = explode(':', $inputType);
522  $inputType = $tmp[0];
523  $loadmethod = $tmp[1];
524  if (!empty($tmp[2])) {
525  $savemethod = $tmp[2];
526  }
527  if (!empty($tmp[3])) {
528  $button_only = true;
529  }
530  } elseif (preg_match('/^textarea/', $inputType)) {
531  $tmp = explode(':', $inputType);
532  $inputType = $tmp[0];
533  $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
534  $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
535  } elseif (preg_match('/^ckeditor/', $inputType)) {
536  $tmp = explode(':', $inputType);
537  $inputType = $tmp[0];
538  $toolbar = $tmp[1];
539  if (!empty($tmp[2])) {
540  $width = $tmp[2];
541  }
542  if (!empty($tmp[3])) {
543  $heigth = $tmp[3];
544  }
545  if (!empty($tmp[4])) {
546  $savemethod = $tmp[4];
547  }
548 
549  if (isModEnabled('fckeditor')) {
550  $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
551  } else {
552  $inputType = 'textarea';
553  }
554  }
555 
556  $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
557  $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
558  $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
559  $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
560  if (!empty($savemethod)) {
561  $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
562  }
563  if (!empty($ext_element)) {
564  $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
565  }
566  if (!empty($custommsg)) {
567  if (is_array($custommsg)) {
568  if (!empty($custommsg['success'])) {
569  $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
570  }
571  if (!empty($custommsg['error'])) {
572  $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
573  }
574  } else {
575  $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
576  }
577  }
578  if ($inputType == 'textarea') {
579  $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
580  $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
581  }
582  $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
583  $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
584  } else {
585  $out = $value;
586  }
587 
588  return $out;
589  }
590 
609  public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
610  {
611  if ($incbefore) {
612  $text = $incbefore.$text;
613  }
614  if (!$htmltext) {
615  return $text;
616  }
617  $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
618 
619  $tag = 'td';
620  if ($notabs == 2) {
621  $tag = 'div';
622  }
623  if ($notabs == 3) {
624  $tag = 'span';
625  }
626  // Sanitize tooltip
627  $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
628 
629  $extrastyle = '';
630  if ($direction < 0) {
631  $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
632  $extrastyle = 'padding: 0px; padding-left: 3px;';
633  }
634  if ($direction > 0) {
635  $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
636  $extrastyle = 'padding: 0px; padding-right: 3px;';
637  }
638 
639  $classfortooltip = 'classfortooltip';
640 
641  $s = '';
642  $textfordialog = '';
643 
644  if ($tooltiptrigger == '') {
645  $htmltext = str_replace('"', '&quot;', $htmltext);
646  } else {
647  $classfortooltip = 'classfortooltiponclick';
648  $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
649  }
650  if ($tooltipon == 2 || $tooltipon == 3) {
651  $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
652  if ($tooltiptrigger == '') {
653  $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
654  } else {
655  $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
656  }
657  } else {
658  $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
659  }
660  if ($tooltipon == 1 || $tooltipon == 3) {
661  $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
662  if ($tooltiptrigger == '') {
663  $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
664  } else {
665  $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
666  }
667  } else {
668  $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
669  }
670  if (empty($notabs)) {
671  $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
672  } elseif ($notabs == 2) {
673  $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
674  }
675  // Define value if value is before
676  if ($direction < 0) {
677  $s .= '<'.$tag.$paramfortooltipimg;
678  if ($tag == 'td') {
679  $s .= ' class="valigntop" width="14"';
680  }
681  $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
682  }
683  // Use another method to help avoid having a space in value in order to use this value with jquery
684  // Define label
685  if ((string) $text != '') {
686  $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
687  }
688  // Define value if value is after
689  if ($direction > 0) {
690  $s .= '<'.$tag.$paramfortooltipimg;
691  if ($tag == 'td') {
692  $s .= ' class="valignmiddle" width="14"';
693  }
694  $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
695  }
696  if (empty($notabs)) {
697  $s .= '</tr></table>';
698  } elseif ($notabs == 2) {
699  $s .= '</div>';
700  }
701 
702  return $s;
703  }
704 
719  public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
720  {
721  global $conf, $langs;
722 
723  //For backwards compatibility
724  if ($type == '0') {
725  $type = 'info';
726  } elseif ($type == '1') {
727  $type = 'help';
728  }
729 
730  if (preg_match('/onsmartphone$/', $tooltiptrigger) && empty($conf->dol_no_mouse_hover)) {
731  $tooltiptrigger = preg_replace('/^.*onsmartphone$/', '', $tooltiptrigger);
732  }
733 
734  $alt = '';
735  if ($tooltiptrigger) {
736  $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
737  }
738 
739  // If info or help with no javascript, show only text
740  if (empty($conf->use_javascript_ajax)) {
741  if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
742  return $text;
743  } else {
744  $alt = $htmltext;
745  $htmltext = '';
746  }
747  }
748 
749  // If info or help with smartphone, show only text (tooltip hover can't works)
750  if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
751  if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
752  return $text;
753  }
754  }
755  // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
756  //if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
757  //{
758  //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
759  //}
760 
761  $img = '';
762  if ($type == 'info') {
763  $img = img_help(0, $alt);
764  } elseif ($type == 'help') {
765  $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
766  } elseif ($type == 'helpclickable') {
767  $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
768  } elseif ($type == 'superadmin') {
769  $img = img_picto($alt, 'redstar');
770  } elseif ($type == 'admin') {
771  $img = img_picto($alt, 'star');
772  } elseif ($type == 'warning') {
773  $img = img_warning($alt);
774  } elseif ($type != 'none') {
775  $img = img_picto($alt, $type); // $type can be an image path
776  }
777 
778  return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
779  }
780 
791  public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
792  {
793  global $conf, $langs, $hookmanager;
794 
795 
796  $disabled = 0;
797  $ret = '<div class="centpercent center">';
798  $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
799 
800  // 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.
801  $parameters = array();
802  $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
803  // check if there is a mass action
804  if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
805  return;
806  }
807  if (empty($reshook)) {
808  $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
809  foreach ($arrayofaction as $code => $label) {
810  $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
811  }
812  }
813  $ret .= $hookmanager->resPrint;
814 
815  $ret .= '</select>';
816 
817  if (empty($conf->dol_optimize_smallscreen)) {
818  $ret .= ajax_combobox('.'.$name.'select');
819  }
820 
821  // 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
822  $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.
823  $ret .= '<input type="submit" disabled name="confirmmassaction"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display: none"').' class="button smallpaddingimp'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'confirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
824  $ret .= '</div>';
825 
826  if (!empty($conf->use_javascript_ajax)) {
827  $ret .= '<!-- JS CODE TO ENABLE mass action select -->
828  <script>
829  function initCheckForSelect(mode, name, cssclass) /* mode is 0 during init of page or click all, 1 when we click on 1 checkboxi, "name" refers to the class of the massaction button, "cssclass" to the class of the checkfor select boxes */
830  {
831  atleastoneselected=0;
832  jQuery("."+cssclass).each(function( index ) {
833  /* console.log( index + ": " + $( this ).text() ); */
834  if ($(this).is(\':checked\')) atleastoneselected++;
835  });
836 
837  console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
838 
839  if (atleastoneselected || '.$alwaysvisible.')
840  {
841  jQuery("."+name).show();
842  '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
843  '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
844  }
845  else
846  {
847  jQuery("."+name).hide();
848  jQuery("."+name+"other").hide();
849  }
850  }
851 
852  jQuery(document).ready(function () {
853  initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
854  jQuery(".' . $cssclass.'").click(function() {
855  initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
856  });
857  jQuery(".' . $name.'select").change(function() {
858  var massaction = $( this ).val();
859  var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
860  if (massaction == "builddoc")
861  {
862  urlform = urlform + "#show_files";
863  }
864  $( this ).closest("form").attr("action", urlform);
865  console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
866  /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
867  if ($(this).val() != \'0\')
868  {
869  jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
870  jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
871  jQuery(".' . $name.'"+massaction).show();
872  }
873  else
874  {
875  jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
876  jQuery(".' . $name.'other").hide(); /* To disable any div open */
877  }
878  });
879  });
880  </script>
881  ';
882  }
883 
884  return $ret;
885  }
886 
887  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
904  public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array(), $hideflags = 0)
905  {
906  // phpcs:enable
907  global $conf, $langs, $mysoc;
908 
909  $langs->load("dict");
910 
911  $out = '';
912  $countryArray = array();
913  $favorite = array();
914  $label = array();
915  $atleastonefavorite = 0;
916 
917  $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
918  $sql .= " FROM ".$this->db->prefix()."c_country";
919  $sql .= " WHERE active > 0";
920  //$sql.= " ORDER BY code ASC";
921 
922  dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
923  $resql = $this->db->query($sql);
924  if ($resql) {
925  $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
926  $num = $this->db->num_rows($resql);
927  $i = 0;
928  if ($num) {
929  while ($i < $num) {
930  $obj = $this->db->fetch_object($resql);
931 
932  $countryArray[$i]['rowid'] = $obj->rowid;
933  $countryArray[$i]['code_iso'] = $obj->code_iso;
934  $countryArray[$i]['code_iso3'] = $obj->code_iso3;
935  $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 : ''));
936  $countryArray[$i]['favorite'] = $obj->favorite;
937  $countryArray[$i]['eec'] = $obj->eec;
938  $favorite[$i] = $obj->favorite;
939  $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
940  $i++;
941  }
942 
943  if (empty($disablefavorites)) {
944  $array1_sort_order = SORT_DESC;
945  $array2_sort_order = SORT_ASC;
946  array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
947  } else {
948  $countryArray = dol_sort_array($countryArray, 'label');
949  }
950 
951  if ($showempty) {
952  if (is_numeric($showempty)) {
953  $out .= '<option value="">&nbsp;</option>'."\n";
954  } else {
955  $out .= '<option value="">'.$langs->trans($showempty).'</option>'."\n";
956  }
957  }
958 
959  if ($addspecialentries) { // Add dedicated entries for groups of countries
960  //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
961  $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
962  $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
963  if ($mysoc->isInEEC()) {
964  $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
965  }
966  $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
967  $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
968  }
969 
970  foreach ($countryArray as $row) {
971  //if (empty($showempty) && empty($row['rowid'])) continue;
972  if (empty($row['rowid'])) {
973  continue;
974  }
975  if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
976  continue; // exclude some countries
977  }
978 
979  if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
980  $atleastonefavorite++;
981  }
982  if (empty($row['favorite']) && $atleastonefavorite) {
983  $atleastonefavorite = 0;
984  $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
985  }
986 
987  $labeltoshow = '';
988  if ($row['label']) {
989  $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
990  } else {
991  $labeltoshow .= '&nbsp;';
992  }
993  if ($row['code_iso']) {
994  $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
995  if (empty($hideflags)) {
996  $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
997  $labeltoshow = $tmpflag.' '.$labeltoshow;
998  }
999  }
1000 
1001  if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
1002  $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" selected data-html="'.dol_escape_htmltag($labeltoshow).'" data-eec="'.((int) $row['eec']).'">';
1003  } else {
1004  $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" data-html="'.dol_escape_htmltag($labeltoshow).'" data-eec="'.((int) $row['eec']).'">';
1005  }
1006  $out .= $labeltoshow;
1007  $out .= '</option>'."\n";
1008  }
1009  }
1010  $out .= '</select>';
1011  } else {
1012  dol_print_error($this->db);
1013  }
1014 
1015  // Make select dynamic
1016  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1017  $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
1018 
1019  return $out;
1020  }
1021 
1022  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1036  public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
1037  {
1038  // phpcs:enable
1039  global $conf, $langs;
1040 
1041  $langs->load("dict");
1042 
1043  $out = '';
1044  $moreattrib = '';
1045  $incotermArray = array();
1046 
1047  $sql = "SELECT rowid, code";
1048  $sql .= " FROM ".$this->db->prefix()."c_incoterms";
1049  $sql .= " WHERE active > 0";
1050  $sql .= " ORDER BY code ASC";
1051 
1052  dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
1053  $resql = $this->db->query($sql);
1054  if ($resql) {
1055  if ($conf->use_javascript_ajax && !$forcecombo) {
1056  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1057  $out .= ajax_combobox($htmlname, $events);
1058  }
1059 
1060  if (!empty($page)) {
1061  $out .= '<form method="post" action="'.$page.'">';
1062  $out .= '<input type="hidden" name="action" value="set_incoterms">';
1063  $out .= '<input type="hidden" name="token" value="'.newToken().'">';
1064  }
1065 
1066  $out .= '<select id="'.$htmlname.'" class="flat selectincoterm width75" name="'.$htmlname.'" '.$htmloption.'>';
1067  $out .= '<option value="0">&nbsp;</option>';
1068  $num = $this->db->num_rows($resql);
1069  $i = 0;
1070  if ($num) {
1071  while ($i < $num) {
1072  $obj = $this->db->fetch_object($resql);
1073  $incotermArray[$i]['rowid'] = $obj->rowid;
1074  $incotermArray[$i]['code'] = $obj->code;
1075  $i++;
1076  }
1077 
1078  foreach ($incotermArray as $row) {
1079  if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
1080  $out .= '<option value="'.$row['rowid'].'" selected>';
1081  } else {
1082  $out .= '<option value="'.$row['rowid'].'">';
1083  }
1084 
1085  if ($row['code']) {
1086  $out .= $row['code'];
1087  }
1088 
1089  $out .= '</option>';
1090  }
1091  }
1092  $out .= '</select>';
1093 
1094  if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
1095  $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT.'/core/ajax/locationincoterms.php')."\n";
1096  $moreattrib .= ' autocomplete="off"';
1097  }
1098  $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="'.$location_incoterms.'">'."\n";
1099 
1100  if (!empty($page)) {
1101  $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="'.$langs->trans("Modify").'"></form>';
1102  }
1103  } else {
1104  dol_print_error($this->db);
1105  }
1106 
1107  return $out;
1108  }
1109 
1110  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1122  public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
1123  {
1124  // phpcs:enable
1125  global $langs, $conf;
1126 
1127  // If product & services are enabled or both disabled.
1128  if ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
1129  || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
1130  if (empty($hidetext)) {
1131  print $langs->trans("Type").': ';
1132  }
1133  print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
1134  if ($showempty) {
1135  print '<option value="-1"';
1136  if ($selected == -1) {
1137  print ' selected';
1138  }
1139  print '>&nbsp;</option>';
1140  }
1141 
1142  print '<option value="0"';
1143  if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
1144  print ' selected';
1145  }
1146  print '>'.$langs->trans("Product");
1147 
1148  print '<option value="1"';
1149  if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
1150  print ' selected';
1151  }
1152  print '>'.$langs->trans("Service");
1153 
1154  print '</select>';
1155  print ajax_combobox('select_'.$htmlname);
1156  //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1157  }
1158  if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
1159  print $langs->trans("Service");
1160  print '<input type="hidden" name="'.$htmlname.'" value="1">';
1161  }
1162  if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
1163  print $langs->trans("Product");
1164  print '<input type="hidden" name="'.$htmlname.'" value="0">';
1165  }
1166  if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
1167  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
1168  }
1169  }
1170 
1171  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1177  public function load_cache_types_fees()
1178  {
1179  // phpcs:enable
1180  global $langs;
1181 
1182  $num = count($this->cache_types_fees);
1183  if ($num > 0) {
1184  return 0; // Cache already loaded
1185  }
1186 
1187  dol_syslog(__METHOD__, LOG_DEBUG);
1188 
1189  $langs->load("trips");
1190 
1191  $sql = "SELECT c.code, c.label";
1192  $sql .= " FROM ".$this->db->prefix()."c_type_fees as c";
1193  $sql .= " WHERE active > 0";
1194 
1195  $resql = $this->db->query($sql);
1196  if ($resql) {
1197  $num = $this->db->num_rows($resql);
1198  $i = 0;
1199 
1200  while ($i < $num) {
1201  $obj = $this->db->fetch_object($resql);
1202 
1203  // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
1204  $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
1205  $this->cache_types_fees[$obj->code] = $label;
1206  $i++;
1207  }
1208 
1209  asort($this->cache_types_fees);
1210 
1211  return $num;
1212  } else {
1213  dol_print_error($this->db);
1214  return -1;
1215  }
1216  }
1217 
1218  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1227  public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
1228  {
1229  // phpcs:enable
1230  global $user, $langs;
1231 
1232  dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
1233 
1234  $this->load_cache_types_fees();
1235 
1236  print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
1237  if ($showempty) {
1238  print '<option value="-1"';
1239  if ($selected == -1) {
1240  print ' selected';
1241  }
1242  print '>&nbsp;</option>';
1243  }
1244 
1245  foreach ($this->cache_types_fees as $key => $value) {
1246  print '<option value="'.$key.'"';
1247  if ($key == $selected) {
1248  print ' selected';
1249  }
1250  print '>';
1251  print $value;
1252  print '</option>';
1253  }
1254 
1255  print '</select>';
1256  if ($user->admin) {
1257  print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
1258  }
1259  }
1260 
1261 
1262  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1284  public 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, $excludeids = array(), $showcode = 0)
1285  {
1286  // phpcs:enable
1287  global $conf, $user, $langs;
1288 
1289  $out = '';
1290 
1291  if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
1292  if (is_null($ajaxoptions)) {
1293  $ajaxoptions = array();
1294  }
1295 
1296  require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1297 
1298  // No immediate load of all database
1299  $placeholder = '';
1300  if ($selected && empty($selected_input_value)) {
1301  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1302  $societetmp = new Societe($this->db);
1303  $societetmp->fetch($selected);
1304  $selected_input_value = $societetmp->name;
1305  unset($societetmp);
1306  }
1307 
1308  // mode 1
1309  $urloption = 'htmlname='.urlencode(str_replace('.', '_', $htmlname)).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '').($showcode ? '&showcode='.urlencode($showcode) : '');
1310 
1311  $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
1312  if (empty($hidelabel)) {
1313  print $langs->trans("RefOrLabel").' : ';
1314  } elseif ($hidelabel > 1) {
1315  $placeholder = $langs->trans("RefOrLabel");
1316  if ($hidelabel == 2) {
1317  $out .= img_picto($langs->trans("Search"), 'search');
1318  }
1319  }
1320  $out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '').' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1321  if ($hidelabel == 3) {
1322  $out .= img_picto($langs->trans("Search"), 'search');
1323  }
1324 
1325  $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1326  } else {
1327  // Immediate load of all database
1328  $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
1329  }
1330 
1331  return $out;
1332  }
1333 
1334  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1356  public 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, $excludeids = array(), $showcode = 0)
1357  {
1358  // phpcs:enable
1359  global $conf, $user, $langs;
1360  global $hookmanager;
1361 
1362  $out = '';
1363  $num = 0;
1364  $outarray = array();
1365 
1366  if ($selected === '') {
1367  $selected = array();
1368  } elseif (!is_array($selected)) {
1369  $selected = array($selected);
1370  }
1371 
1372  // Clean $filter that may contains sql conditions so sql code
1373  if (function_exists('testSqlAndScriptInject')) {
1374  if (testSqlAndScriptInject($filter, 3) > 0) {
1375  $filter = '';
1376  }
1377  }
1378 
1379  // We search companies
1380  $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
1381  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
1382  $sql .= ", s.address, s.zip, s.town";
1383  $sql .= ", dictp.code as country_code";
1384  }
1385  $sql .= " FROM ".$this->db->prefix()."societe as s";
1386  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
1387  $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as dictp ON dictp.rowid = s.fk_pays";
1388  }
1389  if (empty($user->rights->societe->client->voir) && !$user->socid) {
1390  $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
1391  }
1392  $sql .= " WHERE s.entity IN (".getEntity('societe').")";
1393  if (!empty($user->socid)) {
1394  $sql .= " AND s.rowid = ".((int) $user->socid);
1395  }
1396  if ($filter) {
1397  $sql .= " AND (".$filter.")";
1398  }
1399  if (empty($user->rights->societe->client->voir) && !$user->socid) {
1400  $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
1401  }
1402  if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
1403  $sql .= " AND s.status <> 0";
1404  }
1405  if (!empty($excludeids)) {
1406  $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
1407  }
1408  // Add where from hooks
1409  $parameters = array();
1410  $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
1411  $sql .= $hookmanager->resPrint;
1412  // Add criteria
1413  if ($filterkey && $filterkey != '') {
1414  $sql .= " AND (";
1415  $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
1416  // For natural search
1417  $scrit = explode(' ', $filterkey);
1418  $i = 0;
1419  if (count($scrit) > 1) {
1420  $sql .= "(";
1421  }
1422  foreach ($scrit as $crit) {
1423  if ($i > 0) {
1424  $sql .= " AND ";
1425  }
1426  $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
1427  $i++;
1428  }
1429  if (count($scrit) > 1) {
1430  $sql .= ")";
1431  }
1432  if (isModEnabled('barcode')) {
1433  $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1434  }
1435  $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1436  $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1437  $sql .= ")";
1438  }
1439  $sql .= $this->db->order("nom", "ASC");
1440  $sql .= $this->db->plimit($limit, 0);
1441 
1442  // Build output string
1443  dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
1444  $resql = $this->db->query($sql);
1445  if ($resql) {
1446  if (!$forcecombo) {
1447  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1448  $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
1449  }
1450 
1451  // Construct $out and $outarray
1452  $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
1453 
1454  $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
1455  if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
1456  // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
1457  //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
1458  if ($showempty && !is_numeric($showempty)) {
1459  $textifempty = $langs->trans($showempty);
1460  } else {
1461  $textifempty .= $langs->trans("All");
1462  }
1463  }
1464  if ($showempty) {
1465  $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
1466  }
1467 
1468  $companytemp = new Societe($this->db);
1469 
1470  $num = $this->db->num_rows($resql);
1471  $i = 0;
1472  if ($num) {
1473  while ($i < $num) {
1474  $obj = $this->db->fetch_object($resql);
1475  $label = '';
1476  if ($showcode || !empty($conf->global->SOCIETE_ADD_REF_IN_LIST)) {
1477  if (($obj->client) && (!empty($obj->code_client))) {
1478  $label = $obj->code_client.' - ';
1479  }
1480  if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
1481  $label .= $obj->code_fournisseur.' - ';
1482  }
1483  $label .= ' '.$obj->name;
1484  } else {
1485  $label = $obj->name;
1486  }
1487 
1488  if (!empty($obj->name_alias)) {
1489  $label .= ' ('.$obj->name_alias.')';
1490  }
1491 
1492  if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
1493  $label .= ' - '.$obj->tva_intra;
1494  }
1495 
1496  $labelhtml = $label;
1497 
1498  if ($showtype) {
1499  $companytemp->id = $obj->rowid;
1500  $companytemp->client = $obj->client;
1501  $companytemp->fournisseur = $obj->fournisseur;
1502  $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
1503  if ($tmptype) {
1504  $labelhtml .= ' '.$tmptype;
1505  }
1506 
1507  if ($obj->client || $obj->fournisseur) {
1508  $label .= ' (';
1509  }
1510  if ($obj->client == 1 || $obj->client == 3) {
1511  $label .= $langs->trans("Customer");
1512  }
1513  if ($obj->client == 2 || $obj->client == 3) {
1514  $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
1515  }
1516  if ($obj->fournisseur) {
1517  $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
1518  }
1519  if ($obj->client || $obj->fournisseur) {
1520  $label .= ')';
1521  }
1522  }
1523 
1524  if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
1525  $s = ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
1526  if (!empty($obj->country_code)) {
1527  $s .= ', '.$langs->trans('Country'.$obj->country_code);
1528  }
1529  $label .= $s;
1530  $labelhtml .= $s;
1531  }
1532 
1533  if (empty($outputmode)) {
1534  if (in_array($obj->rowid, $selected)) {
1535  $out .= '<option value="'.$obj->rowid.'" selected data-html="'.dol_escape_htmltag($labelhtml).'">'.$label.'</option>';
1536  } else {
1537  $out .= '<option value="'.$obj->rowid.'" data-html="'.dol_escape_htmltag($labelhtml).'">'.$label.'</option>';
1538  }
1539  } else {
1540  array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label, 'labelhtml'=>$labelhtml));
1541  }
1542 
1543  $i++;
1544  if (($i % 10) == 0) {
1545  $out .= "\n";
1546  }
1547  }
1548  }
1549  $out .= '</select>'."\n";
1550  } else {
1551  dol_print_error($this->db);
1552  }
1553 
1554  $this->result = array('nbofthirdparties'=>$num);
1555 
1556  if ($outputmode) {
1557  return $outarray;
1558  }
1559  return $out;
1560  }
1561 
1562 
1563  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1574  public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
1575  {
1576  // phpcs:enable
1577  global $langs, $conf;
1578 
1579  // On recherche les remises
1580  $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1581  $sql .= " re.description, re.fk_facture_source";
1582  $sql .= " FROM ".$this->db->prefix()."societe_remise_except as re";
1583  $sql .= " WHERE re.fk_soc = ".(int) $socid;
1584  $sql .= " AND re.entity = ".$conf->entity;
1585  if ($filter) {
1586  $sql .= " AND ".$filter;
1587  }
1588  $sql .= " ORDER BY re.description ASC";
1589 
1590  dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
1591  $resql = $this->db->query($sql);
1592  if ($resql) {
1593  print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
1594  $num = $this->db->num_rows($resql);
1595 
1596  $qualifiedlines = $num;
1597 
1598  $i = 0;
1599  if ($num) {
1600  print '<option value="0">&nbsp;</option>';
1601  while ($i < $num) {
1602  $obj = $this->db->fetch_object($resql);
1603  $desc = dol_trunc($obj->description, 40);
1604  if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
1605  $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
1606  }
1607  if (preg_match('/\(DEPOSIT\)/', $desc)) {
1608  $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
1609  }
1610  if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
1611  $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
1612  }
1613  if (preg_match('/\(EXCESS PAID\)/', $desc)) {
1614  $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
1615  }
1616 
1617  $selectstring = '';
1618  if ($selected > 0 && $selected == $obj->rowid) {
1619  $selectstring = ' selected';
1620  }
1621 
1622  $disabled = '';
1623  if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
1624  $qualifiedlines--;
1625  $disabled = ' disabled';
1626  }
1627 
1628  if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
1629  $tmpfac = new Facture($this->db);
1630  if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
1631  $desc = $desc.' - '.$tmpfac->ref;
1632  }
1633  }
1634 
1635  print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
1636  $i++;
1637  }
1638  }
1639  print '</select>';
1640  print ajax_combobox('select_'.$htmlname);
1641 
1642  return $qualifiedlines;
1643  } else {
1644  dol_print_error($this->db);
1645  return -1;
1646  }
1647  }
1648 
1649  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1670  public function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
1671  {
1672  // phpcs:enable
1673  print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
1674  return $this->num;
1675  }
1676 
1701  public function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0)
1702  {
1703  global $conf, $langs, $hookmanager, $action;
1704 
1705  $langs->load('companies');
1706 
1707  if (empty($htmlid)) {
1708  $htmlid = $htmlname;
1709  }
1710  $num = 0;
1711 
1712  if ($selected === '') {
1713  $selected = array();
1714  } elseif (!is_array($selected)) {
1715  $selected = array($selected);
1716  }
1717  $out = '';
1718 
1719  if (!is_object($hookmanager)) {
1720  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1721  $hookmanager = new HookManager($this->db);
1722  }
1723 
1724  // We search third parties
1725  $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste, sp.email, sp.phone, sp.phone_perso, sp.phone_mobile, sp.town AS contact_town";
1726  if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
1727  $sql .= ", s.nom as company, s.town AS company_town";
1728  }
1729  $sql .= " FROM ".$this->db->prefix()."socpeople as sp";
1730  if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
1731  $sql .= " LEFT OUTER JOIN ".$this->db->prefix()."societe as s ON s.rowid=sp.fk_soc";
1732  }
1733  $sql .= " WHERE sp.entity IN (".getEntity('contact').")";
1734  if ($socid > 0 || $socid == -1) {
1735  $sql .= " AND sp.fk_soc = ".((int) $socid);
1736  }
1737  if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
1738  $sql .= " AND sp.statut <> 0";
1739  }
1740  // Add where from hooks
1741  $parameters = array();
1742  $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
1743  $sql .= $hookmanager->resPrint;
1744  $sql .= " ORDER BY sp.lastname ASC";
1745 
1746  dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
1747  $resql = $this->db->query($sql);
1748  if ($resql) {
1749  $num = $this->db->num_rows($resql);
1750 
1751  if ($htmlname != 'none' && !$options_only) {
1752  $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
1753  }
1754 
1755  if ($showempty && ! is_numeric($showempty)) {
1756  $textforempty = $showempty;
1757  $out .= '<option class="optiongrey" value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>'.$textforempty.'</option>';
1758  } else {
1759  if (($showempty == 1 || ($showempty == 3 && $num > 1)) && ! $multiple) {
1760  $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
1761  }
1762  if ($showempty == 2) {
1763  $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
1764  }
1765  }
1766 
1767  $i = 0;
1768  if ($num) {
1769  include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1770  $contactstatic = new Contact($this->db);
1771 
1772  while ($i < $num) {
1773  $obj = $this->db->fetch_object($resql);
1774 
1775  // Set email (or phones) and town extended infos
1776  $extendedInfos = '';
1777  if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
1778  $extendedInfos = array();
1779  $email = trim($obj->email);
1780  if (!empty($email)) {
1781  $extendedInfos[] = $email;
1782  } else {
1783  $phone = trim($obj->phone);
1784  $phone_perso = trim($obj->phone_perso);
1785  $phone_mobile = trim($obj->phone_mobile);
1786  if (!empty($phone)) {
1787  $extendedInfos[] = $phone;
1788  }
1789  if (!empty($phone_perso)) {
1790  $extendedInfos[] = $phone_perso;
1791  }
1792  if (!empty($phone_mobile)) {
1793  $extendedInfos[] = $phone_mobile;
1794  }
1795  }
1796  $contact_town = trim($obj->contact_town);
1797  $company_town = trim($obj->company_town);
1798  if (!empty($contact_town)) {
1799  $extendedInfos[] = $contact_town;
1800  } elseif (!empty($company_town)) {
1801  $extendedInfos[] = $company_town;
1802  }
1803  $extendedInfos = implode(' - ', $extendedInfos);
1804  if (!empty($extendedInfos)) {
1805  $extendedInfos = ' - '.$extendedInfos;
1806  }
1807  }
1808 
1809  $contactstatic->id = $obj->rowid;
1810  $contactstatic->lastname = $obj->lastname;
1811  $contactstatic->firstname = $obj->firstname;
1812  if ($obj->statut == 1) {
1813  if ($htmlname != 'none') {
1814  $disabled = 0;
1815  if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
1816  $disabled = 1;
1817  }
1818  if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
1819  $disabled = 1;
1820  }
1821  if (!empty($selected) && in_array($obj->rowid, $selected)) {
1822  $out .= '<option value="'.$obj->rowid.'"';
1823  if ($disabled) {
1824  $out .= ' disabled';
1825  }
1826  $out .= ' selected>';
1827  $out .= $contactstatic->getFullName($langs).$extendedInfos;
1828  if ($showfunction && $obj->poste) {
1829  $out .= ' ('.$obj->poste.')';
1830  }
1831  if (($showsoc > 0) && $obj->company) {
1832  $out .= ' - ('.$obj->company.')';
1833  }
1834  $out .= '</option>';
1835  } else {
1836  $out .= '<option value="'.$obj->rowid.'"';
1837  if ($disabled) {
1838  $out .= ' disabled';
1839  }
1840  $out .= '>';
1841  $out .= $contactstatic->getFullName($langs).$extendedInfos;
1842  if ($showfunction && $obj->poste) {
1843  $out .= ' ('.$obj->poste.')';
1844  }
1845  if (($showsoc > 0) && $obj->company) {
1846  $out .= ' - ('.$obj->company.')';
1847  }
1848  $out .= '</option>';
1849  }
1850  } else {
1851  if (in_array($obj->rowid, $selected)) {
1852  $out .= $contactstatic->getFullName($langs).$extendedInfos;
1853  if ($showfunction && $obj->poste) {
1854  $out .= ' ('.$obj->poste.')';
1855  }
1856  if (($showsoc > 0) && $obj->company) {
1857  $out .= ' - ('.$obj->company.')';
1858  }
1859  }
1860  }
1861  }
1862  $i++;
1863  }
1864  } else {
1865  $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
1866  $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
1867  $out .= $labeltoshow;
1868  $out .= '</option>';
1869  }
1870 
1871  $parameters = array(
1872  'socid'=>$socid,
1873  'htmlname'=>$htmlname,
1874  'resql'=>$resql,
1875  'out'=>&$out,
1876  'showfunction'=>$showfunction,
1877  'showsoc'=>$showsoc,
1878  );
1879 
1880  $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1881 
1882  if ($htmlname != 'none' && !$options_only) {
1883  $out .= '</select>';
1884  }
1885 
1886  if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
1887  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1888  $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
1889  }
1890 
1891  $this->num = $num;
1892  return $out;
1893  } else {
1894  dol_print_error($this->db);
1895  return -1;
1896  }
1897  }
1898 
1899  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1915  public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
1916  {
1917  // phpcs:enable
1918  print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
1919  }
1920 
1921  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1946  public 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 = '', $notdisabled = 0, $outputmode = 0, $multiple = false, $forcecombo = 0)
1947  {
1948  // phpcs:enable
1949  global $conf, $user, $langs, $hookmanager;
1950  global $action;
1951 
1952  // If no preselected user defined, we take current user
1953  if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
1954  $selected = $user->id;
1955  }
1956 
1957  if ($selected === '') {
1958  $selected = array();
1959  } elseif (!is_array($selected)) {
1960  $selected = array($selected);
1961  }
1962 
1963  $excludeUsers = null;
1964  $includeUsers = null;
1965 
1966  // Permettre l'exclusion d'utilisateurs
1967  if (is_array($exclude)) {
1968  $excludeUsers = implode(",", $exclude);
1969  }
1970  // Permettre l'inclusion d'utilisateurs
1971  if (is_array($include)) {
1972  $includeUsers = implode(",", $include);
1973  } elseif ($include == 'hierarchy') {
1974  // Build list includeUsers to have only hierarchy
1975  $includeUsers = implode(",", $user->getAllChildIds(0));
1976  } elseif ($include == 'hierarchyme') {
1977  // Build list includeUsers to have only hierarchy and current user
1978  $includeUsers = implode(",", $user->getAllChildIds(1));
1979  }
1980 
1981  $out = '';
1982  $outarray = array();
1983 
1984  // Forge request to select users
1985  $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
1986  if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
1987  $sql .= ", e.label";
1988  }
1989  $sql .= " FROM ".$this->db->prefix()."user as u";
1990  if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
1991  $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid = u.entity";
1992  if ($force_entity) {
1993  $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
1994  } else {
1995  $sql .= " WHERE u.entity IS NOT NULL";
1996  }
1997  } else {
1998  if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1999  $sql .= " LEFT JOIN ".$this->db->prefix()."usergroup_user as ug";
2000  $sql .= " ON ug.fk_user = u.rowid";
2001  $sql .= " WHERE ug.entity = ".$conf->entity;
2002  } else {
2003  $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
2004  }
2005  }
2006  if (!empty($user->socid)) {
2007  $sql .= " AND u.fk_soc = ".((int) $user->socid);
2008  }
2009  if (is_array($exclude) && $excludeUsers) {
2010  $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
2011  }
2012  if ($includeUsers) {
2013  $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
2014  }
2015  if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $notdisabled) {
2016  $sql .= " AND u.statut <> 0";
2017  }
2018  if (!empty($morefilter)) {
2019  $sql .= " ".$morefilter;
2020  }
2021 
2022  //Add hook to filter on user (for exemple on usergroup define in custom modules)
2023  $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
2024  if (!empty($reshook)) {
2025  $sql .= $hookmanager->resPrint;
2026  }
2027 
2028  if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
2029  $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
2030  } else {
2031  $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
2032  }
2033 
2034  dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
2035 
2036  $resql = $this->db->query($sql);
2037  if ($resql) {
2038  $num = $this->db->num_rows($resql);
2039  $i = 0;
2040  if ($num) {
2041  // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
2042  $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
2043  if ($show_empty && !$multiple) {
2044  $textforempty = ' ';
2045  if (!empty($conf->use_javascript_ajax)) {
2046  $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
2047  }
2048  if (!is_numeric($show_empty)) {
2049  $textforempty = $show_empty;
2050  }
2051  $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
2052  }
2053  if ($show_every) {
2054  $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
2055  }
2056 
2057  $userstatic = new User($this->db);
2058 
2059  while ($i < $num) {
2060  $obj = $this->db->fetch_object($resql);
2061 
2062  $userstatic->id = $obj->rowid;
2063  $userstatic->lastname = $obj->lastname;
2064  $userstatic->firstname = $obj->firstname;
2065  $userstatic->photo = $obj->photo;
2066  $userstatic->statut = $obj->status;
2067  $userstatic->entity = $obj->entity;
2068  $userstatic->admin = $obj->admin;
2069 
2070  $disableline = '';
2071  if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
2072  $disableline = ($enableonlytext ? $enableonlytext : '1');
2073  }
2074 
2075  $labeltoshow = ''; $labeltoshowhtml = '';
2076 
2077  // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
2078  $fullNameMode = 0;
2079  if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
2080  $fullNameMode = 1; //Firstname+lastname
2081  }
2082  $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
2083  $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
2084  if (empty($obj->firstname) && empty($obj->lastname)) {
2085  $labeltoshow .= $obj->login;
2086  $labeltoshowhtml .= $obj->login;
2087  }
2088 
2089  // Complete name with a more info string like: ' (info1 - info2 - ...)'
2090  $moreinfo = ''; $moreinfohtml = '';
2091  if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
2092  $moreinfo .= ($moreinfo ? ' - ' : ' (');
2093  $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
2094  $moreinfo .= $obj->login;
2095  $moreinfohtml .= $obj->login;
2096  }
2097  if ($showstatus >= 0) {
2098  if ($obj->status == 1 && $showstatus == 1) {
2099  $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
2100  $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').$langs->trans('Enabled');
2101  }
2102  if ($obj->status == 0 && $showstatus == 1) {
2103  $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
2104  $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').$langs->trans('Disabled');
2105  }
2106  }
2107  if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
2108  if (!$obj->entity) {
2109  $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
2110  $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').$langs->trans("AllEntities");
2111  } else {
2112  if ($obj->entity != $conf->entity) {
2113  $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
2114  $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
2115  }
2116  }
2117  }
2118  $moreinfo .= ($moreinfo ? ')' : '');
2119  $moreinfohtml .= ($moreinfohtml ? ')' : '');
2120  if ($disableline && $disableline != '1') {
2121  // Add text from $enableonlytext parameter
2122  $moreinfo .= ' - '.$disableline;
2123  $moreinfohtml .= ' - '.$disableline;
2124  }
2125  $labeltoshow .= $moreinfo;
2126  $labeltoshowhtml .= $moreinfohtml;
2127 
2128  $out .= '<option value="'.$obj->rowid.'"';
2129  if ($disableline) {
2130  $out .= ' disabled';
2131  }
2132  if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
2133  $out .= ' selected';
2134  }
2135  $out .= ' data-html="';
2136  $outhtml = '';
2137  // if (!empty($obj->photo)) {
2138  $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
2139  // }
2140  if ($showstatus >= 0 && $obj->status == 0) {
2141  $outhtml .= '<strike class="opacitymediumxxx">';
2142  }
2143  $outhtml .= $labeltoshowhtml;
2144  if ($showstatus >= 0 && $obj->status == 0) {
2145  $outhtml .= '</strike>';
2146  }
2147  $out .= dol_escape_htmltag($outhtml);
2148  $out .= '">';
2149  $out .= $labeltoshow;
2150  $out .= '</option>';
2151 
2152  $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
2153 
2154  $i++;
2155  }
2156  } else {
2157  $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
2158  $out .= '<option value="">'.$langs->trans("None").'</option>';
2159  }
2160  $out .= '</select>';
2161 
2162  if ($num && !$forcecombo) {
2163  // Enhance with select2
2164  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
2165  $out .= ajax_combobox($htmlname);
2166  }
2167  } else {
2168  dol_print_error($this->db);
2169  }
2170 
2171  if ($outputmode) {
2172  return $outarray;
2173  }
2174 
2175  return $out;
2176  }
2177 
2178 
2179  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2202  public 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())
2203  {
2204  // phpcs:enable
2205  global $conf, $user, $langs;
2206 
2207  $userstatic = new User($this->db);
2208  $out = '';
2209 
2210 
2211  $assignedtouser = array();
2212  if (!empty($_SESSION['assignedtouser'])) {
2213  $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
2214  }
2215  $nbassignetouser = count($assignedtouser);
2216 
2217  //if ($nbassignetouser && $action != 'view') $out .= '<br>';
2218  if ($nbassignetouser) {
2219  $out .= '<ul class="attendees">';
2220  }
2221  $i = 0;
2222  $ownerid = 0;
2223  foreach ($assignedtouser as $key => $value) {
2224  if ($value['id'] == $ownerid) {
2225  continue;
2226  }
2227 
2228  $out .= '<li>';
2229  $userstatic->fetch($value['id']);
2230  $out .= $userstatic->getNomUrl(-1);
2231  if ($i == 0) {
2232  $ownerid = $value['id'];
2233  $out .= ' ('.$langs->trans("Owner").')';
2234  }
2235  if ($nbassignetouser > 1 && $action != 'view') {
2236  $out .= ' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned reposition" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
2237  }
2238  // Show my availability
2239  if ($showproperties) {
2240  if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
2241  $out .= '<div class="myavailability inline-block">';
2242  $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span> </span><input id="transparency" class="paddingrightonly" '.($action == 'view' ? 'disabled' : '').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency'] ? ' checked' : '').'><label for="transparency">'.$langs->trans("Busy").'</label>';
2243  $out .= '</div>';
2244  }
2245  }
2246  //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
2247  //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
2248 
2249  $out .= '</li>';
2250  $i++;
2251  }
2252  if ($nbassignetouser) {
2253  $out .= '</ul>';
2254  }
2255 
2256  // Method with no ajax
2257  if ($action != 'view') {
2258  $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
2259  $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
2260  $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
2261  $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
2262  $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
2263  $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
2264  $out .= '});';
2265  $out .= '})</script>';
2266  $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
2267  $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
2268  $out .= '<br>';
2269  }
2270 
2271  return $out;
2272  }
2273 
2274 
2275  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2303  public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 0, $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 = null, $nooutput = 0, $status_purchase = -1)
2304  {
2305  // phpcs:enable
2306  global $langs, $conf;
2307 
2308  $out = '';
2309 
2310  // check parameters
2311  $price_level = (!empty($price_level) ? $price_level : 0);
2312  if (is_null($ajaxoptions)) {
2313  $ajaxoptions = array();
2314  }
2315 
2316  if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
2317  if (isModEnabled("product") && !isModEnabled('service')) {
2318  $filtertype = '0';
2319  } elseif (!isModEnabled('product') && isModEnabled("service")) {
2320  $filtertype = '1';
2321  }
2322  }
2323 
2324  if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
2325  $placeholder = '';
2326 
2327  if ($selected && empty($selected_input_value)) {
2328  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2329  $producttmpselect = new Product($this->db);
2330  $producttmpselect->fetch($selected);
2331  $selected_input_value = $producttmpselect->ref;
2332  unset($producttmpselect);
2333  }
2334  // handle case where product or service module is disabled + no filter specified
2335  if ($filtertype == '') {
2336  if (!isModEnabled('product')) { // when product module is disabled, show services only
2337  $filtertype = 1;
2338  } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
2339  $filtertype = 0;
2340  }
2341  }
2342  // mode=1 means customers products
2343  $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&status_purchase='.$status_purchase.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
2344  //Price by customer
2345  if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2346  $urloption .= '&socid='.$socid;
2347  }
2348  $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
2349 
2350  if (isModEnabled('variants') && is_array($selected_combinations)) {
2351  // Code to automatically insert with javascript the select of attributes under the select of product
2352  // when a parent of variant has been selected.
2353  $out .= '
2354  <!-- script to auto show attributes select tags if a variant was selected -->
2355  <script>
2356  // auto show attributes fields
2357  selected = '.json_encode($selected_combinations).';
2358  combvalues = {};
2359 
2360  jQuery(document).ready(function () {
2361 
2362  jQuery("input[name=\'prod_entry_mode\']").change(function () {
2363  if (jQuery(this).val() == \'free\') {
2364  jQuery(\'div#attributes_box\').empty();
2365  }
2366  });
2367 
2368  jQuery("input#'.$htmlname.'").change(function () {
2369 
2370  if (!jQuery(this).val()) {
2371  jQuery(\'div#attributes_box\').empty();
2372  return;
2373  }
2374 
2375  console.log("A change has started. We get variants fields to inject html select");
2376 
2377  jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
2378  id: jQuery(this).val()
2379  }, function (data) {
2380  jQuery(\'div#attributes_box\').empty();
2381 
2382  jQuery.each(data, function (key, val) {
2383 
2384  combvalues[val.id] = val.values;
2385 
2386  var span = jQuery(document.createElement(\'div\')).css({
2387  \'display\': \'table-row\'
2388  });
2389 
2390  span.append(
2391  jQuery(document.createElement(\'div\')).text(val.label).css({
2392  \'font-weight\': \'bold\',
2393  \'display\': \'table-cell\'
2394  })
2395  );
2396 
2397  var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
2398  \'margin-left\': \'15px\',
2399  \'white-space\': \'pre\'
2400  }).append(
2401  jQuery(document.createElement(\'option\')).val(\'\')
2402  );
2403 
2404  jQuery.each(combvalues[val.id], function (key, val) {
2405  var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
2406 
2407  if (selected[val.fk_product_attribute] == val.id) {
2408  tag.attr(\'selected\', \'selected\');
2409  }
2410 
2411  html.append(tag);
2412  });
2413 
2414  span.append(html);
2415  jQuery(\'div#attributes_box\').append(span);
2416  });
2417  })
2418  });
2419 
2420  '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
2421  });
2422  </script>
2423  ';
2424  }
2425 
2426  if (empty($hidelabel)) {
2427  $out .= $langs->trans("RefOrLabel").' : ';
2428  } elseif ($hidelabel > 1) {
2429  $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
2430  if ($hidelabel == 2) {
2431  $out .= img_picto($langs->trans("Search"), 'search');
2432  }
2433  }
2434  $out .= '<input type="text" class="minwidth100'.($morecss ? ' '.$morecss : '').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
2435  if ($hidelabel == 3) {
2436  $out .= img_picto($langs->trans("Search"), 'search');
2437  }
2438  } else {
2439  $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
2440  }
2441 
2442  if (empty($nooutput)) {
2443  print $out;
2444  } else {
2445  return $out;
2446  }
2447  }
2448 
2449  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2450 
2466  public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
2467  {
2468  // phpcs:enable
2469  global $conf, $user, $langs, $db;
2470 
2471  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2472 
2473  $error = 0;
2474  $out = '';
2475 
2476  if (!$forcecombo) {
2477  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
2478  $events = array();
2479  $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
2480  }
2481 
2482  $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
2483 
2484  $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
2485  $sql.= ' FROM '.MAIN_DB_PREFIX.'bom_bom as b';
2486  $sql.= ' WHERE b.entity IN ('.getEntity('bom').')';
2487  if (!empty($status)) $sql.= ' AND status = '. (int) $status;
2488  if (!empty($type)) $sql.= ' AND bomtype = '. (int) $type;
2489  if (!empty($TProducts)) $sql .= ' AND fk_product IN ('.$this->db->sanitize(implode(',', $TProducts)).')';
2490  if (!empty($limit)) $sql.= ' LIMIT '. (int) $limit;
2491  $resql = $db->query($sql);
2492  if ($resql) {
2493  if ($showempty) {
2494  $out .= '<option value="-1"';
2495  if (empty($selected)) $out .= ' selected';
2496  $out .= '>&nbsp;</option>';
2497  }
2498  while ($obj = $db->fetch_object($resql)) {
2499  $product = new Product($db);
2500  $res = $product->fetch($obj->fk_product);
2501  $out .= '<option value="'.$obj->rowid.'"';
2502  if ($obj->rowid == $selected) $out .= 'selected';
2503  $out .= '>'.$obj->ref.' - '.$product->label .' - '. $obj->label.'</option>';
2504  }
2505  } else {
2506  $error++;
2507  dol_print_error($db);
2508  }
2509  $out .= '</select>';
2510  if (empty($nooutput)) {
2511  print $out;
2512  } else {
2513  return $out;
2514  }
2515  }
2516 
2517  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2543  public 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 = '', $status_purchase = -1)
2544  {
2545  // phpcs:enable
2546  global $langs, $conf;
2547  global $hookmanager;
2548 
2549  $out = '';
2550  $outarray = array();
2551 
2552  // Units
2553  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
2554  $langs->load('other');
2555  }
2556 
2557  $warehouseStatusArray = array();
2558  if (!empty($warehouseStatus)) {
2559  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
2560  if (preg_match('/warehouseclosed/', $warehouseStatus)) {
2561  $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
2562  }
2563  if (preg_match('/warehouseopen/', $warehouseStatus)) {
2564  $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
2565  }
2566  if (preg_match('/warehouseinternal/', $warehouseStatus)) {
2567  $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
2568  }
2569  }
2570 
2571  $selectFields = " p.rowid, p.ref, p.label, p.description, p.barcode, p.fk_country, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.default_vat_code, p.duration, p.fk_price_expression";
2572  if (count($warehouseStatusArray)) {
2573  $selectFieldsGrouped = ", sum(".$this->db->ifsql("e.statut IS NULL", "0", "ps.reel").") as stock"; // e.statut is null if there is no record in stock
2574  } else {
2575  $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
2576  }
2577 
2578  $sql = "SELECT ";
2579  $sql .= $selectFields.$selectFieldsGrouped;
2580 
2581  if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
2582  //Product category
2583  $sql .= ", (SELECT ".$this->db->prefix()."categorie_product.fk_categorie
2584  FROM ".$this->db->prefix()."categorie_product
2585  WHERE ".$this->db->prefix()."categorie_product.fk_product=p.rowid
2586  LIMIT 1
2587  ) AS categorie_product_id ";
2588  }
2589 
2590  //Price by customer
2591  if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2592  $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
2593  $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx, pcp.default_vat_code as custdefault_vat_code, pcp.ref_customer as custref';
2594  $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
2595  }
2596  // Units
2597  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
2598  $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units";
2599  $selectFields .= ', unit_long, unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units';
2600  }
2601 
2602  // Multilang : we add translation
2603  if (getDolGlobalInt('MAIN_MULTILANGS')) {
2604  $sql .= ", pl.label as label_translated";
2605  $sql .= ", pl.description as description_translated";
2606  $selectFields .= ", label_translated";
2607  $selectFields .= ", description_translated";
2608  }
2609  // Price by quantity
2610  if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
2611  $sql .= ", (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid";
2612  if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
2613  $sql .= " AND price_level = ".((int) $price_level);
2614  }
2615  $sql .= " ORDER BY date_price";
2616  $sql .= " DESC LIMIT 1) as price_rowid";
2617  $sql .= ", (SELECT pp.price_by_qty FROM ".$this->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
2618  if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
2619  $sql .= " AND price_level = ".((int) $price_level);
2620  }
2621  $sql .= " ORDER BY date_price";
2622  $sql .= " DESC LIMIT 1) as price_by_qty";
2623  $selectFields .= ", price_rowid, price_by_qty";
2624  }
2625  $sql .= " FROM ".$this->db->prefix()."product as p";
2626  if (count($warehouseStatusArray)) {
2627  $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock as ps on ps.fk_product = p.rowid";
2628  $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
2629  $sql .= ' AND e.statut IN ('.$this->db->sanitize($this->db->escape(implode(',', $warehouseStatusArray))).')'; // Return line if product is inside the selected stock. If not, an empty line will be returned so we will count 0.
2630  }
2631 
2632  // include search in supplier ref
2633  if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
2634  $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2635  }
2636 
2637  //Price by customer
2638  if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2639  $sql .= " LEFT JOIN ".$this->db->prefix()."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
2640  }
2641  // Units
2642  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
2643  $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
2644  }
2645  // Multilang : we add translation
2646  if (getDolGlobalInt('MAIN_MULTILANGS')) {
2647  $sql .= " LEFT JOIN ".$this->db->prefix()."product_lang as pl ON pl.fk_product = p.rowid ";
2648  if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
2649  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
2650  $soc = new Societe($this->db);
2651  $result = $soc->fetch($socid);
2652  if ($result > 0 && !empty($soc->default_lang)) {
2653  $sql .= " AND pl.lang = '".$this->db->escape($soc->default_lang)."'";
2654  } else {
2655  $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
2656  }
2657  } else {
2658  $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
2659  }
2660  }
2661 
2662  if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2663  $sql .= " LEFT JOIN ".$this->db->prefix()."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
2664  }
2665 
2666  $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
2667 
2668  if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2669  $sql .= " AND pac.rowid IS NULL";
2670  }
2671 
2672  if ($finished == 0) {
2673  $sql .= " AND p.finished = ".((int) $finished);
2674  } elseif ($finished == 1) {
2675  $sql .= " AND p.finished = ".((int) $finished);
2676  if ($status >= 0) {
2677  $sql .= " AND p.tosell = ".((int) $status);
2678  }
2679  } elseif ($status >= 0) {
2680  $sql .= " AND p.tosell = ".((int) $status);
2681  }
2682  if ($status_purchase >= 0) {
2683  $sql .= " AND p.tobuy = ".((int) $status_purchase);
2684  }
2685  // Filter by product type
2686  if (strval($filtertype) != '') {
2687  $sql .= " AND p.fk_product_type = ".((int) $filtertype);
2688  } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
2689  $sql .= " AND p.fk_product_type = 1";
2690  } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
2691  $sql .= " AND p.fk_product_type = 0";
2692  }
2693  // Add where from hooks
2694  $parameters = array();
2695  $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
2696  $sql .= $hookmanager->resPrint;
2697  // Add criteria on ref/label
2698  if ($filterkey != '') {
2699  $sql .= ' AND (';
2700  $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2701  // For natural search
2702  $scrit = explode(' ', $filterkey);
2703  $i = 0;
2704  if (count($scrit) > 1) {
2705  $sql .= "(";
2706  }
2707  foreach ($scrit as $crit) {
2708  if ($i > 0) {
2709  $sql .= " AND ";
2710  }
2711  $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
2712  if (getDolGlobalInt('MAIN_MULTILANGS')) {
2713  $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
2714  }
2715  if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2716  $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
2717  }
2718  if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
2719  $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
2720  if (getDolGlobalInt('MAIN_MULTILANGS')) {
2721  $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
2722  }
2723  }
2724  if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
2725  $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
2726  }
2727  $sql .= ")";
2728  $i++;
2729  }
2730  if (count($scrit) > 1) {
2731  $sql .= ")";
2732  }
2733  if (isModEnabled('barcode')) {
2734  $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
2735  }
2736  $sql .= ')';
2737  }
2738  if (count($warehouseStatusArray)) {
2739  $sql .= " GROUP BY ".$selectFields;
2740  }
2741 
2742  //Sort by category
2743  if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
2744  $sql .= " ORDER BY categorie_product_id ";
2745  //ASC OR DESC order
2746  ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
2747  } else {
2748  $sql .= $this->db->order("p.ref");
2749  }
2750 
2751  $sql .= $this->db->plimit($limit, 0);
2752 
2753  // Build output string
2754  dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
2755  $result = $this->db->query($sql);
2756  if ($result) {
2757  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2758  require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2759  require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
2760 
2761  $num = $this->db->num_rows($result);
2762 
2763  $events = null;
2764 
2765  if (!$forcecombo) {
2766  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
2767  $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
2768  }
2769 
2770  $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
2771 
2772  $textifempty = '';
2773  // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
2774  //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
2775  if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
2776  if ($showempty && !is_numeric($showempty)) {
2777  $textifempty = $langs->trans($showempty);
2778  } else {
2779  $textifempty .= $langs->trans("All");
2780  }
2781  } else {
2782  if ($showempty && !is_numeric($showempty)) {
2783  $textifempty = $langs->trans($showempty);
2784  }
2785  }
2786  if ($showempty) {
2787  $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
2788  }
2789 
2790  $i = 0;
2791  while ($num && $i < $num) {
2792  $opt = '';
2793  $optJson = array();
2794  $objp = $this->db->fetch_object($result);
2795 
2796  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) { // Price by quantity will return many prices for the same product
2797  $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
2798  $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
2799  $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
2800  $sql .= " ORDER BY quantity ASC";
2801 
2802  dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
2803  $result2 = $this->db->query($sql);
2804  if ($result2) {
2805  $nb_prices = $this->db->num_rows($result2);
2806  $j = 0;
2807  while ($nb_prices && $j < $nb_prices) {
2808  $objp2 = $this->db->fetch_object($result2);
2809 
2810  $objp->price_by_qty_rowid = $objp2->rowid;
2811  $objp->price_by_qty_price_base_type = $objp2->price_base_type;
2812  $objp->price_by_qty_quantity = $objp2->quantity;
2813  $objp->price_by_qty_unitprice = $objp2->unitprice;
2814  $objp->price_by_qty_remise_percent = $objp2->remise_percent;
2815  // For backward compatibility
2816  $objp->quantity = $objp2->quantity;
2817  $objp->price = $objp2->price;
2818  $objp->unitprice = $objp2->unitprice;
2819  $objp->remise_percent = $objp2->remise_percent;
2820 
2821  //$objp->tva_tx is not overwritten by $objp2 value
2822  //$objp->default_vat_code is not overwritten by $objp2 value
2823 
2824  $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
2825 
2826  $j++;
2827 
2828  // Add new entry
2829  // "key" value of json key array is used by jQuery automatically as selected value
2830  // "label" value of json key array is used by jQuery automatically as text for combo box
2831  $out .= $opt;
2832  array_push($outarray, $optJson);
2833  }
2834  }
2835  } else {
2836  if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
2837  $price_product = new Product($this->db);
2838  $price_product->fetch($objp->rowid, '', '', 1);
2839 
2840  require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2841  $priceparser = new PriceParser($this->db);
2842  $price_result = $priceparser->parseProduct($price_product);
2843  if ($price_result >= 0) {
2844  $objp->price = $price_result;
2845  $objp->unitprice = $price_result;
2846  //Calculate the VAT
2847  $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
2848  $objp->price_ttc = price2num($objp->price_ttc, 'MU');
2849  }
2850  }
2851 
2852  $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
2853  // Add new entry
2854  // "key" value of json key array is used by jQuery automatically as selected value
2855  // "label" value of json key array is used by jQuery automatically as text for combo box
2856  $out .= $opt;
2857  array_push($outarray, $optJson);
2858  }
2859 
2860  $i++;
2861  }
2862 
2863  $out .= '</select>';
2864 
2865  $this->db->free($result);
2866 
2867  if (empty($outputmode)) {
2868  return $out;
2869  }
2870  return $outarray;
2871  } else {
2872  dol_print_error($this->db);
2873  }
2874  }
2875 
2891  protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
2892  {
2893  global $langs, $conf, $user;
2894 
2895  $outkey = '';
2896  $outval = '';
2897  $outref = '';
2898  $outlabel = '';
2899  $outlabel_translated = '';
2900  $outdesc = '';
2901  $outdesc_translated = '';
2902  $outbarcode = '';
2903  $outorigin = '';
2904  $outtype = '';
2905  $outprice_ht = '';
2906  $outprice_ttc = '';
2907  $outpricebasetype = '';
2908  $outtva_tx = '';
2909  $outdefault_vat_code = '';
2910  $outqty = 1;
2911  $outdiscount = 0;
2912 
2913  $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
2914 
2915  $label = $objp->label;
2916  if (!empty($objp->label_translated)) {
2917  $label = $objp->label_translated;
2918  }
2919  if (!empty($filterkey) && $filterkey != '') {
2920  $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
2921  }
2922 
2923  $outkey = $objp->rowid;
2924  $outref = $objp->ref;
2925  $outrefcust = empty($objp->custref) ? '' : $objp->custref;
2926  $outlabel = $objp->label;
2927  $outdesc = $objp->description;
2928  if (getDolGlobalInt('MAIN_MULTILANGS')) {
2929  $outlabel_translated = $objp->label_translated;
2930  $outdesc_translated = $objp->description_translated;
2931  }
2932  $outbarcode = $objp->barcode;
2933  $outorigin = $objp->fk_country;
2934  $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
2935 
2936  $outtype = $objp->fk_product_type;
2937  $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
2938  $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
2939 
2940  if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
2941  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
2942  }
2943 
2944  // Units
2945  $outvalUnits = '';
2946  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
2947  if (!empty($objp->unit_short)) {
2948  $outvalUnits .= ' - '.$objp->unit_short;
2949  }
2950  }
2951  if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
2952  if (!empty($objp->weight) && $objp->weight_units !== null) {
2953  $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
2954  $outvalUnits .= ' - '.$unitToShow;
2955  }
2956  if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
2957  $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
2958  $outvalUnits .= ' - '.$unitToShow;
2959  }
2960  if (!empty($objp->surface) && $objp->surface_units !== null) {
2961  $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
2962  $outvalUnits .= ' - '.$unitToShow;
2963  }
2964  if (!empty($objp->volume) && $objp->volume_units !== null) {
2965  $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
2966  $outvalUnits .= ' - '.$unitToShow;
2967  }
2968  }
2969  if ($outdurationvalue && $outdurationunit) {
2970  $da = array(
2971  'h' => $langs->trans('Hour'),
2972  'd' => $langs->trans('Day'),
2973  'w' => $langs->trans('Week'),
2974  'm' => $langs->trans('Month'),
2975  'y' => $langs->trans('Year')
2976  );
2977  if (isset($da[$outdurationunit])) {
2978  $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
2979  }
2980  }
2981 
2982  $opt = '<option value="'.$objp->rowid.'"';
2983  $opt .= ($objp->rowid == $selected) ? ' selected' : '';
2984  if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
2985  $opt .= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqup="'.$objp->price_by_qty_unitprice.'" data-pbqbase="'.$objp->price_by_qty_price_base_type.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
2986  }
2987  if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
2988  if (!empty($user->rights->stock->lire)) {
2989  if ($objp->stock > 0) {
2990  $opt .= ' class="product_line_stock_ok"';
2991  } elseif ($objp->stock <= 0) {
2992  $opt .= ' class="product_line_stock_too_low"';
2993  }
2994  }
2995  }
2996  if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
2997  $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
2998  $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
2999  }
3000  $opt .= '>';
3001  $opt .= $objp->ref;
3002  if (!empty($objp->custref)) {
3003  $opt.= ' (' . $objp->custref . ')';
3004  }
3005  if ($outbarcode) {
3006  $opt .= ' ('.$outbarcode.')';
3007  }
3008  $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
3009  if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
3010  $opt .= ' ('.getCountry($outorigin, 1).')';
3011  }
3012 
3013  $objRef = $objp->ref;
3014  if (!empty($objp->custref)) {
3015  $objRef .= ' (' . $objp->custref . ')';
3016  }
3017  if (!empty($filterkey) && $filterkey != '') {
3018  $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
3019  }
3020  $outval .= $objRef;
3021  if ($outbarcode) {
3022  $outval .= ' ('.$outbarcode.')';
3023  }
3024  $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
3025  if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
3026  $outval .= ' ('.getCountry($outorigin, 1).')';
3027  }
3028 
3029  // Units
3030  $opt .= $outvalUnits;
3031  $outval .= $outvalUnits;
3032 
3033  $found = 0;
3034 
3035  // Multiprice
3036  // If we need a particular price level (from 1 to n)
3037  if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
3038  $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
3039  $sql .= " FROM ".$this->db->prefix()."product_price";
3040  $sql .= " WHERE fk_product = ".((int) $objp->rowid);
3041  $sql .= " AND entity IN (".getEntity('productprice').")";
3042  $sql .= " AND price_level = ".((int) $price_level);
3043  $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
3044  $sql .= " LIMIT 1";
3045 
3046  dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
3047  $result2 = $this->db->query($sql);
3048  if ($result2) {
3049  $objp2 = $this->db->fetch_object($result2);
3050  if ($objp2) {
3051  $found = 1;
3052  if ($objp2->price_base_type == 'HT') {
3053  $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
3054  $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
3055  } else {
3056  $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
3057  $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
3058  }
3059  $outprice_ht = price($objp2->price);
3060  $outprice_ttc = price($objp2->price_ttc);
3061  $outpricebasetype = $objp2->price_base_type;
3062  if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
3063  $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
3064  $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
3065  } else {
3066  $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
3067  $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
3068  }
3069  }
3070  } else {
3071  dol_print_error($this->db);
3072  }
3073  }
3074 
3075  // Price by quantity
3076  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))) {
3077  $found = 1;
3078  $outqty = $objp->quantity;
3079  $outdiscount = $objp->remise_percent;
3080  if ($objp->quantity == 1) {
3081  $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
3082  $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
3083  $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
3084  $outval .= $langs->transnoentities("Unit");
3085  } else {
3086  $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
3087  $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
3088  $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
3089  $outval .= $langs->transnoentities("Units");
3090  }
3091 
3092  $outprice_ht = price($objp->unitprice);
3093  $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
3094  $outpricebasetype = $objp->price_base_type;
3095  $outtva_tx = $objp->tva_tx; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
3096  $outdefault_vat_code = $objp->default_vat_code; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
3097  }
3098  if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
3099  $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
3100  $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
3101  }
3102  if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
3103  $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
3104  $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
3105  }
3106 
3107  // Price by customer
3108  if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
3109  if (!empty($objp->idprodcustprice)) {
3110  $found = 1;
3111 
3112  if ($objp->custprice_base_type == 'HT') {
3113  $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
3114  $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
3115  } else {
3116  $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
3117  $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
3118  }
3119 
3120  $outprice_ht = price($objp->custprice);
3121  $outprice_ttc = price($objp->custprice_ttc);
3122  $outpricebasetype = $objp->custprice_base_type;
3123  $outtva_tx = $objp->custtva_tx;
3124  $outdefault_vat_code = $objp->custdefault_vat_code;
3125  }
3126  }
3127 
3128  // If level no defined or multiprice not found, we used the default price
3129  if (empty($hidepriceinlabel) && !$found) {
3130  if ($objp->price_base_type == 'HT') {
3131  $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
3132  $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
3133  } else {
3134  $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
3135  $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
3136  }
3137  $outprice_ht = price($objp->price);
3138  $outprice_ttc = price($objp->price_ttc);
3139  $outpricebasetype = $objp->price_base_type;
3140  $outtva_tx = $objp->tva_tx;
3141  $outdefault_vat_code = $objp->default_vat_code;
3142  }
3143 
3144  if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
3145  if (!empty($user->rights->stock->lire)) {
3146  $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
3147 
3148  if ($objp->stock > 0) {
3149  $outval .= ' - <span class="product_line_stock_ok">';
3150  } elseif ($objp->stock <= 0) {
3151  $outval .= ' - <span class="product_line_stock_too_low">';
3152  }
3153  $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
3154  $outval .= '</span>';
3155  if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
3156  $langs->load("stocks");
3157 
3158  $tmpproduct = new Product($this->db);
3159  $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
3160  $tmpproduct->load_virtual_stock();
3161  $virtualstock = $tmpproduct->stock_theorique;
3162 
3163  $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
3164 
3165  $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
3166  if ($virtualstock > 0) {
3167  $outval .= '<span class="product_line_stock_ok">';
3168  } elseif ($virtualstock <= 0) {
3169  $outval .= '<span class="product_line_stock_too_low">';
3170  }
3171  $outval .= $virtualstock;
3172  $outval .= '</span>';
3173 
3174  unset($tmpproduct);
3175  }
3176  }
3177  }
3178 
3179  $opt .= "</option>\n";
3180  $optJson = array(
3181  'key'=>$outkey,
3182  'value'=>$outref,
3183  'label'=>$outval,
3184  'label2'=>$outlabel,
3185  'desc'=>$outdesc,
3186  'type'=>$outtype,
3187  'price_ht'=>price2num($outprice_ht),
3188  'price_ttc'=>price2num($outprice_ttc),
3189  'price_ht_locale'=>price(price2num($outprice_ht)),
3190  'price_ttc_locale'=>price(price2num($outprice_ttc)),
3191  'pricebasetype'=>$outpricebasetype,
3192  'tva_tx'=>$outtva_tx,
3193  'default_vat_code'=>$outdefault_vat_code,
3194  'qty'=>$outqty,
3195  'discount'=>$outdiscount,
3196  'duration_value'=>$outdurationvalue,
3197  'duration_unit'=>$outdurationunit,
3198  'pbq'=>$outpbq,
3199  'labeltrans'=>$outlabel_translated,
3200  'desctrans'=>$outdesc_translated,
3201  'ref_customer'=>$outrefcust
3202  );
3203  }
3204 
3205  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3221  public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
3222  {
3223  // phpcs:enable
3224  global $langs, $conf;
3225  global $price_level, $status, $finished;
3226 
3227  if (!isset($status)) {
3228  $status = 1;
3229  }
3230 
3231  $selected_input_value = '';
3232  if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
3233  if ($selected > 0) {
3234  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
3235  $producttmpselect = new Product($this->db);
3236  $producttmpselect->fetch($selected);
3237  $selected_input_value = $producttmpselect->ref;
3238  unset($producttmpselect);
3239  }
3240 
3241  // mode=2 means suppliers products
3242  $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
3243  print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
3244  print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
3245  } else {
3246  print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
3247  }
3248  }
3249 
3250  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3269  public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '', $showstockinlist = 0, $placeholder = '')
3270  {
3271  // phpcs:enable
3272  global $langs, $conf, $user;
3273  global $hookmanager;
3274 
3275  $out = '';
3276  $outarray = array();
3277 
3278  $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
3279 
3280  $langs->load('stocks');
3281  // Units
3282  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
3283  $langs->load('other');
3284  }
3285 
3286  $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock, p.tva_tx as tva_tx_sale, p.default_vat_code as default_vat_code_sale,";
3287  $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
3288  $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
3289  $sql .= " pfp.supplier_reputation";
3290  // if we use supplier description of the products
3291  if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
3292  $sql .= ", pfp.desc_fourn as description";
3293  } else {
3294  $sql .= ", p.description";
3295  }
3296  // Units
3297  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
3298  $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units";
3299  }
3300  if (isModEnabled('barcode')) {
3301  $sql .= ", pfp.barcode";
3302  }
3303  $sql .= " FROM ".$this->db->prefix()."product as p";
3304  $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
3305  if ($socid > 0) {
3306  $sql .= " AND pfp.fk_soc = ".((int) $socid);
3307  }
3308  $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
3309  // Units
3310  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
3311  $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
3312  }
3313  $sql .= " WHERE p.entity IN (".getEntity('product').")";
3314  if ($statut != -1) {
3315  $sql .= " AND p.tobuy = ".((int) $statut);
3316  }
3317  if (strval($filtertype) != '') {
3318  $sql .= " AND p.fk_product_type = ".((int) $filtertype);
3319  }
3320  if (!empty($filtre)) {
3321  $sql .= " ".$filtre;
3322  }
3323  // Add where from hooks
3324  $parameters = array();
3325  $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
3326  $sql .= $hookmanager->resPrint;
3327  // Add criteria on ref/label
3328  if ($filterkey != '') {
3329  $sql .= ' AND (';
3330  $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
3331  // For natural search
3332  $scrit = explode(' ', $filterkey);
3333  $i = 0;
3334  if (count($scrit) > 1) {
3335  $sql .= "(";
3336  }
3337  foreach ($scrit as $crit) {
3338  if ($i > 0) {
3339  $sql .= " AND ";
3340  }
3341  $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)."%'";
3342  if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
3343  $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
3344  }
3345  $sql .= ")";
3346  $i++;
3347  }
3348  if (count($scrit) > 1) {
3349  $sql .= ")";
3350  }
3351  if (isModEnabled('barcode')) {
3352  $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
3353  $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
3354  }
3355  $sql .= ')';
3356  }
3357  $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
3358  $sql .= $this->db->plimit($limit, 0);
3359 
3360  // Build output string
3361 
3362  dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
3363  $result = $this->db->query($sql);
3364  if ($result) {
3365  require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
3366  require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
3367 
3368  $num = $this->db->num_rows($result);
3369 
3370  //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
3371  $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
3372  if (!$selected) {
3373  $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
3374  } else {
3375  $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
3376  }
3377 
3378  $i = 0;
3379  while ($i < $num) {
3380  $objp = $this->db->fetch_object($result);
3381 
3382  if (is_null($objp->idprodfournprice)) {
3383  // There is no supplier price found, we will use the vat rate for sale
3384  $objp->tva_tx = $objp->tva_tx_sale;
3385  $objp->default_vat_code = $objp->default_vat_code_sale;
3386  }
3387 
3388  $outkey = $objp->idprodfournprice; // id in table of price
3389  if (!$outkey && $alsoproductwithnosupplierprice) {
3390  $outkey = 'idprod_'.$objp->rowid; // id of product
3391  }
3392 
3393  $outref = $objp->ref;
3394  $outbarcode = $objp->barcode;
3395  $outqty = 1;
3396  $outdiscount = 0;
3397  $outtype = $objp->fk_product_type;
3398  $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
3399  $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
3400 
3401  // Units
3402  $outvalUnits = '';
3403  if (!empty($conf->global->PRODUCT_USE_UNITS)) {
3404  if (!empty($objp->unit_short)) {
3405  $outvalUnits .= ' - '.$objp->unit_short;
3406  }
3407  if (!empty($objp->weight) && $objp->weight_units !== null) {
3408  $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
3409  $outvalUnits .= ' - '.$unitToShow;
3410  }
3411  if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
3412  $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
3413  $outvalUnits .= ' - '.$unitToShow;
3414  }
3415  if (!empty($objp->surface) && $objp->surface_units !== null) {
3416  $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
3417  $outvalUnits .= ' - '.$unitToShow;
3418  }
3419  if (!empty($objp->volume) && $objp->volume_units !== null) {
3420  $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
3421  $outvalUnits .= ' - '.$unitToShow;
3422  }
3423  if ($outdurationvalue && $outdurationunit) {
3424  $da = array(
3425  'h' => $langs->trans('Hour'),
3426  'd' => $langs->trans('Day'),
3427  'w' => $langs->trans('Week'),
3428  'm' => $langs->trans('Month'),
3429  'y' => $langs->trans('Year')
3430  );
3431  if (isset($da[$outdurationunit])) {
3432  $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
3433  }
3434  }
3435  }
3436 
3437  $objRef = $objp->ref;
3438  if ($filterkey && $filterkey != '') {
3439  $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
3440  }
3441  $objRefFourn = $objp->ref_fourn;
3442  if ($filterkey && $filterkey != '') {
3443  $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
3444  }
3445  $label = $objp->label;
3446  if ($filterkey && $filterkey != '') {
3447  $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
3448  }
3449 
3450  $optlabel = $objp->ref;
3451  if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
3452  $optlabel .= ' <span class="opacitymedium">('.$objp->ref_fourn.')</span>';
3453  }
3454  if (isModEnabled('barcode') && !empty($objp->barcode)) {
3455  $optlabel .= ' ('.$outbarcode.')';
3456  }
3457  $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
3458 
3459  $outvallabel = $objRef;
3460  if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
3461  $outvallabel .= ' ('.$objRefFourn.')';
3462  }
3463  if (isModEnabled('barcode') && !empty($objp->barcode)) {
3464  $outvallabel .= ' ('.$outbarcode.')';
3465  }
3466  $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
3467 
3468  // Units
3469  $optlabel .= $outvalUnits;
3470  $outvallabel .= $outvalUnits;
3471 
3472  if (!empty($objp->idprodfournprice)) {
3473  $outqty = $objp->quantity;
3474  $outdiscount = $objp->remise_percent;
3475  if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
3476  $prod_supplier = new ProductFournisseur($this->db);
3477  $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
3478  $prod_supplier->id = $objp->fk_product;
3479  $prod_supplier->fourn_qty = $objp->quantity;
3480  $prod_supplier->fourn_tva_tx = $objp->tva_tx;
3481  $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
3482 
3483  require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
3484  $priceparser = new PriceParser($this->db);
3485  $price_result = $priceparser->parseProductSupplier($prod_supplier);
3486  if ($price_result >= 0) {
3487  $objp->fprice = $price_result;
3488  if ($objp->quantity >= 1) {
3489  $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
3490  }
3491  }
3492  }
3493  if ($objp->quantity == 1) {
3494  $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
3495  $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
3496  $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
3497  $outvallabel .= $langs->transnoentities("Unit");
3498  } else {
3499  $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
3500  $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
3501  $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
3502  $outvallabel .= ' '.$langs->transnoentities("Units");
3503  }
3504 
3505  if ($objp->quantity > 1) {
3506  $optlabel .= " (".price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
3507  $outvallabel .= " (".price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
3508  }
3509  if ($objp->remise_percent >= 1) {
3510  $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
3511  $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
3512  }
3513  if ($objp->duration) {
3514  $optlabel .= " - ".$objp->duration;
3515  $outvallabel .= " - ".$objp->duration;
3516  }
3517  if (!$socid) {
3518  $optlabel .= " - ".dol_trunc($objp->name, 8);
3519  $outvallabel .= " - ".dol_trunc($objp->name, 8);
3520  }
3521  if ($objp->supplier_reputation) {
3522  //TODO dictionary
3523  $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
3524 
3525  $optlabel .= " - ".$reputations[$objp->supplier_reputation];
3526  $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
3527  }
3528  } else {
3529  if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
3530  $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
3531  $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
3532  } else // No supplier price defined for product, even on other suppliers
3533  {
3534  $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
3535  $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
3536  }
3537  }
3538 
3539  if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
3540  $novirtualstock = ($showstockinlist == 2);
3541 
3542  if (!empty($user->rights->stock->lire)) {
3543  $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
3544 
3545  if ($objp->stock > 0) {
3546  $optlabel .= ' - <span class="product_line_stock_ok">';
3547  } elseif ($objp->stock <= 0) {
3548  $optlabel .= ' - <span class="product_line_stock_too_low">';
3549  }
3550  $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
3551  $optlabel .= '</span>';
3552  if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
3553  $langs->load("stocks");
3554 
3555  $tmpproduct = new Product($this->db);
3556  $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
3557  $tmpproduct->load_virtual_stock();
3558  $virtualstock = $tmpproduct->stock_theorique;
3559 
3560  $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
3561 
3562  $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
3563  if ($virtualstock > 0) {
3564  $optlabel .= '<span class="product_line_stock_ok">';
3565  } elseif ($virtualstock <= 0) {
3566  $optlabel .= '<span class="product_line_stock_too_low">';
3567  }
3568  $optlabel .= $virtualstock;
3569  $optlabel .= '</span>';
3570 
3571  unset($tmpproduct);
3572  }
3573  }
3574  }
3575 
3576  $optstart = '<option value="'.$outkey.'"';
3577  if ($selected && $selected == $objp->idprodfournprice) {
3578  $optstart .= ' selected';
3579  }
3580  if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
3581  $optstart .= ' disabled';
3582  }
3583 
3584  if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
3585  $optstart .= ' data-product-id="'.dol_escape_htmltag($objp->rowid).'"';
3586  $optstart .= ' data-price-id="'.dol_escape_htmltag($objp->idprodfournprice).'"';
3587  $optstart .= ' data-qty="'.dol_escape_htmltag($objp->quantity).'"';
3588  $optstart .= ' data-up="'.dol_escape_htmltag(price2num($objp->unitprice)).'"';
3589  $optstart .= ' data-up-locale="'.dol_escape_htmltag(price($objp->unitprice)).'"';
3590  $optstart .= ' data-discount="'.dol_escape_htmltag($outdiscount).'"';
3591  $optstart .= ' data-tvatx="'.dol_escape_htmltag(price2num($objp->tva_tx)).'"';
3592  $optstart .= ' data-tvatx-formated="'.dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)).'"';
3593  $optstart .= ' data-default-vat-code="'.dol_escape_htmltag($objp->default_vat_code).'"';
3594  }
3595  $optstart .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
3596 
3597  $outarrayentry = array(
3598  'key' => $outkey,
3599  'value' => $outref,
3600  'label' => $outvallabel,
3601  'qty' => $outqty,
3602  'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
3603  'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
3604  'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
3605  'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
3606  'tva_tx' => price2num($objp->tva_tx),
3607  'default_vat_code' => $objp->default_vat_code,
3608  'discount' => $outdiscount,
3609  'type' => $outtype,
3610  'duration_value' => $outdurationvalue,
3611  'duration_unit' => $outdurationunit,
3612  'disabled' => (empty($objp->idprodfournprice) ? true : false),
3613  'description' => $objp->description
3614  );
3615 
3616  $parameters = array(
3617  'objp' => &$objp,
3618  'optstart' => &$optstart,
3619  'optlabel' => &$optlabel,
3620  'outvallabel' => &$outvallabel,
3621  'outarrayentry' => &$outarrayentry
3622  );
3623  $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
3624 
3625 
3626  // Add new entry
3627  // "key" value of json key array is used by jQuery automatically as selected value. Example: 'type' = product or service, 'price_ht' = unit price without tax
3628  // "label" value of json key array is used by jQuery automatically as text for combo box
3629  $out .= $optstart . ' data-html="'.dol_escape_htmltag($optlabel).'">' . $optlabel . "</option>\n";;
3630  array_push(
3631  $outarray,
3632  array('key'=>$outkey,
3633  'value'=>$outref,
3634  'label'=>$outvallabel,
3635  'qty'=>$outqty,
3636  'price_qty_ht'=>price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
3637  'price_qty_ht_locale'=>price($objp->fprice),
3638  'price_unit_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
3639  'price_unit_ht_locale'=>price($objp->unitprice),
3640  'price_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
3641  'tva_tx_formated' => price($objp->tva_tx),
3642  'tva_tx'=>price2num($objp->tva_tx),
3643  'default_vat_code'=>$objp->default_vat_code,
3644  'discount'=>$outdiscount,
3645  'type'=>$outtype,
3646  'duration_value'=>$outdurationvalue,
3647  'duration_unit'=>$outdurationunit,
3648  'disabled'=>(empty($objp->idprodfournprice) ? true : false),
3649  'description'=>$objp->description
3650  )
3651  );
3652  // Exemple of var_dump $outarray
3653  // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
3654  // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
3655  // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
3656  //}
3657  //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
3658  //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
3659  //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
3660 
3661  $i++;
3662  }
3663  $out .= '</select>';
3664 
3665  $this->db->free($result);
3666 
3667  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
3668  $out .= ajax_combobox($htmlname);
3669  } else {
3670  dol_print_error($this->db);
3671  }
3672 
3673  if (empty($outputmode)) {
3674  return $out;
3675  }
3676  return $outarray;
3677  }
3678 
3679  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3688  public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
3689  {
3690  // phpcs:enable
3691  global $langs, $conf;
3692 
3693  $langs->load('stocks');
3694 
3695  $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
3696  $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
3697  $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
3698  $sql .= " FROM ".$this->db->prefix()."product as p";
3699  $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
3700  $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
3701  $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
3702  $sql .= " AND p.tobuy = 1";
3703  $sql .= " AND s.fournisseur = 1";
3704  $sql .= " AND p.rowid = ".((int) $productid);
3705  if (empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED)) {
3706  $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
3707  } else {
3708  $sql .= " ORDER BY pfp.unitprice ASC";
3709  }
3710 
3711  dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
3712  $result = $this->db->query($sql);
3713 
3714  if ($result) {
3715  $num = $this->db->num_rows($result);
3716 
3717  $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3718 
3719  if (!$num) {
3720  $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
3721  } else {
3722  require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
3723  $form .= '<option value="0">&nbsp;</option>';
3724 
3725  $i = 0;
3726  while ($i < $num) {
3727  $objp = $this->db->fetch_object($result);
3728 
3729  $opt = '<option value="'.$objp->idprodfournprice.'"';
3730  //if there is only one supplier, preselect it
3731  if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && !empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED))) {
3732  $opt .= ' selected';
3733  }
3734  $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
3735 
3736  if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
3737  $prod_supplier = new ProductFournisseur($this->db);
3738  $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
3739  $prod_supplier->id = $productid;
3740  $prod_supplier->fourn_qty = $objp->quantity;
3741  $prod_supplier->fourn_tva_tx = $objp->tva_tx;
3742  $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
3743 
3744  require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
3745  $priceparser = new PriceParser($this->db);
3746  $price_result = $priceparser->parseProductSupplier($prod_supplier);
3747  if ($price_result >= 0) {
3748  $objp->fprice = $price_result;
3749  if ($objp->quantity >= 1) {
3750  $objp->unitprice = $objp->fprice / $objp->quantity;
3751  }
3752  }
3753  }
3754  if ($objp->quantity == 1) {
3755  $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
3756  }
3757 
3758  $opt .= $objp->quantity.' ';
3759 
3760  if ($objp->quantity == 1) {
3761  $opt .= $langs->trans("Unit");
3762  } else {
3763  $opt .= $langs->trans("Units");
3764  }
3765  if ($objp->quantity > 1) {
3766  $opt .= " - ";
3767  $opt .= price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit");
3768  }
3769  if ($objp->duration) {
3770  $opt .= " - ".$objp->duration;
3771  }
3772  $opt .= "</option>\n";
3773 
3774  $form .= $opt;
3775  $i++;
3776  }
3777  }
3778 
3779  $form .= '</select>';
3780  $this->db->free($result);
3781  return $form;
3782  } else {
3783  dol_print_error($this->db);
3784  }
3785  }
3786 
3787  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3797  public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
3798  {
3799  // phpcs:enable
3800  // looking for users
3801  $sql = "SELECT a.rowid, a.label";
3802  $sql .= " FROM ".$this->db->prefix()."societe_address as a";
3803  $sql .= " WHERE a.fk_soc = ".((int) $socid);
3804  $sql .= " ORDER BY a.label ASC";
3805 
3806  dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
3807  $resql = $this->db->query($sql);
3808  if ($resql) {
3809  print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3810  if ($showempty) {
3811  print '<option value="0">&nbsp;</option>';
3812  }
3813  $num = $this->db->num_rows($resql);
3814  $i = 0;
3815  if ($num) {
3816  while ($i < $num) {
3817  $obj = $this->db->fetch_object($resql);
3818 
3819  if ($selected && $selected == $obj->rowid) {
3820  print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
3821  } else {
3822  print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
3823  }
3824  $i++;
3825  }
3826  }
3827  print '</select>';
3828  return $num;
3829  } else {
3830  dol_print_error($this->db);
3831  }
3832  }
3833 
3834  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3841  {
3842  // phpcs:enable
3843  global $langs;
3844 
3845  $num = count($this->cache_conditions_paiements);
3846  if ($num > 0) {
3847  return 0; // Cache already loaded
3848  }
3849 
3850  dol_syslog(__METHOD__, LOG_DEBUG);
3851 
3852  $sql = "SELECT rowid, code, libelle as label, deposit_percent";
3853  $sql .= " FROM ".$this->db->prefix().'c_payment_term';
3854  $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
3855  $sql .= " AND active > 0";
3856  $sql .= " ORDER BY sortorder";
3857 
3858  $resql = $this->db->query($sql);
3859  if ($resql) {
3860  $num = $this->db->num_rows($resql);
3861  $i = 0;
3862  while ($i < $num) {
3863  $obj = $this->db->fetch_object($resql);
3864 
3865  // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3866  $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
3867  $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
3868  $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
3869  $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
3870  $i++;
3871  }
3872 
3873  //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
3874 
3875  return $num;
3876  } else {
3877  dol_print_error($this->db);
3878  return -1;
3879  }
3880  }
3881 
3882  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3888  public function load_cache_availability()
3889  {
3890  // phpcs:enable
3891  global $langs;
3892 
3893  $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
3894  if ($num > 0) {
3895  return 0; // Cache already loaded
3896  }
3897 
3898  dol_syslog(__METHOD__, LOG_DEBUG);
3899 
3900  $langs->load('propal');
3901 
3902  $sql = "SELECT rowid, code, label, position";
3903  $sql .= " FROM ".$this->db->prefix().'c_availability';
3904  $sql .= " WHERE active > 0";
3905 
3906  $resql = $this->db->query($sql);
3907  if ($resql) {
3908  $num = $this->db->num_rows($resql);
3909  $i = 0;
3910  while ($i < $num) {
3911  $obj = $this->db->fetch_object($resql);
3912 
3913  // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3914  $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
3915  $this->cache_availability[$obj->rowid]['code'] = $obj->code;
3916  $this->cache_availability[$obj->rowid]['label'] = $label;
3917  $this->cache_availability[$obj->rowid]['position'] = $obj->position;
3918  $i++;
3919  }
3920 
3921  $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
3922 
3923  return $num;
3924  } else {
3925  dol_print_error($this->db);
3926  return -1;
3927  }
3928  }
3929 
3940  public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
3941  {
3942  global $langs, $user;
3943 
3944  $this->load_cache_availability();
3945 
3946  dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3947 
3948  print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
3949  if ($addempty) {
3950  print '<option value="0">&nbsp;</option>';
3951  }
3952  foreach ($this->cache_availability as $id => $arrayavailability) {
3953  if ($selected == $id) {
3954  print '<option value="'.$id.'" selected>';
3955  } else {
3956  print '<option value="'.$id.'">';
3957  }
3958  print dol_escape_htmltag($arrayavailability['label']);
3959  print '</option>';
3960  }
3961  print '</select>';
3962  if ($user->admin) {
3963  print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
3964  }
3965  print ajax_combobox($htmlname);
3966  }
3967 
3973  public function loadCacheInputReason()
3974  {
3975  global $langs;
3976 
3977  $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
3978  if ($num > 0) {
3979  return 0; // Cache already loaded
3980  }
3981 
3982  $sql = "SELECT rowid, code, label";
3983  $sql .= " FROM ".$this->db->prefix().'c_input_reason';
3984  $sql .= " WHERE active > 0";
3985 
3986  $resql = $this->db->query($sql);
3987  if ($resql) {
3988  $num = $this->db->num_rows($resql);
3989  $i = 0;
3990  $tmparray = array();
3991  while ($i < $num) {
3992  $obj = $this->db->fetch_object($resql);
3993 
3994  // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3995  $label = ($obj->label != '-' ? $obj->label : '');
3996  if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
3997  $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
3998  }
3999  if ($langs->trans($obj->code) != $obj->code) {
4000  $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
4001  }
4002 
4003  $tmparray[$obj->rowid]['id'] = $obj->rowid;
4004  $tmparray[$obj->rowid]['code'] = $obj->code;
4005  $tmparray[$obj->rowid]['label'] = $label;
4006  $i++;
4007  }
4008 
4009  $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
4010 
4011  unset($tmparray);
4012  return $num;
4013  } else {
4014  dol_print_error($this->db);
4015  return -1;
4016  }
4017  }
4018 
4031  public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
4032  {
4033  global $langs, $user;
4034 
4035  $this->loadCacheInputReason();
4036 
4037  print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
4038  if ($addempty) {
4039  print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
4040  }
4041  foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
4042  if ($arraydemandreason['code'] == $exclude) {
4043  continue;
4044  }
4045 
4046  if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
4047  print '<option value="'.$arraydemandreason['id'].'" selected>';
4048  } else {
4049  print '<option value="'.$arraydemandreason['id'].'">';
4050  }
4051  $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
4052  print $langs->trans($label);
4053  print '</option>';
4054  }
4055  print '</select>';
4056  if ($user->admin && empty($notooltip)) {
4057  print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
4058  }
4059  print ajax_combobox('select_'.$htmlname);
4060  }
4061 
4062  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4068  public function load_cache_types_paiements()
4069  {
4070  // phpcs:enable
4071  global $langs;
4072 
4073  $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
4074  if ($num > 0) {
4075  return $num; // Cache already loaded
4076  }
4077 
4078  dol_syslog(__METHOD__, LOG_DEBUG);
4079 
4080  $this->cache_types_paiements = array();
4081 
4082  $sql = "SELECT id, code, libelle as label, type, active";
4083  $sql .= " FROM ".$this->db->prefix()."c_paiement";
4084  $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
4085 
4086  $resql = $this->db->query($sql);
4087  if ($resql) {
4088  $num = $this->db->num_rows($resql);
4089  $i = 0;
4090  while ($i < $num) {
4091  $obj = $this->db->fetch_object($resql);
4092 
4093  // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
4094  $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
4095  $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
4096  $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
4097  $this->cache_types_paiements[$obj->id]['label'] = $label;
4098  $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
4099  $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
4100  $i++;
4101  }
4102 
4103  $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
4104 
4105  return $num;
4106  } else {
4107  dol_print_error($this->db);
4108  return -1;
4109  }
4110  }
4111 
4112 
4113  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4131  public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
4132  {
4133  // phpcs:enable
4134  print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
4135  }
4136 
4137 
4154  public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
4155  {
4156  global $langs, $user, $conf;
4157 
4158  $out = '';
4159  dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
4160 
4162 
4163  // Set default value if not already set by caller
4164  if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
4165  $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
4166  }
4167 
4168  $out.= '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
4169  if ($addempty) {
4170  $out.= '<option value="0">&nbsp;</option>';
4171  }
4172 
4173  $selectedDepositPercent = null;
4174 
4175  foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
4176  if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
4177  continue;
4178  }
4179 
4180  if ($selected == $id) {
4181  $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
4182  $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
4183  } else {
4184  $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
4185  }
4186  $label = $arrayconditions['label'];
4187 
4188  if (!empty($arrayconditions['deposit_percent'])) {
4189  $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
4190  }
4191 
4192  $out.= $label;
4193  $out.= '</option>';
4194  }
4195  $out.= '</select>';
4196  if ($user->admin && empty($noinfoadmin)) {
4197  $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
4198  }
4199  $out.= ajax_combobox($htmlname);
4200 
4201  if ($deposit_percent >= 0) {
4202  $out .= ' <span id="'.$htmlname.'_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
4203  $out .= $langs->trans('DepositPercent') . ' : ';
4204  $out .= '<input id="'.$htmlname.'_deposit_percent" name="'.$htmlname.'_deposit_percent" class="maxwidth50" value="' . strval($deposit_percent) . '" />';
4205  $out .= '</span>';
4206  $out .= '
4207  <script>
4208  $(document).ready(function () {
4209  $("#' . $htmlname . '").change(function () {
4210  let $selected = $(this).find("option:selected");
4211  let depositPercent = $selected.attr("data-deposit_percent");
4212 
4213  if (depositPercent.length > 0) {
4214  $("#'.$htmlname.'_deposit_percent_container").show().find("#'.$htmlname.'_deposit_percent").val(depositPercent);
4215  } else {
4216  $("#'.$htmlname.'_deposit_percent_container").hide();
4217  }
4218 
4219  return true;
4220  });
4221  });
4222  </script>';
4223  }
4224 
4225  return $out;
4226  }
4227 
4228 
4229  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4246  public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
4247  {
4248  // phpcs:enable
4249  global $langs, $user, $conf;
4250 
4251  $out = '';
4252 
4253  dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
4254 
4255  $filterarray = array();
4256  if ($filtertype == 'CRDT') {
4257  $filterarray = array(0, 2, 3);
4258  } elseif ($filtertype == 'DBIT') {
4259  $filterarray = array(1, 2, 3);
4260  } elseif ($filtertype != '' && $filtertype != '-1') {
4261  $filterarray = explode(',', $filtertype);
4262  }
4263 
4264  $this->load_cache_types_paiements();
4265 
4266  // Set default value if not already set by caller
4267  if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
4268  $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
4269  }
4270 
4271  $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
4272  if ($empty) {
4273  $out .= '<option value="">&nbsp;</option>';
4274  }
4275  foreach ($this->cache_types_paiements as $id => $arraytypes) {
4276  // If not good status
4277  if ($active >= 0 && $arraytypes['active'] != $active) {
4278  continue;
4279  }
4280 
4281  // On passe si on a demande de filtrer sur des modes de paiments particuliers
4282  if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
4283  continue;
4284  }
4285 
4286  // We discard empty line if showempty is on because an empty line has already been output.
4287  if ($empty && empty($arraytypes['code'])) {
4288  continue;
4289  }
4290 
4291  if ($format == 0) {
4292  $out .= '<option value="'.$id.'"';
4293  } elseif ($format == 1) {
4294  $out .= '<option value="'.$arraytypes['code'].'"';
4295  } elseif ($format == 2) {
4296  $out .= '<option value="'.$arraytypes['code'].'"';
4297  } elseif ($format == 3) {
4298  $out .= '<option value="'.$id.'"';
4299  }
4300  // Print attribute selected or not
4301  if ($format == 1 || $format == 2) {
4302  if ($selected == $arraytypes['code']) {
4303  $out .= ' selected';
4304  }
4305  } else {
4306  if ($selected == $id) {
4307  $out .= ' selected';
4308  }
4309  }
4310  $out .= '>';
4311  $value = '';
4312  if ($format == 0) {
4313  $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
4314  } elseif ($format == 1) {
4315  $value = $arraytypes['code'];
4316  } elseif ($format == 2) {
4317  $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
4318  } elseif ($format == 3) {
4319  $value = $arraytypes['code'];
4320  }
4321  $out .= $value ? $value : '&nbsp;';
4322  $out .= '</option>';
4323  }
4324  $out .= '</select>';
4325  if ($user->admin && !$noadmininfo) {
4326  $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
4327  }
4328  $out .= ajax_combobox('select'.$htmlname);
4329 
4330  if (empty($nooutput)) {
4331  print $out;
4332  } else {
4333  return $out;
4334  }
4335  }
4336 
4337 
4346  public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
4347  {
4348  global $langs;
4349 
4350  $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
4351  $options = array(
4352  'HT'=>$langs->trans("HT"),
4353  'TTC'=>$langs->trans("TTC")
4354  );
4355  foreach ($options as $id => $value) {
4356  if ($selected == $id) {
4357  $return .= '<option value="'.$id.'" selected>'.$value;
4358  } else {
4359  $return .= '<option value="'.$id.'">'.$value;
4360  }
4361  $return .= '</option>';
4362  }
4363  $return .= '</select>';
4364  if ($addjscombo) {
4365  $return .= ajax_combobox('select_'.$htmlname);
4366  }
4367 
4368  return $return;
4369  }
4370 
4371  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4377  public function load_cache_transport_mode()
4378  {
4379  // phpcs:enable
4380  global $langs;
4381 
4382  $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
4383  if ($num > 0) {
4384  return $num; // Cache already loaded
4385  }
4386 
4387  dol_syslog(__METHOD__, LOG_DEBUG);
4388 
4389  $this->cache_transport_mode = array();
4390 
4391  $sql = "SELECT rowid, code, label, active";
4392  $sql .= " FROM ".$this->db->prefix()."c_transport_mode";
4393  $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
4394 
4395  $resql = $this->db->query($sql);
4396  if ($resql) {
4397  $num = $this->db->num_rows($resql);
4398  $i = 0;
4399  while ($i < $num) {
4400  $obj = $this->db->fetch_object($resql);
4401 
4402  // If traduction exist, we use it else we take the default label
4403  $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
4404  $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
4405  $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
4406  $this->cache_transport_mode[$obj->rowid]['label'] = $label;
4407  $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
4408  $i++;
4409  }
4410 
4411  $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
4412 
4413  return $num;
4414  } else {
4415  dol_print_error($this->db);
4416  return -1;
4417  }
4418  }
4419 
4433  public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
4434  {
4435  global $langs, $user;
4436 
4437  dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
4438 
4439  $this->load_cache_transport_mode();
4440 
4441  print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
4442  if ($empty) {
4443  print '<option value="">&nbsp;</option>';
4444  }
4445  foreach ($this->cache_transport_mode as $id => $arraytypes) {
4446  // If not good status
4447  if ($active >= 0 && $arraytypes['active'] != $active) {
4448  continue;
4449  }
4450 
4451  // We discard empty line if showempty is on because an empty line has already been output.
4452  if ($empty && empty($arraytypes['code'])) {
4453  continue;
4454  }
4455 
4456  if ($format == 0) {
4457  print '<option value="'.$id.'"';
4458  } elseif ($format == 1) {
4459  print '<option value="'.$arraytypes['code'].'"';
4460  } elseif ($format == 2) {
4461  print '<option value="'.$arraytypes['code'].'"';
4462  } elseif ($format == 3) {
4463  print '<option value="'.$id.'"';
4464  }
4465  // If text is selected, we compare with code, else with id
4466  if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
4467  print ' selected';
4468  } elseif ($selected == $id) {
4469  print ' selected';
4470  }
4471  print '>';
4472  $value = '';
4473  if ($format == 0) {
4474  $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
4475  } elseif ($format == 1) {
4476  $value = $arraytypes['code'];
4477  } elseif ($format == 2) {
4478  $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
4479  } elseif ($format == 3) {
4480  $value = $arraytypes['code'];
4481  }
4482  print $value ? $value : '&nbsp;';
4483  print '</option>';
4484  }
4485  print '</select>';
4486  if ($user->admin && !$noadmininfo) {
4487  print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
4488  }
4489  }
4490 
4503  public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
4504  {
4505  global $langs, $conf, $user;
4506 
4507  $langs->load("admin");
4508  $langs->load("deliveries");
4509 
4510  $sql = "SELECT rowid, code, libelle as label";
4511  $sql .= " FROM ".$this->db->prefix()."c_shipment_mode";
4512  $sql .= " WHERE active > 0";
4513  if ($filtre) {
4514  $sql .= " AND ".$filtre;
4515  }
4516  $sql .= " ORDER BY libelle ASC";
4517 
4518  dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
4519  $result = $this->db->query($sql);
4520  if ($result) {
4521  $num = $this->db->num_rows($result);
4522  $i = 0;
4523  if ($num) {
4524  print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
4525  if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
4526  print '<option value="-1">&nbsp;</option>';
4527  }
4528  while ($i < $num) {
4529  $obj = $this->db->fetch_object($result);
4530  if ($selected == $obj->rowid) {
4531  print '<option value="'.$obj->rowid.'" selected>';
4532  } else {
4533  print '<option value="'.$obj->rowid.'">';
4534  }
4535  print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
4536  print '</option>';
4537  $i++;
4538  }
4539  print "</select>";
4540  if ($user->admin && empty($noinfoadmin)) {
4541  print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
4542  }
4543 
4544  print ajax_combobox('select'.$htmlname);
4545  } else {
4546  print $langs->trans("NoShippingMethodDefined");
4547  }
4548  } else {
4549  dol_print_error($this->db);
4550  }
4551  }
4552 
4562  public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
4563  {
4564  global $langs;
4565 
4566  $langs->load("deliveries");
4567 
4568  if ($htmlname != "none") {
4569  print '<form method="POST" action="'.$page.'">';
4570  print '<input type="hidden" name="action" value="setshippingmethod">';
4571  print '<input type="hidden" name="token" value="'.newToken().'">';
4572  $this->selectShippingMethod($selected, $htmlname, '', $addempty);
4573  print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4574  print '</form>';
4575  } else {
4576  if ($selected) {
4577  $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
4578  print $langs->trans("SendingMethod".strtoupper($code));
4579  } else {
4580  print "&nbsp;";
4581  }
4582  }
4583  }
4584 
4593  public function selectSituationInvoices($selected = '', $socid = 0)
4594  {
4595  global $langs;
4596 
4597  $langs->load('bills');
4598 
4599  $opt = '<option value="" selected></option>';
4600  $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
4601  $sql .= ' FROM '.$this->db->prefix().'facture';
4602  $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
4603  $sql .= ' AND situation_counter >= 1';
4604  $sql .= ' AND fk_soc = '.(int) $socid;
4605  $sql .= ' AND type <> 2';
4606  $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
4607  $resql = $this->db->query($sql);
4608 
4609  if ($resql && $this->db->num_rows($resql) > 0) {
4610  // Last seen cycle
4611  $ref = 0;
4612  while ($obj = $this->db->fetch_object($resql)) {
4613  //Same cycle ?
4614  if ($obj->situation_cycle_ref != $ref) {
4615  // Just seen this cycle
4616  $ref = $obj->situation_cycle_ref;
4617  //not final ?
4618  if ($obj->situation_final != 1) {
4619  //Not prov?
4620  if (substr($obj->ref, 1, 4) != 'PROV') {
4621  if ($selected == $obj->rowid) {
4622  $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
4623  } else {
4624  $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
4625  }
4626  }
4627  }
4628  }
4629  }
4630  } else {
4631  dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
4632  }
4633  if ($opt == '<option value ="" selected></option>') {
4634  $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
4635  }
4636  return $opt;
4637  }
4638 
4648  public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
4649  {
4650  global $langs;
4651 
4652  $langs->load('products');
4653 
4654  $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
4655 
4656  $sql = "SELECT rowid, label, code FROM ".$this->db->prefix()."c_units";
4657  $sql .= ' WHERE active > 0';
4658  if (!empty($unit_type)) {
4659  $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
4660  }
4661  $sql .= " ORDER BY sortorder";
4662 
4663  $resql = $this->db->query($sql);
4664  if ($resql && $this->db->num_rows($resql) > 0) {
4665  if ($showempty) {
4666  $return .= '<option value="none"></option>';
4667  }
4668 
4669  while ($res = $this->db->fetch_object($resql)) {
4670  $unitLabel = $res->label;
4671  if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
4672  $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
4673  }
4674 
4675  if ($selected == $res->rowid) {
4676  $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
4677  } else {
4678  $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
4679  }
4680  }
4681  $return .= '</select>';
4682  }
4683  return $return;
4684  }
4685 
4686  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4701  public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
4702  {
4703  // phpcs:enable
4704  global $langs, $conf;
4705 
4706  $out = '';
4707 
4708  $langs->load("admin");
4709  $num = 0;
4710 
4711  $sql = "SELECT rowid, label, bank, clos as status, currency_code";
4712  $sql .= " FROM ".$this->db->prefix()."bank_account";
4713  $sql .= " WHERE entity IN (".getEntity('bank_account').")";
4714  if ($status != 2) {
4715  $sql .= " AND clos = ".(int) $status;
4716  }
4717  if ($filtre) {
4718  $sql .= " AND ".$filtre;
4719  }
4720  $sql .= " ORDER BY label";
4721 
4722  dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
4723  $result = $this->db->query($sql);
4724  if ($result) {
4725  $num = $this->db->num_rows($result);
4726  $i = 0;
4727  if ($num) {
4728  $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
4729  if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
4730  $out .= '<option value="-1">&nbsp;</option>';
4731  }
4732 
4733  while ($i < $num) {
4734  $obj = $this->db->fetch_object($result);
4735  if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
4736  $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
4737  } else {
4738  $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
4739  }
4740  $out .= trim($obj->label);
4741  if ($showcurrency) {
4742  $out .= ' ('.$obj->currency_code.')';
4743  }
4744  if ($status == 2 && $obj->status == 1) {
4745  $out .= ' ('.$langs->trans("Closed").')';
4746  }
4747  $out .= '</option>';
4748  $i++;
4749  }
4750  $out .= "</select>";
4751  $out .= ajax_combobox('select'.$htmlname);
4752  } else {
4753  if ($status == 0) {
4754  $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
4755  } else {
4756  $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
4757  }
4758  }
4759  } else {
4760  dol_print_error($this->db);
4761  }
4762 
4763  // Output or return
4764  if (empty($nooutput)) {
4765  print $out;
4766  } else {
4767  return $out;
4768  }
4769 
4770  return $num;
4771  }
4772 
4784  public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
4785  {
4786  global $langs, $conf;
4787 
4788  $langs->load("admin");
4789  $num = 0;
4790 
4791  $sql = "SELECT rowid, name, fk_country, status, entity";
4792  $sql .= " FROM ".$this->db->prefix()."establishment";
4793  $sql .= " WHERE 1=1";
4794  if ($status != 2) {
4795  $sql .= " AND status = ".(int) $status;
4796  }
4797  if ($filtre) {
4798  $sql .= " AND ".$filtre;
4799  }
4800  $sql .= " ORDER BY name";
4801 
4802  dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
4803  $result = $this->db->query($sql);
4804  if ($result) {
4805  $num = $this->db->num_rows($result);
4806  $i = 0;
4807  if ($num) {
4808  print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
4809  if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
4810  print '<option value="-1">&nbsp;</option>';
4811  }
4812 
4813  while ($i < $num) {
4814  $obj = $this->db->fetch_object($result);
4815  if ($selected == $obj->rowid) {
4816  print '<option value="'.$obj->rowid.'" selected>';
4817  } else {
4818  print '<option value="'.$obj->rowid.'">';
4819  }
4820  print trim($obj->name);
4821  if ($status == 2 && $obj->status == 1) {
4822  print ' ('.$langs->trans("Closed").')';
4823  }
4824  print '</option>';
4825  $i++;
4826  }
4827  print "</select>";
4828  } else {
4829  if ($status == 0) {
4830  print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
4831  } else {
4832  print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
4833  }
4834  }
4835  } else {
4836  dol_print_error($this->db);
4837  }
4838  }
4839 
4849  public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
4850  {
4851  global $langs;
4852  if ($htmlname != "none") {
4853  print '<form method="POST" action="'.$page.'">';
4854  print '<input type="hidden" name="action" value="setbankaccount">';
4855  print '<input type="hidden" name="token" value="'.newToken().'">';
4856  print img_picto('', 'bank_account', 'class="pictofixedwidth"');
4857  $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
4858  if ($nbaccountfound > 0) {
4859  print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
4860  }
4861  print '</form>';
4862  } else {
4863  $langs->load('banks');
4864 
4865  if ($selected) {
4866  require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
4867  $bankstatic = new Account($this->db);
4868  $result = $bankstatic->fetch($selected);
4869  if ($result) {
4870  print $bankstatic->getNomUrl(1);
4871  }
4872  } else {
4873  print "&nbsp;";
4874  }
4875  }
4876  }
4877 
4878  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4897  public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
4898  {
4899  // phpcs:enable
4900  global $conf, $langs;
4901  $langs->load("categories");
4902 
4903  include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
4904 
4905  // For backward compatibility
4906  if (is_numeric($type)) {
4907  dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
4908  }
4909 
4910  if ($type === Categorie::TYPE_BANK_LINE) {
4911  // TODO Move this into common category feature
4912  $cate_arbo = array();
4913  $sql = "SELECT c.label, c.rowid";
4914  $sql .= " FROM ".$this->db->prefix()."bank_categ as c";
4915  $sql .= " WHERE entity = ".$conf->entity;
4916  $sql .= " ORDER BY c.label";
4917  $result = $this->db->query($sql);
4918  if ($result) {
4919  $num = $this->db->num_rows($result);
4920  $i = 0;
4921  while ($i < $num) {
4922  $objp = $this->db->fetch_object($result);
4923  if ($objp) {
4924  $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label, 'color'=>'', 'picto'=>'category');
4925  }
4926  $i++;
4927  }
4928  $this->db->free($result);
4929  } else {
4930  dol_print_error($this->db);
4931  }
4932  } else {
4933  $cat = new Categorie($this->db);
4934  $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
4935  }
4936 
4937  $outarray = array();
4938 
4939  $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
4940  if (is_array($cate_arbo)) {
4941  if (!count($cate_arbo)) {
4942  $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
4943  } else {
4944  $output .= '<option value="-1">&nbsp;</option>';
4945  foreach ($cate_arbo as $key => $value) {
4946  if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
4947  $add = 'selected ';
4948  } else {
4949  $add = '';
4950  }
4951  $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'"';
4952  $output .= ' data-html="'.dol_escape_htmltag(img_picto('', 'category', 'class="pictofixedwidth" style="color: #'.$cate_arbo[$key]['color'].'"').dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle')).'"';
4953  $output .= '>';
4954  $output .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
4955  $output .= '</option>';
4956 
4957  $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
4958  }
4959  }
4960  }
4961  $output .= '</select>';
4962  $output .= "\n";
4963 
4964  if ($outputmode == 2) {
4965  return $cate_arbo;
4966  } elseif ($outputmode) {
4967  return $outarray;
4968  }
4969  return $output;
4970  }
4971 
4972  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4989  public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
4990  {
4991  // phpcs:enable
4992  dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
4993  print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
4994  }
4995 
5023  public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
5024  {
5025  global $langs, $conf;
5026 
5027  $more = '<!-- formconfirm - before call, page='.dol_escape_htmltag($page).' -->';
5028  $formconfirm = '';
5029  $inputok = array();
5030  $inputko = array();
5031 
5032  // Clean parameters
5033  $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
5034  if ($conf->browser->layout == 'phone') {
5035  $width = '95%';
5036  }
5037 
5038  // Set height automatically if not defined
5039  if (empty($height)) {
5040  $height = 220;
5041  if (is_array($formquestion) && count($formquestion) > 2) {
5042  $height += ((count($formquestion) - 2) * 24);
5043  }
5044  }
5045 
5046  if (is_array($formquestion) && !empty($formquestion)) {
5047  // First add hidden fields and value
5048  foreach ($formquestion as $key => $input) {
5049  if (is_array($input) && !empty($input)) {
5050  if ($input['type'] == 'hidden') {
5051  $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
5052  $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
5053 
5054  $more .= '<input type="hidden" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'" value="'.dol_escape_htmltag($input['value']).'" class="'.$morecss.'"'.$moreattr.'>'."\n";
5055  }
5056  }
5057  }
5058 
5059  // Now add questions
5060  $moreonecolumn = '';
5061  $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
5062  foreach ($formquestion as $key => $input) {
5063  if (is_array($input) && !empty($input)) {
5064  $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
5065  $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
5066  $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
5067 
5068  if ($input['type'] == 'text') {
5069  $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="text" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.(empty($input['value']) ? '' : $input['value']).'"'.$moreattr.' /></div></div>'."\n";
5070  } elseif ($input['type'] == 'password') {
5071  $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="password" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.(empty($input['value']) ? '' : $input['value']).'"'.$moreattr.' /></div></div>'."\n";
5072  } elseif ($input['type'] == 'textarea') {
5073  /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
5074  $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
5075  $more .= $input['value'];
5076  $more .= '</textarea>';
5077  $more .= '</div></div>'."\n";*/
5078  $moreonecolumn .= '<div class="margintoponly">';
5079  $moreonecolumn .= $input['label'].'<br>';
5080  $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
5081  $moreonecolumn .= $input['value'];
5082  $moreonecolumn .= '</textarea>';
5083  $moreonecolumn .= '</div>';
5084  } elseif (in_array($input['type'], ['select', 'multiselect'])) {
5085  if (empty($morecss)) {
5086  $morecss = 'minwidth100';
5087  }
5088 
5089  $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
5090  $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
5091  $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
5092  $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
5093  $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
5094  $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
5095  $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
5096 
5097  $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
5098  if (!empty($input['label'])) {
5099  $more .= $input['label'].'</div><div class="tagtd left">';
5100  }
5101  if ($input['type'] == 'select') {
5102  $more .= $this->selectarray($input['name'], $input['values'], !empty($input['default']) ? $input['default'] : '-1', $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
5103  } else {
5104  $more .= $this->multiselectarray($input['name'], $input['values'], is_array($input['default']) ? $input['default'] : [$input['default']], $key_in_label, $value_as_key, $morecss, $translate, $maxlen, $moreattr);
5105  }
5106  $more .= '</div></div>'."\n";
5107  } elseif ($input['type'] == 'checkbox') {
5108  $more .= '<div class="tagtr">';
5109  $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
5110  $more .= '<input type="checkbox" class="flat'.($morecss ? ' '.$morecss : '').'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
5111  if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
5112  $more .= ' checked';
5113  }
5114  if (is_bool($input['value']) && $input['value']) {
5115  $more .= ' checked';
5116  }
5117  if (isset($input['disabled'])) {
5118  $more .= ' disabled';
5119  }
5120  $more .= ' /></div>';
5121  $more .= '</div>'."\n";
5122  } elseif ($input['type'] == 'radio') {
5123  $i = 0;
5124  foreach ($input['values'] as $selkey => $selval) {
5125  $more .= '<div class="tagtr">';
5126  if (isset($input['label'])) {
5127  if ($i == 0) {
5128  $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
5129  } else {
5130  $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
5131  }
5132  }
5133  $more .= '<div class="tagtd'.($i == 0 ? ' tdtop' : '').'"><input type="radio" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name'].$selkey).'" name="'.dol_escape_htmltag($input['name']).'" value="'.$selkey.'"'.$moreattr;
5134  if (!empty($input['disabled'])) {
5135  $more .= ' disabled';
5136  }
5137  if (isset($input['default']) && $input['default'] === $selkey) {
5138  $more .= ' checked="checked"';
5139  }
5140  $more .= ' /> ';
5141  $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'" class="valignmiddle">'.$selval.'</label>';
5142  $more .= '</div></div>'."\n";
5143  $i++;
5144  }
5145  } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
5146  $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
5147  $more .= '<div class="tagtd">';
5148  $addnowlink = (empty($input['datenow']) ? 0 : 1);
5149  $more .= $this->selectDate($input['value'], $input['name'], ($input['type'] == 'datetime' ? 1 : 0), ($input['type'] == 'datetime' ? 1 : 0), 0, '', 1, $addnowlink);
5150  $more .= '</div></div>'."\n";
5151  $formquestion[] = array('name'=>$input['name'].'day');
5152  $formquestion[] = array('name'=>$input['name'].'month');
5153  $formquestion[] = array('name'=>$input['name'].'year');
5154  $formquestion[] = array('name'=>$input['name'].'hour');
5155  $formquestion[] = array('name'=>$input['name'].'min');
5156  } elseif ($input['type'] == 'other') {
5157  $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
5158  if (!empty($input['label'])) {
5159  $more .= $input['label'].'</div><div class="tagtd">';
5160  }
5161  $more .= $input['value'];
5162  $more .= '</div></div>'."\n";
5163  } elseif ($input['type'] == 'onecolumn') {
5164  $moreonecolumn .= '<div class="margintoponly">';
5165  $moreonecolumn .= $input['value'];
5166  $moreonecolumn .= '</div>'."\n";
5167  } elseif ($input['type'] == 'hidden') {
5168  // Do nothing more, already added by a previous loop
5169  } elseif ($input['type'] == 'separator') {
5170  $more .= '<br>';
5171  } else {
5172  $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
5173  }
5174  }
5175  }
5176  $more .= '</div>'."\n";
5177  $more .= $moreonecolumn;
5178  }
5179 
5180  // JQUERY method dialog is broken with smartphone, we use standard HTML.
5181  // 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
5182  // See page product/card.php for example
5183  if (!empty($conf->dol_use_jmobile)) {
5184  $useajax = 0;
5185  }
5186  if (empty($conf->use_javascript_ajax)) {
5187  $useajax = 0;
5188  }
5189 
5190  if ($useajax) {
5191  $autoOpen = true;
5192  $dialogconfirm = 'dialog-confirm';
5193  $button = '';
5194  if (!is_numeric($useajax)) {
5195  $button = $useajax;
5196  $useajax = 1;
5197  $autoOpen = false;
5198  $dialogconfirm .= '-'.$button;
5199  }
5200  $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=yes';
5201  $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=no' : '');
5202 
5203  // Add input fields into list of fields to read during submit (inputok and inputko)
5204  if (is_array($formquestion)) {
5205  foreach ($formquestion as $key => $input) {
5206  //print "xx ".$key." rr ".is_array($input)."<br>\n";
5207  // Add name of fields to propagate with the GET when submitting the form with button OK.
5208  if (is_array($input) && isset($input['name'])) {
5209  if (strpos($input['name'], ',') > 0) {
5210  $inputok = array_merge($inputok, explode(',', $input['name']));
5211  } else {
5212  array_push($inputok, $input['name']);
5213  }
5214  }
5215  // Add name of fields to propagate with the GET when submitting the form with button KO.
5216  if (isset($input['inputko']) && $input['inputko'] == 1) {
5217  array_push($inputko, $input['name']);
5218  }
5219  }
5220  }
5221 
5222  // Show JQuery confirm box.
5223  $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
5224  if (is_array($formquestion) && !empty($formquestion['text'])) {
5225  $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
5226  }
5227  if (!empty($more)) {
5228  $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
5229  }
5230  $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
5231  $formconfirm .= '</div>'."\n";
5232 
5233  $formconfirm .= "\n<!-- begin code of popup for formconfirm page=".$page." -->\n";
5234  $formconfirm .= '<script type="text/javascript">'."\n";
5235  $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
5236  $formconfirm .= 'jQuery(document).ready(function() {
5237  $(function() {
5238  $( "#'.$dialogconfirm.'" ).dialog(
5239  {
5240  autoOpen: '.($autoOpen ? "true" : "false").',';
5241  if ($newselectedchoice == 'no') {
5242  $formconfirm .= '
5243  open: function() {
5244  $(this).parent().find("button.ui-button:eq(2)").focus();
5245  },';
5246  }
5247 
5248  $jsforcursor = '';
5249  if ($useajax == 1) {
5250  $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor'."\n";
5251  $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");'."\n";
5252  }
5253 
5254  $postconfirmas = 'GET';
5255 
5256  $formconfirm .= '
5257  resizable: false,
5258  height: "'.$height.'",
5259  width: "'.$width.'",
5260  modal: true,
5261  closeOnEscape: false,
5262  buttons: {
5263  "'.dol_escape_js($langs->transnoentities($labelbuttonyes)).'": function() {
5264  var options = "token='.urlencode(newToken()).'";
5265  var inputok = '.json_encode($inputok).'; /* List of fields into form */
5266  var page = "'.dol_escape_js(!empty($page) ? $page : '').'";
5267  var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
5268 
5269  if (inputok.length > 0) {
5270  $.each(inputok, function(i, inputname) {
5271  var more = "";
5272  var inputvalue;
5273  if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
5274  inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
5275  } else {
5276  if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
5277  inputvalue = $("#" + inputname + more).val();
5278  }
5279  if (typeof inputvalue == "undefined") { inputvalue=""; }
5280  console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
5281  options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
5282  });
5283  }
5284  var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
5285  if (pageyes.length > 0) {';
5286  if ($postconfirmas == 'GET') {
5287  $formconfirm .= 'location.href = urljump;';
5288  } else {
5289  $formconfirm .= $jsforcursor;
5290  $formconfirm .= 'var post = $.post(
5291  pageyes,
5292  options,
5293  function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
5294  );';
5295  }
5296  $formconfirm .= '
5297  console.log("after post ok");
5298  }
5299  $(this).dialog("close");
5300  },
5301  "'.dol_escape_js($langs->transnoentities($labelbuttonno)).'": function() {
5302  var options = "token='.urlencode(newToken()).'";
5303  var inputko = '.json_encode($inputko).'; /* List of fields into form */
5304  var page = "'.dol_escape_js(!empty($page) ? $page : '').'";
5305  var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
5306  if (inputko.length > 0) {
5307  $.each(inputko, function(i, inputname) {
5308  var more = "";
5309  if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
5310  var inputvalue = $("#" + inputname + more).val();
5311  if (typeof inputvalue == "undefined") { inputvalue=""; }
5312  options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
5313  });
5314  }
5315  var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
5316  //alert(urljump);
5317  if (pageno.length > 0) {';
5318  if ($postconfirmas == 'GET') {
5319  $formconfirm .= 'location.href = urljump;';
5320  } else {
5321  $formconfirm .= $jsforcursor;
5322  $formconfirm .= 'var post = $.post(
5323  pageno,
5324  options,
5325  function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
5326  );';
5327  }
5328  $formconfirm .= '
5329  console.log("after post ko");
5330  }
5331  $(this).dialog("close");
5332  }
5333  }
5334  }
5335  );
5336 
5337  var button = "'.$button.'";
5338  if (button.length > 0) {
5339  $( "#" + button ).click(function() {
5340  $("#'.$dialogconfirm.'").dialog("open");
5341  });
5342  }
5343  });
5344  });
5345  </script>';
5346  $formconfirm .= "<!-- end ajax formconfirm -->\n";
5347  } else {
5348  $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
5349 
5350  if (empty($disableformtag)) {
5351  $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
5352  }
5353 
5354  $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
5355  $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
5356 
5357  $formconfirm .= '<table class="valid centpercent">'."\n";
5358 
5359  // Line title
5360  $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
5361  $formconfirm .= img_picto('', 'pictoconfirm').' '.$title;
5362  $formconfirm .= '</td></tr>'."\n";
5363 
5364  // Line text
5365  if (is_array($formquestion) && !empty($formquestion['text'])) {
5366  $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
5367  }
5368 
5369  // Line form fields
5370  if ($more) {
5371  $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
5372  $formconfirm .= $more;
5373  $formconfirm .= '</td></tr>'."\n";
5374  }
5375 
5376  // Line with question
5377  $formconfirm .= '<tr class="valid">';
5378  $formconfirm .= '<td class="valid">'.$question.'</td>';
5379  $formconfirm .= '<td class="valid center">';
5380  $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
5381  $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="'.$langs->trans("Validate").'">';
5382  $formconfirm .= '</td>';
5383  $formconfirm .= '</tr>'."\n";
5384 
5385  $formconfirm .= '</table>'."\n";
5386 
5387  if (empty($disableformtag)) {
5388  $formconfirm .= "</form>\n";
5389  }
5390  $formconfirm .= '<br>';
5391 
5392  if (!empty($conf->use_javascript_ajax)) {
5393  $formconfirm .= '<!-- code to disable button to avoid double clic -->';
5394  $formconfirm .= '<script type="text/javascript">'."\n";
5395  $formconfirm .= '
5396  $(document).ready(function () {
5397  $(".confirmvalidatebutton").on("click", function() {
5398  console.log("We click on button");
5399  $(this).attr("disabled", "disabled");
5400  setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
5401  //console.log($(this).closest("form"));
5402  $(this).closest("form").submit();
5403  });
5404  });
5405  ';
5406  $formconfirm .= '</script>'."\n";
5407  }
5408 
5409  $formconfirm .= "<!-- end formconfirm -->\n";
5410  }
5411 
5412  return $formconfirm;
5413  }
5414 
5415 
5416  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5432  public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '')
5433  {
5434  // phpcs:enable
5435  global $langs;
5436 
5437  require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
5438  require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
5439 
5440  $out = '';
5441 
5442  $formproject = new FormProjets($this->db);
5443 
5444  $langs->load("project");
5445  if ($htmlname != "none") {
5446  $out .= '<form method="post" action="'.$page.'">';
5447  $out .= '<input type="hidden" name="action" value="classin">';
5448  $out .= '<input type="hidden" name="token" value="'.newToken().'">';
5449  $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
5450  $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
5451  $out .= '</form>';
5452  } else {
5453  $out .= '<span class="project_head_block">';
5454  if ($selected) {
5455  $projet = new Project($this->db);
5456  $projet->fetch($selected);
5457  $out .= $projet->getNomUrl(0, '', 1);
5458  } else {
5459  $out .= '<span class="opacitymedium">'.$textifnoproject.'</span>';
5460  }
5461  $out .= '</span>';
5462  }
5463 
5464  if (empty($nooutput)) {
5465  print $out;
5466  return '';
5467  }
5468  return $out;
5469  }
5470 
5471  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5487  public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
5488  {
5489  // phpcs:enable
5490  global $langs;
5491 
5492  $out = '';
5493 
5494  if ($htmlname != "none") {
5495  $out .= '<form method="POST" action="'.$page.'">';
5496  $out .= '<input type="hidden" name="action" value="setconditions">';
5497  $out .= '<input type="hidden" name="token" value="'.newToken().'">';
5498  if ($type) {
5499  $out .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
5500  }
5501  $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
5502  $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
5503  $out .= '</form>';
5504  } else {
5505  if ($selected) {
5507  if (isset($this->cache_conditions_paiements[$selected])) {
5508  $label = $this->cache_conditions_paiements[$selected]['label'];
5509 
5510  if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
5511  $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
5512  }
5513 
5514  $out .= $label;
5515  } else {
5516  $langs->load('errors');
5517  $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions');
5518  }
5519  } else {
5520  $out .= '&nbsp;';
5521  }
5522  }
5523 
5524  if (empty($nooutput)) {
5525  print $out;
5526  return '';
5527  }
5528  return $out;
5529  }
5530 
5531  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5541  public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
5542  {
5543  // phpcs:enable
5544  global $langs;
5545  if ($htmlname != "none") {
5546  print '<form method="post" action="'.$page.'">';
5547  print '<input type="hidden" name="action" value="setavailability">';
5548  print '<input type="hidden" name="token" value="'.newToken().'">';
5549  $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
5550  print '<input type="submit" name="modify" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
5551  print '<input type="submit" name="cancel" class="button smallpaddingimp" value="'.$langs->trans("Cancel").'">';
5552  print '</form>';
5553  } else {
5554  if ($selected) {
5555  $this->load_cache_availability();
5556  print $this->cache_availability[$selected]['label'];
5557  } else {
5558  print "&nbsp;";
5559  }
5560  }
5561  }
5562 
5573  public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
5574  {
5575  global $langs;
5576  if ($htmlname != "none") {
5577  print '<form method="post" action="'.$page.'">';
5578  print '<input type="hidden" name="action" value="setdemandreason">';
5579  print '<input type="hidden" name="token" value="'.newToken().'">';
5580  $this->selectInputReason($selected, $htmlname, -1, $addempty);
5581  print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
5582  print '</form>';
5583  } else {
5584  if ($selected) {
5585  $this->loadCacheInputReason();
5586  foreach ($this->cache_demand_reason as $key => $val) {
5587  if ($val['id'] == $selected) {
5588  print $val['label'];
5589  break;
5590  }
5591  }
5592  } else {
5593  print "&nbsp;";
5594  }
5595  }
5596  }
5597 
5598  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5612  public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
5613  {
5614  // phpcs:enable
5615  global $langs;
5616 
5617  $ret = '';
5618 
5619  if ($htmlname != "none") {
5620  $ret .= '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
5621  $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
5622  $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
5623  if ($type) {
5624  $ret .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
5625  }
5626  $ret .= '<table class="nobordernopadding">';
5627  $ret .= '<tr><td>';
5628  $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
5629  $ret .= '</td>';
5630  $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
5631  $ret .= '</tr></table></form>';
5632  } else {
5633  if ($displayhour) {
5634  $ret .= dol_print_date($selected, 'dayhour');
5635  } else {
5636  $ret .= dol_print_date($selected, 'day');
5637  }
5638  }
5639 
5640  if (empty($nooutput)) {
5641  print $ret;
5642  }
5643  return $ret;
5644  }
5645 
5646 
5647  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5658  public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
5659  {
5660  // phpcs:enable
5661  global $langs;
5662 
5663  if ($htmlname != "none") {
5664  print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
5665  print '<input type="hidden" name="action" value="set'.$htmlname.'">';
5666  print '<input type="hidden" name="token" value="'.newToken().'">';
5667  print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
5668  print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
5669  print '</form>';
5670  } else {
5671  if ($selected) {
5672  require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
5673  $theuser = new User($this->db);
5674  $theuser->fetch($selected);
5675  print $theuser->getNomUrl(1);
5676  } else {
5677  print "&nbsp;";
5678  }
5679  }
5680  }
5681 
5682 
5683  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5697  public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
5698  {
5699  // phpcs:enable
5700  global $langs;
5701 
5702  $out = '';
5703  if ($htmlname != "none") {
5704  $out .= '<form method="POST" action="'.$page.'">';
5705  $out .= '<input type="hidden" name="action" value="setmode">';
5706  $out .= '<input type="hidden" name="token" value="'.newToken().'">';
5707  if ($type) {
5708  $out .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
5709  }
5710  $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
5711  $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
5712  $out .= '</form>';
5713  } else {
5714  if ($selected) {
5715  $this->load_cache_types_paiements();
5716  $out .= $this->cache_types_paiements[$selected]['label'];
5717  } else {
5718  $out .= "&nbsp;";
5719  }
5720  }
5721 
5722  if ($nooutput) {
5723  return $out;
5724  } else {
5725  print $out;
5726  }
5727  }
5728 
5739  public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
5740  {
5741  global $langs;
5742  if ($htmlname != "none") {
5743  print '<form method="POST" action="'.$page.'">';
5744  print '<input type="hidden" name="action" value="settransportmode">';
5745  print '<input type="hidden" name="token" value="'.newToken().'">';
5746  $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
5747  print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
5748  print '</form>';
5749  } else {
5750  if ($selected) {
5751  $this->load_cache_transport_mode();
5752  print $this->cache_transport_mode[$selected]['label'];
5753  } else {
5754  print "&nbsp;";
5755  }
5756  }
5757  }
5758 
5759  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5768  public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
5769  {
5770  // phpcs:enable
5771  global $langs;
5772  if ($htmlname != "none") {
5773  print '<form method="POST" action="'.$page.'">';
5774  print '<input type="hidden" name="action" value="setmulticurrencycode">';
5775  print '<input type="hidden" name="token" value="'.newToken().'">';
5776  print $this->selectMultiCurrency($selected, $htmlname, 0);
5777  print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
5778  print '</form>';
5779  } else {
5780  dol_include_once('/core/lib/company.lib.php');
5781  print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
5782  }
5783  }
5784 
5785  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5795  public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
5796  {
5797  // phpcs:enable
5798  global $langs, $mysoc, $conf;
5799 
5800  if ($htmlname != "none") {
5801  print '<form method="POST" action="'.$page.'">';
5802  print '<input type="hidden" name="action" value="setmulticurrencyrate">';
5803  print '<input type="hidden" name="token" value="'.newToken().'">';
5804  print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
5805  print '<select name="calculation_mode">';
5806  print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
5807  print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
5808  print '</select> ';
5809  print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
5810  print '</form>';
5811  } else {
5812  if (!empty($rate)) {
5813  print price($rate, 1, $langs, 1, 0);
5814  if ($currency && $rate != 1) {
5815  print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
5816  }
5817  } else {
5818  print 1;
5819  }
5820  }
5821  }
5822 
5823 
5824  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5840  public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
5841  {
5842  // phpcs:enable
5843  global $conf, $langs;
5844  if ($htmlname != "none") {
5845  print '<form method="post" action="'.$page.'">';
5846  print '<input type="hidden" name="action" value="setabsolutediscount">';
5847  print '<input type="hidden" name="token" value="'.newToken().'">';
5848  print '<div class="inline-block">';
5849  if (!empty($discount_type)) {
5850  if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
5851  if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
5852  $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
5853  } else {
5854  $translationKey = 'HasCreditNoteFromSupplier';
5855  }
5856  } else {
5857  if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
5858  $translationKey = 'HasAbsoluteDiscountFromSupplier';
5859  } else {
5860  $translationKey = 'HasCreditNoteFromSupplier';
5861  }
5862  }
5863  } else {
5864  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
5865  if (!$filter || $filter == "fk_facture_source IS NULL") {
5866  $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
5867  } else {
5868  $translationKey = 'CompanyHasCreditNote';
5869  }
5870  } else {
5871  if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
5872  $translationKey = 'CompanyHasAbsoluteDiscount';
5873  } else {
5874  $translationKey = 'CompanyHasCreditNote';
5875  }
5876  }
5877  }
5878  print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
5879  if (empty($hidelist)) {
5880  print ' ';
5881  }
5882  print '</div>';
5883  if (empty($hidelist)) {
5884  print '<div class="inline-block" style="padding-right: 10px">';
5885  $newfilter = 'discount_type='.intval($discount_type);
5886  if (!empty($discount_type)) {
5887  $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
5888  } else {
5889  $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
5890  }
5891  if ($filter) {
5892  $newfilter .= ' AND ('.$filter.')';
5893  }
5894  // output the combo of discounts
5895  $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
5896  if ($nbqualifiedlines > 0) {
5897  print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
5898  if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
5899  print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
5900  }
5901  if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
5902  print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
5903  }
5904 
5905  print '>';
5906  }
5907  print '</div>';
5908  }
5909  if ($more) {
5910  print '<div class="inline-block">';
5911  print $more;
5912  print '</div>';
5913  }
5914  print '</form>';
5915  } else {
5916  if ($selected) {
5917  print $selected;
5918  } else {
5919  print "0";
5920  }
5921  }
5922  }
5923 
5924 
5925  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5935  public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
5936  {
5937  // phpcs:enable
5938  global $langs, $conf;
5939 
5940  if ($htmlname != "none") {
5941  print '<form method="post" action="'.$page.'">';
5942  print '<input type="hidden" name="action" value="set_contact">';
5943  print '<input type="hidden" name="token" value="'.newToken().'">';
5944  print '<table class="nobordernopadding">';
5945  print '<tr><td>';
5946  print $this->selectcontacts($societe->id, $selected, $htmlname);
5947  $num = $this->num;
5948  if ($num == 0) {
5949  $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
5950  print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
5951  }
5952  print '</td>';
5953  print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
5954  print '</tr></table></form>';
5955  } else {
5956  if ($selected) {
5957  require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
5958  $contact = new Contact($this->db);
5959  $contact->fetch($selected);
5960  print $contact->getFullName($langs);
5961  } else {
5962  print "&nbsp;";
5963  }
5964  }
5965  }
5966 
5967  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5984  public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
5985  {
5986  // phpcs:enable
5987  global $langs;
5988 
5989  $out = '';
5990  if ($htmlname != "none") {
5991  $out .= '<form method="post" action="'.$page.'">';
5992  $out .= '<input type="hidden" name="action" value="set_thirdparty">';
5993  $out .= '<input type="hidden" name="token" value="'.newToken().'">';
5994  $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
5995  $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
5996  $out .= '</form>';
5997  } else {
5998  if ($selected) {
5999  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
6000  $soc = new Societe($this->db);
6001  $soc->fetch($selected);
6002  $out .= $soc->getNomUrl(0, '');
6003  } else {
6004  $out .= '<span class="opacitymedium">'.$textifnothirdparty.'</span>';
6005  }
6006  }
6007 
6008  if ($nooutput) {
6009  return $out;
6010  } else {
6011  print $out;
6012  }
6013  }
6014 
6015  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6024  public function select_currency($selected = '', $htmlname = 'currency_id')
6025  {
6026  // phpcs:enable
6027  print $this->selectCurrency($selected, $htmlname);
6028  }
6029 
6039  public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
6040  {
6041  global $conf, $langs, $user;
6042 
6043  $langs->loadCacheCurrencies('');
6044 
6045  $out = '';
6046 
6047  if ($selected == 'euro' || $selected == 'euros') {
6048  $selected = 'EUR'; // Pour compatibilite
6049  }
6050 
6051  $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
6052  if ($useempty) {
6053  $out .= '<option value="-1" selected></option>';
6054  }
6055  foreach ($langs->cache_currencies as $code_iso => $currency) {
6056  $labeltoshow = $currency['label'];
6057  if ($mode == 1) {
6058  $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
6059  } else {
6060  $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
6061  }
6062 
6063  if ($selected && $selected == $code_iso) {
6064  $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
6065  } else {
6066  $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
6067  }
6068  $out .= $labeltoshow;
6069  $out .= '</option>';
6070  }
6071  $out .= '</select>';
6072  if ($user->admin) {
6073  $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
6074  }
6075 
6076  // Make select dynamic
6077  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6078  $out .= ajax_combobox($htmlname);
6079 
6080  return $out;
6081  }
6082 
6095  public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
6096  {
6097  global $conf, $langs;
6098 
6099  $langs->loadCacheCurrencies(''); // Load ->cache_currencies
6100 
6101  $TCurrency = array();
6102 
6103  $sql = "SELECT code FROM ".$this->db->prefix()."multicurrency";
6104  $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
6105  if ($filter) {
6106  $sql .= " AND ".$filter;
6107  }
6108  $resql = $this->db->query($sql);
6109  if ($resql) {
6110  while ($obj = $this->db->fetch_object($resql)) {
6111  $TCurrency[$obj->code] = $obj->code;
6112  }
6113  }
6114 
6115  $out = '';
6116  $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
6117  if ($useempty) {
6118  $out .= '<option value="">&nbsp;</option>';
6119  }
6120  // If company current currency not in table, we add it into list. Should always be available.
6121  if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
6122  $TCurrency[$conf->currency] = $conf->currency;
6123  }
6124  if (count($TCurrency) > 0) {
6125  foreach ($langs->cache_currencies as $code_iso => $currency) {
6126  if (isset($TCurrency[$code_iso])) {
6127  if (!empty($selected) && $selected == $code_iso) {
6128  $out .= '<option value="'.$code_iso.'" selected="selected">';
6129  } else {
6130  $out .= '<option value="'.$code_iso.'">';
6131  }
6132 
6133  $out .= $currency['label'];
6134  $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
6135  $out .= '</option>';
6136  }
6137  }
6138  }
6139 
6140  $out .= '</select>';
6141 
6142  // Make select dynamic
6143  include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
6144  $out .= ajax_combobox($htmlname);
6145 
6146  return $out;
6147  }
6148 
6149  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6156  public function load_cache_vatrates($country_code)
6157  {
6158  // phpcs:enable
6159  global $langs;
6160 
6161  $num = count($this->cache_vatrates);
6162  if ($num > 0) {
6163  return $num; // Cache already loaded
6164  }
6165 
6166  dol_syslog(__METHOD__, LOG_DEBUG);
6167 
6168  $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
6169  $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
6170  $sql .= " WHERE t.fk_pays = c.rowid";
6171  $sql .= " AND t.active > 0";
6172  $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
6173  $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
6174 
6175  $resql = $this->db->query($sql);
6176  if ($resql) {
6177  $num = $this->db->num_rows($resql);
6178  if ($num) {
6179  for ($i = 0; $i < $num; $i++) {
6180  $obj = $this->db->fetch_object($resql);
6181  $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
6182  $this->cache_vatrates[$i]['code'] = $obj->code;
6183  $this->cache_vatrates[$i]['txtva'] = $obj->taux;
6184  $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
6185  $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
6186  $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
6187  $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
6188  $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
6189 
6190  $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
6191  $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
6192  $positiverates = '';
6193  if ($obj->taux) {
6194  $positiverates .= ($positiverates ? '/' : '').$obj->taux;
6195  }
6196  if ($obj->localtax1) {
6197  $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
6198  }
6199  if ($obj->localtax2) {
6200  $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
6201  }
6202  if (empty($positiverates)) {
6203  $positiverates = '0';
6204  }
6205  $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
6206  }
6207 
6208  return $num;
6209  } else {
6210  $this->error = '<span class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</span>';
6211  return -1;
6212  }
6213  } else {
6214  $this->error = '<span class="error">'.$this->db->error().'</span>';
6215  return -2;
6216  }
6217  }
6218 
6219  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6241  public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
6242  {
6243  // phpcs:enable
6244  global $langs, $conf, $mysoc;
6245 
6246  $langs->load('errors');
6247 
6248  $return = '';
6249 
6250  // Define defaultnpr, defaultttx and defaultcode
6251  $defaultnpr = ($info_bits & 0x01);
6252  $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
6253  $defaulttx = str_replace('*', '', $selectedrate);
6254  $defaultcode = '';
6255  $reg = array();
6256  if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
6257  $defaultcode = $reg[1];
6258  $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
6259  }
6260  //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
6261 
6262  // Check parameters
6263  if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
6264  if ($societe_vendeuse->id == $mysoc->id) {
6265  $return .= '<span class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</span>';
6266  } else {
6267  $return .= '<span class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</span>';
6268  }
6269  return $return;
6270  }
6271 
6272  //var_dump($societe_acheteuse);
6273  //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";
6274  //exit;
6275 
6276  // Define list of countries to use to search VAT rates to show
6277  // First we defined code_country to use to find list
6278  if (is_object($societe_vendeuse)) {
6279  $code_country = "'".$societe_vendeuse->country_code."'";
6280  } else {
6281  $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
6282  }
6283  if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
6284  require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
6285  if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
6286  // We also add the buyer country code
6287  if (is_numeric($type)) {
6288  if ($type == 1) { // We know product is a service
6289  $code_country .= ",'".$societe_acheteuse->country_code."'";
6290  }
6291  } elseif (!$idprod) { // We don't know type of product
6292  $code_country .= ",'".$societe_acheteuse->country_code."'";
6293  } else {
6294  $prodstatic = new Product($this->db);
6295  $prodstatic->fetch($idprod);
6296  if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
6297  $code_country .= ",'".$societe_acheteuse->country_code."'";
6298  }
6299  }
6300  }
6301  }
6302 
6303  // Now we get list
6304  $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
6305 
6306  if ($num > 0) {
6307  // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
6308  if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
6309  $tmpthirdparty = new Societe($this->db);
6310 
6311  $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
6312  $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
6313 
6314  if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
6315  $defaultcode = $reg[1];
6316  $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
6317  }
6318  if (empty($defaulttx)) {
6319  $defaultnpr = 0;
6320  }
6321  }
6322 
6323  // If we fails to find a default vat rate, we take the last one in list
6324  // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
6325  if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
6326  if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
6327  // We take the last one found in list
6328  $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
6329  } else {
6330  // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
6331  $defaulttx = '';
6332  if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
6333  $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
6334  }
6335  if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
6336  $defaultcode = $reg[1];
6337  $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
6338  }
6339  }
6340  }
6341 
6342  // Disabled if seller is not subject to VAT
6343  $disabled = false;
6344  $title = '';
6345  if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
6346  // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
6347  // of using supplier invoices (this is a very bad idea !)
6348  if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
6349  $title = ' title="'.dol_escape_htmltag($langs->trans('VATIsNotUsed')).'"';
6350  $disabled = true;
6351  }
6352  }
6353 
6354  if (!$options_only) {
6355  $return .= '<select class="flat minwidth50imp maxwidth100" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
6356  }
6357 
6358  $selectedfound = false;
6359  foreach ($this->cache_vatrates as $rate) {
6360  // Keep only 0 if seller is not subject to VAT
6361  if ($disabled && $rate['txtva'] != 0) {
6362  continue;
6363  }
6364 
6365  // Define key to use into select list
6366  $key = $rate['txtva'];
6367  $key .= $rate['nprtva'] ? '*' : '';
6368  if ($mode > 0 && $rate['code']) {
6369  $key .= ' ('.$rate['code'].')';
6370  }
6371  if ($mode < 0) {
6372  $key = $rate['rowid'];
6373  }
6374 
6375  $return .= '<option value="'.$key.'"';
6376  if (!$selectedfound) {
6377  if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
6378  if ($defaultcode == $rate['code']) {
6379  $return .= ' selected';
6380  $selectedfound = true;
6381  }
6382  } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
6383  $return .= ' selected';
6384  $selectedfound = true;
6385  }
6386  }
6387  $return .= '>';
6388 
6389  // Show label of VAT
6390  if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
6391  // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
6392  $return .= $rate['labelpositiverates'];
6393  } else {
6394  // Simple label
6395  $return .= vatrate($rate['label']);
6396  }
6397 
6398  //$return.=($rate['code']?' '.$rate['code']:'');
6399  $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
6400 
6401  $return .= '</option>';
6402  }
6403 
6404  if (!$options_only) {
6405  $return .= '</select>';
6406  //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
6407  }
6408  } else {
6409  $return .= $this->error;
6410  }
6411 
6412  $this->num = $num;
6413  return $return;
6414  }
6415 
6416 
6417  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6442  public 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 = '')
6443  {
6444  // phpcs:enable
6445  $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
6446  if (!empty($nooutput)) {
6447  return $retstring;
6448  }
6449  print $retstring;
6450  return;
6451  }
6452 
6468  public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
6469  {
6470  global $langs;
6471 
6472  $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
6473  if ($forcenewline) {
6474  $ret .= '<br>';
6475  }
6476  $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
6477  return $ret;
6478  }
6479 
6507  public function selectDate($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '', $openinghours = '', $stepminutes = 1, $labeladddateof = '', $placeholder = '', $gm = 'auto')
6508  {
6509  global $conf, $langs;
6510 
6511  if ($gm === 'auto') {
6512  $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
6513  }
6514 
6515  $retstring = '';
6516 
6517  if ($prefix == '') {
6518  $prefix = 're';
6519  }
6520  if ($h == '') {
6521  $h = 0;
6522  }
6523  if ($m == '') {
6524  $m = 0;
6525  }
6526  $emptydate = 0;
6527  $emptyhours = 0;
6528  if ($stepminutes <= 0 || $stepminutes > 30) {
6529  $stepminutes = 1;
6530  }
6531  if ($empty == 1) {
6532  $emptydate = 1;
6533  $emptyhours = 1;
6534  }
6535  if ($empty == 2) {
6536  $emptydate = 0;
6537  $emptyhours = 1;
6538  }
6539  $orig_set_time = $set_time;
6540 
6541  if ($set_time === '' && $emptydate == 0) {
6542  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
6543  if ($gm == 'tzuser' || $gm == 'tzuserrel') {
6544  $set_time = dol_now($gm);
6545  } else {
6546  $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
6547  }
6548  }
6549 
6550  // Analysis of the pre-selection date
6551  $reg = array();
6552  $shour = '';
6553  $smin = '';
6554  $ssec = '';
6555  if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
6556  // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
6557  $syear = (!empty($reg[1]) ? $reg[1] : '');
6558  $smonth = (!empty($reg[2]) ? $reg[2] : '');
6559  $sday = (!empty($reg[3]) ? $reg[3] : '');
6560  $shour = (!empty($reg[4]) ? $reg[4] : '');
6561  $smin = (!empty($reg[5]) ? $reg[5] : '');
6562  } elseif (strval($set_time) != '' && $set_time != -1) {
6563  // set_time est un timestamps (0 possible)
6564  $syear = dol_print_date($set_time, "%Y", $gm);
6565  $smonth = dol_print_date($set_time, "%m", $gm);
6566  $sday = dol_print_date($set_time, "%d", $gm);
6567  if ($orig_set_time != '') {
6568  $shour = dol_print_date($set_time, "%H", $gm);
6569  $smin = dol_print_date($set_time, "%M", $gm);
6570  $ssec = dol_print_date($set_time, "%S", $gm);
6571  }
6572  } else {
6573  // Date est '' ou vaut -1
6574  $syear = '';
6575  $smonth = '';
6576  $sday = '';
6577  $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
6578  $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
6579  $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
6580  }
6581  if ($h == 3) {
6582  $shour = '';
6583  }
6584  if ($m == 3) {
6585  $smin = '';
6586  }
6587 
6588  $nowgmt = dol_now('gmt');
6589  //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
6590 
6591  // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
6592  $usecalendar = 'combo';
6593  if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
6594  $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
6595  }
6596 
6597  if ($d) {
6598  // Show date with popup
6599  if ($usecalendar != 'combo') {
6600  $formated_date = '';
6601  //print "e".$set_time." t ".$conf->format_date_short;
6602  if (strval($set_time) != '' && $set_time != -1) {
6603  //$formated_date=dol_print_date($set_time,$conf->format_date_short);
6604  $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
6605  }
6606 
6607  // Calendrier popup version eldy
6608  if ($usecalendar == "eldy") {
6609  // Input area to enter date manually
6610  $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
6611  $retstring .= ($disabled ? ' disabled' : '');
6612  $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
6613  $retstring .= '>';
6614 
6615  // Icon calendar
6616  $retstringbuttom = '';
6617  if (!$disabled) {
6618  $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
6619  $base = DOL_URL_ROOT.'/core/';
6620  $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
6621  $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
6622  } else {
6623  $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons