dolibarr 25.0.0-alpha
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-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
19 * Copyright (C) 2018-2022 Ferran Marcet <fmarcet@2byte.es>
20 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.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 * Copyright (C) 2023 Nick Fragoulis
26 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
27 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
28 * Copyright (C) 2026 Lenin Rivas <lenin.rivas777@gmail.com>
29 * Copyright (C) 2026 Open-Dsi <support@open-dsi.fr>
30 * Copyright (C) 2026 Jose MARTINEZ <jose.martinez@pichinov.com>
31 *
32 * This program is free software; you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation; either version 3 of the License, or
35 * (at your option) any later version.
36 *
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 * GNU General Public License for more details.
41 *
42 * You should have received a copy of the GNU General Public License
43 * along with this program. If not, see <https://www.gnu.org/licenses/>.
44 */
45
59class Form
60{
64 public $db;
65
69 public $error = '';
70
74 public $errors = array();
75
76 // Some properties used to return data by some methods
78 public $result;
79
81 public $num;
82
83 // Cache arrays
85 public $cache_types_paiements = array();
87 public $cache_conditions_paiements = array();
89 public $cache_transport_mode = array();
91 public $cache_availability = array();
93 public $cache_demand_reason = array();
95 public $cache_types_fees = array();
97 public $cache_vatrates = array();
99 public $cache_invoice_subtype = array();
101 public $cache_rule_for_lines_dates = array();
102
106 private $phoneInputSharedJsLoaded = false;
107
108
114 public function __construct($db)
115 {
116 $this->db = $db;
117 }
118
127 public function getDurationTypes(Translate $langs, $plurial = true, $reverse = false)
128 {
129 if ($plurial) {
130 $arrayoftypes = [
131 'y' => $langs->trans('Years'),
132 'm' => $langs->trans('Month'),
133 'w' => $langs->trans('Weeks'),
134 'd' => $langs->trans('Days'),
135 'h' => $langs->trans('Hours'),
136 'i' => $langs->trans('Minutes'),
137 's' => $langs->trans('Seconds'),
138 ];
139 } else {
140 $arrayoftypes = [
141 "y" => $langs->trans("Year"),
142 "m" => $langs->trans("Month"),
143 "w" => $langs->trans("Week"),
144 "d" => $langs->trans("Day"),
145 "h" => $langs->trans("Hour"),
146 "i" => $langs->trans("Minute"),
147 's' => $langs->trans('Second'),
148 ];
149 }
150 if ($reverse) {
151 return array_reverse($arrayoftypes);
152 } else {
153 return $arrayoftypes;
154 }
155 }
156
173 public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
174 {
175 global $langs;
176
177 $ret = '';
178
179 // TODO change for compatibility
180 if (getDolGlobalString('MAIN_USE_EDIT_IN_PLACE') && !preg_match('/^select;/', $typeofdata)) {
181 if ($perm) {
182 $tmp = explode(':', $typeofdata);
183 $ret .= '<div class="editkey_' . $tmp[0] . (!empty($tmp[1]) ? ' ' . $tmp[1] : '') . '" id="' . $htmlname . '">';
184 if ($fieldrequired) {
185 $ret .= '<span class="fieldrequired">';
186 }
187 if ($help) {
188 $ret .= $this->textwithpicto($langs->trans($text), $help);
189 } else {
190 $ret .= $langs->trans($text);
191 }
192 if ($fieldrequired) {
193 $ret .= '</span>';
194 }
195 $ret .= '</div>' . "\n";
196 } else {
197 if ($fieldrequired) {
198 $ret .= '<span class="fieldrequired">';
199 }
200 if ($help) {
201 $ret .= $this->textwithpicto($langs->trans($text), $help);
202 } else {
203 $ret .= $langs->trans($text);
204 }
205 if ($fieldrequired) {
206 $ret .= '</span>';
207 }
208 }
209 } else {
210 if (empty($notabletag) && $perm) {
211 $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
212 }
213 if ($fieldrequired) {
214 $ret .= '<span class="fieldrequired">';
215 }
216 if ($help) {
217 $ret .= $this->textwithpicto($langs->trans($text), $help);
218 } else {
219 $ret .= $langs->trans($text);
220 }
221 if ($fieldrequired) {
222 $ret .= '</span>';
223 }
224 if (!empty($notabletag)) {
225 $ret .= ' ';
226 }
227 if (empty($notabletag) && $perm) {
228 $ret .= '</td>';
229 }
230 if (empty($notabletag) && $perm) {
231 $ret .= '<td class="right">';
232 }
233 if ($htmlname && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm && is_object($object)) {
234 $ret .= '<a class="editfielda reposition" href="' . dolBuildUrl($_SERVER["PHP_SELF"], ['action' => 'edit' . $htmlname, $paramid => $object->id], true) . $moreparam . '">';
235 $ret .= img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1));
236 $ret .= '</a>';
237 }
238 if (!empty($notabletag) && $notabletag == 1) {
239 if ($text) {
240 $ret .= ' : ';
241 } else {
242 $ret .= ' ';
243 }
244 }
245 if (!empty($notabletag) && $notabletag == 3) {
246 $ret .= ' ';
247 }
248 if (empty($notabletag) && $perm) {
249 $ret .= '</td>';
250 }
251 if (empty($notabletag) && $perm) {
252 $ret .= '</tr></table>';
253 }
254 }
255
256 return $ret;
257 }
258
282 public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 1, $formatfunc = '', $paramid = 'id', $gm = 'auto', $moreoptions = array(), $editaction = '')
283 {
284 global $conf, $langs;
285
286 $ret = '';
287
288 // Check parameters
289 if (empty($typeofdata)) {
290 return 'ErrorBadParameter typeofdata is empty';
291 }
292 // Clean parameter $typeofdata
293 if ($typeofdata == 'datetime') {
294 $typeofdata = 'dayhour';
295 }
296 if ($typeofdata == 'date') {
297 $typeofdata = 'day';
298 }
299 $reg = array();
300 if (preg_match('/^(\w+)\‍((\d+)\‍)$/', $typeofdata, $reg)) {
301 if ($reg[1] == 'varchar') {
302 $typeofdata = 'string';
303 } elseif ($reg[1] == 'int') {
304 $typeofdata = 'numeric';
305 } else {
306 return 'ErrorBadParameter ' . $typeofdata;
307 }
308 }
309
310 // When option to edit inline is activated
311 if (getDolGlobalString('MAIN_USE_EDIT_IN_PLACE') && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
312 $ret .= $this->editInPlace($object, $value, $htmlname, ($perm ? 1 : 0), $typeofdata, $editvalue, $extObject, $custommsg);
313 } else {
314 if ($editaction == '') {
315 $editaction = GETPOST('action', 'aZ09');
316 }
317 $editmode = ($editaction == 'edit' . $htmlname);
318 if ($editmode) { // edit mode
319 $ret .= "<!-- formeditfieldval -->\n";
320 $ret .= '<form method="post" action="' . $_SERVER["PHP_SELF"] . ($moreparam ? '?' . $moreparam : '') . '">';
321 $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
322 $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
323 $ret .= '<input type="hidden" name="' . $paramid . '" value="' . $object->id . '">';
324 if (empty($notabletag)) {
325 $ret .= '<table class="nobordernopadding centpercent">';
326 }
327 if (empty($notabletag)) {
328 $ret .= '<tr><td>';
329 }
330 if (preg_match('/^(string|safehtmlstring|email|phone|url)/', $typeofdata)) {
331 $tmp = explode(':', $typeofdata);
332 $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($editvalue ? $editvalue : $value) . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus spellcheck="false">';
333 } elseif (preg_match('/^(integer)/', $typeofdata)) {
334 $tmp = explode(':', $typeofdata);
335 $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
336 $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $valuetoshow . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
337 } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
338 $tmp = explode(':', $typeofdata);
339 $valuetoshow = price2num($editvalue ? $editvalue : $value);
340 $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($valuetoshow != '' ? price($valuetoshow) : '') . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
341 } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
342 $tmp = explode(':', $typeofdata);
343 $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($value ? $value : 'on') . '"' . ($value ? ' checked' : '') . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
344 } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
345 $tmp = explode(':', $typeofdata);
346 $cols = (empty($tmp[2]) ? '' : $tmp[2]);
347 $morealt = '';
348 if (preg_match('/%/', $cols)) {
349 $morealt = ' style="width: ' . $cols . '"';
350 $cols = '';
351 }
352 $valuetoshow = ($editvalue ? $editvalue : $value);
353 $ret .= '<textarea id="' . $htmlname . '" name="' . $htmlname . '" wrap="soft" rows="' . (empty($tmp[1]) ? '20' : $tmp[1]) . '"' . ($cols ? ' cols="' . $cols . '"' : 'class="quatrevingtpercent"') . $morealt . '" autofocus>';
354 // textarea convert automatically entities chars into simple chars.
355 // 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 wysiwyg is off.
356 $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
357 $ret .= dol_htmlwithnojs(dol_string_neverthesehtmltags($valuetoshow, array('textarea')));
358 $ret .= '</textarea><div class="clearboth"></div>';
359 } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
360 $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
361 $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
362 $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
363 $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
364 } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
365 $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
366 $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
367 $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
368 $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
369 } elseif (preg_match('/^select;/', $typeofdata)) {
370 $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
371 $arraylist = array();
372 foreach ($arraydata as $val) {
373 $tmp = explode(':', $val);
374 $tmpkey = str_replace('|', ':', $tmp[0]);
375 $arraylist[$tmpkey] = $tmp[1];
376 }
377 $ret .= $this->selectarray($htmlname, $arraylist, $value);
378 } elseif (preg_match('/^link/', $typeofdata)) {
379 // TODO Not yet implemented. See code for extrafields
380 } elseif (preg_match('/^ckeditor/', $typeofdata)) {
381 $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
382 require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
383 $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), (empty($tmp[2]) ? '' : $tmp[2]), (empty($tmp[3]) ? 100 : (int) $tmp[3]), (empty($tmp[1]) ? 'dolibarr_notes' : $tmp[1]), 'In', (empty($tmp[5]) ? false : (bool) $tmp[5]), (isset($tmp[8]) ? ($tmp[8] ? true : false) : true), true, (empty($tmp[6]) ? 20 : (int) $tmp[6]), (empty($tmp[7]) ? '100' : $tmp[7]));
384 $ret .= $doleditor->Create(1);
385 } elseif ($typeofdata == 'asis') {
386 $ret .= ($editvalue ? $editvalue : $value);
387 }
388 if (empty($notabletag)) {
389 $ret .= '</td>';
390 }
391
392 // Button save-cancel
393 if (empty($notabletag)) {
394 $ret .= '<td>';
395 }
396 //else $ret.='<div class="clearboth"></div>';
397 $ret .= '<input type="submit" class="smallpaddingimp nomargingtop nomarginbottom button' . (empty($notabletag) ? '' : ' ') . '" name="modify" value="' . $langs->trans("Save") . '">';
398 if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
399 $ret .= '<br>' . "\n";
400 }
401 $ret .= '<input type="submit" class="smallpaddingimp nomargingtop nomarginbottom button button-cancel' . (empty($notabletag) ? '' : ' ') . '" name="cancel" value="' . $langs->trans("Cancel") . '">';
402 if (empty($notabletag)) {
403 $ret .= '</td>';
404 }
405
406 if (empty($notabletag)) {
407 $ret .= '</tr></table>' . "\n";
408 }
409 $ret .= '</form>' . "\n";
410 } else { // view mode
411 if (preg_match('/^email/', $typeofdata)) {
412 $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
413 } elseif (preg_match('/^phone/', $typeofdata)) {
414 $ret .= dol_print_phone($value, '_blank', 32, 1);
415 } elseif (preg_match('/^url/', $typeofdata)) {
416 $ret .= dol_print_url($value, '_blank', 32, 1);
417 } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
418 $ret .= ($value != '' ? price($value, 0, $langs, 0, -1, -1, $conf->currency) : '');
419 } elseif (preg_match('/^checkbox/', $typeofdata)) {
420 $tmp = explode(':', $typeofdata);
421 $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($value ? ' checked' : '') . ($tmp[1] ? $tmp[1] : '') . '/>';
422 } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
424 } elseif (preg_match('/^(safehtmlstring|restricthtml)/', $typeofdata)) { // 'restricthtml' is not an allowed type for editfieldval. Value is 'safehtmlstring'
426 } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
427 $ret .= '<span class="valuedate">' . dol_print_date($value, 'day', $gm) . '</span>';
428 } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
429 $ret .= '<span class="valuedate">' . dol_print_date($value, 'dayhour', $gm) . '</span>';
430 } elseif (preg_match('/^select;/', $typeofdata)) {
431 $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
432 $arraylist = array();
433 foreach ($arraydata as $val) {
434 $tmp = explode(':', $val);
435 $arraylist[$tmp[0]] = $tmp[1];
436 }
437 $ret .= $arraylist[$value];
438 if ($htmlname == 'fk_product_type') {
439 if ($value == 0) {
440 $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
441 } else {
442 $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
443 }
444 }
445 } elseif (preg_match('/^ckeditor/', $typeofdata)) {
446 $tmpcontent = dol_htmlentitiesbr($value);
447 if (getDolGlobalString('MAIN_DISABLE_NOTES_TAB')) {
448 $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
449 $firstline = preg_replace('/[\n\r].*/', '', $firstline);
450 $tmpcontent = $firstline . ((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
451 }
452 // We don't use dol_escape_htmltag to get the html formatting active, but this need we must also
453 // clean data from some dangerous html
455 } else {
456 if (empty($moreoptions['valuealreadyhtmlescaped'])) {
457 $ret .= dol_escape_htmltag($value);
458 } else {
459 $ret .= $value; // $value must be already html escaped.
460 }
461 }
462
463 // Custom format if parameter $formatfunc has been provided
464 if ($formatfunc && method_exists($object, $formatfunc)) {
465 $ret = $object->$formatfunc($ret);
466 }
467 }
468 }
469 return $ret;
470 }
471
483 public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
484 {
485 global $conf, $langs, $extralanguages;
486
487 $result = '';
488
489 // List of extra languages
490 $arrayoflangcode = array();
491 if (getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE')) {
492 $arrayoflangcode[] = getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE');
493 }
494
495 if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
496 if (!is_object($extralanguages)) {
497 include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
498 $extralanguages = new ExtraLanguages($this->db);
499 }
500 $extralanguages->fetch_name_extralanguages('societe');
501
502 // ExtraLanguages::fetch_name_extralanguages() leaves $this->attributes empty
503 // when MAIN_USE_ALTERNATE_TRANSLATION_FOR is not configured, so PHP 8 raises
504 // 'Undefined array key' on the read below if we do not guard it (issue #34596).
505 if (empty($extralanguages->attributes[$object->element]) || !is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
506 return ''; // No extralang field to show
507 }
508
509 $result .= '<!-- Widget for translation -->' . "\n";
510 $result .= '<div class="inline-block paddingleft image-' . $object->element . '-' . $fieldname . '">';
511 $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', 0, 0, 0, '', 'fa-15 editfieldlang');
512 $result .= $s;
513 $result .= '</div>';
514
515 $result .= '<div class="inline-block hidden field-' . $object->element . '-' . $fieldname . '">';
516
517 $resultforextrlang = '';
518 foreach ($arrayoflangcode as $langcode) {
519 $valuetoshow = GETPOSTISSET('field-' . $object->element . "-" . $fieldname . "-" . $langcode) ? GETPOST('field-' . $object->element . '-' . $fieldname . "-" . $langcode, $check) : '';
520 if (empty($valuetoshow)) {
521 $object->fetchValuesForExtraLanguages();
522 //var_dump($object->array_languages);
523 $valuetoshow = $object->array_languages[$fieldname][$langcode];
524 }
525
526 $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
527 $resultforextrlang .= $s;
528
529 // TODO Use the showInputField() method of ExtraLanguages object
530 if ($typeofdata == 'textarea') {
531 $resultforextrlang .= '<textarea name="field-' . $object->element . "-" . $fieldname . "-" . $langcode . '" id="' . $fieldname . "-" . $langcode . '" class="' . $morecss . '" rows="' . ROWS_2 . '" wrap="soft">';
532 $resultforextrlang .= $valuetoshow;
533 $resultforextrlang .= '</textarea>';
534 } else {
535 $resultforextrlang .= '<input type="text" class="inputfieldforlang ' . ($morecss ? ' ' . $morecss : '') . '" name="field-' . $object->element . '-' . $fieldname . '-' . $langcode . '" value="' . $valuetoshow . '">';
536 }
537 }
538 $result .= $resultforextrlang;
539
540 $result .= '</div>';
541 $result .= '<script nonce="' . getNonce() . '">$(".image-' . $object->element . '-' . $fieldname . '").click(function() { console.log("Toggle lang widget"); jQuery(".field-' . $object->element . '-' . $fieldname . '").toggle(); });</script>';
542 }
543
544 return $result;
545 }
546
560 protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
561 {
562 $out = '';
563
564 // Check parameters
565 if (preg_match('/^text/', $inputType)) {
566 $value = dol_nl2br($value);
567 } elseif (preg_match('/^numeric/', $inputType)) {
568 $value = price($value);
569 } elseif ($inputType == 'day' || $inputType == 'datepicker') {
570 $value = dol_print_date($value, 'day');
571 }
572
573 if ($condition) {
574 $element = false;
575 $table_element = false;
576 $fk_element = false;
577 $loadmethod = false;
578 $savemethod = false;
579 $ext_element = false;
580 $button_only = false;
581 $inputOption = '';
582 $rows = '';
583 $cols = '';
584
585 if (is_object($object)) {
586 $element = $object->element;
587 $table_element = $object->table_element;
588 $fk_element = $object->id;
589 }
590
591 if (is_object($extObject)) {
592 $ext_element = $extObject->element;
593 }
594
595 if (preg_match('/^(string|email|numeric)/', $inputType)) {
596 $tmp = explode(':', $inputType);
597 $inputType = $tmp[0];
598 if (!empty($tmp[1])) {
599 $inputOption = $tmp[1];
600 }
601 if (!empty($tmp[2])) {
602 $savemethod = $tmp[2];
603 }
604 $out .= '<input id="width_' . $htmlname . '" value="' . $inputOption . '" type="hidden"/>' . "\n";
605 } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
606 $tmp = explode(':', $inputType);
607 $inputType = $tmp[0];
608 if (!empty($tmp[1])) {
609 $inputOption = $tmp[1];
610 }
611 if (!empty($tmp[2])) {
612 $savemethod = $tmp[2];
613 }
614
615 $out .= '<input id="timestamp" type="hidden"/>' . "\n"; // Use for timestamp format
616 } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
617 $tmp = explode(':', $inputType);
618 $inputType = $tmp[0];
619 $loadmethod = $tmp[1];
620 if (!empty($tmp[2])) {
621 $savemethod = $tmp[2];
622 }
623 if (!empty($tmp[3])) {
624 $button_only = true;
625 }
626 } elseif (preg_match('/^textarea/', $inputType)) {
627 $tmp = explode(':', $inputType);
628 $inputType = $tmp[0];
629 $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
630 $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
631 } elseif (preg_match('/^ckeditor/', $inputType)) {
632 $tmp = explode(':', $inputType);
633 $inputType = $tmp[0];
634 $toolbar = $tmp[1];
635 if (!empty($tmp[2])) {
636 $width = $tmp[2];
637 }
638 if (!empty($tmp[3])) {
639 $height = $tmp[3];
640 }
641 if (!empty($tmp[4])) {
642 $savemethod = $tmp[4];
643 }
644
645 if (isModEnabled('fckeditor')) {
646 $out .= '<input id="ckeditor_toolbar" value="' . $toolbar . '" type="hidden"/>' . "\n";
647 } else {
648 $inputType = 'textarea';
649 }
650 }
651
652 $out .= '<input id="element_' . $htmlname . '" value="' . $element . '" type="hidden"/>' . "\n";
653 $out .= '<input id="table_element_' . $htmlname . '" value="' . $table_element . '" type="hidden"/>' . "\n";
654 $out .= '<input id="fk_element_' . $htmlname . '" value="' . $fk_element . '" type="hidden"/>' . "\n";
655 $out .= '<input id="loadmethod_' . $htmlname . '" value="' . $loadmethod . '" type="hidden"/>' . "\n";
656 if (!empty($savemethod)) {
657 $out .= '<input id="savemethod_' . $htmlname . '" value="' . $savemethod . '" type="hidden"/>' . "\n";
658 }
659 if (!empty($ext_element)) {
660 $out .= '<input id="ext_element_' . $htmlname . '" value="' . $ext_element . '" type="hidden"/>' . "\n";
661 }
662 if (!empty($custommsg)) {
663 if (is_array($custommsg)) {
664 if (!empty($custommsg['success'])) {
665 $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg['success'] . '" type="hidden"/>' . "\n";
666 }
667 if (!empty($custommsg['error'])) {
668 $out .= '<input id="errormsg_' . $htmlname . '" value="' . $custommsg['error'] . '" type="hidden"/>' . "\n";
669 }
670 } else {
671 $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg . '" type="hidden"/>' . "\n";
672 }
673 }
674 if ($inputType == 'textarea') {
675 $out .= '<input id="textarea_' . $htmlname . '_rows" value="' . $rows . '" type="hidden"/>' . "\n";
676 $out .= '<input id="textarea_' . $htmlname . '_cols" value="' . $cols . '" type="hidden"/>' . "\n";
677 }
678 $out .= '<span id="viewval_' . $htmlname . '" class="viewval_' . $inputType . ($button_only ? ' inactive' : ' active') . '">' . $value . '</span>' . "\n";
679 $out .= '<span id="editval_' . $htmlname . '" class="editval_' . $inputType . ($button_only ? ' inactive' : ' active') . ' hideobject">' . (!empty($editvalue) ? $editvalue : $value) . '</span>' . "\n";
680 } else {
681 $out = $value;
682 }
683
684 return $out;
685 }
686
705 public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
706 {
707 if ($incbefore) {
708 $text = $incbefore . $text;
709 }
710 if (!$htmltext) {
711 return $text;
712 }
713 $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
714
715 $tag = 'td';
716 if ($notabs == 2) {
717 $tag = 'div';
718 }
719 if ($notabs == 3) {
720 $tag = 'span';
721 }
722 // Sanitize tooltip
723 $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
724
725 $extrastyle = '';
726 if ($direction < 0) {
727 $extracss = ($extracss ? $extracss : '') . ($notabs != 3 ? ' inline-block' : '');
728 $extrastyle = 'padding: 0px; padding-left: 2px;';
729 }
730 if ($direction > 0) {
731 $extracss = ($extracss ? $extracss : '') . ($notabs != 3 ? ' inline-block' : '');
732 $extrastyle = 'padding: 0px; padding-right: 2px;';
733 }
734
735 $classfortooltip = 'classfortooltip';
736
737 $s = '';
738 $textfordialog = '';
739
740 if ($tooltiptrigger == '') {
741 $htmltext = str_replace('"', '&quot;', $htmltext);
742 } else {
743 $classfortooltip = 'classfortooltiponclick';
744 $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_' . $tooltiptrigger . '" class="classfortooltiponclicktext"';
745 // Set default title of dialog
746 global $langs;
747 if ($langs instanceof Translate) {
748 $textfordialog .= ' title="'.$langs->trans("Note").'"';
749 }
750 $textfordialog .= '>' . $htmltext . '</div>';
751 }
752 if ($tooltipon == 2 || $tooltipon == 3) {
753 $paramfortooltipimg = ' class="' . $classfortooltip . ($notabs != 3 ? ' inline-block' : '') . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '"';
754 if ($tooltiptrigger == '') {
755 $paramfortooltipimg .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1, 0, 'span', 0, 1)) . '"'; // Attribute to put on img tag to store tooltip
756 } else {
757 $paramfortooltipimg .= ' dolid="' . $tooltiptrigger . '"';
758 }
759 } else {
760 $paramfortooltipimg = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribute to put on td text tag
761 }
762 if ($tooltipon == 1 || $tooltipon == 3) {
763 $paramfortooltiptd = ' class="' . ($tooltipon == 3 ? 'cursorpointer ' : '') . $classfortooltip . ($tag != 'td' ? ' inline-block' : '') . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '" ';
764 if ($tooltiptrigger == '') {
765 $paramfortooltiptd .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1, 0, 'span', 0, 1)) . '"'; // Attribute to put on td tag to store tooltip
766 } else {
767 $paramfortooltiptd .= ' dolid="' . $tooltiptrigger . '"';
768 }
769 } else {
770 $paramfortooltiptd = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribute to put on td text tag
771 }
772 if (empty($notabs)) {
773 $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
774 } elseif ($notabs == 2) {
775 $s .= '<div class="inline-block' . ($forcenowrap ? ' nowrap' : '') . '">';
776 }
777 // Define value if value is before
778 if ($direction < 0) {
779 $s .= '<' . $tag . $paramfortooltipimg;
780 if ($tag == 'td') {
781 $s .= ' class="valigntop" width="14"';
782 }
783 $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
784 }
785 // Use another method to help avoid having a space in value in order to use this value with jquery
786 // Define label
787 if ((string) $text != '') {
788 $s .= '<' . $tag . $paramfortooltiptd . '>' . $text . '</' . $tag . '>';
789 }
790 // Define value if value is after
791 if ($direction > 0) {
792 $s .= '<' . $tag . $paramfortooltipimg;
793 if ($tag == 'td') {
794 $s .= ' class="valignmiddle" width="14"';
795 }
796 $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
797 }
798 if (empty($notabs)) {
799 $s .= '</tr></table>';
800 } elseif ($notabs == 2) {
801 $s .= '</div>';
802 }
803
804 return $s;
805 }
806
821 public function textwithpicto($text, $htmltooltip, $direction = 1, $type = 'help', $extracss = 'valignmiddle', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
822 {
823 global $conf, $langs;
824
825 //For backwards compatibility
826 if ($type == '0') {
827 $type = 'info';
828 } elseif ($type == '1') {
829 $type = 'help';
830 }
831 // Clean parameters
832 $tooltiptrigger = preg_replace('/[^a-z0-9]/i', '', $tooltiptrigger);
833
834 if (preg_match('/onsmartphone$/', $tooltiptrigger) && empty($conf->dol_no_mouse_hover)) {
835 $tooltiptrigger = preg_replace('/^.*onsmartphone$/', '', $tooltiptrigger);
836 }
837 $alt = '';
838 if ($tooltiptrigger) {
839 $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
840 }
841
842 // If info or help with no javascript, show only text
843 if (empty($conf->use_javascript_ajax)) {
844 if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
845 return $text;
846 } else {
847 $alt = $htmltooltip;
848 $htmltooltip = '';
849 }
850 }
851
852 // If info or help with smartphone, show only text (tooltip hover can't works)
853 if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
854 if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
855 return $text;
856 }
857 }
858 // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
859 //if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
860 //{
861 //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.'</a>';
862 //}
863
864 $img = '';
865 if ($type == 'info') {
866 $img = img_help(($tooltiptrigger != '' ? 2 : 0), $alt);
867 } elseif ($type == 'help') {
868 $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
869 } elseif ($type == 'helpclickable') {
870 $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
871 } elseif ($type == 'warning') {
872 $img = img_warning($alt);
873 } elseif ($type != 'none') {
874 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
875 $img = img_picto($alt, $type); // $type can be an image path
876 }
877
878 $tooltipon = ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2);
879
880 return $this->textwithtooltip($text, $htmltooltip, $tooltipon, $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
881 }
882
893 public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
894 {
895 global $conf, $langs, $hookmanager;
896
897 $disabled = 0;
898 $ret = '<div class="centpercent center">';
899 $ret .= '<select class="flat' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'select valignmiddle alignstart" id="' . $name . '" name="' . $name . '"' . ($disabled ? ' disabled="disabled"' : '') . '>';
900
901 // 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.
902 $parameters = array();
903 $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
904 // check if there is a mass action
905
906 if (is_array($arrayofaction) && count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
907 return;
908 }
909 if (empty($reshook)) {
910 $ret .= '<option value="0"' . ($disabled ? ' disabled="disabled"' : '') . '>-- ' . $langs->trans("SelectAction") . ' --</option>';
911 if (is_array($arrayofaction)) {
912 foreach ($arrayofaction as $code => $label) {
913 $ret .= '<option value="' . $code . '"' . ($disabled ? ' disabled="disabled"' : '') . ' data-html="' . dol_escape_htmltag($label) . '">' . $label . '</option>';
914 }
915 }
916 }
917 $ret .= $hookmanager->resPrint;
918
919 $ret .= '</select>';
920
921 if (empty($conf->dol_optimize_smallscreen)) {
922 $ret .= ajax_combobox('.' . $name . 'select');
923 }
924
925 // 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
926 $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.
927 $ret .= '<input type="submit" disabled name="confirmmassaction"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display: none"') . ' class="reposition button smallpaddingimp' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'confirmed" value="' . dol_escape_htmltag($langs->trans("Confirm")) . '">';
928 $ret .= '</div>';
929
930 if (!empty($conf->use_javascript_ajax)) {
931 $ret .= '<!-- JS CODE TO ENABLE mass action select -->
932 <script nonce="' . getNonce() . '">
933 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 check for select boxes */
934 atleastoneselected=0;
935 jQuery("."+cssclass).each(function( index ) {
936 /* console.log( index + ": " + $( this ).text() ); */
937 if ($(this).is(\':checked\')) atleastoneselected++;
938 });
939
940 console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
941
942 if (atleastoneselected || ' . ((int) $alwaysvisible) . ') {
943 jQuery("."+name).show();
944 ' . ($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("' . $selected . '").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '') . '
945 ' . ($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '') . '
946 } else {
947 jQuery("."+name).hide();
948 jQuery("."+name+"other").hide();
949 }
950 }
951
952 jQuery(document).ready(function () {
953 initCheckForSelect(0, "' . $name . '", "' . $cssclass . '");
954 jQuery(".' . $cssclass . '").change(function() {
955 console.log("A change was done on .' . $cssclass . '");
956 initCheckForSelect(1, "' . $name . '", "' . $cssclass . '");
957 });
958 jQuery(".' . $name . 'select").change(function() {
959 var massaction = $( this ).val();
960 var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
961 if (massaction == "builddoc") {
962 urlform = urlform + "#show_files";
963 }
964 $( this ).closest("form").attr("action", urlform);
965 console.log("we select a mass action name=' . $name . ' massaction="+massaction+" - "+urlform);
966 /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
967 if ($(this).val() != \'0\') {
968 jQuery(".' . $name . 'confirmed").prop(\'disabled\', false);
969 jQuery(".' . $name . 'other").hide(); /* To disable if another div was open */
970 jQuery(".' . $name . '"+massaction).show();
971 } else {
972 jQuery(".' . $name . 'confirmed").prop(\'disabled\', true);
973 jQuery(".' . $name . 'other").hide(); /* To disable any div open */
974 }
975 });
976 });
977 </script>
978 ';
979 }
980
981 return $ret;
982 }
983
984 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
985
1003 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, $forcecombo = 0)
1004 {
1005 // phpcs:enable
1006 global $langs, $mysoc;
1007
1008 $langs->load("dict");
1009
1010 $selected = (string) $selected;
1011
1012 $out = '';
1014 $countryArray = array();
1015 $favorite = array();
1016 $label = array();
1017 $atleastonefavorite = 0;
1018
1019 $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
1020 $sql .= " FROM " . $this->db->prefix() . "c_country";
1021 $sql .= " WHERE active > 0";
1022 //$sql.= " ORDER BY code ASC";
1023
1024 dol_syslog(get_class($this) . "::select_country", LOG_DEBUG);
1025
1026 $resql = $this->db->query($sql);
1027 if ($resql) {
1028 $out .= '<select id="select' . $htmlname . '" class="flat maxwidth200onsmartphone selectcountry' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" ' . $htmloption . '>';
1029 $num = $this->db->num_rows($resql);
1030 $i = 0;
1031 if ($num) {
1032 while ($i < $num) {
1033 $obj = $this->db->fetch_object($resql);
1034
1035 $countryArray[$i]
1036 = array(
1037 'rowid' => (int) $obj->rowid,
1038 'code_iso' => (string) $obj->code_iso,
1039 'code_iso3' => (string) $obj->code_iso3,
1040 'label' => (string) ($obj->code_iso && $langs->transnoentitiesnoconv("Country" . $obj->code_iso) != "Country" . $obj->code_iso ? $langs->transnoentitiesnoconv("Country" . $obj->code_iso) : ($obj->label != '-' ? $obj->label : '')),
1041 'favorite' => (string) $obj->favorite,
1042 'eec' => (string) $obj->eec,
1043 );
1044 $favorite[$i] = $obj->favorite;
1045 $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
1046 $i++;
1047 }
1048
1049 if (empty($disablefavorites)) {
1050 $array1_sort_order = SORT_DESC;
1051 $array2_sort_order = SORT_ASC;
1052 array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
1053 } else {
1054 $countryArray = dol_sort_array($countryArray, 'label');
1055 }
1056
1057 if ($showempty) {
1058 if (is_numeric($showempty)) {
1059 $out .= '<option value="">&nbsp;</option>' . "\n";
1060 } else {
1061 $out .= '<option value="-1">' . $langs->trans($showempty) . '</option>' . "\n";
1062 }
1063 }
1064
1065 if ($addspecialentries) { // Add dedicated entries for groups of countries
1066 //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
1067 $out .= '<option value="special_allnotme"' . ($selected == 'special_allnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
1068 $out .= '<option value="special_eec"' . ($selected == 'special_eec' ? ' selected' : '') . '>' . $langs->trans("CountriesInEEC") . '</option>';
1069 if ($mysoc->isInEEC()) {
1070 $out .= '<option value="special_eecnotme"' . ($selected == 'special_eecnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
1071 }
1072 $out .= '<option value="special_noteec"' . ($selected == 'special_noteec' ? ' selected' : '') . '>' . $langs->trans("CountriesNotInEEC") . '</option>';
1073 $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
1074 }
1075
1076 foreach ($countryArray as $row) {
1077 //if (empty($showempty) && empty($row['rowid'])) continue;
1078 if (empty($row['rowid'])) {
1079 continue;
1080 }
1081 if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
1082 continue; // exclude some countries
1083 }
1084
1085 if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
1086 $atleastonefavorite++;
1087 }
1088 if (empty($row['favorite']) && $atleastonefavorite) {
1089 $atleastonefavorite = 0;
1090 $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
1091 }
1092
1093 $labeltoshow = '';
1094 if ($row['label']) {
1095 $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
1096 } else {
1097 $labeltoshow .= '&nbsp;';
1098 }
1099 if ($row['code_iso']) {
1100 $labeltoshow .= ' <span class="opacitymedium">(' . $row['code_iso'] . ')</span>';
1101 if (empty($hideflags)) {
1102 $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
1103 $labeltoshow = $tmpflag . ' ' . $labeltoshow;
1104 }
1105 }
1106
1107 if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
1108 $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']) . '">';
1109 } else {
1110 $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']) . '">';
1111 }
1112 $out .= dol_string_nohtmltag($labeltoshow);
1113 $out .= '</option>' . "\n";
1114 }
1115 }
1116 $out .= '</select>';
1117 } else {
1118 dol_print_error($this->db);
1119 }
1120
1121 // Make select dynamic
1122 if (empty($forcecombo)) {
1123 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1124 $out .= ajax_combobox('select' . $htmlname, array(), 0, 0, 'resolve');
1125 }
1126
1127 return $out;
1128 }
1129
1140 public function selectPhoneCode($selected = '', $htmlname = 'phone_code', $morecss = 'maxwidth150', $showempty = 0, $country_id_hint = 0)
1141 {
1142 global $langs;
1143
1144 $langs->load("dict");
1145
1146 $out = '';
1147 $codeArray = array();
1148 $favorite = array();
1149 $label = array();
1150 $atleastonefavorite = 0;
1151
1152 $sql = "SELECT rowid, code, label, phone_code, favorite, trunk_prefix";
1153 $sql .= " FROM ".$this->db->prefix()."c_country";
1154 // phone_code is an integer column, comparing it to an empty string fails on PostgreSQL
1155 $sql .= " WHERE active > 0 AND phone_code IS NOT NULL AND phone_code != 0";
1156
1157 dol_syslog(get_class($this)."::selectPhoneCode", LOG_DEBUG);
1158 $resql = $this->db->query($sql);
1159 if ($resql) {
1160 $num = $this->db->num_rows($resql);
1161 $i = 0;
1162 while ($i < $num) {
1163 $obj = $this->db->fetch_object($resql);
1164
1165 $translabel = ($obj->code && $langs->transnoentitiesnoconv("Country".$obj->code) != "Country".$obj->code) ? $langs->transnoentitiesnoconv("Country".$obj->code) : $obj->label;
1166
1167 $codeArray[$i]['rowid'] = $obj->rowid;
1168 $codeArray[$i]['code'] = $obj->code;
1169 $codeArray[$i]['label'] = $translabel;
1170 $codeArray[$i]['phone_code'] = '+'.$obj->phone_code;
1171 $codeArray[$i]['favorite'] = $obj->favorite;
1172 $codeArray[$i]['trunk_prefix'] = $obj->trunk_prefix;
1173 $favorite[$i] = $obj->favorite;
1174 $label[$i] = dol_string_unaccent($translabel);
1175 $i++;
1176 }
1177
1178 $array1_sort_order = SORT_DESC;
1179 $array2_sort_order = SORT_ASC;
1180 array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $codeArray);
1181
1182 $out .= '<select id="select'.$htmlname.'" class="flat selectphonecode'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
1183
1184 if ($showempty) {
1185 $out .= '<option value="">&nbsp;</option>'."\n";
1186 }
1187
1188 // Determine which row index to select: prefer country_id_hint match, fallback to first phone_code match
1189 $selectedIdx = -1;
1190 $firstMatchIdx = -1;
1191 if ($selected !== '') {
1192 foreach ($codeArray as $idx => $row) {
1193 if ($row['phone_code'] == $selected) {
1194 if ($firstMatchIdx < 0) {
1195 $firstMatchIdx = $idx;
1196 }
1197 if ($country_id_hint > 0 && $row['rowid'] == $country_id_hint) {
1198 $selectedIdx = $idx;
1199 break;
1200 }
1201 }
1202 }
1203 if ($selectedIdx < 0 && $firstMatchIdx >= 0) {
1204 $selectedIdx = $firstMatchIdx;
1205 }
1206 }
1207
1208 foreach ($codeArray as $idx => $row) {
1209 if (empty($row['code'])) {
1210 continue;
1211 }
1212
1213 if ($row['favorite']) {
1214 $atleastonefavorite++;
1215 }
1216 if (empty($row['favorite']) && $atleastonefavorite) {
1217 $atleastonefavorite = 0;
1218 $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
1219 }
1220
1221 $tmpflag = picto_from_langcode($row['code'], 'class="saturatemedium paddingrightonly"', 1);
1222
1223 // Short label for selected display: flag + country code
1224 $selectlabel = ($tmpflag ? $tmpflag.' ' : '').$row['code'];
1225
1226 // Detailed label for dropdown list: flag + country name + phone code
1227 $labeltoshow = ($tmpflag ? $tmpflag.' ' : '').$row['label'].' '.$row['phone_code'];
1228
1229 $out .= '<option value="'.dol_escape_htmltag($row['phone_code']).'"';
1230 if ($idx === $selectedIdx) {
1231 $out .= ' selected';
1232 }
1233 $out .= ' data-html="'.dol_escape_htmltag($labeltoshow).'"';
1234 $out .= ' data-select-html="'.dol_escape_htmltag($selectlabel).'"';
1235 $out .= ' data-country-id="'.((int) $row['rowid']).'"';
1236 $out .= ' data-trunk-prefix="'.dol_escape_htmltag((string) $row['trunk_prefix']).'"';
1237 $out .= '>';
1238 $out .= dol_string_nohtmltag($labeltoshow);
1239 $out .= '</option>'."\n";
1240 }
1241 $out .= '</select>';
1242 } else {
1243 dol_print_error($this->db);
1244 }
1245
1246 // Make select dynamic
1247 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1248 $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
1249
1250 return $out;
1251 }
1252
1269 public function showPhoneInput($phoneValue, $htmlname, $country_id_hint = 0, $picto = 'object_phoning', $morecss = 'maxwidth150', $maxlength = 0, $countrySelectorId = 'selectcountry_id')
1270 {
1271 global $mysoc;
1272
1273 include_once DOL_DOCUMENT_ROOT.'/core/lib/phone.lib.php';
1274
1275 $codename = $htmlname.'_code';
1276
1277 // Fallback country_id: use caller hint, else main company country
1278 if (empty($country_id_hint) && !empty($mysoc->country_id)) {
1279 $country_id_hint = $mysoc->country_id;
1280 }
1281
1282 // On POST re-display, read the hidden field (which contains the full phone string)
1283 if (GETPOSTISSET($htmlname)) {
1284 $fullPhone = (string) GETPOST($htmlname);
1285 } else {
1286 $fullPhone = (string) $phoneValue;
1287 }
1288
1289 // Split into code + number
1290 $parsed = dol_parse_phone($fullPhone);
1291
1292 // Resolve default phone code: parsed code if set, else from country hint
1293 $phonecode = !empty($parsed['code']) ? $parsed['code'] : dol_get_phone_code_from_country($this->db, $country_id_hint);
1294
1295 $selectedCode = $phonecode;
1296 $numberValue = $parsed['number'];
1297
1298 // Remove country code
1299 if (strpos($numberValue, $selectedCode) === 0) {
1300 $numberValue = str_replace($selectedCode, '', $numberValue);
1301 }
1302
1303 // Add back trunk prefix for display (e.g. "644986885" → "0644986885" for France)
1304 if ($numberValue !== '' && $selectedCode !== '') {
1305 $trunkPrefix = dol_get_trunk_prefix($this->db, $selectedCode);
1306 if ($trunkPrefix !== '' && strpos($numberValue, $trunkPrefix) !== 0) {
1307 $numberValue = $trunkPrefix.$numberValue;
1308 }
1309 }
1310
1311 // Build output: hidden field (POSTed value)
1312 $out = '<input type="hidden" name="'.dol_escape_htmltag($htmlname).'" id="'.dol_escape_htmltag($htmlname).'" value="'.dol_escape_htmltag($fullPhone).'">';
1313
1314 // Picto
1315 $out .= img_picto('', $picto, 'class="pictofixedwidth"');
1316
1317 // Phone code select (display-only name, not submitted as separate POST param)
1318 $out .= $this->selectPhoneCode($selectedCode, $codename, 'maxwidth75 phone_code_select', 0, $country_id_hint);
1319
1320 // Visible number input (no name — not POSTed)
1321 $out .= '<input type="tel" inputmode="numeric" pattern="[0-9]*" id="'.dol_escape_htmltag($htmlname).'_input" class="'.dol_escape_htmltag($morecss).'"';
1322 if ($maxlength > 0) {
1323 $out .= ' maxlength="'.$maxlength.'"';
1324 }
1325 $out .= ' value="'.dol_escape_htmltag($numberValue).'">';
1326
1327 // Per-field JS to sync hidden field
1328 $out .= $this->getPhoneInputFieldJs($htmlname, $codename);
1329
1330 // Shared JS for country-sync (output once per page)
1331 $out .= $this->getPhoneInputSharedJs($countrySelectorId);
1332
1333 return $out;
1334 }
1335
1346 private function getPhoneInputFieldJs($htmlname, $codename)
1347 {
1348 $hiddenId = dol_escape_js($htmlname); // TODO: Not the correct method
1349 $inputId = dol_escape_js($htmlname).'_input'; // Correctly quoted with '' below @phan-suppress-current-line FunctionMissingSingleQuoteWrapping
1350 $selectId = 'select'.dol_escape_js($codename); // Correctly quoted with '' below @phan-suppress-current-line FunctionMissingSingleQuoteWrapping
1351
1352 $out = "\n".'<script type="text/javascript">'."\n";
1353 $out .= 'jQuery(document).ready(function() {'."\n";
1354 $out .= ' function syncPhoneField_'.$hiddenId.'() {'."\n";
1355 $out .= ' var selectEl = jQuery(\'#'.$selectId.'\');'."\n";
1356 $out .= ' var code = selectEl.val() || "";'."\n";
1357 $out .= ' var number = (jQuery(\'#'.$inputId.'\').val() || "").replace(/[^0-9]/g, "");'."\n";
1358 $out .= ' if (code && number) {'."\n";
1359 $out .= ' var selOpt = selectEl[0] && selectEl[0].selectedOptions && selectEl[0].selectedOptions[0];'."\n";
1360 $out .= ' var trunkPrefix = selOpt ? (selOpt.getAttribute("data-trunk-prefix") || "") : "";'."\n";
1361 $out .= ' if (trunkPrefix !== "" && number.indexOf(trunkPrefix) === 0) {'."\n";
1362 $out .= ' number = number.substring(trunkPrefix.length);'."\n";
1363 $out .= ' }'."\n";
1364 $out .= ' jQuery("#'.$hiddenId.'").val(code + " " + number);'."\n";
1365 $out .= ' } else if (number) {'."\n";
1366 $out .= ' jQuery("#'.$hiddenId.'").val(number);'."\n";
1367 $out .= ' } else {'."\n";
1368 $out .= ' jQuery("#'.$hiddenId.'").val("");'."\n";
1369 $out .= ' }'."\n";
1370 $out .= ' }'."\n";
1371 $out .= ' jQuery(\'#'.$selectId.'\').on("change", function() { syncPhoneField_'.$hiddenId.'(); });'."\n";
1372 $out .= ' jQuery(\'#'.$inputId.'\').on("input change", function() { syncPhoneField_'.$hiddenId.'(); });'."\n";
1373 $out .= '});'."\n";
1374 $out .= '</script>'."\n";
1375
1376 return $out;
1377 }
1378
1388 private function getPhoneInputSharedJs($countrySelectorId)
1389 {
1390 if ($this->phoneInputSharedJsLoaded) {
1391 return '';
1392 }
1393 $this->phoneInputSharedJsLoaded = true;
1394
1395 $out = "\n".'<script type="text/javascript">'."\n";
1396 $out .= 'jQuery(document).ready(function() {'."\n";
1397 $out .= ' jQuery(\'#'.dol_escape_js($countrySelectorId).'\').on("change", function() {'."\n";
1398 $out .= ' var country_id = jQuery(this).val();'."\n";
1399 $out .= ' if (country_id) {'."\n";
1400 $out .= ' jQuery.getJSON("'.DOL_URL_ROOT.'/core/ajax/getphonecode.php", {country_id: country_id, token: "'.currentToken().'"}, function(data) {'."\n";
1401 $out .= ' if (data.phone_code) {'."\n";
1402 $out .= ' jQuery(".phone_code_select").each(function() {'."\n";
1403 $out .= ' jQuery(this).val(data.phone_code).trigger("change");'."\n";
1404 $out .= ' });'."\n";
1405 $out .= ' }'."\n";
1406 $out .= ' });'."\n";
1407 $out .= ' }'."\n";
1408 $out .= ' });'."\n";
1409 $out .= '});'."\n";
1410 $out .= '</script>'."\n";
1411
1412 return $out;
1413 }
1414
1424 private function flagLinksFromHook($linksfromhook)
1425 {
1426 foreach ($linksfromhook as $key => $val) {
1427 if (is_array($val)) {
1428 $linksfromhook[$key]['fromhook'] = 1;
1429 }
1430 }
1431
1432 return $linksfromhook;
1433 }
1434
1448 private function makeAddLinkToObject($object, $key, $possiblelink, $num, $resqllist)
1449 {
1450 dol_syslog(__METHOD__, LOG_DEBUG);
1451 global $langs, $form;
1452 if (empty($form)) {
1453 $form = new Form($this->db);
1454 }
1455 $htmltoenteralink = '';
1456 $i = 0;
1457
1458 // headers
1459 $htmltoenteralink .= '<tr class="liste_titre">';
1460 $htmltoenteralink .= '<td class="nowrap"></td>';
1461 $htmltoenteralink .= '<td>' . $langs->trans("Ref") . '</td>';
1462 $htmltoenteralink .= '<td>' . $langs->trans("RefCustomer") . '</td>';
1463 $htmltoenteralink .= '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
1464 $htmltoenteralink .= '<td>' . $langs->trans("Company") . '</td>';
1465 $htmltoenteralink .= '</tr>';
1466
1467 // rows with data
1468 while ($i < $num) {
1469 $objp = $this->db->fetch_object($resqllist);
1470 $alreadylinked = false;
1471 if (!empty($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key])) {
1472 if (in_array($objp->rowid, array_values($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key]))) {
1473 $alreadylinked = true;
1474 }
1475 }
1476 $htmltoenteralink .= '<tr class="oddeven">';
1477 $htmltoenteralink .= '<td>';
1478 if ($alreadylinked) {
1479 $htmltoenteralink .= img_picto('', 'link');
1480 } else {
1481 $htmltoenteralink .= '<input type="checkbox" name="idtolinkto[' . $key . '_' . $objp->rowid . ']" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
1482 }
1483 $htmltoenteralink .= '</td>';
1484 $htmltoenteralink .= '<td>';
1485 if (!$alreadylinked) {
1486 $htmltoenteralink .= '<label for="' . $key . '_' . $objp->rowid . '">';
1487 }
1488 $htmltoenteralink .= $objp->ref;
1489 if (!$alreadylinked) {
1490 $htmltoenteralink .= '</label>';
1491 }
1492 $htmltoenteralink .= '</td>';
1493 $htmltoenteralink .= '<td>' . (!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')) . '</td>';
1494 $htmltoenteralink .= '<td class="right">';
1495 if ($possiblelink['label'] == 'LinkToContract') {
1496 $htmltoenteralink .= $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")) . ' ';
1497 }
1498 $htmltoenteralink .= '<span class="amount">' . (isset($objp->total_ht) ? price($objp->total_ht) : '') . '</span>';
1499 $htmltoenteralink .= '</td>';
1500 $htmltoenteralink .= '<td>' . $objp->name . '</td>';
1501 $htmltoenteralink .= '</tr>';
1502 $i++;
1503 }
1504
1505 return $htmltoenteralink;
1506 }
1507
1522 private function makeAddLinkToAttendee($object, $key, $possiblelink, $num, $resqllist)
1523 {
1524 dol_syslog(__METHOD__, LOG_DEBUG);
1525 global $langs, $form;
1526 require_once DOL_DOCUMENT_ROOT . '/eventorganization/class/conferenceorboothattendee.class.php';
1527 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1528 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
1529 $attendeestatic = new ConferenceOrBoothAttendee($this->db);
1530 $companystatic = new Societe($this->db);
1531 $projectstatic = new Project($this->db);
1532 if (empty($form)) {
1533 $form = new Form($this->db);
1534 }
1535 $htmltoenteralink = '';
1536 $i = 0;
1537
1538 // headers
1539 $htmltoenteralink .= '<tr class="liste_titre">';
1540 $htmltoenteralink .= '<td class="nowrap"></td>';
1541 $htmltoenteralink .= '<td>' . $langs->trans("Ref") . '</td>';
1542 $htmltoenteralink .= '<td>' . $langs->trans("Name") . '</td>';
1543 $htmltoenteralink .= '<td>' . $langs->trans("Email") . '</td>';
1544 $htmltoenteralink .= '<td>' . $langs->trans("Company") . '</td>';
1545 $htmltoenteralink .= '<td>' . $langs->trans("Project") . '</td>';
1546 $htmltoenteralink .= '<td>' . $langs->trans("DateOfRegistration") . '</td>';
1547 $htmltoenteralink .= '</tr>';
1548
1549 // rows with data
1550 while ($i < $num) {
1551 $objp = $this->db->fetch_object($resqllist);
1552 $alreadylinked = false;
1553 if (!empty($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key])) {
1554 if (in_array($objp->rowid, array_values($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key]))) {
1555 $alreadylinked = true;
1556 }
1557 }
1558 $htmltoenteralink .= '<tr class="oddeven">';
1559 $htmltoenteralink .= '<td>';
1560 if ($alreadylinked) {
1561 $htmltoenteralink .= img_picto('', 'link');
1562 } else {
1563 $htmltoenteralink .= '<input type="checkbox" name="idtolinkto[' . $key . '_' . $objp->rowid . ']" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
1564 }
1565 $htmltoenteralink .= '</td>';
1566 $fetchattendee = $attendeestatic->fetch($objp->rowid);
1567 if ($fetchattendee) {
1568 $htmltoenteralink .= '<td>' . $attendeestatic->getNomUrl(0). '</td>';
1569 } else {
1570 $htmltoenteralink .= '<td><label for="' . $key . '_' . $objp->rowid . '">' . $objp->ref . '</label></td>';
1571 }
1572 $htmltoenteralink .= '<td>' . $objp->name . '</td>';
1573 $htmltoenteralink .= '<td>' . $objp->email . '</td>';
1574 $fetchcompany = $companystatic->fetch($objp->socid);
1575 if ($fetchcompany) {
1576 $htmltoenteralink .= '<td>' . $companystatic->getNomUrl(0). '</td>';
1577 } else {
1578 $htmltoenteralink .= '<td>' . $objp->name . '</td>';
1579 }
1580 $fetchcproject = $projectstatic->fetch($objp->fk_project);
1581 if ($fetchcproject) {
1582 $htmltoenteralink .= '<td>' . $projectstatic->getNomUrl(0). '</td>';
1583 } else {
1584 $htmltoenteralink .= '<td>' . $objp->fk_project . '</td>';
1585 }
1586 $htmltoenteralink .= '<td>' . $objp->date_subscription . '</td>';
1587 $htmltoenteralink .= '</tr>';
1588 $i++;
1589 }
1590
1591 return $htmltoenteralink;
1592 }
1593
1594 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1595
1609 public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
1610 {
1611 // phpcs:enable
1612 global $conf, $langs;
1613
1614 $langs->load("dict");
1615
1616 $out = '';
1617 //$moreattrib = '';
1618 $incotermArray = array();
1619
1620 $sql = "SELECT rowid, code";
1621 $sql .= " FROM " . $this->db->prefix() . "c_incoterms";
1622 $sql .= " WHERE active > 0";
1623 $sql .= " ORDER BY code ASC";
1624
1625 dol_syslog(get_class($this) . "::select_incoterm", LOG_DEBUG);
1626 $resql = $this->db->query($sql);
1627 if ($resql) {
1628 if ($conf->use_javascript_ajax && !$forcecombo) {
1629 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1630 $out .= ajax_combobox($htmlname, $events);
1631 }
1632
1633 if (!empty($page)) {
1634 $out .= '<form method="post" action="' . $page . '">';
1635 $out .= '<input type="hidden" name="action" value="set_incoterms">';
1636 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
1637 }
1638
1639 $out .= '<select id="' . $htmlname . '" class="flat selectincoterm width75" name="' . $htmlname . '" ' . $htmloption . '>';
1640 $out .= '<option value="0">&nbsp;</option>';
1641 $num = $this->db->num_rows($resql);
1642 $i = 0;
1643 if ($num) {
1644 while ($i < $num) {
1645 $obj = $this->db->fetch_object($resql);
1646 $incotermArray[$i]['rowid'] = $obj->rowid;
1647 $incotermArray[$i]['code'] = $obj->code;
1648 $i++;
1649 }
1650
1651 foreach ($incotermArray as $row) {
1652 if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
1653 $out .= '<option value="' . $row['rowid'] . '" selected>';
1654 } else {
1655 $out .= '<option value="' . $row['rowid'] . '">';
1656 }
1657
1658 if ($row['code']) {
1659 $out .= $row['code'];
1660 }
1661
1662 $out .= '</option>';
1663 }
1664 }
1665 $out .= '</select>';
1666 $out .= ajax_combobox($htmlname);
1667
1668 if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
1669 $out .= ajax_multiautocompleter('location_incoterms', array(), DOL_URL_ROOT . '/core/ajax/locationincoterms.php') . "\n";
1670 //$moreattrib .= ' autocomplete="off"';
1671 }
1672 $out .= '<input id="location_incoterms" class="maxwidthonsmartphone heightofcombo" type="text" name="location_incoterms" value="' . $location_incoterms . '">' . "\n";
1673
1674 if (!empty($page)) {
1675 $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="' . $langs->trans("Modify") . '"></form>';
1676 }
1677 } else {
1678 dol_print_error($this->db);
1679 }
1680
1681 return $out;
1682 }
1683
1684 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1685
1699 public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0, $morecss = "", $useajaxcombo = 1)
1700 {
1701 // phpcs:enable
1702 global $langs;
1703
1704 // If product & services are enabled or both disabled.
1705 if ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
1706 || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
1707 if (empty($hidetext)) {
1708 print $langs->trans("Type").'...';
1709 }
1710
1711 print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_' . $htmlname . '" name="' . $htmlname . '">';
1712 if ($showempty) {
1713 print '<option value="-1" class="opacitymedium"'.($useajaxcombo ? '' : ' disabled="disabled"');
1714 if ($selected == -1) {
1715 print ' selected';
1716 }
1717 print '>';
1718 if (is_numeric($showempty)) {
1719 print '&nbsp;';
1720 } else {
1721 print $showempty;
1722 }
1723 print '</option>';
1724 }
1725
1726 print '<option value="0"';
1727 if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
1728 print ' selected';
1729 }
1730 print '>' . $langs->trans("Product");
1731 print '</option>';
1732
1733 print '<option value="1"';
1734 if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
1735 print ' selected';
1736 }
1737 print '>' . $langs->trans("Service");
1738 print '</option>';
1739
1740 print '</select>';
1741
1742 if ($useajaxcombo) {
1743 print ajax_combobox('select_' . $htmlname);
1744 }
1745 //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1746 }
1747 if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
1748 print $langs->trans("Service");
1749 print '<input type="hidden" name="' . $htmlname . '" value="1">';
1750 }
1751 if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
1752 print $langs->trans("Product");
1753 print '<input type="hidden" name="' . $htmlname . '" value="0">';
1754 }
1755 if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
1756 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
1757 }
1758 }
1759
1760 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1761
1767 public function load_cache_types_fees()
1768 {
1769 // phpcs:enable
1770 global $langs;
1771
1772 $num = count($this->cache_types_fees);
1773 if ($num > 0) {
1774 return 0; // Cache already loaded
1775 }
1776
1777 dol_syslog(__METHOD__, LOG_DEBUG);
1778
1779 $langs->load("trips");
1780
1781 $sql = "SELECT c.code, c.label";
1782 $sql .= " FROM " . $this->db->prefix() . "c_type_fees as c";
1783 $sql .= " WHERE active > 0";
1784
1785 $resql = $this->db->query($sql);
1786 if ($resql) {
1787 $num = $this->db->num_rows($resql);
1788 $i = 0;
1789
1790 while ($i < $num) {
1791 $obj = $this->db->fetch_object($resql);
1792
1793 // If a translation exists, we use is, otherwise, we take the label by default
1794 $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
1795 $this->cache_types_fees[$obj->code] = $label;
1796 $i++;
1797 }
1798
1799 asort($this->cache_types_fees);
1800
1801 return $num;
1802 } else {
1803 dol_print_error($this->db);
1804 return -1;
1805 }
1806 }
1807
1808 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1809
1821 public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0, $morecss = '', $nooutput = 0, $noadmin = 0)
1822 {
1823 // phpcs:enable
1824 global $user, $langs;
1825
1826 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
1827
1828 $this->load_cache_types_fees();
1829
1830 $out = '';
1831
1832 $out .= '<select id="select_' . $htmlname . '" class="flat'.($morecss ? ' '.$morecss : '').'" name="' . $htmlname . '">';
1833 if ($showempty) {
1834 $out .= '<option value="-1"';
1835 if ($selected === -1) {
1836 $out .= ' selected';
1837 }
1838 $out .= '>';
1839 if (!is_numeric($showempty)) {
1840 $out .= $langs->trans($showempty);
1841 }
1842 $out .= '</option>';
1843 }
1844
1845 foreach ($this->cache_types_fees as $key => $value) {
1846 $out .= '<option value="' . $key . '"';
1847 if ($key == (string) $selected) {
1848 $out .= ' selected';
1849 }
1850 $out .= '>';
1851 $out .= $value;
1852 $out .= '</option>';
1853 }
1854
1855 $out .= '</select>';
1856 if ($user->admin && empty($noadmin)) {
1857 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
1858 }
1859
1860 $out .= ajax_combobox('select_'.$htmlname);
1861
1862 if (empty($nooutput)) {
1863 print $out;
1864 return '';
1865 }
1866
1867 return $out;
1868 }
1869
1870
1871 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1872
1895 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)
1896 {
1897 // phpcs:enable
1898 global $conf, $langs;
1899
1900 $out = '';
1901
1902 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT') && !$forcecombo) {
1903 if (is_null($ajaxoptions)) {
1904 $ajaxoptions = array();
1905 }
1906
1907 require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1908
1909 // No immediate load of all database
1910 $placeholder = '';
1911 if ($selected && empty($selected_input_value)) {
1912 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1913 $societetmp = new Societe($this->db);
1914 $societetmp->fetch($selected);
1915 $selected_input_value = $societetmp->name;
1916 unset($societetmp);
1917 }
1918
1919 // mode 1
1920 $urloption = 'htmlname=' . urlencode((string) (str_replace('.', '_', $htmlname))) . '&outjson=1&filter=' . urlencode((string) ($filter)) . (empty($excludeids) ? '' : '&excludeids=' . implode(',', $excludeids)) . ($showtype ? '&showtype=' . urlencode((string) ($showtype)) : '') . ($showcode ? '&showcode=' . urlencode((string) ($showcode)) : '') . ($limit ? '&limit='.$limit : '');
1921
1922 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
1923 if (empty($hidelabel)) {
1924 $out .= $langs->trans("RefOrLabel") . ' : ';
1925 } elseif ($hidelabel == 1 && !is_numeric($showempty)) {
1926 $placeholder = $langs->trans($showempty);
1927 } elseif ($hidelabel > 1) {
1928 $placeholder = $langs->trans("RefOrLabel");
1929 if ($hidelabel == 2) {
1930 $out .= img_picto($langs->trans("Search"), 'search');
1931 }
1932 }
1933 $out .= '<input type="text" class="' . $morecss . '" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '') . ' ' . (getDolGlobalString('THIRDPARTY_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' spellcheck="false" />';
1934 if ($hidelabel == 3) {
1935 $out .= img_picto($langs->trans("Search"), 'search');
1936 }
1937
1938 $out .= ajax_event($htmlname, $events);
1939
1940 // Label of the greyed line shown when the search returns nothing
1941 if (!isset($ajaxoptions['noresultlabel'])) {
1942 $langs->load("companies");
1943 $ajaxoptions['noresultlabel'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NoThirdPartyFound"));
1944 }
1945
1946 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, getDolGlobalInt('COMPANY_USE_SEARCH_TO_SELECT'), 0, $ajaxoptions);
1947 } else {
1948 // Immediate load of all database
1949 $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
1950 }
1951
1952 return $out;
1953 }
1954
1955
1956 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1957
1984 public function select_contact($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $nokeyifsocid = true, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $selected_input_value = '', $filter = '', $multiple = false)
1985 {
1986 // phpcs:enable
1987
1988 global $conf, $langs;
1989
1990 $out = '';
1991
1992 if (empty($htmlid)) {
1993 $htmlid = $htmlname;
1994 }
1995
1996 $sav = getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT');
1997 if ($nokeyifsocid && $socid > 0) {
1998 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = 0;
1999 }
2000
2001 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT') && !$forcecombo) {
2002 require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2003 require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2004
2005 // select2 combo pre-filled with only the currently selected contact(s) as <option selected>.
2006 // select2 keeps those and fetches the rest on demand from contact/ajax/contact.php instead of
2007 // loading the whole contact list into the page.
2008 $selectedids = array();
2009 foreach (($multiple ? (is_array($selected) ? $selected : array()) : ($selected !== '' && $selected !== 0 ? array($selected) : array())) as $tmpid) {
2010 if (is_numeric($tmpid) && (int) $tmpid > 0) {
2011 $selectedids[] = (int) $tmpid;
2012 }
2013 }
2014
2015 // A non-numeric $showempty ('&nbsp;', a label, ...) is used as a select2 placeholder instead of
2016 // an <option> value; select2 needs an empty first <option> in single mode to be able to show it.
2017 $placeholder = is_numeric($showempty) ? '' : (string) $showempty;
2018
2019 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlid . '" name="' . $htmlname . ($multiple ? '[]' : '') . '"' . ($multiple ? ' multiple' : '') . ($moreparam ? ' ' . $moreparam : '') . '>';
2020 if (!$multiple) {
2021 $out .= '<option></option>';
2022 }
2023 if (count($selectedids)) {
2024 $contacttmp = new Contact($this->db);
2025 foreach ($selectedids as $tmpid) {
2026 if ($contacttmp->fetch($tmpid) > 0) {
2027 $out .= '<option value="' . $tmpid . '" selected>' . dol_escape_htmltag($contacttmp->getFullName($langs)) . '</option>';
2028 }
2029 }
2030 unset($contacttmp);
2031 }
2032 $out .= '</select>';
2033
2034 $out .= ajax_event($htmlname, $events);
2035
2036 // Same as the value of 'htmlname=' below: the endpoint reads the typed term from a GET param
2037 // named after this transformed htmlname (see contact/ajax/contact.php).
2038 $htmlnamefortermparam = str_replace('.', '_', $htmlname);
2039 $urloption = 'htmlname=' . urlencode((string) $htmlnamefortermparam) . '&outjson=1&filter=' . urlencode((string) $filter)
2040 . (empty($exclude) ? '' : '&exclude=' . urlencode($exclude))
2041 . ($showsoc ? '&showsoc=' . urlencode((string) $showsoc) : '')
2042 . ($socid > 0 ? '&socid=' . ((int) $socid) : '');
2043
2044 // A non-numeric value ('infinite') means "infinite list": no minimum number of chars, the list
2045 // opens as soon as the field gets the focus (select2 queries the endpoint with an empty term).
2046 $minlengthforajax = getDolGlobalInt('CONTACT_USE_SEARCH_TO_SELECT');
2047 if ($minlengthforajax < 1) {
2048 $minlengthforajax = 0;
2049 }
2050 // Page size of the ajax endpoint (CONTACT_LIMIT_SIZE): select2 keeps asking for the next page
2051 // while the endpoint returns a full page, so the whole list stays browsable by scrolling.
2052 $ajaxpagesize = getDolGlobalInt('CONTACT_LIMIT_SIZE', 20);
2053
2054 $htmlidjs = str_replace('.', '\\\\.', $htmlid);
2055 $out .= '<script nonce="' . getNonce() . '">jQuery(function() {
2056 jQuery("#' . $htmlidjs . '").select2({
2057 theme: "default",
2058 language: (typeof select2arrayoflanguage === "undefined") ? "en" : select2arrayoflanguage,
2059 containerCssClass: ":all:",
2060 placeholder: ' . json_encode($placeholder) . ',
2061 minimumInputLength: ' . ((int) $minlengthforajax) . ',
2062 ajax: {
2063 url: "' . DOL_URL_ROOT . '/contact/ajax/contact.php?' . $urloption . '",
2064 dataType: "json",
2065 delay: 250,
2066 data: function(params) {
2067 var d = {};
2068 d[' . json_encode($htmlnamefortermparam) . '] = params.term;
2069 d.page = params.page || 1;
2070 return d;
2071 },
2072 processResults: function(data) {
2073 var result = [];
2074 jQuery.each(data, function(i, val) {
2075 result.push({ id: val.key, text: val.value });
2076 });
2077 return { results: result, pagination: { more: data.length >= ' . ((int) $ajaxpagesize) . ' } };
2078 },
2079 cache: true
2080 }
2081 });' . (getDolGlobalString('CONTACT_SEARCH_AUTOFOCUS') ? '
2082 jQuery("#' . $htmlidjs . '").select2("open");' : '') . '
2083 });</script>';
2084 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.select2-container { z-index: 1010; }</style>';
2085 } else {
2086 // Immediate load of all database
2087 $disableifempty = 0;
2088 $options_only = 0;
2089 $limitto = '';
2090
2091 $out .= $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid, $multiple, $disableifempty, $filter);
2092 }
2093
2094 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = $sav;
2095
2096 return $out;
2097 }
2098
2099
2100 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2101
2125 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)
2126 {
2127 // phpcs:enable
2128 global $user, $langs;
2129 global $hookmanager;
2130
2131 $langs->loadLangs(array("companies", "suppliers"));
2132
2133 $out = '';
2134 $num = 0;
2135 $outarray = array();
2136
2137 if ($selected === '') {
2138 $selected = array();
2139 } elseif (!is_array($selected)) {
2140 $selected = array($selected);
2141 }
2142
2143 // Clean $filter that may contains sql conditions so sql code
2144 if (function_exists('testSqlAndScriptInject')) {
2145 if (testSqlAndScriptInject($filter, 3) > 0) {
2146 $filter = '';
2147 return 'SQLInjectionTryDetected';
2148 }
2149 }
2150
2151 if ($filter != '') { // If a filter was provided
2152 $errormsg = '';
2153 $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
2154
2155 // Redo clean $filter that may contains sql conditions so sql code
2156 if (function_exists('testSqlAndScriptInject')) {
2157 if (testSqlAndScriptInject($filter, 3) > 0) {
2158 $filter = '';
2159 return 'SQLInjectionTryDetected';
2160 }
2161 }
2162 }
2163
2164 // We search companies
2165 $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
2166 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
2167 $sql .= ", s.address, s.zip, s.town";
2168 $sql .= ", dictp.code as country_code";
2169 }
2170 $sql .= " FROM " . $this->db->prefix() . "societe as s";
2171 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
2172 $sql .= " LEFT JOIN " . $this->db->prefix() . "c_country as dictp ON dictp.rowid = s.fk_pays";
2173 }
2174 if (!$user->hasRight('societe', 'client', 'voir')) {
2175 $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
2176 }
2177 $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")";
2178 if (!empty($user->socid)) {
2179 $sql .= " AND s.rowid = " . ((int) $user->socid);
2180 }
2181 if ($filter) {
2182 // $filter is safe because, it has been tested by testSqlAndScriptInject() and sanitized by forgeSQLFromUniversalSearchCriteria()
2183 $sqlwhere = $filter; // @phan-suppress-current-line SqlInjection
2184 $sql .= " AND (" . $sqlwhere . ")";
2185 }
2186 if (!$user->hasRight('societe', 'client', 'voir')) {
2187 $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
2188 }
2189 if (getDolGlobalString('COMPANY_HIDE_INACTIVE_IN_COMBOBOX')) {
2190 $sql .= " AND s.status <> 0";
2191 }
2192 if (!empty($excludeids)) {
2193 $sql .= " AND s.rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeids)) . ")";
2194 }
2195 // Add where from hooks
2196 $parameters = array();
2197 $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
2198 $sql .= $hookmanager->resPrint;
2199 // Add criteria
2200 if ($filterkey && $filterkey != '') {
2201 $sql .= " AND (";
2202 $prefix = !getDolGlobalString('COMPANY_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
2203 // For natural search
2204 $search_crit = explode(' ', $filterkey);
2205 $i = 0;
2206 if (count($search_crit) > 1) {
2207 $sql .= "(";
2208 }
2209 foreach ($search_crit as $crit) {
2210 if ($i > 0) {
2211 $sql .= " AND ";
2212 }
2213 $sql .= "(s.nom LIKE '" . $this->db->escape($prefix . $crit) . "%')";
2214 $i++;
2215 }
2216 if (count($search_crit) > 1) {
2217 $sql .= ")";
2218 }
2219 if (isModEnabled('barcode')) {
2220 $sql .= " OR s.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
2221 }
2222 $sql .= " OR s.code_client LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.code_fournisseur LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
2223 $sql .= " OR s.name_alias LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.tva_intra LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
2224 $sql .= ")";
2225 }
2226 $sql .= $this->db->order("nom", "ASC");
2227 $sql .= $this->db->plimit($limit, 0);
2228
2229 // Build output string
2230 dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
2231 $resql = $this->db->query($sql);
2232 if ($resql) {
2233 // Construct $out and $outarray
2234 $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($moreparam ? ' ' . $moreparam : '') . ' name="' . $htmlname . ($multiple ? '[]' : '') . '"' . ($multiple ? ' multiple' : '') . '>' . "\n";
2235
2236 $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
2237 if (getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT')) {
2238 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
2239 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
2240 if ($showempty && !is_numeric($showempty)) {
2241 $textifempty = $langs->trans($showempty);
2242 } else {
2243 $textifempty .= $langs->trans("All");
2244 }
2245 }
2246 if ($showempty) {
2247 $out .= '<option value="-1" data-html="' . dol_escape_htmltag('<span class="opacitymedium">' . ($textifempty ? $textifempty : '&nbsp;') . '</span>') . '">' . $textifempty . '</option>' . "\n";
2248 }
2249
2250 $companytemp = new Societe($this->db);
2251
2252 $num = $this->db->num_rows($resql);
2253 $i = 0;
2254 if ($num) {
2255 while ($i < $num) {
2256 $obj = $this->db->fetch_object($resql);
2257 $label = '';
2258 if ($showcode || getDolGlobalString('SOCIETE_ADD_REF_IN_LIST')) {
2259 if (($obj->client) && (!empty($obj->code_client)) && $showcode != 'supplier') {
2260 $label = $obj->code_client . ' - ';
2261 }
2262 if (($obj->fournisseur) && (!empty($obj->code_fournisseur)) && $showcode != 'customer') {
2263 $label .= $obj->code_fournisseur . ' - ';
2264 }
2265 $label .= ' ' . $obj->name;
2266 } else {
2267 $label = $obj->name;
2268 }
2269
2270 if (!empty($obj->name_alias)) {
2271 $label .= ' (' . $obj->name_alias . ')';
2272 }
2273
2274 if (getDolGlobalString('SOCIETE_SHOW_VAT_IN_LIST') && !empty($obj->tva_intra)) {
2275 $label .= ' - '.$obj->tva_intra;
2276 }
2277
2278 $labelhtml = $label;
2279
2280 if ($showtype) {
2281 $companytemp->id = $obj->rowid;
2282 $companytemp->client = $obj->client;
2283 $companytemp->fournisseur = $obj->fournisseur;
2284 $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
2285 if ($tmptype) {
2286 $labelhtml .= ' ' . $tmptype;
2287 }
2288
2289 if ($obj->client || $obj->fournisseur) {
2290 $label .= ' (';
2291 }
2292 if ($obj->client == 1 || $obj->client == 3) {
2293 $label .= $langs->trans("Customer");
2294 }
2295 if ($obj->client == 2 || $obj->client == 3) {
2296 $label .= ($obj->client == 3 ? ', ' : '') . $langs->trans("Prospect");
2297 }
2298 if ($obj->fournisseur) {
2299 $label .= ($obj->client ? ', ' : '') . $langs->trans("Supplier");
2300 }
2301 if ($obj->client || $obj->fournisseur) {
2302 $label .= ')';
2303 }
2304 }
2305
2306 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
2307 $s = ($obj->address ? ' - ' . $obj->address : '') . ($obj->zip ? ' - ' . $obj->zip : '') . ($obj->town ? ' ' . $obj->town : '');
2308 if (!empty($obj->country_code)) {
2309 $s .= ', ' . $langs->trans('Country' . $obj->country_code);
2310 }
2311 $label .= $s;
2312 $labelhtml .= $s;
2313 }
2314
2315 if (empty($outputmode)) {
2316 if (in_array($obj->rowid, $selected)) {
2317 $out .= '<option value="' . $obj->rowid . '" selected data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
2318 } else {
2319 $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
2320 }
2321 } else {
2322 array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label, 'labelhtml' => $labelhtml));
2323 }
2324
2325 $i++;
2326 if (($i % 10) == 0) {
2327 $out .= "\n";
2328 }
2329 }
2330 }
2331 $out .= '</select>' . "\n";
2332 if (!$forcecombo) {
2333 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2334 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("COMPANY_USE_SEARCH_TO_SELECT"));
2335 }
2336 } else {
2337 dol_print_error($this->db);
2338 }
2339
2340 $this->result = array('nbofthirdparties' => $num);
2341
2342 if ($outputmode) {
2343 return $outarray;
2344 }
2345 return $out;
2346 }
2347
2348
2376 public function selectcontacts($socid, $selected = array(), $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $options_only = 0, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0, $filter = '', $limit = 0, $limitoffset = 0)
2377 {
2378 global $conf, $user, $langs, $hookmanager, $action;
2379
2380 $langs->load('companies');
2381
2382 if (empty($htmlid)) {
2383 $htmlid = $htmlname;
2384 }
2385 $num = 0;
2386 $out = '';
2387 $outarray = array();
2388
2389 if ($selected === '') {
2390 $selected = array();
2391 } elseif (!is_array($selected)) {
2392 $selected = array((int) $selected);
2393 }
2394
2395 // Clean $filter that may contains sql conditions so sql code
2396 if (function_exists('testSqlAndScriptInject')) {
2397 if (testSqlAndScriptInject($filter, 3) > 0) {
2398 $filter = '';
2399 return 'SQLInjectionTryDetected';
2400 }
2401 }
2402
2403 if ($filter != '') { // If a filter was provided
2404 if (preg_match('/[\‍(\‍)]/', $filter)) {
2405 // If there is one parenthesis inside the criteria, we assume it is an Universal Filter Syntax.
2406 $errormsg = '';
2407 $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
2408
2409 // Redo clean $filter that may contains sql conditions so sql code
2410 if (function_exists('testSqlAndScriptInject')) {
2411 if (testSqlAndScriptInject($filter, 3) > 0) {
2412 $filter = '';
2413 return 'SQLInjectionTryDetected';
2414 }
2415 }
2416 } else {
2417 // If not, we do nothing. We already know that there is no parenthesis
2418 // TODO Disallow this case in a future by returning an error here.
2419 dol_syslog("Warning, select_thirdparty_list was called with a filter criteria not using the Universal Search Filter Syntax.", LOG_WARNING);
2420 }
2421 }
2422
2423 if (!is_object($hookmanager)) {
2424 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
2425 $hookmanager = new HookManager($this->db);
2426 }
2427
2428 // We search third parties
2429 $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";
2430 if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
2431 $sql .= ", s.nom as company, s.town AS company_town";
2432 }
2433 $sql .= " FROM " . $this->db->prefix() . "socpeople as sp";
2434 if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
2435 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON s.rowid = sp.fk_soc";
2436 }
2437 $sql .= " WHERE sp.entity IN (" . getEntity('contact') . ")";
2438 $sql .= " AND ((sp.fk_user_creat = ".((int) $user->id)." AND sp.priv = 1) OR sp.priv = 0)"; // check if this is a private contact
2439 if ($socid > 0 || $socid == -1) {
2440 $sql .= " AND sp.fk_soc = " . ((int) $socid);
2441 }
2442 if (getDolGlobalString('CONTACT_HIDE_INACTIVE_IN_COMBOBOX')) {
2443 $sql .= " AND sp.statut <> 0";
2444 }
2445 // filter user access
2446 if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
2447 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = sp.fk_soc AND sc.fk_user = ".(int) $user->id .")";
2448 }
2449 if ($user->socid > 0) {
2450 $sql .= " AND sp.fk_soc = ".((int) $user->socid);
2451 }
2452 if ($filter) {
2453 // $filter is safe because, if it contains '(' or ')', it has been sanitized by testSqlAndScriptInject() and forgeSQLFromUniversalSearchCriteria()
2454 // if not, by testSqlAndScriptInject() only.
2455 $sanitizedfilter = $filter; // @phan-suppress-current-line SqlInjection
2456 $sql .= " AND (" . $sanitizedfilter . ")";
2457 }
2458 // Add where from hooks
2459 $parameters = array();
2460 $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
2461 $sql .= $hookmanager->resPrint;
2462 $sql .= " ORDER BY sp.lastname ASC";
2463 $sql .= $this->db->plimit($limit, ((int) $limitoffset > 0 ? (int) $limitoffset : 0));
2464
2465 dol_syslog(get_class($this) . "::selectcontacts", LOG_DEBUG);
2466 $resql = $this->db->query($sql);
2467 if ($resql) {
2468 $num = $this->db->num_rows($resql);
2469
2470 if ($htmlname != 'none' && !$options_only) {
2471 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlid . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . (($num || empty($disableifempty)) ? '' : ' disabled') . ($multiple ? 'multiple' : '') . ' ' . (!empty($moreparam) ? $moreparam : '') . '>';
2472 }
2473
2474 if ($showempty && !is_numeric($showempty)) {
2475 $textforempty = $showempty;
2476 $out .= '<option class="optiongrey" value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>' . dol_escape_htmltag($textforempty) . '</option>';
2477 } else {
2478 if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
2479 $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>&nbsp;</option>';
2480 }
2481 if ($showempty == 2) {
2482 $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>-- ' . $langs->trans("Internal") . ' --</option>';
2483 }
2484 }
2485
2486 $i = 0;
2487 if ($num) {
2488 include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2489 $contactstatic = new Contact($this->db);
2490
2491 while ($i < $num) {
2492 $obj = $this->db->fetch_object($resql);
2493
2494 // Set email (or phones) and town extended infos
2495 $extendedInfos = '';
2496 if (getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
2497 $extendedInfos = array();
2498 $email = trim($obj->email);
2499 if (!empty($email)) {
2500 $extendedInfos[] = $email;
2501 } else {
2502 $phone = trim($obj->phone);
2503 $phone_perso = trim($obj->phone_perso);
2504 $phone_mobile = trim($obj->phone_mobile);
2505 if (!empty($phone)) {
2506 $extendedInfos[] = $phone;
2507 }
2508 if (!empty($phone_perso)) {
2509 $extendedInfos[] = $phone_perso;
2510 }
2511 if (!empty($phone_mobile)) {
2512 $extendedInfos[] = $phone_mobile;
2513 }
2514 }
2515 $contact_town = trim($obj->contact_town);
2516 $company_town = trim($obj->company_town);
2517 if (!empty($contact_town)) {
2518 $extendedInfos[] = $contact_town;
2519 } elseif (!empty($company_town)) {
2520 $extendedInfos[] = $company_town;
2521 }
2522 $extendedInfos = implode(' - ', $extendedInfos);
2523 if (!empty($extendedInfos)) {
2524 $extendedInfos = ' - ' . $extendedInfos;
2525 }
2526 }
2527
2528 $contactstatic->id = $obj->rowid;
2529 $contactstatic->lastname = $obj->lastname;
2530 $contactstatic->firstname = $obj->firstname;
2531 if ($obj->statut == 1) {
2532 $tmplabel = '';
2533 if ($htmlname != 'none') {
2534 $disabled = 0;
2535 if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
2536 $disabled = 1;
2537 }
2538 if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
2539 $disabled = 1;
2540 }
2541 if (!empty($selected) && in_array($obj->rowid, $selected)) {
2542 $out .= '<option value="' . $obj->rowid . '"';
2543 if ($disabled) {
2544 $out .= ' disabled';
2545 }
2546 $out .= ' selected>';
2547
2548 $tmplabel = $contactstatic->getFullName($langs) . $extendedInfos;
2549 if ($showfunction && $obj->poste) {
2550 $tmplabel .= ' (' . $obj->poste . ')';
2551 }
2552 if (($showsoc > 0) && $obj->company) {
2553 $tmplabel .= ' - (' . $obj->company . ')';
2554 }
2555
2556 $out .= $tmplabel;
2557 $out .= '</option>';
2558 } else {
2559 $out .= '<option value="' . $obj->rowid . '"';
2560 if ($disabled) {
2561 $out .= ' disabled';
2562 }
2563 $out .= '>';
2564
2565 $tmplabel = $contactstatic->getFullName($langs) . $extendedInfos;
2566 if ($showfunction && $obj->poste) {
2567 $tmplabel .= ' (' . $obj->poste . ')';
2568 }
2569 if (($showsoc > 0) && $obj->company) {
2570 $tmplabel .= ' - (' . $obj->company . ')';
2571 }
2572
2573 $out .= $tmplabel;
2574 $out .= '</option>';
2575 }
2576 } else {
2577 if (in_array($obj->rowid, $selected)) {
2578 $tmplabel = $contactstatic->getFullName($langs) . $extendedInfos;
2579 if ($showfunction && $obj->poste) {
2580 $tmplabel .= ' (' . $obj->poste . ')';
2581 }
2582 if (($showsoc > 0) && $obj->company) {
2583 $tmplabel .= ' - (' . $obj->company . ')';
2584 }
2585
2586 $out .= $tmplabel;
2587 }
2588 }
2589
2590 if ($tmplabel != '') {
2591 array_push($outarray, array('key' => $obj->rowid, 'value' => $tmplabel, 'label' => $tmplabel, 'labelhtml' => $tmplabel));
2592 }
2593 }
2594 $i++;
2595 }
2596 } else {
2597 $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
2598 $out .= '<option class="disabled" value="-1"' . (($showempty == 2 || $multiple) ? '' : ' selected') . ' disabled="disabled">';
2599 $out .= $labeltoshow;
2600 $out .= '</option>';
2601 }
2602
2603 $parameters = array(
2604 'socid' => $socid,
2605 'htmlname' => $htmlname,
2606 'resql' => $resql,
2607 'out' => &$out,
2608 'showfunction' => $showfunction,
2609 'showsoc' => $showsoc,
2610 );
2611
2612 $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2613
2614 if ($htmlname != 'none' && !$options_only) {
2615 $out .= '</select>';
2616 }
2617
2618 if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
2619 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2620 $out .= ajax_combobox($htmlid, $events, getDolGlobalInt("CONTACT_USE_SEARCH_TO_SELECT"));
2621 }
2622
2623 $this->num = $num;
2624
2625 if ($options_only === 2) {
2626 // Return array of options
2627 return $outarray;
2628 } else {
2629 return $out;
2630 }
2631 } else {
2632 dol_print_error($this->db);
2633 return -1;
2634 }
2635 }
2636
2637
2638 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2639
2650 public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
2651 {
2652 // phpcs:enable
2653 global $langs, $conf;
2654
2655 $showsourceinvoice = getDolGlobalString('MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST');
2656
2657 // Search for the discounts
2658 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
2659 $sql .= " re.description, re.fk_facture_source, re.fk_invoice_supplier_source";
2660 if ($showsourceinvoice) {
2661 // Resolve the source invoice (customer or supplier) in the main query instead of one fetch per line
2662 $sql .= ", f.ref as src_cust_ref, f.datef as src_cust_date";
2663 $sql .= ", ff.ref as src_supp_ref, ff.datef as src_supp_date";
2664 }
2665 $sql .= " FROM " . $this->db->prefix() . "societe_remise_except as re";
2666 if ($showsourceinvoice) {
2667 $sql .= " LEFT JOIN " . $this->db->prefix() . "facture as f ON f.rowid = re.fk_facture_source";
2668 $sql .= " LEFT JOIN " . $this->db->prefix() . "facture_fourn as ff ON ff.rowid = re.fk_invoice_supplier_source";
2669 }
2670 $sql .= " WHERE re.fk_soc = " . (int) $socid;
2671 $sql .= " AND re.entity = " . ((int) $conf->entity);
2672 if ($filter) {
2673 $sanitizedfilter = $filter; // @phan-suppress-current-line SqlInjection
2674 if ($showsourceinvoice) {
2675 // The joined tables also carry a fk_facture_source column: qualify unprefixed references of the caller filter
2676 $sanitizedfilter = preg_replace('/(?<![a-zA-Z0-9_.])fk_facture_source\b/', 're.fk_facture_source', $sanitizedfilter);
2677 }
2678 $sql .= " AND " . $sanitizedfilter;
2679 }
2680 if ($showsourceinvoice) {
2681 // When the source invoices are shown, their date is the natural order (oldest deposit first)
2682 $sql .= " ORDER BY COALESCE(ff.datef, f.datef, re.datec) ASC, re.rowid ASC";
2683 } else {
2684 $sql .= " ORDER BY re.description ASC";
2685 }
2686
2687 dol_syslog(get_class($this) . "::select_remises", LOG_DEBUG);
2688 $resql = $this->db->query($sql);
2689 if ($resql) {
2690 print '<select id="select_' . $htmlname . '" class="flat maxwidth300 maxwidth200onsmartphone" name="' . $htmlname . '">';
2691 $num = $this->db->num_rows($resql);
2692
2693 $qualifiedlines = $num;
2694
2695 $i = 0;
2696 if ($num) {
2697 print '<option value="0">&nbsp;</option>';
2698 while ($i < $num) {
2699 $obj = $this->db->fetch_object($resql);
2700 $desc = dol_trunc($obj->description, 40);
2701 if (preg_match('/\‍(CREDIT_NOTE\‍)/', $desc)) {
2702 $desc = preg_replace('/\‍(CREDIT_NOTE\‍)/', $langs->trans("CreditNote"), $desc);
2703 }
2704 if (preg_match('/\‍(DEPOSIT\‍)/', $desc)) {
2705 $desc = preg_replace('/\‍(DEPOSIT\‍)/', $langs->trans("Deposit"), $desc);
2706 }
2707 if (preg_match('/\‍(EXCESS RECEIVED\‍)/', $desc)) {
2708 $desc = preg_replace('/\‍(EXCESS RECEIVED\‍)/', $langs->trans("ExcessReceived"), $desc);
2709 }
2710 if (preg_match('/\‍(EXCESS PAID\‍)/', $desc)) {
2711 $desc = preg_replace('/\‍(EXCESS PAID\‍)/', $langs->trans("ExcessPaid"), $desc);
2712 }
2713
2714 $selectstring = '';
2715 if ($selected > 0 && $selected == $obj->rowid) {
2716 $selectstring = ' selected';
2717 }
2718
2719 $disabled = '';
2720 if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
2721 $qualifiedlines--;
2722 $disabled = ' disabled';
2723 }
2724
2725 if ($showsourceinvoice) {
2726 $srcref = !empty($obj->src_supp_ref) ? $obj->src_supp_ref : (!empty($obj->src_cust_ref) ? $obj->src_cust_ref : '');
2727 $srcdate = !empty($obj->src_supp_date) ? $obj->src_supp_date : (!empty($obj->src_cust_date) ? $obj->src_cust_date : '');
2728 if ($srcref) {
2729 $desc = $desc . ' - ' . $srcref;
2730 if ($srcdate) {
2731 $desc .= ' (' . dol_print_date($this->db->jdate($srcdate), 'day') . ')';
2732 }
2733 }
2734 }
2735
2736 print '<option value="' . $obj->rowid . '"' . $selectstring . $disabled . '>' . $desc . ' (' . price($obj->amount_ht) . ' ' . $langs->trans("HT") . ' - ' . price($obj->amount_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
2737 $i++;
2738 }
2739 }
2740 print '</select>';
2741 print ajax_combobox('select_' . $htmlname);
2742
2743 return $qualifiedlines;
2744 } else {
2745 dol_print_error($this->db);
2746 return -1;
2747 }
2748 }
2749
2750
2751 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2752
2768 public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0')
2769 {
2770 // phpcs:enable
2771 print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
2772 }
2773
2785 public static $user_combo_allowed_morefilters = array(
2786 'u.statut:=:1', // active users only
2787 '(statut:=:1)', // active users only
2788 'employee:=:1', // employees only
2789 '(employee:=:1)', // employees only
2790 '(admin:=:1) AND (statut:=:1)', // active administrators only
2791 );
2792
2800 public static function isUserComboMorefilterAllowed($morefilter)
2801 {
2802 return in_array(trim((string) $morefilter), self::$user_combo_allowed_morefilters, true);
2803 }
2804
2820 private function buildSelectDolusersAjaxUrlOption($htmlname, $exclude, $include, $force_entity, $showstatus, $notdisabled, $maxlength, $morefilter = '')
2821 {
2822 $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1';
2823 if (is_array($exclude) && count($exclude)) {
2824 $urloption .= '&exclude='.urlencode(implode(',', $exclude));
2825 }
2826 if (is_array($include) && count($include)) {
2827 $urloption .= '&include='.urlencode(implode(',', $include));
2828 } elseif (is_string($include) && $include !== '') {
2829 $urloption .= '&include='.urlencode($include);
2830 }
2831 if ($force_entity !== '') {
2832 $urloption .= '&force_entity='.urlencode((string) $force_entity);
2833 }
2834 if ($showstatus !== 0) {
2835 $urloption .= '&showstatus='.((int) $showstatus);
2836 }
2837 if (!empty($notdisabled)) {
2838 $urloption .= '&notdisabled=1';
2839 }
2840 if (!empty($maxlength)) {
2841 $urloption .= '&maxlength='.((int) $maxlength);
2842 }
2843 // $morefilter is a raw Universal Search Filter fed to forgeSQLFromUniversalSearchCriteria().
2844 // Only forward it when it is one of the known-safe expressions of self::$user_combo_allowed_morefilters
2845 // (the endpoint re-checks against the same list); any other value would let a client run arbitrary
2846 // WHERE clauses on llx_user and is dropped here - the ajax list is then simply not narrowed by it.
2847 if ((string) $morefilter !== '') {
2848 if (self::isUserComboMorefilterAllowed($morefilter)) {
2849 $urloption .= '&morefilter='.urlencode(trim((string) $morefilter));
2850 } else {
2851 dol_syslog(__METHOD__.": morefilter '".$morefilter."' is not in Form::\$user_combo_allowed_morefilters; the search-to-select user list will not be narrowed by it", LOG_WARNING);
2852 }
2853 }
2854 return $urloption;
2855 }
2856
2868 private function buildSelectDolusersAjaxSelect2Script($htmlname, $urloption, $minlengthforajax, $ajaxpagesize)
2869 {
2870 $htmlnamejs = str_replace('.', '\\\\.', $htmlname);
2871 return '<script nonce="'.getNonce().'">jQuery(function() {
2872 jQuery("#'.$htmlnamejs.'").select2({
2873 theme: "default",
2874 language: (typeof select2arrayoflanguage === "undefined") ? "en" : select2arrayoflanguage,
2875 containerCssClass: ":all:",
2876 placeholder: "",
2877 minimumInputLength: '.((int) $minlengthforajax).',
2878 ajax: {
2879 url: "'.DOL_URL_ROOT.'/user/ajax/users.php?'.$urloption.'",
2880 dataType: "json",
2881 delay: 250,
2882 data: function(params) {
2883 var d = {};
2884 d['.json_encode($htmlname).'] = params.term;
2885 d.page = params.page || 1;
2886 return d;
2887 },
2888 processResults: function(data) {
2889 var result = [];
2890 jQuery.each(data, function(i, val) {
2891 result.push({ id: val.key, text: val.value });
2892 });
2893 return { results: result, pagination: { more: data.length >= '.((int) $ajaxpagesize).' } };
2894 },
2895 cache: true
2896 }
2897 });
2898 });</script>';
2899 }
2900
2901 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2902
2930 public function select_dolusers($userselected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '', $maxlength = 0, $showstatus = 0, $morefilter = '', $showalso = 0, $enableonlytext = '', $morecss = '', $notdisabled = 0, $outputmode = 0, $multiple = false, $forcecombo = 0, $filterkey = '', $limit = 0, $limitoffset = 0)
2931 {
2932 // phpcs:enable
2933 global $conf, $user, $langs, $hookmanager;
2934 global $action;
2935
2936 // Convert $selected into an int (in case it is an object)
2937 if (is_object($userselected)) {
2938 $selected = (int) $userselected->id;
2939 } elseif (is_numeric($userselected)) {
2940 $selected = (int) $userselected;
2941 } elseif (is_array($userselected)) {
2942 $selected = $userselected;
2943 } else {
2944 $selected = -1;
2945 }
2946
2947 // If no preselected user defined, we take current user
2948 if ((is_numeric($selected) && ((int) $selected < -4 || empty($selected))) && !getDolGlobalString('SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE')) {
2949 $selected = $user->id;
2950 }
2951
2952 // Convert selected int into an array
2953 if (!is_array($selected)) {
2954 if ($selected === -1 || $selected === '') {
2955 $selected = array();
2956 } else {
2957 $selected = array($selected);
2958 }
2959 }
2960
2961 // Exclude some users in $excludeUsers string
2962 $excludeUsers = null;
2963 if (is_array($exclude)) {
2964 $excludeUsers = implode(",", $exclude);
2965 }
2966
2967 // Include some users in $includeUsers string
2968 $includeUsers = null;
2969 $includeUsersArray = array();
2970 if (is_array($include)) {
2971 $includeUsersArray = $include;
2972 } elseif ($include == 'hierarchy') {
2973 // Build list includeUsersArray to have only hierarchy
2974 $includeUsersArray = $user->getAllChildIds(0);
2975 } elseif ($include == 'hierarchyme') {
2976 // Build list includeUsersArray to have only hierarchy and current user
2977 $includeUsersArray = $user->getAllChildIds(1);
2978 }
2979 // Get list of allowed users
2980 /* We do not limit list of users. Because we should limit this only for combo list into HR features where we may be allowed to
2981 * see all other users and element in other. For example in agenda, we can have permission to read all event of otherusers.
2982 * So we disable this.
2983 if (!$user->hasRight('user', 'user', 'lire')) {
2984 if (empty($includeUsersArray)) {
2985 $includeUsers = implode(",", $user->getAllChildIds(1));
2986 } else {
2987 $includeUsers = implode(",", array_intersect($includeUsersArray, $user->getAllChildIds(1)));
2988 }
2989 } else {
2990 $includeUsers = implode(",", $includeUsersArray);
2991 } */
2992 $includeUsers = implode(",", $includeUsersArray);
2993
2994 $num = 0;
2995
2996 $out = '';
2997 $outarray = array();
2998 $outarray2 = array();
2999
3000 // If the ajax "search to select" mode is enabled for users (constant USER_USE_SEARCH_TO_SELECT), we output a
3001 // select2 combo calling user/ajax/users.php instead of loading the full list of users. This is limited to
3002 // the HTML output: array output, forced combo, pseudo-entries (showalso) and per-line enabling (enableonly)
3003 // keep the full-list behaviour. Both single and multiple select page through the same endpoint (see
3004 // buildSelectDolusersAjaxSelect2Script()); only the <select> markup (single option vs multiple/[]) differs.
3005 $canajaxsearchtoselect = !empty($conf->use_javascript_ajax) && getDolGlobalString('USER_USE_SEARCH_TO_SELECT') && !$forcecombo && empty($outputmode)
3006 && empty($showalso) && !(is_array($enableonly) && count($enableonly)) && $filterkey === '';
3007
3008 if ($canajaxsearchtoselect && !$multiple) {
3009 $preselected = 0;
3010 if (!empty($selected)) {
3011 $firstval = reset($selected);
3012 if (is_numeric($firstval) && (int) $firstval > 0) {
3013 $preselected = (int) $firstval;
3014 }
3015 }
3016
3017 $preselectedlabel = '';
3018 if ($preselected > 0) {
3019 $usertmpselect = new User($this->db);
3020 if ($usertmpselect->fetch($preselected) > 0) {
3021 $fullNameMode = getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION') ? 0 : 1;
3022 $preselectedlabel = $usertmpselect->getFullName($langs, $fullNameMode, -1, $maxlength);
3023 if ($preselectedlabel === '') {
3024 $preselectedlabel = $usertmpselect->login;
3025 }
3026 }
3027 unset($usertmpselect);
3028 }
3029
3030 $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').'>';
3031 if ($preselected > 0) {
3032 $out .= '<option value="'.$preselected.'" selected>'.dol_escape_htmltag($preselectedlabel).'</option>';
3033 }
3034 $out .= '</select>';
3035
3036 // Propagate the filters to the ajax endpoint so it returns the same subset as the full combo would
3037 $urloption = $this->buildSelectDolusersAjaxUrlOption($htmlname, $exclude, $include, $force_entity, $showstatus, $notdisabled, $maxlength, $morefilter);
3038
3039 // A non-numeric value ('infinite') means "infinite list": no minimum number of chars, the list
3040 // opens as soon as the field gets the focus (select2 queries the endpoint with an empty term).
3041 $minlengthforajax = getDolGlobalInt('USER_USE_SEARCH_TO_SELECT');
3042 if ($minlengthforajax < 1) {
3043 $minlengthforajax = 0;
3044 }
3045 // Page size of the ajax endpoint (USER_LIMIT_SIZE): select2 keeps asking for the next page
3046 // while the endpoint returns a full page, so the whole list stays browsable by scrolling.
3047 $ajaxpagesize = getDolGlobalInt('USER_LIMIT_SIZE', 20);
3048
3049 $out .= $this->buildSelectDolusersAjaxSelect2Script($htmlname, $urloption, $minlengthforajax, $ajaxpagesize);
3050 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.select2-container { z-index: 1010; }</style>';
3051
3052 return $out;
3053 }
3054
3055 if ($canajaxsearchtoselect && $multiple) {
3056 // Multiple select + "search to select": render a select2 combo pre-filled with only the currently
3057 // selected users as <option selected>. select2 keeps those and fetches the rest on demand from
3058 // user/ajax/users.php instead of loading the whole llx_user table into the page.
3059 $preselectedids = array();
3060 foreach ($selected as $tmpid) {
3061 if (is_numeric($tmpid) && (int) $tmpid > 0) {
3062 $preselectedids[] = (int) $tmpid;
3063 }
3064 }
3065
3066 $fullNameMode = getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION') ? 0 : 1;
3067 $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.'[]" multiple'.($disabled ? ' disabled' : '').'>';
3068 if (count($preselectedids)) {
3069 $usertmpselect = new User($this->db);
3070 foreach ($preselectedids as $tmpid) {
3071 if ($usertmpselect->fetch($tmpid) > 0) {
3072 $labeltoshow = $usertmpselect->getFullName($langs, $fullNameMode, -1, $maxlength);
3073 if ($labeltoshow === '') {
3074 $labeltoshow = $usertmpselect->login;
3075 }
3076 $out .= '<option value="'.$tmpid.'" selected>'.dol_escape_htmltag($labeltoshow).'</option>';
3077 }
3078 }
3079 unset($usertmpselect);
3080 }
3081 $out .= '</select>';
3082
3083 $urloption = $this->buildSelectDolusersAjaxUrlOption($htmlname, $exclude, $include, $force_entity, $showstatus, $notdisabled, $maxlength, $morefilter);
3084
3085 // A non-numeric value ('infinite') means "infinite list": no minimum number of chars, the list
3086 // opens as soon as the field gets the focus (select2 queries the endpoint with an empty term).
3087 $minlengthforajax = getDolGlobalInt('USER_USE_SEARCH_TO_SELECT');
3088 if ($minlengthforajax < 1) {
3089 $minlengthforajax = 0;
3090 }
3091 // Page size of the ajax endpoint (USER_LIMIT_SIZE): select2 keeps asking for the next page
3092 // while the endpoint returns a full page, so the whole list stays browsable by scrolling.
3093 $ajaxpagesize = getDolGlobalInt('USER_LIMIT_SIZE', 20);
3094
3095 $out .= $this->buildSelectDolusersAjaxSelect2Script($htmlname, $urloption, $minlengthforajax, $ajaxpagesize);
3096 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.select2-container { z-index: 1010; }</style>';
3097
3098 return $out;
3099 }
3100
3101 // Do we want to show the label of entity into the combo list ?
3102 $showlabelofentity = isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1 && !empty($user->admin) && empty($user->entity) && !preg_match('/^search_/', $htmlname);
3103 $userissuperadminentityone = isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && empty($user->entity);
3104
3105 // Forge request to select users
3106 $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.gender, u.photo";
3107 if ($showlabelofentity) {
3108 $sql .= ", e.label";
3109 }
3110 $sql .= " FROM " . $this->db->prefix() . "user as u";
3111 if ($showlabelofentity) {
3112 $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid = u.entity";
3113 }
3114 // Condition here should be the same than into societe->getSalesRepresentatives().
3115 if ($userissuperadminentityone && $force_entity !== 'default') {
3116 if (!empty($force_entity)) {
3117 $sql .= " WHERE u.entity IN (0, " . $this->db->sanitize($force_entity) . ")";
3118 } else {
3119 $sql .= " WHERE u.entity IS NOT NULL";
3120 }
3121 } else {
3122 if (isModEnabled('multicompany') && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
3123 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
3124 } else {
3125 $sql .= " WHERE u.entity IN (" . getEntity('user') . ")";
3126 }
3127 }
3128
3129 if (!empty($user->socid)) {
3130 $sql .= " AND u.fk_soc = " . ((int) $user->socid);
3131 }
3132 if (is_array($exclude) && $excludeUsers) {
3133 $sql .= " AND u.rowid NOT IN (" . $this->db->sanitize($excludeUsers) . ")";
3134 }
3135 if ($includeUsers) {
3136 $sql .= " AND u.rowid IN (" . $this->db->sanitize($includeUsers) . ")";
3137 }
3138 if (getDolGlobalString('USER_HIDE_INACTIVE_IN_COMBOBOX') || $notdisabled) {
3139 $sql .= " AND (u.statut <> 0";
3140 if (!empty($selected)) {
3141 $sql .= " OR u.rowid IN (".$this->db->sanitize(implode(',', $selected)).")"; // We must always keep the selected users to avoid to loose it/them when updating
3142 }
3143 $sql .= ")";
3144 }
3145 if (getDolGlobalString('USER_HIDE_NONEMPLOYEE_IN_COMBOBOX')) {
3146 $sql .= " AND u.employee <> 0";
3147 }
3148 if (getDolGlobalString('USER_HIDE_EXTERNAL_IN_COMBOBOX')) {
3149 $sql .= " AND u.fk_soc IS NULL";
3150 }
3151 if (!empty($morefilter)) {
3152 $errormessage = '';
3153 $sql .= forgeSQLFromUniversalSearchCriteria($morefilter, $errormessage);
3154 if ($errormessage) {
3155 $this->errors[] = $errormessage;
3156 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
3157 if ($outputmode == 0) {
3158 return 'Error bad param $morefilter';
3159 } else {
3160 return array();
3161 }
3162 }
3163 }
3164
3165 //Add hook to filter on user (for example on usergroup define in custom modules)
3166 $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
3167 if (!empty($reshook)) {
3168 $sql .= $hookmanager->resPrint;
3169 }
3170
3171 // Add criteria on the natural search string (used by the user/ajax/users.php autocomplete endpoint)
3172 if ($filterkey !== '') {
3173 $sql .= " AND (";
3174 $prefix = getDolGlobalString('USER_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if USER_DONOTSEARCH_ANYWHERE is on
3175 // For natural search
3176 $search_crit = explode(' ', $filterkey);
3177 $i = 0;
3178 if (count($search_crit) > 1) {
3179 $sql .= "(";
3180 }
3181 foreach ($search_crit as $crit) {
3182 if ($i > 0) {
3183 $sql .= " AND ";
3184 }
3185 $sql .= "(u.firstname LIKE '".$this->db->escape($prefix.$crit)."%' OR u.lastname LIKE '".$this->db->escape($prefix.$crit)."%' OR u.login LIKE '".$this->db->escape($prefix.$crit)."%')";
3186 $i++;
3187 }
3188 if (count($search_crit) > 1) {
3189 $sql .= ")";
3190 }
3191 $sql .= ")";
3192 }
3193
3194 if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
3195 $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
3196 } else {
3197 $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
3198 }
3199
3200 if ($limit > 0) {
3201 $sql .= $this->db->plimit($limit, ((int) $limitoffset > 0 ? (int) $limitoffset : 0));
3202 }
3203
3204 dol_syslog(get_class($this) . "::select_dolusers", LOG_DEBUG);
3205
3206 $resql = $this->db->query($sql);
3207 if ($resql) {
3208 $num = $this->db->num_rows($resql);
3209 $i = 0;
3210 if ($num) {
3211 // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
3212 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : ' minwidth200') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
3213 if ($show_empty && !$multiple) {
3214 $textforempty = ' ';
3215 if (!empty($conf->use_javascript_ajax)) {
3216 $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
3217 }
3218 if (!is_numeric($show_empty)) {
3219 $textforempty = $show_empty;
3220 }
3221 $out .= '<option class="optiongrey" value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ((empty($selected) || in_array(-1, $selected)) ? ' selected' : '') . '>' . dol_escape_htmltag($textforempty) . '</option>' . "\n";
3222
3223 $outarray[($show_empty < 0 ? $show_empty : -1)] = $textforempty;
3224 $outarray2[($show_empty < 0 ? $show_empty : -1)] = array(
3225 'id' => ($show_empty < 0 ? $show_empty : -1),
3226 'label' => $textforempty,
3227 'labelhtml' => $textforempty,
3228 'color' => '',
3229 'picto' => ''
3230 );
3231 }
3232 if ($showalso == 2 || $showalso == 3) {
3233 $out .= '<option value="-3"' . ((in_array(-3, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("MyTeam") . ' --</option>' . "\n";
3234
3235 $hasAtLeastOneSubordinate = (count($user->getAllChildIds(1)) > 1);
3236 if ($hasAtLeastOneSubordinate) {
3237 //$sql = "SELECT rowid FROM".MAIN_DB_PREFIX."user "
3238 $outarray[-3] = '-- ' . $langs->trans("MyTeam") . ' --';
3239 $outarray2[-3] = array(
3240 'id' => -3,
3241 'label' => '-- ' . $langs->trans("MyTeam") . ' --',
3242 'labelhtml' => '-- ' . $langs->trans("MyTeam") . ' --',
3243 'color' => '',
3244 'picto' => ''
3245 );
3246 }
3247 }
3248 if ($showalso == 1 || $showalso == 3) {
3249 $out .= '<option value="-2"' . ((in_array(-2, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("Everybody") . ' --</option>' . "\n";
3250
3251 $outarray[-2] = '-- ' . $langs->trans("Everybody") . ' --';
3252 $outarray2[-2] = array(
3253 'id' => -2,
3254 'label' => '-- ' . $langs->trans("Everybody") . ' --',
3255 'labelhtml' => '-- ' . $langs->trans("Everybody") . ' --',
3256 'color' => '',
3257 'picto' => ''
3258 );
3259 }
3260 if ($showalso == 4) {
3261 $out .= '<option value="-4"' . ((in_array(-4, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("AllProjectContacts") . ' --</option>' . "\n";
3262
3263 $outarray[-4] = '-- ' . $langs->trans("AllProjectContacts") . ' --';
3264 $outarray2[-4] = array(
3265 'id' => -4,
3266 'label' => '-- ' . $langs->trans("AllProjectContacts") . ' --',
3267 'labelhtml' => '-- ' . $langs->trans("AllProjectContacts") . ' --',
3268 'color' => '',
3269 'picto' => ''
3270 );
3271 }
3272
3273 $userstatic = new User($this->db);
3274
3275 while ($i < $num) {
3276 $obj = $this->db->fetch_object($resql);
3277
3278 $userstatic->id = $obj->rowid;
3279 $userstatic->lastname = $obj->lastname;
3280 $userstatic->firstname = $obj->firstname;
3281 $userstatic->photo = $obj->photo;
3282 $userstatic->status = $obj->status;
3283 $userstatic->entity = $obj->entity;
3284 $userstatic->admin = $obj->admin;
3285 $userstatic->gender = $obj->gender;
3286
3287 $disableline = '';
3288 if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
3289 $disableline = ($enableonlytext ? $enableonlytext : '1');
3290 }
3291
3292 $labeltoshow = '';
3293 $labeltoshowhtml = '';
3294
3295 // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
3296 $fullNameMode = 0;
3297 if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) {
3298 $fullNameMode = 1; //Firstname+lastname
3299 }
3300 $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
3301 $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
3302 if (empty($obj->firstname) && empty($obj->lastname)) {
3303 $labeltoshow .= $obj->login;
3304 $labeltoshowhtml .= $obj->login;
3305 }
3306
3307 // Complete name with a more info string like: ' (info1 - info2 - ...)'
3308 $moreinfo = '';
3309 $moreinfohtml = '';
3310 if (getDolGlobalString('MAIN_SHOW_LOGIN')) {
3311 $moreinfo .= ($moreinfo ? ' - ' : ' (');
3312 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
3313 $moreinfo .= $obj->login;
3314 $moreinfohtml .= $obj->login;
3315 }
3316 if ($showstatus >= 0) {
3317 if ($obj->status == 1 && $showstatus == 1) {
3318 $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Enabled');
3319 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Enabled');
3320 }
3321 if ($obj->status == 0 && $showstatus == 1) {
3322 $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Disabled');
3323 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Disabled');
3324 }
3325 }
3326 if ($showlabelofentity) {
3327 if (empty($obj->entity)) {
3328 $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans("AllEntities");
3329 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans("AllEntities");
3330 } else {
3331 if ($obj->entity != $conf->entity) {
3332 $moreinfo .= ($moreinfo ? ' - ' : ' (') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
3333 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
3334 }
3335 }
3336 }
3337 $moreinfo .= (!empty($moreinfo) ? ')' : '');
3338 $moreinfohtml .= (!empty($moreinfohtml) ? ')</span>' : '');
3339 if (!empty($disableline) && $disableline != '1') {
3340 // Add text from $enableonlytext parameter
3341 $moreinfo .= ' - ' . $disableline;
3342 $moreinfohtml .= ' - ' . $disableline;
3343 }
3344 $labeltoshow .= $moreinfo;
3345 $labeltoshowhtml .= $moreinfohtml;
3346
3347 $out .= '<option value="' . $obj->rowid . '"';
3348 if (!empty($disableline)) {
3349 $out .= ' disabled';
3350 }
3351 if (in_array($obj->rowid, $selected)) {
3352 $out .= ' selected';
3353 }
3354 $out .= ' data-html="';
3355
3356 $outhtml = $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1) . ' ';
3357 if ($showstatus >= 0 && $obj->status == 0) {
3358 $outhtml .= '<strike class="opacitymediumxxx">';
3359 }
3360 $outhtml .= $labeltoshowhtml;
3361 if ($showstatus >= 0 && $obj->status == 0) {
3362 $outhtml .= '</strike>';
3363 }
3364 $labeltoshowhtml = $outhtml;
3365
3366 $out .= dol_escape_htmltag($outhtml);
3367 $out .= '">';
3368 $out .= $labeltoshow;
3369 $out .= '</option>';
3370
3371 $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength) . $moreinfo;
3372 $outarray2[$userstatic->id] = array(
3373 'id' => $userstatic->id,
3374 'label' => $labeltoshow,
3375 'labelhtml' => $labeltoshowhtml,
3376 'color' => '',
3377 'picto' => ''
3378 );
3379
3380 $i++;
3381 }
3382 } else {
3383 $out .= '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '" disabled>';
3384 $out .= '<option value="">' . $langs->trans("None") . '</option>';
3385 }
3386 $out .= '</select>';
3387
3388 if ($num && !$forcecombo) {
3389 // Enhance with select2
3390 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
3391 $out .= ajax_combobox($htmlname);
3392 }
3393 } else {
3394 dol_print_error($this->db);
3395 }
3396
3397 $this->num = $num;
3398
3399 if ($outputmode == 2) {
3400 return $outarray2;
3401 } elseif ($outputmode) {
3402 return $outarray;
3403 }
3404
3405 return $out;
3406 }
3407
3408
3409 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3433 public function select_dolusers_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = array(), $enableonly = array(), $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofuserid = array(), $listofcontactid = array(), $listofotherid = array(), $canremoveowner = 1)
3434 {
3435 // phpcs:enable
3436 global $langs, $user;
3437
3438 $userstatic = new User($this->db);
3439 $out = '';
3440
3441 // The list of selected users is provided by the caller through $listofuserid (owner first).
3442 // Fall back to the legacy global $_SESSION['assignedtouser'] only when no list is provided
3443 // (comm/action/card.php now scopes that session bucket per event id and no longer feeds this key).
3444 if (!empty($listofuserid)) {
3445 $assignedtouser = $listofuserid;
3446 } elseif (!empty($_SESSION['assignedtouser'])) {
3447 $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
3448 if (!is_array($assignedtouser)) {
3449 $assignedtouser = array();
3450 }
3451 } else {
3452 $assignedtouser = array();
3453 }
3454 $nbassignetouser = count($assignedtouser);
3455
3456 //if ($nbassignetouser && $action != 'view') $out .= '<br>';
3457 if ($nbassignetouser) {
3458 $out .= '<ul class="attendees">';
3459 }
3460 $i = 0;
3461 $ownerid = 0;
3462 foreach ($assignedtouser as $key => $value) {
3463 if ($value['id'] == $ownerid) {
3464 continue;
3465 }
3466
3467 $out .= '<li>';
3468
3469 $userstatic->fetch($value['id']);
3470 $out .= $userstatic->getNomUrl(-4);
3471
3472 if ($i == 0) {
3473 $ownerid = $value['id'];
3474 $out .= ' (' . $langs->trans("Owner") . ')';
3475 }
3476 // Add picto to delete owner/assignee
3477 if ($nbassignetouser > 1 && $action != 'view') {
3478 $canremoveassignee = 1;
3479 if ($i == 0) {
3480 // We are on the owner of the event
3481 if (!$canremoveowner) {
3482 $canremoveassignee = 0;
3483 }
3484 if (!$user->hasRight('agenda', 'allactions', 'create')) {
3485 $canremoveassignee = 0; // Can't remove the owner
3486 }
3487 } else {
3488 // We are not on the owner of the event but on a secondary assignee
3489 }
3490 if ($canremoveassignee) {
3491 // If user has all permission, he should be ableto remove a assignee.
3492 // If user has not all permission, he can onlyremove assignee of other (he can't remove itself)
3493 $out .= ' <input type="image" style="border: 0px;" src="' . img_picto($langs->trans("Remove"), 'delete', '', 0, 1) . '" value="' . $userstatic->id . '" class="noborderfocus removedassigned reposition" id="removedassigned_' . $userstatic->id . '" name="removedassigned_' . $userstatic->id . '">';
3494 }
3495 }
3496 // Show my availability
3497 if ($showproperties) {
3498 if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
3499 $out .= '<div class="myavailability inline-block">';
3500 $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;';
3501 //$out .= '<span class="opacitymedium">' . $langs->trans("Availability") . ':</span>';
3502 $out .= '</span>';
3503 $out .= ' <input title="'.$langs->trans("Availability").'" id="transparency" class="paddingrightonly" ' . ($action == 'view' ? 'disabled' : '') . ' type="checkbox" name="transparency"' . ($listofuserid[$ownerid]['transparency'] ? ' checked' : '') . '><label for="transparency">' . $langs->trans("Busy") . '</label>';
3504 $out .= '</div>';
3505 }
3506 }
3507 //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
3508 //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
3509
3510 $out .= '</li>';
3511 $i++;
3512 }
3513 if ($nbassignetouser) {
3514 $out .= '</ul>';
3515 }
3516
3517 // Method with no ajax
3518 if ($action != 'view') {
3519 // Section to add another user
3520 $out .= '<div class="divadduser'.$htmlname.'">';
3521 $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
3522 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
3523 $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
3524 $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
3525 $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#' . $action . 'assignedtouser").attr("disabled", false); }';
3526 $out .= ' else { jQuery("#' . $action . 'assignedtouser").attr("disabled", true); }';
3527 $out .= '});';
3528 $out .= '})</script>';
3529 $out .= img_picto('', 'user', 'class="pictofixedwidth"');
3530 // Force a real combo (forcecombo=1): this widget drives the "Add" button from the <option> elements of the
3531 // select, so it must not be replaced by the ajax autocomplete of select_dolusers() (USER_USE_SEARCH_TO_SELECT).
3532 $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter, 0, '', 'minwidth200', 0, 0, false, 1);
3533 // select_dolusers() skips the select2 beautification when forcecombo is set, so re-apply it here.
3534 include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
3535 $out .= ajax_combobox($htmlname);
3536 $out .= ' <button type="submit" disabled class="button valignmiddle smallpaddingimp reposition butActionAdd" id="' . $action . 'assignedtouser" name="' . $action . 'assignedtouser" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
3537 $out .= $langs->trans("Add").'</button>';
3538 $out .= '</div>';
3539 //$out .= '<br>';
3540 }
3541
3542 return $out;
3543 }
3544
3545 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3565 public function select_dolresources_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = array(), $enableonly = array(), $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofresourceid = array())
3566 {
3567 // phpcs:enable
3568 global $langs;
3569
3570 require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php';
3571 require_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php';
3572 $formresources = new FormResource($this->db);
3573 $resourcestatic = new Dolresource($this->db);
3574
3575 $out = '';
3576 // The list of selected resources is provided by the caller through $listofresourceid.
3577 // Fall back to the legacy global $_SESSION['assignedtoresource'] only when no list is provided
3578 // (comm/action/card.php now scopes that session bucket per event id and no longer feeds this key).
3579 if (!empty($listofresourceid)) {
3580 $assignedtoresource = $listofresourceid;
3581 } elseif (!empty($_SESSION['assignedtoresource'])) {
3582 $assignedtoresource = json_decode($_SESSION['assignedtoresource'], true);
3583 if (!is_array($assignedtoresource)) {
3584 $assignedtoresource = array();
3585 }
3586 } else {
3587 $assignedtoresource = array();
3588 }
3589 $nbassignetoresource = count($assignedtoresource);
3590
3591 //if ($nbassignetoresource && $action != 'view') $out .= '<br>';
3592 if ($nbassignetoresource) {
3593 $out .= '<ul class="attendees">';
3594 }
3595 $i = 0;
3596
3597 foreach ($assignedtoresource as $key => $value) {
3598 $out .= '<li>';
3599 $resourcestatic->fetch($value['id']);
3600 $out .= $resourcestatic->getNomUrl(-1);
3601 if ($nbassignetoresource >= 1 && $action != 'view') {
3602 $out .= ' <input type="image" style="border: 0px;" src="' . img_picto($langs->trans("Remove"), 'delete', '', 0, 1) . '" value="' . $resourcestatic->id . '" class="removedassignedresource reposition" id="removedassignedresource_' . $resourcestatic->id . '" name="removedassignedresource_' . $resourcestatic->id . '">';
3603 }
3604 // Show my availability
3605 if ($showproperties) {
3606 if (is_array($listofresourceid) && count($listofresourceid)) {
3607 $out .= '<div class="myavailability inline-block">';
3608 $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;';
3609 //$out .= '<span class="opacitymedium">' . $langs->trans("Availability") . ': </span>';
3610 $out .= '</span>';
3611 $out .= ' <input title="'.$langs->trans("Availability").'" id="transparencyresource'.$value['id'].'" class="paddingrightonly" ' . ($action == 'view' ? 'disabled' : '') . ' type="checkbox" name="transparency"' . (!empty($listofresourceid[$value['id']]['transparency']) ? ' checked' : '') . '><label for="transparencyresource'.$value['id'].'">' . $langs->trans("Busy") . '</label>';
3612 $out .= '</div>';
3613 }
3614 }
3615 //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
3616 //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
3617
3618 $out .= '</li>';
3619 $i++;
3620 }
3621 if ($nbassignetoresource) {
3622 $out .= '</ul>';
3623 }
3624
3625 // Method with no ajax
3626 if ($action != 'view') {
3627 $out .= '<input type="hidden" class="removedassignedresourcehidden" name="removedassignedresource" value="">';
3628 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
3629 $out .= 'jQuery(".removedassignedresource").click(function() { jQuery(".removedassignedresourcehidden").val(jQuery(this).val()); });';
3630 $out .= 'jQuery(".assignedtoresource").change(function() { console.log(jQuery(".assignedtoresource option:selected").val());';
3631 $out .= ' if (jQuery(".assignedtoresource option:selected").val() > 0) { jQuery("#' . $action . 'assignedtoresource").attr("disabled", false); }';
3632 $out .= ' else { jQuery("#' . $action . 'assignedtoresource").attr("disabled", true); }';
3633 $out .= '});';
3634 $out .= '})</script>';
3635
3636 $events = array();
3637 if ($nbassignetoresource) {
3638 //$out .= img_picto('', 'add', 'class="pictofixedwidth"');
3639 } else {
3640 $out .= img_picto('', 'resource', 'class="pictofixedwidth"');
3641 }
3642 $out .= $formresources->select_resource_list(0, $htmlname, '', 1, 1, 0, $events, '', 2, 0, 'minwidth200');
3643 //$out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
3644 $out .= ' <button type="submit" disabled class="button valignmiddle smallpaddingimp reposition butActionAdd" id="' . $action . 'assignedtoresource" name="' . $action . 'assignedtoresource" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
3645 $out .= $langs->trans("Add");
3646 $out .= '</button>';
3647 $out .= '<br>';
3648 }
3649
3650 return $out;
3651 }
3652
3653 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3654
3684 public function select_produits($selected = 0, $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, $warehouseId = 0)
3685 {
3686 // phpcs:enable
3687 global $langs, $conf;
3688
3689 $out = '';
3690
3691 // check parameters
3692 $price_level = (!empty($price_level) ? $price_level : 0);
3693 if (is_null($ajaxoptions)) {
3694 $ajaxoptions = array();
3695 }
3696
3697 if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
3698 if (isModEnabled("product") && !isModEnabled('service')) {
3699 $filtertype = '0';
3700 } elseif (!isModEnabled('product') && isModEnabled("service")) {
3701 $filtertype = '1';
3702 }
3703 }
3704
3705 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
3706 $placeholder = (is_numeric($showempty) ? '' : 'placeholder="'.dolPrintHTML($showempty).'"');
3707
3708 if ($selected && empty($selected_input_value)) {
3709 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
3710 $producttmpselect = new Product($this->db);
3711 $producttmpselect->fetch($selected);
3712 $selected_input_value = $producttmpselect->ref;
3713 unset($producttmpselect);
3714 }
3715 // handle case where product or service module is disabled + no filter specified
3716 if ($filtertype == '') {
3717 if (!isModEnabled('product')) { // when product module is disabled, show services only
3718 $filtertype = 1;
3719 } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
3720 $filtertype = 0;
3721 }
3722 }
3723 // mode=1 means customers products
3724 $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=1&status=' . $status . '&status_purchase=' . $status_purchase . '&finished=' . $finished . '&hidepriceinlabel=' . $hidepriceinlabel . '&warehousestatus=' . $warehouseStatus;
3725 if ((int) $warehouseId > 0) {
3726 $urloption .= '&warehouseid=' . (int) $warehouseId;
3727 }
3728
3729 if (isModEnabled('variants') && is_array($selected_combinations)) {
3730 // Code to automatically insert with javascript the select of attributes under the select of product
3731 // when a parent of variant has been selected.
3732 // Note: Samecode than for product input using select
3733 $htmltag = 'input';
3734 $out .= '
3735 <!-- script to auto show attributes select tags if a variant was selected -->
3736 <script nonce="' . getNonce() . '">
3737 // auto show attributes fields
3738 selected = ' . json_encode($selected_combinations) . ';
3739 combvalues = {};
3740
3741 jQuery(document).ready(function () {
3742
3743 jQuery("input[name=\'prod_entry_mode\']").change(function () {
3744 if (jQuery(this).val() == \'free\') {
3745 jQuery(\'div#attributes_box\').empty();
3746 }
3747 });
3748
3749 jQuery("'.$htmltag.'#' . $htmlname . '").change(function () {
3750
3751 if (!jQuery(this).val()) {
3752 jQuery(\'div#attributes_box\').empty();
3753 return;
3754 }
3755
3756 console.log("A change has started. We get variants fields to inject html select");
3757
3758 jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
3759 id: jQuery(this).val()
3760 }, function (data) {
3761 jQuery(\'div#attributes_box\').empty();
3762
3763 jQuery.each(data, function (key, val) {
3764
3765 combvalues[val.id] = val.values;
3766
3767 var span = jQuery(document.createElement(\'div\')).css({
3768 \'display\': \'table-row\'
3769 });
3770
3771 span.append(
3772 jQuery(document.createElement(\'div\')).text(val.label).css({
3773 \'font-weight\': \'bold\',
3774 \'display\': \'table-cell\'
3775 })
3776 );
3777
3778 var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
3779 \'margin-left\': \'15px\',
3780 \'white-space\': \'pre\'
3781 }).append(
3782 jQuery(document.createElement(\'option\')).val(\'\')
3783 );
3784
3785 jQuery.each(combvalues[val.id], function (key, val) {
3786 var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
3787
3788 if (selected[val.fk_product_attribute] == val.id) {
3789 tag.attr(\'selected\', \'selected\');
3790 }
3791
3792 html.append(tag);
3793 });
3794
3795 span.append(html);
3796 jQuery(\'div#attributes_box\').append(span);
3797 });
3798 })
3799 });
3800
3801 ' . ($selected ? 'jQuery("'.$htmltag.'#' . $htmlname . '").change();' : '') . '
3802 });
3803 </script>
3804 ';
3805 }
3806
3807 if (empty($hidelabel)) {
3808 $placeholder = ' placeholder="' . dolPrintHTMLForAttribute($langs->trans("RefOrLabel")) . '"';
3809 } elseif ($hidelabel > 1) {
3810 $placeholder = ' placeholder="' . dolPrintHTMLForAttribute($langs->trans("RefOrLabel")) . '"';
3811 if ($hidelabel == 2) {
3812 $out .= img_picto($langs->trans("Search"), 'search');
3813 }
3814 }
3815
3816 $out .= '<input type="text" class="minwidth100' . ($morecss ? ' ' . $morecss : '') . '" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' spellcheck="false" />';
3817 if ($hidelabel == 3) {
3818 $out .= img_picto($langs->trans("Search"), 'search');
3819 }
3820
3821 $out .= ajax_autocompleter((string) $selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, getDolGlobalInt('PRODUIT_USE_SEARCH_TO_SELECT'), getDolGlobalInt('PRODUCT_SEARCH_AUTO_SELECT_IF_ONLY_ONE', 1), $ajaxoptions);
3822 } else {
3823 $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase, $warehouseId);
3824
3825 if (isModEnabled('variants') && is_array($selected_combinations)) {
3826 // Code to automatically insert with javascript the select of attributes under the select of product
3827 // when a parent of variant has been selected.
3828 // Note: Samecode than for product input using Ajax
3829 $htmltag = 'select';
3830 $out .= '
3831 <!-- script to auto show attributes select tags if a variant was selected -->
3832 <script nonce="' . getNonce() . '">
3833 // auto show attributes fields
3834 selected = ' . json_encode($selected_combinations) . ';
3835 combvalues = {};
3836
3837 jQuery(document).ready(function () {
3838
3839 jQuery("input[name=\'prod_entry_mode\']").change(function () {
3840 if (jQuery(this).val() == \'free\') {
3841 jQuery(\'div#attributes_box\').empty();
3842 }
3843 });
3844
3845 jQuery("'.$htmltag.'#' . $htmlname . '").change(function () {
3846
3847 if (!jQuery(this).val()) {
3848 jQuery(\'div#attributes_box\').empty();
3849 return;
3850 }
3851
3852 console.log("A change has started. We get variants fields to inject html select");
3853
3854 jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
3855 id: jQuery(this).val()
3856 }, function (data) {
3857 jQuery(\'div#attributes_box\').empty();
3858
3859 jQuery.each(data, function (key, val) {
3860
3861 combvalues[val.id] = val.values;
3862
3863 var span = jQuery(document.createElement(\'div\')).css({
3864 \'display\': \'table-row\'
3865 });
3866
3867 span.append(
3868 jQuery(document.createElement(\'div\')).text(val.label).css({
3869 \'font-weight\': \'bold\',
3870 \'display\': \'table-cell\'
3871 })
3872 );
3873
3874 var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
3875 \'margin-left\': \'15px\',
3876 \'white-space\': \'pre\'
3877 }).append(
3878 jQuery(document.createElement(\'option\')).val(\'\')
3879 );
3880
3881 jQuery.each(combvalues[val.id], function (key, val) {
3882 var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
3883
3884 if (selected[val.fk_product_attribute] == val.id) {
3885 tag.attr(\'selected\', \'selected\');
3886 }
3887
3888 html.append(tag);
3889 });
3890
3891 span.append(html);
3892 jQuery(\'div#attributes_box\').append(span);
3893 });
3894 })
3895 });
3896
3897 ' . ($selected ? 'jQuery("'.$htmltag.'#' . $htmlname . '").change();' : '') . '
3898 });
3899 </script>
3900 ';
3901 }
3902 }
3903
3904 if (empty($nooutput)) {
3905 print $out;
3906 } else {
3907 return $out;
3908 }
3909 }
3910
3911 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3912
3928 public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
3929 {
3930 // phpcs:enable
3931
3932 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
3933
3934 $error = 0;
3935 $out = '';
3936
3937 if (!$forcecombo) {
3938 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
3939 $events = array();
3940 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("BOM_USE_SEARCH_TO_SELECT"));
3941 }
3942
3943 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
3944
3945 $sql = 'SELECT b.rowid, b.ref, b.label as bomLabel, p.label as productLabel';
3946 $sql .= ' FROM ' . $this->db->prefix() . 'bom_bom as b';
3947 $sql .= ' INNER JOIN ' . $this->db->prefix() . 'product as p ON b.fk_product = p.rowid';
3948 $sql .= ' WHERE b.entity IN (' . getEntity('bom') . ')';
3949 if (!empty($status)) {
3950 $sql .= ' AND status = ' . (int) $status;
3951 }
3952 if (!empty($type)) {
3953 $sql .= ' AND bomtype = ' . (int) $type;
3954 }
3955 if (!empty($TProducts)) {
3956 $sql .= ' AND fk_product IN (' . $this->db->sanitize(implode(',', $TProducts)) . ')';
3957 }
3958 if (!empty($limit)) {
3959 $sql .= ' LIMIT ' . (int) $limit;
3960 }
3961 $resql = $this->db->query($sql);
3962 if ($resql) {
3963 if ($showempty) {
3964 $out .= '<option value="-1"';
3965 if (empty($selected)) {
3966 $out .= ' selected';
3967 }
3968 $out .= '>&nbsp;</option>';
3969 }
3970 while ($obj = $this->db->fetch_object($resql)) {
3971 $out .= '<option value="' . $obj->rowid . '"';
3972 if ($obj->rowid == $selected) {
3973 $out .= 'selected';
3974 }
3975 $out .= '>' . $obj->ref . ' - ' . $obj->productLabel . ' - ' . $obj->bomLabel . '</option>';
3976 }
3977 } else {
3978 $error++;
3979 dol_print_error($this->db);
3980 }
3981 $out .= '</select>';
3982 if (empty($nooutput)) {
3983 print $out;
3984 } else {
3985 return $out;
3986 }
3987 }
3988
3989 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3990
4017 public function select_produits_list($selected = 0, $htmlname = 'productid', $filtertype = '', $limit = 1000, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = 'maxwidth500', $hidepriceinlabel = 0, $warehouseStatus = '', $status_purchase = -1, $warehouseId = 0)
4018 {
4019 // phpcs:enable
4020 global $langs;
4021 global $hookmanager;
4022
4023 $out = '';
4024 $outarray = array();
4025
4026 // Units
4027 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4028 $langs->load('other');
4029 }
4030
4031 $warehouseStatusArray = array();
4032 if (!empty($warehouseStatus)) {
4033 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
4034 if (preg_match('/warehouseclosed/', $warehouseStatus)) {
4035 $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
4036 }
4037 if (preg_match('/warehouseopen/', $warehouseStatus)) {
4038 $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
4039 }
4040 if (preg_match('/warehouseinternal/', $warehouseStatus)) {
4041 $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
4042 }
4043 }
4044
4045 $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";
4046 if (count($warehouseStatusArray)) {
4047 $selectFieldsGrouped = ", SUM(" . $this->db->ifsql("e.statut IS NULL", "0", "ps.reel") . ") as stock"; // e.statut is null if there is no record in a qualified stock
4048 } else {
4049 $selectFieldsGrouped = ", " . $this->db->ifsql("p.stock IS NULL", '0', "p.stock") . " AS stock";
4050 }
4051
4052 $sql = "SELECT ";
4053
4054 // Add select from hooks
4055 $parameters = array();
4056 $reshook = $hookmanager->executeHooks('selectProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
4057 if (empty($reshook)) {
4058 $sql .= $selectFields.$selectFieldsGrouped.$hookmanager->resPrint;
4059 } else {
4060 $sql .= $hookmanager->resPrint;
4061 }
4062
4063 if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
4064 // Take randomly the first category of product to allow a sort on it. Bugged feature !
4065 $sql .= ", (SELECT " . $this->db->prefix() . "categorie_product.fk_categorie
4066 FROM " . $this->db->prefix() . "categorie_product
4067 WHERE " . $this->db->prefix() . "categorie_product.fk_product = p.rowid
4068 LIMIT 1
4069 ) AS categorie_product_id";
4070 }
4071
4072 // Price by customer
4073 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
4074 $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
4075 $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, pcp.discount_percent as custdiscount_percent';
4076 $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref, custdiscount_percent";
4077 }
4078 // Units
4079 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4080 $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";
4081 $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';
4082 }
4083
4084 // Multilang : we add translation
4085 if (getDolGlobalInt('MAIN_MULTILANGS')) {
4086 $sql .= ", pl.label as label_translated";
4087 $sql .= ", pl.description as description_translated";
4088 $selectFields .= ", label_translated";
4089 $selectFields .= ", description_translated";
4090 }
4091 // Price by quantity
4092 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
4093 $sql .= ", (SELECT pp.rowid FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid";
4094 if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
4095 $sql .= " AND price_level = " . ((int) $price_level);
4096 }
4097 $sql .= " ORDER BY date_price";
4098 $sql .= " DESC LIMIT 1) as price_rowid";
4099 $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
4100 if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
4101 $sql .= " AND price_level = " . ((int) $price_level);
4102 }
4103 $sql .= " ORDER BY date_price";
4104 $sql .= " DESC LIMIT 1) as price_by_qty";
4105 $selectFields .= ", price_rowid, price_by_qty";
4106 }
4107
4108 //$sqlfields = $sql; // $sql fields to remove for count total
4109
4110 $sql .= " FROM ".$this->db->prefix()."product as p";
4111
4112 if (getDolGlobalString('MAIN_SEARCH_PRODUCT_FORCE_INDEX')) {
4113 $sql .= " USE INDEX (" . $this->db->sanitize(getDolGlobalString('MAIN_PRODUCT_FORCE_INDEX')) . ")";
4114 }
4115
4116 // Add from (left join) from hooks
4117 $parameters = array(
4118 'socid' => $socid,
4119 );
4120 $reshook = $hookmanager->executeHooks('selectProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
4121 $sql .= $hookmanager->resPrint;
4122
4123 if (count($warehouseStatusArray)) {
4124 // Return line if product is inside the selected stock. If not, e.* and p.* will be null so we will count 0.
4125 // Replace this with a AND EXISTS ? Not possible as we need the ps.reel field for the SUM or 0 if no link.
4126 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as ps ON ps.fk_product = p.rowid";
4127 $sql .= " LEFT JOIN " . $this->db->prefix() . "entrepot as e ON ps.fk_entrepot = e.rowid AND e.entity IN (" . getEntity('stock') . ")";
4128 $sql .= ' AND e.statut IN (' . $this->db->sanitize($this->db->escape(implode(',', $warehouseStatusArray))) . ')';
4129 }
4130
4131 // Price by customer (Add field pcp for the older price for couple product/thirdparty.
4132 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
4133 $now = dol_now();
4134 $sql .= " LEFT JOIN (";
4135 $sql .= " SELECT pcp1.*";
4136 $sql .= " FROM " . $this->db->prefix() . "product_customer_price AS pcp1";
4137 $sql .= " LEFT JOIN (";
4138 $sql .= " SELECT fk_soc, fk_product, MIN(date_begin) AS date_begin";
4139 $sql .= " FROM " . $this->db->prefix() . "product_customer_price";
4140 $sql .= " WHERE fk_soc = " . ((int) $socid);
4141 $sql .= " AND date_begin <= '" . $this->db->idate($now) . "'";
4142 $sql .= " AND (date_end IS NULL OR '" . $this->db->idate($now) . "' <= date_end)";
4143 $sql .= " GROUP BY fk_soc, fk_product";
4144 $sql .= " ) AS pcp2 ON pcp1.fk_soc = pcp2.fk_soc AND pcp1.fk_product = pcp2.fk_product AND pcp1.date_begin = pcp2.date_begin";
4145 $sql .= " WHERE pcp2.fk_soc IS NOT NULL";
4146 $sql .= " ) AS pcp ON pcp.fk_soc = " . ((int) $socid) . " AND pcp.fk_product = p.rowid";
4147 }
4148 // Units : we add unit properties with a link on the primary key of unit
4149 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4150 $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units as u ON u.rowid = p.fk_unit";
4151 }
4152 // Multilang : we add translation fields with a link on unique key fk_product/lang.
4153 if (getDolGlobalInt('MAIN_MULTILANGS')) {
4154 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_lang as pl ON pl.fk_product = p.rowid";
4155 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && !empty($socid)) {
4156 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
4157 $soc = new Societe($this->db);
4158 $result = $soc->fetch($socid);
4159 if ($result > 0 && !empty($soc->default_lang)) {
4160 $sql .= " AND pl.lang = '" . $this->db->escape($soc->default_lang) . "'";
4161 } else {
4162 $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
4163 }
4164 } else {
4165 $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
4166 }
4167 }
4168
4169 // Add WHERE conditions
4170 $sql .= ' WHERE p.entity IN (' . getEntity('product') . ')';
4171 if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD')) {
4172 if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD_BUT_ALLOW_SEARCH_IN_EAN13')) {
4173 if (strlen($filterkey) != 13) {
4174 $sql .= " AND NOT EXISTS (SELECT pac.rowid FROM ".$this->db->prefix()."product_attribute_combination as pac WHERE pac.fk_product_child = p.rowid)";
4175 }
4176 } else {
4177 $sql .= " AND NOT EXISTS (SELECT pac.rowid FROM ".$this->db->prefix()."product_attribute_combination as pac WHERE pac.fk_product_child = p.rowid)";
4178 }
4179 }
4180 if ($finished == 0) {
4181 $sql .= " AND p.finished = " . ((int) $finished);
4182 } elseif ($finished == 1) {
4183 $sql .= " AND p.finished = ".((int) $finished);
4184 }
4185 if ($status >= 0) {
4186 $sql .= " AND p.tosell = ".((int) $status);
4187 }
4188 if ($status_purchase >= 0) {
4189 $sql .= " AND p.tobuy = " . ((int) $status_purchase);
4190 }
4191 // Filter by product type
4192 if (strval($filtertype) != '') {
4193 $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
4194 } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
4195 $sql .= " AND p.fk_product_type = 1";
4196 } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
4197 $sql .= " AND p.fk_product_type = 0";
4198 }
4199
4200 if ((int) $warehouseId > 0) {
4201 $sql .= " AND EXISTS (SELECT psw.fk_product FROM " . $this->db->prefix() . "product_stock as psw WHERE psw.reel > 0 AND psw.fk_entrepot = ".(int) $warehouseId." AND psw.fk_product = p.rowid)";
4202 }
4203
4204 // Add where from hooks
4205 $parameters = array(
4206 'filterkey' => &$filterkey,
4207 'socid' => $socid,
4208 );
4209 $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
4210 $sql .= $hookmanager->resPrint;
4211 // Add criteria on ref/label
4212 if ($filterkey != '') {
4213 $sqlSupplierSearch = '';
4214
4215 $sql .= ' AND (';
4216 $prefix = getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
4217 // For natural search
4218 $search_crit = explode(' ', $filterkey);
4219 $i = 0;
4220 if (count($search_crit) > 1) {
4221 $sql .= "(";
4222 }
4223 foreach ($search_crit as $crit) {
4224 if ($i > 0) {
4225 $sql .= " AND ";
4226 }
4227 $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
4228 if (getDolGlobalInt('MAIN_MULTILANGS')) {
4229 $sql .= " OR pl.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
4230 }
4231 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
4232 $sql .= " OR pcp.ref_customer LIKE '" . $this->db->escape($prefix . $crit) . "%'";
4233 }
4234 if (getDolGlobalString('PRODUCT_AJAX_SEARCH_ON_DESCRIPTION')) {
4235 $sql .= " OR p.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
4236 if (getDolGlobalInt('MAIN_MULTILANGS')) {
4237 $sql .= " OR pl.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
4238 }
4239 }
4240
4241 // include search in supplier ref
4242 if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF')) {
4243 $sqlSupplierSearch .= !empty($sqlSupplierSearch) ? ' AND ' : '';
4244 $sqlSupplierSearch .= " pfp.ref_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
4245 }
4246 $sql .= ")";
4247 $i++;
4248 }
4249 if (count($search_crit) > 1) {
4250 $sql .= ")";
4251 }
4252 if (isModEnabled('barcode')) {
4253 $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
4254 }
4255
4256 // include search in supplier ref
4257 if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF')) {
4258 $sql .= " OR EXISTS (SELECT pfp.fk_product FROM " . $this->db->prefix() . "product_fournisseur_price as pfp WHERE p.rowid = pfp.fk_product";
4259 $sql .= " AND ((";
4260 $sql .= $sqlSupplierSearch;
4261 $sql .= ")";
4262 if (isModEnabled('barcode')) {
4263 $sql .= " OR pfp.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
4264 }
4265 $sql .= "))";
4266 }
4267
4268 $sql .= ')';
4269 }
4270 if (count($warehouseStatusArray)) {
4271 $sql .= " GROUP BY " . $this->db->sanitize($selectFields, 0, 0, 1); // To have the SUM on ps.reel working in the select.
4272 }
4273
4274 // Sort by category
4275 // The preselected product is put first so it is not cut by the limit (for example a product just created with the + button of the line form)
4276 if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
4277 $sql .= " ORDER BY".((int) $selected > 0 ? " CASE WHEN p.rowid = ".((int) $selected)." THEN 0 ELSE 1 END," : "")." categorie_product_id ".(getDolGlobalInt('PRODUCT_SORT_BY_CATEGORY') == 1 ? "ASC" : "DESC");
4278 } elseif ((int) $selected > 0) {
4279 $sql .= " ORDER BY CASE WHEN p.rowid = ".((int) $selected)." THEN 0 ELSE 1 END, p.ref ASC";
4280 } else {
4281 $sql .= $this->db->order("p.ref");
4282 }
4283
4284 $limit = getDolGlobalInt('SEARCH_LIMIT_AJAX') ?: $limit; // SEARCH_LIMIT_AJAX is a hidden option that has priority on visible option PRODUIT_LIMIT_SIZE if set.
4285 $sql .= $this->db->plimit($limit, 0);
4286
4287 /* The fast and low memory method to get and count full list converts the sql into a sql count */
4288 /*
4289 $nbtotalofrecords = 0;
4290 $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
4291 $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
4292
4293 $resql = $this->db->query($sqlforcount);
4294 if ($resql) {
4295 $objforcount = $this->db->fetch_object($resql);
4296 $nbtotalofrecords = $objforcount->nbtotalofrecords;
4297 } else {
4298 dol_print_error($this->db);
4299 }
4300 */
4301
4302 // Build output string
4303 dol_syslog(get_class($this) . "::select_produits_list search products", LOG_DEBUG);
4304
4305 // If we have no $limit parameter, this request may hang dur to high number of lines returned.
4306 // This should not happen because this method should not be called directly, iIt is called by select_produit() that always add a $limit parameter.
4307 $result = $this->db->query($sql);
4308
4309 if ($result) {
4310 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
4311 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
4312 require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
4313
4314 $num = $this->db->num_rows($result);
4315
4316 $events = array();
4317
4318 if (!$forcecombo) {
4319 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4320 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
4321 }
4322
4323 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
4324
4325 $textifempty = '';
4326 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
4327 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
4328 if (getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
4329 if ($showempty && !is_numeric($showempty)) {
4330 $textifempty = $langs->trans($showempty);
4331 } else {
4332 $textifempty .= $langs->trans("All");
4333 }
4334 } else {
4335 if ($showempty && !is_numeric($showempty)) {
4336 $textifempty = $langs->trans($showempty);
4337 }
4338 }
4339 if ($showempty) {
4340 $out .= '<option value="-1" selected>' . ($textifempty ? $textifempty : '&nbsp;') . '</option>';
4341 }
4342
4343 $i = 0;
4344 while ($num && $i < $num) {
4345 $opt = '';
4346 $optJson = array();
4347 $objp = $this->db->fetch_object($result);
4348
4349 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('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
4350 $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
4351 $sql .= " FROM " . $this->db->prefix() . "product_price_by_qty";
4352 $sql .= " WHERE fk_product_price = " . ((int) $objp->price_rowid);
4353 $sql .= " ORDER BY quantity ASC";
4354
4355 dol_syslog(get_class($this) . "::select_produits_list search prices by qty", LOG_DEBUG);
4356 $result2 = $this->db->query($sql);
4357 if ($result2) {
4358 $nb_prices = $this->db->num_rows($result2);
4359 $j = 0;
4360 while ($nb_prices && $j < $nb_prices) {
4361 $objp2 = $this->db->fetch_object($result2);
4362
4363 $objp->price_by_qty_rowid = $objp2->rowid;
4364 $objp->price_by_qty_price_base_type = $objp2->price_base_type;
4365 $objp->price_by_qty_quantity = $objp2->quantity;
4366 $objp->price_by_qty_unitprice = $objp2->unitprice;
4367 $objp->price_by_qty_remise_percent = $objp2->remise_percent;
4368 // For backward compatibility
4369 $objp->quantity = $objp2->quantity;
4370 $objp->price = $objp2->price;
4371 $objp->unitprice = $objp2->unitprice;
4372 $objp->remise_percent = $objp2->remise_percent;
4373
4374 //$objp->tva_tx is not overwritten by $objp2 value
4375 //$objp->default_vat_code is not overwritten by $objp2 value
4376
4377 $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
4378 '@phan-var-force array{key:string,value:string,label:string,label2:string,desc:string,type:string,price_ht:string,price_ttc:string,price_ht_locale:string,price_ttc_locale:string,pricebasetype:string,tva_tx:string,default_vat_code:string,qty:string,discount:string,duration_value:string,duration_unit:string,pbq:string,labeltrans:string,desctrans:string,ref_customer:string} $optJson';
4379 $j++;
4380
4381 // Add new entry
4382 // "key" value of json key array is used by jQuery automatically as selected value
4383 // "label" value of json key array is used by jQuery automatically as text for combo box
4384 $out .= $opt;
4385 array_push($outarray, $optJson);
4386 }
4387 }
4388 } else {
4389 if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
4390 $price_product = new Product($this->db);
4391 $price_product->fetch($objp->rowid, '', '', '1');
4392
4393 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
4394 $priceparser = new PriceParser($this->db);
4395 $price_result = $priceparser->parseProduct($price_product);
4396 if ($price_result >= 0) {
4397 $objp->price = $price_result;
4398 $objp->unitprice = $price_result;
4399 //Calculate the VAT
4400 $objp->price_ttc = (float) price2num($objp->price) * (1 + ($objp->tva_tx / 100));
4401 $objp->price_ttc = price2num($objp->price_ttc, 'MU');
4402 }
4403 }
4404 if (getDolGlobalInt('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES') && !empty($objp->custprice)) {
4405 $price_level = '';
4406 }
4407 $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
4408 // Add new entry
4409 // "key" value of json key array is used by jQuery automatically as selected value
4410 // "label" value of json key array is used by jQuery automatically as text for combo box
4411 $out .= $opt;
4412 array_push($outarray, $optJson);
4413 }
4414
4415 $i++;
4416 }
4417
4418 $out .= '</select>';
4419
4420 $this->db->free($result);
4421
4422 if (empty($outputmode)) {
4423 return $out;
4424 }
4425
4426 return $outarray;
4427 } else {
4428 dol_print_error($this->db);
4429 }
4430
4431 return '';
4432 }
4433
4449 protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
4450 {
4451 global $langs, $conf, $user;
4452 global $hookmanager;
4453
4454 $outkey = '';
4455 $outval = '';
4456 $outref = '';
4457 $outlabel = '';
4458 $outlabel_translated = '';
4459 $outdesc = '';
4460 $outdesc_translated = '';
4461 $outbarcode = '';
4462 $outorigin = '';
4463 $outtype = '';
4464 $outprice_ht = '';
4465 $outprice_ttc = '';
4466 $outpricebasetype = '';
4467 $outtva_tx = '';
4468 $outdefault_vat_code = '';
4469 $outqty = 1;
4470 $outdiscount = '0';
4471
4472 $maxlengtharticle = getDolGlobalInt('PRODUCT_MAX_LENGTH_COMBO', 48);
4473
4474 $productlabel = $objp->label;
4475 if (!empty($objp->label_translated)) {
4476 $productlabel = $objp->label_translated;
4477 }
4478 $label = $productlabel;
4479 if (!empty($filterkey) && $filterkey != '') {
4480 $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
4481 }
4482
4483 $outkey = $objp->rowid;
4484 $outref = $objp->ref;
4485 $outrefcust = empty($objp->custref) ? '' : $objp->custref;
4486 $outlabel = $objp->label;
4487 $outdesc = $objp->description;
4488 if (getDolGlobalInt('MAIN_MULTILANGS')) {
4489 $outlabel_translated = $objp->label_translated;
4490 $outdesc_translated = $objp->description_translated;
4491 }
4492 $outbarcode = $objp->barcode;
4493 $outorigin = $objp->fk_country;
4494 $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
4495
4496 $outtype = $objp->fk_product_type;
4497 $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
4498 $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
4499
4500 if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
4501 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
4502 }
4503
4504 // Units
4505 $outvalUnits = '';
4506 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4507 if (!empty($objp->unit_short)) {
4508 $outvalUnits .= ' - ' . $objp->unit_short;
4509 }
4510 }
4511 if (getDolGlobalString('PRODUCT_SHOW_DIMENSIONS_IN_COMBO')) {
4512 if (!empty($objp->weight) && $objp->weight_units !== null) {
4513 $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
4514 $outvalUnits .= ' - ' . $unitToShow;
4515 }
4516 if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
4517 $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
4518 $outvalUnits .= ' - ' . $unitToShow;
4519 }
4520 if (!empty($objp->surface) && $objp->surface_units !== null) {
4521 $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
4522 $outvalUnits .= ' - ' . $unitToShow;
4523 }
4524 if (!empty($objp->volume) && $objp->volume_units !== null) {
4525 $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
4526 $outvalUnits .= ' - ' . $unitToShow;
4527 }
4528 }
4529 if ($outdurationvalue && $outdurationunit) {
4530 $da = array(
4531 'h' => $langs->trans('Hour'),
4532 'd' => $langs->trans('Day'),
4533 'w' => $langs->trans('Week'),
4534 'm' => $langs->trans('Month'),
4535 'y' => $langs->trans('Year')
4536 );
4537 if (isset($da[$outdurationunit])) {
4538 $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
4539 }
4540 }
4541
4542 // Set stocktag (stock too low or not or unknown)
4543 $stocktag = 0;
4544 if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
4545 if ($user->hasRight('stock', 'lire')) {
4546 if ($objp->stock > 0) {
4547 $stocktag = 1;
4548 } elseif ($objp->stock <= 0) {
4549 $stocktag = -1;
4550 }
4551 }
4552 }
4553
4554 // Set full plain label for the native <option> text. Select2 uses this text
4555 // as its search corpus, while data-html below keeps the visible label short.
4556 $labeltosearch = '';
4557 $labeltosearch .= $objp->ref;
4558 if (!empty($objp->custref)) {
4559 $labeltosearch .= ' (' . $objp->custref . ')';
4560 }
4561 if ($outbarcode) {
4562 $labeltosearch .= ' (' . $outbarcode . ')';
4563 }
4564 $labeltosearch .= ' - ' . $productlabel;
4565 if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
4566 $labeltosearch .= ' (' . getCountry($outorigin, '1') . ')';
4567 }
4568
4569 // Set $labltoshowhtml
4570 $labeltoshowhtml = '';
4571 $labeltoshowhtml .= $objp->ref;
4572 if (!empty($objp->custref)) {
4573 $labeltoshowhtml .= ' (' . $objp->custref . ')';
4574 }
4575 if (!empty($filterkey) && $filterkey != '') {
4576 $labeltoshowhtml = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $labeltoshowhtml, 1);
4577 }
4578 if ($outbarcode) {
4579 $labeltoshowhtml .= ' (' . $outbarcode . ')';
4580 }
4581 $labeltoshowhtml .= ' - ' . dol_trunc($label, $maxlengtharticle);
4582 if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
4583 $labeltoshowhtml .= ' (' . getCountry($outorigin, '1') . ')';
4584 }
4585
4586 // Stock
4587 $labeltoshowstock = '';
4588 $labeltoshowhtmlstock = '';
4589 if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
4590 if ($user->hasRight('stock', 'lire')) {
4591 $labeltoshowstock .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
4592
4593 if ($objp->stock > 0) {
4594 $labeltoshowhtmlstock .= ' - <span class="product_line_stock_ok">';
4595 } elseif ($objp->stock <= 0) {
4596 $labeltoshowhtmlstock .= ' - <span class="product_line_stock_too_low">';
4597 }
4598 $labeltoshowhtmlstock .= $langs->transnoentities("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
4599 $labeltoshowhtmlstock .= '</span>';
4600
4601 if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
4602 $langs->load("stocks");
4603
4604 $tmpproduct = new Product($this->db);
4605 $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
4606 $tmpproduct->load_virtual_stock();
4607 $virtualstock = $tmpproduct->stock_theorique;
4608
4609 $labeltoshowstock .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
4610
4611 $labeltoshowhtmlstock .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
4612 if ($virtualstock > 0) {
4613 $labeltoshowhtmlstock .= '<span class="product_line_stock_ok">';
4614 } elseif ($virtualstock <= 0) {
4615 $labeltoshowhtmlstock .= '<span class="product_line_stock_too_low">';
4616 }
4617 $labeltoshowhtmlstock .= $virtualstock;
4618 $labeltoshowhtmlstock .= '</span>';
4619
4620 unset($tmpproduct);
4621 }
4622 }
4623 }
4624
4625 // Price
4626 $found = 0;
4627 $labeltoshowprice = '';
4628 $labeltoshowhtmlprice = '';
4629 // If we need a particular price level (from 1 to n)
4630 if (empty($hidepriceinlabel) && $price_level >= 1 && (getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'))) {
4631 $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
4632 $sql .= " FROM " . $this->db->prefix() . "product_price";
4633 $sql .= " WHERE fk_product = " . ((int) $objp->rowid);
4634 $sql .= " AND entity IN (" . getEntity('productprice') . ")";
4635 $sql .= " AND price_level = " . ((int) $price_level);
4636 $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
4637 $sql .= " LIMIT 1";
4638
4639 dol_syslog(get_class($this) . '::constructProductListOption search price for product ' . $objp->rowid . ' AND level ' . $price_level, LOG_DEBUG);
4640 $result2 = $this->db->query($sql);
4641 if ($result2) {
4642 $objp2 = $this->db->fetch_object($result2);
4643 if ($objp2) {
4644 $found = 1;
4645 if ($objp2->price_base_type == 'HT') {
4646 $labeltoshowprice .= ' - ' . price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
4647 $labeltoshowhtmlprice .= ' - ' . price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
4648 } else {
4649 $labeltoshowprice .= ' - ' . price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
4650 $labeltoshowhtmlprice .= ' - ' . price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
4651 }
4652 $outprice_ht = price($objp2->price);
4653 $outprice_ttc = price($objp2->price_ttc);
4654 $outpricebasetype = $objp2->price_base_type;
4655 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
4656 $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
4657 $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
4658 } else {
4659 $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
4660 $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
4661 }
4662 }
4663 } else {
4664 dol_print_error($this->db);
4665 }
4666 }
4667
4668 // Price by quantity
4669 if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'))) {
4670 $found = 1;
4671 $outqty = $objp->quantity;
4672 $outdiscount = $objp->remise_percent;
4673 if ($objp->quantity == 1) {
4674 $labeltoshowprice .= ' - ' . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/";
4675 $labeltoshowhtmlprice .= ' - ' . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/";
4676 $labeltoshowprice .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
4677 $labeltoshowhtmlprice .= $langs->transnoentities("Unit");
4678 } else {
4679 $labeltoshowprice .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
4680 $labeltoshowhtmlprice .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
4681 $labeltoshowprice .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
4682 $labeltoshowhtmlprice .= $langs->transnoentities("Units");
4683 }
4684
4685 $outprice_ht = price($objp->unitprice);
4686 $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
4687 $outpricebasetype = $objp->price_base_type;
4688 $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
4689 $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
4690 }
4691 if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
4692 $labeltoshowprice .= " (" . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
4693 $labeltoshowhtmlprice .= " (" . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
4694 }
4695 if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
4696 $labeltoshowprice .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
4697 $labeltoshowhtmlprice .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
4698 }
4699
4700 // Price by customer
4701 if (empty($hidepriceinlabel) && (getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'))) {
4702 if (!empty($objp->idprodcustprice)) {
4703 $found = 1;
4704
4705 if ($objp->custprice_base_type == 'HT') {
4706 $labeltoshowprice .= ' - ' . price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
4707 $labeltoshowhtmlprice .= ' - ' . price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
4708 } else {
4709 $labeltoshowprice .= ' - ' . price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
4710 $labeltoshowhtmlprice .= ' - ' . price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
4711 }
4712
4713 $outprice_ht = price($objp->custprice);
4714 $outprice_ttc = price($objp->custprice_ttc);
4715 $outpricebasetype = $objp->custprice_base_type;
4716 $outtva_tx = $objp->custtva_tx;
4717 $outdefault_vat_code = $objp->custdefault_vat_code;
4718 $outdiscount = $objp->custdiscount_percent;
4719 }
4720 }
4721
4722 // If level no defined or multiprice not found, we used the default price
4723 if (empty($hidepriceinlabel) && !$found) {
4724 if ($objp->price_base_type == 'HT') {
4725 $labeltoshowprice .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
4726 $labeltoshowhtmlprice .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
4727 } else {
4728 $labeltoshowprice .= ' - ' . price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
4729 $labeltoshowhtmlprice .= ' - ' . price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
4730 }
4731 $outprice_ht = price($objp->price);
4732 $outprice_ttc = price($objp->price_ttc);
4733 $outpricebasetype = $objp->price_base_type;
4734 $outtva_tx = $objp->tva_tx;
4735 $outdefault_vat_code = $objp->default_vat_code;
4736 }
4737
4738 $optiontext = $labeltosearch.$outvalUnits.$labeltoshowprice.$labeltoshowstock;
4739 $optionhtml = $labeltoshowhtml.$outvalUnits.$labeltoshowhtmlprice.$labeltoshowhtmlstock;
4740 $optionhtmlforattribute = dol_escape_htmltag($optionhtml, 0, 0, '', 0, 1);
4741
4742 // Build options
4743 $opt = '<option value="' . $objp->rowid . '"';
4744 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
4745 if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
4746 $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 . '"';
4747 }
4748 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
4749 $opt .= ' data-labeltrans="' . dol_escape_htmltag($outlabel_translated, 0, 0, '', 0, 1) . '"';
4750 $opt .= ' data-desctrans="' . dol_escape_htmltag($outdesc_translated) . '"';
4751 }
4752
4753 if ($stocktag == 1) {
4754 $opt .= ' class="product_line_stock_ok" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml, 0, array('strong')).dolPrintHTMLForAttribute($outvalUnits).$labeltoshowhtmlprice.dolPrintHTMLForAttribute($labeltoshowhtmlstock).'"';
4755 //$opt .= ' class="product_line_stock_ok"';
4756 }
4757 if ($stocktag == -1) {
4758 $opt .= ' class="product_line_stock_too_low" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml, 0, array('strong')).dolPrintHTMLForAttribute($outvalUnits).$labeltoshowhtmlprice.dolPrintHTMLForAttribute($labeltoshowhtmlstock).'"';
4759 //$opt .= ' class="product_line_stock_too_low"';
4760 }
4761 $opt .= ' data-html="'.$optionhtmlforattribute.'" data-select-html="'.$optionhtmlforattribute.'"';
4762
4763 $opt .= '>';
4764
4765 // Ref, barcode, country
4766 $opt .= dol_escape_htmltag($optiontext, 0, 0, '', 0, 1);
4767 $outval .= $labeltoshowhtml;
4768
4769 // Units
4770 $outval .= $outvalUnits;
4771
4772 // Price
4773 $outval .= $labeltoshowhtmlprice;
4774
4775 // Stock
4776 $outval .= $labeltoshowhtmlstock;
4777
4778
4779 $parameters = array('objp' => $objp);
4780 $reshook = $hookmanager->executeHooks('constructProductListOption', $parameters); // Note that $action and $object may have been modified by hook
4781 if (empty($reshook)) {
4782 $opt .= $hookmanager->resPrint;
4783 } else {
4784 $opt = $hookmanager->resPrint;
4785 }
4786
4787 $opt .= "</option>\n";
4788 $optJson = array(
4789 'key' => $outkey,
4790 'value' => $outref,
4791 'label' => $outval,
4792 'label2' => $outlabel,
4793 'desc' => $outdesc,
4794 'type' => $outtype,
4795 'price_ht' => price2num($outprice_ht),
4796 'price_ttc' => price2num($outprice_ttc),
4797 'price_ht_locale' => price(price2num($outprice_ht)),
4798 'price_ttc_locale' => price(price2num($outprice_ttc)),
4799 'pricebasetype' => $outpricebasetype,
4800 'tva_tx' => $outtva_tx,
4801 'default_vat_code' => $outdefault_vat_code,
4802 'qty' => $outqty,
4803 'discount' => $outdiscount,
4804 'duration_value' => $outdurationvalue,
4805 'duration_unit' => $outdurationunit,
4806 'pbq' => $outpbq,
4807 'labeltrans' => $outlabel_translated,
4808 'desctrans' => $outdesc_translated,
4809 'ref_customer' => $outrefcust
4810 );
4811 }
4812
4813 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4814
4831 public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $notused = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '', $nooutput = 0)
4832 {
4833 // phpcs:enable
4834 global $langs, $conf;
4835 global $price_level, $status, $finished;
4836
4837 if (!isset($status)) {
4838 $status = 1;
4839 }
4840
4841 $selected_input_value = '';
4842 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
4843 $regtmpsel = array();
4844 if ((int) $selected > 0) {
4845 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
4846 $producttmpselect = new Product($this->db);
4847 $producttmpselect->fetch((int) $selected);
4848 $selected_input_value = $producttmpselect->ref;
4849 unset($producttmpselect);
4850 } elseif (preg_match('/^idprod_([0-9]+)$/', (string) $selected, $regtmpsel)) {
4851 // Preselect when a product without supplier price was just created ('idprod_ID' value, used by backtopage of creation popup)
4852 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
4853 $producttmpselect = new Product($this->db);
4854 $producttmpselect->fetch((int) $regtmpsel[1]);
4855 $selected_input_value = $producttmpselect->ref;
4856 unset($producttmpselect);
4857 }
4858
4859 // mode=2 means suppliers products
4860 $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=2&status=' . $status . '&finished=' . $finished . '&alsoproductwithnosupplierprice=' . $alsoproductwithnosupplierprice;
4861
4862 $s = ($hidelabel ? '' : $langs->trans("RefOrLabel") . ' : ') . '<input type="text" class="'.$morecss.'" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . $placeholder . '"' : '') . ' spellcheck="false">';
4863
4864 $s .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, getDolGlobalInt('PRODUIT_USE_SEARCH_TO_SELECT'), 0, $ajaxoptions);
4865 } else {
4866 $s = $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $notused, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, getDolGlobalInt('SUPPLIER_SHOW_STOCK_IN_PRODUCTS_COMBO'), $placeholder);
4867 }
4868
4869 if ($nooutput) {
4870 return $s;
4871 } else {
4872 print $s;
4873 }
4874 }
4875
4876 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4877
4896 public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $notused = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '', $showstockinlist = 0, $placeholder = '')
4897 {
4898 // phpcs:enable
4899 global $langs, $conf, $user;
4900 global $hookmanager;
4901
4902 $out = '';
4903 $outarray = array();
4904
4905 $maxlengtharticle = getDolGlobalInt('PRODUCT_MAX_LENGTH_COMBO', 48);
4906
4907 $langs->load('stocks');
4908 // Units
4909 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4910 $langs->load('other');
4911 }
4912
4913 $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,";
4914 $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice, pfp.barcode";
4915 $sql .= ", pfp.multicurrency_code, pfp.multicurrency_unitprice";
4916 $sql .= ", pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name";
4917 $sql .= ", pfp.supplier_reputation";
4918 // if we use supplier description of the products
4919 if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
4920 $sql .= ", pfp.desc_fourn as description";
4921 } else {
4922 $sql .= ", p.description";
4923 }
4924 // Units
4925 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4926 $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";
4927 }
4928
4929 // Add select from hooks
4930 $parameters = [];
4931 $reshook = $hookmanager->executeHooks('selectSuppliersProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
4932 $sql .= $hookmanager->resPrint;
4933
4934 $sql .= " FROM " . $this->db->prefix() . "product as p";
4935
4936 // Add join from hooks
4937 $parameters = [];
4938 $reshook = $hookmanager->executeHooks('selectSuppliersProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
4939 $sql .= $hookmanager->resPrint;
4940
4941 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (" . getEntity('product') . ") )";
4942 if ($socid > 0) {
4943 $sql .= " AND pfp.fk_soc = " . ((int) $socid);
4944 }
4945 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
4946 // Units
4947 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4948 $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
4949 }
4950 $sql .= " WHERE p.entity IN (" . getEntity('product') . ")";
4951 if ($statut != -1) {
4952 $sql .= " AND p.tobuy = " . ((int) $statut);
4953 }
4954 if (strval($filtertype) != '') {
4955 $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
4956 }
4957
4958 // Add where from hooks
4959 $parameters = array();
4960 $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
4961 $sql .= $hookmanager->resPrint;
4962 // Add criteria on ref/label
4963 if ($filterkey != '') {
4964 $sql .= ' AND (';
4965 $prefix = getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
4966 // For natural search
4967 $search_crit = explode(' ', $filterkey);
4968 $i = 0;
4969 if (count($search_crit) > 1) {
4970 $sql .= "(";
4971 }
4972 foreach ($search_crit as $crit) {
4973 if ($i > 0) {
4974 $sql .= " AND ";
4975 }
4976 $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) . "%'";
4977 if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
4978 $sql .= " OR pfp.desc_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
4979 }
4980 $sql .= ")";
4981 $i++;
4982 }
4983 if (count($search_crit) > 1) {
4984 $sql .= ")";
4985 }
4986 if (isModEnabled('barcode')) {
4987 $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
4988 $sql .= " OR pfp.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
4989 }
4990 $sql .= ')';
4991 }
4992 $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
4993 $sql .= $this->db->plimit($limit, 0);
4994
4995 // Build output string
4996
4997 dol_syslog(get_class($this) . "::select_produits_fournisseurs_list", LOG_DEBUG);
4998 $result = $this->db->query($sql);
4999 if ($result) {
5000 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
5001 require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
5002
5003 $num = $this->db->num_rows($result);
5004
5005 //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
5006 $out .= '<select class="flat ' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '">';
5007 if (!$selected) {
5008 $out .= '<option value="-1" selected>' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
5009 } else {
5010 $out .= '<option value="-1">' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
5011 }
5012
5013 $i = 0;
5014 while ($i < $num) {
5015 $objp = $this->db->fetch_object($result);
5016
5017 if (is_null($objp->idprodfournprice)) {
5018 // There is no supplier price found, we will use the vat rate for sale
5019 $objp->tva_tx = $objp->tva_tx_sale;
5020 $objp->default_vat_code = $objp->default_vat_code_sale;
5021 }
5022
5023 $outkey = $objp->idprodfournprice; // id in table of price
5024 if (!$outkey && $alsoproductwithnosupplierprice) {
5025 $outkey = 'idprod_' . $objp->rowid; // id of product
5026 }
5027
5028 $outref = $objp->ref;
5029 $outbarcode = $objp->barcode;
5030 $outqty = 1;
5031 $outdiscount = 0;
5032 $outtype = $objp->fk_product_type;
5033 $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
5034 $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
5035
5036 // Units
5037 $outvalUnits = '';
5038 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
5039 if (!empty($objp->unit_short)) {
5040 $outvalUnits .= ' - ' . $objp->unit_short;
5041 }
5042 if (!empty($objp->weight) && $objp->weight_units !== null) {
5043 $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
5044 $outvalUnits .= ' - ' . $unitToShow;
5045 }
5046 if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
5047 $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
5048 $outvalUnits .= ' - ' . $unitToShow;
5049 }
5050 if (!empty($objp->surface) && $objp->surface_units !== null) {
5051 $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
5052 $outvalUnits .= ' - ' . $unitToShow;
5053 }
5054 if (!empty($objp->volume) && $objp->volume_units !== null) {
5055 $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
5056 $outvalUnits .= ' - ' . $unitToShow;
5057 }
5058 if ($outdurationvalue && $outdurationunit) {
5059 $da = array(
5060 'h' => $langs->trans('Hour'),
5061 'd' => $langs->trans('Day'),
5062 'w' => $langs->trans('Week'),
5063 'm' => $langs->trans('Month'),
5064 'y' => $langs->trans('Year')
5065 );
5066 if (isset($da[$outdurationunit])) {
5067 $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
5068 }
5069 }
5070 }
5071
5072 $objRef = $objp->ref;
5073 if ($filterkey && $filterkey != '') {
5074 $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
5075 }
5076 $objRefFourn = $objp->ref_fourn;
5077 if ($filterkey && $filterkey != '') {
5078 $objRefFourn = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRefFourn, 1);
5079 }
5080 $label = $objp->label;
5081 if ($filterkey && $filterkey != '') {
5082 $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
5083 }
5084
5085 switch ($objp->fk_product_type) {
5087 $picto = 'product';
5088 break;
5090 $picto = 'service';
5091 break;
5092 default:
5093 $picto = '';
5094 break;
5095 }
5096
5097 if (empty($picto)) {
5098 $optlabel = '';
5099 } else {
5100 $optlabel = img_object('', $picto, 'class="paddingright classfortooltip"', 0, 0, 1);
5101 }
5102
5103 $optlabel .= $objp->ref;
5104 if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
5105 $optlabel .= ' <span class="opacitymedium">(' . $objp->ref_fourn . ')</span>';
5106 }
5107 if (isModEnabled('barcode') && !empty($objp->barcode)) {
5108 $optlabel .= ' (' . $outbarcode . ')';
5109 }
5110 $optlabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
5111
5112 $outvallabel = $objRef;
5113 if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
5114 $outvallabel .= ' (' . $objRefFourn . ')';
5115 }
5116 if (isModEnabled('barcode') && !empty($objp->barcode)) {
5117 $outvallabel .= ' (' . $outbarcode . ')';
5118 }
5119 $outvallabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
5120
5121 $outsearchlabel = implode(' ', array_filter(array(
5122 (string) $objp->ref,
5123 (string) $objp->ref_fourn,
5124 (string) $objp->barcode,
5125 (string) $objp->label,
5126 dol_string_nohtmltag((string) $objp->description)
5127 ), function (string $value): bool {
5128 return $value !== '';
5129 }));
5130
5131 // Units
5132 $optlabel .= $outvalUnits;
5133 $outvallabel .= $outvalUnits;
5134
5135 if (!empty($objp->idprodfournprice)) {
5136 $outqty = $objp->quantity;
5137 $outdiscount = $objp->remise_percent;
5138 if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
5139 $prod_supplier = new ProductFournisseur($this->db);
5140 $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
5141 $prod_supplier->id = $objp->fk_product;
5142 $prod_supplier->fourn_qty = $objp->quantity;
5143 $prod_supplier->fourn_tva_tx = $objp->tva_tx;
5144 $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
5145
5146 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
5147 $priceparser = new PriceParser($this->db);
5148 $price_result = $priceparser->parseProductSupplier($prod_supplier);
5149 if ($price_result >= 0) {
5150 $objp->fprice = $price_result;
5151 if ($objp->quantity >= 1) {
5152 $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
5153 }
5154 }
5155 }
5156 if ($objp->quantity == 1) {
5157 $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
5158 $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/";
5159 $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
5160 $outvallabel .= $langs->transnoentities("Unit");
5161 } else {
5162 $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
5163 $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
5164 $optlabel .= ' ' . $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
5165 $outvallabel .= ' ' . $langs->transnoentities("Units");
5166 }
5167
5168 if ($objp->quantity != 1) {
5169 $optlabel .= " (" . price($objp->unitprice * (getDolGlobalString('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
5170 $outvallabel .= " (" . price($objp->unitprice * (getDolGlobalString('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
5171 }
5172 if ($objp->remise_percent >= 1) {
5173 $optlabel .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
5174 $outvallabel .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
5175 }
5176 if ($objp->duration) {
5177 $optlabel .= " - " . $objp->duration;
5178 $outvallabel .= " - " . $objp->duration;
5179 }
5180 if (!$socid) {
5181 $optlabel .= " - " . dol_trunc($objp->name, 8);
5182 $outvallabel .= " - " . dol_trunc($objp->name, 8);
5183 }
5184 if ($objp->supplier_reputation) {
5185 //TODO dictionary
5186 $reputations = array('' => $langs->trans('Standard'), 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
5187
5188 $optlabel .= " - " . $reputations[$objp->supplier_reputation];
5189 $outvallabel .= " - " . $reputations[$objp->supplier_reputation];
5190 }
5191 } else {
5192 $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
5193 $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
5194 }
5195
5196 if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
5197 $novirtualstock = ($showstockinlist == 2);
5198
5199 if ($user->hasRight('stock', 'lire')) {
5200 $outvallabel .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
5201
5202 if ($objp->stock > 0) {
5203 $optlabel .= ' - <span class="product_line_stock_ok">';
5204 } elseif ($objp->stock <= 0) {
5205 $optlabel .= ' - <span class="product_line_stock_too_low">';
5206 }
5207 $optlabel .= $langs->transnoentities("Stock") . ':' . price(price2num($objp->stock, 'MS'));
5208 $optlabel .= '</span>';
5209 if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
5210 $langs->load("stocks");
5211
5212 $tmpproduct = new Product($this->db);
5213 $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
5214 $tmpproduct->load_virtual_stock();
5215 $virtualstock = $tmpproduct->stock_theorique;
5216
5217 $outvallabel .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
5218
5219 $optlabel .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
5220 if ($virtualstock > 0) {
5221 $optlabel .= '<span class="product_line_stock_ok">';
5222 } elseif ($virtualstock <= 0) {
5223 $optlabel .= '<span class="product_line_stock_too_low">';
5224 }
5225 $optlabel .= $virtualstock;
5226 $optlabel .= '</span>';
5227
5228 unset($tmpproduct);
5229 }
5230 }
5231 }
5232
5233 $optstart = '<option value="' . $outkey . '"';
5234 if ($selected && preg_match('/^idprod_/', (string) $selected) && (string) $selected == 'idprod_'.$objp->rowid) {
5235 $optstart .= ' selected';
5236 } elseif ($selected && (string) $selected == (string) $objp->idprodfournprice) {
5237 $optstart .= ' selected';
5238 }
5239
5240 if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
5241 $optstart .= ' disabled';
5242 }
5243
5244 if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
5245 $optstart .= ' data-product-id="' . dol_escape_htmltag($objp->rowid) . '"';
5246 $optstart .= ' data-price-id="' . dol_escape_htmltag($objp->idprodfournprice) . '"';
5247 $optstart .= ' data-qty="' . dol_escape_htmltag($objp->quantity) . '"';
5248 $optstart .= ' data-up="' . dol_escape_htmltag(price2num($objp->unitprice)) . '"'; // the price with numeric international format
5249 $optstart .= ' data-up-locale="' . dol_escape_htmltag(price($objp->unitprice)) . '"'; // the price formatted in user language
5250 $optstart .= ' data-discount="' . dol_escape_htmltag((string) $outdiscount) . '"';
5251 $optstart .= ' data-tvatx="' . dol_escape_htmltag(price2num($objp->tva_tx)) . '"'; // the rate with numeric international format
5252 $optstart .= ' data-tvatx-formated="' . dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)) . '"'; // the rate formatted in user language
5253 $optstart .= ' data-default-vat-code="' . dol_escape_htmltag($objp->default_vat_code) . '"';
5254 $optstart .= ' data-supplier-ref="' . dol_escape_htmltag($objp->ref_fourn) . '"';
5255 if (isModEnabled('multicurrency')) {
5256 $optstart .= ' data-multicurrency-code="' . dol_escape_htmltag($objp->multicurrency_code) . '"';
5257 $optstart .= ' data-multicurrency-unitprice="' . dol_escape_htmltag(price2num($objp->multicurrency_unitprice)) . '"'; // the price with numeric international format
5258 }
5259 }
5260 $optstart .= ' data-description="' . dol_escape_htmltag($objp->description, 0, 1) . '"';
5261 $optstart .= ' data-search="' . dol_escape_htmltag($outsearchlabel) . '"';
5262
5263 // set $parameters to call hook
5264 $outarrayentry = array(
5265 'key' => $outkey,
5266 'value' => $outref,
5267 'label' => $outvallabel,
5268 'labelhtml' => $optlabel,
5269 'qty' => $outqty,
5270 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
5271 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
5272 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
5273 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
5274 'tva_tx' => price2num($objp->tva_tx),
5275 'default_vat_code' => $objp->default_vat_code,
5276 'supplier_ref' => $objp->ref_fourn,
5277 'discount' => $outdiscount,
5278 'type' => $outtype,
5279 'duration_value' => $outdurationvalue,
5280 'duration_unit' => $outdurationunit,
5281 'disabled' => empty($objp->idprodfournprice),
5282 'description' => $objp->description
5283 );
5284 if (isModEnabled('multicurrency')) {
5285 $outarrayentry['multicurrency_code'] = $objp->multicurrency_code;
5286 $outarrayentry['multicurrency_unitprice'] = price2num($objp->multicurrency_unitprice, 'MU');
5287 }
5288 $parameters = array(
5289 'objp' => &$objp,
5290 'optstart' => &$optstart,
5291 'optlabel' => &$optlabel,
5292 'outvallabel' => &$outvallabel,
5293 'outarrayentry' => &$outarrayentry,
5294 'fk_soc' => $socid
5295 );
5296 $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
5297
5298
5299 // Add new entry
5300 // "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
5301 // "label" value of json key array is used by jQuery automatically as text for combo box
5302 $out .= $optstart . ' data-html="' . dol_escape_htmltag($optlabel) . '">' . $optlabel . "</option>\n";
5303 $outarraypush = array(
5304 'key' => $outkey,
5305 'value' => $outref,
5306 'label' => $outvallabel,
5307 'labelhtml' => $optlabel,
5308 'qty' => $outqty,
5309 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
5310 'price_qty_ht_locale' => price($objp->fprice),
5311 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
5312 'price_unit_ht_locale' => price($objp->unitprice),
5313 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
5314 'tva_tx_formated' => price($objp->tva_tx),
5315 'tva_tx' => price2num($objp->tva_tx),
5316 'default_vat_code' => $objp->default_vat_code,
5317 'supplier_ref' => $objp->ref_fourn,
5318 'discount' => $outdiscount,
5319 'type' => $outtype,
5320 'duration_value' => $outdurationvalue,
5321 'duration_unit' => $outdurationunit,
5322 'disabled' => empty($objp->idprodfournprice),
5323 'description' => $objp->description
5324 );
5325 if (isModEnabled('multicurrency')) {
5326 $outarraypush['multicurrency_code'] = $objp->multicurrency_code;
5327 $outarraypush['multicurrency_unitprice'] = price2num($objp->multicurrency_unitprice, 'MU');
5328 }
5329 array_push($outarray, $outarraypush);
5330
5331 // Example of var_dump $outarray
5332 // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
5333 // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/unit (20,00 Euros/unit)"
5334 // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
5335 //}
5336 //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
5337 //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unit (20,00 Euros/unit)');
5338 //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
5339
5340 $i++;
5341 }
5342 $out .= '</select>';
5343
5344 $this->db->free($result);
5345
5346 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5347 $out .= ajax_combobox($htmlname);
5348 } else {
5349 dol_print_error($this->db);
5350 }
5351
5352 if (empty($outputmode)) {
5353 return $out;
5354 }
5355 return $outarray;
5356 }
5357
5358 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5359
5368 public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = 0)
5369 {
5370 // phpcs:enable
5371 global $langs, $conf;
5372
5373 $langs->load('stocks');
5374
5375 $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
5376 $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
5377 $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
5378 $sql .= " FROM " . $this->db->prefix() . "product as p";
5379 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
5380 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
5381 $sql .= " WHERE pfp.entity IN (" . getEntity('productsupplierprice') . ")";
5382 $sql .= " AND p.tobuy = 1";
5383 $sql .= " AND s.fournisseur = 1";
5384 $sql .= " AND p.rowid = " . ((int) $productid);
5385 if (!getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED')) {
5386 $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
5387 } else {
5388 $sql .= " ORDER BY pfp.unitprice - pfp.unitprice * pfp.remise_percent / 100 ASC";
5389 }
5390
5391 dol_syslog(get_class($this) . "::select_product_fourn_price", LOG_DEBUG);
5392 $result = $this->db->query($sql);
5393
5394 if ($result) {
5395 $num = $this->db->num_rows($result);
5396
5397 $form = '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
5398
5399 if (!$num) {
5400 $form .= '<option value="0">-- ' . $langs->trans("NoSupplierPriceDefinedForThisProduct") . ' --</option>';
5401 } else {
5402 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
5403 $form .= '<option value="0">&nbsp;</option>';
5404
5405 $i = 0;
5406 while ($i < $num) {
5407 $objp = $this->db->fetch_object($result);
5408
5409 $opt = '<option value="' . $objp->idprodfournprice . '"';
5410 //if there is only one supplier, preselect it
5411 if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED'))) {
5412 $opt .= ' selected';
5413 }
5414 $opt .= '>' . $objp->name . ' - ' . $objp->ref_fourn . ' - ';
5415
5416 if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
5417 $prod_supplier = new ProductFournisseur($this->db);
5418 $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
5419 $prod_supplier->id = $productid;
5420 $prod_supplier->fourn_qty = $objp->quantity;
5421 $prod_supplier->fourn_tva_tx = $objp->tva_tx;
5422 $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
5423
5424 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
5425 $priceparser = new PriceParser($this->db);
5426 $price_result = $priceparser->parseProductSupplier($prod_supplier);
5427 if ($price_result >= 0) {
5428 $objp->fprice = $price_result;
5429 if ($objp->quantity >= 1) {
5430 $objp->unitprice = $objp->fprice / $objp->quantity;
5431 }
5432 }
5433 }
5434 if ($objp->quantity == 1) {
5435 $opt .= price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
5436 }
5437
5438 $opt .= $objp->quantity . ' ';
5439
5440 if ($objp->quantity == 1) {
5441 $opt .= $langs->trans("Unit");
5442 } else {
5443 $opt .= $langs->trans("Units");
5444 }
5445 if ($objp->quantity > 1) {
5446 $opt .= " - ";
5447 $opt .= price($objp->unitprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit");
5448 }
5449 if ($objp->duration) {
5450 $opt .= " - " . $objp->duration;
5451 }
5452 $opt .= "</option>\n";
5453
5454 $form .= $opt;
5455 $i++;
5456 }
5457 }
5458
5459 $form .= '</select>';
5460 $this->db->free($result);
5461 return $form;
5462 } else {
5463 dol_print_error($this->db);
5464 return '';
5465 }
5466 }
5467
5468
5469 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5476 {
5477 // phpcs:enable
5478 global $langs, $hookmanager;
5479
5480 $num = count($this->cache_conditions_paiements);
5481 if ($num > 0) {
5482 return 0; // Cache already loaded
5483 }
5484
5485 dol_syslog(__METHOD__, LOG_DEBUG);
5486
5487 $this->cache_conditions_paiements = array();
5488
5489 $sql = "SELECT rowid, code, libelle as label, deposit_percent, entity";
5490 $sql .= " FROM " . $this->db->prefix() . 'c_payment_term';
5491 $sql .= " WHERE entity IN (" . getEntity('c_payment_term') . ")";
5492 $sql .= " AND active > 0";
5493 $sql .= " ORDER BY sortorder";
5494
5495 $resql = $this->db->query($sql);
5496 if ($resql) {
5497 $num = $this->db->num_rows($resql);
5498 $i = 0;
5499 while ($i < $num) {
5500 $obj = $this->db->fetch_object($resql);
5501
5502 // If a translation exists, we use it, otherwise, we take the label by default
5503 $label = ($langs->trans("PaymentConditionShort" . $obj->code) != "PaymentConditionShort" . $obj->code ? $langs->trans("PaymentConditionShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
5504
5505 $this->cache_conditions_paiements[$obj->rowid]['code'] = (string) $obj->code;
5506 $this->cache_conditions_paiements[$obj->rowid]['label'] = (string) $label;
5507 $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = (string) $obj->deposit_percent;
5508 $this->cache_conditions_paiements[$obj->rowid]['entity'] = (int) $obj->entity;
5509
5510 $i++;
5511 }
5512
5513 $parameters = array('dictionary' => 'paymentterm');
5514 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
5515 if (empty($reshook)) {
5516 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
5517 $this->cache_conditions_paiements = array_merge($this->cache_conditions_paiements, $hookmanager->resArray);
5518 }
5519 } else {
5520 $this->cache_conditions_paiements = $hookmanager->resArray;
5521 }
5522
5523 //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
5524
5525 return $num;
5526 } else {
5527 dol_print_error($this->db);
5528 return -1;
5529 }
5530 }
5531
5532 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5533
5540 {
5541 // phpcs:enable
5542 $factureRec = new FactureRec($this->db);
5543
5544 $this->cache_rule_for_lines_dates = $factureRec->fields['rule_for_lines_dates']['arrayofkeyval'];
5545
5546 if (empty($this->cache_rule_for_lines_dates)) {
5547 return -1;
5548 }
5549
5550 return 1;
5551 }
5552
5553 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5554
5560 public function load_cache_availability()
5561 {
5562 // phpcs:enable
5563 global $langs;
5564
5565 $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
5566 if ($num > 0) {
5567 return 0; // Cache already loaded
5568 }
5569
5570 dol_syslog(__METHOD__, LOG_DEBUG);
5571
5572 $this->cache_availability = array();
5573
5574 $langs->load('propal');
5575
5576 $sql = "SELECT rowid, code, label, position";
5577 $sql .= " FROM " . $this->db->prefix() . 'c_availability';
5578 $sql .= " WHERE active > 0";
5579
5580 $resql = $this->db->query($sql);
5581 if ($resql) {
5582 $num = $this->db->num_rows($resql);
5583 $i = 0;
5584 while ($i < $num) {
5585 $obj = $this->db->fetch_object($resql);
5586
5587 // If a translation exists, we use is, otherwise, we take the label by default
5588 $label = ($langs->trans("AvailabilityType" . $obj->code) != "AvailabilityType" . $obj->code ? $langs->trans("AvailabilityType" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
5589 $this->cache_availability[$obj->rowid]['code'] = (string) $obj->code;
5590 $this->cache_availability[$obj->rowid]['label'] = (string) $label;
5591 $this->cache_availability[$obj->rowid]['position'] = (int) $obj->position;
5592 $i++;
5593 }
5594
5595 // @phan-suppress-next-line PhanTypeMismatchProperty PhanTypeMismatchDimFetch
5596 $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
5597
5598 return $num;
5599 } else {
5600 dol_print_error($this->db);
5601 return -1;
5602 }
5603 }
5604
5616 public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '', $noouput = 0)
5617 {
5618 global $langs, $user;
5619
5620 $this->load_cache_availability();
5621
5622 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
5623
5624 $out = '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
5625 if ($addempty) {
5626 $out .= '<option value="-1">'.(is_numeric($addempty) ? '&nbsp;' : $langs->trans($addempty)).'</option>';
5627 }
5628 foreach ($this->cache_availability as $id => $arrayavailability) {
5629 if ($selected == $id) {
5630 $out .= '<option value="' . $id . '" selected>';
5631 } else {
5632 $out .= '<option value="' . $id . '">';
5633 }
5634 $out .= dol_escape_htmltag($arrayavailability['label']);
5635 $out .= '</option>';
5636 }
5637 $out .= '</select>';
5638 if ($user->admin) {
5639 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5640 }
5641 $out .= ajax_combobox($htmlname);
5642
5643 if ($noouput) {
5644 return $out;
5645 } else {
5646 print $out;
5647 return '';
5648 }
5649 }
5650
5656 public function loadCacheInputReason()
5657 {
5658 global $langs;
5659
5660 $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
5661 if ($num > 0) {
5662 return 0; // Cache already loaded
5663 }
5664
5665 $sql = "SELECT rowid, code, label";
5666 $sql .= " FROM " . $this->db->prefix() . 'c_input_reason';
5667 $sql .= " WHERE active > 0";
5668
5669 $resql = $this->db->query($sql);
5670 if ($resql) {
5671 $num = $this->db->num_rows($resql);
5672 $i = 0;
5674 $tmparray = array();
5675 while ($i < $num) {
5676 $obj = $this->db->fetch_object($resql);
5677
5678 // If a translation exists, we use is, otherwise, we take the label by default
5679 $label = ($obj->label != '-' ? (string) $obj->label : '');
5680 if ($langs->trans("DemandReasonType" . $obj->code) != "DemandReasonType" . $obj->code) {
5681 $label = $langs->trans("DemandReasonType" . $obj->code); // So translation key DemandReasonTypeSRC_XXX will work
5682 }
5683 if ($langs->trans($obj->code) != $obj->code) {
5684 $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
5685 }
5686
5687 $tmparray[(int) $obj->rowid]
5688 = array(
5689 'id' => (int) $obj->rowid,
5690 'code' => (string) $obj->code,
5691 'label' => $label,
5692 );
5693 $i++;
5694 }
5695
5696 $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
5697
5698 unset($tmparray);
5699 return $num;
5700 } else {
5701 dol_print_error($this->db);
5702 return -1;
5703 }
5704 }
5705
5718 public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
5719 {
5720 global $langs, $user;
5721
5722 $this->loadCacheInputReason();
5723
5724 print '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="select_' . $htmlname . '" name="' . $htmlname . '">';
5725 if ($addempty) {
5726 print '<option value="0"' . (empty($selected) ? ' selected' : '') . '>&nbsp;</option>';
5727 }
5728 foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
5729 if ($arraydemandreason['code'] == $exclude) {
5730 continue;
5731 }
5732
5733 if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
5734 print '<option value="' . $arraydemandreason['id'] . '" selected>';
5735 } else {
5736 print '<option value="' . $arraydemandreason['id'] . '">';
5737 }
5738 $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
5739 print $langs->trans($label);
5740 print '</option>';
5741 }
5742 print '</select>';
5743 if ($user->admin && empty($notooltip)) {
5744 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5745 }
5746 print ajax_combobox('select_' . $htmlname);
5747 }
5748
5749 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5750
5757 {
5758 // phpcs:enable
5759 global $langs, $hookmanager;
5760
5761 $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
5762 if ($num > 0) {
5763 return $num; // Cache already loaded
5764 }
5765
5766 dol_syslog(__METHOD__, LOG_DEBUG);
5767
5768 $this->cache_types_paiements = array();
5769
5770 $sql = "SELECT id, code, libelle as label, type, entity, active";
5771 $sql .= " FROM " . $this->db->prefix() . "c_paiement";
5772 $sql .= " WHERE entity IN (" . getEntity('c_paiement') . ")";
5773
5774 $resql = $this->db->query($sql);
5775 if ($resql) {
5776 $num = $this->db->num_rows($resql);
5777 $i = 0;
5778 while ($i < $num) {
5779 $obj = $this->db->fetch_object($resql);
5780
5781 // If a translation exists, we use is, otherwise, we take the label by default
5782 $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
5783 $shortlabel = $label; // TODO
5784
5785 $this->cache_types_paiements[(int) $obj->id]['id'] = (int) $obj->id;
5786 $this->cache_types_paiements[(int) $obj->id]['code'] = (string) $obj->code;
5787 $this->cache_types_paiements[(int) $obj->id]['label'] = (string) $label;
5788 $this->cache_types_paiements[(int) $obj->id]['shortlabel'] = (string) $shortlabel;
5789 $this->cache_types_paiements[(int) $obj->id]['type'] = (int) $obj->type;
5790 $this->cache_types_paiements[(int) $obj->id]['entity'] = (int) $obj->entity;
5791 $this->cache_types_paiements[(int) $obj->id]['active'] = (int) $obj->active;
5792 $i++;
5793 }
5794
5795 $parameters = array('dictionary' => 'paymenttype');
5796 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
5797 if (empty($reshook)) {
5798 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
5799 $this->cache_types_paiements = array_merge($this->cache_types_paiements, $hookmanager->resArray);
5800 }
5801 } else {
5802 $this->cache_types_paiements = $hookmanager->resArray;
5803 }
5804
5805 $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
5806
5807 return $num;
5808 } else {
5809 dol_print_error($this->db);
5810 return -1;
5811 }
5812 }
5813
5814
5815 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5816
5835 public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1, $noprint = 0)
5836 {
5837 // phpcs:enable
5838 $out = $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
5839 if (empty($noprint)) {
5840 print $out;
5841 } else {
5842 return $out;
5843 }
5844 }
5845
5846
5863 public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
5864 {
5865 global $langs, $user;
5866
5867 $out = '';
5868 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
5869
5870 $this->load_cache_conditions_paiements();
5871
5872 // Set default value if not already set by caller
5873 if (empty($selected) && strpos($htmlname, 'search_') !== 0 && getDolGlobalInt('MAIN_DEFAULT_PAYMENT_TERM_ID')) {
5874 dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TERM_ID", LOG_NOTICE);
5875 $selected = getDolGlobalInt('MAIN_DEFAULT_PAYMENT_TERM_ID');
5876 }
5877
5878 $out .= '<select id="' . $htmlname . '" class="flat selectpaymentterms' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
5879 if ($addempty) {
5880 $out .= '<option value="0">&nbsp;</option>';
5881 }
5882
5883 $selectedDepositPercent = null;
5884
5885 foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
5886 if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
5887 continue;
5888 }
5889
5890 if ($selected == $id) {
5891 $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
5892 $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
5893 } else {
5894 $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
5895 }
5896 $label = $arrayconditions['label'];
5897
5898 if (!empty($arrayconditions['deposit_percent'])) {
5899 $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
5900 }
5901
5902 $out .= $label;
5903 $out .= '</option>';
5904 }
5905 $out .= '</select>';
5906 if ($user->admin && empty($noinfoadmin)) {
5907 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5908 }
5909 $out .= ajax_combobox($htmlname);
5910
5911 if ($deposit_percent >= 0) {
5912 $out .= ' <span id="' . $htmlname . '_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
5913 $out .= $langs->trans('DepositPercent') . ' : ';
5914 $out .= '<input id="' . $htmlname . '_deposit_percent" name="' . $htmlname . '_deposit_percent" class="maxwidth50" value="' . $deposit_percent . '" />';
5915 $out .= '</span>';
5916 $out .= '
5917 <script nonce="' . getNonce() . '">
5918 $(document).ready(function () {
5919 let $select = $("#' . $htmlname . '");
5920 let $container = $("#' . $htmlname . '_deposit_percent_container");
5921 let $input = $("#' . $htmlname . '_deposit_percent");
5922
5923 function refreshDepositPercent(isInit) {
5924 let depositPercent = $select.find("option:selected").attr("data-deposit_percent") || "";
5925
5926 if (depositPercent.length > 0) {
5927 $container.show();
5928 // On page load, keep an existing (possibly customized) value; on user change use the payment term default
5929 if (!isInit || !parseFloat($input.val())) {
5930 $input.val(depositPercent);
5931 }
5932 } else {
5933 $container.hide();
5934 }
5935 }
5936
5937 $select.change(function () {
5938 refreshDepositPercent(false);
5939 return true;
5940 });
5941
5942 // Initialize on load so a default payment term with a deposit is reflected without a manual change
5943 refreshDepositPercent(true);
5944 });
5945 </script>';
5946 }
5947
5948 return $out;
5949 }
5950
5951
5960 public function getSelectRuleForLinesDates($selected = '', $htmlname = 'rule_for_lines_dates', $addempty = 0)
5961 {
5962 global $langs;
5963
5964 $out = '';
5965
5966 $this->load_cache_rule_for_lines_dates();
5967
5968 $out .= '<select id="' . $htmlname . '" class="flat selectbillingterm" name="' . $htmlname . '">';
5969 if ($addempty) {
5970 $out .= '<option value="-1">&nbsp;</option>';
5971 }
5972
5973
5974 foreach ($this->cache_rule_for_lines_dates as $rule_for_lines_dates_key => $rule_for_lines_dates_name) {
5975 if ($selected == $rule_for_lines_dates_key) {
5976 $out .= '<option value="' . $rule_for_lines_dates_key . '" selected>';
5977 } else {
5978 $out .= '<option value="' . $rule_for_lines_dates_key . '">';
5979 }
5980
5981 $out .= $langs->trans($rule_for_lines_dates_name);
5982 $out .= '</option>';
5983 }
5984 $out .= '</select>';
5985
5986 $out .= ajax_combobox($htmlname);
5987
5988 return $out;
5989 }
5990
5991
5992 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5993
6010 public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
6011 {
6012 // phpcs:enable
6013 global $langs, $user;
6014
6015 $out = '';
6016
6017 dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
6018
6019 $filterarray = array();
6020 if ($filtertype == 'CRDT') {
6021 $filterarray = array(0, 2, 3);
6022 } elseif ($filtertype == 'DBIT') {
6023 $filterarray = array(1, 2, 3);
6024 } elseif ($filtertype != '' && $filtertype != '-1') {
6025 $filterarray = explode(',', $filtertype);
6026 }
6027
6028 $this->load_cache_types_paiements();
6029
6030 // Set default value if not already set by caller
6031 if (empty($selected) && strpos($htmlname, 'search_') !== 0 && getDolGlobalString('MAIN_DEFAULT_PAYMENT_TYPE_ID')) {
6032 dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TYPE_ID", LOG_NOTICE);
6033 $selected = getDolGlobalString('MAIN_DEFAULT_PAYMENT_TYPE_ID');
6034 }
6035
6036 $out .= '<select id="select' . $htmlname . '" class="flat selectpaymenttypes' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
6037 if ($empty) {
6038 $out .= '<option value="">&nbsp;</option>';
6039 }
6040 foreach ($this->cache_types_paiements as $id => $arraytypes) {
6041 // If not good status
6042 if ($active >= 0 && $arraytypes['active'] != $active) {
6043 continue;
6044 }
6045
6046 // We skip of the user requested to filter on specific payment methods
6047 if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
6048 continue;
6049 }
6050
6051 // We discard empty lines if showempty is on because an empty line has already been output.
6052 if ($empty && empty($arraytypes['code'])) {
6053 continue;
6054 }
6055
6056 if ($format == 0) {
6057 $out .= '<option value="' . $id . '" data-code="'.$arraytypes['code'].'"';
6058 } elseif ($format == 1) {
6059 $out .= '<option value="' . $arraytypes['code'] . '"';
6060 } elseif ($format == 2) {
6061 $out .= '<option value="' . $arraytypes['code'] . '"';
6062 } elseif ($format == 3) {
6063 $out .= '<option value="' . $id . '"';
6064 }
6065 // Print attribute selected or not
6066 if ($format == 1 || $format == 2) {
6067 if ($selected == $arraytypes['code']) {
6068 $out .= ' selected';
6069 }
6070 } else {
6071 if ($selected == $id) {
6072 $out .= ' selected';
6073 }
6074 }
6075 $out .= '>';
6076 $value = '';
6077 if ($format == 0) {
6078 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
6079 } elseif ($format == 1) {
6080 $value = $arraytypes['code'];
6081 } elseif ($format == 2) {
6082 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
6083 } elseif ($format == 3) {
6084 $value = $arraytypes['code'];
6085 }
6086 $out .= $value ? $value : '&nbsp;';
6087 $out .= '</option>';
6088 }
6089 $out .= '</select>';
6090 if ($user->admin && !$noadmininfo) {
6091 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
6092 }
6093 $out .= ajax_combobox('select' . $htmlname);
6094
6095 if (empty($nooutput)) {
6096 print $out;
6097 } else {
6098 return $out;
6099 }
6100 }
6101
6102
6111 public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
6112 {
6113 global $langs;
6114
6115 $return = '<select class="flat maxwidth100" id="select_' . $htmlname . '" name="' . $htmlname . '">';
6116 $options = array(
6117 'HT' => $langs->trans("HT"),
6118 'TTC' => $langs->trans("TTC")
6119 );
6120 foreach ($options as $id => $value) {
6121 if ($selected == $id) {
6122 $return .= '<option value="' . $id . '" selected>' . $value;
6123 } else {
6124 $return .= '<option value="' . $id . '">' . $value;
6125 }
6126 $return .= '</option>';
6127 }
6128 $return .= '</select>';
6129 if ($addjscombo) {
6130 $return .= ajax_combobox('select_' . $htmlname);
6131 }
6132
6133 return $return;
6134 }
6135
6136 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6137
6144 {
6145 // phpcs:enable
6146 global $langs;
6147
6148 $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
6149 if ($num > 0) {
6150 return $num; // Cache already loaded
6151 }
6152
6153 dol_syslog(__METHOD__, LOG_DEBUG);
6154
6155 $this->cache_transport_mode = array();
6156
6157 $sql = "SELECT rowid, code, label, active";
6158 $sql .= " FROM " . $this->db->prefix() . "c_transport_mode";
6159 $sql .= " WHERE entity IN (" . getEntity('c_transport_mode') . ")";
6160
6161 $resql = $this->db->query($sql);
6162 if ($resql) {
6163 $num = $this->db->num_rows($resql);
6164 $i = 0;
6165 while ($i < $num) {
6166 $obj = $this->db->fetch_object($resql);
6167
6168 // If traduction exist, we use it else we take the default label
6169 $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
6170 $this->cache_transport_mode[(int) $obj->rowid]
6171 = array(
6172 'rowid' => (int) $obj->rowid,
6173 'code' => (string) $obj->code,
6174 'label' => (string) $label,
6175 'active' => (int) $obj->active,
6176 );
6177 $i++;
6178 }
6179
6180 $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
6181
6182 return $num;
6183 } else {
6184 dol_print_error($this->db);
6185 return -1;
6186 }
6187 }
6188
6202 public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
6203 {
6204 global $langs, $user;
6205
6206 dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $format, LOG_DEBUG);
6207
6208 $this->load_cache_transport_mode();
6209
6210 print '<select id="select' . $htmlname . '" class="flat selectmodetransport' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
6211 if ($empty) {
6212 print '<option value="">&nbsp;</option>';
6213 }
6214 foreach ($this->cache_transport_mode as $id => $arraytypes) {
6215 // If not good status
6216 if ($active >= 0 && $arraytypes['active'] != $active) {
6217 continue;
6218 }
6219
6220 // We discard empty line if showempty is on because an empty line has already been output.
6221 if ($empty && empty($arraytypes['code'])) {
6222 continue;
6223 }
6224
6225 if ($format == 0) {
6226 print '<option value="' . $id . '"';
6227 } elseif ($format == 1) {
6228 print '<option value="' . $arraytypes['code'] . '"';
6229 } elseif ($format == 2) {
6230 print '<option value="' . $arraytypes['code'] . '"';
6231 } elseif ($format == 3) {
6232 print '<option value="' . $id . '"';
6233 }
6234 // If text is selected, we compare with code, else with id
6235 if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
6236 print ' selected';
6237 } elseif ($selected == $id) {
6238 print ' selected';
6239 }
6240 print '>';
6241 $value = '';
6242 if ($format == 0) {
6243 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
6244 } elseif ($format == 1) {
6245 $value = $arraytypes['code'];
6246 } elseif ($format == 2) {
6247 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
6248 } elseif ($format == 3) {
6249 $value = $arraytypes['code'];
6250 }
6251 print $value ? $value : '&nbsp;';
6252 print '</option>';
6253 }
6254 print '</select>';
6255
6256 print ajax_combobox("select".$htmlname);
6257
6258 if ($user->admin && !$noadmininfo) {
6259 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
6260 }
6261 }
6262
6275 public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
6276 {
6277 global $langs, $user;
6278
6279 $langs->loadLangs(array("admin", "sendings"));
6280
6281 $sql = "SELECT rowid, code, libelle as label";
6282 $sql .= " FROM " . $this->db->prefix() . "c_shipment_mode";
6283 $sql .= " WHERE active > 0";
6284 if ($filtre) {
6285 $sql .= forgeSQLFromUniversalSearchCriteria($filtre);
6286 }
6287 $sql .= " ORDER BY libelle ASC";
6288
6289 dol_syslog(get_class($this) . "::selectShippingMode", LOG_DEBUG);
6290
6291 $result = $this->db->query($sql);
6292 if ($result) {
6293 $num = $this->db->num_rows($result);
6294 $i = 0;
6295 if ($num) {
6296 print '<select id="select' . $htmlname . '" class="flat selectshippingmethod' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
6297 if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6298 print '<option value="-1">&nbsp;</option>';
6299 }
6300 while ($i < $num) {
6301 $obj = $this->db->fetch_object($result);
6302 if ($selected == $obj->rowid) {
6303 print '<option value="' . $obj->rowid . '" selected>';
6304 } else {
6305 print '<option value="' . $obj->rowid . '">';
6306 }
6307 print ($langs->trans("SendingMethod" . strtoupper($obj->code)) != "SendingMethod" . strtoupper($obj->code)) ? $langs->trans("SendingMethod" . strtoupper($obj->code)) : $obj->label;
6308 print '</option>';
6309 $i++;
6310 }
6311 print "</select>";
6312 if ($user->admin && empty($noinfoadmin)) {
6313 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
6314 }
6315
6316 print ajax_combobox('select' . $htmlname);
6317 } else {
6318 print $langs->trans("NoShippingMethodDefined");
6319 }
6320 } else {
6321 dol_print_error($this->db);
6322 }
6323 }
6324
6334 public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
6335 {
6336 global $langs;
6337
6338 $langs->load("sendings");
6339
6340 if ($htmlname != "none") {
6341 print '<form method="POST" action="' . $page . '">';
6342 print '<input type="hidden" name="action" value="setshippingmethod">';
6343 print '<input type="hidden" name="token" value="' . newToken() . '">';
6344 $this->selectShippingMethod($selected, $htmlname, '', $addempty);
6345 print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
6346 print '</form>';
6347 } else {
6348 if ($selected) {
6349 $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
6350 print $langs->trans("SendingMethod" . strtoupper($code));
6351 } else {
6352 print "&nbsp;";
6353 }
6354 }
6355 }
6356
6365 public function selectSituationInvoices($selected = '', $socid = 0)
6366 {
6367 global $langs;
6368
6369 $langs->load('bills');
6370
6371 $opt = '';
6372
6373 $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
6374 $sql .= ' FROM ' . $this->db->prefix() . 'facture';
6375 $sql .= ' WHERE entity IN (' . getEntity('invoice') . ')';
6376 $sql .= ' AND situation_counter >= 1';
6377 $sql .= ' AND fk_soc = ' . (int) $socid;
6378 $sql .= ' AND type <> 2';
6379 $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
6380 $resql = $this->db->query($sql);
6381
6382 $nbSituationInvoiceForThirdparty = 0;
6383
6384 if ($resql && $this->db->num_rows($resql) > 0) {
6385 // Last seen cycle
6386 $ref = 0;
6387 while ($obj = $this->db->fetch_object($resql)) {
6388 //Same cycle ?
6389 if ($obj->situation_cycle_ref != $ref) {
6390 // Just seen this cycle
6391 $ref = $obj->situation_cycle_ref;
6392 //not final ?
6393 if ($obj->situation_final != 1) {
6394 //Not prov?
6395 if (substr($obj->ref, 1, 4) != 'PROV') {
6396 $nbSituationInvoiceForThirdparty++;
6397
6398 if ($selected == $obj->rowid) {
6399 $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
6400 } else {
6401 $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
6402 }
6403 }
6404 }
6405 }
6406 }
6407 } else {
6408 dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
6409 }
6410
6411 if ($nbSituationInvoiceForThirdparty > 0) {
6412 $opt = '<option class="minwidth100" value="" selected>&nbsp;</option>'.$opt;
6413 } else {
6414 $opt = '<option class="minwidth100" value="-1" selected>'.$langs->trans('NoSituations').'</option>';
6415 }
6416
6417 return $opt;
6418 }
6419
6429 public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
6430 {
6431 global $langs;
6432
6433 $langs->load('products');
6434
6435 $return = '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
6436
6437 $sql = "SELECT rowid, label, code FROM " . $this->db->prefix() . "c_units";
6438 $sql .= ' WHERE active > 0';
6439 if (!empty($unit_type)) {
6440 $sql .= " AND unit_type = '" . $this->db->escape($unit_type) . "'";
6441 }
6442 $sql .= " ORDER BY sortorder";
6443
6444 $resql = $this->db->query($sql);
6445 if ($resql && $this->db->num_rows($resql) > 0) {
6446 if ($showempty) {
6447 $return .= '<option value="-1"></option>';
6448 }
6449
6450 while ($res = $this->db->fetch_object($resql)) {
6451 $unitLabel = $res->label;
6452 if (!empty($langs->tab_translate['unit' . $res->code])) { // check if Translation is available before
6453 $unitLabel = $langs->trans('unit' . $res->code) != $res->label ? $langs->trans('unit' . $res->code) : $res->label;
6454 }
6455
6456 if ($selected == $res->rowid) {
6457 $return .= '<option value="' . $res->rowid . '" selected>' . $unitLabel . '</option>';
6458 } else {
6459 $return .= '<option value="' . $res->rowid . '">' . $unitLabel . '</option>';
6460 }
6461 }
6462 $return .= '</select>';
6463
6464 $return .= ajax_combobox($htmlname);
6465 }
6466 return $return;
6467 }
6468
6469 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6470
6486 public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0, $addentrynone = 0)
6487 {
6488 // phpcs:enable
6489 global $langs;
6490
6491 $out = '';
6492
6493 $langs->loadLangs(array("admin", "banks"));
6494 $num = 0;
6495
6496 $sql = "SELECT rowid, label, bank, clos as status, currency_code";
6497 $sql .= " FROM " . $this->db->prefix() . "bank_account";
6498 $sql .= " WHERE entity IN (" . getEntity('bank_account') . ")";
6499 if ($status != 2) {
6500 $sql .= " AND clos = " . (int) $status;
6501 }
6502 if ($filtre) {
6503 $sql .= forgeSQLFromUniversalSearchCriteria($filtre);
6504 }
6505 $sql .= " ORDER BY label";
6506
6507 dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
6508 $result = $this->db->query($sql);
6509 if ($result) {
6510 $num = $this->db->num_rows($result);
6511 $i = 0;
6512
6513 $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
6514
6515 if ($num == 0) {
6516 if ($status == 0) {
6517 $out .= '<option class="opacitymedium" value="-1">' . $langs->trans("NoActiveBankAccountDefined") . '</span>';
6518 } else {
6519 $out .= '<option class="opacitymedium" value="-1">' . $langs->trans("NoBankAccountDefined") . '</span>';
6520 }
6521 } else {
6522 if (!empty($useempty) && !is_numeric($useempty)) {
6523 $out .= '<option value="-1">'.$langs->trans($useempty).'</option>';
6524 } elseif ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6525 $out .= '<option value="-1">&nbsp;</option>';
6526 }
6527 }
6528
6529 while ($i < $num) {
6530 $obj = $this->db->fetch_object($result);
6531
6532 $labeltoshow = trim($obj->label);
6533 $labeltoshowhtml = trim($obj->label);
6534 if ($showcurrency) {
6535 $labeltoshow .= ' (' . $obj->currency_code . ')';
6536 $labeltoshowhtml .= ' <span class="opacitymedium">(' . $obj->currency_code . ')</span>';
6537 }
6538 if ($status == 2 && $obj->status == 1) {
6539 $labeltoshow .= ' (' . $langs->trans("Closed") . ')';
6540 $labeltoshowhtml .= ' <span class="opacitymedium">(' . $langs->trans("Closed") . ')</span>';
6541 }
6542
6543 if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
6544 $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml).'" selected>';
6545 } else {
6546 $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml).'">';
6547 }
6548 $out .= $labeltoshow;
6549 $out .= '</option>';
6550 $i++;
6551 }
6552
6553 if (!empty($addentrynone)) {
6554 $out .= '<option value="-2"'.($selected == -2 ? ' selected="selected"' : '').' data-html="'.dolPrintHTMLForAttribute('<span class="opacitymedium">'.$langs->trans("None").'</span>').'">'.$langs->trans("None").'</option>';
6555 }
6556
6557 $out .= "</select>";
6558 $out .= ajax_combobox('select' . $htmlname);
6559 } else {
6560 dol_print_error($this->db);
6561 }
6562
6563 // Output or return
6564 if (empty($nooutput)) {
6565 print $out;
6566 } else {
6567 return $out;
6568 }
6569
6570 return $num;
6571 }
6572
6586 public function selectRib($selected = '', $htmlname = 'ribcompanyid', $filtre = '', $useempty = 0, $moreattrib = '', $showibanbic = 0, $morecss = '', $nooutput = 0)
6587 {
6588 // phpcs:enable
6589 global $langs;
6590
6591 $out = '';
6592
6593 $langs->loadLangs(array("admin", "banks"));
6594 $num = 0;
6595
6596 $sql = "SELECT rowid, label, bank, status, iban_prefix, bic, default_rib";
6597 $sql .= " FROM " . $this->db->prefix() . "societe_rib";
6598 $sql .= " WHERE type = 'ban'";
6599 if ($filtre) {
6600 $sql .= forgeSQLFromUniversalSearchCriteria($filtre);
6601 }
6602 $sql .= " ORDER BY label";
6603 dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
6604 $result = $this->db->query($sql);
6605 if ($result) {
6606 $num = $this->db->num_rows($result);
6607 $i = 0;
6608
6609 $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
6610
6611 if ($num == 0) {
6612 $out .= '<option class="opacitymedium" value="-1">' . $langs->trans("NoBankAccountDefined") . '</span>';
6613 } else {
6614 if (!empty($useempty) && !is_numeric($useempty)) {
6615 $out .= '<option value="-1">'.$langs->trans($useempty).'</option>';
6616 } elseif ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6617 $out .= '<option value="-1">&nbsp;</option>';
6618 }
6619 }
6620
6621 while ($i < $num) {
6622 $obj = $this->db->fetch_object($result);
6623 $iban = dolDecrypt($obj->iban_prefix);
6624 if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
6625 $out .= '<option value="' . $obj->rowid . '" data-iban-prefix="' . $iban . ' data-bic="' . $obj->bic . '" selected>';
6626 } else {
6627 $out .= '<option value="' . $obj->rowid . '" data-iban-prefix="' . $iban . ' data-bic="' . $obj->bic . '">';
6628 }
6629 $out .= trim($obj->label);
6630 if ($showibanbic) {
6631 $out .= ' (' . $iban . '/' .$obj->bic. ')' . ($obj->default_rib ? ' ['.$langs->trans("ByDefault").']' : '');
6632 }
6633 $out .= '</option>';
6634 $i++;
6635 }
6636 $out .= "</select>";
6637 $out .= ajax_combobox('select' . $htmlname);
6638 } else {
6639 dol_print_error($this->db);
6640 }
6641
6642 // Output or return
6643 if (empty($nooutput)) {
6644 print $out;
6645 } else {
6646 return $out;
6647 }
6648
6649 return $num;
6650 }
6651
6663 public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
6664 {
6665 global $langs;
6666
6667 $langs->load("admin");
6668 $num = 0;
6669
6670 $sql = "SELECT rowid, name, fk_country, status, entity";
6671 $sql .= " FROM " . $this->db->prefix() . "establishment";
6672 $sql .= " WHERE 1=1";
6673 if ($status != 2) {
6674 $sql .= " AND status = " . (int) $status;
6675 }
6676 if ($filtre) {
6677 $sql .= forgeSQLFromUniversalSearchCriteria($filtre);
6678 }
6679 $sql .= " ORDER BY name";
6680
6681 dol_syslog(get_class($this) . "::select_establishment", LOG_DEBUG);
6682 $result = $this->db->query($sql);
6683 if ($result) {
6684 $num = $this->db->num_rows($result);
6685 $i = 0;
6686 if ($num) {
6687 print '<select id="select' . $htmlname . '" class="flat selectestablishment" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
6688 if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6689 print '<option value="-1">&nbsp;</option>';
6690 }
6691
6692 while ($i < $num) {
6693 $obj = $this->db->fetch_object($result);
6694 if ($selected == $obj->rowid) {
6695 print '<option value="' . $obj->rowid . '" selected>';
6696 } else {
6697 print '<option value="' . $obj->rowid . '">';
6698 }
6699 print trim($obj->name);
6700 if ($status == 2 && $obj->status == 1) {
6701 print ' (' . $langs->trans("Closed") . ')';
6702 }
6703 print '</option>';
6704 $i++;
6705 }
6706 print "</select>";
6707 } else {
6708 if ($status == 0) {
6709 print '<span class="opacitymedium">' . $langs->trans("NoActiveEstablishmentDefined") . '</span>';
6710 } else {
6711 print '<span class="opacitymedium">' . $langs->trans("NoEstablishmentFound") . '</span>';
6712 }
6713 }
6714
6715 return $num;
6716 } else {
6717 dol_print_error($this->db);
6718 return -1;
6719 }
6720 }
6721
6731 public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
6732 {
6733 global $langs;
6734 if ($htmlname != "none") {
6735 print '<form method="POST" action="' . $page . '">';
6736 print '<input type="hidden" name="action" value="setbankaccount">';
6737 print '<input type="hidden" name="token" value="' . newToken() . '">';
6738 print img_picto('', 'bank_account', 'class="pictofixedwidth"');
6739 $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
6740 if ($nbaccountfound > 0) {
6741 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
6742 }
6743 print '</form>';
6744 } else {
6745 $langs->load('banks');
6746
6747 if ($selected) {
6748 require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
6749 $bankstatic = new Account($this->db);
6750 $result = $bankstatic->fetch((int) $selected);
6751 if ($result) {
6752 print $bankstatic->getNomUrl(1);
6753 }
6754 } else {
6755 print "&nbsp;";
6756 }
6757 }
6758 }
6759
6771 public function formRib($page, $selected = '', $htmlname = 'ribcompanyid', $filtre = '', $addempty = 0, $showibanbic = 0)
6772 {
6773 global $langs;
6774 if ($htmlname != "none") {
6775 print '<form method="POST" action="' . $page . '">';
6776 print '<input type="hidden" name="action" value="setbankaccountcustomer">';
6777 print '<input type="hidden" name="token" value="' . newToken() . '">';
6778 $nbaccountfound = $this->selectRib($selected, $htmlname, $filtre, $addempty, '', $showibanbic);
6779 if ($nbaccountfound > 0) {
6780 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
6781 }
6782 print '</form>';
6783 } else {
6784 $langs->load('banks');
6785
6786 if ($selected) {
6787 require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
6788 $bankstatic = new CompanyBankAccount($this->db);
6789 $result = $bankstatic->fetch((int) $selected);
6790 if ($result) {
6791 print $bankstatic->label;
6792 if ($showibanbic) {
6793 print ' (' . $bankstatic->iban . '/' .$bankstatic->bic. ')';
6794 }
6795 }
6796 } else {
6797 print "&nbsp;";
6798 }
6799 }
6800 }
6801
6811 public function selectCategories($categtype, $htmlname, $object = null)
6812 {
6813 global $langs;
6814
6815 $out = '';
6816
6817 $cate_arbo = $this->select_all_categories($categtype, '', '', 64, 0, 3);
6818
6819 $arrayselected = array();
6820 if (GETPOSTISARRAY($htmlname)) {
6821 $arrayselected = GETPOST($htmlname, 'array:int');
6822 } elseif (is_object($object) && $object->id > 0) {
6823 $c = new Categorie($this->db);
6824 $cats = $c->containing($object->id, $categtype);
6825 $arrayselected = array();
6826 foreach ($cats as $cat) {
6827 $arrayselected[] = $cat->id;
6828 }
6829 }
6830
6831 $out .= img_picto('', 'category', 'class="pictofixedwidth"');
6832 $out .= $this->multiselectarray($htmlname, $cate_arbo, $arrayselected, 0, 0, 'minwidth100 widthcentpercentminusxx', 0, 0);
6833
6834 if (!getDolGlobalString('CATEGORY_EDIT_IN_MENU_NOT_IN_POPUP')) {
6835 // Add html code to add the edit button and go back
6836 $jsonclose = 'doJsCodeAfterPopupClose'.dol_sanitizeKeyCode($htmlname).'()';
6837 $urltoopen = '/categories/categorie_list.php?type='.urlencode($categtype).'&nosearch=1';
6838
6839 $s = dolButtonToOpenUrlInDialogPopup($htmlname, $langs->transnoentitiesnoconv("Categories"), img_picto('', 'add', 'class="editfielda"'), $urltoopen, '', '', '', $jsonclose);
6840 $out .= $s;
6841 // Add js code to add the edit button and go back
6842 $out .= '<!-- Add js code to open the popup for category/edit/add -->'."\n";
6843 $out .= '<script>function doJsCodeAfterPopupClose'.dol_sanitizeKeyCode($htmlname).'() {
6844 console.log("doJsCodeAfterPopupClose'.dol_sanitizeKeyCode($htmlname).' has been called, we refresh the combo content + refresh select2...");
6845
6846 // Call an ajax to reload values and update the select
6847
6848 $.ajax({
6849 url: \''.DOL_URL_ROOT.'/core/ajax/fetchCategories.php\',
6850 data: {
6851 action: \'getCategories\',
6852 type: \''.dol_escape_htmltag($categtype).'\'
6853 },
6854 type: \'GET\',
6855 dataType: \'json\',
6856 success: function (data) {
6857 var $select = $(\'#'.dol_sanitizeKeyCode($htmlname).'\');
6858 var selectedValues = $select.val(); // This is an array of selected values
6859 console.log(selectedValues);
6860 $select.empty();
6861 $.each(data, function (index, item) {
6862 $select.append(\'<option value="\' + item.id + \'" data-html="\' + item.htmlforattribute + \'">\' + item.htmlforoption + \'</option>\');
6863 });
6864 $select.val(selectedValues);
6865 },
6866 error: function (xhr, status, error) {
6867 console.log("Error when loading ajax page : " + error);
6868 }
6869 });
6870
6871 // Refresh select2 to take account of new values (enough for small change)
6872 $("#'.dol_sanitizeKeyCode($htmlname).'").trigger("change");
6873
6874 // Alternative if change in select is complex
6875 /*
6876 $("#'.dol_sanitizeKeyCode($htmlname).'").select2("destroy");
6877 $("#'.dol_sanitizeKeyCode($htmlname).'").select2();
6878 */
6879 }</script>';
6880 }
6881
6882 return $out;
6883 }
6884
6885
6886 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6906 public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $fromid = 0, $outputmode = 0, $include = 0, $morecss = '', $useempty = 1)
6907 {
6908 // phpcs:enable
6909 global $langs;
6910
6911 include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
6912
6913 $cat = new Categorie($this->db);
6914
6915 if (is_numeric($type)) {
6916 $type = array_search($type, $cat->MAP_ID); // For backward compatibility
6917 }
6918
6919 $cate_arbo = $cat->get_full_arbo($type, $fromid, $include);
6920
6921 $outarray = array();
6922 $outarrayrichhtml = array();
6923
6924
6925 $output = '<select class="flat minwidth100' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
6926 $num = 0;
6927 if (is_array($cate_arbo)) {
6928 $num = count($cate_arbo);
6929
6930 if (!$num) {
6931 $langs->load("categories");
6932 $output .= '<option value="-1" disabled>' . $langs->trans("NoCategoriesDefined") . '</option>';
6933 } else {
6934 if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6935 $output .= '<option value="-1">&nbsp;</option>';
6936 }
6937 foreach ($cate_arbo as $key => $value) {
6938 if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
6939 $add = 'selected ';
6940 } else {
6941 $add = '';
6942 }
6943
6944 $labeltoshow = img_picto('', 'category', 'class="pictofixedwidth"'.(empty($cate_arbo[$key]['color']) ? '' : ' style="color: #' . $cate_arbo[$key]['color'] . '"'));
6945 $labeltoshow .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
6946
6947 $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
6948
6949 $outarrayrichhtml[$cate_arbo[$key]['id']] = $labeltoshow;
6950
6951 $output .= '<option ' . $add . 'value="' . $cate_arbo[$key]['id'] . '"';
6952 $output .= ' data-html="' . dol_escape_htmltag($labeltoshow) . '"';
6953 $output .= '>';
6954 // The visible (truncated) label is rendered via data-html in
6955 // templateResult of the select2 combobox; the bare option text
6956 // must keep the full label so that the select2 search matcher
6957 // (ajax_combobox in core/lib/ajax.lib.php) can find a hit on
6958 // characters that lie outside the truncated portion.
6959 $output .= dol_escape_htmltag($cate_arbo[$key]['fulllabel']);
6960 $output .= '</option>';
6961
6962 $cate_arbo[$key]['data-html'] = $labeltoshow;
6963 }
6964 }
6965 }
6966 $output .= '</select>';
6967 $output .= "\n";
6968
6969 $this->num = $num;
6970
6971 if ($outputmode == 2) {
6972 // TODO: handle error when $cate_arbo is not an array
6973 return $cate_arbo;
6974 } elseif ($outputmode == 1) {
6975 return $outarray;
6976 } elseif ($outputmode == 3) {
6977 return $outarrayrichhtml;
6978 }
6979 return $output;
6980 }
6981
6990 public function getHelpBlock($content, $icon = 'fa-question-circle')
6991 {
6992 global $langs;
6993
6994 // Sanitize content (assuming it might contain HTML, but escaping text nodes if needed)
6995 // We trust the caller to pass safe HTML or translated strings.
6996
6997 $html = '<details class="dolibarr-help-block" style="margin-top:8px;">';
6998 $html .= '<summary style="cursor:pointer; color:#0056b3; font-weight:normal; list-style:none; font-size:0.9em; display:flex; align-items:center;">';
6999 $html .= '<span class="fa ' . $icon . '" style="margin-right:6px;"></span>';
7000 $html .= $langs->trans("Help"); // Standardized title
7001 $html .= '</summary>';
7002 $html .= '<div style="margin-top:6px; padding:10px; background:#f8f9fa; border:1px solid #dee2e6; border-radius:4px; font-size:0.9em; color:#555; line-height:1.5;">';
7003 $html .= $content;
7004 $html .= '</div>';
7005 $html .= '</details>';
7006
7007 return $html;
7008 }
7009
7010 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7011
7030 public function form_confirm($page, $title, $question, $action, $formquestion = array(), $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
7031 {
7032 // phpcs:enable
7033 dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
7034 print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
7035 }
7036
7068 public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 600, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No', $helpContent = '', $labelbuttonother = '', $valuebuttonother = 'other')
7069 {
7070 global $langs, $conf;
7071
7072 $more = '';
7073 $formconfirm = '<!-- formconfirm - before call, page=' . dol_escape_htmltag($page) . ' -->';
7074
7075 $inputok = array();
7076 $inputko = array();
7077
7078 // Clean parameters
7079 $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
7080 if ($conf->browser->layout == 'phone') {
7081 $width = '95%';
7082 }
7083
7084 // Set height automatically if not defined
7085 if (empty($height)) {
7086 $height = 185;
7087 if (is_array($formquestion)) {
7088 $nbofquestions = 0;
7089 foreach ($formquestion as $input) {
7090 // Hidden fields are not visible so they must not be counted into the height
7091 if (is_array($input) && (!isset($input['type']) || $input['type'] != 'hidden')) {
7092 $nbofquestions++;
7093 }
7094 }
7095 $height += ($nbofquestions * 40);
7096 }
7097 if ($question) {
7098 $height += dol_nboflines_bis($question, 80) * 40;
7099 }
7100 }
7101
7102 if (is_array($formquestion) && !empty($formquestion)) {
7103 // First add hidden fields and value
7104 foreach ($formquestion as $key => $input) {
7105 if (is_array($input) && !empty($input)) {
7106 if ($input['type'] == 'hidden') {
7107 $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
7108 $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
7109
7110 $more .= '<input type="hidden" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '" value="' . dol_escape_htmltag(isset($input['value']) ? $input['value'] : '') . '" class="' . $morecss . '"' . $moreattr . '>' . "\n"; // 'value' non fourni par tous les appelants
7111 }
7112 }
7113 }
7114
7115 // Now add questions
7116 $moreonecolumn = '';
7117 $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">' . "\n";
7118 foreach ($formquestion as $key => $input) {
7119 if (is_array($input) && !empty($input)) {
7120 $size = (!empty($input['size']) ? ' size="' . $input['size'] . '"' : ''); // deprecated. Use morecss instead.
7121 $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
7122 $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
7123
7124 if ($input['type'] == 'text' || $input['type'] == 'input') { // traditional input
7125 $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 . ' spellcheck="false" /></div></div>' . "\n";
7126 } elseif ($input['type'] == 'password') {
7127 $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";
7128 } elseif ($input['type'] == 'textarea') {
7129 $moreonecolumn .= '<div class="margintoponly">';
7130 $moreonecolumn .= ($input['label'] ?? '') . '<br>';
7131 $moreonecolumn .= '<textarea name="' . dol_escape_htmltag($input['name']) . '" id="' . dol_escape_htmltag($input['name']) . '" class="' . $morecss . '"' . $moreattr . '>';
7132 $moreonecolumn .= $input['value'] ?? ''; // 'value' is optional (blank textarea by default), like for the 'text' and 'password' types above
7133 $moreonecolumn .= '</textarea>';
7134 $moreonecolumn .= '</div>';
7135 } elseif (in_array($input['type'], ['select', 'multiselect'])) {
7136 if (empty($morecss)) {
7137 $morecss = 'minwidth100';
7138 }
7139
7140 $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
7141 $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
7142 $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
7143 $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
7144 $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
7145 $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
7146 $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
7147
7148 $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">';
7149 if (!empty($input['label'])) {
7150 $more .= $input['label'] . '</div><div class="tagtd left">';
7151 }
7152 if ($input['type'] == 'select') {
7153 $more .= $this->selectarray($input['name'], $input['values'], isset($input['default']) ? $input['default'] : '-1', $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
7154 } else {
7155 $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);
7156 }
7157 $more .= '</div></div>' . "\n";
7158 } elseif ($input['type'] == 'checkbox') {
7159 $more .= '<div class="tagtr">';
7160 $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '"><label for="' . dol_escape_htmltag($input['name']) . '">' . $input['label'] . '</label></div><div class="tagtd">';
7161 $more .= '<input type="checkbox" class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $moreattr;
7162 if (isset($input['value']) && !is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
7163 $more .= ' checked';
7164 }
7165 if (isset($input['value']) && is_bool($input['value']) && $input['value']) {
7166 $more .= ' checked';
7167 }
7168 if (isset($input['disabled'])) {
7169 $more .= ' disabled';
7170 }
7171 $more .= ' /></div>';
7172 $more .= '</div>' . "\n";
7173 } elseif ($input['type'] == 'radio') {
7174 $i = 0;
7175 foreach ($input['values'] as $selkey => $selval) {
7176 $more .= '<div class="tagtr">';
7177 if (isset($input['label'])) {
7178 if ($i == 0) {
7179 $more .= '<div class="tagtd' . (empty($input['tdclass']) ? ' tdtop' : (' tdtop ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
7180 } else {
7181 $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' "' . $input['tdclass'])) . '">&nbsp;</div>';
7182 }
7183 }
7184 $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;
7185 if (!empty($input['disabled'])) {
7186 $more .= ' disabled';
7187 }
7188 if (isset($input['default']) && $input['default'] === $selkey) {
7189 $more .= ' checked="checked"';
7190 }
7191 $more .= ' /> ';
7192 $more .= '<label for="' . dol_escape_htmltag($input['name'] . $selkey) . '" class="valignmiddle">' . $selval . '</label>';
7193 $more .= '</div></div>' . "\n";
7194 $i++;
7195 }
7196 } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
7197 $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
7198 $more .= '<div class="tagtd">';
7199 $addnowlink = (empty($input['datenow']) ? 0 : 1);
7200 $h = $m = 0;
7201 if ($input['type'] == 'datetime') {
7202 $h = isset($input['hours']) ? $input['hours'] : 1;
7203 $m = isset($input['minutes']) ? $input['minutes'] : 1;
7204 }
7205 $more .= $this->selectDate(isset($input['value']) ? $input['value'] : -1, $input['name'], $h, $m, 0, '', 1, $addnowlink);
7206 $more .= '</div></div>'."\n";
7207 $formquestion[] = array('name' => $input['name'].'day');
7208 $formquestion[] = array('name' => $input['name'].'month');
7209 $formquestion[] = array('name' => $input['name'].'year');
7210 $formquestion[] = array('name' => $input['name'].'hour');
7211 $formquestion[] = array('name' => $input['name'].'min');
7212 } elseif ($input['type'] == 'other') { // can be 1 column or 2 depending if label is set or not
7213 $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
7214 if (!empty($input['label'])) {
7215 $more .= $input['label'] . '</div><div class="tagtd">';
7216 }
7217 if (!empty($input['value'])) {
7218 $more .= $input['value'];
7219 }
7220 $more .= '</div></div>' . "\n";
7221 } elseif ($input['type'] == 'onecolumn') {
7222 $moreonecolumn .= '<div class="margintoponly">';
7223 $moreonecolumn .= $input['value'] ?? '';
7224 $moreonecolumn .= '</div>' . "\n";
7225 } elseif ($input['type'] == 'hidden') {
7226 // Do nothing more, already added by a previous loop
7227 } elseif ($input['type'] == 'separator') {
7228 $more .= '<br>';
7229 } else {
7230 $more .= 'Error type ' . $input['type'] . ' for the confirm box is not a supported type';
7231 }
7232 }
7233 }
7234 $more .= '</div>' . "\n";
7235 $more .= $moreonecolumn;
7236 }
7237
7238 // JQUERY method dialog is broken with smartphone, we use standard HTML.
7239 // 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
7240 // See page product/card.php for example
7241 if (!empty($conf->dol_use_jmobile)) {
7242 $useajax = 0;
7243 }
7244 if (empty($conf->use_javascript_ajax)) {
7245 $useajax = 0;
7246 }
7247
7248 if ($useajax) {
7249 $autoOpen = true;
7250 $dialogconfirm = 'dialog-confirm';
7251 $button = '';
7252 if (!is_numeric($useajax)) {
7253 $button = $useajax;
7254 $useajax = 1;
7255 $autoOpen = false;
7256 $dialogconfirm .= '-' . $button;
7257 }
7258 $pageyes = $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=yes';
7259 $pageno = ($useajax == 2 ? $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=no' : '');
7260
7261 // Add input fields into list of fields to read during submit (inputok and inputko)
7262 if (is_array($formquestion)) {
7263 foreach ($formquestion as $key => $input) {
7264 //print "xx ".$key." rr ".is_array($input)."<br>\n";
7265 // Add name of fields to propagate with the GET when submitting the form with button OK.
7266 if (is_array($input) && isset($input['name'])) {
7267 if (strpos($input['name'], ',') > 0) {
7268 $inputok = array_merge($inputok, explode(',', $input['name']));
7269 } else {
7270 array_push($inputok, $input['name']);
7271 }
7272 }
7273 // Add name of fields to propagate with the GET when submitting the form with button KO.
7274 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
7275 if (is_array($input) && isset($input['inputko']) && $input['inputko'] == 1 && isset($input['name'])) {
7276 array_push($inputko, $input['name']);
7277 }
7278 }
7279 }
7280
7281 // Show JQuery confirm box.
7282 // Add 'flex-direction: column' and 'justify-content: space-between' to push content to top and buttons to bottom
7283 $formconfirm .= '<div id="' . $dialogconfirm . '" title="' . dol_escape_htmltag($title) . '" style="display: none;">';
7284 $formconfirm .= '<div style="display: flex; flex-direction: column; height: 100%;">';
7285 if (is_array($formquestion) && array_key_exists('text', $formquestion) && !empty($formquestion['text'])) {
7286 $formconfirm .= '<div class="confirmtext">' . $formquestion['text'] . '</div>' . "\n";
7287 }
7288 if (!empty($more)) {
7289 $formconfirm .= '<div class="confirmquestions">' . $more . '</div>' . "\n";
7290 }
7291 // NEW: Add help block if content provided
7292 if (!empty($helpContent)) {
7293 $formconfirm .= '<div style="text-align:left; margin-top:12px; padding-top:8px; border-top:1px solid #eee; clear:both;">';
7294 $formconfirm .= $this->getHelpBlock($helpContent);
7295 $formconfirm .= '</div>';
7296 }
7297 if (!empty($question)) {
7298 $formconfirm .= '<div class="confirmmessage" style="padding-top: 15px;">';
7299 $formconfirm .= img_help(0, '') . ' ' . $question;
7300 $formconfirm .= '</div>';
7301 }
7302 $formconfirm .= '</div>';
7303 $formconfirm .= '</div>' . "\n";
7304
7305 $formconfirm .= "\n<!-- begin code of popup for formconfirm page=" . $page . " -->\n";
7306 $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
7307 $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
7308 $formconfirm .= 'jQuery(document).ready(function() {
7309 $(function() {
7310 $( "#' . $dialogconfirm . '" ).dialog({
7311 autoOpen: ' . ($autoOpen ? "true" : "false") . ',';
7312 if ($newselectedchoice == 'no') {
7313 $formconfirm .= '
7314 open: function() {
7315 $(this).parent().find("button.ui-button:eq(2)").focus();
7316 },';
7317 }
7318
7319 $jsforcursor = '';
7320 if ($useajax == 1) {
7321 $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor' . "\n";
7322 $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");' . "\n";
7323 }
7324
7325 $postconfirmas = 'GET';
7326 $maxurllengthforget = getDolGlobalInt('MAIN_MAX_URL_LENGTH_FOR_GET', 2000);
7327
7328 // Height is auto so content is never truncated. The $height provided or calculated is used as a min height.
7329 $formconfirm .= '
7330 resizable: false,
7331 height: \'auto\',' . (is_numeric($height) ? '
7332 minHeight: ' . ((int) $height) . ',' : '') . '
7333 maxHeight: Math.round($(window).height() * 0.9),
7334 width: \'' . dol_escape_js($width) . '\',
7335 modal: true,
7336 closeOnEscape: false,
7337 buttons: [{
7338 text: \'' . dol_escape_js($langs->transnoentities($labelbuttonyes)) . '\',
7339 click: function() {
7340 var options = "token=' . urlencode(newToken()) . '";
7341 var inputok = ' . json_encode($inputok) . '; /* List of fields into form */
7342 var page = \'' . dol_escape_js(!empty($page) ? $page : '') . '\';
7343 var pageyes = \'' . dol_escape_js(!empty($pageyes) ? $pageyes : '') . '\';
7344
7345 if (inputok.length > 0) {
7346 $.each(inputok, function(i, inputname) {
7347 var more = "";
7348 var inputvalue;
7349 if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
7350 inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
7351 } else {
7352 if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
7353 inputvalue = $("#" + inputname + more).val();
7354 }
7355 if (typeof inputvalue == "undefined") { inputvalue=""; }
7356 console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
7357 options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
7358 });
7359 }
7360 var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
7361 if (pageyes.length > 0) {';
7362 if ($postconfirmas == 'GET') {
7363 $formconfirm .= 'dolSubmitConfirmForm(urljump, pageyes, options, ' . $maxurllengthforget . ');';
7364 } else {
7365 $formconfirm .= $jsforcursor;
7366 $formconfirm .= 'var post = $.post(
7367 pageyes,
7368 options,
7369 function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
7370 );';
7371 }
7372 $formconfirm .= '
7373 console.log("after post ok");
7374 }
7375 $(this).dialog("close");
7376 }
7377 }, {
7378 text: \'' . dol_escape_js($langs->transnoentities($labelbuttonno)) . '\',
7379 click: function() {
7380 var options = "token=' . urlencode(newToken()) . '";
7381 var inputko = ' . json_encode($inputko) . '; /* List of fields into form */
7382 var page = \'' . dol_escape_js(!empty($page) ? $page : '') . '\';
7383 var pageno=\'' . dol_escape_js(!empty($pageno) ? $pageno : '') . '\';
7384 if (inputko.length > 0) {
7385 $.each(inputko, function(i, inputname) {
7386 var more = "";
7387 if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
7388 var inputvalue = $("#" + inputname + more).val();
7389 if (typeof inputvalue == "undefined") { inputvalue=""; }
7390 options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
7391 });
7392 }
7393 var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
7394 //alert(urljump);
7395 if (pageno.length > 0) {';
7396 if ($postconfirmas == 'GET') {
7397 $formconfirm .= 'dolSubmitConfirmForm(urljump, pageno, options, ' . $maxurllengthforget . ');';
7398 } else {
7399 $formconfirm .= $jsforcursor;
7400 $formconfirm .= 'var post = $.post(
7401 pageno,
7402 options,
7403 function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
7404 );';
7405 }
7406 $formconfirm .= '
7407 console.log("after post ko");
7408 }
7409 $(this).dialog("close");
7410 }
7411 }';
7412 if ($labelbuttonother !== '') {
7413 $formconfirm .= ', {
7414 text: \'' . dol_escape_js($langs->transnoentities($labelbuttonother)) . '\',
7415 click: function() {';
7416 if ($valuebuttonother !== '') {
7417 $pageother = $page . (strpos($page, '?') === false ? '?' : '&') . 'action=' . urlencode($action) . '&confirm=' . urlencode($valuebuttonother);
7418 $formconfirm .= '
7419 var options = "token=' . urlencode(newToken()) . '";
7420 var inputok = ' . json_encode($inputok) . ';
7421 var fields = $(this).find(":input");
7422 $.each(inputok, function(i, inputname) {
7423 var field = fields.filter(function() { return this.id === inputname || this.name === inputname; });
7424 if (field.is(":radio, :checkbox")) { field = field.filter(":checked"); }
7425 var inputvalue = field.val();
7426 if (typeof inputvalue === "undefined") { inputvalue = ""; }
7427 options += "&" + encodeURIComponent(inputname) + "=" + encodeURIComponent(inputvalue);
7428 });
7429 var pageother = \'' . dol_escape_js($pageother) . '\';
7430 var urljump = pageother + "&" + options;
7431 dolSubmitConfirmForm(urljump, pageother, options, ' . $maxurllengthforget . ');';
7432 }
7433 $formconfirm .= '
7434 $(this).dialog("close");
7435 }
7436 }';
7437 }
7438 $formconfirm .= ']
7439 }
7440 );
7441
7442 var button = "' . $button . '";
7443 if (button.length > 0) {
7444 $( "#" + button ).click(function(e) { e.preventDefault();
7445 $("#' . $dialogconfirm . '").dialog("open");
7446 });
7447 }
7448 });
7449 });
7450 </script>';
7451 $formconfirm .= "<!-- end ajax formconfirm -->\n";
7452 } else {
7453 $formconfirm .= "\n<!-- begin formconfirm page=" . dol_escape_htmltag($page) . " -->\n";
7454
7455 if (empty($disableformtag)) {
7456 $formconfirm .= '<form method="POST" action="' . $page . '" class="notoptoleftnoright">' . "\n";
7457 }
7458
7459 $formconfirm .= '<input type="hidden" name="action" value="' . $action . '">' . "\n";
7460 $formconfirm .= '<input type="hidden" name="token" value="' . newToken() . '">' . "\n";
7461
7462 $formconfirm .= '<div class="valid">' . "\n";
7463
7464 // Line title
7465 $formconfirm .= '<div class="validtitre">';
7466 $formconfirm .= img_picto('', 'pictoconfirm') . ' ' . $title;
7467 $formconfirm .= '</div>' . "\n";
7468
7469 // Line text
7470 if (is_array($formquestion) && array_key_exists('text', $formquestion) && !empty($formquestion['text'])) {
7471 $formconfirm .= '<div class="valid">' . $formquestion['text'] . '</div>' . "\n";
7472 }
7473
7474 // Line form fields
7475 if ($more) {
7476 $formconfirm .= '<div>' . "\n";
7477 $formconfirm .= $more;
7478 $formconfirm .= '</div>' . "\n";
7479 }
7480
7481 // NEW: Help block row (between form fields and question)
7482 if (!empty($helpContent)) {
7483 $formconfirm .= '<div style="padding-top:8px; border-top:1px solid #888;">';
7484 $formconfirm .= $this->getHelpBlock($helpContent);
7485 $formconfirm .= '</div>' . "\n";
7486 }
7487
7488 // Let's add a row that acts as a spacer.
7489 $formconfirm .= '<div style="padding-top: 20px;"></div>' . "\n";
7490
7491 // Question row
7492 $formconfirm .= '<div class="inline-block">' . $question . '</div>';
7493
7494 $formconfirm .= '<div class="inline-block">';
7495 if ($labelbuttonother !== '') {
7496 foreach (array(array('confirm', 'yes', $labelbuttonyes), array('confirm', 'no', $labelbuttonno), array($valuebuttonother === '' ? 'cancel' : 'confirm', $valuebuttonother === '' ? '1' : $valuebuttonother, $labelbuttonother)) as $confirmbutton) {
7497 $formconfirm .= '<button class="button valignmiddle confirmvalidatebutton small" type="submit" name="' . $confirmbutton[0] . '" value="' . dol_escape_htmltag($confirmbutton[1]) . '"' . ($confirmbutton[0] === 'cancel' ? ' formnovalidate' : '') . '>' . dol_escape_htmltag($langs->transnoentities($confirmbutton[2])) . '</button>';
7498 }
7499 } else {
7500 $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
7501 $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="' . $langs->trans("Validate") . '">';
7502 }
7503 $formconfirm .= '</div>';
7504
7505 $formconfirm .= '</div>';
7506
7507 if (empty($disableformtag)) {
7508 $formconfirm .= "</form>\n";
7509 }
7510 $formconfirm .= '<br>';
7511
7512 if (!empty($conf->use_javascript_ajax)) {
7513 $formconfirm .= '<!-- code to disable button to avoid double clic -->';
7514 $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
7515 $formconfirm .= '
7516 $(document).ready(function () {
7517 $(".confirmvalidatebutton").off("click.formconfirm").on("click.formconfirm", function(event) {
7518 event.preventDefault();
7519 var form = $(this).closest("form");
7520 if (form.data("formconfirm-submitting")) { return; }
7521 console.log("We click on button confirmvalidatebutton");
7522 if (this.name) {
7523 if (!this.formNoValidate && !form[0].reportValidity()) { return; }
7524 $("<input>").attr({type: "hidden", name: this.name, value: this.value, "data-formconfirm-choice": "1"}).appendTo(form);
7525 }
7526 form.data("formconfirm-submitting", true);
7527 $(this).attr("disabled", "disabled");
7528 setTimeout(function() {
7529 form.removeData("formconfirm-submitting");
7530 form.find(".confirmvalidatebutton").removeAttr("disabled");
7531 form.find("[data-formconfirm-choice]").remove();
7532 }, 3000);
7533 //console.log($(this).closest("form"));
7534 form.submit();
7535 });
7536 });
7537 ';
7538 $formconfirm .= '</script>' . "\n";
7539 }
7540
7541 $formconfirm .= "<!-- end formconfirm -->\n";
7542 }
7543
7544 return $formconfirm;
7545 }
7546
7547 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7548
7565 public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '', $option = '')
7566 {
7567 // phpcs:enable
7568 global $langs;
7569
7570 require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
7571 require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
7572
7573 $out = '';
7574
7575 $formproject = new FormProjets($this->db);
7576
7577 $langs->load("project");
7578 if ($htmlname != "none") {
7579 $out .= '<form method="post" action="' . $page . '">';
7580 $out .= '<input type="hidden" name="action" value="classin">';
7581 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7582 $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
7583 $out .= '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7584 $out .= '</form>';
7585 } else {
7586 $out .= '<span class="project_head_block">';
7587 if ($selected instanceof Project) {
7588 $out .= $selected->getNomUrl(0, $option, 1);
7589 } elseif (is_numeric($selected)) {
7590 $projet = new Project($this->db);
7591 $projet->fetch((int) $selected);
7592 $out .= $projet->getNomUrl(0, $option, 1);
7593 } else {
7594 $out .= '<span class="opacitymedium">' . $textifnoproject . '</span>';
7595 }
7596 $out .= '</span>';
7597 }
7598
7599 if (empty($nooutput)) {
7600 print $out;
7601 return '';
7602 }
7603 return $out;
7604 }
7605
7606 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7607
7623 public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
7624 {
7625 // phpcs:enable
7626 global $langs;
7627
7628 $selected = (int) $selected;
7629
7630 $out = '';
7631
7632 if ($htmlname != "none") {
7633 $out .= '<form method="POST" action="' . $page . '">';
7634 $out .= '<input type="hidden" name="action" value="setconditions">';
7635 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7636 if ($type) {
7637 $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
7638 }
7639 $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
7640 $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7641 $out .= '</form>';
7642 } else {
7643 if ($selected) {
7644 $this->load_cache_conditions_paiements();
7645
7646 if (isset($this->cache_conditions_paiements[$selected])) {
7647 $label = $this->cache_conditions_paiements[$selected]['label'];
7648
7649 if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
7650 $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
7651 }
7652
7653 $out .= $label;
7654 } else {
7655 $langs->load('errors');
7656 $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions', $selected);
7657 }
7658 } else {
7659 $out .= '&nbsp;';
7660 }
7661 }
7662
7663 if (empty($nooutput)) {
7664 print $out;
7665 return '';
7666 }
7667 return $out;
7668 }
7669
7670 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7671
7682 public function form_rule_for_lines_dates($page, $selected = '', $htmlname = 'rule_for_lines_dates', $addempty = 0, $nooutput = 0): string
7683 {
7684 // phpcs:enable
7685 global $langs;
7686
7687 $out = '';
7688
7689 if ($htmlname != 'none') {
7690 $out .= '<form method="POST" action="' . $page . '">';
7691 $out .= '<input type="hidden" name="action" value="setruleforlinesdates">';
7692 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7693 $out .= $this->getSelectRuleForLinesDates($selected, $htmlname, $addempty);
7694 $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7695 $out .= '</form>';
7696 } else {
7697 if (isset($selected)) {
7698 $this->load_cache_rule_for_lines_dates();
7699 if (isset($this->cache_rule_for_lines_dates[$selected])) {
7700 $label = $this->cache_rule_for_lines_dates[$selected];
7701 $out .= $langs->trans($label);
7702 }
7703 } else {
7704 $out .= '&nbsp;';
7705 }
7706 }
7707
7708 if (empty($nooutput)) {
7709 print $out;
7710 return '';
7711 }
7712
7713 return $out;
7714 }
7715
7716 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7717
7727 public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
7728 {
7729 dol_syslog(__METHOD__, LOG_DEBUG);
7730 // phpcs:enable
7731 global $langs;
7732 if ($htmlname != "none") {
7733 print '<form method="post" action="' . $page . '">';
7734 print '<input type="hidden" name="action" value="setavailability">';
7735 print '<input type="hidden" name="token" value="' . newToken() . '">';
7736 print $this->selectAvailabilityDelay($selected, $htmlname, '', $addempty, '', 1);
7737 print '<input type="submit" name="modify" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7738 print '<input type="submit" name="cancel" class="button smallpaddingimp" value="' . $langs->trans("Cancel") . '">';
7739 print '</form>';
7740 } else {
7741 if ($selected) {
7742 $this->load_cache_availability();
7743 // @phan-suppress-next-line PhanTypeMismatchProperty
7744 if (isset($this->cache_availability[$selected])) {
7745 print $this->cache_availability[$selected]['label'];
7746 } else {
7747 print "&nbsp;";
7748 }
7749 } else {
7750 print "&nbsp;";
7751 }
7752 }
7753 }
7754
7766 public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0, $morecss = '')
7767 {
7768 global $langs;
7769 if ($htmlname != "none") {
7770 print '<form method="post" action="' . $page . '">';
7771 print '<input type="hidden" name="action" value="setdemandreason">';
7772 print '<input type="hidden" name="token" value="' . newToken() . '">';
7773 $this->selectInputReason($selected, $htmlname, '-1', $addempty, $morecss);
7774 print '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7775 print '</form>';
7776 } else {
7777 if ($selected) {
7778 $this->loadCacheInputReason();
7779 foreach ($this->cache_demand_reason as $key => $val) {
7780 if ($val['id'] == $selected) {
7781 print $val['label'];
7782 break;
7783 }
7784 }
7785 } else {
7786 print "&nbsp;";
7787 }
7788 }
7789 }
7790
7791 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7792
7806 public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
7807 {
7808 // phpcs:enable
7809 global $langs;
7810
7811 $ret = '';
7812
7813 if ($htmlname != "none") {
7814 $ret .= '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
7815 $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
7816 $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
7817 if ($type) {
7818 $ret .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
7819 }
7820 $ret .= '<table class="nobordernopadding">';
7821 $ret .= '<tr><td>';
7822 $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form' . $htmlname, 1, 0);
7823 $ret .= '</td>';
7824 $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
7825 $ret .= '</tr></table></form>';
7826 } else {
7827 if ($displayhour) {
7828 $ret .= dol_print_date($selected, 'dayhour');
7829 } else {
7830 $ret .= dol_print_date($selected, 'day');
7831 }
7832 }
7833
7834 if (empty($nooutput)) {
7835 print $ret;
7836 }
7837 return $ret;
7838 }
7839
7840
7841 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7842
7853 public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = array(), $include = array())
7854 {
7855 // phpcs:enable
7856 global $langs;
7857
7858 if ($htmlname != "none") {
7859 print '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
7860 print '<input type="hidden" name="action" value="set' . $htmlname . '">';
7861 print '<input type="hidden" name="token" value="' . newToken() . '">';
7862 print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
7863 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7864 print '</form>';
7865 } else {
7866 if ($selected) {
7867 require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
7868 $theuser = new User($this->db);
7869 $theuser->fetch((int) $selected);
7870 print $theuser->getNomUrl(1);
7871 } else {
7872 print "&nbsp;";
7873 }
7874 }
7875 }
7876
7877
7878 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7879
7894 public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0, $short = 0)
7895 {
7896 // phpcs:enable
7897 global $langs;
7898
7899 $out = '';
7900 if ($htmlname != "none") {
7901 $out .= '<form method="POST" action="' . $page . '">';
7902 $out .= '<input type="hidden" name="action" value="setmode">';
7903 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7904 if ($type) {
7905 $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
7906 }
7907 $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
7908 $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7909 $out .= '</form>';
7910 } else {
7911 if ((int) $selected) {
7912 $this->load_cache_types_paiements();
7913 if ($short) {
7914 $out .= $this->cache_types_paiements[(int) $selected]['shortlabel'] ?? '&nbsp;';
7915 } else {
7916 $out .= $this->cache_types_paiements[(int) $selected]['label'] ?? '&nbsp;';
7917 }
7918 } else {
7919 $out .= "&nbsp;";
7920 }
7921 }
7922
7923 if ($nooutput) {
7924 return $out;
7925 } else {
7926 print $out;
7927 }
7928 return '';
7929 }
7930
7941 public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
7942 {
7943 global $langs;
7944 if ($htmlname != "none") {
7945 print '<form method="POST" action="' . $page . '">';
7946 print '<input type="hidden" name="action" value="settransportmode">';
7947 print '<input type="hidden" name="token" value="' . newToken() . '">';
7948 $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
7949 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7950 print '</form>';
7951 } else {
7952 if ($selected) {
7953 $this->load_cache_transport_mode();
7954 print $this->cache_transport_mode[$selected]['label'];
7955 } else {
7956 print "&nbsp;";
7957 }
7958 }
7959 }
7960
7961 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7962
7971 public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
7972 {
7973 // phpcs:enable
7974 global $langs;
7975 if ($htmlname != "none") {
7976 print '<form method="POST" action="' . $page . '">';
7977 print '<input type="hidden" name="action" value="setmulticurrencycode">';
7978 print '<input type="hidden" name="token" value="' . newToken() . '">';
7979 print $this->selectMultiCurrency($selected, $htmlname, 0);
7980 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7981 print '</form>';
7982 } else {
7983 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
7984 print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
7985 }
7986 }
7987
7988 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7989
8000 public function form_multicurrency_rate($page, $rate = 0.0, $htmlname = 'multicurrency_tx', $currency = '', $rate_direct = 0.0)
8001 {
8002 // phpcs:enable
8003 global $langs, $conf;
8004
8005 if ($htmlname != "none") {
8006 print '<form method="POST" action="' . $page . '">';
8007 print '<input type="hidden" name="action" value="setmulticurrencyrate">';
8008 print '<input type="hidden" name="token" value="' . newToken() . '">';
8009 // Keep the value entered by the user when the page is submitted again (for example after an error)
8010 $ratetoshow = (GETPOSTISSET($htmlname) ? GETPOST($htmlname, 'alpha') : (!empty($rate) ? price(price2num($rate, 'CR')) : 1));
8011 print '<input type="text" class="maxwidth75 valignmiddle" name="' . $htmlname . '" value="' . dolPrintHTMLForAttribute((string) $ratetoshow) . '" spellcheck="false" /> ';
8012 $arraycalculationmode = array(
8013 1 => 'Change ' . $langs->trans("PriceUHT") . ' of lines',
8014 2 => 'Change ' . $langs->trans("PriceUHTCurrency") . ' of lines'
8015 );
8016 print '<select name="calculation_mode" id="calculation_mode">';
8017 // With several choices, no choice is preselected so the user must select one, with no risk of a wrong default
8018 if (count($arraycalculationmode) > 1) {
8019 print '<option value="-1">&nbsp;</option>';
8020 }
8021 foreach ($arraycalculationmode as $key => $val) {
8022 print '<option value="' . $key . '">' . $val . '</option>';
8023 }
8024 print '</select> ';
8025 print ajax_combobox("calculation_mode");
8026 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
8027 print '</form>';
8028 } else {
8029 if (!empty($rate)) {
8030 print price($rate, 1, $langs, 0, 0);
8031 if ($currency && $rate != 1) {
8037 if (getDolGlobalString('MULTICURRENCY_USE_RATE_DIRECT')) {
8038 print ' &nbsp; <span class="opacitymedium">(' . price($rate_direct, 1, $langs, 0, 0) . ' ' . $conf->currency . ' = 1 ' . $currency . ')</span>';
8039 } else {
8040 print ' &nbsp; <span class="opacitymedium">(' . price($rate, 1, $langs, 0, 0) . ' ' . $currency . ' = 1 ' . $conf->currency . ')</span>';
8041 }
8042 }
8043 } else {
8044 print 1;
8045 }
8046 }
8047 }
8048
8049 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8050
8068 public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0, $filterabsolutediscount = 0, $filtercreditnote = 0)
8069 {
8070 // phpcs:enable
8071 global $conf, $langs;
8072
8073 if ($htmlname != "none") {
8074 print '<form method="post" action="' . $page . '" class="inline-block">';
8075 print '<input type="hidden" name="action" value="setabsolutediscount">';
8076 print '<input type="hidden" name="token" value="' . newToken() . '">';
8077 print '<div class="inline-block">';
8078 if (!empty($discount_type)) {
8079 if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
8080 if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
8081 $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be subtracted to payments only and not to total of final invoice
8082 } else {
8083 $translationKey = 'HasCreditNoteFromSupplier';
8084 }
8085 } else {
8086 if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
8087 $translationKey = 'HasAbsoluteDiscountFromSupplier';
8088 } else {
8089 $translationKey = 'HasCreditNoteFromSupplier';
8090 }
8091 }
8092 } else {
8093 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
8094 if (!$filter || $filter == "fk_facture_source IS NULL") {
8095 $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be subtracted to payments only and not to total of final invoice
8096 } else {
8097 $translationKey = 'CompanyHasCreditNote';
8098 }
8099 } else {
8100 if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
8101 $translationKey = 'CompanyHasAbsoluteDiscount';
8102 } else {
8103 $translationKey = 'CompanyHasCreditNote';
8104 }
8105 }
8106 }
8107 print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
8108 if (empty($hidelist)) {
8109 print ' ';
8110 }
8111 print '</div>';
8112 if (empty($hidelist)) {
8113 print '<div class="inline-block" style="padding-right: 10px">';
8114 $newfilter = 'discount_type = ' . intval($discount_type);
8115 if (!empty($discount_type)) {
8116 $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
8117 } else {
8118 $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
8119 }
8120 if ($filter) {
8121 $sanitizedfilter = $filter; // @phan-suppress-current-line SqlInjection
8122 $newfilter .= ' AND (' . $sanitizedfilter . ')';
8123 }
8124 // output the combo of discounts
8125 $nbqualifiedlines = $this->select_remises((string) $selected, $htmlname, $newfilter, $socid, $maxvalue);
8126 if ($nbqualifiedlines > 0) {
8127 print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("UseLine")) . '"';
8128 if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
8129 print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
8130 }
8131 if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
8132 print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
8133 }
8134
8135 print '>';
8136 }
8137 print '</div>';
8138 }
8139 if ($more) {
8140 print '<div class="inline-block">';
8141 print $more;
8142 print '</div>';
8143 }
8144 print '</form>';
8145 } else {
8146 if ($selected) {
8147 print $selected;
8148 } else {
8149 print "0";
8150 }
8151 }
8152 }
8153
8154
8155 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8156
8166 public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
8167 {
8168 // phpcs:enable
8169 global $langs;
8170
8171 if ($htmlname != "none") {
8172 print '<form method="post" action="' . $page . '">';
8173 print '<input type="hidden" name="action" value="set_contact">';
8174 print '<input type="hidden" name="token" value="' . newToken() . '">';
8175 print '<table class="nobordernopadding">';
8176 print '<tr><td>';
8177 print $this->selectcontacts($societe->id, $selected, $htmlname);
8178 $num = $this->num;
8179 if ($num == 0) {
8180 $addcontact = (getDolGlobalString('SOCIETE_ADDRESSES_MANAGEMENT') ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
8181 print '<a href="' . DOL_URL_ROOT . '/contact/card.php?socid=' . $societe->id . '&action=create&backtoreferer=1">' . $addcontact . '</a>';
8182 }
8183 print '</td>';
8184 print '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
8185 print '</tr></table></form>';
8186 } else {
8187 if ($selected) {
8188 require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
8189 $contact = new Contact($this->db);
8190 $contact->fetch((int) $selected);
8191 print $contact->getFullName($langs);
8192 } else {
8193 print "&nbsp;";
8194 }
8195 }
8196 }
8197
8198 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8199
8216 public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
8217 {
8218 // phpcs:enable
8219 global $langs;
8220
8221 $out = '';
8222 if ($htmlname != "none") {
8223 $limit = getDolGlobalInt('THIRDPARTY_LIMIT_SIZE');
8224
8225 $out .= '<form method="post" action="' . $page . '">';
8226 $out .= '<input type="hidden" name="action" value="set_thirdparty">';
8227 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
8228 $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, $limit, 'minwidth100', '', '', 1, array(), false, $excludeids);
8229 $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
8230 $out .= '</form>';
8231 } else {
8232 if ($selected) {
8233 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
8234 $soc = new Societe($this->db);
8235 $soc->fetch((int) $selected);
8236 $out .= $soc->getNomUrl(0, '');
8237 } else {
8238 $out .= '<span class="opacitymedium">' . $textifnothirdparty . '</span>';
8239 }
8240 }
8241
8242 if ($nooutput) {
8243 return $out;
8244 } else {
8245 print $out;
8246 }
8247
8248 return '';
8249 }
8250
8251 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8252
8261 public function select_currency($selected = '', $htmlname = 'currency_id')
8262 {
8263 // phpcs:enable
8264 print $this->selectCurrency($selected, $htmlname);
8265 }
8266
8276 public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
8277 {
8278 global $langs, $user;
8279
8280 $langs->loadCacheCurrencies('');
8281
8282 $out = '';
8283
8284 if ($selected == 'euro' || $selected == 'euros') {
8285 $selected = 'EUR'; // Pour compatibilite
8286 }
8287
8288 $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="' . $htmlname . '" id="' . $htmlname . '">';
8289 if ($useempty) {
8290 $out .= '<option value="-1" selected></option>';
8291 }
8292 foreach ($langs->cache_currencies as $code_iso => $currency) {
8293 $labeltoshow = $currency['label'];
8294 if ($mode == 1) {
8295 $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso . ')</span>';
8296 } elseif ($mode == 2) {
8297 $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso.' - '.$langs->getCurrencySymbol($code_iso) . ')</span>';
8298 } else {
8299 $labeltoshow .= ' <span class="opacitymedium">(' . $langs->getCurrencySymbol($code_iso) . ')</span>';
8300 }
8301
8302 if ($selected && $selected == $code_iso) {
8303 $out .= '<option value="' . $code_iso . '" selected data-html="' . dol_escape_htmltag($labeltoshow) . '">';
8304 } else {
8305 $out .= '<option value="' . $code_iso . '" data-html="' . dol_escape_htmltag($labeltoshow) . '">';
8306 }
8307 $out .= dol_string_nohtmltag($labeltoshow);
8308 $out .= '</option>';
8309 }
8310 $out .= '</select>';
8311 if ($user->admin) {
8312 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
8313 }
8314
8315 // Make select dynamic
8316 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
8317 $out .= ajax_combobox($htmlname);
8318
8319 return $out;
8320 }
8321
8334 public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = 'maxwidth200 widthcentpercentminusx')
8335 {
8336 global $conf, $langs;
8337
8338 $langs->loadCacheCurrencies(''); // Load ->cache_currencies
8339
8340 $TCurrency = array();
8341
8342 $sql = "SELECT code FROM " . $this->db->prefix() . "multicurrency";
8343 $sql .= " WHERE entity IN ('" . getEntity('multicurrency') . "')";
8344 if ($filter) {
8345 $sql .= forgeSQLFromUniversalSearchCriteria($filter);
8346 }
8347 $resql = $this->db->query($sql);
8348 if ($resql) {
8349 while ($obj = $this->db->fetch_object($resql)) {
8350 $TCurrency[$obj->code] = $obj->code;
8351 }
8352 }
8353
8354 $out = '';
8355 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
8356 if ($useempty) {
8357 $out .= '<option value="">&nbsp;</option>';
8358 }
8359 // If company current currency not in table, we add it into list. Should always be available.
8360 if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
8361 $TCurrency[$conf->currency] = $conf->currency;
8362 }
8363 if (count($TCurrency) > 0) {
8364 foreach ($langs->cache_currencies as $code_iso => $currency) {
8365 if (isset($TCurrency[$code_iso])) {
8366 if (!empty($selected) && $selected == $code_iso) {
8367 $out .= '<option value="' . $code_iso . '" selected="selected">';
8368 } else {
8369 $out .= '<option value="' . $code_iso . '">';
8370 }
8371
8372 $out .= $currency['label'];
8373 $out .= ' (' . $langs->getCurrencySymbol($code_iso) . ')';
8374 $out .= '</option>';
8375 }
8376 }
8377 }
8378
8379 $out .= '</select>';
8380
8381 // Make select dynamic
8382 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
8383 $out .= ajax_combobox($htmlname);
8384
8385 return $out;
8386 }
8387
8388 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8389
8396 public function load_cache_vatrates($country_code)
8397 {
8398 // phpcs:enable
8399 global $langs, $user, $hookmanager;
8400
8401 $num = count($this->cache_vatrates);
8402 if ($num > 0) {
8403 return $num; // Cache already loaded
8404 }
8405
8406 dol_syslog(__METHOD__, LOG_DEBUG);
8407
8408 // entity and fk_pays are returned so a hook on loadDictionaryCache can tell two rows apart
8409 // when the dictionary is read across entities (most rows carry an empty code)
8410 $sql = "SELECT t.rowid, t.entity, t.fk_pays, t.type_vat, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly, t.einvoice_vatex";
8411 $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
8412 $sql .= " WHERE t.fk_pays = c.rowid";
8413 $sql .= " AND t.active > 0";
8414 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
8415 $sql .= " AND c.code IN (" . $this->db->sanitize($country_code, 1) . ")";
8416 $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
8417
8418 $resql = $this->db->query($sql);
8419 if ($resql) {
8420 $num = $this->db->num_rows($resql);
8421 if ($num) {
8422 for ($i = 0; $i < $num; $i++) {
8423 $obj = $this->db->fetch_object($resql);
8424
8425 $tmparray = array();
8426 $tmparray['rowid'] = (int) $obj->rowid;
8427 $tmparray['entity'] = (int) $obj->entity;
8428 $tmparray['fk_pays'] = (int) $obj->fk_pays;
8429 $tmparray['type_vat'] = ($obj->type_vat <= 0 ? 0 : $obj->type_vat); // Some version have type_vat corrupted with value -1
8430 $tmparray['code'] = $obj->code;
8431 $tmparray['txtva'] = $obj->taux;
8432 $tmparray['nprtva'] = $obj->recuperableonly;
8433 $tmparray['localtax1'] = $obj->localtax1;
8434 $tmparray['localtax1_type'] = $obj->localtax1_type;
8435 $tmparray['localtax2'] = $obj->localtax2;
8436 $tmparray['localtax2_type'] = $obj->localtax1_type;
8437 $tmparray['einvoice_vatex'] = $obj->einvoice_vatex;
8438
8439 $tmparray['label'] = $obj->taux . '%' . ($obj->code ? ' (' . $obj->code . ')' : ''); // Label must contains only 0-9 , . % or *
8440 $tmparray['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
8441 $positiverates = '';
8442 if ($obj->taux) {
8443 $positiverates .= ($positiverates ? '/' : '') . $obj->taux;
8444 }
8445 if ($obj->localtax1) {
8446 $positiverates .= ($positiverates ? '/' : '') . $obj->localtax1;
8447 }
8448 if ($obj->localtax2) {
8449 $positiverates .= ($positiverates ? '/' : '') . $obj->localtax2;
8450 }
8451 if (empty($positiverates)) {
8452 $positiverates = '0';
8453 }
8454 $tmparray['labelpositiverates'] = $positiverates . ($obj->code ? ' (' . $obj->code . ')' : ''); // Must never be used as key, only label
8455
8456 $this->cache_vatrates[$obj->rowid] = $tmparray;
8457 }
8458
8459 $parameters = array('dictionary' => 'vatrate', 'country_code' => $country_code);
8460 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
8461 if (empty($reshook)) {
8462 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
8463 $this->cache_vatrates = array_merge($this->cache_vatrates, $hookmanager->resArray);
8464 }
8465 } else {
8466 $this->cache_vatrates = $hookmanager->resArray;
8467 }
8468
8469 return count($this->cache_vatrates);
8470 } else {
8471 $this->error = '<span class="error">';
8472 $this->error .= $langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code);
8473 $reg = array();
8474 if (!empty($user) && $user->admin && preg_match('/\'(..)\'/', $country_code, $reg)) {
8475 $langs->load("errors");
8476 $new_country_code = $reg[1];
8477 $country_id = dol_getIdFromCode($this->db, $new_country_code, 'c_country', 'code', 'rowid');
8478 $this->error .= '<br>'.$langs->trans("ErrorFixThisHere", DOL_URL_ROOT.'/admin/dict.php?id=10'.($country_id > 0 ? '&countryidforinsert='.$country_id : ''));
8479 }
8480 $this->error .= '</span>';
8481 return -1;
8482 }
8483 } else {
8484 $this->error = '<span class="error">' . $this->db->error() . '</span>';
8485 return -2;
8486 }
8487 }
8488
8489 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8490
8513 public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = null, $societe_acheteuse = null, $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0, $type_vat = 0)
8514 {
8515 // phpcs:enable
8516 global $langs, $mysoc, $hookmanager;
8517
8518 $langs->load('errors');
8519
8520 $return = '';
8521 // Bypass the default method
8522 $hookmanager->initHooks(array('commonobject'));
8523 $info_bits == 1 ? $is_npr = 1 : $is_npr = 0;
8524 $parameters = array(
8525 'htmlname' => $htmlname,
8526 'selectedrate' => $selectedrate,
8527 'seller' => $societe_vendeuse,
8528 'buyer' => $societe_acheteuse,
8529 'idprod' => $idprod,
8530 'is_npr' => $is_npr,
8531 'type' => $type,
8532 'options_only' => $options_only,
8533 'mode' => $mode,
8534 'type_vat' => $type_vat
8535 );
8536 $reshook = $hookmanager->executeHooks('load_tva', $parameters);
8537 if ($reshook > 0) {
8538 return $hookmanager->resPrint;
8539 } elseif ($reshook === 0) {
8540 $return .= $hookmanager->resPrint;
8541 }
8542
8543 // Define defaultnpr, defaultttx and defaultcode
8544 $defaultnpr = ($info_bits & 0x01);
8545 $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
8546 $defaulttx = str_replace('*', '', $selectedrate);
8547 $defaultcode = '';
8548 $reg = array();
8549 if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
8550 $defaultcode = $reg[1];
8551 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
8552 }
8553 //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
8554
8555 // Check parameters
8556 if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
8557 if ($societe_vendeuse->id == $mysoc->id) {
8558 $return .= '<span class="error">' . $langs->trans("ErrorYourCountryIsNotDefined") . '</span>';
8559 } else {
8560 $return .= '<span class="error">' . $langs->trans("ErrorSupplierCountryIsNotDefined") . '</span>';
8561 }
8562 return $return;
8563 }
8564
8565 //var_dump($societe_acheteuse);
8566 //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";
8567 //exit;
8568
8569 // Define list of countries to use to search VAT rates to show
8570 // First we defined code_country to use to find list.
8571 // country_code must be a c_country ISO code (e.g. 'FR', 'CH'). In some setups it may hold a
8572 // country label (e.g. 'Suisse') instead, which would make the "c.code IN (...)" lookup done by
8573 // load_cache_vatrates() match nothing and wrongly force the VAT rate to 0%. A valid ISO code is
8574 // always 2 chars, so when the value is not a well formed ISO code (empty or a label) and we have
8575 // a valid country id, we recover the ISO code from the authoritative country id. This way we do
8576 // not run any SQL on each page access when we already have a valid ISO code.
8577 $sellercountrycode = is_object($societe_vendeuse) ? $societe_vendeuse->country_code : $mysoc->country_code;
8578 $sellercountryid = is_object($societe_vendeuse) ? $societe_vendeuse->country_id : $mysoc->country_id;
8579 if ((int) $sellercountryid > 0 && strlen((string) $sellercountrycode) != 2) {
8580 $tmpcountrycode = dol_getIdFromCode($this->db, (string) $sellercountryid, 'c_country', 'rowid', 'code');
8581 if (!empty($tmpcountrycode) && !is_numeric($tmpcountrycode)) {
8582 $sellercountrycode = $tmpcountrycode;
8583 }
8584 }
8585 $code_country = "'" . $sellercountrycode . "'"; // Pour compatibilite ascendente
8586
8587 if ($societe_vendeuse == $mysoc && getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) { // If option to have vat for end customer for services is on
8588 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
8589 // If SERVICE_ARE_ECOMMERCE_200238EC=1 combo list vat rate of purchaser and seller countries
8590 // If SERVICE_ARE_ECOMMERCE_200238EC=2 combo list only the vat rate of the purchaser country
8591 $selectVatComboMode = getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC');
8592 if (is_object($societe_vendeuse) && is_object($societe_acheteuse) && isInEEC($societe_vendeuse) && isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()) {
8593 // We also add the buyer country code
8594 if (is_numeric($type)) {
8595 if ($type == 1) { // We know product is a service
8596 switch ($selectVatComboMode) {
8597 case '1':
8598 $code_country .= ",'" . $societe_acheteuse->country_code . "'";
8599 break;
8600 case '2':
8601 $code_country = "'" . $societe_acheteuse->country_code . "'";
8602 break;
8603 }
8604 }
8605 } elseif (!$idprod) { // We don't know type of product
8606 switch ($selectVatComboMode) {
8607 case '1':
8608 $code_country .= ",'" . $societe_acheteuse->country_code . "'";
8609 break;
8610 case '2':
8611 $code_country = "'" . $societe_acheteuse->country_code . "'";
8612 break;
8613 }
8614 } else {
8615 $prodstatic = new Product($this->db);
8616 $prodstatic->fetch($idprod);
8617 if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
8618 $code_country .= ",'" . $societe_acheteuse->country_code . "'";
8619 }
8620 }
8621 }
8622 }
8623
8624 // Now we load the list of VAT
8625 $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
8626
8627 // Keep only the VAT qualified for $type_vat (0 means all types)
8628 $arrayofvatrates = array();
8629 foreach ($this->cache_vatrates as $cachevalue) {
8630 if ($type_vat == 0 || empty($cachevalue['type_vat']) || $cachevalue['type_vat'] == $type_vat) {
8631 $arrayofvatrates[] = $cachevalue;
8632 }
8633 }
8634
8635 $num = count($arrayofvatrates);
8636 if ($num > 0) {
8637 // Define the vat rate to preselect (if defaulttx not forced so is -1 or '')
8638 if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
8639 // Define a default thirdparty to use if the seller or buyer is not defined
8640 $tmpthirdparty = new Societe($this->db);
8641 $tmpthirdparty->country_code = $mysoc->country_code;
8642
8643 $defaulttx = get_default_tva(is_object($societe_vendeuse) ? $societe_vendeuse : $tmpthirdparty, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
8644 $defaultnpr = get_default_npr(is_object($societe_vendeuse) ? $societe_vendeuse : $tmpthirdparty, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
8645
8646 if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
8647 $defaultcode = $reg[1];
8648 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
8649 }
8650 if (empty($defaulttx)) {
8651 $defaultnpr = 0;
8652 }
8653 }
8654
8655 // If we fails to find a default vat rate, we take the last one in list
8656 // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
8657 if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
8658 if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
8659 // We take the last one found in list
8660 $defaulttx = $arrayofvatrates[$num - 1]['txtva'];
8661 } else {
8662 // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
8663 $defaulttx = '';
8664 if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
8665 $defaulttx = getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS');
8666 }
8667 if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
8668 $defaultcode = $reg[1];
8669 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
8670 }
8671 }
8672 }
8673
8674 // Disabled is true if the seller is not subject to VAT
8675 $disabled = false;
8676 $title = '';
8677 if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && empty($societe_vendeuse->tva_assuj)) {
8678 // When we are seller and we do not use VAT, we want to force to disable VAT selection, except if EXPENSEREPORT_OVERRIDE_VAT is set
8679 // EXPENSEREPORT_OVERRIDE_VAT is a strange option that allow to override/enable VAT regardless of sellet vat option - needed for expense report if
8680 // expense report used for business expenses instead of using supplier invoices (but this is a very bad idea !)
8681 if (!getDolGlobalString('EXPENSEREPORT_OVERRIDE_VAT')) {
8682 $title = ' title="' . dol_escape_htmltag($langs->trans('VATIsNotUsed')) . '"';
8683 $disabled = true;
8684 }
8685 }
8686
8687 if (!$options_only) {
8688 $return .= '<select class="flat valignmiddle minwidth75imp maxwidth100 right" id="' . $htmlname . '" name="' . $htmlname . '"' . ($disabled ? ' disabled' : '') . $title . '>';
8689 }
8690
8691 $selectedfound = false;
8692 foreach ($arrayofvatrates as $rate) {
8693 // Keep only 0 if seller is not subject to VAT
8694 if ($disabled && $rate['txtva'] != 0) {
8695 continue;
8696 }
8697
8698 // Define key to use into select list
8699 $key = $rate['txtva'];
8700 $key .= $rate['nprtva'] ? '*' : '';
8701 if ($mode > 0 && $rate['code']) {
8702 $key .= ' (' . $rate['code'] . ')';
8703 }
8704 if ($mode < 0) {
8705 $key = $rate['rowid'];
8706 }
8707
8708 $return .= '<option value="' . $key . '" data-vatid="'.$rate['rowid'].'"';
8709 if (!$selectedfound) {
8710 if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
8711 if ($defaultcode == $rate['code']) {
8712 $return .= ' selected';
8713 $selectedfound = true;
8714 }
8715 } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
8716 $return .= ' selected';
8717 $selectedfound = true;
8718 }
8719 }
8720 $return .= '>';
8721
8722 // Show label of VAT
8723 if ($mysoc->country_code == 'IN' || getDolGlobalString('MAIN_VAT_LABEL_IS_POSITIVE_RATES')) {
8724 // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
8725 $return .= $rate['labelpositiverates'];
8726 } else {
8727 // Simple label
8728 $return .= vatrate($rate['label']);
8729 }
8730
8731 //$return.=($rate['code']?' '.$rate['code']:'');
8732 $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
8733
8734 $return .= '</option>';
8735 }
8736
8737 if (!$options_only) {
8738 $return .= '</select>';
8739 //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
8740 }
8741 } else {
8742 $return .= $this->error;
8743 }
8744
8745 $this->num = $num;
8746 return $return;
8747 }
8748
8749
8750 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8751
8776 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 = 0, $addplusone = '', $adddateof = '')
8777 {
8778 // phpcs:enable
8779 dol_syslog(__METHOD__ . ': using select_date is deprecated. Use selectDate instead.', LOG_WARNING);
8780 $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
8781 if (!empty($nooutput)) {
8782 return $retstring;
8783 }
8784 print $retstring;
8785
8786 return '';
8787 }
8788
8804 public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
8805 {
8806 global $langs;
8807
8808 $ret = $this->selectDate($set_time, $prefix . '_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
8809 if ($forcenewline) {
8810 $ret .= '<br>';
8811 }
8812 $ret .= $this->selectDate($set_time_end, $prefix . '_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
8813 return $ret;
8814 }
8815
8844 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', $calendarpicto = '')
8845 {
8846 global $conf, $langs;
8847
8848 if ($gm === 'auto') {
8849 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
8850 }
8851
8852 $retstring = '';
8853
8854 if ($prefix == '') {
8855 $prefix = 're';
8856 }
8857 if ($h == '') {
8858 $h = 0;
8859 }
8860 if ($m == '') {
8861 $m = 0;
8862 }
8863 $emptydate = 0;
8864 $emptyhours = 0;
8865 if ($stepminutes <= 0 || $stepminutes > 30) {
8866 $stepminutes = 1;
8867 }
8868 if ($empty == 1) {
8869 $emptydate = 1;
8870 $emptyhours = 1;
8871 }
8872 if ($empty == 2) {
8873 $emptydate = 0;
8874 $emptyhours = 1;
8875 }
8876 $orig_set_time = $set_time;
8877
8878 if ($set_time === '' && $emptydate == 0) {
8879 include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
8880 if ($gm == 'tzuser' || $gm == 'tzuserrel') {
8881 $set_time = dol_now($gm);
8882 } else {
8883 $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
8884 }
8885 }
8886
8887 // Analysis of the preselected date
8888 $reg = array();
8889 $shour = '';
8890 $smin = '';
8891 $ssec = '';
8892 if (!empty($set_time) && preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', (string) $set_time, $reg)) { // deprecated usage
8893 // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
8894 $syear = (!empty($reg[1]) ? $reg[1] : '');
8895 $smonth = (!empty($reg[2]) ? $reg[2] : '');
8896 $sday = (!empty($reg[3]) ? $reg[3] : '');
8897 $shour = (!empty($reg[4]) ? $reg[4] : '');
8898 $smin = (!empty($reg[5]) ? $reg[5] : '');
8899 } elseif (strval($set_time) != '' && $set_time != -1) {
8900 // set_time est un timestamps (0 possible)
8901 $syear = dol_print_date($set_time, "%Y", $gm);
8902 $smonth = dol_print_date($set_time, "%m", $gm);
8903 $sday = dol_print_date($set_time, "%d", $gm);
8904 if ($orig_set_time != '') {
8905 $shour = dol_print_date($set_time, "%H", $gm);
8906 $smin = dol_print_date($set_time, "%M", $gm);
8907 $ssec = dol_print_date($set_time, "%S", $gm);
8908 }
8909 } else {
8910 // Date est '' ou vaut -1
8911 $syear = '';
8912 $smonth = '';
8913 $sday = '';
8914 $shour = getDolGlobalString('MAIN_DEFAULT_DATE_HOUR', ($h == -1 ? '23' : ''));
8915 $smin = getDolGlobalString('MAIN_DEFAULT_DATE_MIN', ($h == -1 ? '59' : ''));
8916 $ssec = getDolGlobalString('MAIN_DEFAULT_DATE_SEC', ($h == -1 ? '59' : ''));
8917 }
8918 if ($h == 3 || $h == 4) {
8919 $shour = '';
8920 }
8921 if ($m == 3) {
8922 $smin = '';
8923 }
8924
8925 $nowgmt = dol_now('gmt');
8926 //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
8927
8928 // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
8929 $usecalendar = 'combo';
8930 if (!empty($conf->use_javascript_ajax) && (!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') != "none")) {
8931 $usecalendar = ((!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') == 'eldy') ? 'jquery' : getDolGlobalString("MAIN_POPUP_CALENDAR"));
8932 }
8933 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
8934 // If we use a text browser or screen reader, we use the 'combo' date selector
8935 $usecalendar = 'html';
8936 }
8937
8938 if ($d) {
8939 // Show date with popup
8940 if ($usecalendar != 'combo') {
8941 // Set $format and $formatjs and $formatjquery
8942 $reduceformat = (!empty($conf->dol_optimize_smallscreen) ? 1 : 0); // Test on original $format param.
8943 if ($reduceformat) {
8944 $format = str_replace('%Y', '%y', $langs->transnoentitiesnoconv("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
8945 $formatjslong = $langs->transnoentitiesnoconv("FormatDateShortJavaInput"); // don't trust the name
8946 $formatjs = str_replace('yyyy', 'yy', $langs->transnoentitiesnoconv("FormatDateShortJavaInput"));
8947 $formatjquery = str_replace('yyyy', 'yy', $langs->trans("FormatDateShortJQueryInput"));
8948 } else {
8949 $format = $langs->transnoentitiesnoconv("FormatDateShortInput"); // FormatDateShortInput for dol_print_date is same than FormatDateShortJavaInput for javascript
8950 $formatjslong = $langs->transnoentitiesnoconv("FormatDateShortJavaInput"); // don't trust the name
8951 $formatjs = $langs->transnoentitiesnoconv("FormatDateShortJavaInput"); // FormatDateShortInput for dol_print_date is same than FormatDateShortJavaInput for javascript
8952 $formatjquery = $langs->trans("FormatDateShortJQueryInput");
8953 }
8954
8955 // Set formatted_date (for example: '%d/%m/%Y', '%m-%d-%y', ...
8956 $formatted_date = '';
8957 if (strval($set_time) != '' && $set_time != -1) {
8958 $formatted_date = dol_print_date($set_time, $format, $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
8959 }
8960
8961 // Calendrier popup version eldy
8962 if ($usecalendar == "eldy") {
8963 // To have this manager working back, you must retrieve all functions showDP child found into the lib_head.js of v4 for example
8964 // and load the js that contains them so the call of showDP will works.
8965 /*
8966 // Input area to enter date manually
8967 $retstring .= '<!-- datepicker usecalendar=eldy --><input id="' . $prefix . '" name="' . $prefix . '" type="text" class="maxwidthdate center" maxlength="11" value="' . $formatted_date . '"';
8968 $retstring .= ($disabled ? ' disabled' : '');
8969 $retstring .= ' onChange="dpChangeDay(\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($formatjslong")) . '\'); "'; // FormatDateShortInput for dol_print_date is same than FormatDateShortJavaInput for javascript
8970 $retstring .= ' autocomplete="off">';
8971
8972 // Icon calendar
8973 $retstringbuttom = '';
8974 if (!$disabled) {
8975 $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons"';
8976 $base = DOL_URL_ROOT . '/core/';
8977 $retstringbuttom .= ' onClick="showDP(\'' . dol_escape_js($base) . '\',\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($langs->trans("FormatDateShortJavaInput")) . '\',\'' . dol_escape_js($langs->defaultlang) . '\');"';
8978 $retstringbuttom .= '>' . img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink paddingright"') . '</button>';
8979 } else {
8980 $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink paddingright"') . '</button>';
8981 }
8982 $retstring = $retstringbuttom . $retstring;
8983
8984 $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
8985 $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
8986 $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
8987 */
8988 } elseif ($usecalendar == 'jquery' || $usecalendar == 'html') {
8989 if (!$disabled && $usecalendar != 'html') {
8990 // Output javascript for datepicker
8991 $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (idate('Y') - 100));
8992 $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (idate('Y') + 100));
8993
8994 $retstring .= '<!-- datepicker usecalendar='.$usecalendar.' --><script nonce="' . getNonce() . '" type="text/javascript">';
8995 $retstring .= "$(function(){ $('#" . $prefix . "').datepicker({
8996 dateFormat: '" . dol_escape_js($formatjquery) . "',
8997 autoclose: true,
8998 todayHighlight: true,
8999 yearRange: '" . $minYear . ":" . $maxYear . "',";
9000 if (!empty($conf->dol_use_jmobile)) {
9001 $retstring .= "
9002 beforeShow: function (input, datePicker) {
9003 input.disabled = true;
9004 },
9005 onClose: function (dateText, datePicker) {
9006 this.disabled = false;
9007 },
9008 ";
9009 }
9010 // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
9011 if (!getDolGlobalString('MAIN_POPUP_CALENDAR_ON_FOCUS')) {
9012 $buttonImage = $calendarpicto ?: DOL_URL_ROOT . "/theme/" . dol_escape_js($conf->theme) . "/img/object_calendarday.png"; // Correctly wrapped in '' below @phan-suppress-current-line FunctionMissingSingleQuoteWrapping
9013 $retstring .= "
9014 showOn: 'button', /* both has problem with autocompletion */
9015 buttonImage: '" . $buttonImage . "',
9016 buttonImageOnly: true";
9017 }
9018 $retstring .= "
9019 }) });";
9020 $retstring .= "</script>";
9021 }
9022
9023 // Input area to enter date manually
9024 $retstring .= '<div class="nowraponall inline-block divfordateinput">';
9025 $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="'.($usecalendar == 'html' ? "date" : "text").'" class="maxwidthdate'.(getDolUserString('MAIN_OPTIMIZEFORTEXTBROWSER') ? ' textbrowser' : '').' center" maxlength="11" value="'.$formatted_date.'"';
9026 $retstring .= ($disabled ? ' disabled' : '');
9027 $retstring .= ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '');
9028 $retstring .= ' onChange="dpChangeDay(\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($usecalendar == 'html' ? 'yyyy-mm-dd' : $formatjslong) . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
9029 $retstring .= ' autocomplete="off">';
9030
9031 // Icon calendar
9032 if ($disabled) {
9033 $retstringbutton = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink ui-datepicker-notrigger"') . '</button>';
9034 $retstring .= $retstringbutton;
9035 }
9036
9037 $retstring .= '</div>';
9038 $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
9039 $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
9040 $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
9041 } else {
9042 $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
9043 }
9044 } else {
9045 // Show date with combo selects
9046 // Day
9047 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50imp" id="' . $prefix . 'day" name="' . $prefix . 'day">';
9048
9049 if ($emptydate || $set_time == -1) {
9050 $retstring .= '<option value="0" selected>&nbsp;</option>';
9051 }
9052
9053 for ($day = 1; $day <= 31; $day++) {
9054 $retstring .= '<option value="' . $day . '"' . ($day == $sday ? ' selected' : '') . '>' . $day . '</option>';
9055 }
9056
9057 $retstring .= "</select>";
9058
9059 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'month" name="' . $prefix . 'month">';
9060 if ($emptydate || $set_time == -1) {
9061 $retstring .= '<option value="0" selected>&nbsp;</option>';
9062 }
9063
9064 // Month
9065 for ($month = 1; $month <= 12; $month++) {
9066 $retstring .= '<option value="' . $month . '"' . ($month == $smonth ? ' selected' : '') . '>';
9067 $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
9068 $retstring .= "</option>";
9069 }
9070 $retstring .= "</select>";
9071
9072 // Year
9073 if ($emptydate || $set_time == -1) {
9074 $retstring .= '<input' . ($disabled ? ' disabled' : '') . ' placeholder="' . dol_escape_htmltag($langs->trans("Year")) . '" class="flat maxwidth50imp valignmiddle" type="number" min="0" max="3000" maxlength="4" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">';
9075 } else {
9076 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'year" name="' . $prefix . 'year">';
9077
9078 $syear = (int) $syear;
9079 for ($year = $syear - 10; $year < (int) $syear + 10; $year++) {
9080 $retstring .= '<option value="' . $year . '"' . ($year == $syear ? ' selected' : '') . '>' . $year . '</option>';
9081 }
9082 $retstring .= "</select>\n";
9083 }
9084 }
9085 }
9086
9087 if ($d && $h) {
9088 $retstring .= (($h == 2 || $h == 4) ? '<br>' : ' ');
9089 $retstring .= '<span class="nowraponall">';
9090 }
9091
9092 if ($h) {
9093 $hourstart = 0;
9094 $hourend = 24;
9095 if ($openinghours != '') {
9096 $openinghours = explode(',', $openinghours);
9097 $hourstart = $openinghours[0];
9098 $hourend = $openinghours[1];
9099 if ($hourend < $hourstart) {
9100 $hourend = $hourstart;
9101 }
9102 }
9103
9104 // Show hour
9105 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75 '; // Note maxwidth50 generates truncated number on some desktops even with same version of chrome that works on others
9106 $retstring .= ($fullday ? $fullday . 'hour' : '') . '" id="' . $prefix . 'hour" name="' . $prefix . 'hour">';
9107 if ($emptyhours) {
9108 $retstring .= '<option value="-1">&nbsp;</option>';
9109 }
9110 for ($hour = $hourstart; $hour < $hourend; $hour++) {
9111 if (strlen($hour) < 2) {
9112 $hour = "0" . $hour;
9113 }
9114 $retstring .= '<option value="' . $hour . '"' . (($hour == $shour) ? ' selected' : '') . '>' . $hour;
9115 $retstring .= '</option>';
9116 }
9117 $retstring .= '</select>';
9118
9119 if ($disabled) {
9120 $retstring .= '<input type="hidden" id="' . $prefix . 'hour" name="' . $prefix . 'hour" value="' . $shour . '">' . "\n";
9121 }
9122 if ($m) {
9123 $retstring .= ":";
9124 }
9125 }
9126
9127 if ($m) {
9128 // Show minutes
9129 $retstring .= '<select ' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75 '; // Note maxwidth50 generates truncated number on some desktops even with same version of chrome that works on others
9130 $retstring .= ($fullday ? $fullday . 'min' : '') . '" id="' . $prefix . 'min" name="' . $prefix . 'min">';
9131 if ($emptyhours) {
9132 $retstring .= '<option value="-1">&nbsp;</option>';
9133 }
9134 for ($min = 0; $min < 60; $min += $stepminutes) {
9135 $min_str = sprintf("%02d", $min);
9136 $retstring .= '<option value="' . $min_str . '"' . (($min_str == $smin) ? ' selected' : '') . '>' . $min_str . '</option>';
9137 }
9138 $retstring .= '</select>';
9139 if ($disabled) {
9140 $retstring .= '<input type="hidden" id="' . $prefix . 'min" name="' . $prefix . 'min" value="' . $smin . '">' . "\n";
9141 }
9142 // Add also seconds
9143 $retstring .= '<input type="hidden" name="' . $prefix . 'sec" value="' . $ssec . '">';
9144 }
9145
9146 if ($d && $h) {
9147 $retstring .= '</span>';
9148 }
9149
9150 // Add a "Now" link
9151 if (!empty($conf->use_javascript_ajax) && $addnowlink && !$disabled) {
9152 // Script which will be inserted in the onClick of the "Now" link
9153 $reset_scripts = "";
9154 if ($addnowlink == 2) { // local computer time
9155 // pad add leading 0 on numbers
9156 $reset_scripts .= "Number.prototype.pad = function(size) {
9157 var s = String(this);
9158 while (s.length < (size || 2)) {s = '0' + s;}
9159 return s;
9160 };
9161 var d = new Date();";
9162 }
9163
9164 // Generate the date part, depending on the use or not of the javascript calendar
9165 if ($addnowlink == 1) { // server time expressed in user time setup
9166 $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
9167 $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
9168 $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
9169 $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
9170 } elseif ($addnowlink == 2) {
9171 /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
9172 * This break application for foreign languages.
9173 $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
9174 $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
9175 $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
9176 $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
9177 */
9178 $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
9179 $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
9180 $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
9181 $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
9182 }
9183 /*if ($usecalendar == "eldy")
9184 {
9185 $base=DOL_URL_ROOT.'/core/';
9186 $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
9187 }
9188 else
9189 {
9190 $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
9191 $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
9192 $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
9193 }*/
9194 // Update the hour part
9195 if ($h) {
9196 if ($fullday) {
9197 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
9198 }
9199 //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
9200 if ($addnowlink == 1) {
9201 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
9202 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
9203 } elseif ($addnowlink == 2) {
9204 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(d.getHours().pad());';
9205 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
9206 }
9207
9208 if ($fullday) {
9209 $reset_scripts .= ' } ';
9210 }
9211 }
9212 // Update the minute part
9213 if ($m) {
9214 if ($fullday) {
9215 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
9216 }
9217 //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
9218 if ($addnowlink == 1) {
9219 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
9220 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
9221 } elseif ($addnowlink == 2) {
9222 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(d.getMinutes().pad());';
9223 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
9224 }
9225 if ($fullday) {
9226 $reset_scripts .= ' } ';
9227 }
9228 }
9229 // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
9230 if ($reset_scripts && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
9231 $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonNow" type="button" name="_useless" value="now" onClick="' . $reset_scripts . '">';
9232 $retstring .= $langs->trans("Now");
9233 $retstring .= '</button> ';
9234 }
9235 }
9236
9237 // Add a "Plus one hour" link
9238 if ($conf->use_javascript_ajax && $addplusone && !$disabled) {
9239 // Script which will be inserted in the onClick of the "Add plusone" link
9240 $reset_scripts = "";
9241
9242 // Generate the date part, depending on the use or not of the javascript calendar
9243 $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel') . '\');';
9244 $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
9245 $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
9246 $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
9247 // Update the hour part
9248 if ($h) {
9249 if ($fullday) {
9250 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
9251 }
9252 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
9253 if ($fullday) {
9254 $reset_scripts .= ' } ';
9255 }
9256 }
9257 // Update the minute part
9258 if ($m) {
9259 if ($fullday) {
9260 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
9261 }
9262 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
9263 if ($fullday) {
9264 $reset_scripts .= ' } ';
9265 }
9266 }
9267 // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
9268 if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
9269 $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="' . $reset_scripts . '">';
9270 $retstring .= $langs->trans("DateStartPlusOne");
9271 $retstring .= '</button> ';
9272 }
9273 }
9274
9275 // Add a link to set data
9276 if ($conf->use_javascript_ajax && !empty($adddateof) && !$disabled) {
9277 if (!is_array($adddateof)) {
9278 $arrayofdateof = array(array('adddateof' => $adddateof, 'labeladddateof' => $labeladddateof));
9279 } else {
9280 $arrayofdateof = $adddateof;
9281 }
9282 foreach ($arrayofdateof as $valuedateof) {
9283 $tmpadddateof = empty($valuedateof['adddateof']) ? 0 : $valuedateof['adddateof'];
9284 $tmplabeladddateof = empty($valuedateof['labeladddateof']) ? '' : $valuedateof['labeladddateof'];
9285 $tmparray = dol_getdate($tmpadddateof);
9286 if (empty($tmplabeladddateof)) {
9287 $tmplabeladddateof = $langs->trans("DateInvoice");
9288 }
9289 $reset_scripts = 'console.log(\'Click on now link\'); ';
9290 $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($tmpadddateof, 'dayinputnoreduce').'\');';
9291 $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.$tmparray['mday'].'\');';
9292 $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.$tmparray['mon'].'\');';
9293 $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.$tmparray['year'].'\');';
9294 $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="'.$reset_scripts.'">'.$tmplabeladddateof.'</button>';
9295 }
9296 }
9297
9298 return $retstring;
9299 }
9300
9310 public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array(), $morecss = 'minwidth75 maxwidth100')
9311 {
9312 global $langs;
9313
9314 $TDurationTypes = $this->getDurationTypes($langs);
9315
9316 // Removed undesired duration types
9317 foreach ($excludetypes as $value) {
9318 unset($TDurationTypes[$value]);
9319 }
9320
9321 $retstring = '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_' . $prefix . 'type_duration" name="' . $prefix . 'type_duration">';
9322 foreach ($TDurationTypes as $key => $typeduration) {
9323 $retstring .= '<option value="' . $key . '"';
9324 if ($key == $selected) {
9325 $retstring .= " selected";
9326 }
9327 $retstring .= ">" . $typeduration . "</option>";
9328 }
9329 $retstring .= "</select>";
9330
9331 $retstring .= ajax_combobox('select_' . $prefix . 'type_duration');
9332
9333 return $retstring;
9334 }
9335
9336 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
9337
9351 public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
9352 {
9353 // phpcs:enable
9354 global $langs;
9355
9356 $retstring = '<span class="nowraponall">';
9357
9358 $hourSelected = '';
9359 $minSelected = '';
9360
9361 // Hours
9362 if ($iSecond != '') {
9363 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
9364
9365 $hourSelected = convertSecondToTime($iSecond, 'allhour');
9366 $minSelected = convertSecondToTime($iSecond, 'min');
9367 }
9368
9369 if ($typehour == 'select') {
9370 $retstring .= '<select class="flat" id="select_' . $prefix . 'hour" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . '>';
9371 for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
9372 $retstring .= '<option value="' . $hour . '"';
9373 if (is_numeric($hourSelected) && $hourSelected == $hour) {
9374 $retstring .= " selected";
9375 }
9376 $retstring .= ">" . $hour . "</option>";
9377 }
9378 $retstring .= "</select>";
9379 } elseif ($typehour == 'text' || $typehour == 'textselect') {
9380 $retstring .= '<input placeholder="' . $langs->trans('HourShort') . '" type="number" min="0" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputhour right" value="' . (($hourSelected != '') ? ((int) $hourSelected) : '') . '">';
9381 } else {
9382 return 'BadValueForParameterTypeHour';
9383 }
9384
9385 if ($typehour != 'text') {
9386 $retstring .= ' ' . $langs->trans('HourShort');
9387 } else {
9388 $retstring .= '<span class="">:</span>';
9389 }
9390
9391 // Minutes
9392 if ($minunderhours) {
9393 $retstring .= '<br>';
9394 } else {
9395 if ($typehour != 'text') {
9396 $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
9397 }
9398 }
9399
9400 if ($typehour == 'select' || $typehour == 'textselect') {
9401 $retstring .= '<select class="flat" id="select_' . $prefix . 'min" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . '>';
9402 $step = getDolGlobalInt('MAIN_DURATION_STEP');
9403 $duration_step = ($step > 0) ? $step : 5;
9404 for ($min = 0; $min <= 59; $min += $duration_step) {
9405 $retstring .= '<option value="' . $min . '"';
9406 if (is_numeric($minSelected) && $minSelected == $min) {
9407 $retstring .= ' selected';
9408 }
9409 $retstring .= '>' . $min . '</option>';
9410 }
9411 $retstring .= "</select>";
9412 } elseif ($typehour == 'text') {
9413 $retstring .= '<input placeholder="' . $langs->trans('MinuteShort') . '" type="number" min="0" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputminute right" value="' . (($minSelected != '') ? ((int) $minSelected) : '') . '">';
9414 }
9415
9416 if ($typehour != 'text') {
9417 $retstring .= ' ' . $langs->trans('MinuteShort');
9418 }
9419
9420 $retstring .= "</span>";
9421
9422 if (!empty($nooutput)) {
9423 return $retstring;
9424 }
9425
9426 print $retstring;
9427
9428 return '';
9429 }
9430
9450 public function selectTickets($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
9451 {
9452 global $langs, $conf;
9453
9454 $out = '';
9455
9456 // check parameters
9457 if (is_null($ajaxoptions)) {
9458 $ajaxoptions = array();
9459 }
9460
9461 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
9462 $placeholder = '';
9463
9464 if ($selected && empty($selected_input_value)) {
9465 require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
9466 $tickettmpselect = new Ticket($this->db);
9467 $tickettmpselect->fetch((int) $selected);
9468 $selected_input_value = $tickettmpselect->ref;
9469 unset($tickettmpselect);
9470 }
9471
9472 $urloption = '';
9473 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
9474
9475 if (empty($hidelabel)) {
9476 $out .= $langs->trans("RefOrLabel") . ' : ';
9477 } elseif ($hidelabel > 1) {
9478 $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
9479 if ($hidelabel == 2) {
9480 $out .= img_picto($langs->trans("Search"), 'search');
9481 }
9482 }
9483 $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
9484 if ($hidelabel == 3) {
9485 $out .= img_picto($langs->trans("Search"), 'search');
9486 }
9487 } else {
9488 $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, '', $status, 0, $showempty, $forcecombo, $morecss);
9489 }
9490
9491 if (empty($nooutput)) {
9492 print $out;
9493 } else {
9494 return $out;
9495 }
9496 return '';
9497 }
9498
9499
9516 public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
9517 {
9518 global $langs;
9519
9520 $out = '';
9521 $outarray = array();
9522
9523 $selectFields = " p.rowid, p.ref, p.message";
9524
9525 $sql = "SELECT ";
9526 $sql .= $this->db->sanitize($selectFields, 0, 0, 1);
9527 $sql .= " FROM " . $this->db->prefix() . "ticket as p";
9528 $sql .= ' WHERE p.entity IN (' . getEntity('ticket') . ')';
9529
9530 // Add criteria on ref/label
9531 if ($filterkey != '') {
9532 $sql .= ' AND (';
9533 $prefix = getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if TICKET_DONOTSEARCH_ANYWHERE is on
9534 // For natural search
9535 $search_crit = explode(' ', $filterkey);
9536 $i = 0;
9537 if (count($search_crit) > 1) {
9538 $sql .= "(";
9539 }
9540 foreach ($search_crit as $crit) {
9541 if ($i > 0) {
9542 $sql .= " AND ";
9543 }
9544 $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.subject LIKE '" . $this->db->escape($prefix . $crit) . "%'";
9545 $sql .= ")";
9546 $i++;
9547 }
9548 if (count($search_crit) > 1) {
9549 $sql .= ")";
9550 }
9551 $sql .= ')';
9552 }
9553
9554 $sql .= $this->db->plimit($limit, 0);
9555
9556 // Build output string
9557 dol_syslog(get_class($this) . "::selectTicketsList search tickets", LOG_DEBUG);
9558 $result = $this->db->query($sql);
9559 if ($result) {
9560 require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
9561 require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php';
9562
9563 $num = $this->db->num_rows($result);
9564
9565 $events = array();
9566
9567 if (!$forcecombo) {
9568 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
9569 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt('TICKET_USE_SEARCH_TO_SELECT'));
9570 }
9571
9572 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
9573
9574 $textifempty = '';
9575 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
9576 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
9577 if (getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
9578 if ($showempty && !is_numeric($showempty)) {
9579 $textifempty = $langs->trans($showempty);
9580 } else {
9581 $textifempty .= $langs->trans("All");
9582 }
9583 } else {
9584 if ($showempty && !is_numeric($showempty)) {
9585 $textifempty = $langs->trans($showempty);
9586 }
9587 }
9588 if ($showempty) {
9589 $out .= '<option value="0" selected>' . $textifempty . '</option>';
9590 }
9591
9592 $i = 0;
9593 while ($num && $i < $num) {
9594 $opt = '';
9595 $optJson = array();
9596 $objp = $this->db->fetch_object($result);
9597
9598 $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
9599 '@phan-var-force array{key:string,value:mixed,type:int} $optJson';
9600 // Add new entry
9601 // "key" value of json key array is used by jQuery automatically as selected value
9602 // "label" value of json key array is used by jQuery automatically as text for combo box
9603 $out .= $opt;
9604 array_push($outarray, $optJson);
9605
9606 $i++;
9607 }
9608
9609 $out .= '</select>';
9610
9611 $this->db->free($result);
9612
9613 if (empty($outputmode)) {
9614 return $out;
9615 }
9616 return $outarray;
9617 } else {
9618 dol_print_error($this->db);
9619 }
9620
9621 return array();
9622 }
9623
9635 protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
9636 {
9637 $outkey = '';
9638 $outref = '';
9639 $outtype = '';
9640
9641 $outkey = $objp->rowid;
9642 $outref = $objp->ref;
9643
9644 $opt = '<option value="' . $objp->rowid . '"';
9645 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
9646 $opt .= '>';
9647 $opt .= $objp->ref;
9648 $objRef = $objp->ref;
9649 if (!empty($filterkey) && $filterkey != '') {
9650 $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
9651 }
9652
9653 $opt .= "</option>\n";
9654 $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
9655 }
9656
9676 public function selectProjects($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
9677 {
9678 global $langs, $conf;
9679
9680 $out = '';
9681
9682 // check parameters
9683 if (is_null($ajaxoptions)) {
9684 $ajaxoptions = array();
9685 }
9686
9687 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
9688 $placeholder = '';
9689
9690 if ($selected && empty($selected_input_value)) {
9691 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
9692 $projecttmpselect = new Project($this->db);
9693 $projecttmpselect->fetch((int) $selected);
9694 $selected_input_value = $projecttmpselect->ref;
9695 unset($projecttmpselect);
9696 }
9697
9698 $urloption = '';
9699 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
9700
9701 if (empty($hidelabel)) {
9702 $out .= $langs->trans("RefOrLabel") . ' : ';
9703 } elseif ($hidelabel > 1) {
9704 $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
9705 if ($hidelabel == 2) {
9706 $out .= img_picto($langs->trans("Search"), 'search');
9707 }
9708 }
9709 $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
9710 if ($hidelabel == 3) {
9711 $out .= img_picto($langs->trans("Search"), 'search');
9712 }
9713 } else {
9714 $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, '', $status, 0, $showempty, $forcecombo, $morecss);
9715 }
9716
9717 if (empty($nooutput)) {
9718 print $out;
9719 } else {
9720 return $out;
9721 }
9722 return '';
9723 }
9724
9741 public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
9742 {
9743 global $langs, $conf;
9744
9745 $out = '';
9746 $outarray = array();
9747
9748 $selectFields = " p.rowid, p.ref";
9749
9750 $sql = "SELECT ";
9751 $sql .= $this->db->sanitize($selectFields, 0, 0, 1);
9752 $sql .= " FROM " . $this->db->prefix() . "projet as p";
9753 $sql .= ' WHERE p.entity IN (' . getEntity('project') . ')';
9754
9755 // Add criteria on ref/label
9756 if ($filterkey != '') {
9757 $sql .= ' AND (';
9758 $prefix = !getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
9759 // For natural search
9760 $search_crit = explode(' ', $filterkey);
9761 $i = 0;
9762 if (count($search_crit) > 1) {
9763 $sql .= "(";
9764 }
9765 foreach ($search_crit as $crit) {
9766 if ($i > 0) {
9767 $sql .= " AND ";
9768 }
9769 $sql .= "p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%'";
9770 $sql .= "";
9771 $i++;
9772 }
9773 if (count($search_crit) > 1) {
9774 $sql .= ")";
9775 }
9776 $sql .= ')';
9777 }
9778
9779 $sql .= $this->db->plimit($limit, 0);
9780
9781 // Build output string
9782 dol_syslog(get_class($this) . "::selectProjectsList search projects", LOG_DEBUG);
9783 $result = $this->db->query($sql);
9784 if ($result) {
9785 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
9786 require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
9787
9788 $num = $this->db->num_rows($result);
9789
9790 $events = array();
9791
9792 if (!$forcecombo) {
9793 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
9794 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt('PROJECT_USE_SEARCH_TO_SELECT'));
9795 }
9796
9797 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
9798
9799 $textifempty = '';
9800 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
9801 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
9802 if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
9803 if ($showempty && !is_numeric($showempty)) {
9804 $textifempty = $langs->trans($showempty);
9805 } else {
9806 $textifempty .= $langs->trans("All");
9807 }
9808 } else {
9809 if ($showempty && !is_numeric($showempty)) {
9810 $textifempty = $langs->trans($showempty);
9811 }
9812 }
9813 if ($showempty) {
9814 $out .= '<option value="0" selected>' . $textifempty . '</option>';
9815 }
9816
9817 $i = 0;
9818 while ($num && $i < $num) {
9819 $opt = '';
9820 $optJson = array();
9821 $objp = $this->db->fetch_object($result);
9822
9823 $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
9824 // Add new entry
9825 // "key" value of json key array is used by jQuery automatically as selected value
9826 // "label" value of json key array is used by jQuery automatically as text for combo box
9827 $out .= $opt;
9828 array_push($outarray, $optJson);
9829
9830 $i++;
9831 }
9832
9833 $out .= '</select>';
9834
9835 $this->db->free($result);
9836
9837 if (empty($outputmode)) {
9838 return $out;
9839 }
9840 return $outarray;
9841 } else {
9842 dol_print_error($this->db);
9843 }
9844
9845 return array();
9846 }
9847
9861 protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
9862 {
9863 $outkey = '';
9864 $outref = '';
9865 $outtype = '';
9866
9867 $label = $objp->label;
9868
9869 $outkey = $objp->rowid;
9870 $outref = $objp->ref;
9871 $outlabel = $objp->label;
9872 $outtype = $objp->fk_product_type;
9873
9874 $opt = '<option value="' . $objp->rowid . '"';
9875 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
9876 $opt .= '>';
9877 $opt .= $objp->ref;
9878 $objRef = $objp->ref;
9879 if (!empty($filterkey) && $filterkey != '') {
9880 $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', (string) $objRef, 1);
9881 }
9882
9883 $opt .= "</option>\n";
9884 $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
9885 }
9886
9887
9908 public function selectMembers($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0, $excludeids = array())
9909 {
9910 global $langs, $conf;
9911
9912 $out = '';
9913
9914 // check parameters
9915 if (is_null($ajaxoptions)) {
9916 $ajaxoptions = array();
9917 }
9918
9919 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
9920 $placeholder = '';
9921
9922 if ($selected && empty($selected_input_value)) {
9923 require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
9924 $adherenttmpselect = new Adherent($this->db);
9925 $adherenttmpselect->fetch((int) $selected);
9926 $selected_input_value = $adherenttmpselect->ref;
9927 unset($adherenttmpselect);
9928 }
9929
9930 $urloption = '';
9931
9932 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
9933
9934 if (empty($hidelabel)) {
9935 $out .= $langs->trans("RefOrLabel") . ' : ';
9936 } elseif ($hidelabel > 1) {
9937 $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
9938 if ($hidelabel == 2) {
9939 $out .= img_picto($langs->trans("Search"), 'search');
9940 }
9941 }
9942 $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
9943 if ($hidelabel == 3) {
9944 $out .= img_picto($langs->trans("Search"), 'search');
9945 }
9946 } else {
9947 $filterkey = '';
9948
9949 $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss, $excludeids);
9950 }
9951
9952 if (empty($nooutput)) {
9953 print $out;
9954 } else {
9955 return $out;
9956 }
9957 return '';
9958 }
9959
9977 public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $excludeids = array())
9978 {
9979 global $langs, $conf;
9980
9981 $out = '';
9982 $outarray = array();
9983
9984 $selectFields = " p.rowid, p.ref, p.firstname, p.lastname, p.fk_adherent_type";
9985
9986 $sql = "SELECT ";
9987 $sql .= $this->db->sanitize($selectFields, 0, 0, 1);
9988 $sql .= " FROM " . $this->db->prefix() . "adherent as p";
9989 $sql .= ' WHERE p.entity IN (' . getEntity('adherent') . ')';
9990
9991 // Add criteria on ref/label
9992 if ($filterkey != '') {
9993 $sql .= ' AND (';
9994 $prefix = !getDolGlobalString('MEMBER_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
9995 // For natural search
9996 $search_crit = explode(' ', $filterkey);
9997 $i = 0;
9998 if (count($search_crit) > 1) {
9999 $sql .= "(";
10000 }
10001 foreach ($search_crit as $crit) {
10002 if ($i > 0) {
10003 $sql .= " AND ";
10004 }
10005 $sql .= "(p.firstname LIKE '" . $this->db->escape($prefix . $crit) . "%'";
10006 $sql .= " OR p.lastname LIKE '" . $this->db->escape($prefix . $crit) . "%')";
10007 $i++;
10008 }
10009 if (count($search_crit) > 1) {
10010 $sql .= ")";
10011 }
10012 $sql .= ')';
10013 }
10014 if ($status != -1) {
10015 $sql .= ' AND statut = ' . ((int) $status);
10016 }
10017 if (!empty($excludeids)) {
10018 $sql .= " AND p.rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeids)) . ")";
10019 }
10020 $sql .= $this->db->plimit($limit, 0);
10021
10022 // Build output string
10023 dol_syslog(get_class($this) . "::selectMembersList search adherents", LOG_DEBUG);
10024 $result = $this->db->query($sql);
10025 if ($result) {
10026 require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
10027 require_once DOL_DOCUMENT_ROOT . '/core/lib/member.lib.php';
10028
10029 $num = $this->db->num_rows($result);
10030
10031 $events = array();
10032
10033 if (!$forcecombo) {
10034 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
10035 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt('PROJECT_USE_SEARCH_TO_SELECT'));
10036 }
10037
10038 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
10039
10040 $textifempty = '';
10041 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
10042 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
10043 if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
10044 if ($showempty && !is_numeric($showempty)) {
10045 $textifempty = $langs->trans($showempty);
10046 } else {
10047 $textifempty .= $langs->trans("All");
10048 }
10049 } else {
10050 if ($showempty && !is_numeric($showempty)) {
10051 $textifempty = $langs->trans($showempty);
10052 }
10053 }
10054 if ($showempty) {
10055 $out .= '<option value="-1" selected>' . $textifempty . '</option>';
10056 }
10057
10058 $i = 0;
10059 while ($num && $i < $num) {
10060 $opt = '';
10061 $optJson = array();
10062 $objp = $this->db->fetch_object($result);
10063
10064 $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
10065
10066 // Add new entry
10067 // "key" value of json key array is used by jQuery automatically as selected value
10068 // "label" value of json key array is used by jQuery automatically as text for combo box
10069 $out .= $opt;
10070 array_push($outarray, $optJson);
10071
10072 $i++;
10073 }
10074
10075 $out .= '</select>';
10076
10077 $this->db->free($result);
10078
10079 if (empty($outputmode)) {
10080 return $out;
10081 }
10082 return $outarray;
10083 } else {
10084 dol_print_error($this->db);
10085 }
10086
10087 return array();
10088 }
10089
10101 protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
10102 {
10103 $outkey = '';
10104 $outlabel = '';
10105 $outtype = '';
10106
10107 $outkey = $objp->rowid;
10108 $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
10109 $outtype = $objp->fk_adherent_type;
10110
10111 $opt = '<option value="' . $objp->rowid . '"';
10112 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
10113 $opt .= '>';
10114 if (!empty($filterkey) && $filterkey != '') {
10115 $outlabel = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $outlabel, 1);
10116 }
10117 $opt .= $outlabel;
10118 $opt .= "</option>\n";
10119
10120 $optJson = array('key' => $outkey, 'value' => $outlabel, 'type' => $outtype);
10121 }
10122
10144 public function selectForForms($objectdesc, $htmlname, $preSelectedValue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '', $objectfield = '')
10145 {
10146 global $conf, $extrafields, $user, $hookmanager, $action;
10147
10148 // Example of common usage for a link to a thirdparty
10149
10150 // We got this in a modulebuilder form of "MyObject" of module "mymodule".
10151 // When ->fields is array( ... "fk_soc" => array("type"=>"integer:Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))" ...), we have
10152 // $objectdesc = 'Societe'
10153 // $objectfield = Method 1: 'myobject@mymodule:fk_soc' ('fk_soc' is code to retrieve myobject->fields['fk_soc'])
10154 // Method 2 recommended (it can be the array): array("type"=>"integer:Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))" ...)
10155
10156 // We got this when showing an extrafields on resource that is a link to societe
10157 // When extrafields 'link_to_societe' for object Resource is 'link' to 'Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))', we have
10158 // $objectdesc = 'Societe'
10159 // $objectfield = Method 1: 'resource:options_link_to_societe'
10160 // Method 2 recommended (it can be the array): array("type"=>'Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))" ...)
10161
10162 // With old usage:
10163 // $objectdesc = 'Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))'
10164 // $objectfield = ''
10165
10166 //var_dump($objectdesc.' '.$objectfield);
10167 //debug_print_backtrace();
10168
10169 $objectdescorig = $objectdesc;
10170 $objecttmp = null;
10171 $InfoFieldList = array();
10172 $classname = '';
10173 $filter = ''; // Ensure filter has value (for static analysis)
10174 $sortfield = ''; // Ensure filter has value (for static analysis)
10175
10176 if (is_array($objectfield)) { // objectfield is an array
10177 $objectdesc = $objectfield['type'];
10178 $objectdesc = preg_replace('/^integer[^:]*:/', '', $objectdesc);
10179 } elseif ($objectfield) { // objectfield is a string. We must retrieve the objectdesc from the field or extrafield. Deprecated, it is better to provide the array record directly.
10180 // Example: $objectfield = 'product:options_package' or 'myobject@mymodule:options_myfield'
10181 $tmparray = explode(':', $objectfield);
10182
10183 // Get instance of object from $element
10184 $objectforfieldstmp = fetchObjectByElement(0, strtolower($tmparray[0]));
10185
10186 if (is_object($objectforfieldstmp)) {
10187 $objectdesc = '';
10188
10189 $reg = array();
10190 if (preg_match('/^options_(.*)$/', $tmparray[1], $reg)) {
10191 // For a property in extrafields
10192 $key = $reg[1];
10193 // fetch optionals attributes and labels
10194 $extrafields->fetch_name_optionals_label($objectforfieldstmp->table_element);
10195
10196 if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key]) && $extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key] == 'link') {
10197 if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options'])) {
10198 $tmpextrafields = array_keys($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options']);
10199 $objectdesc = $tmpextrafields[0];
10200 }
10201 }
10202 } else {
10203 // For a property in ->fields
10204 if (array_key_exists($tmparray[1], $objectforfieldstmp->fields)) {
10205 $objectdesc = $objectforfieldstmp->fields[$tmparray[1]]['type'];
10206 $objectdesc = preg_replace('/^integer[^:]*:/', '', $objectdesc);
10207 }
10208 }
10209 }
10210 }
10211
10212 if ($objectdesc) {
10213 // Example of value for $objectdesc:
10214 // Bom:bom/class/bom.class.php:0:t.status=1
10215 // Bom:bom/class/bom.class.php:0:t.status=1:ref
10216 // Bom:bom/class/bom.class.php:0:(t.status:=:1) OR (t.field2:=:2):ref
10217 $InfoFieldList = explode(":", $objectdesc, 4);
10218 $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
10219 $reg = array();
10220 if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
10221 $InfoFieldList[4] = $reg[1]; // take the sort field
10222 }
10223 $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
10224
10225 $classname = $InfoFieldList[0];
10226 $classpath = empty($InfoFieldList[1]) ? '' : $InfoFieldList[1];
10227 //$addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
10228 $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
10229 $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
10230
10231 // Load object according to $id and $element
10232 $objecttmp = fetchObjectByElement(0, strtolower($InfoFieldList[0]));
10233
10234 // Fallback to another solution to get $objecttmp
10235 if (empty($objecttmp) && !empty($classpath)) {
10236 dol_include_once($classpath);
10237
10238 if ($classname && class_exists($classname)) {
10239 $objecttmp = new $classname($this->db);
10240 }
10241 }
10242 }
10243
10244 // Make some replacement in $filter. May not be used if we used the ajax mode with $objectfield. In such a case
10245 // we propagate the $objectfield and not the filter and replacement is done by the ajax/selectobject.php component.
10246 $sharedentities = (is_object($objecttmp) && property_exists($objecttmp, 'element')) ? getEntity($objecttmp->element) : strtolower($classname);
10247 $filter = str_replace(
10248 array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
10249 array($conf->entity, $sharedentities, $user->id),
10250 $filter
10251 );
10252
10253 if (!is_object($objecttmp)) {
10254 dol_syslog('selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.(is_array($objectfield) ? 'array' : $objectfield).', objectdesc='.$objectdesc, LOG_WARNING);
10255 return 'selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.(is_array($objectfield) ? 'array' : $objectfield).', objectdesc='.$objectdesc;
10256 }
10257 '@phan-var-force CommonObject $objecttmp';
10259 //var_dump($filter);
10260 $prefixforautocompletemode = $objecttmp->element;
10261 if ($prefixforautocompletemode == 'societe') {
10262 $prefixforautocompletemode = 'company';
10263 }
10264 if ($prefixforautocompletemode == 'product') {
10265 $prefixforautocompletemode = 'produit';
10266 }
10267
10268 $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
10269
10270 dol_syslog(get_class($this) . "::selectForForms filter=" . $filter, LOG_DEBUG);
10271
10272 // Generate the combo HTML component
10273 $out = '';
10274 if (!empty($conf->use_javascript_ajax) && getDolGlobalString($confkeyforautocompletemode) && !$forcecombo) {
10275 // No immediate load of all database
10276 $placeholder = '';
10277
10278 if ($preSelectedValue && empty($selected_input_value)) {
10279 $objecttmp->fetch($preSelectedValue);
10280 $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
10281
10282 $oldValueForShowOnCombobox = 0;
10283 foreach ($objecttmp->fields as $fieldK => $fielV) {
10284 if (!array_key_exists('showoncombobox', $fielV) || !$fielV['showoncombobox'] || empty($objecttmp->$fieldK)) {
10285 continue;
10286 }
10287
10288 if (!$oldValueForShowOnCombobox) {
10289 $selected_input_value = '';
10290 }
10291
10292 $selected_input_value .= $oldValueForShowOnCombobox ? ' - ' : '';
10293 $selected_input_value .= $objecttmp->$fieldK;
10294 $oldValueForShowOnCombobox = empty($fielV['showoncombobox']) ? 0 : $fielV['showoncombobox'];
10295 }
10296 }
10297
10298 // Set url and param to call to get json of the search results
10299 $urlforajaxcall = DOL_URL_ROOT . '/core/ajax/selectobject.php';
10300 $urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1&objectdesc=' . urlencode($objectdescorig) . (is_scalar($objectfield) ? '&objectfield='.urlencode($objectfield) : '') . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
10301 //$urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1'.(is_scalar($objectfield) ? '&objectfield='.urlencode($objectfield) : '') . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
10302
10303 // Hook 'selectForFormsListUrl' - Added to allow modules to modify the AJAX URL
10304 $parameters = array(
10305 'urloption' => $urloption,
10306 'object' => $objecttmp,
10307 'htmlname' => $htmlname,
10308 'filter' => $filter,
10309 'searchkey' => $searchkey,
10310 );
10311 $reshook = $hookmanager->executeHooks('selectForFormsListUrl', $parameters, $objecttmp, $action);
10312 if (!empty($reshook)) {
10313 $urloption = $hookmanager->resPrint;
10314 $hookmanager->resPrint = '';
10315 }
10316
10317 // Activate the auto complete using ajax call.
10318 $out .= ajax_autocompleter((string) $preSelectedValue, $htmlname, $urlforajaxcall, $urloption, getDolGlobalInt($confkeyforautocompletemode), 0);
10319 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
10320 $out .= '<input type="text" class="' . $morecss . '"' . ($disabled ? ' disabled="disabled"' : '') . ' name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '') . ' />';
10321 } else {
10322 // Immediate load of table record.
10323 $out .= $this->selectForFormsList($objecttmp, $htmlname, $preSelectedValue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
10324 }
10325
10326 return $out;
10327 }
10328
10329
10351 public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '', $sortorder = 'ASC')
10352 {
10353 global $langs, $user, $hookmanager;
10354
10355 //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
10356
10357 $prefixforautocompletemode = $objecttmp->element;
10358 if ($prefixforautocompletemode == 'societe') {
10359 $prefixforautocompletemode = 'company';
10360 }
10361 $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
10362
10363 $fieldstoshow = '';
10364 if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
10365 $tmpfieldstoshow = '';
10366 foreach ($objecttmp->fields as $key => $val) {
10367 if (! (int) dol_eval((string) $val['enabled'], 1, 1, '1')) {
10368 continue;
10369 }
10370 if (!empty($val['showoncombobox'])) {
10371 $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '') . 't.' . $key;
10372 }
10373 }
10374 if ($tmpfieldstoshow) {
10375 $fieldstoshow = $tmpfieldstoshow;
10376 }
10377 } elseif ($objecttmp->element === 'category') {
10378 $fieldstoshow = 't.label';
10379 } else {
10380 // For backward compatibility
10381 $objecttmp->fields['ref'] = array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'position' => 10, 'visible' => 4, 'showoncombobox' => 1);
10382 }
10383
10384 if (empty($fieldstoshow)) {
10385 if (!empty($objecttmp->parent_element)) {
10386 $fieldstoshow = 'o.ref';
10387 if (empty($sortfield)) {
10388 $sortfield = 'o.ref';
10389 }
10390 if (in_array($objecttmp->element, ['commandedet', 'propaldet', 'facturedet', 'expeditiondet'])) {
10391 $fieldstoshow .= ',p.ref AS p_ref,p.label,t.description';
10392 $sortfield .= ', p.ref';
10393 }
10394 } elseif (isset($objecttmp->fields['ref'])) {
10395 $fieldstoshow = 't.ref';
10396 } else {
10397 $langs->load("errors");
10398 $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
10399 return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
10400 }
10401 }
10402
10403 $out = '';
10404 $outarray = array();
10405 $tmparray = array();
10406
10407 $num = 0;
10408
10409 $sanitizedfieldstoshow = $fieldstoshow;
10410
10411 // Search data
10412 $sql = "SELECT t.rowid, " . $sanitizedfieldstoshow . " FROM " . $this->db->prefix() . $this->db->sanitize($objecttmp->table_element) . " as t";
10413 if (!empty($objecttmp->isextrafieldmanaged)) {
10414 $extrafieldTable = $objecttmp->table_element;
10415 if ($extrafieldTable == 'categorie') {
10416 $extrafieldTable = 'categories'; // For compatibility
10417 }
10418 $sql .= " LEFT JOIN " . $this->db->prefix() . $this->db->sanitize($extrafieldTable) . "_extrafields as e ON t.rowid = e.fk_object";
10419 }
10420 if (!empty($objecttmp->parent_element)) { // If parent_element is defined
10421 '@phan-var-force CommonObjectLine $objecttmp';
10422 $parent_properties = getElementProperties($objecttmp->parent_element);
10423 // @phan-suppress-next-line SqlInjection
10424 $sql .= " INNER JOIN " . $this->db->prefix() . $this->db->sanitize($parent_properties['table_element']) . " as o ON o.rowid = t.".$this->db->sanitize($objecttmp->fk_parent_attribute);
10425 }
10426 if (!empty($objecttmp->parent_element) && in_array($objecttmp->parent_element, ['commande', 'propal', 'facture', 'expedition'])) {
10427 $sql .= " LEFT JOIN " . $this->db->prefix() . "product as p ON p.rowid = t.fk_product";
10428 }
10429 if (!empty($objecttmp->ismultientitymanaged)) {
10430 if ($objecttmp->ismultientitymanaged == 1) { // @phan-suppress-current-line PhanPluginEmptyStatementIf
10431 // No need to join/link another table
10432 }
10433 if (!is_numeric($objecttmp->ismultientitymanaged)) {
10434 $tmparray = explode('@', $objecttmp->ismultientitymanaged);
10435 $sql .= " INNER JOIN " . $this->db->prefix() . $this->db->sanitize($tmparray[1]) . " as parenttable ON parenttable.rowid = t." . $this->db->sanitize($tmparray[0]);
10436 }
10437 }
10438
10439 // Add where from hooks
10440 $parameters = array(
10441 'object' => $objecttmp,
10442 'htmlname' => $htmlname,
10443 'filter' => $filter,
10444 'searchkey' => $searchkey
10445 );
10446
10447 $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
10448 if (!empty($hookmanager->resPrint)) {
10449 $sql .= $hookmanager->resPrint;
10450 } else {
10451 $sql .= " WHERE 1=1";
10452
10453 // If table need a multientity restriction
10454 if (!empty($objecttmp->ismultientitymanaged)) {
10455 if ($objecttmp->ismultientitymanaged == 1) {
10456 $sql .= " AND t.entity IN (" . getEntity($objecttmp->element) . ")";
10457 }
10458 if (!is_numeric($objecttmp->ismultientitymanaged)) {
10459 $sql .= " AND parenttable.entity = t." . $this->db->sanitize($tmparray[0]);
10460 }
10461 // If the parent table is llx_societe and user is not an external user (a more robust test done later for external users),
10462 // then we must also check that user has permissions
10463 if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
10464 if (!$user->hasRight('societe', 'client', 'voir') && empty($user->socid)) {
10465 $sql .= " AND EXISTS (SELECT sc.rowid FROM ".$this->db->prefix() . "societe_commerciaux as sc";
10466 $sql .= " WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $user->id).")";
10467 }
10468 }
10469 }
10470
10471 // If user is external user, we must also make a test on thirdparty
10472 if (!empty($user->socid)) {
10473 if ($objecttmp->element == 'societe') {
10474 $sql .= " AND t.rowid = " . ((int) $user->socid);
10475 } elseif (!empty($objecttmp->fields['fk_soc']) || !empty($objecttmp->fields['t.fk_soc']) || property_exists($objecttmp, 'fk_soc') || property_exists($objecttmp, 'socid')) {
10476 $sql .= " AND t.fk_soc = " . ((int) $user->socid);
10477 } elseif (!empty($objecttmp->parent_element)) {
10478 $tmpparent = fetchObjectByElement(0, $objecttmp->parent_element, '', 1);
10479 if (is_object($tmpparent) && (!empty($tmpparent->fields['fk_soc']) || !empty($tmpparent->fields['t.fk_soc']) || property_exists($tmpparent, 'fk_soc') || property_exists($tmpparent, 'socid'))) {
10480 $sql .= " AND o.fk_soc = " . ((int) $user->socid);
10481 }
10482 }
10483 }
10484
10485 $splittedfieldstoshow = explode(',', $fieldstoshow);
10486 foreach ($splittedfieldstoshow as &$field2) {
10487 if (is_numeric($pos = strpos($field2, ' '))) {
10488 $field2 = substr($field2, 0, $pos);
10489 }
10490 }
10491 if ($searchkey != '') {
10492 $sql .= natural_search($splittedfieldstoshow, $searchkey);
10493 }
10494
10495 if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:>:'20160101')"
10496 $errormessage = '';
10497 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
10498 if ($errormessage) {
10499 return 'Error forging a SQL request from an universal criteria: ' . $errormessage;
10500 }
10501 }
10502 }
10503 $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, $sortorder);
10504 //$sql.=$this->db->plimit($limit, 0);
10505 //print $sql;
10506
10507 // Build output string
10508 $resql = $this->db->query($sql);
10509 if ($resql) {
10510 // Construct $out and $outarray
10511 $out .= '<select id="' . $htmlname . '" class="flat minwidth100' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ($moreparams ? ' ' . $moreparams : '') . ' name="' . $htmlname . '">' . "\n";
10512
10513 // Warning: Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'. Seems it is no more true with selec2 v4
10514 $textifempty = '&nbsp;';
10515
10516 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
10517 if (getDolGlobalInt($confkeyforautocompletemode)) {
10518 if ($showempty && !is_numeric($showempty)) {
10519 $textifempty = $langs->trans($showempty);
10520 } else {
10521 $textifempty .= $langs->trans("All");
10522 }
10523 }
10524 if ($showempty) {
10525 $out .= '<option value="-1">' . $textifempty . '</option>' . "\n";
10526 }
10527
10528 $num = $this->db->num_rows($resql);
10529 $i = 0;
10530 if ($num) {
10531 while ($i < $num) {
10532 $obj = $this->db->fetch_object($resql);
10533 $label = '';
10534 $labelhtml = '';
10535 $tmparray = explode(',', $fieldstoshow);
10536 $oldvalueforshowoncombobox = 0;
10537 foreach ($tmparray as $key => $val) {
10538 $val = preg_replace('/(t|p|o)\./', '', $val);
10539 $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
10540 $labelhtml .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
10541 $label .= $obj->$val;
10542 $labelhtml .= $obj->$val;
10543
10544 $oldvalueforshowoncombobox = empty($objecttmp->fields[$val]['showoncombobox']) ? 0 : $objecttmp->fields[$val]['showoncombobox'];
10545 }
10546 if (empty($outputmode)) {
10547 if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
10548 $out .= '<option value="' . $obj->rowid . '" selected data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
10549 } else {
10550 $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
10551 }
10552 } else {
10553 array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label));
10554 }
10555
10556 $i++;
10557 if (($i % 10) == 0) {
10558 $out .= "\n";
10559 }
10560 }
10561 }
10562
10563 $out .= '</select>' . "\n";
10564
10565 if (!$forcecombo) {
10566 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
10567 $out .= ajax_combobox($htmlname, array(), getDolGlobalInt($confkeyforautocompletemode, 0));
10568 }
10569 } else {
10570 dol_print_error($this->db);
10571 }
10572
10573 $this->result = array('nbofelement' => $num);
10574
10575 if ($outputmode) {
10576 return $outarray;
10577 }
10578 return $out;
10579 }
10580
10591 public static function radio($htmlName, $radioItems, $selected = '', $moreGlobalParams = [])
10592 {
10593 // Default parameters for each radio input
10594 $defaultParams = [
10595 'disabled' => false,
10596 'attr' => [
10597 'type' => 'radio',
10598 'name' => $htmlName,
10599 ],
10600 'attrLabel' => [],
10601 'labelIsHtml' => false
10602 ];
10603
10604 // Merge global parameters with defaults
10605 $params = array_merge_recursive_distinct($defaultParams, $moreGlobalParams);
10606
10607 $out = '';
10608 if (!empty($radioItems)) {
10609 foreach ($radioItems as $key => $item) {
10610 // Normalize item to array structure if it's a simple string
10611 if (!is_array($item)) {
10612 $item = [
10613 'attr' => [
10614 'value' => $key,
10615 ],
10616 'label' => $item
10617 ];
10618 }
10619
10620 // Default properties for individual item
10621 $defaultItem = [
10622 'attr' => [
10623 'value' => !isset($item['attr']['value']) ? $key : '',
10624 ],
10625 'label' => '',
10626 ];
10627
10628 // Merge defaults with global params and item-specific properties
10629 $defaultItem = array_merge_recursive_distinct($params, $defaultItem);
10630 $item = array_merge_recursive_distinct($defaultItem, $item);
10631
10632 // Determine if this radio should be checked
10633 if ((is_array($selected) && in_array($item['attr']['value'], $selected, true)) || $selected === $item['attr']['value']) {
10634 $item['attr']['checked'] = true;
10635 }
10636
10637 // Build HTML attributes for input and label
10638 $inputAttributes = implode(' ', commonHtmlAttributeBuilder($item['attr']));
10639 $labelAttributes = implode(' ', commonHtmlAttributeBuilder($item['attrLabel']));
10640
10641 // prevent accidental Xss todo : escape $item['label'] but html friendly compatible
10642 $text = $item['labelIsHtml'] ? $item['label'] : htmlspecialchars($item['label'], ENT_QUOTES | ENT_SUBSTITUTE);
10643
10644 // Generate HTML
10645 $out .= '<label ' . $labelAttributes . '><input ' . $inputAttributes . ' /> ' . $text . '</label> ';
10646 }
10647 }
10648
10649 return $out;
10650 }
10651
10652
10676 public static function selectarray($htmlname, $array, $id = '', $show_empty = 0, $key_in_label = 0, $value_as_key = 0, $moreparam = '', $translate = 0, $maxlen = 0, $disabled = 0, $sort = '', $morecss = 'minwidth75', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
10677 {
10678 global $conf, $langs;
10679
10680 // Do we want a multiselect ?
10681 //$jsbeautify = 0;
10682 //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
10683 $jsbeautify = 1;
10684
10685 if ($value_as_key) {
10686 $array = array_combine($array, $array);
10687 }
10688
10689 '@phan-var-force array{label:string,data-html:string,disable?:int<0,1>,css?:string} $array'; // Array combine breaks information
10690
10691 $out = '';
10692
10693 if ($addjscombo < 0) {
10694 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
10695 $addjscombo = 1;
10696 } else {
10697 $addjscombo = 0;
10698 }
10699 }
10700 $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
10701 $out .= '<select id="' . preg_replace('/^\./', '', $idname) . '" ' . ($disabled ? 'disabled="disabled" ' : '') . 'class="flat ' . (preg_replace('/^\./', '', $htmlname)) . ($morecss ? ' ' . $morecss : '') . ' selectformat"';
10702 $out .= ' name="' . preg_replace('/^\./', '', $htmlname) . '" ' . ($moreparam ? $moreparam : '');
10703 $out .= '>'."\n";
10704
10705 if ($show_empty) {
10706 $textforempty = ' ';
10707 if (!empty($conf->use_javascript_ajax)) {
10708 $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
10709 }
10710 if (!is_numeric($show_empty)) {
10711 $textforempty = $show_empty;
10712 }
10713 $out .= '<option class="optiongrey" ' . ($moreparamonempty ? $moreparamonempty . ' ' : '') . 'value="' . (((int) $show_empty) < 0 ? $show_empty : -1) . '"' . ($id == $show_empty ? ' selected' : '') . '>' . dol_escape_htmltag($textforempty) . '</option>' . "\n";
10714 }
10715 if (is_array($array)) {
10716 // Translate
10717 if ($translate) {
10718 foreach ($array as $key => $value) {
10719 if (!is_array($value)) {
10720 $array[$key] = $langs->trans($value);
10721 } else {
10722 $array[$key]['label'] = $langs->trans($value['label']);
10723 }
10724 }
10725 }
10726 // Sort
10727 if ($sort == 'ASC') {
10728 asort($array);
10729 } elseif ($sort == 'DESC') {
10730 arsort($array);
10731 }
10732
10733 foreach ($array as $key => $tmpvalue) {
10734 if (is_array($tmpvalue)) {
10735 $value = $tmpvalue['label'];
10736 //$valuehtml = empty($tmpvalue['data-html']) ? $value : $tmpvalue['data-html'];
10737 $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
10738 $style = empty($tmpvalue['css']) ? '' : ' class="' . $tmpvalue['css'] . '"';
10739 } else {
10740 $value = $tmpvalue;
10741 //$valuehtml = $tmpvalue;
10742 $disabled = '';
10743 $style = '';
10744 }
10745 if (!empty($disablebademail)) {
10746 if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
10747 || ($disablebademail == 2 && preg_match('/---/', $value))) {
10748 $disabled = ' disabled';
10749 $style = ' class="warning"';
10750 }
10751 }
10752 if ($key_in_label) {
10753 if (empty($nohtmlescape)) {
10754 $selectOptionValue = dol_escape_htmltag($key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value));
10755 } else {
10756 $selectOptionValue = $key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value);
10757 }
10758 } else {
10759 if (empty($nohtmlescape)) {
10760 $selectOptionValue = dol_escape_htmltag($maxlen ? dol_trunc($value, $maxlen) : $value);
10761 } else {
10762 $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
10763 }
10764 if ($value == '' || $value == '-') {
10765 $selectOptionValue = '&nbsp;';
10766 }
10767 }
10768 $out .= '<option value="' . $key . '"';
10769 $out .= $style . $disabled;
10770 $out .= is_array($tmpvalue) && !empty($tmpvalue['parent']) ? ' parent="' . dolPrintHTMLForAttribute($tmpvalue['parent']) . '"' : '';
10771 if (is_array($id)) {
10772 if (in_array($key, $id) && !$disabled) {
10773 $out .= ' selected'; // To preselect a value
10774 }
10775 } else {
10776 $id = (string) $id; // if $id = 0, then $id = '0'
10777 if ($id != '' && (($id == (string) $key) || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
10778 $out .= ' selected'; // To preselect a value
10779 }
10780 }
10781
10782 if (is_array($tmpvalue)) {
10783 foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
10784 if ($keyforvalue == 'labelhtml') {
10785 $keyforvalue = 'data-html';
10786 }
10787 if (preg_match('/^data-/', $keyforvalue)) { // The best solution if you want to use HTML values into the list is to use data-html.
10788 $out .= ' '.dol_escape_htmltag($keyforvalue).'="'.dol_escape_htmltag($valueforvalue).'"';
10789 }
10790 }
10791 } elseif (!empty($nohtmlescape)) { // deprecated. Use instead the previous cas, an array with 'data-html', 'data-xxx' ... to use HTML content in the select
10792 $out .= ' data-html="' . dol_escape_htmltag($selectOptionValue) . '"';
10793 }
10794
10795 $out .= '>';
10796 $out .= $selectOptionValue;
10797 $out .= "</option>\n";
10798 }
10799 }
10800 $out .= "</select>";
10801
10802 // Add code for jquery to use multiselect
10803 if ($addjscombo && $jsbeautify) {
10804 // Enhance with select2
10805 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
10806 $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', (((int) $show_empty) < 0 ? (string) $show_empty : '-1'), $morecss);
10807 }
10808
10809 return $out;
10810 }
10811
10830 public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
10831 {
10832 global $conf;
10833 global $delayedhtmlcontent; // Will be used later outside of this function
10834
10835 // TODO Use an internal dolibarr component instead of select2
10836 if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
10837 return '';
10838 }
10839
10840 $out = '<select type="text" class="' . $htmlname . ($morecss ? ' ' . $morecss : '') . '" ' . ($moreparam ? $moreparam . ' ' : '') . 'name="' . $htmlname . '"></select>';
10841
10842 $outdelayed = '';
10843 if (!empty($conf->use_javascript_ajax)) {
10844 $tmpplugin = 'select2';
10845 $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
10846 <script nonce="' . getNonce() . '">
10847 $(document).ready(function () {
10848
10849 ' . ($callurlonselect ? 'var saveRemoteData = [];' : '') . '
10850
10851 $(".' . $htmlname . '").select2({
10852 ajax: {
10853 dir: "ltr",
10854 url: "' . $url . '",
10855 dataType: \'json\',
10856 delay: 250,
10857 data: function (params) {
10858 return {
10859 q: params.term, // search term
10860 page: params.page
10861 }
10862 },
10863 processResults: function (data) {
10864 // parse the results into the format expected by Select2.
10865 // since we are using custom formatting functions we do not need to alter the remote JSON data
10866 //console.log(data);
10867 saveRemoteData = data;
10868 /* format json result for select2 */
10869 result = []
10870 $.each( data, function( key, value ) {
10871 result.push({id: key, text: value.text});
10872 });
10873 //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
10874 //console.log(result);
10875 return {results: result, more: false}
10876 },
10877 cache: true
10878 },
10879 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage,
10880 containerCssClass: \':all:\', /* Line to add class from the original SELECT propagated to the new <span class="select2-selection...> tag */
10881 placeholder: \'' . dol_escape_js($placeholder) . '\',
10882 escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
10883 minimumInputLength: ' . ((int) $minimumInputLength) . ',
10884 formatResult: function (result, container, query, escapeMarkup) {
10885 return escapeMarkup(result.text);
10886 },
10887 });
10888
10889 ' . ($callurlonselect ? '
10890 /* Code to execute a GET when we select a value */
10891 $(".' . $htmlname . '").change(function() {
10892 var selected = $(\'.' . dol_escape_js($htmlname) . '\').val();
10893 console.log("We select in selectArrayAjax the entry "+selected)
10894 $(\'.' . dol_escape_js($htmlname) . '\').val(""); /* reset visible combo value */
10895 $.each( saveRemoteData, function( key, value ) {
10896 if (key == selected)
10897 {
10898 console.log("selectArrayAjax - Do a redirect to "+value.url)
10899 location.assign(value.url);
10900 }
10901 });
10902 });' : '') . '
10903
10904 });
10905 </script>';
10906 }
10907
10908 if ($acceptdelayedhtml) {
10909 $delayedhtmlcontent .= $outdelayed;
10910 } else {
10911 $out .= $outdelayed;
10912 }
10913 return $out;
10914 }
10915
10935 public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0, $textfortitle = '')
10936 {
10937 global $conf;
10938 global $delayedhtmlcontent; // Will be used later outside of this function
10939
10940 // TODO Use an internal dolibarr component instead of select2
10941 if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
10942 return '';
10943 }
10944
10945 $out = '<select type="text"'.($textfortitle ? ' title="'.dol_escape_htmltag($textfortitle).'"' : '').' id="'.$htmlname.'" class="'.$htmlname.($morecss ? ' ' . $morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.'"><option></option></select>';
10946
10947 $formattedarrayresult = array();
10948
10949 foreach ($array as $key => $value) {
10950 $o = new stdClass();
10951 $o->id = $key;
10952 $o->text = $value['text'];
10953 $o->url = $value['url'];
10954 $formattedarrayresult[] = $o;
10955 }
10956
10957 $outdelayed = '';
10958 if (!empty($conf->use_javascript_ajax)) {
10959 $tmpplugin = 'select2';
10960 $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
10961 <script nonce="' . getNonce() . '">
10962 $(document).ready(function () {
10963 var data = ' . json_encode($formattedarrayresult) . ';
10964
10965 ' . ($callurlonselect ? 'var saveRemoteData = ' . json_encode($array) . ';' : '') . '
10966
10967 $(\'.' . dol_escape_js($htmlname) . '\').select2({
10968 data: data,
10969 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage,
10970 containerCssClass: \':all:\', /* Line to add class from the original SELECT propagated to the new <span class="select2-selection...> tag */
10971 placeholder: \'' . dol_escape_js($placeholder) . '\',
10972 escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
10973 minimumInputLength: ' . ((int) $minimumInputLength) . ',
10974 formatResult: function (result, container, query, escapeMarkup) {
10975 return escapeMarkup(result.text);
10976 },
10977 matcher: function (params, data) {
10978
10979 if(! data.id) return null;';
10980
10981 if ($callurlonselect) {
10982 // We forge the url with 'sall='
10983 $outdelayed .= '
10984
10985 var urlBase = data.url;
10986 var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
10987 /* console.log("params.term="+params.term); */
10988 /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
10989 saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
10990 }
10991
10992 if (!$disableFiltering) {
10993 $outdelayed .= '
10994
10995 if(data.text.match(new RegExp(params.term))) {
10996 return data;
10997 }
10998
10999 return null;';
11000 } else {
11001 $outdelayed .= '
11002
11003 return data;';
11004 }
11005
11006 $outdelayed .= '
11007 }
11008 });
11009
11010 ' . ($callurlonselect ? '
11011 /* Code to execute a GET when we select a value */
11012 $(\'.' . dol_escape_js($htmlname) . '\').change(function() {
11013 var selected = $(\'.' . dol_escape_js($htmlname) . '\').val();
11014 console.log("We select "+selected)
11015
11016 $(\'.' . dol_escape_js($htmlname) . '\').val(""); /* reset visible combo value */
11017 $.each( saveRemoteData, function( key, value ) {
11018 if (key == selected)
11019 {
11020 console.log("selectArrayFilter - Do a redirect to "+value.url)
11021 location.assign(value.url);
11022 }
11023 });
11024 });' : '') . '
11025
11026 });
11027 </script>';
11028 }
11029
11030 if ($acceptdelayedhtml) {
11031 $delayedhtmlcontent .= $outdelayed;
11032 } else {
11033 $out .= $outdelayed;
11034 }
11035 return $out;
11036 }
11037
11056 public static function multiselectarray($htmlname, $array, $selected = array(), $key_in_label = 0, $value_as_key = 0, $morecss = '', $translate = 0, $width = 0, $moreattrib = '', $nu = '', $placeholder = '', $addjscombo = -1)
11057 {
11058 global $conf, $langs;
11059 $out = '';
11060
11061 if ($addjscombo < 0) {
11062 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
11063 $addjscombo = 1;
11064 } else {
11065 $addjscombo = 0;
11066 }
11067 }
11068
11069 $useenhancedmultiselect = 0;
11070 if (!empty($conf->use_javascript_ajax) && !defined('MAIN_DO_NOT_USE_JQUERY_MULTISELECT') && (getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT'))) {
11071 if ($addjscombo) {
11072 $useenhancedmultiselect = 1; // Use the js multiselect in one line. Possible only if $addjscombo not 0.
11073 }
11074 }
11075
11076 $out .= '<span class="multiselectarray'.$htmlname.'">';
11077
11078 // We need a hidden field because when using the multiselect, if we unselect all, there is no
11079 // variable submitted at all, so no way to make a difference between variable not submitted and variable
11080 // submitted to nothing.
11081 $out .= '<input type="hidden" name="'.$htmlname.'_multiselect" value="1">';
11082 // Output select component
11083 $out .= '<select id="'.$htmlname.'" class="multiselect' . ($useenhancedmultiselect ? ' multiselectononeline' : '') . ($morecss ? ' ' . $morecss : '') . '" multiple name="' . $htmlname . '[]"' . ($moreattrib ? ' ' . $moreattrib : '') . ($width ? ' style="width: ' . (preg_match('/%/', (string) $width) ? $width : $width . 'px') . '"' : '') . '>' . "\n";
11084 if (is_array($array) && !empty($array)) {
11085 if ($value_as_key) {
11086 $array = array_combine($array, $array);
11087 }
11088
11089 if (!empty($array)) {
11090 foreach ($array as $key => $value) {
11091 $tmpkey = $key;
11092 $tmplabel = $value;
11093 $tmplabelhtml = '';
11094 $tmpcolor = '';
11095 $tmppicto = '';
11096 $tmpdisabled = '';
11097 if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
11098 $tmpkey = $value['id'];
11099 $tmplabel = empty($value['label']) ? '' : $value['label'];
11100 $tmplabelhtml = empty($value['labelhtml']) ? (empty($value['data-html']) ? '' : $value['data-html']) : $value['labelhtml'];
11101 $tmpcolor = empty($value['color']) ? '' : $value['color'];
11102 $tmppicto = empty($value['picto']) ? '' : $value['picto'];
11103 $tmpdisabled = empty($value['disabled']) ? '' : $value['disabled'];
11104 }
11105 $newval = ($translate ? $langs->trans($tmplabel) : $tmplabel);
11106 $newval = ($key_in_label ? $tmpkey . ' - ' . $newval : $newval);
11107
11108 $tmplabelhtml = ($translate ? $langs->trans($tmplabelhtml) : $tmplabelhtml);
11109 $tmplabelhtml = ($key_in_label ? $tmpkey . ' - ' . $tmplabelhtml : $tmplabelhtml);
11110
11111 $out .= '<option value="' . $tmpkey . '"';
11112 if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
11113 $out .= ' selected';
11114 }
11115 $out .= is_array($value) && array_key_exists('parent', $value) && !empty($value['parent']) ? ' parent="' . dolPrintHTMLForAttribute($value['parent']) . '"' : '';
11116 if ($tmpdisabled) {
11117 $out .= ' disabled="disabled"';
11118 }
11119 if (!empty($tmplabelhtml)) {
11120 $out .= ' data-html="' . dolPrintHTMLForAttribute($tmplabelhtml) . '"';
11121 } else {
11122 $tmplabelhtml = ($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #' . $tmpcolor . '"') : '') . $newval;
11123 $out .= ' data-html="' . dolPrintHTMLForAttribute($tmplabelhtml) . '"';
11124 }
11125 $out .= '>';
11126 $out .= dol_htmlentitiesbr($newval);
11127 $out .= '</option>' . "\n";
11128 }
11129 }
11130 }
11131 $out .= '</select>' . "\n";
11132
11133 $out .= '</span>';
11134
11135 // Add code for jquery to use multiselect
11136 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT')) {
11137 $out .= "\n" . '<!-- JS CODE TO ENABLE select for id ' . $htmlname . ', addjscombo=' . $addjscombo . ' -->';
11138 $out .= "\n" . '<script nonce="' . getNonce() . '">' . "\n";
11139 if ($addjscombo == 1) {
11140 $moreselect2theme = ($morecss ? dol_escape_js(' '.$morecss) : '');
11141 $moreselect2theme = preg_replace('/widthcentpercentminus[^\s]*/', '', $moreselect2theme);
11142
11143 $widthTypeOfAutocomplete = 'resolve';
11144
11145 $tmpplugin = getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT', (defined('REQUIRE_JQUERY_MULTISELECT') ? constant('REQUIRE_JQUERY_MULTISELECT') : 'select2'));
11146
11147 // If property data-html set, we decode html entities and use this.
11148 // Note that HTML content must have been sanitized from js with dol_escape_htmltag(xxx, 0, 0, '', 0, 1) when building the select option.
11149 // TODO Move this into common js ?
11150 $out .= 'function formatResult(record, container) {' . "\n";
11151 $out .= ' if ($(record.element).attr("data-html") != undefined && typeof htmlEntityDecodeJs === "function") {';
11152 $out .= ' return htmlEntityDecodeJs($(record.element).attr("data-html"));';
11153 $out .= ' }'."\n";
11154 $out .= ' return record.text;';
11155 $out .= '}' . "\n";
11156
11157 $out .= 'function formatSelection(record) {' . "\n";
11158 $out .= ' return record.text;';
11159 $out .= '}' . "\n";
11160
11161 // Load the select2 enhancer
11162 //$out .= 'console.log(\'addjscombo=1 for htmlname=' . dol_escape_js($htmlname) . '\');';
11163 $out .= '$(document).ready(function () {
11164 $(\'#' . dol_escape_js($htmlname) . '\').' . $tmpplugin . '({';
11165 // when $morecss contains 'onrightofpage', the select2 component must also be inside a parent with class="parentonrightofpage"
11166 if (preg_match('/onrightofpage/', $morecss)) { // In this cas, htmlname must be an ID not a class.
11167 $out .= ' dropdownAutoWidth: true, ';
11168 $out .= ' dropdownParent: $(\'#'.$htmlname.'\').parent(), ';
11169 }
11170 if ($placeholder) {
11171 $out .= '
11172 placeholder: {
11173 id: \'-1\',
11174 text: \''.dol_escape_js($placeholder).'\'
11175 },';
11176 }
11177 $out .= ' dir: \'ltr\',
11178 width: \''.dol_escape_js($widthTypeOfAutocomplete).'\', /* off or resolve */
11179 theme: \'default' . dol_escape_js($moreselect2theme) . '\', /* to add css on generated html components */
11180 containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag (ko with multiselect) */
11181 selectionCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
11182 dropdownCssClass: \'dol-dropdown-dialog dol-dropdown-dialogmulti\', /* Line to add class on the new <span class="select2-selection...> tag (ok with multiselect). Need full version of select2. */
11183 // Specify format function for dropdown item
11184 formatResult: formatResult,
11185 templateResult: formatResult, /* For 4.0 */
11186 escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
11187 // Specify format function for selected item
11188 formatSelection: formatSelection,
11189 templateSelection: formatSelection, /* For 4.0 */
11190 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage
11191 });
11192
11193 /* Add also morecss to the css .select2 that is after the #htmlname, for component that are shown dynamically after load, because select2 set
11194 the size only if component is not hidden by default on load */
11195 $(\'#' . dol_escape_js($htmlname) . ' + .select2\').addClass(\'' . dol_escape_js($morecss) . '\');
11196 });' . "\n";
11197 } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
11198 // Add other js lib
11199 // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
11200 // ...
11201 $out .= 'console.log(\'addjscombo=2 for htmlname=' . dol_escape_js($htmlname) . '\');';
11202 $out .= '$(document).ready(function () {
11203 $(\'#' . dol_escape_js($htmlname) . '\').multiSelect({
11204 containerHTML: \'<div class="multi-select-container">\',
11205 menuHTML: \'<div class="multi-select-menu">\',
11206 buttonHTML: \'<span class="multi-select-button ' . dol_escape_js($morecss) . '">\',
11207 menuItemHTML: \'<label class="multi-select-menuitem">\',
11208 activeClass: \'multi-select-container--open\',
11209 noneText: \'' . dol_escape_js($placeholder) . '\'
11210 });
11211 })';
11212 }
11213 $out .= '</script>';
11214 }
11215
11216 return $out;
11217 }
11218
11219
11233 public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '', $draganddrop = 0)
11234 {
11235 global $conf, $langs, $user;
11236
11237 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
11238 return '';
11239 }
11240 if (empty($array)) {
11241 return '';
11242 }
11243
11244 $tmpvar = "MAIN_SELECTEDFIELDS_" . $varpage; // To get list of saved selected fields to show
11245
11246 if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
11247 $tmparray = explode(',', $user->conf->$tmpvar);
11248 foreach ($array as $key => $val) {
11249 //var_dump($key);
11250 //var_dump($tmparray);
11251 if (in_array($key, $tmparray)) {
11252 $array[$key]['checked'] = 1;
11253 } else {
11254 $array[$key]['checked'] = 0;
11255 }
11256 }
11257 } else { // There is no list of fields already customized for user
11258 foreach ($array as $key => $val) {
11259 if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
11260 $array[$key]['checked'] = 0;
11261 }
11262 }
11263 }
11264
11265 $listoffieldsforselection = '';
11266 $listcheckedstring = '';
11267
11268 foreach ($array as $key => $val) {
11269 // var_dump($val);
11270 // var_dump(array_key_exists('enabled', $val));
11271 // var_dump(!$val['enabled']);
11272 if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
11273 unset($array[$key]); // We don't want this field
11274 continue;
11275 }
11276 if (!empty($val['type']) && $val['type'] == 'separate') {
11277 // Field remains in array but we don't add it into $listoffieldsforselection
11278 //$listoffieldsforselection .= '<li>-----</li>';
11279 continue;
11280 }
11281 if (!empty($val['label']) && $val['label']) {
11282 if (!empty($val['langfile']) && is_object($langs)) {
11283 $langs->load($val['langfile']);
11284 }
11285
11286 // Note: $val['checked'] <> 0 means we must show the field into the combo list @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
11287 $listoffieldsforselection .= '<li '.(!empty($draganddrop) ? 'class="fieldsortable" id="'.$key : '').'"><input type="checkbox" id="checkbox' . $key . '" value="' . $key . '"' . ((!array_key_exists('checked', $val) || empty($val['checked']) || $val['checked'] == '-1') ? '' : ' checked="checked"') . ' data-position="'.(empty($val['position']) ? '' : $val['position']).'" />';
11288 $listoffieldsforselection .= '<label for="checkbox' . $key . '" class="paddingleft">';
11289 $listoffieldsforselection .= dolPrintHTML(dol_string_nohtmltag($langs->trans($val['label'])));
11290 $listoffieldsforselection .= '</label>';
11291 if (!empty($draganddrop)) {
11292 $listoffieldsforselection .= img_picto($langs->trans("MoveField", !empty($key) ? $key : 'none'), 'grip_title', 'class="opacitymedium boxhandle hideonsmartphone cursormove marginleftonly"');
11293 }
11294 $listoffieldsforselection .= '</li>';
11295 $listcheckedstring .= (empty($val['checked']) ? '' : $key . ',');
11296 }
11297 }
11298
11299 $out = '<!-- Component multiSelectArrayWithCheckbox ' . $htmlname . ' -->
11300
11301 <dl class="dropdown">
11302 <dt>
11303 <a href="#' . $htmlname . '" class="multiselectpicto">
11304 ' . img_picto('', 'list') . '
11305 </a>
11306 <input type="hidden" class="' . $htmlname . '" name="' . $htmlname . '" value="' . $listcheckedstring . '">
11307 </dt>
11308 <dd class="dropdowndd">
11309 <div class="multiselectcheckbox'.$htmlname.'">
11310 <ul class="'.$htmlname.(((string) $pos == '1' || (string) $pos == 'left') ? 'left' : '').(!empty($draganddrop) ? ' sortable' : '').'">
11311 <li class="liinputsearch">
11312 <input class="inputsearch_dropdownselectedfields width90p minwidth200imp" style="width:90%;" type="text" placeholder="'.$langs->trans('Search').'">
11313 </li>
11314 '.$listoffieldsforselection.'
11315 </ul>
11316 </div>
11317 </dd>
11318 </dl>
11319
11320 <script>
11321 function updateFieldOrder() {
11322 var positionfields = $(".sortable").sortable("toArray");
11323 $.ajax({
11324 url: \''.DOL_URL_ROOT.'/core/ajax/changepositionfields.php?positionfields=\'+positionfields+\'&token='.newToken().'&action=listafterchangingpositionfields&contextpage='.$varpage.'&userid='.$user->id.'\',
11325 async: false,
11326 success: function () {
11327 // reload page
11328 window.location.href = "'.$_SERVER["PHP_SELF"].'";
11329 }
11330 });
11331 }
11332 $( ".sortable" ).sortable({
11333 handle: \'.boxhandle\',
11334 revert: \'invalid\',
11335 items: \'.fieldsortable\',
11336 stop: function(event, ui) {
11337 console.log("We moved box so we call updateBoxOrder with ajax actions");
11338 updateFieldOrder(); /* 1 to avoid message after a move */
11339 }
11340 });
11341 </script>
11342
11343 <script nonce="' . getNonce() . '" type="text/javascript">
11344 jQuery(document).ready(function () {
11345 $(\'.multiselectcheckbox' . $htmlname . ' input[type="checkbox"]\').on("click", function () {
11346 console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
11347
11348 $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
11349
11350 var title = $(this).val() + ",";
11351 if ($(this).is(\':checked\')) {
11352 $(\'.' . $htmlname . '\').val(title + $(\'.' . $htmlname . '\').val());
11353 }
11354 else {
11355 $(\'.' . $htmlname . '\').val( $(\'.' . $htmlname . '\').val().replace(title, \'\') )
11356 }
11357 // Now, we submit page
11358 //$(this).parents(\'form:first\').submit();
11359 });
11360
11361 $("input.inputsearch_dropdownselectedfields").on("keyup", function() {
11362 console.log("keyup on inputsearch_dropdownselectedfields");
11363 var value = $(this).val().toLowerCase();
11364 $(\'.multiselectcheckbox'.$htmlname.' li > label\').filter(function() {
11365 $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
11366 });
11367 });
11368 ';
11369 if (empty($conf->browser->layout) || $conf->browser->layout != 'phone') {
11370 $out .= '
11371 $(".dropdown dt a").on("click", function () {
11372 console.log("Click on dropdown, we set focus to search field");
11373 setTimeout(() => { $(\'.inputsearch_dropdownselectedfields\').focus(); }, 200);
11374 });';
11375 }
11376 $out .= '
11377 });
11378 </script>
11379
11380 ';
11381 return $out;
11382 }
11383
11393 public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
11394 {
11395 global $conf;
11396
11397 include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
11398
11399 $cat = new Categorie($this->db);
11400 $categories = $cat->containing($id, $type);
11401
11402 if ($rendermode == 1 || $rendermode == 2) {
11403 $toprint = array();
11404 foreach ($categories as $c) {
11405 $ways = $c->print_all_ways('auto', ($nolink ? 'none' : ''), 0, 1, ($rendermode == 2 ? 0 : 1)); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
11406 foreach ($ways as $way) {
11407 $color = $c->color;
11408 $sfortag = '<li class="select2-search-choice-dolibarr noborderoncategories'.(empty($toprint) ? ' nomarginleft' : '');
11409 $forced_color = 'categtextwhite'; // We want color white because the getNomUrl of a tag is always called inside a dark background like '<span color="bbb"></span>' to show it as a tag. TODO Add this in param to force when called outside of span.
11410 if ($c->color && colorIsLight($c->color)) {
11411 $forced_color = 'categtextblack';
11412 }
11413 $sfortag .= ' '.$forced_color;
11414 $sfortag .= '"';
11415 $sfortag .= ($color ? ' style="background: #' . $color . ';"' : ' style="background: #bbb"');
11416 $titlestring = $ways[0];
11417 $titlestring = str_replace('>', ' - ', dol_string_nohtmltag($titlestring));
11418 $sfortag .= ' title="' . dolPrintHTMLForAttribute($titlestring) . '"';
11419 $sfortag .= '>';
11420 if ($rendermode == 1) {
11421 $sfortag .= '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.((int) $c->id).'&type='.urlencode($c->type).'" class="'.$forced_color.'" tabindex="-1">';
11422 $sfortag .= img_picto('', 'category', 'class="paddingright"');
11423 if ($conf->dol_optimize_smallscreen) {
11424 $sfortag .= dolPrintHTML(dol_trunc($c->label, 8));
11425 } else {
11426 $sfortag .= dolPrintHTML($c->label);
11427 }
11428 $sfortag .= '</a>';
11429 } else {
11430 $sfortag .= $way;
11431 }
11432 $sfortag .= '</li>';
11433
11434 $toprint[] = $sfortag; // Add tag in list of tag to show
11435 }
11436 }
11437 if (empty($toprint)) {
11438 return '';
11439 } else {
11440 return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
11441 }
11442 }
11443
11444 if ($rendermode == 0) {
11445 $arrayselected = array();
11446 $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 3);
11447 foreach ($categories as $c) {
11448 $arrayselected[(string) $c->id] = (string) $c->id;
11449 }
11450
11451 return $this->multiselectarray('categories', $cate_arbo, $arrayselected, 0, 0, '', 0, '100%', 'disabled', 'category');
11452 }
11453
11454 return 'ErrorBadValueForParameterRenderMode'; // Should not happened
11455 }
11456
11466 public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = array(), $title = 'RelatedObjects')
11467 {
11468 global $conf, $langs, $hookmanager;
11469 global $action;
11470 global $db, $user; // Will be used into tpl
11471
11472 dol_syslog(__METHOD__, LOG_DEBUG);
11473
11474 $object->fetchObjectLinked();
11475
11476 // Bypass the default method
11477 $hookmanager->initHooks(array('commonobject'));
11478 $parameters = array(
11479 'morehtmlright' => $morehtmlright,
11480 'compatibleImportElementsList' => &$compatibleImportElementsList,
11481 );
11482 $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
11483
11484 $nbofdifferenttypes = count($object->linkedObjects);
11485
11486 if (empty($reshook)) {
11487 print '<!-- showLinkedObjectBlock -->';
11488 print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, '', 'showlinkedobjectblock');
11489
11490
11491 print '<div class="div-table-responsive-no-min">';
11492 print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="' . $object->element . '" data-elementid="' . $object->id . '" >';
11493
11494 print '<tr class="liste_titre">';
11495 print '<td>' . $langs->trans("Type") . '</td>';
11496 print '<td>' . $langs->trans("Ref") . '</td>';
11497 print '<td></td>';
11498 print '<td></td>';
11499 print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
11500 print '<td class="right">' . $langs->trans("Status") . '</td>';
11501 print '<td></td>';
11502 print '</tr>';
11503
11504 $nboftypesoutput = 0;
11505
11506 foreach ($object->linkedObjects as $objecttype => $objects) {
11507 $tplpath = $element = $subelement = $objecttype;
11508
11509 // to display import button on tpl
11510 global $showImportButton; // Will be used into tpl
11511 $showImportButton = false;
11512 if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
11513 $showImportButton = true;
11514 }
11515
11516 $regs = array();
11517
11518 if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
11519 $element = $regs[1];
11520 $subelement = $regs[2];
11521 $tplpath = $element . '/' . $subelement;
11522 }
11523 $tplname = 'linkedobjectblock';
11524
11525 // If we ask a resource form external module (instead of default path)
11526 if (preg_match('/^([^@]+)@([^@]+)$/i', $objecttype, $regs)) { // 'myobject@mymodule'
11527 $element = $regs[1];
11528 $module = $regs[2];
11529 $tplpath = $module. '/' . $element;
11530 $tplname = $tplname.'_'.$element;
11531 }
11532
11533 // To work with non standard path
11534 if ($objecttype == 'facture') {
11535 $tplpath = 'compta/' . $element;
11536 if (!isModEnabled('invoice')) {
11537 continue; // Do not show if module disabled
11538 }
11539 } elseif ($objecttype == 'facturerec') {
11540 $tplpath = 'compta/facture';
11541 $tplname = 'linkedobjectblockForRec';
11542 if (!isModEnabled('invoice')) {
11543 continue; // Do not show if module disabled
11544 }
11545 } elseif ($objecttype == 'propal') {
11546 $tplpath = 'comm/' . $element;
11547 if (!isModEnabled('propal')) {
11548 continue; // Do not show if module disabled
11549 }
11550 } elseif ($objecttype == 'supplier_proposal') {
11551 if (!isModEnabled('supplier_proposal')) {
11552 continue; // Do not show if module disabled
11553 }
11554 } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
11555 $tplpath = 'expedition';
11556 if (!isModEnabled('shipping')) {
11557 continue; // Do not show if module disabled
11558 }
11559 } elseif ($objecttype == 'reception') {
11560 $tplpath = 'reception';
11561 if (!isModEnabled('reception')) {
11562 continue; // Do not show if module disabled
11563 }
11564 } elseif ($objecttype == 'delivery') {
11565 $tplpath = 'delivery';
11566 if (!getDolGlobalInt('MAIN_SUBMODULE_DELIVERY')) {
11567 continue; // Do not show if sub module disabled
11568 }
11569 } elseif ($objecttype == 'ficheinter') {
11570 $tplpath = 'fichinter';
11571 if (!isModEnabled('intervention')) {
11572 continue; // Do not show if module disabled
11573 }
11574 } elseif ($objecttype == 'invoice_supplier') {
11575 $tplpath = 'fourn/facture';
11576 } elseif ($objecttype == 'order_supplier') {
11577 $tplpath = 'fourn/commande';
11578 } elseif ($objecttype == 'expensereport') {
11579 $tplpath = 'expensereport';
11580 } elseif ($objecttype == 'subscription') {
11581 $tplpath = 'adherents';
11582 } elseif ($objecttype == 'conferenceorbooth') {
11583 $tplpath = 'eventorganization';
11584 } elseif ($objecttype == 'conferenceorboothattendee') {
11585 $tplpath = 'eventorganization';
11586 } elseif ($objecttype == 'mo') {
11587 $tplpath = 'mrp';
11588 if (!isModEnabled('mrp')) {
11589 continue; // Do not show if module disabled
11590 }
11591 } elseif ($objecttype == 'project_task') {
11592 $tplpath = 'projet/tasks';
11593 }
11594
11595 global $linkedObjectBlock; // Will be used into tpl
11596 $linkedObjectBlock = $objects;
11597
11598 // Output template part (modules that overwrite templates must declare this into descriptor)
11599 $dirtpls = array_merge($conf->modules_parts['tpl'], array('/' . $tplpath . '/tpl'));
11600
11601 foreach ($dirtpls as $reldir) {
11602 $reldir = rtrim($reldir, '/');
11603 if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
11604 global $noMoreLinkedObjectBlockAfter; // Will be used into tpl
11605 $noMoreLinkedObjectBlockAfter = 1;
11606 }
11607 $file = dol_buildpath($reldir . '/' . $tplname . '.tpl.php');
11608 if (file_exists($file)) {
11609 $res = @include $file;
11610 if ($res) {
11611 $nboftypesoutput++;
11612 break;
11613 }
11614 }
11615 }
11616 }
11617
11618 if (!$nboftypesoutput) {
11619 print '<tr><td colspan="7"><span class="opacitymedium">' . $langs->trans("None") . '</span></td></tr>';
11620 }
11621
11622 print '</table>';
11623
11624 if (!empty($compatibleImportElementsList)) {
11625 $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
11626 }
11627
11628 print '</div>';
11629 }
11630
11631 return $nbofdifferenttypes;
11632 }
11633
11643 public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array(), $nooutput = 0)
11644 {
11645 global $conf, $langs, $hookmanager, $form;
11646 global $action;
11647
11648 dol_syslog(__METHOD__, LOG_DEBUG);
11649
11650 if (empty($form)) {
11651 $form = new Form($this->db);
11652 }
11653
11654 $linktoelem = '';
11655 $linktoelemlist = '';
11656 $listofidcompanytoscan = '';
11657
11658 if (!is_object($object->thirdparty)) {
11659 if ($object->element == 'subscription' && isset($object->fk_adherent)) {
11660 $subby = new Subscription($object->db);
11661 $subby->fetch($object->id);
11662 $adh = new Adherent($object->db);
11663 //$fk_adherent = $object->fk_adherent;
11664 // creating new subscription object only to fetch the adherent which obviously exists given the if statement above are Inefficient, but else phan complains
11665 $fk_adherent = $subby->fk_adherent;
11666 $adh->fetch($fk_adherent);
11667 $thirdparty_id = $adh->fetch_thirdparty();
11668 }
11669 } else {
11670 $thirdparty_id = $object->thirdparty->id;
11671 }
11672
11673 $possiblelinks = array();
11674
11675 $dontIncludeCompletedItems = getDolGlobalString('DONT_INCLUDE_COMPLETED_ELEMENTS_LINKS');
11676
11677 // Maximum number of candidate objects fetched and rendered per link type.
11678 // The candidate lists are built on every object card load, so without a ceiling a thirdparty with a large
11679 // history makes this function run unbounded queries and serialize all of their rows into hidden HTML.
11680 // 0 = no limit (restores the historical unbounded behaviour).
11681 $maxcandidates = getDolGlobalInt('MAIN_LINKTOOBJECT_MAX_CANDIDATES', 100);
11682
11683 if (!empty($thirdparty_id) && $thirdparty_id > 0) {
11684 $listofidcompanytoscan = (int) $thirdparty_id;
11685 if (is_object($object->thirdparty) && ($object->thirdparty->parent > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PARENT_IN_LINKTO')) {
11686 $listofidcompanytoscan .= ',' . (int) $object->thirdparty->parent;
11687 }
11688 if (($object->fk_project > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO')) {
11689 include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
11690 $tmpproject = new Project($this->db);
11691 $tmpproject->fetch((int) $object->fk_project);
11692 if ($tmpproject->socid > 0 && ($tmpproject->socid != $thirdparty_id)) {
11693 $listofidcompanytoscan .= ',' . (int) $tmpproject->socid;
11694 }
11695 unset($tmpproject);
11696 }
11697
11698 $possiblelinks = array(
11699 'propal' => array(
11700 'enabled' => isModEnabled('propal'),
11701 'perms' => 1,
11702 'label' => 'LinkToProposal',
11703 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('propal') . ')'.($dontIncludeCompletedItems ? ' AND t.fk_statut < 4' : ''),
11704 ),
11705 'shipping' => array(
11706 'enabled' => isModEnabled('shipping'),
11707 'perms' => 1,
11708 'label' => 'LinkToExpedition',
11709 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "expedition as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('shipping') . ')'.($dontIncludeCompletedItems ? ' AND t.fk_statut < 2' : ''),
11710 ),
11711 'order' => array(
11712 'enabled' => isModEnabled('order'),
11713 'perms' => 1,
11714 'label' => 'LinkToOrder',
11715 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('commande') . ')'.($dontIncludeCompletedItems ? ' AND t.facture < 1' : ''),
11716 'linkname' => 'commande',
11717 ),
11718 'subscription' => array(
11719 'enabled' => isModEnabled('member'),
11720 'perms' => 1,
11721 'label' => 'LinkToMemberSubscription',
11722 'sql' => "SELECT a.fk_soc as socid, CONCAT(a.firstname, ' ', a.lastname) as name, a.entity as client, sub.rowid, sub.note as ref, '' as ref_client, sub.subscription as total_ht FROM " . $this->db->prefix() . "adherent as a, " . $this->db->prefix() . "subscription as sub WHERE sub.fk_adherent = a.rowid AND a.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND a.entity IN (' . getEntity('subscription') . ')',
11723 'linkname' => 'subscription',
11724 'orderby' => 'sub.rowid DESC', // This query does not use the 't' alias
11725 ),
11726 'conferenceorboothattendee' => array(
11727 'enabled' => isModEnabled('eventorganization'),
11728 'perms' => 1,
11729 'label' => 'LinkToConferenceOrBoothAttendee',
11730 'sql' => "SELECT s.rowid as socid, CONCAT(a.firstname, ' ', a.lastname) as name, a.rowid as rowid, a.fk_project as fk_project, a.ref as ref, a.email as email, a.date_subscription as date_subscription FROM "
11731 .$this->db->prefix()."societe as s, "
11732 .$this->db->prefix()."eventorganization_conferenceorboothattendee as a WHERE a.fk_soc = s.rowid AND a.fk_soc IN ("
11733 .$this->db->sanitize($listofidcompanytoscan) . ') AND s.entity IN (' . getEntity('conferenceorboothattendee') . ')'
11734 . (empty($object->fk_project) ? '' : ' AND a.fk_project = ' . (int) $object->fk_project),
11735 'linkname' => 'attendee',
11736 'orderby' => 'a.rowid DESC', // This query does not use the 't' alias
11737 ),
11738 'invoice' => array(
11739 'enabled' => isModEnabled('invoice'),
11740 'perms' => 1,
11741 'label' => 'LinkToInvoice',
11742 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('invoice') . ')'.($dontIncludeCompletedItems ? ' AND t.paye < 1' : ''),
11743 'linkname' => 'facture',
11744 ),
11745 'invoice_template' => array(
11746 'enabled' => isModEnabled('invoice'),
11747 'perms' => 1,
11748 'label' => 'LinkToTemplateInvoice',
11749 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('invoice') . ')',
11750 ),
11751 'contrat' => array(
11752 'enabled' => isModEnabled('contract'),
11753 'perms' => 1,
11754 'label' => 'LinkToContract',
11755 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_customer as ref_client, t.ref_supplier, SUM(td.total_ht) as total_ht
11756 FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "contrat as t, " . $this->db->prefix() . "contratdet as td WHERE t.fk_soc = s.rowid AND td.fk_contrat = t.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('contract') . ') GROUP BY s.rowid, s.nom, s.client, t.rowid, t.ref, t.ref_customer, t.ref_supplier',
11757 ),
11758 'fichinter' => array(
11759 'enabled' => isModEnabled('intervention'),
11760 'perms' => 1,
11761 'label' => 'LinkToIntervention',
11762 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('intervention') . ')',
11763 ),
11764 'supplier_proposal' => array(
11765 'enabled' => isModEnabled('supplier_proposal'),
11766 'perms' => 1,
11767 'label' => 'LinkToSupplierProposal',
11768 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('supplier_proposal') . ')'.($dontIncludeCompletedItems ? ' AND t.fk_statut < 4' : ''),
11769 ),
11770 'order_supplier' => array(
11771 'enabled' => isModEnabled("supplier_order"),
11772 'perms' => 1,
11773 'label' => 'LinkToSupplierOrder',
11774 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('commande_fournisseur') . ')'.($dontIncludeCompletedItems ? ' AND t.billed < 1' : ''),
11775 ),
11776 'invoice_supplier' => array(
11777 'enabled' => isModEnabled("supplier_invoice"),
11778 'perms' => 1, 'label' => 'LinkToSupplierInvoice',
11779 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('facture_fourn') . ')'.($dontIncludeCompletedItems ? ' AND t.paye < 1' : ''),
11780 ),
11781 'ticket' => array(
11782 'enabled' => isModEnabled('ticket'),
11783 'perms' => 1,
11784 'label' => 'LinkToTicket',
11785 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('ticket') . ')'.($dontIncludeCompletedItems ? ' AND t.fk_statut < 8' : ''),
11786 ),
11787 'mo' => array(
11788 'enabled' => isModEnabled('mrp'),
11789 'perms' => 1,
11790 'label' => 'LinkToMo',
11791 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM " . $this->db->prefix() . "societe as s INNER JOIN " . $this->db->prefix() . "mrp_mo as t ON t.fk_soc = s.rowid WHERE t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('mo') . ')'.($dontIncludeCompletedItems ? ' AND t.status < 3' : ''),
11792 ),
11793 );
11794 }
11795
11796 if ($object->table_element == 'commande_fournisseur') {
11797 $possiblelinks['mo']['sql'] = "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM ".$this->db->prefix()."societe as s INNER JOIN ".$this->db->prefix().'mrp_mo as t ON t.fk_soc = s.rowid WHERE t.entity IN ('.getEntity('mo').')'.($dontIncludeCompletedItems ? ' AND t.status < 3' : '');
11798 } elseif ($object->table_element == 'mrp_mo') {
11799 $possiblelinks['order_supplier']['sql'] = "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix().'commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.entity IN ('.getEntity('commande_fournisseur').')'.($dontIncludeCompletedItems ? ' AND t.billed < 1' : '');
11800 }
11801
11802 $reshook = 0; // Ensure $reshook is defined for static analysis
11803 if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
11804 // Can complete the possiblelink array
11805 $hookmanager->initHooks(array('commonobject'));
11806 $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
11807 $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
11808 }
11809
11810 if (empty($reshook)) {
11811 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
11812 $possiblelinks = array_merge($possiblelinks, $this->flagLinksFromHook($hookmanager->resArray));
11813 }
11814 } elseif ($reshook > 0) {
11815 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
11816 $possiblelinks = $this->flagLinksFromHook($hookmanager->resArray);
11817 }
11818 }
11819
11820 if (!empty($possiblelinks)) {
11821 $object->fetchObjectLinked();
11822 }
11823
11824 // Build the html part with possible suggested links
11825 $htmltoenteralink = '';
11826 foreach ($possiblelinks as $key => $possiblelink) {
11827 $num = 0;
11828 if (empty($possiblelink['enabled'])) {
11829 continue;
11830 }
11831
11832
11833 // If we ask a resource form external module (instead of default path)
11834 $module = '';
11835 if (preg_match('/^([^@]+)@([^@]+)$/i', $key, $regs)) { // 'myobject@mymodule'
11836 $key = $regs[1];
11837 $module = $regs[2];
11838 }
11839
11840 if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
11841 $htmltoenteralink .= '<div id="' . $key . 'list"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display:none"') . '>';
11842
11843 // Section for free ref input
11844 if (!getDolGlobalString('MAIN_HIDE_LINK_BY_REF_IN_LINKTO')) {
11845 $htmltoenteralink .= '<br>'."\n";
11846 $htmltoenteralink .= '<!-- form to add a link from anywhere -->'."\n";
11847 $htmltoenteralink .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
11848 $htmltoenteralink .= '<input type="hidden" name="token" value="' . newToken() . '">';
11849 $htmltoenteralink .= '<input type="hidden" name="action" value="addlinkbyref">';
11850 $htmltoenteralink .= '<input type="hidden" name="id" value="' . $object->id . '">';
11851 $htmltoenteralink .= '<input type="hidden" name="addlink" value="' . $key .(!empty($module) ? '@'.$module : ''). '">';
11852 $htmltoenteralink .= '<table class="noborder">';
11853 $htmltoenteralink .= '<tr class="liste_titre">';
11854 //print '<td>' . $langs->trans("Ref") . '</td>';
11855 $htmltoenteralink .= '<td class="center"><input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Ref")).'" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">';
11856 $htmltoenteralink .= '<br>';
11857 $htmltoenteralink .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;';
11858 $htmltoenteralink .= '<input type="submit" class="button smallpaddingimp" name="cancel" value="' . $langs->trans('Cancel') . '">';
11859 $htmltoenteralink .= '</td>';
11860 $htmltoenteralink .= '</tr>';
11861 $htmltoenteralink .= '</table>';
11862 $htmltoenteralink .= '</form>';
11863 }
11864
11865 $sql = $possiblelink['sql'];
11866
11867 // Bound the candidate list. We fetch one row more than the ceiling: if we get it, we know the list is
11868 // truncated without having to run a separate COUNT(*) for each link type.
11869 // An ORDER BY is mandatory here, otherwise the rows kept by the LIMIT would be an arbitrary subset.
11870 // We skip a query that is already limited or that comes from a hook without a known sort column, so a
11871 // query provided by an external module is never rewritten.
11872 $truncated = false;
11873 $applylimit = ($maxcandidates > 0 && !preg_match('/\bLIMIT\b/i', $sql));
11874 if ($applylimit && !empty($possiblelink['fromhook']) && empty($possiblelink['orderby'])) {
11875 $applylimit = false;
11876 }
11877 if ($applylimit) {
11878 // Note: the 4th parameter of sanitize() keeps the spaces, needed for a "field DESC" expression
11879 $sql .= ' ORDER BY '.$this->db->sanitize(empty($possiblelink['orderby']) ? 't.rowid DESC' : $possiblelink['orderby'], 0, 0, 1);
11880 $sql .= $this->db->plimit($maxcandidates + 1, 0);
11881 }
11882
11883 $resqllist = $this->db->query($sql);
11884 if ($resqllist) {
11885 $num = $this->db->num_rows($resqllist);
11886
11887 if ($applylimit && $num > $maxcandidates) {
11888 $truncated = true;
11889 $num = $maxcandidates; // Render the ceiling only, the extra row was fetched to detect truncation
11890 }
11891
11892 if ($num > 0) {
11893 // Section for free predefined list
11894 if (getDolGlobalString('MAIN_HIDE_LINK_BY_REF_IN_LINKTO')) {
11895 $htmltoenteralink .= '<br>';
11896 }
11897 // Tell the user the list is not complete, so a missing candidate is never silently hidden
11898 if ($truncated) {
11899 $htmltoenteralink .= '<div class="opacitymedium small paddingtopbottom">';
11900 $htmltoenteralink .= img_warning().' '.$langs->trans("LinkToObjectListTruncated", $maxcandidates);
11901 $htmltoenteralink .= '</div>';
11902 }
11903
11904 $htmltoenteralink .= '<!-- form to add a link from object to same thirdparty -->'."\n";
11905 $htmltoenteralink .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinked' . $key . '">';
11906 $htmltoenteralink .= '<input type="hidden" name="token" value="' . newToken() . '">';
11907 $htmltoenteralink .= '<input type="hidden" name="action" value="addlink">';
11908 $htmltoenteralink .= '<input type="hidden" name="id" value="' . $object->id . '">';
11909 $htmltoenteralink .= '<input type="hidden" name="addlink" value="' . $key . (!empty($module) ? '@'.$module : ''). '">';
11910 $htmltoenteralink .= '<table class="noborder">';
11911
11912 switch ($key) {
11913 case 'conferenceorboothattendee':
11914 // Custom logic for linking to attendees
11915 $htmltoenteralink .= $this->makeAddLinkToAttendee($object, $key, $possiblelink, $num, $resqllist);
11916 break;
11917
11918 default:
11919 // Standard logic for all other object types
11920 $htmltoenteralink .= $this->makeAddLinkToObject($object, $key, $possiblelink, $num, $resqllist);
11921 break;
11922 }
11923
11924 $htmltoenteralink .= '</table>';
11925 $htmltoenteralink .= '<div class="center">';
11926 if ($num) {
11927 $htmltoenteralink .= '<input type="submit" class="button valignmiddle marginleftonly marginrightonly smallpaddingimp" value="' . $langs->trans('ToLink') . '">';
11928 }
11929 if (empty($conf->use_javascript_ajax)) {
11930 $htmltoenteralink .= '<input type="submit" class="button button-cancel marginleftonly marginrightonly smallpaddingimp" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
11931 } else {
11932 $htmltoenteralink .= '<input type="submit" onclick="jQuery(\'#' . $key . 'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly smallpaddingimp" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
11933 }
11934 $htmltoenteralink .= '</form>';
11935 }
11936
11937 $this->db->free($resqllist);
11938 } else {
11939 dol_print_error($this->db);
11940 }
11941 $htmltoenteralink .= '</div>';
11942
11943
11944 // Complete the list for the combo box
11945 // When the list was truncated, $num is the ceiling and not the real total, so we show it as "100+"
11946 $nbtoshow = ($truncated ? $num.'+' : (string) $num);
11947 if ($num > 0 || !getDolGlobalString('MAIN_HIDE_LINK_BY_REF_IN_LINKTO')) {
11948 $linktoelemlist .= '<li><a href="#linkto' . $key . '" class="linkto dropdowncloseonclick" rel="' . $key . '">' . $langs->trans($possiblelink['label']) . ' (' . $nbtoshow . ')</a></li>';
11949 // } else $linktoelem.=$langs->trans($possiblelink['label']);
11950 } else {
11951 $linktoelemlist .= '<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
11952 }
11953 }
11954 }
11955
11956 if ($linktoelemlist) {
11957 $linktoelem = '
11958 <dl class="dropdown" id="linktoobjectname">
11959 ';
11960 if (!empty($conf->use_javascript_ajax)) {
11961 $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>' . $langs->trans("LinkTo") . '...</a></dt>';
11962 }
11963 $linktoelem .= '<dd>
11964 <div class="multiselectlinkto">
11965 <ul class="ulselectedfields">' . $linktoelemlist . '
11966 </ul>
11967 </div>
11968 </dd>
11969 </dl>';
11970 } else {
11971 $linktoelem = '';
11972 }
11973
11974 if (!empty($conf->use_javascript_ajax)) {
11975 print '<!-- Add js to show linkto box -->
11976 <script nonce="' . getNonce() . '">
11977 jQuery(document).ready(function() {
11978 jQuery(".linkto").click(function() {
11979 console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
11980 jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
11981 });
11982 });
11983 </script>
11984 ';
11985 }
11986
11987 if ($nooutput) {
11988 return array('linktoelem' => $linktoelem, 'htmltoenteralink' => $htmltoenteralink);
11989 } else {
11990 print $htmltoenteralink;
11991 }
11992
11993 return $linktoelem;
11994 }
11995
12010 public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = 'yesno width75', $labelyes = 'Yes', $labelno = 'No')
12011 {
12012 global $langs;
12013
12014 $yes = "yes";
12015 $no = "no";
12016 if ($option) {
12017 $yes = "1";
12018 $no = "0";
12019 }
12020
12021 $disabled = ($disabled ? ' disabled' : '');
12022
12023 $resultyesno = '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '"' . $disabled . '>' . "\n";
12024 if ($useempty) {
12025 $resultyesno .= '<option value="-1"' . (($value < 0) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
12026 }
12027 if (("$value" == 'yes') || ($value == 1)) {
12028 $resultyesno .= '<option value="' . $yes . '" selected>' . $langs->trans($labelyes) . '</option>' . "\n";
12029 $resultyesno .= '<option value="' . $no . '">' . $langs->trans($labelno) . '</option>' . "\n";
12030 } else {
12031 $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
12032 $resultyesno .= '<option value="' . $yes . '">' . $langs->trans($labelyes) . '</option>' . "\n";
12033 $resultyesno .= '<option value="' . $no . '"' . $selected . '>' . $langs->trans($labelno) . '</option>' . "\n";
12034 }
12035 $resultyesno .= '</select>' . "\n";
12036
12037 if ($addjscombo) {
12038 $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
12039 }
12040
12041 return $resultyesno;
12042 }
12043
12044 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
12045
12055 public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
12056 {
12057 // phpcs:enable
12058 $sql = "SELECT rowid, label";
12059 $sql .= " FROM " . $this->db->prefix() . "export_model";
12060 $sql .= " WHERE type = '" . $this->db->escape($type) . "'";
12061 $sql .= " ORDER BY rowid";
12062 $result = $this->db->query($sql);
12063 if ($result) {
12064 print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
12065 if ($useempty) {
12066 print '<option value="-1">&nbsp;</option>';
12067 }
12068
12069 $num = $this->db->num_rows($result);
12070 $i = 0;
12071 while ($i < $num) {
12072 $obj = $this->db->fetch_object($result);
12073 if ($selected == $obj->rowid) {
12074 print '<option value="' . $obj->rowid . '" selected>';
12075 } else {
12076 print '<option value="' . $obj->rowid . '">';
12077 }
12078 print $obj->label;
12079 print '</option>';
12080 $i++;
12081 }
12082 print "</select>";
12083 } else {
12084 dol_print_error($this->db);
12085 }
12086 }
12087
12106 public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
12107 {
12108 global $conf, $langs, $hookmanager, $extralanguages;
12109
12110 $ret = '';
12111 if (empty($fieldid)) {
12112 $fieldid = 'rowid';
12113 }
12114 if (empty($fieldref)) {
12115 $fieldref = 'ref';
12116 }
12117
12118 // Preparing gender's display if there is one
12119 $addgendertxt = '';
12120 if (property_exists($object, 'gender') && !empty($object->gender)) {
12121 $addgendertxt = ' ';
12122 switch ($object->gender) {
12123 case 'man':
12124 $addgendertxt .= '<i class="fas fa-mars valignmiddle"></i>';
12125 break;
12126 case 'woman':
12127 $addgendertxt .= '<i class="fas fa-venus valignmiddle"></i>';
12128 break;
12129 case 'other':
12130 $addgendertxt .= '<i class="fas fa-transgender valignmiddle"></i>';
12131 break;
12132 }
12133 }
12134
12135 // Add where from hooks
12136 if (is_object($hookmanager)) {
12137 $parameters = array('showrefnav' => true);
12138 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
12139 if (!empty($hookmanager->resPrint)) {
12140 if (empty($object->next_prev_filter) && preg_match('/^\s*AND/i', $hookmanager->resPrint)) {
12141 $object->next_prev_filter = (string) preg_replace('/^\s*AND\s*/i', '', $hookmanager->resPrint);
12142 } elseif (!empty($object->next_prev_filter) && !preg_match('/^\s*AND/i', $hookmanager->resPrint)) {
12143 $object->next_prev_filter .= ' AND '.$hookmanager->resPrint;
12144 } else {
12145 $object->next_prev_filter .= $hookmanager->resPrint;
12146 }
12147 }
12148 }
12149
12150 $previous_ref = $next_ref = '';
12151 if ($shownav) {
12152 //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,fieldid=$fieldid,filedref=$fieldref,morehtmlref=$morehtmlref,moreparam=$moreparam";
12153 $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
12154
12155 $navurl = $_SERVER["PHP_SELF"];
12156
12157 // Special case for token card
12158 if ($paramid == 'api_token_card') {
12159 if (preg_match('/\/user\/api_token/', $navurl)) {
12160 $navurl = preg_replace('/card/', 'list', $navurl);
12161 $paramid = 'id';
12162 }
12163 }
12164
12165 // Special case for project/task page
12166 if ($paramid == 'project_ref') {
12167 if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
12168 $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
12169 $paramid = 'ref';
12170 }
12171 }
12172
12173 $previous_ref = $object->ref_previous ? '<a accesskey="p" alt="'.dol_escape_htmltag($langs->trans("Previous")).'" title="' . $conf->browser->stringforfirstkey . ' p" class="classfortooltip reposition" href="' . $navurl . '?' . $paramid . '=' . urlencode($object->ref_previous) . $moreparam . '"><i class="fa fa-chevron-left"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
12174 $next_ref = $object->ref_next ? '<a accesskey="n" alt="'.dol_escape_htmltag($langs->trans("Next")).'" title="' . $conf->browser->stringforfirstkey . ' n" class="classfortooltip reposition" href="' . $navurl . '?' . $paramid . '=' . urlencode($object->ref_next) . $moreparam . '"><i class="fa fa-chevron-right"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
12175 }
12176
12177 //print "xx".$previous_ref."x".$next_ref;
12178 $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
12179
12180 // Right part of banner
12181 if ($morehtmlright) {
12182 $ret .= '<div class="inline-block floatleft">' . $morehtmlright . '</div>';
12183 }
12184
12185 if ($previous_ref || $next_ref || $morehtml) {
12186 $ret .= '<div class="pagination paginationref"><ul class="right">';
12187 }
12188 if ($morehtml && getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
12189 $ret .= '<!-- morehtml --><li class="noborder litext' . (($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '') . '">' . $morehtml . '</li>';
12190 }
12191 if ($shownav && ($previous_ref || $next_ref)) {
12192 $ret .= '<li class="pagination">' . $previous_ref . '</li>';
12193 $ret .= '<li class="pagination">' . $next_ref . '</li>';
12194 }
12195 if ($previous_ref || $next_ref || $morehtml) {
12196 $ret .= '</ul></div>';
12197 }
12198
12199 // Status
12200 $parameters = array('morehtmlstatus' => $morehtmlstatus);
12201 $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
12202 if (empty($reshook)) {
12203 $morehtmlstatus .= $hookmanager->resPrint;
12204 } else {
12205 $morehtmlstatus = $hookmanager->resPrint;
12206 }
12207 if ($morehtmlstatus) {
12208 $ret .= '<!-- status --><div class="statusref">' . $morehtmlstatus . '</div>';
12209 }
12210
12211 $parameters = array();
12212 $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
12213 if (empty($reshook)) {
12214 $morehtmlref .= $hookmanager->resPrint;
12215 } elseif ($reshook > 0) {
12216 $morehtmlref = $hookmanager->resPrint;
12217 }
12218
12219 // Left part of banner
12220 if ($morehtmlleft) {
12221 if ($conf->browser->layout == 'phone') {
12222 $ret .= '<!-- morehtmlleft --><div class="floatleft">' . $morehtmlleft . '</div>';
12223 } else {
12224 $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">' . $morehtmlleft . '</div>';
12225 }
12226 }
12227
12228 //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
12229 $ret .= '<!-- Ref or ID --><div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid' . (($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '') . '">';
12230
12231 // For thirdparty, contact, user, member, the ref is the id, so we show something else
12232 if ($object->element == 'societe') {
12233 $ret .= '<span class="valignmiddle">'.dolPrintHTML((string) $object->name).'</span>';
12234
12235 // List of extra languages
12236 $arrayoflangcode = array();
12237 if (getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE')) {
12238 $arrayoflangcode[] = getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE');
12239 }
12240
12241 if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
12242 if (!is_object($extralanguages)) {
12243 include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
12244 $extralanguages = new ExtraLanguages($this->db);
12245 }
12246 $extralanguages->fetch_name_extralanguages('societe');
12247
12248 // Guard against PHP 8 'Undefined array key' when MAIN_USE_ALTERNATE_TRANSLATION_FOR
12249 // is not configured and fetch_name_extralanguages() leaves attributes empty (issue #34596).
12250 if (!empty($extralanguages->attributes['societe']) && !empty($extralanguages->attributes['societe']['name'])) {
12251 $object->fetchValuesForExtraLanguages();
12252
12253 $htmltext = '';
12254 // If there is extra languages
12255 foreach ($arrayoflangcode as $extralangcode) {
12256 $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
12257 if ($object->array_languages['name'][$extralangcode]) {
12258 $htmltext .= $object->array_languages['name'][$extralangcode];
12259 } else {
12260 $htmltext .= '<span class="opacitymedium">' . $langs->trans("SwitchInEditModeToAddTranslation") . '</span>';
12261 }
12262 }
12263 $ret .= '<!-- Show translations of name -->' . "\n";
12264 $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
12265 }
12266 }
12267 } elseif ($object->element == 'member') {
12268 '@phan-var-force Adherent $object';
12269 $ret .= $object->ref . '<br>';
12270 $fullname = $object->getFullName($langs);
12271 if ($object->morphy == 'mor' && $object->societe) {
12272 $ret .= '<span class="valignmiddle">'.dolPrintHTML((string) $object->societe) . ((!empty($fullname) && $object->societe != $fullname) ? ' (' . dol_htmlentities($fullname) . $addgendertxt . ')' : '').'</span>';
12273 } else {
12274 $ret .= '<span class="valignmiddle">'.dolPrintHTML($fullname) . $addgendertxt . ((!empty($object->societe) && $object->societe != $fullname) ? ' (' . dol_htmlentities((string) $object->societe) . ')' : '').'</span>';
12275 }
12276 } elseif (in_array($object->element, array('contact', 'user'))) {
12277 $ret .= '<span class="valignmiddle">'.dolPrintHTML($object->getFullName($langs)).'</span>'.$addgendertxt;
12278 } elseif ($object->element == 'usergroup') {
12279 $ret .= dol_htmlentities((string) $object->name);
12280 } elseif (in_array($object->element, array('action', 'agenda'))) {
12281 '@phan-var-force ActionComm $object';
12282 $ret .= $object->ref . '<br>' . $object->label;
12283 } elseif (in_array($object->element, array('adherent_type'))) {
12284 $ret .= $object->label;
12285 } elseif ($object->element == 'ecm_directories') {
12286 $ret .= '';
12287 } elseif ($object->element == 'accountingbookkeeping' && !empty($object->context['mode']) && $object->context['mode'] == '_tmp') {
12288 $ret .= '<span class="valignmiddle">'.$langs->trans("Draft").'</span>';
12289 } elseif ($object instanceof Ticket) {
12290 '@phan-var-force Ticket $object';
12291 $ret .= '<span class="valignmiddle">'.dolPrintHTML(!empty($object->$fieldref) ? $object->$fieldref : "").'</span>';
12292 $ret .= ' &nbsp; <span class="nobold small" title="'.dolPrintHTMLForAttribute($langs->trans("TicketTrackId")).'">('.$object->track_id.')</span>';
12293 } elseif ($fieldref != 'none') {
12294 // Generic case
12295 $ret .= '<span class="valignmiddle">'.dolPrintHTML(!empty($object->$fieldref) ? $object->$fieldref : "").'</span>';
12296 }
12297 if ($morehtmlref) {
12298 // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
12299 if (substr($morehtmlref, 0, 4) != '<div') {
12300 $ret .= ' ';
12301 }
12302
12303 $ret .= '<!-- morehtmlref -->'.$morehtmlref;
12304 }
12305
12306 $ret .= '</div>';
12307
12308 $ret .= '</div><!-- End banner content -->';
12309
12310 return $ret;
12311 }
12312
12313
12322 public function showbarcode(&$object, $width = 100, $morecss = '')
12323 {
12324 //Check if barcode is filled in the card
12325 if (empty($object->barcode)) {
12326 return '';
12327 }
12328
12329 // Complete object if not complete
12330 if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
12331 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
12332 $result = $object->fetchBarCode();
12333 //Check if fetchBarCode() failed
12334 if ($result < 1) {
12335 return '<!-- ErrorFetchBarcode -->';
12336 }
12337 }
12338
12339 // Barcode image @phan-suppress-next-line PhanUndeclaredProperty
12340 $url = DOL_URL_ROOT . '/viewimage.php?modulepart=barcode&generator=' . urlencode($object->barcode_type_coder) . '&code=' . urlencode($object->barcode) . '&encoding=' . urlencode($object->barcode_type_code);
12341 $out = '<!-- url barcode = ' . $url . ' -->';
12342 $out .= '<img src="' . $url . '"' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
12343
12344 return $out;
12345 }
12346
12365 public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0, $usesharelinkifavailable = 0)
12366 {
12367 global $conf, $db, $langs;
12368
12369 $entity = (empty($object->entity) ? $conf->entity : $object->entity);
12370 $id = (empty($object->id) ? $object->rowid : $object->id); // @phan-suppress-current-line PhanUndeclaredProperty (->rowid)
12371
12372 $dir = '';
12373 $file = '';
12374 $originalfile = '';
12375 $altfile = '';
12376 $email = '';
12377 $capture = '';
12378 if ($modulepart == 'societe') {
12379 $dir = $conf->societe->multidir_output[$entity];
12380 if (!empty($object->logo)) {
12381 if (dolIsAllowedForPreview($object->logo)) {
12382 if ((string) $imagesize == 'mini') {
12383 $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
12384 } elseif ((string) $imagesize == 'small') {
12385 $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_small');
12386 } else {
12387 $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
12388 }
12389 $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
12390 }
12391 }
12392 $email = $object->email;
12393 } elseif ($modulepart == 'contact') {
12394 $dir = $conf->societe->multidir_output[$entity] . '/contact';
12395 $photo = $object->photo; // Copy to help static analysis
12396 if (!empty($photo)) {
12397 if (dolIsAllowedForPreview($photo)) {
12398 if ((string) $imagesize == 'mini') {
12399 $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($photo, '_mini');
12400 } elseif ((string) $imagesize == 'small') {
12401 $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($photo, '_small');
12402 } else {
12403 $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $photo;
12404 }
12405 $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $photo;
12406 }
12407 }
12408 $email = $object->email;
12409 $capture = 'user';
12410 } elseif ($modulepart == 'userphoto') {
12411 $dir = $conf->user->dir_output;
12412 $photo = $object->photo; // Copy to help static analysis
12413 if (!empty($photo)) {
12414 if (dolIsAllowedForPreview($photo)) {
12415 if ((string) $imagesize == 'mini') {
12416 $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($photo, '_mini');
12417 } elseif ((string) $imagesize == 'small') {
12418 $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($photo, '_small');
12419 } else {
12420 $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $photo;
12421 }
12422 $originalfile = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $photo;
12423 }
12424 }
12425 if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
12426 $altfile = $object->id . ".jpg"; // For backward compatibility
12427 }
12428 $email = $object->email;
12429 $capture = 'user';
12430 } elseif ($modulepart == 'memberphoto') {
12431 $dir = $conf->member->dir_output;
12432 $photo = $object->photo; // Copy to help static analysis
12433 if (!empty($photo)) {
12434 if (dolIsAllowedForPreview($photo)) {
12435 if ((string) $imagesize == 'mini') {
12436 $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($photo, '_mini');
12437 } elseif ((string) $imagesize == 'small') {
12438 $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($photo, '_small');
12439 } else {
12440 $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $photo;
12441 }
12442 $originalfile = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $photo;
12443 }
12444 }
12445 if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
12446 $altfile = $object->id . ".jpg"; // For backward compatibility
12447 }
12448 $email = $object->email;
12449 $capture = 'user';
12450 } else {
12451 // Generic case to show photos
12452 // TODO Implement this method in previous objects so we can always use this generic method.
12453 if ($modulepart != "unknown" && method_exists($object, 'getDataToShowPhoto')) {
12454 $tmpdata = $object->getDataToShowPhoto($modulepart, $imagesize);
12455
12456 $dir = $tmpdata['dir'];
12457 $file = $tmpdata['file'];
12458 $originalfile = $tmpdata['originalfile'];
12459 $altfile = $tmpdata['altfile'];
12460 $email = $tmpdata['email'];
12461 $capture = $tmpdata['capture'];
12462 }
12463 }
12464
12465 if ($forcecapture) {
12466 $capture = $forcecapture;
12467 }
12468
12469 $ret = '';
12470
12471 if ($dir) {
12472 if ($file && file_exists($dir . "/" . $file)) {
12473 if ($addlinktofullsize) {
12474 $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
12475 if ($urladvanced) {
12476 $ret .= '<a href="' . $urladvanced . '">';
12477 } else {
12478 $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
12479 }
12480 }
12481
12482 $sharekey = '';
12483 if ($usesharelinkifavailable) {
12484 // $dir is a full path '/home/.../dolibarr_documents/module'
12485 $relativefileforecm = preg_replace('/^'.preg_quote(DOL_DATA_ROOT.'/', '/').'/', '', $dir.'/'.$originalfile);
12486 // $relativefileforecme = 'module/...'
12487 require_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
12488 $ecmfiles = new EcmFiles($db);
12489 $ecmfiles->fetch(0, '', $relativefileforecm);
12490
12491 $sharekey = (string) $ecmfiles->share;
12492 }
12493
12494 if (!empty($sharekey)) {
12495 $ret .= '<img alt="" class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . ' photologo' . (preg_replace('/[^a-z]/i', '_', $file)) . '" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . '/viewimage.php?hashp=' . urlencode($sharekey) . '&cache=' . urlencode((string) $cache) . '">';
12496 } else {
12497 $ret .= '<img alt="" class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . ' photologo' . (preg_replace('/[^a-z]/i', '_', $file)) . '" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . urlencode($modulepart) . '&entity=' . ((int) $entity) . '&file=' . urlencode($file) . '&cache=' . urlencode((string) $cache) . '">';
12498 }
12499 if ($addlinktofullsize) {
12500 $ret .= '</a>';
12501 }
12502 } elseif ($altfile && file_exists($dir . "/" . $altfile)) {
12503 if ($addlinktofullsize) {
12504 $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
12505 if ($urladvanced) {
12506 $ret .= '<a href="' . $urladvanced . '">';
12507 } else {
12508 $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
12509 }
12510 }
12511 $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="Photo alt" id="photologo' . (preg_replace('/[^a-z]/i', '_', $file)) . '" class="' . $cssclass . '" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . urlencode($modulepart) . '&entity=' . ((int) $entity) . '&file=' . urlencode($altfile) . '&cache=' . urlencode((string) $cache) . '">';
12512 if ($addlinktofullsize) {
12513 $ret .= '</a>';
12514 }
12515 } else {
12516 $nophoto = '/public/theme/common/nophoto.png';
12517 $defaultimg = 'identicon'; // For gravatar
12518 if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
12519 if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && !empty($object->morphy) && strpos($object->morphy, 'mor') !== false)) {
12520 $nophoto = 'company';
12521 } else {
12522 $nophoto = '/public/theme/common/user_anonymous.png';
12523 if (!empty($object->gender) && $object->gender == 'man') {
12524 $nophoto = '/public/theme/common/user_man.png';
12525 }
12526 if (!empty($object->gender) && $object->gender == 'woman') {
12527 $nophoto = '/public/theme/common/user_woman.png';
12528 }
12529 }
12530 }
12531
12532 if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
12533 // see https://gravatar.com/site/implement/images/php/
12534 $ret .= '<!-- Put link to gravatar -->';
12535 $ret .= '<img class="gravatar photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" title="'.dolPrintHTMLForAttribute('Gravatar avatar - '.$email).'" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="https://www.gravatar.com/avatar/' . dol_hash(strtolower(trim($email)), 'sha256', 1) . '?s=' . $width . '&d=' . $defaultimg . '">'; // gravatar accepts a sha256 hash
12536 } else {
12537 if ($nophoto == 'company') {
12538 $ret .= '<div class="divforspanimg valignmiddle inline-block center photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . '>' . img_picto('', 'company') . '</div>';
12539 //$ret .= '<div class="difforspanimgright"></div>';
12540 } else {
12541 $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . $nophoto . '">';
12542 }
12543 }
12544 }
12545
12546 if ($caneditfield) {
12547 if ($object->photo) {
12548 $ret .= "<br>\n";
12549 }
12550 $ret .= '<table class="nobordernopadding centpercent">';
12551 if ($object->photo) {
12552 $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">' . $langs->trans("Delete") . '</label><br><br></td></tr>';
12553 }
12554 $ret .= '<tr><td class="tdoverflow">';
12555 $maxfilesizearray = getMaxFileSizeArray();
12556 $maxmin = $maxfilesizearray['maxmin'];
12557 if ($maxmin > 0) {
12558 $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">'; // MAX_FILE_SIZE must precede the field type=file
12559 }
12560 $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"' . ($capture ? ' capture="' . dolPrintHTMLForAttribute($capture) . '"' : '') . '>';
12561 $ret .= '</td></tr>';
12562 $ret .= '</table>';
12563 }
12564 }
12565
12566 return $ret;
12567 }
12568
12569 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
12570
12587 public function select_dolgroups($selected = 0, $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0', $multiple = false, $morecss = 'minwidth200')
12588 {
12589 // phpcs:enable
12590 global $conf, $user, $langs;
12591
12592 // Allow excluding groups
12593 $excludeGroups = null;
12594 if (is_array($exclude)) {
12595 $excludeGroups = implode(",", $exclude);
12596 }
12597 // Allow including groups
12598 $includeGroups = null;
12599 if (is_array($include)) {
12600 $includeGroups = implode(",", $include);
12601 }
12602
12603 if (!is_array($selected)) {
12604 $selected = array($selected);
12605 }
12606
12607 $out = '';
12608
12609 // Build sql to search groups
12610 $sql = "SELECT ug.rowid, ug.nom as name";
12611 if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
12612 $sql .= ", e.label";
12613 }
12614 $sql .= " FROM " . $this->db->prefix() . "usergroup as ug ";
12615 if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
12616 $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid=ug.entity";
12617 if ($force_entity) {
12618 $sql .= " WHERE ug.entity IN (0, " . ((int) $force_entity) . ")";
12619 } else {
12620 $sql .= " WHERE ug.entity IS NOT NULL";
12621 }
12622 } else {
12623 $sql .= " WHERE ug.entity IN (0, " . ((int) $conf->entity) . ")";
12624 }
12625 if (is_array($exclude) && $excludeGroups) {
12626 $sql .= " AND ug.rowid NOT IN (" . $this->db->sanitize($excludeGroups) . ")";
12627 }
12628 if (is_array($include) && $includeGroups) {
12629 $sql .= " AND ug.rowid IN (" . $this->db->sanitize($includeGroups) . ")";
12630 }
12631 $sql .= " ORDER BY ug.nom ASC";
12632
12633 dol_syslog(get_class($this) . "::select_dolgroups", LOG_DEBUG);
12634 $resql = $this->db->query($sql);
12635 if ($resql) {
12636 // Enhance with select2
12637 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
12638
12639 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
12640
12641 $num = $this->db->num_rows($resql);
12642 $i = 0;
12643 if ($num) {
12644 if ($show_empty && !$multiple) {
12645 $textforempty = '&nbsp;';
12646 if (!is_numeric($show_empty)) {
12647 $textforempty = dol_escape_htmltag($show_empty);
12648 }
12649 $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
12650 }
12651
12652 while ($i < $num) {
12653 $obj = $this->db->fetch_object($resql);
12654 $disableline = 0;
12655 if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
12656 $disableline = 1;
12657 }
12658
12659 $label = $obj->name;
12660 $labelhtml = $obj->name;
12661 if (isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1) {
12662 $label .= " (" . $obj->label . ")";
12663 $labelhtml .= ' <span class="opacitymedium">(' . $obj->label . ')</span>';
12664 }
12665
12666 $out .= '<option value="' . $obj->rowid . '"';
12667 if ($disableline) {
12668 $out .= ' disabled';
12669 }
12670 if ((isset($selected[0]) && is_object($selected[0]) && $selected[0]->id == $obj->rowid)
12671 || ((!isset($selected[0]) || !is_object($selected[0])) && !empty($selected) && in_array($obj->rowid, $selected))) {
12672 $out .= ' selected';
12673 }
12674 $out .= ' data-html="'.dol_escape_htmltag($labelhtml).'"';
12675 $out .= '>';
12676 $out .= $label;
12677 $out .= '</option>';
12678 $i++;
12679 }
12680 } else {
12681 if ($show_empty) {
12682 $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '></option>' . "\n";
12683 }
12684 $out .= '<option value="" disabled>' . $langs->trans("NoUserGroupDefined") . '</option>';
12685 }
12686 $out .= '</select>';
12687
12688 $out .= ajax_combobox($htmlname);
12689 } else {
12690 dol_print_error($this->db);
12691 }
12692
12693 return $out;
12694 }
12695
12696
12703 public function showFilterButtons($pos = '')
12704 {
12705 $out = '<div class="nowraponall">';
12706 $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fas fa-search"></span></button>';
12707 $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fas fa-times"></span></button>';
12708 $out .= '</div>';
12709
12710 return $out;
12711 }
12712
12721 public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
12722 {
12723 global $conf;
12724
12725 $out = '';
12726
12727 if (!empty($conf->use_javascript_ajax)) {
12728 $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="' . $cssclass . 's" name="' . $cssclass . 's" class="checkallactions"></div>';
12729 }
12730 $out .= '<script nonce="' . getNonce() . '">
12731 $(document).ready(function() {
12732 $("#' . $cssclass . 's").click(function() {
12733 if($(this).is(\':checked\')){
12734 console.log("We check all ' . $cssclass . ' and trigger the change method");
12735 $(".' . $cssclass . '").prop(\'checked\', true).trigger(\'change\');
12736 }
12737 else
12738 {
12739 console.log("We uncheck all");
12740 $(".' . $cssclass . '").prop(\'checked\', false).trigger(\'change\');
12741 }' . "\n";
12742 if ($calljsfunction) {
12743 $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "' . $massactionname . '", "' . $cssclass . '"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
12744 }
12745 $out .= ' });
12746 $(".' . $cssclass . '").change(function() {
12747 console.log("We check and change the tr class highlight after a change on .'.$cssclass.'");
12748 var $row = $(this).closest("tr");
12749 if ($row.length) {
12750 var anyChecked = $row.find(\'input[type="checkbox"].' . $cssclass . ':checked\').length > 0;
12751 console.log("anychecked="+anyChecked);
12752 if (!anyChecked) {
12753 $row.removeClass("highlight");
12754 } else {
12755 $row.addClass("highlight");
12756 }
12757 }
12758 });
12759 });
12760 </script>';
12761
12762 return $out;
12763 }
12764
12774 public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
12775 {
12776 $out = $this->showFilterButtons();
12777 if ($addcheckuncheckall) {
12778 $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
12779 }
12780 return $out;
12781 }
12782
12796 public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
12797 {
12798 global $langs, $user;
12799
12800 $out = '';
12801 $sql = "SELECT rowid, label FROM " . $this->db->prefix() . "c_exp_tax_cat WHERE active = 1";
12802 $sql .= " AND entity IN (0," . getEntity('c_exp_tax_cat') . ")";
12803 if (!empty($excludeid)) {
12804 $sql .= " AND rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeid)) . ")";
12805 }
12806 $sql .= " ORDER BY label";
12807
12808 $resql = $this->db->query($sql);
12809 if ($resql) {
12810 $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp maxwidth200">';
12811 if ($useempty) {
12812 $out .= '<option value="0">&nbsp;</option>';
12813 }
12814
12815 while ($obj = $this->db->fetch_object($resql)) {
12816 $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . $langs->trans($obj->label) . '</option>';
12817 }
12818 $out .= '</select>';
12819 $out .= ajax_combobox('select_' . $htmlname);
12820
12821 if (!empty($htmlname) && $user->admin && $info_admin) {
12822 $out .= ' ' . info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
12823 }
12824
12825 if (!empty($target)) {
12826 $sql = "SELECT c.id FROM " . $this->db->prefix() . "c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
12827 $resql = $this->db->query($sql);
12828 if ($resql) {
12829 if ($this->db->num_rows($resql) > 0) {
12830 $obj = $this->db->fetch_object($resql);
12831 $out .= '<script nonce="' . getNonce() . '">
12832 $(function() {
12833 $("select[name=' . $target . ']").on("change", function() {
12834 var current_val = $(this).val();
12835 if (current_val == ' . $obj->id . ') {';
12836 if (!empty($default_selected) || !empty($selected)) {
12837 $out .= '$("select[name=' . $htmlname . ']").val("' . ($default_selected > 0 ? $default_selected : $selected) . '");';
12838 }
12839
12840 $out .= '
12841 $("select[name=' . $htmlname . ']").change();
12842 }
12843 });
12844
12845 $("select[name=' . $htmlname . ']").change(function() {
12846
12847 if ($("select[name=' . $target . ']").val() == ' . $obj->id . ') {
12848 // get price of kilometer to fill the unit price
12849 $.ajax({
12850 method: "POST",
12851 dataType: "json",
12852 data: { fk_c_exp_tax_cat: $(this).val(), token: \'' . currentToken() . '\' },
12853 url: "' . (DOL_URL_ROOT . '/expensereport/ajax/ajaxik.php?' . implode('&', $params)) . '",
12854 }).done(function( data, textStatus, jqXHR ) {
12855 console.log(data);
12856 if (typeof data.up != "undefined") {
12857 $("input[name=value_unit]").val(data.up);
12858 $("select[name=' . $htmlname . ']").attr("title", data.title);
12859 } else {
12860 $("input[name=value_unit]").val("");
12861 $("select[name=' . $htmlname . ']").attr("title", "");
12862 }
12863 });
12864 }
12865 });
12866 });
12867 </script>';
12868 }
12869 }
12870 }
12871 } else {
12872 dol_print_error($this->db);
12873 }
12874
12875 return $out;
12876 }
12877
12886 public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
12887 {
12888 global $langs;
12889
12890 $out = '';
12891 $sql = "SELECT rowid, range_ik FROM " . $this->db->prefix() . "c_exp_tax_range";
12892 $sql .= " WHERE entity IN (0," . getEntity('c_exp_tax_range') . ") AND active = 1";
12893
12894 $resql = $this->db->query($sql);
12895 if ($resql) {
12896 $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
12897 if ($useempty) {
12898 $out .= '<option value="0"></option>';
12899 }
12900
12901 while ($obj = $this->db->fetch_object($resql)) {
12902 $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . price($obj->range_ik, 0, $langs, 1, 0) . '</option>';
12903 }
12904 $out .= '</select>';
12905 } else {
12906 dol_print_error($this->db);
12907 }
12908
12909 return $out;
12910 }
12911
12922 public function selectExpenseFees($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
12923 {
12924 global $langs;
12925
12926 $out = '';
12927 $sql = "SELECT id, code, label";
12928 $sql .= " FROM ".$this->db->prefix()."c_type_fees";
12929 $sql .= " WHERE active = 1";
12930
12931 $resql = $this->db->query($sql);
12932 if ($resql) {
12933 $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
12934 if ($useempty) {
12935 $out .= '<option value="0"></option>';
12936 }
12937 if ($allchoice) {
12938 $out .= '<option value="-1">' . $langs->trans('AllExpenseReport') . '</option>';
12939 }
12940
12941 $field = 'code';
12942 if ($useid) {
12943 $field = 'id';
12944 }
12945
12946 while ($obj = $this->db->fetch_object($resql)) {
12947 $key = $langs->trans($obj->code);
12948 $out .= '<option ' . ($selected == $obj->{$field} ? 'selected="selected"' : '') . ' value="' . $obj->{$field} . '">' . ($key != $obj->code ? $key : $obj->label) . '</option>';
12949 }
12950 $out .= '</select>';
12951
12952 $out .= ajax_combobox('select_'.$htmlname);
12953 } else {
12954 dol_print_error($this->db);
12955 }
12956
12957 return $out;
12958 }
12959
12978 public function selectInvoiceForTimeProject($socid = -1, $selected = '', $htmlname = 'invoiceid', $maxlength = 24, $option_only = 0, $show_empty = '1', $discard_closed = 0, $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500', $projectsListId = '', $showproject = 'all', $usertofilter = null)
12979 {
12980 global $user, $conf, $langs;
12981
12982 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
12983
12984 if (is_null($usertofilter)) {
12985 $usertofilter = $user;
12986 }
12987
12988 $out = '';
12989
12990 $hideunselectables = false;
12991 if (getDolGlobalString('INVOICE_HIDE_UNSELECTABLES')) {
12992 $hideunselectables = true;
12993 }
12994
12995 if (empty($projectsListId)) {
12996 if (!$usertofilter->hasRight('projet', 'all', 'lire')) {
12997 $projectstatic = new Project($this->db);
12998 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
12999 }
13000 }
13001
13002 // Search all projects
13003 $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref, p.title, p.fk_soc, p.fk_statut, p.public, s.nom as name";
13004 $sql .= " FROM " . $this->db->prefix() . "facture as f";
13005 $sql .= " INNER JOIN " . $this->db->prefix() . "projet as p ON p.entity IN (" . getEntity('project') . ") AND f.fk_projet = p.rowid";
13006 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON s.rowid = p.fk_soc";
13007 $sql .= " WHERE f.fk_statut = 0"; // Draft invoices only
13008 //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
13009 //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
13010 //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
13011 $sql .= " ORDER BY p.ref, f.ref ASC";
13012
13013 $resql = $this->db->query($sql);
13014 if ($resql) {
13015 // Use select2 selector
13016 if (!empty($conf->use_javascript_ajax)) {
13017 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
13018 $comboenhancement = ajax_combobox($htmlname, array(), 0, $forcefocus);
13019 $out .= $comboenhancement;
13020 $morecss = 'minwidth200imp maxwidth500';
13021 }
13022
13023 if (empty($option_only)) {
13024 $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
13025 }
13026 if (!empty($show_empty)) {
13027 $out .= '<option value="0" class="optiongrey">';
13028 if (!is_numeric($show_empty)) {
13029 $out .= $show_empty;
13030 } else {
13031 $out .= '&nbsp;';
13032 }
13033 $out .= '</option>';
13034 }
13035 $num = $this->db->num_rows($resql);
13036 $i = 0;
13037 if ($num) {
13038 while ($i < $num) {
13039 $obj = $this->db->fetch_object($resql);
13040 // If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
13041 if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && !$usertofilter->hasRight('societe', 'lire')) {
13042 // Do nothing
13043 } else {
13044 if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
13045 $i++;
13046 continue;
13047 }
13048
13049 $labeltoshow = '';
13050
13051 if ($showproject == 'all') {
13052 $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
13053 if ($obj->name) {
13054 $labeltoshow .= ' - ' . $obj->name; // Soc name
13055 }
13056
13057 $disabled = 0;
13058 if ($obj->fk_statut == Project::STATUS_DRAFT) {
13059 $disabled = 1;
13060 $labeltoshow .= ' - ' . $langs->trans("Draft");
13061 } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
13062 if ($discard_closed == 2) {
13063 $disabled = 1;
13064 }
13065 $labeltoshow .= ' - ' . $langs->trans("Closed");
13066 } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
13067 $disabled = 1;
13068 $labeltoshow .= ' - ' . $langs->trans("LinkedToAnotherCompany");
13069 }
13070 }
13071
13072 if (!empty($selected) && $selected == $obj->rowid) {
13073 $out .= '<option value="' . $obj->rowid . '" selected';
13074 //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
13075 $out .= '>' . $labeltoshow . '</option>';
13076 } else {
13077 if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
13078 $resultat = '';
13079 } else {
13080 $resultat = '<option value="' . $obj->rowid . '"';
13081 if ($disabled) {
13082 $resultat .= ' disabled';
13083 }
13084 //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
13085 //else $labeltoshow.=' ('.$langs->trans("Private").')';
13086 $resultat .= '>';
13087 $resultat .= $labeltoshow;
13088 $resultat .= '</option>';
13089 }
13090 $out .= $resultat;
13091 }
13092 }
13093 $i++;
13094 }
13095 }
13096 if (empty($option_only)) {
13097 $out .= '</select>';
13098 }
13099
13100 $this->db->free($resql);
13101
13102 return $out;
13103 } else {
13104 dol_print_error($this->db);
13105 return '';
13106 }
13107 }
13108
13123 public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
13124 {
13125 global $conf, $langs;
13126
13127 $out = '';
13128
13129 dol_syslog('FactureRec::fetch', LOG_DEBUG);
13130
13131 $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
13132 $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
13133 $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
13134 $sql .= " ORDER BY f.titre ASC";
13135
13136 $resql = $this->db->query($sql);
13137 if ($resql) {
13138 // Use select2 selector
13139 if (!empty($conf->use_javascript_ajax)) {
13140 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
13141 $comboenhancement = ajax_combobox($htmlname, array(), 0, $forcefocus);
13142 $out .= $comboenhancement;
13143 $morecss = 'minwidth200imp maxwidth500';
13144 }
13145
13146 if (empty($option_only)) {
13147 $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
13148 }
13149 if (!empty($show_empty)) {
13150 $out .= '<option value="0" class="optiongrey">';
13151 if (!is_numeric($show_empty)) {
13152 $out .= $show_empty;
13153 } else {
13154 $out .= '&nbsp;';
13155 }
13156 $out .= '</option>';
13157 }
13158 $num = $this->db->num_rows($resql);
13159 if ($num) {
13160 while ($obj = $this->db->fetch_object($resql)) {
13161 $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
13162
13163 $disabled = 0;
13164 if (!empty($obj->suspended)) {
13165 $disabled = 1;
13166 $labeltoshow .= ' - ' . $langs->trans("Closed");
13167 }
13168
13169
13170 if (!empty($selected) && $selected == $obj->rowid) {
13171 $out .= '<option value="' . $obj->rowid . '" selected';
13172 //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
13173 $out .= '>' . $labeltoshow . '</option>';
13174 } else {
13175 if ($disabled && ($selected != $obj->rowid)) {
13176 $resultat = '';
13177 } else {
13178 $resultat = '<option value="' . $obj->rowid . '"';
13179 if ($disabled) {
13180 $resultat .= ' disabled';
13181 }
13182 $resultat .= '>';
13183 $resultat .= $labeltoshow;
13184 $resultat .= '</option>';
13185 }
13186 $out .= $resultat;
13187 }
13188 }
13189 }
13190 if (empty($option_only)) {
13191 $out .= '</select>';
13192 }
13193
13194 print $out;
13195
13196 $this->db->free($resql);
13197 return $num;
13198 } else {
13199 $this->errors[] = $this->db->lasterror;
13200 return -1;
13201 }
13202 }
13203
13204
13215 public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '', $arrayoffiltercriterias = array())
13216 {
13217 // TODO: Use $arrayoffiltercriterias param instead of $arrayofcriterias to include linked object fields in search
13218 global $langs, $form;
13219
13220 if ($search_component_params_hidden != '' && !preg_match('/^\‍(.*\‍)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
13221 $search_component_params_hidden = '(' . $search_component_params_hidden . ')';
13222 }
13223
13224 $ret = '<!-- filterComponent -->';
13225
13226 $ret .= '<div class="divadvancedsearchfieldcomp centpercent inline-block">';
13227 $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor" tabindex="-1">';
13228 $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="' . dol_escape_htmltag($langs->trans("Filters")) . '" id="idsubimgproductdistribution"></span>';
13229 $ret .= '</a>';
13230
13231 $ret .= '<div class="divadvancedsearchfieldcompinput centpercentminusx inline-block minwidth500">';
13232
13233 // Show select fields as tags.
13234 $ret .= '<div id="divsearch_component_params" name="divsearch_component_params" class="noborderbottom search_component_params inline-block">';
13235
13236 if ($search_component_params_hidden) {
13237 // Split the criteria on each AND
13238 //var_dump($search_component_params_hidden);
13239
13240 $arrayofandtags = dolForgeExplodeAnd($search_component_params_hidden);
13241
13242 // $arrayofandtags is now array( '...' , '...', ...)
13243 // Show each AND part
13244 foreach ($arrayofandtags as $tmpkey => $tmpval) {
13245 $errormessage = '';
13246 $searchtags = forgeSQLFromUniversalSearchCriteria($tmpval, $errormessage, 1, 1);
13247 if ($errormessage) {
13248 $this->error = 'ERROR in parsing search string: '.$errormessage;
13249 }
13250 // Remove first and last parenthesis but only if first is the opening and last the closing of the same group
13251 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
13252 $searchtags = removeGlobalParenthesis($searchtags);
13253
13254 $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch" data-ufilterid="'.($tmpkey + 1).'" data-ufilter="'.dol_escape_htmltag($tmpval).'">';
13255 $ret .= '<span class="tagsearchdelete select2-selection__choice__remove" data-ufilterid="'.($tmpkey + 1).'">x</span> ';
13256 $ret .= dol_escape_htmltag($searchtags);
13257 $ret .= '</span>';
13258 }
13259 }
13260
13261 //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
13262
13263 //$ret .= search_component_params
13264 //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
13265 //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
13266
13267 $show_search_component_params_hidden = 1;
13268 if ($show_search_component_params_hidden) {
13269 $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
13270 }
13271 $ret .= "<!-- We store the full Universal Search String into this field. For example: (t.ref:like:'SO-%') AND ((t.ref:like:'CO-%') OR (t.ref:like:'AA%')) -->";
13272 $ret .= '<input type="hidden" id="search_component_params_hidden" name="search_component_params_hidden" value="' . dol_escape_htmltag($search_component_params_hidden) . '">';
13273 // $ret .= "<!-- sql= ".forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage)." -->";
13274
13275 // TODO : Use $arrayoffiltercriterias instead of $arrayofcriterias
13276 // For compatibility with forms that show themselves the search criteria in addition of this component, we output these fields
13277 foreach ($arrayofcriterias as $criteria) {
13278 foreach ($criteria as $criteriafamilykey => $criteriafamilyval) {
13279 if (in_array('search_' . $criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
13280 continue;
13281 }
13282 if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
13283 continue;
13284 }
13285 if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
13286 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_start">';
13287 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startyear">';
13288 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startmonth">';
13289 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startday">';
13290 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_end">';
13291 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endyear">';
13292 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endmonth">';
13293 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endday">';
13294 } else {
13295 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '">';
13296 }
13297 }
13298 }
13299
13300 $ret .= '</div>';
13301
13302 $ret .= "<!-- Field to enter a generic filter string: t.ref:like:'SO-%', t.date_creation:>:'20160101', t.date_creation:<:'2016-01-01 12:30:00', t.nature:is:NULL, t.field2:isnot:NULL -->\n";
13303 $ret .= '<input type="text" placeholder="' . $langs->trans("Filters") . '" id="search_component_params_input" name="search_component_params_input" class="noborderall search_component_input" value="">';
13304
13305 $ret .= '</div>';
13306 $ret .= '</div>';
13307
13308 $ret .= '<script>
13309 jQuery("#divsearch_component_params").on("click", ".tagsearchdelete", function(e) { /* Delegated, so it works also for tags added by JS */
13310 var filterid = $(this).parents().attr("data-ufilterid");
13311 console.log("We click to delete the criteria nb "+filterid);
13312
13313 // Regenerate the search_component_params_hidden with all data-ufilter except the one to delete, and post the page
13314 var newparamstring = \'\';
13315 $(\'.tagsearch[data-ufilterid]\').each(function(index, element) {
13316 tmpfilterid = $(this).attr("data-ufilterid");
13317 if (tmpfilterid != filterid) {
13318 // We keep this criteria
13319 if (newparamstring == \'\') {
13320 newparamstring = $(this).attr("data-ufilter");
13321 } else {
13322 newparamstring = newparamstring + \' AND \' + $(this).attr("data-ufilter");
13323 }
13324 }
13325 });
13326 console.log("newparamstring = "+newparamstring);
13327
13328 jQuery("#search_component_params_hidden").val(newparamstring);
13329
13330 // We repost the form
13331 $(this).closest(\'form\').submit();
13332 });
13333
13334 jQuery("#search_component_params_input").keydown(function(e) {
13335 console.log("We press a key on the filter field that is "+jQuery("#search_component_params_input").val());
13336 console.log(e.which);
13337 if (jQuery("#search_component_params_input").val() == "" && e.which == 8) {
13338 /* We click on back when the input field is already empty */
13339 event.preventDefault();
13340 jQuery("#divsearch_component_params .tagsearch").last().remove();
13341 /* Regenerate content of search_component_params_hidden from remaining .tagsearch */
13342 var s = "";
13343 jQuery("#divsearch_component_params .tagsearch").each(function( index ) {
13344 if (s != "") {
13345 s = s + " AND ";
13346 }
13347 s = s + $(this).attr("data-ufilter");
13348 });
13349 console.log("New value for search_component_params_hidden = "+s);
13350 jQuery("#search_component_params_hidden").val(s);
13351 }
13352 });
13353
13354 </script>
13355 ';
13356
13357 // Convert $arrayoffiltercriterias into a json object that can be used in jquery to build the search component dynamically
13358 $arrayoffiltercriterias_json = json_encode($arrayoffiltercriterias);
13359
13360 // Build $arrayoffilterelements that is an array of elements (tables) with the list of their fields,
13361 // so we can show a single 2 levels combo: select first the element (the table), then the field appears
13362 // into the same combo, in a second level shown under the element
13363 $arrayoffilterelements = array();
13364
13365 foreach ($arrayoffiltercriterias as $key => $val) {
13366 // Discard the fields declared with attribute 'bi' set to 0 (field hidden on BI tool).
13367 // The array is flat, so this also discards the fields of the sub-elements (the sub-tables).
13368 if (isset($val['bi']) && (int) $val['bi'] == 0) {
13369 continue;
13370 }
13371 // The element (table) is the part of the field key before the last dot ('t.ref' -> 't', 't__fk_project.ref' -> 't__fk_project')
13372 $tmpelementkey = preg_replace('/\.[^.]*$/', '', $key);
13373 // Extrafields of an element are stored with the alias 'te', 'te__...', so we map them onto the same element than their parent table 't', 't__...'
13374 $tmpelementkey = preg_replace('/^te(__|$)/', 't$1', $tmpelementkey);
13375
13376 $tmpelementlabel = $tmpelementkey;
13377 $tmpelementpicto = '';
13378 $tmpfieldlabel = $key;
13379 if (!empty($val['labelnohtml'])) {
13380 $tmpfieldlabel = $val['labelnohtml'];
13381 // The labelnohtml is 'LabelOfElement: LabelOfField', so we extract the label of the element and the label of the field
13382 $tmpmatch = array();
13383 if (preg_match('/^(.+?): /', $val['labelnohtml'], $tmpmatch)) {
13384 $tmpelementlabel = $tmpmatch[1];
13385 $tmpfieldlabel = trim(substr($val['labelnohtml'], strlen($tmpelementlabel) + 1));
13386 }
13387 if (!empty($val['label'])) {
13388 // The label is the picto of the element followed by the labelnohtml, so we extract the picto of the element
13389 $tmpelementpicto = trim(str_replace($val['labelnohtml'], '', $val['label']));
13390 }
13391 }
13392
13393 if (!isset($arrayoffilterelements[$tmpelementkey])) {
13394 $arrayoffilterelements[$tmpelementkey] = array('picto' => $tmpelementpicto, 'label' => $tmpelementlabel, 'fields' => array());
13395 }
13396 $arrayoffilterelements[$tmpelementkey]['fields'][$key] = array('label' => $tmpfieldlabel, 'type' => $val['type']);
13397 }
13398 $ret .= '<script>
13399 var arrayoffiltercriterias = ' . $arrayoffiltercriterias_json . ';
13400 </script>';
13401
13402
13403 // Adding the div for search assistance
13404 $ret .= '<div class="search-component-assistance">';
13405 $ret .= '<div>';
13406
13407 $ret .= '<p class="assistance-title">' . img_picto('', 'filter') . ' ' . $langs->trans('FilterAssistance') . ' </p>';
13408
13409 $ret .= '<p class="assistance-errors error" style="display:none">' . $langs->trans('AllFieldsRequired') . ' </p>';
13410
13411 // Combo with 2 levels to select the field: select first the element (the table), the list of fields of the element
13412 // appears then under the element into the same combo, then select the field
13413 // (this is a pure JS combo, we do not use select2 for this component)
13414 $ret .= '<div class="operand valigntop">';
13415 $ret .= '<div class="fieldcombo">';
13416 // Hidden input to store the selected field ('' or a field key like 't.ref' or 't__fk_project.ref')
13417 $ret .= '<input type="hidden" id="search_filter_field" name="search_filter_field" value="">';
13418 // Button of the combo (show the placeholder "Fields" or the selected "element: field")
13419 $ret .= '<button type="button" class="fieldcombo-toggle"><span class="fieldcombo-label opacitymedium">' . dol_escape_htmltag($langs->trans('Fields')) . '</span><span class="fas fa-caret-down fieldcombo-caret"></span></button>';
13420 // Panel of the combo, with the list of elements (the root tables), and into each element, the list of
13421 // its fields then the list of its sub-elements (sub-tables, indented, after the fields). The fields and
13422 // the sub-elements are hidden by default and shown only after a search or a click on the element.
13423 $ret .= '<div class="fieldcombo-panel" style="display:none">';
13424 $ret .= '<div class="liinputsearch"><input type="text" class="fieldcombo-search noborderfocus" placeholder="' . dol_escape_htmltag($langs->trans('Search')) . '"></div>';
13425 $ret .= '<div class="fieldcombo-list">';
13426
13427
13428 // Recursive rendering of an element of the combo, with the list of its sub-elements (indented into it)
13429 // and the list of its fields. A direct sub-element is an element whose key starts with the key of its parent
13430 // element followed by '__', without any other '__' after (so 't__fk_soc' is a sub-element of 't',
13431 // 't__fk_soc__fk_pays' is a sub-element of 't__fk_soc' and not a direct sub-element of 't')
13436 $renderElementCombo = function ($tmpelementkey) use ($arrayoffilterelements, &$renderElementCombo) {
13437 $tmpelementval = $arrayoffilterelements[$tmpelementkey];
13438 $arrayofchildelementkeys = array();
13439 foreach ($arrayoffilterelements as $tmpchildelementkey => $tmpchildelementval) {
13440 if (strpos($tmpchildelementkey, $tmpelementkey.'__') === 0 && strpos(substr($tmpchildelementkey, strlen($tmpelementkey) + 2), '__') === false) {
13441 $arrayofchildelementkeys[] = $tmpchildelementkey;
13442 }
13443 }
13444 $out = '';
13445 $out .= '<div class="fieldcombo-element" data-element="' . dolPrintHTMLForAttribute($tmpelementkey) . '">';
13446 $out .= '<div class="fieldcombo-elementheader" tabindex="0"><span class="fieldcombo-elementlabel">' . $tmpelementval['picto'] . ' ' . dol_escape_htmltag($tmpelementval['label']) . '</span><span class="fas fa-caret-right fieldcombo-elementcaret"></span></div>';
13447 // The list of fields is hidden by default, it is shown only after a search or a click on the element
13448 $out .= '<div class="fieldcombo-fields" style="display:none">';
13449 foreach ($tmpelementval['fields'] as $tmpfieldkey => $tmpfieldval) {
13450 $out .= '<div class="fieldcombo-field" tabindex="0" data-field="' . dolPrintHTMLForAttribute($tmpfieldkey) . '" data-type="' . dolPrintHTMLForAttribute($tmpfieldval['type']) . '">' . dol_escape_htmltag($tmpfieldval['label']) . '</div>';
13451 }
13452 $out .= '</div>';
13453 if (!empty($arrayofchildelementkeys)) {
13454 // The list of sub-elements is shown after the fields, it is hidden by default and it is shown
13455 // (indented) only after a search or a click on the element
13456 $out .= '<div class="fieldcombo-children" style="display:none">';
13457 foreach ($arrayofchildelementkeys as $tmpchildelementkey) {
13458 $out .= $renderElementCombo($tmpchildelementkey);
13459 }
13460 $out .= '</div>';
13461 }
13462 $out .= '</div>';
13463 return $out;
13464 };
13465
13466
13467 // Render the list of fields we can use as filter
13468 foreach ($arrayoffilterelements as $tmpelementkey => $tmpelementval) {
13469 // The parent element is the part of the key before the last '__' ('t__fk_soc' -> 't', 't__fk_soc__fk_pays' -> 't__fk_soc')
13470 $tmpparentkey = '';
13471 if (strpos($tmpelementkey, '__') !== false) {
13472 $tmparrayofkey = explode('__', $tmpelementkey);
13473 array_pop($tmparrayofkey);
13474 $tmpparentkey = implode('__', $tmparrayofkey);
13475 }
13476 // At root level, we render only the elements without parent element (or with a parent not found into
13477 // the list), the sub-elements are rendered recursively into their parent element
13478 if ($tmpparentkey == '' || !isset($arrayoffilterelements[$tmpparentkey])) {
13479 $ret .= $renderElementCombo($tmpelementkey);
13480 }
13481 }
13482 $ret .= '</div>';
13483 $ret .= '</div>';
13484 $ret .= '</div>';
13485 $ret .= '</div>';
13486
13487 $ret .= '<span class="separator"></span>';
13488
13489 // Operator selector (will be populated dynamically)
13490 $ret .= '<div class="operator valigntop">';
13491 $ret .= '<select class="operator-selector width150" id="operator-selector"">';
13492 $ret .= '</select>';
13493 $ret .= '<script>$(document).ready(function() {';
13494 $ret .= ' $(".operator-selector").select2({';
13495 $ret .= ' dropdownCssClass: \'operator-selector-dropdown\','; // To have a smaller height of options than other select2 (need full version of select2)
13496 $ret .= ' placeholder: \'' . dol_escape_js($langs->transnoentitiesnoconv('Operator')) . '\'';
13497 $ret .= ' });';
13498 // Press the down or right arrow on the closed combo: open it (select2 opens it only with Enter, Space or Alt+Down)
13499 $ret .= ' $(".operator-selector").next(".select2-container").find(".select2-selection").on("keydown", function(e) {';
13500 $ret .= ' if ((e.key === "ArrowDown" || e.key === "ArrowRight") && !$(this).closest(".select2-container").hasClass("select2-container--open")) {';
13501 $ret .= ' e.preventDefault();';
13502 $ret .= ' $(".operator-selector").select2("open");';
13503 $ret .= ' }';
13504 $ret .= ' });';
13505 $ret .= '});</script>';
13506 $ret .= '</div>';
13507
13508 $ret .= '<span class="separator"></span>';
13509
13510 $ret .= '<div class="value valigntop">';
13511 // Input field for entering values
13512 $ret .= '<input type="text" class="flat width100 value-input" placeholder="' . dolPrintHTML($langs->trans('Value')) . '">';
13513
13514 // Date selector
13515 $dateOne = '';
13516 $ret .= '<span class="date-one" style="display:none">';
13517 $ret .= $form->selectDate(($dateOne ? $dateOne : -1), 'dateone', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '');
13518 $ret .= '</span>';
13519
13520 // Value selector (will be populated dynamically) based on search_filter_field value if a selected value has an array of values
13521 $ret .= '<select class="value-selector width150" id="value-selector" style="display:none">';
13522 $ret .= '</select>';
13523 $ret .= '<script>
13524 $(document).ready(function() {
13525 $("#value-selector").select2({
13526 placeholder: \'' . dol_escape_js($langs->trans('Value')) . '\'
13527 });
13528 $("#value-selector").hide();
13529 $("#value-selector").next(".select2-container").hide();
13530 });
13531 </script>';
13532
13533 $ret .= '</div>';
13534
13535 $ret .= '<div class="btn-div">';
13536 $ret .= '<button class="butAction add-filter-btn" type="button">' . $langs->trans("addToFilter") . '</button>';
13537 $ret .= '</div>';
13538
13539 $ret .= '</div>';
13540 //$ret .= '</tbody></table>';
13541
13542 // End of the assistance div
13543 $ret .= '</div>';
13544
13545 // Script jQuery to show/hide the floating assistance
13546 $ret .= '<script>
13547 $(document).ready(function() {
13548 $("#search_component_params_input").closest(".divadvancedsearchfieldcompinput").on("click", function(e) {
13549 // Open the assistance on a click in the zone of filters, except on a tag
13550 if ($(e.target).closest(".tagsearch").length) {
13551 return;
13552 }
13553 const inputPosition = $("#search_component_params_input").offset();
13554 const inputHeight = $("#search_component_params_input").outerHeight();
13555 $(".search-component-assistance").css({
13556 top: inputPosition.top + inputHeight + 5 + "px",
13557 left: $("#divsearch_component_params").position().left
13558 }).slideToggle(200);
13559 });
13560 $(document).on("click", function(e) {
13561 if (!$(e.target).closest(".search-component-assistance, #ui-datepicker-div").length && !$(e.target).closest(".divadvancedsearchfieldcompinput").find("#search_component_params_input").length) {
13562 $(".search-component-assistance").hide();
13563 }
13564 });
13565 // Press the down arrow (or the right arrow at the end of the text) into the field Filters to open the filter editor
13566 $("#search_component_params_input").on("keydown", function(e) {
13567 if (e.key !== "ArrowDown" && !(e.key === "ArrowRight" && this.selectionStart === this.value.length)) {
13568 return;
13569 }
13570 if ($(".search-component-assistance").is(":visible")) {
13571 return;
13572 }
13573 e.preventDefault();
13574 $(this).trigger("click"); // Open the editor with the same code than a click into the zone of filters
13575 $(".fieldcombo-toggle").trigger("focus");
13576 });
13577 // Press Escape to close the filter editor. We use the capture phase to know the state before the handlers of
13578 // the sub-components: if one of them is open (combo of fields, select2, datepicker), Escape closes only this one.
13579 document.addEventListener("keydown", function(e) {
13580 if (e.key !== "Escape" || !$(".search-component-assistance").is(":visible")) {
13581 return;
13582 }
13583 if ($(".fieldcombo-panel").is(":visible") || $(".select2-container--open").length || $("#ui-datepicker-div").is(":visible")) {
13584 return;
13585 }
13586 $(".search-component-assistance").hide();
13587 $("#search_component_params_input").trigger("focus"); // Keep the focus visible when the editor is closed
13588 }, true);
13589 });
13590 </script>';
13591
13592 $ret .= '<script>
13593 $(document).ready(function() {
13594 // Reset and hide all the value input fields (this does not clear the operator selector)
13595 function resetValueInputs() {
13596 $(".value-input, .dateone, .datemonth, .dateyear").val("").hide();
13597 $("#datemonth, #dateyear").val(null).trigger("change.select2");
13598 $("#dateone").datepicker("setDate", null);
13599 $(".date-one, .date-month, .date-year").hide();
13600 $("#value-selector").val("").hide();
13601 $("#value-selector").next(".select2-container").hide();
13602 $("#value-selector").val(null).trigger("change.select2");
13603 }
13604
13605 // Clear the operator selector and reset and hide all the value input fields
13606 function resetOperatorAndValueInputs() {
13607 $(".operator-selector").empty();
13608 resetValueInputs();
13609 }
13610
13611 // JS code of the 2 levels combo to select first the element (the table) then the field
13612 // Click on the toggle button: show/hide the panel of the combo
13613 $(".fieldcombo-toggle").on("click", function(e) {
13614 e.stopPropagation();
13615 $(this).closest(".fieldcombo").find(".fieldcombo-panel").toggle();
13616 // Reset the search input and the filter, so the panel always opens with the first level open
13617 // (the fields and the sub-tables of the main object are shown, the deeper levels stay closed)
13618 $(this).closest(".fieldcombo").find(".fieldcombo-search").val("").trigger("keyup");
13619 // Put the focus on the search input when the panel is opened
13620 if ($(this).closest(".fieldcombo").find(".fieldcombo-panel").is(":visible")) {
13621 $(this).closest(".fieldcombo").find(".fieldcombo-search").trigger("focus");
13622 }
13623 });
13624
13625 // Press the down or right arrow on the toggle button: open the panel (as a click)
13626 $(".fieldcombo-toggle").on("keydown", function(e) {
13627 if ((e.key === "ArrowDown" || e.key === "ArrowRight") && !$(this).closest(".fieldcombo").find(".fieldcombo-panel").is(":visible")) {
13628 e.preventDefault();
13629 $(this).trigger("click");
13630 }
13631 });
13632
13633 // Arrows into the panel: up moves on the previous visible row, down on the next one.
13634 // From the search input, only the down arrow moves on the first row.
13635 $(".fieldcombo-panel").on("keydown", function(e) {
13636 const isnext = (e.key === "ArrowDown");
13637 const isprev = (e.key === "ArrowUp");
13638 const search = $(this).find(".fieldcombo-search");
13639 if ((!isnext && !isprev) || (e.target === search[0] && e.key !== "ArrowDown")) {
13640 return;
13641 }
13642 e.preventDefault();
13643 const rows = $(this).find(".fieldcombo-elementheader:visible, .fieldcombo-field:visible");
13644 const index = (e.target === search[0] ? -1 : rows.index(e.target)) + (isnext ? 1 : -1);
13645 if (index < 0) {
13646 search.trigger("focus");
13647 } else if (index < rows.length) {
13648 rows.eq(index).trigger("focus");
13649 }
13650 });
13651
13652 // Click on an element (a table): show the list of its sub-elements (indented) and the list of its fields.
13653 // We close all the other elements before, except the parent elements of the clicked element (else it would be hidden)
13654 $(".fieldcombo-elementheader").on("click", function(e) {
13655 e.stopPropagation();
13656 const elementdiv = $(this).closest(".fieldcombo-element");
13657 const wasopen = elementdiv.hasClass("open");
13658 $(".fieldcombo-element").removeClass("open");
13659 $(".fieldcombo-fields, .fieldcombo-children").hide();
13660 $(".fieldcombo-field").show();
13661 elementdiv.parents(".fieldcombo-element").addClass("open").show().children(".fieldcombo-fields, .fieldcombo-children").show();
13662 if (!wasopen) {
13663 elementdiv.addClass("open").show().children(".fieldcombo-fields, .fieldcombo-children").show();
13664 }
13665 });
13666
13667 // Click on a field (second level of the combo): select the field and close the combo
13668 $(".fieldcombo-field").on("click", function(e) {
13669 e.stopPropagation();
13670 const fieldlabel = $(this).text();
13671 const elementlabelhtml = $(this).closest(".fieldcombo-element").find(".fieldcombo-elementlabel").html();
13672 $(".fieldcombo-field").removeClass("selected");
13673 $(this).addClass("selected");
13674 $(".fieldcombo-label").html(elementlabelhtml).removeClass("opacitymedium").append(document.createTextNode(": " + fieldlabel));
13675 $("#search_filter_field").attr("data-type", $(this).attr("data-type")).val($(this).attr("data-field"));
13676 $(".fieldcombo-panel").hide();
13677 $(this).closest(".fieldcombo").find(".fieldcombo-toggle").trigger("focus"); // The selected row is now hidden, keep the focus on the combo
13678 $("#search_filter_field").trigger("change");
13679 });
13680
13681 // Type something into the search input to filter the list of elements and fields
13682 $(".fieldcombo-search").on("keyup change", function() {
13683 const term = $(this).val().toLowerCase();
13684 // Without search term, we show the first level (the main object) open, so its fields and
13685 // its sub-tables are shown, but the deeper levels stay closed
13686 if (term === "") {
13687 $(".fieldcombo-element").removeClass("open").show();
13688 $(".fieldcombo-fields, .fieldcombo-children").hide();
13689 $(".fieldcombo-field").show();
13690 $(".fieldcombo-list > .fieldcombo-element").addClass("open").children(".fieldcombo-fields, .fieldcombo-children").show();
13691 return;
13692 }
13693 // With a search term, we show the elements matching by their label or their fields, and we also
13694 // show the matching sub-elements into their parent element, so we open the parents of the matches
13695 $(".fieldcombo-element").each(function() {
13696 const elementmatch = $(this).children(".fieldcombo-elementheader").find(".fieldcombo-elementlabel").text().toLowerCase().indexOf(term) > -1;
13697 let hasfieldmatch = false;
13698 $(this).children(".fieldcombo-fields").children(".fieldcombo-field").each(function() {
13699 const fieldmatch = elementmatch || $(this).text().toLowerCase().indexOf(term) > -1;
13700 $(this).toggle(fieldmatch);
13701 if (fieldmatch) {
13702 hasfieldmatch = true;
13703 }
13704 });
13705 $(this).toggleClass("open", elementmatch || hasfieldmatch);
13706 $(this).children(".fieldcombo-fields").toggle(elementmatch || hasfieldmatch);
13707 });
13708 $(".fieldcombo-element").each(function() {
13709 if ($(this).hasClass("open")) {
13710 // The element matches, so we show it and we open its parent elements to make it visible into them
13711 $(this).show();
13712 $(this).parents(".fieldcombo-element").addClass("open").show().children(".fieldcombo-children").show();
13713 } else {
13714 $(this).hide();
13715 }
13716 });
13717 });
13718
13719 // Press Escape to close the combo, press Enter on a row to activate it
13720 $(document).on("keydown", function(e) {
13721 if (e.which === 27) {
13722 if ($(".fieldcombo-panel").is(":visible") && $(e.target).closest(".fieldcombo").length) {
13723 $(e.target).closest(".fieldcombo").find(".fieldcombo-toggle").trigger("focus"); // Keep the focus visible on the combo
13724 }
13725 $(".fieldcombo-panel").hide();
13726 }
13727 });
13728 $(".fieldcombo-elementheader, .fieldcombo-field").on("keydown", function(e) {
13729 if (e.which === 13) {
13730 e.preventDefault();
13731 $(this).trigger("click");
13732 }
13733 });
13734
13735 // Close the combo when we click outside of it
13736 $(document).on("click", function(e) {
13737 if (!$(e.target).closest(".fieldcombo").length) {
13738 $(".fieldcombo-panel").hide();
13739 }
13740 });
13741 // Close the combo when the focus leaves it with the keyboard (Tab). A click outside is managed by the click handler.
13742 $(".fieldcombo").on("focusout", function(e) {
13743 if (e.relatedTarget && !$.contains(this, e.relatedTarget)) {
13744 $(this).find(".fieldcombo-panel").hide();
13745 }
13746 });
13747
13748 $("#search_filter_field").on("change", function() {
13749 console.log("We change search_filter_field");
13750
13751 let maybenull = 0;
13752 let fieldType = $(this).attr("data-type");
13753 const selectedFieldValue = $(this).val();
13754
13755 // If the selected option is the placeholder (no field selected), then we reset the operator and value fields
13756 if (arrayoffiltercriterias[selectedFieldValue] === undefined) {
13757 resetOperatorAndValueInputs();
13758 return;
13759 }
13760
13761 // If the selected field has an array of values then ask toshow the value selector instead of the value input
13762 if (arrayoffiltercriterias[selectedFieldValue]["arrayofkeyval"] !== undefined) {
13763 fieldType = "select";
13764 }
13765
13766 // If the selected field may be null then ask to append the "IsDefined" and "IsNotDefined" operators
13767 if (arrayoffiltercriterias[selectedFieldValue]["maybenull"] !== undefined) {
13768 maybenull = 1;
13769 }
13770 const operators = getOperatorsForFieldType(fieldType, maybenull);
13771 const operatorSelector = $(".operator-selector");
13772
13773 // Clear existing options
13774 operatorSelector.empty();
13775
13776 // Populate operators
13777 Object.entries(operators).forEach(function([operator, label]) {
13778 if (operator.indexOf("separator") === 0) {
13779 // A non empty value is required, else select2 hides the option (it is considered as the placeholder)
13780 operatorSelector.append("<option value=\'" + operator + "\' disabled>" + label + "</option>");
13781 } else {
13782 operatorSelector.append("<option value=\'" + operator + "\'>" + label + "</option>");
13783 }
13784 });
13785
13786 operatorSelector.trigger("change.select2");
13787
13788 // Clear and hide all the value input elements initially (the operator selector has just been populated, we do not clear it)
13789 resetValueInputs();
13790
13791 if (fieldType === "date" || fieldType === "datetime" || fieldType === "timestamp") {
13792 $(".date-one").show();
13793 } else if (arrayoffiltercriterias[selectedFieldValue]["arrayofkeyval"] !== undefined) {
13794 var arrayofkeyval = arrayoffiltercriterias[selectedFieldValue]["arrayofkeyval"];
13795 var valueSelector = $("#value-selector");
13796 valueSelector.empty();
13797 Object.entries(arrayofkeyval).forEach(function([key, val]) {
13798 valueSelector.append("<option value=\'" + key + "\'>" + val + "</option>");
13799 });
13800 valueSelector.trigger("change.select2");
13801
13802 $("#value-selector").show();
13803 $("#value-selector").next(".select2-container").show();
13804 } else {
13805 $(".value-input").show();
13806 }
13807 });
13808
13809 $("#operator-selector").on("change", function() {
13810 console.log("We change operator-selector");
13811
13812 const selectedOperator = $(this).find(":selected").val();
13813 if (selectedOperator === "IsDefined" || selectedOperator === "IsNotDefined") {
13814 // Disable all value input elements
13815 $(".value-input, .dateone, .datemonth, .dateyear").val("").prop("disabled", true);
13816 $("#datemonth, #dateyear").val(null).trigger("change.select2");
13817 $("#dateone").datepicker("setDate", null).datepicker("option", "disabled", true);
13818 $(".date-one, .date-month, .date-year").prop("disabled", true);
13819 $("#value-selector").val("").prop("disabled", true);
13820 $("#value-selector").val(null).trigger("change.select2");
13821 } else {
13822 // Enable all value input elements
13823 $(".value-input, .dateone, .datemonth, .dateyear").prop("disabled", false);
13824 $(".date-one, .date-month, .date-year").prop("disabled", false);
13825 $("#dateone").datepicker("option", "disabled", false);
13826 $("#value-selector").prop("disabled", false);
13827 }
13828
13829 // For the "in list" operators on a field with a list of predefined values, values are typed as a list
13830 // into the free text input, so we show it instead of the single value selector
13831 const selectedFieldForOperator = $("#search_filter_field").val();
13832 if (arrayoffiltercriterias[selectedFieldForOperator] !== undefined && arrayoffiltercriterias[selectedFieldForOperator]["arrayofkeyval"] !== undefined) {
13833 if (selectedOperator === "IsInList" || selectedOperator === "IsNotInList") {
13834 $("#value-selector").hide();
13835 $("#value-selector").next(".select2-container").hide();
13836 $(".value-input").val("").show();
13837 } else {
13838 $(".value-input").val("").hide();
13839 $("#value-selector").show();
13840 $("#value-selector").next(".select2-container").show();
13841 }
13842 }
13843 });
13844
13845 $(".add-filter-btn").on("click", function(event) {
13846 console.log("We click on add-filter-btn");
13847
13848 event.preventDefault();
13849
13850 const field = $("#search_filter_field").val();
13851 const operator = $(".operator-selector").val();
13852 let value = $(".value-input").val();
13853 const fieldType = $("#search_filter_field").attr("data-type");
13854
13855 if (["date", "datetime", "timestamp"].includes(fieldType)) {
13856 const year = $("#dateoneyear").val().toString().padStart(4, "0");;
13857 const month = $("#dateonemonth").val().toString().padStart(2, "0");
13858 const day = $("#dateoneday").val().toString().padStart(2, "0");
13859 value = `${year}-${month}-${day}`;
13860 console.log("value="+value);
13861 }
13862
13863 // If the selected field has an array of values then take the selected value,
13864 // except for the "in list" operators for which the values are typed into the free text input
13865 if (operator !== "IsInList" && operator !== "IsNotInList" && arrayoffiltercriterias[field] !== undefined && arrayoffiltercriterias[field]["arrayofkeyval"] !== undefined) {
13866 value = $("#value-selector").val();
13867 }
13868
13869 // If the operator is "IsDefined" or "IsNotDefined" then set the value to 1 (it will not be used)
13870 if (operator === "IsDefined" || operator === "IsNotDefined") {
13871 value = "1";
13872 }
13873
13874 const filterString = generateFilterString(field, operator, value, fieldType);
13875
13876 // Add the criteria to the list of filters without submitting the form (it will be applied on next refresh of page)
13877 if (filterString !== "" && field !== "" && field !== "-1" && field !== null && operator !== "" && operator !== null && value !== "" && value !== null) {
13878 // Convert the filter string into the universal filter syntax: "t.ref like \'%a%\'" -> "(t.ref:like:\'%a%\')"
13879 let ufilter = filterString;
13880 const regufs = filterString.match(/^([a-zA-Z0-9_.]+) (like|notlike|=|!=|<|>|<=|>=) (.*)$/);
13881 if (regufs) {
13882 ufilter = "(" + regufs[1] + ":" + regufs[2] + ":" + regufs[3] + ")";
13883 } else if (!/^\(.*\)$/.test(filterString)) {
13884 ufilter = "(" + filterString + ")";
13885 }
13886 console.log("Add the criteria "+ufilter+" to search_component_params_hidden");
13887
13888 const hiddenfield = $("#search_component_params_hidden");
13889 hiddenfield.val(hiddenfield.val() !== "" ? hiddenfield.val() + " AND " + ufilter : ufilter);
13890
13891 let newufilterid = 1;
13892 $("#divsearch_component_params .tagsearch[data-ufilterid]").each(function() {
13893 newufilterid = Math.max(newufilterid, parseInt($(this).attr("data-ufilterid")) + 1);
13894 });
13895 const newtag = $("<span class=\"marginleftonlyshort valignmiddle tagsearch\"></span>").attr("data-ufilterid", newufilterid).attr("data-ufilter", ufilter);
13896 newtag.append($("<span class=\"tagsearchdelete select2-selection__choice__remove\">x</span>").attr("data-ufilterid", newufilterid), " ", document.createTextNode(ufilter.replace(/^\((.*)\)$/, "$1").replace(/^([a-zA-Z0-9_.]+):([a-zA-Z!<>=]+):/, "$1 $2 ")));
13897 const lasttag = $("#divsearch_component_params .tagsearch").last();
13898 if (lasttag.length) {
13899 newtag.insertAfter(lasttag);
13900 } else {
13901 $("#divsearch_component_params").prepend(newtag);
13902 }
13903
13904 // Reset the value so another criteria can be entered
13905 $(".assistance-errors").hide();
13906 $(".value-input").val("").trigger("focus");
13907 } else {
13908 $(".assistance-errors").show();
13909 }
13910 });
13911
13912 // Press Enter into the filter editor: add the filter (as a click on the button Add) instead of submitting the form
13913 $(".search-component-assistance").on("keydown", function(e) {
13914 if (e.which !== 13) {
13915 return;
13916 }
13917 const target = $(e.target);
13918 // Enter on a row of the combo of fields is managed by the combo, Enter on the button Add already clicks it
13919 if (target.closest(".fieldcombo-elementheader, .fieldcombo-field, .add-filter-btn").length) {
13920 return;
13921 }
13922 e.preventDefault();
13923 // Enter into the search input of the combo of fields must not add the filter
13924 if (target.hasClass("fieldcombo-search")) {
13925 return;
13926 }
13927 // The change event updates the hidden fields of a date (dateoneday, dateonemonth, dateoneyear)
13928 target.filter("input").trigger("change");
13929 $(".add-filter-btn").trigger("click");
13930 });
13931 });
13932 </script>';
13933
13934 return $ret;
13935 }
13936
13948 public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0, $selected = 0, $morecss = '')
13949 {
13950 global $langs, $user;
13951
13952 $retstring = '';
13953
13954 $TModels = array();
13955
13956 include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
13957 $formmail = new FormMail($this->db);
13958 $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
13959
13960 if ($default) {
13961 $TModels[0] = $langs->trans('DefaultMailModel');
13962 }
13963 if ($result > 0) {
13964 foreach ($formmail->lines_model as $model) {
13965 $TModels[(int) $model->id] = $model->label;
13966 }
13967 }
13968
13969 $retstring .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_' . $prefix . 'model_mail" name="' . $prefix . 'model_mail">';
13970
13971 foreach ($TModels as $id_model => $label_model) {
13972 $retstring .= '<option value="' . $id_model . '"';
13973 if (!empty($selected) && ((int) $selected) == $id_model) {
13974 $retstring .= "selected";
13975 }
13976 $retstring .= ">" . $label_model . "</option>";
13977 }
13978
13979 $retstring .= "</select>";
13980
13981 if ($addjscombo) {
13982 $retstring .= ajax_combobox('select_' . $prefix . 'model_mail');
13983 }
13984
13985 return $retstring;
13986 }
13987
13999 public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = false, $morecss = '', $dol_openinpopup = '')
14000 {
14001 global $langs;
14002
14003 $buttons = array();
14004
14005 $save = array(
14006 'name' => 'save',
14007 'label_key' => $save_label,
14008 );
14009
14010 if ($save_label == 'Create' || $save_label == 'Add') {
14011 $save['name'] = 'add';
14012 } elseif ($save_label == 'Modify') {
14013 $save['name'] = 'edit';
14014 }
14015
14016 $cancel = array(
14017 'name' => 'cancel',
14018 'label_key' => 'Cancel',
14019 );
14020
14021 // If MAIN_BUTTON_POSITION_FIRST_OR_LEFT not set, default is to have main action first, then complementary, then cancel at end
14022 if (!getDolGlobalInt('MAIN_BUTTON_POSITION_FIRST_OR_LEFT')) {
14023 !empty($save_label) ? $buttons[] = $save : '';
14024 if (!empty($morebuttons)) {
14025 $buttons[] = $morebuttons;
14026 }
14027 !empty($cancel_label) ? $buttons[] = $cancel : '';
14028 } else {
14029 if (!empty($morebuttons)) {
14030 $buttons[] = $morebuttons;
14031 }
14032 !empty($cancel_label) ? $buttons[] = $cancel : '';
14033 !empty($save_label) ? $buttons[] = $save : '';
14034 }
14035
14036 $retstring = $withoutdiv ? '' : '<div class="center">';
14037
14038 foreach ($buttons as $button) {
14039 $addclass = empty($button['addclass']) ? '' : $button['addclass'];
14040 // Add class to disable submit buttons (except cancel) once form is submitted to prevent duplicate form submissions on slow connections (see lib_foot.js.php)
14041 if ($button['name'] !== 'cancel') {
14042 $addclass .= ($addclass ? ' ' : '').'disableonsubmit';
14043 }
14044 $retstring .= '<input type="submit" class="button marginleftonly marginrightonly button-' . $button['name'] . ($morecss ? ' ' . $morecss : '') . ' ' . $addclass . '" name="' . $button['name'] . '" value="' . dol_escape_htmltag($langs->transnoentities($button['label_key'])) . '">';
14045 }
14046 $retstring .= $withoutdiv ? '' : '</div>';
14047
14048 if ($dol_openinpopup) {
14049 $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . dol_escape_htmltag($dol_openinpopup) . ' context, so we enable the close of dialog on cancel -->' . "\n";
14050 $retstring .= '<script nonce="' . getNonce() . '">';
14051 $retstring .= 'jQuery(".button-cancel").click(function(e) {
14052 e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . dol_escape_js($dol_openinpopup) . '\');
14053 window.parent.jQuery(\'#idfordialog' . dol_escape_js($dol_openinpopup) . '\').dialog(\'close\');
14054 });';
14055 $retstring .= '</script>';
14056 }
14057
14058 return $retstring;
14059 }
14060
14061
14062 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
14063
14070 {
14071 // phpcs:enable
14072 global $langs;
14073
14074 $num = count($this->cache_invoice_subtype);
14075 if ($num > 0) {
14076 return 0; // Cache already loaded
14077 }
14078
14079 dol_syslog(__METHOD__, LOG_DEBUG);
14080
14081 $sql = "SELECT rowid, code, label as label";
14082 $sql .= " FROM " . MAIN_DB_PREFIX . 'c_invoice_subtype';
14083 $sql .= " WHERE active = 1";
14084
14085 $resql = $this->db->query($sql);
14086 if ($resql) {
14087 $num = $this->db->num_rows($resql);
14088 $i = 0;
14089 while ($i < $num) {
14090 $obj = $this->db->fetch_object($resql);
14091
14092 // If translation exists, we use it, otherwise we take the default wording
14093 $label = ($langs->trans("InvoiceSubtype" . $obj->rowid) != "InvoiceSubtype" . $obj->rowid) ? $langs->trans("InvoiceSubtype" . $obj->rowid) : (($obj->label != '-') ? $obj->label : '');
14094 $this->cache_invoice_subtype[(int) $obj->rowid]['rowid'] = (int) $obj->rowid;
14095 $this->cache_invoice_subtype[(int) $obj->rowid]['code'] = (string) $obj->code;
14096 $this->cache_invoice_subtype[(int) $obj->rowid]['label'] = (string) $label;
14097 $i++;
14098 }
14099
14100 $this->cache_invoice_subtype = dol_sort_array($this->cache_invoice_subtype, 'code', 'asc', 0, 0, 1);
14101
14102 return $num;
14103 } else {
14104 dol_print_error($this->db);
14105 return -1;
14106 }
14107 }
14108
14109
14120 public function getSelectInvoiceSubtype($selected = 0, $htmlname = 'subtypeid', $addempty = 0, $noinfoadmin = 0, $morecss = '')
14121 {
14122 global $langs, $user;
14123
14124 $out = '';
14125 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
14126
14127 $this->load_cache_invoice_subtype();
14128
14129 $out .= '<select id="' . $htmlname . '" class="flat selectsubtype' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
14130 if ($addempty) {
14131 $out .= '<option value="0">&nbsp;</option>';
14132 }
14133
14134 foreach ($this->cache_invoice_subtype as $rowid => $subtype) {
14135 $label = $subtype['label'];
14136 $out .= '<option value="' . $subtype['rowid'] . '"';
14137 if ($selected == $subtype['rowid']) {
14138 $out .= ' selected="selected"';
14139 }
14140 $out .= '>';
14141 $out .= $label;
14142 $out .= '</option>';
14143 }
14144
14145 $out .= '</select>';
14146 if ($user->admin && empty($noinfoadmin)) {
14147 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
14148 }
14149 $out .= ajax_combobox($htmlname);
14150
14151 return $out;
14152 }
14153
14163 public function getSearchFilterToolInput($dataTarget, $htmlName = 'search-tools-input', $value = '', $params = [])
14164 {
14165 global $langs;
14166
14167 $attr = array(
14168 'type' => 'search',
14169 'name' => $htmlName,
14170 'value' => $value,
14171 'class' => "search-tool-input",
14172 'placeholder' => $langs->trans('Search'),
14173 'autocomplete' => 'off'
14174 );
14175
14176 // Optional data attr
14177 // 'autofocus' : will set auto focus on field ,
14178 // data-counter-target : will get count results
14179 // data-no-item-target : will be display if count results is 0
14180
14181 if ($dataTarget !== false) {
14182 $attr['data-search-tool-target'] = $dataTarget;
14183 }
14184
14185 // Override attr
14186 if (!empty($params['attr']) && is_array($params['attr'])) {
14187 foreach ($params['attr'] as $key => $value) {
14188 if ($key == 'class') {
14189 $attr['class'] .= ' '.$value;
14190 } elseif ($key == 'classOverride') {
14191 $attr['class'] = $value;
14192 } else {
14193 $attr[$key] = $value;
14194 }
14195 }
14196 }
14197
14198 // automatic add tooltip when title is detected
14199 if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
14200 $attr['class'] .= ' classfortooltip';
14201 }
14202
14203 $TCompiledAttr = [];
14204 foreach ($attr as $key => $value) {
14205 if (in_array($key, ['data-target'])
14206 || (!empty($params['use_unsecured_unescapedattr']) && is_array($params['use_unsecured_unescapedattr']) && in_array($key, $params['use_unsecured_unescapedattr']))) { // Not recommended
14207 $value = dol_htmlentities($value, ENT_QUOTES | ENT_SUBSTITUTE);
14208 } else {
14209 $value = dolPrintHTMLForAttribute($value);
14210 }
14211
14212 $TCompiledAttr[] = $key . '="' . $value . '"'; // $value has been escaped by the dolPrintHTMLForAttribute... just before
14213 }
14214
14215 $compiledAttributes = implode(' ', $TCompiledAttr);
14216
14217
14218 return '<div class="search-tool-container"><input '.$compiledAttributes.'></div>';
14219 }
14220
14234 public function inputType($type, $name, $value = '', $id = '', $morecss = '', $moreparam = '', $label = '', $addInputLabel = '')
14235 {
14236 $out = '';
14237 if ($label != '') {
14238 $out .= '<label for="' . dolPrintHTMLForAttribute($id) . '">';
14239 }
14240 $out .= '<input type="' . dolPrintHTMLForAttribute($type) . '"';
14241 $out .= ' class="flat valignmiddle maxwidthonsmartphone ' . dolPrintHTMLForAttribute($morecss) . '"';
14242 if ($id != '') {
14243 $out .= ' id="' . dolPrintHTMLForAttribute($id) . '"';
14244 }
14245 $out .= ' name="' . dolPrintHTMLForAttribute($name) . '"';
14246 $out .= ' value="' . dolPrintHTMLForAttribute($value) . '" ';
14247 $out .= ($moreparam ? ' ' . $moreparam : '');
14248 $out .= ' />' . $addInputLabel;
14249 if ($label != '') {
14250 $out .= $label . '</label>';
14251 }
14252
14253 return $out;
14254 }
14255
14268 public function inputSelectAjax($htmlName, $array, $id, $ajaxUrl, $ajaxData = [], $morecss = 'minwidth75', $moreparam = '')
14269 {
14270 $out = "
14271 <script>
14272 $(document).ready(function () {
14273 $('#" . $htmlName . "').select2({
14274 ajax: {
14275 url: '" . $ajaxUrl . "',
14276 dataType: 'json',
14277 delay: 250, // wait 250 milliseconds before triggering the request
14278 data: function (params) {
14279 var query = {
14280 search: params.term,
14281 page: params.page || 1";
14282 if (!empty($ajaxData) && is_array($ajaxData)) {
14283 foreach ($ajaxData as $key => $value) {
14284 $out .= ", " . $key . ": '" . $value . "'";
14285 }
14286 }
14287 $out .= "
14288 }
14289 return query;
14290 }
14291 }
14292 })
14293 });
14294 </script>";
14295
14296 $out .= $this->selectarray($htmlName, $array, $id, 0, 0, 0, $moreparam, 0, 0, 0, '', $morecss);
14297
14298 return $out;
14299 }
14300
14310 public function inputHtml($htmlName, $value, $morecss = '', $moreparam = '')
14311 {
14312 require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
14313 $doleditor = new DolEditor($htmlName, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_5, '90%');
14314
14315 return (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
14316 }
14317
14328 public function inputText($htmlName, $value, $morecss = '', $moreparam = '', $options = array())
14329 {
14330 global $langs;
14331
14332 $out = '';
14333 if (!empty($options)) {
14334 // If the textarea field has a list of arrayofkeyval into its definition, we suggest a combo with possible values to fill the textarea.
14335 $out .= $this->selectarray($htmlName . "_multiinput", $options, '', 1, 0, 0, $moreparam, 0, 0, 0, '', "flat maxwidthonphone" . $morecss);
14336 $out .= '<input id="' . $htmlName . '_multiinputadd" type="button" class="button" value="' . $langs->trans("Add") . '">';
14337 $out .= "<script>";
14338 $out .= '
14339 function handlemultiinputdisabling(htmlname){
14340 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
14341 multiinput = $("#"+htmlname+"_multiinput");
14342 multiinput.find("option").each(function(){
14343 tmpval = $("#"+htmlname).val();
14344 tmpvalarray = tmpval.split("\n");
14345 valtotest = $(this).val();
14346 if(tmpvalarray.includes(valtotest)){
14347 $(this).prop("disabled",true);
14348 } else {
14349 if($(this).prop("disabled") == true){
14350 console.log(valtotest)
14351 $(this).prop("disabled", false);
14352 }
14353 }
14354 });
14355 }
14356
14357 $(document).ready(function () {
14358 $("#' . $htmlName . '_multiinputadd").on("click",function() {
14359 tmpval = $("#' . $htmlName . '").val();
14360 tmpvalarray = tmpval.split(",");
14361 valtotest = $("#' . $htmlName . '_multiinput").val();
14362 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
14363 console.log("We add the selected value to the text area ' . $htmlName . '");
14364 if(tmpval == ""){
14365 tmpval = valtotest;
14366 } else {
14367 tmpval = tmpval + "\n" + valtotest;
14368 }
14369 $("#' . $htmlName . '").val(tmpval);
14370 handlemultiinputdisabling("' . $htmlName . '");
14371 $("#' . $htmlName . '_multiinput").val(-1);
14372 } else {
14373 console.log("We add nothing the text area ' . $htmlName . '");
14374 }
14375 });
14376 $("#' . $htmlName . '").on("change",function(){
14377 handlemultiinputdisabling("' . $htmlName . '");
14378 });
14379 handlemultiinputdisabling("' . $htmlName . '");
14380 })';
14381 $out .= "</script>";
14382 $value = str_replace(',', "\n", $value);
14383 }
14384
14385 require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
14386 $doleditor = new DolEditor($htmlName, (string) $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
14387 $out .= (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
14388
14389 return $out;
14390 }
14391
14402 public function inputRadio($htmlName, $options, $selectedValue, $morecss = '', $moreparam = '')
14403 {
14404 $out = '';
14405 foreach ($options as $optionKey => $optionLabel) {
14406 $selected = ((string) $selectedValue) === ((string) $optionKey) ? ' checked="checked"' : '';
14407 $optionId = $htmlName . '_' . $optionKey;
14408 $out .= '<input class="flat' . $morecss . '" type="radio" name="' . $htmlName . '" id="' . $optionId . '" value="' . dolPrintHTMLForAttribute((string) $optionKey) . '"' . $selected . $moreparam . '/><label for="' . $optionId . '">' . $optionLabel . '</label><br>';
14409 }
14410
14411 return $out;
14412 }
14413
14424 public function inputStars($htmlName, $size, $value, $morecss = '', $moreparam = '')
14425 {
14426 $out = '<input type="hidden" class="flat ' . $morecss . '" name="' . $htmlName . '" id="' . $htmlName . '" value="' . dolPrintHTMLForAttribute((string) $value) . '"' . $moreparam . '>';
14427 $out .= '<div class="star-selection" id="' . $htmlName . '_selection">';
14428 for ($i = 1; $i <= $size; $i++) {
14429 $out .= '<span class="star" data-value="' . $i . '">' . img_picto('', 'fontawesome_star_fas') . '</span>';
14430 }
14431 $out .= '</div>';
14432 $out .= '<script>
14433 jQuery(function($) { /* commonobject.class.php 1 */
14434 let container = $("#' . $htmlName . '_selection");
14435 let selectedStars = parseInt($("#' . $htmlName . '").val()) || 0;
14436 container.find(".star").each(function() {
14437 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
14438 });
14439 container.find(".star").on("mouseover", function() {
14440 let selectedStar = $(this).data("value");
14441 container.find(".star").each(function() {
14442 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
14443 });
14444 });
14445 container.on("mouseout", function() {
14446 container.find(".star").each(function() {
14447 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
14448 });
14449 });
14450 container.find(".star").off("click").on("click", function() {
14451 selectedStars = $(this).data("value");
14452 if (selectedStars === 1 && $("#' . $htmlName . '").val() == 1) {
14453 selectedStars = 0;
14454 }
14455 $("#' . $htmlName . '").val(selectedStars);
14456 container.find(".star").each(function() {
14457 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
14458 });
14459 });
14460 });
14461 </script>';
14462
14463 return $out;
14464 }
14465
14475 public function inputIcon($htmlName, $value, $morecss = '', $moreparam = '')
14476 {
14477 global $langs;
14478
14479 /* External lib inclusion are not allowed in backoffice. Also lib is included several time if there is several icon file.
14480 Some code must be added into main when MAIN_ADD_ICONPICKER_JS is set to add of lib in html header
14481 $out ='<link rel="stylesheet" href="'.dol_buildpath('/myfield/css/fontawesome-iconpicker.min.css', 1).'">';
14482 $out.='<script src="'.dol_buildpath('/myfield/js/fontawesome-iconpicker.min.js', 1).'"></script>';
14483 */
14484 $out = '<input type="text" class="form-control icp icp-auto iconpicker-element iconpicker-input flat ' . $morecss . ' maxwidthonsmartphone"';
14485 $out .= ' name="' . $htmlName . '" id="' . $htmlName . '" value="' . dolPrintHTMLForAttribute((string) $value) . '" ' . ((string) $moreparam) . '>';
14486 if (getDolGlobalInt('MAIN_ADD_ICONPICKER_JS')) {
14487 $out .= '<script>';
14488 $options = "{ title: '<b>" . $langs->trans("IconFieldSelector") . "</b>', placement: 'right', showFooter: false, templates: {";
14489 $options .= "iconpicker: '<div class=\"iconpicker\"><div style=\"background-color:#EFEFEF;\" class=\"iconpicker-items\"></div></div>',";
14490 $options .= "iconpickerItem: '<a role=\"button\" href=\"#\" class=\"iconpicker-item\" style=\"background-color:#DDDDDD;\"><i></i></a>',";
14491 // $options.="buttons: '<button style=\"background-color:#FFFFFF;\" class=\"iconpicker-btn iconpicker-btn-cancel btn btn-default btn-sm\">".$langs->trans("Cancel")."</button>";
14492 // $options.="<button style=\"background-color:#FFFFFF;\" class=\"iconpicker-btn iconpicker-btn-accept btn btn-primary btn-sm\">".$langs->trans("Save")."</button>',";
14493 $options .= "footer: '<div class=\"popover-footer\" style=\"background-color:#EFEFEF;\"></div>',";
14494 $options .= "search: '<input type=\"search\" class\"form-control iconpicker-search\" placeholder=\"" . $langs->trans("TypeToFilter") . "\" />',";
14495 $options .= "popover: '<div class=\"iconpicker-popover popover\">";
14496 $options .= " <div class=\"arrow\" ></div>";
14497 $options .= " <div class=\"popover-title\" style=\"text-align:center;background-color:#EFEFEF;\"></div>";
14498 $options .= " <div class=\"popover-content \" ></div>";
14499 $options .= "</div>'}}";
14500 $out .= "$('#" . $htmlName . "').iconpicker(" . $options . ");";
14501 $out .= '</script>';
14502 }
14503
14504 return $out;
14505 }
14506
14515 public function inputGeoPoint($htmlName, $value, $type = '')
14516 {
14517 require_once DOL_DOCUMENT_ROOT . '/core/class/dolgeophp.class.php';
14518 require_once DOL_DOCUMENT_ROOT . '/core/class/geomapeditor.class.php';
14519 $dolgeophp = new DolGeoPHP($this->db);
14520 $geomapeditor = new GeoMapEditor();
14521
14522 $geojson = '{}';
14523 $centroidjson = getDolGlobalString('MAIN_INFO_SOCIETE_GEO_COORDINATES', '{}');
14524 if (!empty($value)) {
14525 $tmparray = $dolgeophp->parseGeoString($value);
14526 $geojson = $tmparray['geojson'];
14527 $centroidjson = $tmparray['centroidjson'];
14528 }
14529
14530 return $geomapeditor->getHtml($htmlName, $geojson, $centroidjson, $type);
14531 }
14532
14539 public function outputMultiValues($values)
14540 {
14541 $out = '';
14542 $toPrint = array();
14543 $values = is_array($values) ? $values : array();
14544
14545 foreach ($values as $value) {
14546 $toPrint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $value . '</li>';
14547 }
14548 if (!empty($toPrint)) {
14549 $out = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toPrint) . '</ul></div>';
14550 }
14551
14552 return $out;
14553 }
14554
14562 public function outputStars($size, $value)
14563 {
14564 $out = '<div class="star-selection" data-value="' . dolPrintHTMLForAttribute((string) $value) . '">';
14565 for ($i = 1; $i <= $size; $i++) {
14566 $out .= '<span class="star' . ($i <= $value ? ' active' : '') . '" data-value="' . $i . '">' . img_picto('', 'fontawesome_star_fas') . '</span>';
14567 }
14568 $out .= '</div>';
14569
14570 return $out;
14571 }
14572
14579 public function outputIcon($value)
14580 {
14581 $out = '<span class="' . dolPrintHTMLForAttribute((string) $value) . '"></span>';
14582
14583 return $out;
14584 }
14585
14593 public function outputGeoPoint($value, $type)
14594 {
14595 $out = '';
14596
14597 if (!empty($value)) {
14598 require_once DOL_DOCUMENT_ROOT . '/core/class/dolgeophp.class.php';
14599 $dolgeophp = new DolGeoPHP($this->db);
14600 if ($type == 'point') {
14601 $out = $dolgeophp->getXYString($value);
14602 } else { // multipts, linestrg, polygon
14603 $out = $dolgeophp->getPointString($value);
14604 }
14605 }
14606
14607 return $out;
14608 }
14609
14624 public function getNomUrl(&$object, $withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '', $add_label = 0, $sep = ' - ')
14625 {
14626 if (is_object($object) && method_exists($object, 'getNomUrl')) {
14627 $out = $object->getNomUrl($withpicto, $option, $maxlength, $save_lastsearch_value, $notooltip, $morecss, $add_label, $sep);
14628 return $out;
14629 } else {
14630 return '';
14631 }
14632 }
14633}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
ajax_autocompleter($selected, $htmlname, $url, $urloption='', $minLength=2, $autoselect=0, $ajaxoptions=array(), $moreparams='')
Generic function that return javascript to add to transform a common input text or select field into ...
Definition ajax.lib.php:51
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:488
$c
Definition line.php:353
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage bank accounts.
Class to manage members of a foundation.
Class to manage categories.
Class to manage bank accounts description of third parties.
Class to manage contact/addresses.
Class to manage a WYSIWYG editor.
Class to manage Geo processing Usage: $dolgeophp=new DolGeoPHP($db);.
DAO Resource object.
Class to manage ECM files.
const STATUS_OPEN_INTERNAL
Warehouse open and only operations for stock transfers/corrections allowed (not for customer shipping...
const STATUS_OPEN_ALL
Warehouse open and any operations are allowed (customer shipping, supplier dispatch,...
const STATUS_CLOSED
Warehouse closed, inactive.
Class to manage standard extra languages.
Class to manage invoice templates.
Class to manage generation of HTML components Only common components must be here.
showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array(), $nooutput=0)
Show block with links "to link to" other objects.
inputSelectAjax($htmlName, $array, $id, $ajaxUrl, $ajaxData=[], $morecss='minwidth75', $moreparam='')
Html for select with get options by AJAX.
selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0, $filter='', $excludeConfCurrency=false, $morecss='maxwidth200 widthcentpercentminusx')
Return array of currencies in user language.
showFilterButtons($pos='')
Return HTML to show the search and clear search button.
load_cache_vatrates($country_code)
Load into the cache ->cache_vatrates, all the vat rates of a country.
inputRadio($htmlName, $options, $selectedValue, $morecss='', $moreparam='')
Html for input radio.
select_comptes($selected='', $htmlname='accountid', $status=0, $filtre='', $useempty=0, $moreattrib='', $showcurrency=0, $morecss='', $nooutput=0, $addentrynone=0)
Return a HTML select list of bank accounts.
static selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
Return a HTML select string, built from an array of key+value, but content returned into select come ...
inputGeoPoint($htmlName, $value, $type='')
Html for input geo point.
editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=1, $formatfunc='', $paramid='id', $gm='auto', $moreoptions=array(), $editaction='')
Output value of a field for an editable field.
form_availability($page, $selected='', $htmlname='availability', $addempty=0)
Show a form to select a delivery delay.
showLinkedObjectBlock($object, $morehtmlright='', $compatibleImportElementsList=array(), $title='RelatedObjects')
Show linked object block.
selectMassAction($selected, $arrayofaction, $alwaysvisible=0, $name='massaction', $cssclass='checkforselect')
Generate select HTML to choose massaction.
getSelectRuleForLinesDates($selected='', $htmlname='rule_for_lines_dates', $addempty=0)
Returns select with rule for lines dates.
select_dolresources_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include=array(), $enableonly=array(), $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $showproperties=0, $listofresourceid=array())
Return select list of resources.
form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
Show form with multicurrency code.
static radio($htmlName, $radioItems, $selected='', $moreGlobalParams=[])
Generates a set of HTML radio inputs from an array of key-value items.
formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=0, $width=600, $disableformtag=0, $labelbuttonyes='Yes', $labelbuttonno='No', $helpContent='', $labelbuttonother='', $valuebuttonother='other')
Show a confirmation HTML form or AJAX popup.
formRib($page, $selected='', $htmlname='ribcompanyid', $filtre='', $addempty=0, $showibanbic=0)
Display form to select bank customer account.
showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0, $massactionname="massaction")
Return HTML to show the search and clear search button.
select_produits($selected=0, $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, $warehouseId=0)
Return list of products.
inputType($type, $name, $value='', $id='', $morecss='', $moreparam='', $label='', $addInputLabel='')
Html for input with label.
select_dolgroups($selected=0, $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly=array(), $force_entity='0', $multiple=false, $morecss='minwidth200')
Return select list of user groups.
selectInputReason($selected='', $htmlname='demandreasonid', $exclude='', $addempty=0, $morecss='', $notooltip=0)
Return list of input reason (events that triggered an object creation, like after sending an emailing...
select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=1, $noadmininfo=0, $maxlength=0, $active=1, $morecss='', $nooutput=0)
Return list of payment methods Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value bu...
select_currency($selected='', $htmlname='currency_id')
Returns the list of currencies in the user's language.
inputStars($htmlName, $size, $value, $morecss='', $moreparam='')
Html for input stars.
formSelectTransportMode($page, $selected='', $htmlname='transport_mode_id', $active=1, $addempty=0)
Show form with transport mode.
selectShippingMethod($selected='', $htmlname='shipping_method_id', $filtre='', $useempty=0, $moreattrib='', $noinfoadmin=0, $morecss='')
Return a HTML select list of shipping mode.
select_produits_list($selected=0, $htmlname='productid', $filtertype='', $limit=1000, $price_level=0, $filterkey='', $status=1, $finished=2, $outputmode=0, $socid=0, $showempty='1', $forcecombo=0, $morecss='maxwidth500', $hidepriceinlabel=0, $warehouseStatus='', $status_purchase=-1, $warehouseId=0)
Return list of products for a customer.
selectRib($selected='', $htmlname='ribcompanyid', $filtre='', $useempty=0, $moreattrib='', $showibanbic=0, $morecss='', $nooutput=0)
Return a HTML select list of bank accounts customer.
formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
Display form to select shipping mode.
getSelectInvoiceSubtype($selected=0, $htmlname='subtypeid', $addempty=0, $noinfoadmin=0, $morecss='')
Return list of invoice subtypes.
form_contacts($page, $societe, $selected='', $htmlname='contactid')
Show forms to select a contact.
load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse=null, $societe_acheteuse=null, $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0, $type_vat=0)
Output an HTML select vat rate.
load_cache_availability()
Load int a cache property the list of possible delivery delays.
select_bom($selected='', $htmlname='bom_id', $limit=0, $status=1, $type=0, $showempty='1', $morecss='', $nooutput='', $forcecombo=0, $TProducts=[])
Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list.
form_rule_for_lines_dates($page, $selected='', $htmlname='rule_for_lines_dates', $addempty=0, $nooutput=0)
Form select for rule for lines dates.
static selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='minwidth75', $addjscombo=1, $moreparamonempty='', $disablebademail=0, $nohtmlescape=0)
Return a HTML select string, built from an array of key+value.
selectInvoiceRec($selected='', $htmlname='facrecid', $maxlength=24, $option_only=0, $show_empty='1', $forcefocus=0, $disabled=0, $morecss='maxwidth500')
Output a combo list with invoices qualified for a third party TODO Bad method.
inputIcon($htmlName, $value, $morecss='', $moreparam='')
Html for input icon.
form_multicurrency_rate($page, $rate=0.0, $htmlname='multicurrency_tx', $currency='', $rate_direct=0.0)
Show form with multicurrency rate.
editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
Output edit in place form.
form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1, $addempty=0, $type='', $nooutput=0, $short=0)
Show form with payment mode.
getPhoneInputSharedJs($countrySelectorId)
Return inline JS for country-selector → phone code sync (output once per page).
showPhoneInput($phoneValue, $htmlname, $country_id_hint=0, $picto='object_phoning', $morecss='maxwidth150', $maxlength=0, $countrySelectorId='selectcountry_id')
Show a self-contained phone input: hidden field + country code dropdown + number text field + JS.
selectUnits($selected='', $htmlname='units', $showempty=0, $unit_type='')
Creates HTML units selector (code => label)
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0, $usesharelinkifavailable=0)
Return HTML code to output a photo.
constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0, $filterkey='', $novirtualstock=0)
Function to forge the string with OPTIONs of SELECT.
selectTransportMode($selected='', $htmlname='transportmode', $format=0, $empty=1, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')
Return list of transport mode for intracomm report.
form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0, $type='', $filtertype=-1, $deposit_percent=-1, $nooutput=0)
Show a form to select payment conditions.
selectSituationInvoices($selected='', $socid=0)
Creates HTML last in cycle situation invoices selector.
selectPriceBaseType($selected='', $htmlname='price_base_type', $addjscombo=0)
Selection HT or TTC.
load_cache_transport_mode()
getSearchFilterToolInput($dataTarget, $htmlName='search-tools-input', $value='', $params=[])
select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='', $deposit_percent=-1, $noprint=0)
print list of payment modes.
showbarcode(&$object, $width=100, $morecss='')
Return HTML code to output a barcode.
load_cache_rule_for_lines_dates()
Loads into a cache property the list of possible rules for line dates.
form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0, $filterabsolutediscount=0, $filtercreditnote=0)
Show a select box with available absolute discounts.
getPhoneInputFieldJs($htmlname, $codename)
Return inline JS that syncs the hidden phone field from select + text input.
form_confirm($page, $title, $question, $action, $formquestion=array(), $selectedchoice="", $useajax=0, $height=170, $width=500)
Show a confirmation HTML form or AJAX popup.
load_cache_conditions_paiements()
Load into cache list of payment terms.
selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array(), $info_admin=1)
Return HTML to show the select of expense categories.
selectPhoneCode($selected='', $htmlname='phone_code', $morecss='maxwidth150', $showempty=0, $country_id_hint=0)
Return a select list of country phone calling codes.
select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier=0)
Return list of suppliers prices for a product.
getNomUrl(&$object, $withpicto=0, $option='', $maxlength=0, $save_lastsearch_value=-1, $notooltip=0, $morecss='', $add_label=0, $sep=' - ')
Return link of object.
form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0, $textifnoproject='', $morecss='', $option='')
Show a form to select a project.
selectAvailabilityDelay($selected='', $htmlname='availid', $filtertype='', $addempty=0, $morecss='', $noouput=0)
Return the list of type of delay available.
outputGeoPoint($value, $type)
Html for show geo point.
form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0, $type='')
Show a form + html select a date.
showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0, $massactionname="massaction")
Return HTML to show the search and clear search button.
__construct($db)
Constructor.
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', $calendarpicto='')
Show a HTML widget to input a date or combo list for day, month, years and optionally hours and minut...
inputText($htmlName, $value, $morecss='', $moreparam='', $options=array())
Html for HTML area.
select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $fromid=0, $outputmode=0, $include=0, $morecss='', $useempty=1)
Return list of categories having chosen type.
textwithpicto($text, $htmltooltip, $direction=1, $type='help', $extracss='valignmiddle', $noencodehtmltext=0, $notabs=3, $tooltiptrigger='', $forcenowrap=0)
Show a text with a picto and a tooltip on picto.
select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday=0, $addplusone='', $adddateof='')
Show a HTML widget to input a date or combo list for day, month, years and optionally hours and minut...
load_cache_invoice_subtype()
Load into cache list of invoice subtypes.
select_export_model($selected='', $htmlname='exportmodelid', $type='', $useempty=0)
Return list of export templates.
selectDateToDate($set_time='', $set_time_end='', $prefix='re', $empty=0, $forcenewline=0)
Show 2 HTML widget to input a date or combo list for day, month, years and optionally hours and minut...
outputMultiValues($values)
Html for show selected multiple values.
textwithtooltip($text, $htmltext, $tooltipon=1, $direction=0, $img='', $extracss='', $notabs=3, $incbefore='', $noencodehtmltext=0, $tooltiptrigger='', $forcenowrap=0)
Show a text and picto with tooltip on text or picto.
selectCategories($categtype, $htmlname, $object=null)
Return HTML component to select a category.
outputIcon($value)
Html for show icon.
getHelpBlock($content, $icon='fa-question-circle')
Generate a collapsible help block with a standard '?' icon.
getSelectConditionsPaiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='', $deposit_percent=-1)
Return list of payment modes.
widgetForTranslation($fieldname, $object, $perm, $typeofdata='string', $check='', $morecss='')
Output edit in place form.
outputStars($size, $value)
Html for show stars.
getDurationTypes(Translate $langs, $plurial=true, $reverse=false)
Return an array of Duration Types.
form_thirdparty($page, $selected='', $htmlname='socid', $filter='', $showempty=0, $showtype=0, $forcecombo=0, $events=array(), $nooutput=0, $excludeids=array(), $textifnothirdparty='')
Output html select to select thirdparty.
selectEstablishments($selected='', $htmlname='entity', $status=0, $filtre='', $useempty=0, $moreattrib='')
Return a HTML select list of establishment.
formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0, $morecss='')
Output HTML form to select list of input reason (events that triggered an object creation,...
formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
Display form to select bank account.
form_users($page, $selected='', $htmlname='userid', $exclude=array(), $include=array())
Show a select form to choose a user.
editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0, $paramid='id', $help='')
Output key field for an editable field.
showCategories($id, $type, $rendermode=0, $nolink=0)
Render list of categories linked to object with id $id and type $type.
load_cache_types_paiements()
Load into the cacha array all possible payment modes.
select_produits_fournisseurs_list($socid, $selected='', $htmlname='productid', $filtertype='', $notused='', $filterkey='', $statut=-1, $outputmode=0, $limit=100, $alsoproductwithnosupplierprice=0, $morecss='', $showstockinlist=0, $placeholder='')
Return list of suppliers products.
selectCurrency($selected='', $htmlname='currency_id', $mode=0, $useempty='')
Returns the list of currencies in the user's language.
selectyesno($htmlname, $value='', $option=0, $disabled=false, $useempty=0, $addjscombo=0, $morecss='yesno width75', $labelyes='Yes', $labelno='No')
Return an html string with a select combo box to choose yes or no.
inputHtml($htmlName, $value, $morecss='', $moreparam='')
Html for HTML area.
select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $notused='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0, $morecss='', $placeholder='', $nooutput=0)
Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs...
showrefnav($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $morehtmlright='')
Return a HTML area with the reference of object and a navigation bar for a business object Note: To c...
searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput=array(), $search_component_params_hidden='', $arrayoffiltercriterias=array())
Output the component to make advanced search criteria.
selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0, $disabled=0, $sortfield='', $filter='', $sortorder='ASC')
Output html form to select an object.
Class to manage building of HTML components.
Class to manage forms for the module resource.
Class to manage a Leaflet map width geometrics objects.
Class for MyObject.
Class to parse product price expressions.
Class to manage predefined suppliers products.
Class to manage products or services.
const TYPE_PRODUCT
Regular product.
const TYPE_SERVICE
Service.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage subscriptions of foundation members.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
currency_name($code_iso, $withcode=0, $outputlangs=null)
Return label of currency or code+label.
isInEEC($object)
Return if a country of an object is inside the EEC (European Economic Community)
global $mysoc
getServerTimeZoneInt($refgmtdate='now')
Return server timezone int.
Definition date.lib.php:87
removeGlobalParenthesis($string)
Remove first and last parenthesis but only if first is the opening and last the closing of the same g...
dol_now($mode='gmt')
Return date for now.
dol_print_email($email, $contactid=0, $socid=0, $addlink=0, $max=0, $showinvalid=2, $withpicto=0, $morecss='paddingrightonly')
Show EMail link formatted for HTML output.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
dolForgeExplodeAnd($sqlfilters)
Explode an universal search string with AND parts.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
currentToken()
Return the value of token currently saved into session with name 'token'.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
dol_print_url($url, $target='_blank', $max=32, $withpicto=0, $morecss='')
Show Url link.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolUserString($key, $default='', $tmpuser=null)
Return Dolibarr user constant string value.
GETPOSTISARRAY($paramname, $method=0)
Return true if the parameter $paramname is submit from a POST OR GET as an array.
natural_search($fields, $value, $mode=0, $nofirstand=0, $sqltoadd='')
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getElementProperties($elementType)
Get an array with properties of an element.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags=array('textarea'), $cleanalsosomestyles=0)
Clean a string from some undesirable HTML tags.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
getImageFileNameForSize($file, $extName, $extImgTarget='')
Return the filename of file to get the thumbs.
colorIsLight($stringcolor)
Return true if the color is light.
dolIsAllowedForPreview($file)
Return if a file is qualified for preview.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getNonce()
Return a random string to be used as a nonce value for js.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox=0, $check='restricthtml')
Sanitize a HTML to remove js, dangerous content and external links.
dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles=1, $removeclassattribute=1, $cleanalsojavascript=0, $allowiframe=0, $allowed_tags=array(), $allowlink=0, $allowscript=0, $allowstyle=0, $allowphp=0)
Clean a string to keep only desirable HTML tags.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_sanitizeKeyCode($str)
Clean a string to use it as a key or code.
isModEnabled($module)
Is Dolibarr module enabled.
array_merge_recursive_distinct(array $array1, array $array2)
Recursively merges two arrays while preserving keys and replacing existing values.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_nboflines_bis($text, $maxlinesize=0, $charset='UTF-8')
Return nb of lines of a formatted text with and (WARNING: string must not have mixed and br sep...
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
commonHtmlAttributeBuilder($attr, array $unescapedAttr=[])
Builds an array of safe and properly escaped HTML attributes from a key-value pair list.
dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled='', $morecss='classlink button bordertransp', $jsonopen='', $jsonclose='', $accesskey='')
Return HTML code to output a button to open a dialog popup box.
Definition html.lib.php:437
showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no', $use_short_label=0)
Output a dimension with best unit.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
Build the customer statement lines (invoices and payments) with running balance.
Class to generate the form for creating a new ticket.
dol_get_trunk_prefix($db, $phone_code)
Get the national trunk prefix for a phone code.
dol_parse_phone($phone)
Parse a stored phone number into country code and number parts.
Definition phone.lib.php:34
dol_get_phone_code_from_country($db, $country_id)
Get the phone calling code for a country.
measuringUnitString($unitid, $measuring_style='', $unitscale=null, $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:166
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:165
getMaxFileSizeArray()
Return the max allowed for file upload.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
treeview li table
No Email.
a disabled
testSqlAndScriptInject($val, $type)
Security: WAF layer for SQL Injection and XSS Injection (scripts) protection (Filters on GET,...
Definition waf.inc.php:103