dolibarr 24.0.3
html.form.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
5 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6 * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
7 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
9 * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>
10 * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
11 * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
12 * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
13 * Copyright (C) 2010-2021 Philippe Grand <philippe.grand@atoo-net.com>
14 * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
15 * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
16 * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
17 * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
18 * Copyright (C) 2014-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, $this->db);
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 // Add back trunk prefix for display (e.g. "644986885" → "0644986885" for France)
1299 // A number still starting with "+" has an unknown country code: never prefix it
1300 if ($numberValue !== '' && $selectedCode !== '' && strpos($numberValue, '+') !== 0) {
1301 $trunkPrefix = dol_get_trunk_prefix($this->db, $selectedCode);
1302 if ($trunkPrefix !== '' && strpos($numberValue, $trunkPrefix) !== 0) {
1303 $numberValue = $trunkPrefix.$numberValue;
1304 }
1305 }
1306
1307 // Keep digits only, as the visible field only accepts digits (pattern) and the JS keeps only digits on save
1308 $numberValue = preg_replace('/[^0-9]/', '', $numberValue);
1309
1310 // Build output: hidden field (POSTed value)
1311 $out = '<input type="hidden" name="'.dol_escape_htmltag($htmlname).'" id="'.dol_escape_htmltag($htmlname).'" value="'.dol_escape_htmltag($fullPhone).'">';
1312
1313 // Picto
1314 $out .= img_picto('', $picto, 'class="pictofixedwidth"');
1315
1316 // Phone code select (display-only name, not submitted as separate POST param)
1317 $out .= $this->selectPhoneCode($selectedCode, $codename, 'maxwidth75 phone_code_select', 0, $country_id_hint);
1318
1319 // Visible number input (no name — not POSTed)
1320 $out .= '<input type="tel" inputmode="numeric" pattern="[0-9]*" id="'.dol_escape_htmltag($htmlname).'_input" class="'.dol_escape_htmltag($morecss).'"';
1321 if ($maxlength > 0) {
1322 $out .= ' maxlength="'.$maxlength.'"';
1323 }
1324 $out .= ' value="'.dol_escape_htmltag($numberValue).'">';
1325
1326 // Per-field JS to sync hidden field
1327 $out .= $this->getPhoneInputFieldJs($htmlname, $codename);
1328
1329 // Shared JS for country-sync (output once per page)
1330 $out .= $this->getPhoneInputSharedJs($countrySelectorId);
1331
1332 return $out;
1333 }
1334
1345 private function getPhoneInputFieldJs($htmlname, $codename)
1346 {
1347 $hiddenId = dol_escape_js($htmlname);
1348 $inputId = dol_escape_js($htmlname).'_input';
1349 $selectId = 'select'.dol_escape_js($codename);
1350
1351 $out = "\n".'<script type="text/javascript">'."\n";
1352 $out .= 'jQuery(document).ready(function() {'."\n";
1353 $out .= ' function syncPhoneField_'.$hiddenId.'() {'."\n";
1354 $out .= ' var selectEl = jQuery("#'.$selectId.'");'."\n";
1355 $out .= ' var code = selectEl.val() || "";'."\n";
1356 $out .= ' var number = (jQuery("#'.$inputId.'").val() || "").replace(/[^0-9]/g, "");'."\n";
1357 $out .= ' if (code && number) {'."\n";
1358 $out .= ' var selOpt = selectEl[0] && selectEl[0].selectedOptions && selectEl[0].selectedOptions[0];'."\n";
1359 $out .= ' var trunkPrefix = selOpt ? (selOpt.getAttribute("data-trunk-prefix") || "") : "";'."\n";
1360 $out .= ' if (trunkPrefix !== "" && number.indexOf(trunkPrefix) === 0) {'."\n";
1361 $out .= ' number = number.substring(trunkPrefix.length);'."\n";
1362 $out .= ' }'."\n";
1363 $out .= ' jQuery("#'.$hiddenId.'").val(code + " " + number);'."\n";
1364 $out .= ' } else if (number) {'."\n";
1365 $out .= ' jQuery("#'.$hiddenId.'").val(number);'."\n";
1366 $out .= ' } else {'."\n";
1367 $out .= ' jQuery("#'.$hiddenId.'").val("");'."\n";
1368 $out .= ' }'."\n";
1369 $out .= ' }'."\n";
1370 $out .= ' jQuery("#'.$selectId.'").on("change", function() { syncPhoneField_'.$hiddenId.'(); });'."\n";
1371 $out .= ' jQuery("#'.$inputId.'").on("input change", function() { syncPhoneField_'.$hiddenId.'(); });'."\n";
1372 $out .= '});'."\n";
1373 $out .= '</script>'."\n";
1374
1375 return $out;
1376 }
1377
1387 private function getPhoneInputSharedJs($countrySelectorId)
1388 {
1389 if ($this->phoneInputSharedJsLoaded) {
1390 return '';
1391 }
1392 $this->phoneInputSharedJsLoaded = true;
1393
1394 $out = "\n".'<script type="text/javascript">'."\n";
1395 $out .= 'jQuery(document).ready(function() {'."\n";
1396 $out .= ' jQuery("#'.dol_escape_js($countrySelectorId).'").on("change", function() {'."\n";
1397 $out .= ' var country_id = jQuery(this).val();'."\n";
1398 $out .= ' if (country_id) {'."\n";
1399 $out .= ' jQuery.getJSON("'.DOL_URL_ROOT.'/core/ajax/getphonecode.php", {country_id: country_id, token: "'.currentToken().'"}, function(data) {'."\n";
1400 $out .= ' if (data.phone_code) {'."\n";
1401 $out .= ' jQuery(".phone_code_select").each(function() {'."\n";
1402 $out .= ' jQuery(this).val(data.phone_code).trigger("change");'."\n";
1403 $out .= ' });'."\n";
1404 $out .= ' }'."\n";
1405 $out .= ' });'."\n";
1406 $out .= ' }'."\n";
1407 $out .= ' });'."\n";
1408 $out .= '});'."\n";
1409 $out .= '</script>'."\n";
1410
1411 return $out;
1412 }
1413
1427 private function makeAddLinkToObject($object, $key, $possiblelink, $num, $resqllist)
1428 {
1429 dol_syslog(__METHOD__, LOG_DEBUG);
1430 global $langs, $form;
1431 if (empty($form)) {
1432 $form = new Form($this->db);
1433 }
1434 $htmltoenteralink = '';
1435 $i = 0;
1436
1437 // headers
1438 $htmltoenteralink .= '<tr class="liste_titre">';
1439 $htmltoenteralink .= '<td class="nowrap"></td>';
1440 $htmltoenteralink .= '<td>' . $langs->trans("Ref") . '</td>';
1441 $htmltoenteralink .= '<td>' . $langs->trans("RefCustomer") . '</td>';
1442 $htmltoenteralink .= '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
1443 $htmltoenteralink .= '<td>' . $langs->trans("Company") . '</td>';
1444 $htmltoenteralink .= '</tr>';
1445
1446 // rows with data
1447 while ($i < $num) {
1448 $objp = $this->db->fetch_object($resqllist);
1449 $alreadylinked = false;
1450 if (!empty($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key])) {
1451 if (in_array($objp->rowid, array_values($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key]))) {
1452 $alreadylinked = true;
1453 }
1454 }
1455 $htmltoenteralink .= '<tr class="oddeven">';
1456 $htmltoenteralink .= '<td>';
1457 if ($alreadylinked) {
1458 $htmltoenteralink .= img_picto('', 'link');
1459 } else {
1460 $htmltoenteralink .= '<input type="checkbox" name="idtolinkto[' . $key . '_' . $objp->rowid . ']" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
1461 }
1462 $htmltoenteralink .= '</td>';
1463 $htmltoenteralink .= '<td>';
1464 if (!$alreadylinked) {
1465 $htmltoenteralink .= '<label for="' . $key . '_' . $objp->rowid . '">';
1466 }
1467 $htmltoenteralink .= $objp->ref;
1468 if (!$alreadylinked) {
1469 $htmltoenteralink .= '</label>';
1470 }
1471 $htmltoenteralink .= '</td>';
1472 $htmltoenteralink .= '<td>' . (!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')) . '</td>';
1473 $htmltoenteralink .= '<td class="right">';
1474 if ($possiblelink['label'] == 'LinkToContract') {
1475 $htmltoenteralink .= $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")) . ' ';
1476 }
1477 $htmltoenteralink .= '<span class="amount">' . (isset($objp->total_ht) ? price($objp->total_ht) : '') . '</span>';
1478 $htmltoenteralink .= '</td>';
1479 $htmltoenteralink .= '<td>' . $objp->name . '</td>';
1480 $htmltoenteralink .= '</tr>';
1481 $i++;
1482 }
1483
1484 return $htmltoenteralink;
1485 }
1486
1501 private function makeAddLinkToAttendee($object, $key, $possiblelink, $num, $resqllist)
1502 {
1503 dol_syslog(__METHOD__, LOG_DEBUG);
1504 global $langs, $form;
1505 require_once DOL_DOCUMENT_ROOT . '/eventorganization/class/conferenceorboothattendee.class.php';
1506 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1507 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
1508 $attendeestatic = new ConferenceOrBoothAttendee($this->db);
1509 $companystatic = new Societe($this->db);
1510 $projectstatic = new Project($this->db);
1511 if (empty($form)) {
1512 $form = new Form($this->db);
1513 }
1514 $htmltoenteralink = '';
1515 $i = 0;
1516
1517 // headers
1518 $htmltoenteralink .= '<tr class="liste_titre">';
1519 $htmltoenteralink .= '<td class="nowrap"></td>';
1520 $htmltoenteralink .= '<td>' . $langs->trans("Ref") . '</td>';
1521 $htmltoenteralink .= '<td>' . $langs->trans("Name") . '</td>';
1522 $htmltoenteralink .= '<td>' . $langs->trans("Email") . '</td>';
1523 $htmltoenteralink .= '<td>' . $langs->trans("Company") . '</td>';
1524 $htmltoenteralink .= '<td>' . $langs->trans("Project") . '</td>';
1525 $htmltoenteralink .= '<td>' . $langs->trans("DateOfRegistration") . '</td>';
1526 $htmltoenteralink .= '</tr>';
1527
1528 // rows with data
1529 while ($i < $num) {
1530 $objp = $this->db->fetch_object($resqllist);
1531 $alreadylinked = false;
1532 if (!empty($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key])) {
1533 if (in_array($objp->rowid, array_values($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key]))) {
1534 $alreadylinked = true;
1535 }
1536 }
1537 $htmltoenteralink .= '<tr class="oddeven">';
1538 $htmltoenteralink .= '<td>';
1539 if ($alreadylinked) {
1540 $htmltoenteralink .= img_picto('', 'link');
1541 } else {
1542 $htmltoenteralink .= '<input type="checkbox" name="idtolinkto[' . $key . '_' . $objp->rowid . ']" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
1543 }
1544 $htmltoenteralink .= '</td>';
1545 $fetchattendee = $attendeestatic->fetch($objp->rowid);
1546 if ($fetchattendee) {
1547 $htmltoenteralink .= '<td>' . $attendeestatic->getNomUrl(0). '</td>';
1548 } else {
1549 $htmltoenteralink .= '<td><label for="' . $key . '_' . $objp->rowid . '">' . $objp->ref . '</label></td>';
1550 }
1551 $htmltoenteralink .= '<td>' . $objp->name . '</td>';
1552 $htmltoenteralink .= '<td>' . $objp->email . '</td>';
1553 $fetchcompany = $companystatic->fetch($objp->socid);
1554 if ($fetchcompany) {
1555 $htmltoenteralink .= '<td>' . $companystatic->getNomUrl(0). '</td>';
1556 } else {
1557 $htmltoenteralink .= '<td>' . $objp->name . '</td>';
1558 }
1559 $fetchcproject = $projectstatic->fetch($objp->fk_project);
1560 if ($fetchcproject) {
1561 $htmltoenteralink .= '<td>' . $projectstatic->getNomUrl(0). '</td>';
1562 } else {
1563 $htmltoenteralink .= '<td>' . $objp->fk_project . '</td>';
1564 }
1565 $htmltoenteralink .= '<td>' . $objp->date_subscription . '</td>';
1566 $htmltoenteralink .= '</tr>';
1567 $i++;
1568 }
1569
1570 return $htmltoenteralink;
1571 }
1572
1573 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1574
1588 public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
1589 {
1590 // phpcs:enable
1591 global $conf, $langs;
1592
1593 $langs->load("dict");
1594
1595 $out = '';
1596 //$moreattrib = '';
1597 $incotermArray = array();
1598
1599 $sql = "SELECT rowid, code";
1600 $sql .= " FROM " . $this->db->prefix() . "c_incoterms";
1601 $sql .= " WHERE active > 0";
1602 $sql .= " ORDER BY code ASC";
1603
1604 dol_syslog(get_class($this) . "::select_incoterm", LOG_DEBUG);
1605 $resql = $this->db->query($sql);
1606 if ($resql) {
1607 if ($conf->use_javascript_ajax && !$forcecombo) {
1608 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1609 $out .= ajax_combobox($htmlname, $events);
1610 }
1611
1612 if (!empty($page)) {
1613 $out .= '<form method="post" action="' . $page . '">';
1614 $out .= '<input type="hidden" name="action" value="set_incoterms">';
1615 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
1616 }
1617
1618 $out .= '<select id="' . $htmlname . '" class="flat selectincoterm width75" name="' . $htmlname . '" ' . $htmloption . '>';
1619 $out .= '<option value="0">&nbsp;</option>';
1620 $num = $this->db->num_rows($resql);
1621 $i = 0;
1622 if ($num) {
1623 while ($i < $num) {
1624 $obj = $this->db->fetch_object($resql);
1625 $incotermArray[$i]['rowid'] = $obj->rowid;
1626 $incotermArray[$i]['code'] = $obj->code;
1627 $i++;
1628 }
1629
1630 foreach ($incotermArray as $row) {
1631 if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
1632 $out .= '<option value="' . $row['rowid'] . '" selected>';
1633 } else {
1634 $out .= '<option value="' . $row['rowid'] . '">';
1635 }
1636
1637 if ($row['code']) {
1638 $out .= $row['code'];
1639 }
1640
1641 $out .= '</option>';
1642 }
1643 }
1644 $out .= '</select>';
1645 $out .= ajax_combobox($htmlname);
1646
1647 if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
1648 $out .= ajax_multiautocompleter('location_incoterms', array(), DOL_URL_ROOT . '/core/ajax/locationincoterms.php') . "\n";
1649 //$moreattrib .= ' autocomplete="off"';
1650 }
1651 $out .= '<input id="location_incoterms" class="maxwidthonsmartphone heightofcombo" type="text" name="location_incoterms" value="' . $location_incoterms . '">' . "\n";
1652
1653 if (!empty($page)) {
1654 $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="' . $langs->trans("Modify") . '"></form>';
1655 }
1656 } else {
1657 dol_print_error($this->db);
1658 }
1659
1660 return $out;
1661 }
1662
1663 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1664
1678 public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0, $morecss = "", $useajaxcombo = 1)
1679 {
1680 // phpcs:enable
1681 global $langs;
1682
1683 // If product & services are enabled or both disabled.
1684 if ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
1685 || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
1686 if (empty($hidetext)) {
1687 print $langs->trans("Type").'...';
1688 }
1689
1690 print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_' . $htmlname . '" name="' . $htmlname . '">';
1691 if ($showempty) {
1692 print '<option value="-1" class="opacitymedium"'.($useajaxcombo ? '' : ' disabled="disabled"');
1693 if ($selected == -1) {
1694 print ' selected';
1695 }
1696 print '>';
1697 if (is_numeric($showempty)) {
1698 print '&nbsp;';
1699 } else {
1700 print $showempty;
1701 }
1702 print '</option>';
1703 }
1704
1705 print '<option value="0"';
1706 if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
1707 print ' selected';
1708 }
1709 print '>' . $langs->trans("Product");
1710 print '</option>';
1711
1712 print '<option value="1"';
1713 if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
1714 print ' selected';
1715 }
1716 print '>' . $langs->trans("Service");
1717 print '</option>';
1718
1719 print '</select>';
1720
1721 if ($useajaxcombo) {
1722 print ajax_combobox('select_' . $htmlname);
1723 }
1724 //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1725 }
1726 if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
1727 print $langs->trans("Service");
1728 print '<input type="hidden" name="' . $htmlname . '" value="1">';
1729 }
1730 if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
1731 print $langs->trans("Product");
1732 print '<input type="hidden" name="' . $htmlname . '" value="0">';
1733 }
1734 if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
1735 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
1736 }
1737 }
1738
1739 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1740
1746 public function load_cache_types_fees()
1747 {
1748 // phpcs:enable
1749 global $langs;
1750
1751 $num = count($this->cache_types_fees);
1752 if ($num > 0) {
1753 return 0; // Cache already loaded
1754 }
1755
1756 dol_syslog(__METHOD__, LOG_DEBUG);
1757
1758 $langs->load("trips");
1759
1760 $sql = "SELECT c.code, c.label";
1761 $sql .= " FROM " . $this->db->prefix() . "c_type_fees as c";
1762 $sql .= " WHERE active > 0";
1763
1764 $resql = $this->db->query($sql);
1765 if ($resql) {
1766 $num = $this->db->num_rows($resql);
1767 $i = 0;
1768
1769 while ($i < $num) {
1770 $obj = $this->db->fetch_object($resql);
1771
1772 // If a translation exists, we use is, otherwise, we take the label by default
1773 $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
1774 $this->cache_types_fees[$obj->code] = $label;
1775 $i++;
1776 }
1777
1778 asort($this->cache_types_fees);
1779
1780 return $num;
1781 } else {
1782 dol_print_error($this->db);
1783 return -1;
1784 }
1785 }
1786
1787 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1788
1797 public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
1798 {
1799 // phpcs:enable
1800 global $user, $langs;
1801
1802 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
1803
1804 $this->load_cache_types_fees();
1805
1806 print '<select id="select_' . $htmlname . '" class="flat" name="' . $htmlname . '">';
1807 if ($showempty) {
1808 print '<option value="-1"';
1809 if ($selected == -1) {
1810 print ' selected';
1811 }
1812 print '>&nbsp;</option>';
1813 }
1814
1815 foreach ($this->cache_types_fees as $key => $value) {
1816 print '<option value="' . $key . '"';
1817 if ($key == $selected) {
1818 print ' selected';
1819 }
1820 print '>';
1821 print $value;
1822 print '</option>';
1823 }
1824
1825 print '</select>';
1826 if ($user->admin) {
1827 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
1828 }
1829 }
1830
1831
1832 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1833
1856 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)
1857 {
1858 // phpcs:enable
1859 global $conf, $langs;
1860
1861 $out = '';
1862
1863 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT') && !$forcecombo) {
1864 if (is_null($ajaxoptions)) {
1865 $ajaxoptions = array();
1866 }
1867
1868 require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1869
1870 // No immediate load of all database
1871 $placeholder = '';
1872 if ($selected && empty($selected_input_value)) {
1873 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1874 $societetmp = new Societe($this->db);
1875 $societetmp->fetch($selected);
1876 $selected_input_value = $societetmp->name;
1877 unset($societetmp);
1878 }
1879
1880 // mode 1
1881 $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 : '');
1882
1883 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
1884 if (empty($hidelabel)) {
1885 $out .= $langs->trans("RefOrLabel") . ' : ';
1886 } elseif ($hidelabel == 1 && !is_numeric($showempty)) {
1887 $placeholder = $langs->trans($showempty);
1888 } elseif ($hidelabel > 1) {
1889 $placeholder = $langs->trans("RefOrLabel");
1890 if ($hidelabel == 2) {
1891 $out .= img_picto($langs->trans("Search"), 'search');
1892 }
1893 }
1894 $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" />';
1895 if ($hidelabel == 3) {
1896 $out .= img_picto($langs->trans("Search"), 'search');
1897 }
1898
1899 $out .= ajax_event($htmlname, $events);
1900
1901 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, getDolGlobalInt('COMPANY_USE_SEARCH_TO_SELECT'), 0, $ajaxoptions);
1902 } else {
1903 // Immediate load of all database
1904 $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
1905 }
1906
1907 return $out;
1908 }
1909
1910
1911 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1912
1938 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 = '')
1939 {
1940 // phpcs:enable
1941
1942 global $conf, $langs;
1943
1944 $out = '';
1945
1946 $sav = getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT');
1947 if ($nokeyifsocid && $socid > 0) {
1948 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = 0;
1949 }
1950
1951 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT') && !$forcecombo) {
1952 $ajaxoptions = array();
1953
1954 require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1955
1956 // No immediate load of all database
1957 $placeholder = '';
1958 if ($selected && empty($selected_input_value)) {
1959 require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
1960 $contacttmp = new Contact($this->db);
1961 $contacttmp->fetch($selected);
1962 $selected_input_value = $contacttmp->getFullName($langs);
1963 unset($contacttmp);
1964 }
1965 if (!is_numeric($showempty)) {
1966 $placeholder = $showempty;
1967 }
1968
1969 // mode 1
1970 $urloption = 'htmlname=' . urlencode((string) (str_replace('.', '_', $htmlname))) . '&outjson=1&filter=' . urlencode((string) ($filter)) . (empty($exclude) ? '' : '&exclude=' . urlencode($exclude)) . ($showsoc ? '&showsoc=' . urlencode((string) ($showsoc)) : '');
1971
1972 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
1973
1974 $out .= '<input type="text" class="' . $morecss . '" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '') . ' ' . (getDolGlobalString('CONTACT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' spellcheck="false" />';
1975
1976 $out .= ajax_event($htmlname, $events);
1977
1978 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/contact/ajax/contact.php', $urloption, getDolGlobalInt('CONTACT_USE_SEARCH_TO_SELECT'), 0, $ajaxoptions);
1979 } else {
1980 // Immediate load of all database
1981 $multiple = false;
1982 $disableifempty = 0;
1983 $options_only = 0;
1984 $limitto = '';
1985
1986 $out .= $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid, $multiple, $disableifempty);
1987 }
1988
1989 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = $sav;
1990
1991 return $out;
1992 }
1993
1994
1995 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1996
2020 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)
2021 {
2022 // phpcs:enable
2023 global $user, $langs;
2024 global $hookmanager;
2025
2026 $langs->loadLangs(array("companies", "suppliers"));
2027
2028 $out = '';
2029 $num = 0;
2030 $outarray = array();
2031
2032 if ($selected === '') {
2033 $selected = array();
2034 } elseif (!is_array($selected)) {
2035 $selected = array($selected);
2036 }
2037
2038 // Clean $filter that may contains sql conditions so sql code
2039 if (function_exists('testSqlAndScriptInject')) {
2040 if (testSqlAndScriptInject($filter, 3) > 0) {
2041 $filter = '';
2042 return 'SQLInjectionTryDetected';
2043 }
2044 }
2045
2046 if ($filter != '') { // If a filter was provided
2047 $errormsg = '';
2048 $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
2049
2050 // Redo clean $filter that may contains sql conditions so sql code
2051 if (function_exists('testSqlAndScriptInject')) {
2052 if (testSqlAndScriptInject($filter, 3) > 0) {
2053 $filter = '';
2054 return 'SQLInjectionTryDetected';
2055 }
2056 }
2057 }
2058
2059 // We search companies
2060 $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
2061 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
2062 $sql .= ", s.address, s.zip, s.town";
2063 $sql .= ", dictp.code as country_code";
2064 }
2065 $sql .= " FROM " . $this->db->prefix() . "societe as s";
2066 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
2067 $sql .= " LEFT JOIN " . $this->db->prefix() . "c_country as dictp ON dictp.rowid = s.fk_pays";
2068 }
2069 if (!$user->hasRight('societe', 'client', 'voir')) {
2070 $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
2071 }
2072 $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")";
2073 if (!empty($user->socid)) {
2074 $sql .= " AND s.rowid = " . ((int) $user->socid);
2075 }
2076 if ($filter) {
2077 // $filter is safe because, it has been tested by testSqlAndScriptInject() and sanitized by forgeSQLFromUniversalSearchCriteria()
2078 $sqlwhere = $filter; // @phan-suppress-current-line SqlInjection
2079 $sql .= " AND (" . $sqlwhere . ")";
2080 }
2081 if (!$user->hasRight('societe', 'client', 'voir')) {
2082 $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
2083 }
2084 if (getDolGlobalString('COMPANY_HIDE_INACTIVE_IN_COMBOBOX')) {
2085 $sql .= " AND s.status <> 0";
2086 }
2087 if (!empty($excludeids)) {
2088 $sql .= " AND s.rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeids)) . ")";
2089 }
2090 // Add where from hooks
2091 $parameters = array();
2092 $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
2093 $sql .= $hookmanager->resPrint;
2094 // Add criteria
2095 if ($filterkey && $filterkey != '') {
2096 $sql .= " AND (";
2097 $prefix = !getDolGlobalString('COMPANY_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
2098 // For natural search
2099 $search_crit = explode(' ', $filterkey);
2100 $i = 0;
2101 if (count($search_crit) > 1) {
2102 $sql .= "(";
2103 }
2104 foreach ($search_crit as $crit) {
2105 if ($i > 0) {
2106 $sql .= " AND ";
2107 }
2108 $sql .= "(s.nom LIKE '" . $this->db->escape($prefix . $crit) . "%')";
2109 $i++;
2110 }
2111 if (count($search_crit) > 1) {
2112 $sql .= ")";
2113 }
2114 if (isModEnabled('barcode')) {
2115 $sql .= " OR s.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
2116 }
2117 $sql .= " OR s.code_client LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.code_fournisseur LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
2118 $sql .= " OR s.name_alias LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.tva_intra LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
2119 $sql .= ")";
2120 }
2121 $sql .= $this->db->order("nom", "ASC");
2122 $sql .= $this->db->plimit($limit, 0);
2123
2124 // Build output string
2125 dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
2126 $resql = $this->db->query($sql);
2127 if ($resql) {
2128 // Construct $out and $outarray
2129 $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($moreparam ? ' ' . $moreparam : '') . ' name="' . $htmlname . ($multiple ? '[]' : '') . '"' . ($multiple ? ' multiple' : '') . '>' . "\n";
2130
2131 $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
2132 if (getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT')) {
2133 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
2134 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
2135 if ($showempty && !is_numeric($showempty)) {
2136 $textifempty = $langs->trans($showempty);
2137 } else {
2138 $textifempty .= $langs->trans("All");
2139 }
2140 }
2141 if ($showempty) {
2142 $out .= '<option value="-1" data-html="' . dol_escape_htmltag('<span class="opacitymedium">' . ($textifempty ? $textifempty : '&nbsp;') . '</span>') . '">' . $textifempty . '</option>' . "\n";
2143 }
2144
2145 $companytemp = new Societe($this->db);
2146
2147 $num = $this->db->num_rows($resql);
2148 $i = 0;
2149 if ($num) {
2150 while ($i < $num) {
2151 $obj = $this->db->fetch_object($resql);
2152 $label = '';
2153 if ($showcode || getDolGlobalString('SOCIETE_ADD_REF_IN_LIST')) {
2154 if (($obj->client) && (!empty($obj->code_client))) {
2155 $label = $obj->code_client . ' - ';
2156 }
2157 if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
2158 $label .= $obj->code_fournisseur . ' - ';
2159 }
2160 $label .= ' ' . $obj->name;
2161 } else {
2162 $label = $obj->name;
2163 }
2164
2165 if (!empty($obj->name_alias)) {
2166 $label .= ' (' . $obj->name_alias . ')';
2167 }
2168
2169 if (getDolGlobalString('SOCIETE_SHOW_VAT_IN_LIST') && !empty($obj->tva_intra)) {
2170 $label .= ' - '.$obj->tva_intra;
2171 }
2172
2173 $labelhtml = $label;
2174
2175 if ($showtype) {
2176 $companytemp->id = $obj->rowid;
2177 $companytemp->client = $obj->client;
2178 $companytemp->fournisseur = $obj->fournisseur;
2179 $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
2180 if ($tmptype) {
2181 $labelhtml .= ' ' . $tmptype;
2182 }
2183
2184 if ($obj->client || $obj->fournisseur) {
2185 $label .= ' (';
2186 }
2187 if ($obj->client == 1 || $obj->client == 3) {
2188 $label .= $langs->trans("Customer");
2189 }
2190 if ($obj->client == 2 || $obj->client == 3) {
2191 $label .= ($obj->client == 3 ? ', ' : '') . $langs->trans("Prospect");
2192 }
2193 if ($obj->fournisseur) {
2194 $label .= ($obj->client ? ', ' : '') . $langs->trans("Supplier");
2195 }
2196 if ($obj->client || $obj->fournisseur) {
2197 $label .= ')';
2198 }
2199 }
2200
2201 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
2202 $s = ($obj->address ? ' - ' . $obj->address : '') . ($obj->zip ? ' - ' . $obj->zip : '') . ($obj->town ? ' ' . $obj->town : '');
2203 if (!empty($obj->country_code)) {
2204 $s .= ', ' . $langs->trans('Country' . $obj->country_code);
2205 }
2206 $label .= $s;
2207 $labelhtml .= $s;
2208 }
2209
2210 if (empty($outputmode)) {
2211 if (in_array($obj->rowid, $selected)) {
2212 $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>';
2213 } else {
2214 $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
2215 }
2216 } else {
2217 array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label, 'labelhtml' => $labelhtml));
2218 }
2219
2220 $i++;
2221 if (($i % 10) == 0) {
2222 $out .= "\n";
2223 }
2224 }
2225 }
2226 $out .= '</select>' . "\n";
2227 if (!$forcecombo) {
2228 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2229 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("COMPANY_USE_SEARCH_TO_SELECT"));
2230 }
2231 } else {
2232 dol_print_error($this->db);
2233 }
2234
2235 $this->result = array('nbofthirdparties' => $num);
2236
2237 if ($outputmode) {
2238 return $outarray;
2239 }
2240 return $out;
2241 }
2242
2243
2269 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 = '')
2270 {
2271 global $conf, $user, $langs, $hookmanager, $action;
2272
2273 $langs->load('companies');
2274
2275 if (empty($htmlid)) {
2276 $htmlid = $htmlname;
2277 }
2278 $num = 0;
2279 $out = '';
2280 $outarray = array();
2281
2282 if ($selected === '') {
2283 $selected = array();
2284 } elseif (!is_array($selected)) {
2285 $selected = array((int) $selected);
2286 }
2287
2288 // Clean $filter that may contains sql conditions so sql code
2289 if (function_exists('testSqlAndScriptInject')) {
2290 if (testSqlAndScriptInject($filter, 3) > 0) {
2291 $filter = '';
2292 return 'SQLInjectionTryDetected';
2293 }
2294 }
2295
2296 if ($filter != '') { // If a filter was provided
2297 if (preg_match('/[\‍(\‍)]/', $filter)) {
2298 // If there is one parenthesis inside the criteria, we assume it is an Universal Filter Syntax.
2299 $errormsg = '';
2300 $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
2301
2302 // Redo clean $filter that may contains sql conditions so sql code
2303 if (function_exists('testSqlAndScriptInject')) {
2304 if (testSqlAndScriptInject($filter, 3) > 0) {
2305 $filter = '';
2306 return 'SQLInjectionTryDetected';
2307 }
2308 }
2309 } else {
2310 // If not, we do nothing. We already know that there is no parenthesis
2311 // TODO Disallow this case in a future by returning an error here.
2312 dol_syslog("Warning, select_thirdparty_list was called with a filter criteria not using the Universal Search Filter Syntax.", LOG_WARNING);
2313 }
2314 }
2315
2316 if (!is_object($hookmanager)) {
2317 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
2318 $hookmanager = new HookManager($this->db);
2319 }
2320
2321 // We search third parties
2322 $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";
2323 if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
2324 $sql .= ", s.nom as company, s.town AS company_town";
2325 }
2326 $sql .= " FROM " . $this->db->prefix() . "socpeople as sp";
2327 if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
2328 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON s.rowid = sp.fk_soc";
2329 }
2330 $sql .= " WHERE sp.entity IN (" . getEntity('contact') . ")";
2331 $sql .= " AND ((sp.fk_user_creat = ".((int) $user->id)." AND sp.priv = 1) OR sp.priv = 0)"; // check if this is a private contact
2332 if ($socid > 0 || $socid == -1) {
2333 $sql .= " AND sp.fk_soc = " . ((int) $socid);
2334 }
2335 if (getDolGlobalString('CONTACT_HIDE_INACTIVE_IN_COMBOBOX')) {
2336 $sql .= " AND sp.statut <> 0";
2337 }
2338 // filter user access
2339 if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
2340 $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 .")";
2341 }
2342 if ($user->socid > 0) {
2343 $sql .= " AND sp.fk_soc = ".((int) $user->socid);
2344 }
2345 if ($filter) {
2346 // $filter is safe because, if it contains '(' or ')', it has been sanitized by testSqlAndScriptInject() and forgeSQLFromUniversalSearchCriteria()
2347 // if not, by testSqlAndScriptInject() only.
2348 $sanitizedfilter = $filter; // @phan-suppress-current-line SqlInjection
2349 $sql .= " AND (" . $sanitizedfilter . ")";
2350 }
2351 // Add where from hooks
2352 $parameters = array();
2353 $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
2354 $sql .= $hookmanager->resPrint;
2355 $sql .= " ORDER BY sp.lastname ASC";
2356
2357 dol_syslog(get_class($this) . "::selectcontacts", LOG_DEBUG);
2358 $resql = $this->db->query($sql);
2359 if ($resql) {
2360 $num = $this->db->num_rows($resql);
2361
2362 if ($htmlname != 'none' && !$options_only) {
2363 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlid . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . (($num || empty($disableifempty)) ? '' : ' disabled') . ($multiple ? 'multiple' : '') . ' ' . (!empty($moreparam) ? $moreparam : '') . '>';
2364 }
2365
2366 if ($showempty && !is_numeric($showempty)) {
2367 $textforempty = $showempty;
2368 $out .= '<option class="optiongrey" value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>' . $textforempty . '</option>';
2369 } else {
2370 if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
2371 $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>&nbsp;</option>';
2372 }
2373 if ($showempty == 2) {
2374 $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>-- ' . $langs->trans("Internal") . ' --</option>';
2375 }
2376 }
2377
2378 $i = 0;
2379 if ($num) {
2380 include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
2381 $contactstatic = new Contact($this->db);
2382
2383 while ($i < $num) {
2384 $obj = $this->db->fetch_object($resql);
2385
2386 // Set email (or phones) and town extended infos
2387 $extendedInfos = '';
2388 if (getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
2389 $extendedInfos = array();
2390 $email = trim($obj->email);
2391 if (!empty($email)) {
2392 $extendedInfos[] = $email;
2393 } else {
2394 $phone = trim($obj->phone);
2395 $phone_perso = trim($obj->phone_perso);
2396 $phone_mobile = trim($obj->phone_mobile);
2397 if (!empty($phone)) {
2398 $extendedInfos[] = $phone;
2399 }
2400 if (!empty($phone_perso)) {
2401 $extendedInfos[] = $phone_perso;
2402 }
2403 if (!empty($phone_mobile)) {
2404 $extendedInfos[] = $phone_mobile;
2405 }
2406 }
2407 $contact_town = trim($obj->contact_town);
2408 $company_town = trim($obj->company_town);
2409 if (!empty($contact_town)) {
2410 $extendedInfos[] = $contact_town;
2411 } elseif (!empty($company_town)) {
2412 $extendedInfos[] = $company_town;
2413 }
2414 $extendedInfos = implode(' - ', $extendedInfos);
2415 if (!empty($extendedInfos)) {
2416 $extendedInfos = ' - ' . $extendedInfos;
2417 }
2418 }
2419
2420 $contactstatic->id = $obj->rowid;
2421 $contactstatic->lastname = $obj->lastname;
2422 $contactstatic->firstname = $obj->firstname;
2423 if ($obj->statut == 1) {
2424 $tmplabel = '';
2425 if ($htmlname != 'none') {
2426 $disabled = 0;
2427 if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
2428 $disabled = 1;
2429 }
2430 if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
2431 $disabled = 1;
2432 }
2433 if (!empty($selected) && in_array($obj->rowid, $selected)) {
2434 $out .= '<option value="' . $obj->rowid . '"';
2435 if ($disabled) {
2436 $out .= ' disabled';
2437 }
2438 $out .= ' selected>';
2439
2440 $tmplabel = $contactstatic->getFullName($langs) . $extendedInfos;
2441 if ($showfunction && $obj->poste) {
2442 $tmplabel .= ' (' . $obj->poste . ')';
2443 }
2444 if (($showsoc > 0) && $obj->company) {
2445 $tmplabel .= ' - (' . $obj->company . ')';
2446 }
2447
2448 $out .= $tmplabel;
2449 $out .= '</option>';
2450 } else {
2451 $out .= '<option value="' . $obj->rowid . '"';
2452 if ($disabled) {
2453 $out .= ' disabled';
2454 }
2455 $out .= '>';
2456
2457 $tmplabel = $contactstatic->getFullName($langs) . $extendedInfos;
2458 if ($showfunction && $obj->poste) {
2459 $tmplabel .= ' (' . $obj->poste . ')';
2460 }
2461 if (($showsoc > 0) && $obj->company) {
2462 $tmplabel .= ' - (' . $obj->company . ')';
2463 }
2464
2465 $out .= $tmplabel;
2466 $out .= '</option>';
2467 }
2468 } else {
2469 if (in_array($obj->rowid, $selected)) {
2470 $tmplabel = $contactstatic->getFullName($langs) . $extendedInfos;
2471 if ($showfunction && $obj->poste) {
2472 $tmplabel .= ' (' . $obj->poste . ')';
2473 }
2474 if (($showsoc > 0) && $obj->company) {
2475 $tmplabel .= ' - (' . $obj->company . ')';
2476 }
2477
2478 $out .= $tmplabel;
2479 }
2480 }
2481
2482 if ($tmplabel != '') {
2483 array_push($outarray, array('key' => $obj->rowid, 'value' => $tmplabel, 'label' => $tmplabel, 'labelhtml' => $tmplabel));
2484 }
2485 }
2486 $i++;
2487 }
2488 } else {
2489 $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
2490 $out .= '<option class="disabled" value="-1"' . (($showempty == 2 || $multiple) ? '' : ' selected') . ' disabled="disabled">';
2491 $out .= $labeltoshow;
2492 $out .= '</option>';
2493 }
2494
2495 $parameters = array(
2496 'socid' => $socid,
2497 'htmlname' => $htmlname,
2498 'resql' => $resql,
2499 'out' => &$out,
2500 'showfunction' => $showfunction,
2501 'showsoc' => $showsoc,
2502 );
2503
2504 $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2505
2506 if ($htmlname != 'none' && !$options_only) {
2507 $out .= '</select>';
2508 }
2509
2510 if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
2511 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2512 $out .= ajax_combobox($htmlid, $events, getDolGlobalInt("CONTACT_USE_SEARCH_TO_SELECT"));
2513 }
2514
2515 $this->num = $num;
2516
2517 if ($options_only === 2) {
2518 // Return array of options
2519 return $outarray;
2520 } else {
2521 return $out;
2522 }
2523 } else {
2524 dol_print_error($this->db);
2525 return -1;
2526 }
2527 }
2528
2529
2530 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2531
2542 public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
2543 {
2544 // phpcs:enable
2545 global $langs, $conf;
2546
2547 // On recherche les remises
2548 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
2549 $sql .= " re.description, re.fk_facture_source";
2550 $sql .= " FROM " . $this->db->prefix() . "societe_remise_except as re";
2551 $sql .= " WHERE re.fk_soc = " . (int) $socid;
2552 $sql .= " AND re.entity = " . ((int) $conf->entity);
2553 if ($filter) {
2554 $sanitizedfilter = $filter; // @phan-suppress-current-line SqlInjection
2555 $sql .= " AND " . $sanitizedfilter;
2556 }
2557 $sql .= " ORDER BY re.description ASC";
2558
2559 dol_syslog(get_class($this) . "::select_remises", LOG_DEBUG);
2560 $resql = $this->db->query($sql);
2561 if ($resql) {
2562 print '<select id="select_' . $htmlname . '" class="flat maxwidth200onsmartphone" name="' . $htmlname . '">';
2563 $num = $this->db->num_rows($resql);
2564
2565 $qualifiedlines = $num;
2566
2567 $i = 0;
2568 if ($num) {
2569 print '<option value="0">&nbsp;</option>';
2570 while ($i < $num) {
2571 $obj = $this->db->fetch_object($resql);
2572 $desc = dol_trunc($obj->description, 40);
2573 if (preg_match('/\‍(CREDIT_NOTE\‍)/', $desc)) {
2574 $desc = preg_replace('/\‍(CREDIT_NOTE\‍)/', $langs->trans("CreditNote"), $desc);
2575 }
2576 if (preg_match('/\‍(DEPOSIT\‍)/', $desc)) {
2577 $desc = preg_replace('/\‍(DEPOSIT\‍)/', $langs->trans("Deposit"), $desc);
2578 }
2579 if (preg_match('/\‍(EXCESS RECEIVED\‍)/', $desc)) {
2580 $desc = preg_replace('/\‍(EXCESS RECEIVED\‍)/', $langs->trans("ExcessReceived"), $desc);
2581 }
2582 if (preg_match('/\‍(EXCESS PAID\‍)/', $desc)) {
2583 $desc = preg_replace('/\‍(EXCESS PAID\‍)/', $langs->trans("ExcessPaid"), $desc);
2584 }
2585
2586 $selectstring = '';
2587 if ($selected > 0 && $selected == $obj->rowid) {
2588 $selectstring = ' selected';
2589 }
2590
2591 $disabled = '';
2592 if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
2593 $qualifiedlines--;
2594 $disabled = ' disabled';
2595 }
2596
2597 if (getDolGlobalString('MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST') && !empty($obj->fk_facture_source)) {
2598 $tmpfac = new Facture($this->db);
2599 if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
2600 $desc = $desc . ' - ' . $tmpfac->ref;
2601 }
2602 }
2603
2604 print '<option value="' . $obj->rowid . '"' . $selectstring . $disabled . '>' . $desc . ' (' . price($obj->amount_ht) . ' ' . $langs->trans("HT") . ' - ' . price($obj->amount_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
2605 $i++;
2606 }
2607 }
2608 print '</select>';
2609 print ajax_combobox('select_' . $htmlname);
2610
2611 return $qualifiedlines;
2612 } else {
2613 dol_print_error($this->db);
2614 return -1;
2615 }
2616 }
2617
2618
2619 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2620
2636 public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0')
2637 {
2638 // phpcs:enable
2639 print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
2640 }
2641
2642 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2643
2668 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)
2669 {
2670 // phpcs:enable
2671 global $conf, $user, $langs, $hookmanager;
2672 global $action;
2673
2674 // Convert $selected into an int (in case it is an object)
2675 if (is_object($userselected)) {
2676 $selected = (int) $userselected->id;
2677 } elseif (is_numeric($userselected)) {
2678 $selected = (int) $userselected;
2679 } elseif (is_array($userselected)) {
2680 $selected = $userselected;
2681 } else {
2682 $selected = -1;
2683 }
2684
2685 // If no preselected user defined, we take current user
2686 if ((is_numeric($selected) && ((int) $selected < -4 || empty($selected))) && !getDolGlobalString('SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE')) {
2687 $selected = $user->id;
2688 }
2689
2690 // Convert selected int into an array
2691 if (!is_array($selected)) {
2692 if ($selected === -1 || $selected === '') {
2693 $selected = array();
2694 } else {
2695 $selected = array($selected);
2696 }
2697 }
2698
2699 // Exclude some users in $excludeUsers string
2700 $excludeUsers = null;
2701 if (is_array($exclude)) {
2702 $excludeUsers = implode(",", $exclude);
2703 }
2704
2705 // Include some users in $includeUsers string
2706 $includeUsers = null;
2707 $includeUsersArray = array();
2708 if (is_array($include)) {
2709 $includeUsersArray = $include;
2710 } elseif ($include == 'hierarchy') {
2711 // Build list includeUsersArray to have only hierarchy
2712 $includeUsersArray = $user->getAllChildIds(0);
2713 } elseif ($include == 'hierarchyme') {
2714 // Build list includeUsersArray to have only hierarchy and current user
2715 $includeUsersArray = $user->getAllChildIds(1);
2716 }
2717 // Get list of allowed users
2718 /* 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
2719 * see all other users and element in other. For example in agenda, we can have permission to read all event of otherusers.
2720 * So we disable this.
2721 if (!$user->hasRight('user', 'user', 'lire')) {
2722 if (empty($includeUsersArray)) {
2723 $includeUsers = implode(",", $user->getAllChildIds(1));
2724 } else {
2725 $includeUsers = implode(",", array_intersect($includeUsersArray, $user->getAllChildIds(1)));
2726 }
2727 } else {
2728 $includeUsers = implode(",", $includeUsersArray);
2729 } */
2730 $includeUsers = implode(",", $includeUsersArray);
2731
2732 $num = 0;
2733
2734 $out = '';
2735 $outarray = array();
2736 $outarray2 = array();
2737
2738 // Do we want to show the label of entity into the combo list ?
2739 $showlabelofentity = isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1 && !empty($user->admin) && empty($user->entity) && !preg_match('/^search_/', $htmlname);
2740 $userissuperadminentityone = isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && empty($user->entity);
2741
2742 // Forge request to select users
2743 $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";
2744 if ($showlabelofentity) {
2745 $sql .= ", e.label";
2746 }
2747 $sql .= " FROM " . $this->db->prefix() . "user as u";
2748 if ($showlabelofentity) {
2749 $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid = u.entity";
2750 }
2751 // Condition here should be the same than into societe->getSalesRepresentatives().
2752 if ($userissuperadminentityone && $force_entity !== 'default') {
2753 if (!empty($force_entity)) {
2754 $sql .= " WHERE u.entity IN (0, " . $this->db->sanitize($force_entity) . ")";
2755 } else {
2756 $sql .= " WHERE u.entity IS NOT NULL";
2757 }
2758 } else {
2759 if (isModEnabled('multicompany') && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2760 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2761 } else {
2762 $sql .= " WHERE u.entity IN (" . getEntity('user') . ")";
2763 }
2764 }
2765
2766 if (!empty($user->socid)) {
2767 $sql .= " AND u.fk_soc = " . ((int) $user->socid);
2768 }
2769 if (is_array($exclude) && $excludeUsers) {
2770 $sql .= " AND u.rowid NOT IN (" . $this->db->sanitize($excludeUsers) . ")";
2771 }
2772 if ($includeUsers) {
2773 $sql .= " AND u.rowid IN (" . $this->db->sanitize($includeUsers) . ")";
2774 }
2775 if (getDolGlobalString('USER_HIDE_INACTIVE_IN_COMBOBOX') || $notdisabled) {
2776 $sql .= " AND (u.statut <> 0";
2777 if (!empty($selected)) {
2778 $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
2779 }
2780 $sql .= ")";
2781 }
2782 if (getDolGlobalString('USER_HIDE_NONEMPLOYEE_IN_COMBOBOX')) {
2783 $sql .= " AND u.employee <> 0";
2784 }
2785 if (getDolGlobalString('USER_HIDE_EXTERNAL_IN_COMBOBOX')) {
2786 $sql .= " AND u.fk_soc IS NULL";
2787 }
2788 if (!empty($morefilter)) {
2789 $errormessage = '';
2790 $sql .= forgeSQLFromUniversalSearchCriteria($morefilter, $errormessage);
2791 if ($errormessage) {
2792 $this->errors[] = $errormessage;
2793 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
2794 if ($outputmode == 0) {
2795 return 'Error bad param $morefilter';
2796 } else {
2797 return array();
2798 }
2799 }
2800 }
2801
2802 //Add hook to filter on user (for example on usergroup define in custom modules)
2803 $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
2804 if (!empty($reshook)) {
2805 $sql .= $hookmanager->resPrint;
2806 }
2807
2808 if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
2809 $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
2810 } else {
2811 $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
2812 }
2813
2814 dol_syslog(get_class($this) . "::select_dolusers", LOG_DEBUG);
2815
2816 $resql = $this->db->query($sql);
2817 if ($resql) {
2818 $num = $this->db->num_rows($resql);
2819 $i = 0;
2820 if ($num) {
2821 // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
2822 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : ' minwidth200') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
2823 if ($show_empty && !$multiple) {
2824 $textforempty = ' ';
2825 if (!empty($conf->use_javascript_ajax)) {
2826 $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
2827 }
2828 if (!is_numeric($show_empty)) {
2829 $textforempty = $show_empty;
2830 }
2831 $out .= '<option class="optiongrey" value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ((empty($selected) || in_array(-1, $selected)) ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
2832
2833 $outarray[($show_empty < 0 ? $show_empty : -1)] = $textforempty;
2834 $outarray2[($show_empty < 0 ? $show_empty : -1)] = array(
2835 'id' => ($show_empty < 0 ? $show_empty : -1),
2836 'label' => $textforempty,
2837 'labelhtml' => $textforempty,
2838 'color' => '',
2839 'picto' => ''
2840 );
2841 }
2842 if ($showalso == 2 || $showalso == 3) {
2843 $out .= '<option value="-3"' . ((in_array(-3, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("MyTeam") . ' --</option>' . "\n";
2844
2845 $hasAtLeastOneSubordinate = (count($user->getAllChildIds(1)) > 1);
2846 if ($hasAtLeastOneSubordinate) {
2847 //$sql = "SELECT rowid FROM".MAIN_DB_PREFIX."user "
2848 $outarray[-3] = '-- ' . $langs->trans("MyTeam") . ' --';
2849 $outarray2[-3] = array(
2850 'id' => -3,
2851 'label' => '-- ' . $langs->trans("MyTeam") . ' --',
2852 'labelhtml' => '-- ' . $langs->trans("MyTeam") . ' --',
2853 'color' => '',
2854 'picto' => ''
2855 );
2856 }
2857 }
2858 if ($showalso == 1 || $showalso == 3) {
2859 $out .= '<option value="-2"' . ((in_array(-2, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("Everybody") . ' --</option>' . "\n";
2860
2861 $outarray[-2] = '-- ' . $langs->trans("Everybody") . ' --';
2862 $outarray2[-2] = array(
2863 'id' => -2,
2864 'label' => '-- ' . $langs->trans("Everybody") . ' --',
2865 'labelhtml' => '-- ' . $langs->trans("Everybody") . ' --',
2866 'color' => '',
2867 'picto' => ''
2868 );
2869 }
2870 if ($showalso == 4) {
2871 $out .= '<option value="-4"' . ((in_array(-4, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("AllProjectContacts") . ' --</option>' . "\n";
2872
2873 $outarray[-4] = '-- ' . $langs->trans("AllProjectContacts") . ' --';
2874 $outarray2[-4] = array(
2875 'id' => -4,
2876 'label' => '-- ' . $langs->trans("AllProjectContacts") . ' --',
2877 'labelhtml' => '-- ' . $langs->trans("AllProjectContacts") . ' --',
2878 'color' => '',
2879 'picto' => ''
2880 );
2881 }
2882
2883 $userstatic = new User($this->db);
2884
2885 while ($i < $num) {
2886 $obj = $this->db->fetch_object($resql);
2887
2888 $userstatic->id = $obj->rowid;
2889 $userstatic->lastname = $obj->lastname;
2890 $userstatic->firstname = $obj->firstname;
2891 $userstatic->photo = $obj->photo;
2892 $userstatic->status = $obj->status;
2893 $userstatic->entity = $obj->entity;
2894 $userstatic->admin = $obj->admin;
2895 $userstatic->gender = $obj->gender;
2896
2897 $disableline = '';
2898 if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
2899 $disableline = ($enableonlytext ? $enableonlytext : '1');
2900 }
2901
2902 $labeltoshow = '';
2903 $labeltoshowhtml = '';
2904
2905 // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
2906 $fullNameMode = 0;
2907 if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) {
2908 $fullNameMode = 1; //Firstname+lastname
2909 }
2910 $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
2911 $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
2912 if (empty($obj->firstname) && empty($obj->lastname)) {
2913 $labeltoshow .= $obj->login;
2914 $labeltoshowhtml .= $obj->login;
2915 }
2916
2917 // Complete name with a more info string like: ' (info1 - info2 - ...)'
2918 $moreinfo = '';
2919 $moreinfohtml = '';
2920 if (getDolGlobalString('MAIN_SHOW_LOGIN')) {
2921 $moreinfo .= ($moreinfo ? ' - ' : ' (');
2922 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
2923 $moreinfo .= $obj->login;
2924 $moreinfohtml .= $obj->login;
2925 }
2926 if ($showstatus >= 0) {
2927 if ($obj->status == 1 && $showstatus == 1) {
2928 $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Enabled');
2929 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Enabled');
2930 }
2931 if ($obj->status == 0 && $showstatus == 1) {
2932 $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Disabled');
2933 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Disabled');
2934 }
2935 }
2936 if ($showlabelofentity) {
2937 if (empty($obj->entity)) {
2938 $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans("AllEntities");
2939 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans("AllEntities");
2940 } else {
2941 if ($obj->entity != $conf->entity) {
2942 $moreinfo .= ($moreinfo ? ' - ' : ' (') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
2943 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
2944 }
2945 }
2946 }
2947 $moreinfo .= (!empty($moreinfo) ? ')' : '');
2948 $moreinfohtml .= (!empty($moreinfohtml) ? ')</span>' : '');
2949 if (!empty($disableline) && $disableline != '1') {
2950 // Add text from $enableonlytext parameter
2951 $moreinfo .= ' - ' . $disableline;
2952 $moreinfohtml .= ' - ' . $disableline;
2953 }
2954 $labeltoshow .= $moreinfo;
2955 $labeltoshowhtml .= $moreinfohtml;
2956
2957 $out .= '<option value="' . $obj->rowid . '"';
2958 if (!empty($disableline)) {
2959 $out .= ' disabled';
2960 }
2961 if (in_array($obj->rowid, $selected)) {
2962 $out .= ' selected';
2963 }
2964 $out .= ' data-html="';
2965
2966 $outhtml = $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1) . ' ';
2967 if ($showstatus >= 0 && $obj->status == 0) {
2968 $outhtml .= '<strike class="opacitymediumxxx">';
2969 }
2970 $outhtml .= $labeltoshowhtml;
2971 if ($showstatus >= 0 && $obj->status == 0) {
2972 $outhtml .= '</strike>';
2973 }
2974 $labeltoshowhtml = $outhtml;
2975
2976 $out .= dol_escape_htmltag($outhtml);
2977 $out .= '">';
2978 $out .= $labeltoshow;
2979 $out .= '</option>';
2980
2981 $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength) . $moreinfo;
2982 $outarray2[$userstatic->id] = array(
2983 'id' => $userstatic->id,
2984 'label' => $labeltoshow,
2985 'labelhtml' => $labeltoshowhtml,
2986 'color' => '',
2987 'picto' => ''
2988 );
2989
2990 $i++;
2991 }
2992 } else {
2993 $out .= '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '" disabled>';
2994 $out .= '<option value="">' . $langs->trans("None") . '</option>';
2995 }
2996 $out .= '</select>';
2997
2998 if ($num && !$forcecombo) {
2999 // Enhance with select2
3000 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
3001 $out .= ajax_combobox($htmlname);
3002 }
3003 } else {
3004 dol_print_error($this->db);
3005 }
3006
3007 $this->num = $num;
3008
3009 if ($outputmode == 2) {
3010 return $outarray2;
3011 } elseif ($outputmode) {
3012 return $outarray;
3013 }
3014
3015 return $out;
3016 }
3017
3018
3019 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3043 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)
3044 {
3045 // phpcs:enable
3046 global $langs, $user;
3047
3048 $userstatic = new User($this->db);
3049 $out = '';
3050
3051 // The list of selected users is provided by the caller through $listofuserid (owner first).
3052 // Fall back to the legacy global $_SESSION['assignedtouser'] only when no list is provided
3053 // (comm/action/card.php now scopes that session bucket per event id and no longer feeds this key).
3054 if (!empty($listofuserid)) {
3055 $assignedtouser = $listofuserid;
3056 } elseif (!empty($_SESSION['assignedtouser'])) {
3057 $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
3058 if (!is_array($assignedtouser)) {
3059 $assignedtouser = array();
3060 }
3061 } else {
3062 $assignedtouser = array();
3063 }
3064 $nbassignetouser = count($assignedtouser);
3065
3066 //if ($nbassignetouser && $action != 'view') $out .= '<br>';
3067 if ($nbassignetouser) {
3068 $out .= '<ul class="attendees">';
3069 }
3070 $i = 0;
3071 $ownerid = 0;
3072 foreach ($assignedtouser as $key => $value) {
3073 if ($value['id'] == $ownerid) {
3074 continue;
3075 }
3076
3077 $out .= '<li>';
3078
3079 $userstatic->fetch($value['id']);
3080 $out .= $userstatic->getNomUrl(-4);
3081
3082 if ($i == 0) {
3083 $ownerid = $value['id'];
3084 $out .= ' (' . $langs->trans("Owner") . ')';
3085 }
3086 // Add picto to delete owner/assignee
3087 if ($nbassignetouser > 1 && $action != 'view') {
3088 $canremoveassignee = 1;
3089 if ($i == 0) {
3090 // We are on the owner of the event
3091 if (!$canremoveowner) {
3092 $canremoveassignee = 0;
3093 }
3094 if (!$user->hasRight('agenda', 'allactions', 'create')) {
3095 $canremoveassignee = 0; // Can't remove the owner
3096 }
3097 } else {
3098 // We are not on the owner of the event but on a secondary assignee
3099 }
3100 if ($canremoveassignee) {
3101 // If user has all permission, he should be ableto remove a assignee.
3102 // If user has not all permission, he can onlyremove assignee of other (he can't remove itself)
3103 $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 . '">';
3104 }
3105 }
3106 // Show my availability
3107 if ($showproperties) {
3108 if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
3109 $out .= '<div class="myavailability inline-block">';
3110 $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;';
3111 //$out .= '<span class="opacitymedium">' . $langs->trans("Availability") . ':</span>';
3112 $out .= '</span>';
3113 $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>';
3114 $out .= '</div>';
3115 }
3116 }
3117 //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
3118 //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
3119
3120 $out .= '</li>';
3121 $i++;
3122 }
3123 if ($nbassignetouser) {
3124 $out .= '</ul>';
3125 }
3126
3127 // Method with no ajax
3128 if ($action != 'view') {
3129 // Section to add another user
3130 $out .= '<div class="divadduser'.$htmlname.'">';
3131 $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
3132 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
3133 $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
3134 $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
3135 $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#' . $action . 'assignedtouser").attr("disabled", false); }';
3136 $out .= ' else { jQuery("#' . $action . 'assignedtouser").attr("disabled", true); }';
3137 $out .= '});';
3138 $out .= '})</script>';
3139 $out .= img_picto('', 'user', 'class="pictofixedwidth"');
3140 $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter, 0, '', 'minwidth200');
3141 $out .= ' <button type="submit" disabled class="button valignmiddle smallpaddingimp reposition butActionAdd" id="' . $action . 'assignedtouser" name="' . $action . 'assignedtouser" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
3142 $out .= $langs->trans("Add").'</button>';
3143 $out .= '</div>';
3144 //$out .= '<br>';
3145 }
3146
3147 return $out;
3148 }
3149
3150 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3170 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())
3171 {
3172 // phpcs:enable
3173 global $langs;
3174
3175 require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php';
3176 require_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php';
3177 $formresources = new FormResource($this->db);
3178 $resourcestatic = new Dolresource($this->db);
3179
3180 $out = '';
3181 // The list of selected resources is provided by the caller through $listofresourceid.
3182 // Fall back to the legacy global $_SESSION['assignedtoresource'] only when no list is provided
3183 // (comm/action/card.php now scopes that session bucket per event id and no longer feeds this key).
3184 if (!empty($listofresourceid)) {
3185 $assignedtoresource = $listofresourceid;
3186 } elseif (!empty($_SESSION['assignedtoresource'])) {
3187 $assignedtoresource = json_decode($_SESSION['assignedtoresource'], true);
3188 if (!is_array($assignedtoresource)) {
3189 $assignedtoresource = array();
3190 }
3191 } else {
3192 $assignedtoresource = array();
3193 }
3194 $nbassignetoresource = count($assignedtoresource);
3195
3196 //if ($nbassignetoresource && $action != 'view') $out .= '<br>';
3197 if ($nbassignetoresource) {
3198 $out .= '<ul class="attendees">';
3199 }
3200 $i = 0;
3201
3202 foreach ($assignedtoresource as $key => $value) {
3203 $out .= '<li>';
3204 $resourcestatic->fetch($value['id']);
3205 $out .= $resourcestatic->getNomUrl(-1);
3206 if ($nbassignetoresource >= 1 && $action != 'view') {
3207 $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 . '">';
3208 }
3209 // Show my availability
3210 if ($showproperties) {
3211 if (is_array($listofresourceid) && count($listofresourceid)) {
3212 $out .= '<div class="myavailability inline-block">';
3213 $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;';
3214 //$out .= '<span class="opacitymedium">' . $langs->trans("Availability") . ': </span>';
3215 $out .= '</span>';
3216 $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>';
3217 $out .= '</div>';
3218 }
3219 }
3220 //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
3221 //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
3222
3223 $out .= '</li>';
3224 $i++;
3225 }
3226 if ($nbassignetoresource) {
3227 $out .= '</ul>';
3228 }
3229
3230 // Method with no ajax
3231 if ($action != 'view') {
3232 $out .= '<input type="hidden" class="removedassignedresourcehidden" name="removedassignedresource" value="">';
3233 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
3234 $out .= 'jQuery(".removedassignedresource").click(function() { jQuery(".removedassignedresourcehidden").val(jQuery(this).val()); });';
3235 $out .= 'jQuery(".assignedtoresource").change(function() { console.log(jQuery(".assignedtoresource option:selected").val());';
3236 $out .= ' if (jQuery(".assignedtoresource option:selected").val() > 0) { jQuery("#' . $action . 'assignedtoresource").attr("disabled", false); }';
3237 $out .= ' else { jQuery("#' . $action . 'assignedtoresource").attr("disabled", true); }';
3238 $out .= '});';
3239 $out .= '})</script>';
3240
3241 $events = array();
3242 if ($nbassignetoresource) {
3243 //$out .= img_picto('', 'add', 'class="pictofixedwidth"');
3244 } else {
3245 $out .= img_picto('', 'resource', 'class="pictofixedwidth"');
3246 }
3247 $out .= $formresources->select_resource_list(0, $htmlname, '', 1, 1, 0, $events, '', 2, 0, 'minwidth200');
3248 //$out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
3249 $out .= ' <button type="submit" disabled class="button valignmiddle smallpaddingimp reposition butActionAdd" id="' . $action . 'assignedtoresource" name="' . $action . 'assignedtoresource" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
3250 $out .= $langs->trans("Add");
3251 $out .= '</button>';
3252 $out .= '<br>';
3253 }
3254
3255 return $out;
3256 }
3257
3258 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3259
3289 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)
3290 {
3291 // phpcs:enable
3292 global $langs, $conf;
3293
3294 $out = '';
3295
3296 // check parameters
3297 $price_level = (!empty($price_level) ? $price_level : 0);
3298 if (is_null($ajaxoptions)) {
3299 $ajaxoptions = array();
3300 }
3301
3302 if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
3303 if (isModEnabled("product") && !isModEnabled('service')) {
3304 $filtertype = '0';
3305 } elseif (!isModEnabled('product') && isModEnabled("service")) {
3306 $filtertype = '1';
3307 }
3308 }
3309
3310 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
3311 $placeholder = (is_numeric($showempty) ? '' : 'placeholder="'.dolPrintHTML($showempty).'"');
3312
3313 if ($selected && empty($selected_input_value)) {
3314 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
3315 $producttmpselect = new Product($this->db);
3316 $producttmpselect->fetch($selected);
3317 $selected_input_value = $producttmpselect->ref;
3318 unset($producttmpselect);
3319 }
3320 // handle case where product or service module is disabled + no filter specified
3321 if ($filtertype == '') {
3322 if (!isModEnabled('product')) { // when product module is disabled, show services only
3323 $filtertype = 1;
3324 } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
3325 $filtertype = 0;
3326 }
3327 }
3328 // mode=1 means customers products
3329 $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;
3330 if ((int) $warehouseId > 0) {
3331 $urloption .= '&warehouseid=' . (int) $warehouseId;
3332 }
3333
3334 if (isModEnabled('variants') && is_array($selected_combinations)) {
3335 // Code to automatically insert with javascript the select of attributes under the select of product
3336 // when a parent of variant has been selected.
3337 // Note: Samecode than for product input using select
3338 $htmltag = 'input';
3339 $out .= '
3340 <!-- script to auto show attributes select tags if a variant was selected -->
3341 <script nonce="' . getNonce() . '">
3342 // auto show attributes fields
3343 selected = ' . json_encode($selected_combinations) . ';
3344 combvalues = {};
3345
3346 jQuery(document).ready(function () {
3347
3348 jQuery("input[name=\'prod_entry_mode\']").change(function () {
3349 if (jQuery(this).val() == \'free\') {
3350 jQuery(\'div#attributes_box\').empty();
3351 }
3352 });
3353
3354 jQuery("'.$htmltag.'#' . $htmlname . '").change(function () {
3355
3356 if (!jQuery(this).val()) {
3357 jQuery(\'div#attributes_box\').empty();
3358 return;
3359 }
3360
3361 console.log("A change has started. We get variants fields to inject html select");
3362
3363 jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
3364 id: jQuery(this).val()
3365 }, function (data) {
3366 jQuery(\'div#attributes_box\').empty();
3367
3368 jQuery.each(data, function (key, val) {
3369
3370 combvalues[val.id] = val.values;
3371
3372 var span = jQuery(document.createElement(\'div\')).css({
3373 \'display\': \'table-row\'
3374 });
3375
3376 span.append(
3377 jQuery(document.createElement(\'div\')).text(val.label).css({
3378 \'font-weight\': \'bold\',
3379 \'display\': \'table-cell\'
3380 })
3381 );
3382
3383 var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
3384 \'margin-left\': \'15px\',
3385 \'white-space\': \'pre\'
3386 }).append(
3387 jQuery(document.createElement(\'option\')).val(\'\')
3388 );
3389
3390 jQuery.each(combvalues[val.id], function (key, val) {
3391 var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
3392
3393 if (selected[val.fk_product_attribute] == val.id) {
3394 tag.attr(\'selected\', \'selected\');
3395 }
3396
3397 html.append(tag);
3398 });
3399
3400 span.append(html);
3401 jQuery(\'div#attributes_box\').append(span);
3402 });
3403 })
3404 });
3405
3406 ' . ($selected ? 'jQuery("'.$htmltag.'#' . $htmlname . '").change();' : '') . '
3407 });
3408 </script>
3409 ';
3410 }
3411
3412 if (empty($hidelabel)) {
3413 $placeholder = ' placeholder="' . dolPrintHTMLForAttribute($langs->trans("RefOrLabel")) . '"';
3414 } elseif ($hidelabel > 1) {
3415 $placeholder = ' placeholder="' . dolPrintHTMLForAttribute($langs->trans("RefOrLabel")) . '"';
3416 if ($hidelabel == 2) {
3417 $out .= img_picto($langs->trans("Search"), 'search');
3418 }
3419 }
3420
3421 $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" />';
3422 if ($hidelabel == 3) {
3423 $out .= img_picto($langs->trans("Search"), 'search');
3424 }
3425
3426 $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);
3427 } else {
3428 $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase, $warehouseId);
3429
3430 if (isModEnabled('variants') && is_array($selected_combinations)) {
3431 // Code to automatically insert with javascript the select of attributes under the select of product
3432 // when a parent of variant has been selected.
3433 // Note: Samecode than for product input using Ajax
3434 $htmltag = 'select';
3435 $out .= '
3436 <!-- script to auto show attributes select tags if a variant was selected -->
3437 <script nonce="' . getNonce() . '">
3438 // auto show attributes fields
3439 selected = ' . json_encode($selected_combinations) . ';
3440 combvalues = {};
3441
3442 jQuery(document).ready(function () {
3443
3444 jQuery("input[name=\'prod_entry_mode\']").change(function () {
3445 if (jQuery(this).val() == \'free\') {
3446 jQuery(\'div#attributes_box\').empty();
3447 }
3448 });
3449
3450 jQuery("'.$htmltag.'#' . $htmlname . '").change(function () {
3451
3452 if (!jQuery(this).val()) {
3453 jQuery(\'div#attributes_box\').empty();
3454 return;
3455 }
3456
3457 console.log("A change has started. We get variants fields to inject html select");
3458
3459 jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
3460 id: jQuery(this).val()
3461 }, function (data) {
3462 jQuery(\'div#attributes_box\').empty();
3463
3464 jQuery.each(data, function (key, val) {
3465
3466 combvalues[val.id] = val.values;
3467
3468 var span = jQuery(document.createElement(\'div\')).css({
3469 \'display\': \'table-row\'
3470 });
3471
3472 span.append(
3473 jQuery(document.createElement(\'div\')).text(val.label).css({
3474 \'font-weight\': \'bold\',
3475 \'display\': \'table-cell\'
3476 })
3477 );
3478
3479 var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
3480 \'margin-left\': \'15px\',
3481 \'white-space\': \'pre\'
3482 }).append(
3483 jQuery(document.createElement(\'option\')).val(\'\')
3484 );
3485
3486 jQuery.each(combvalues[val.id], function (key, val) {
3487 var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
3488
3489 if (selected[val.fk_product_attribute] == val.id) {
3490 tag.attr(\'selected\', \'selected\');
3491 }
3492
3493 html.append(tag);
3494 });
3495
3496 span.append(html);
3497 jQuery(\'div#attributes_box\').append(span);
3498 });
3499 })
3500 });
3501
3502 ' . ($selected ? 'jQuery("'.$htmltag.'#' . $htmlname . '").change();' : '') . '
3503 });
3504 </script>
3505 ';
3506 }
3507 }
3508
3509 if (empty($nooutput)) {
3510 print $out;
3511 } else {
3512 return $out;
3513 }
3514 }
3515
3516 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3517
3533 public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
3534 {
3535 // phpcs:enable
3536
3537 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
3538
3539 $error = 0;
3540 $out = '';
3541
3542 if (!$forcecombo) {
3543 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
3544 $events = array();
3545 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("BOM_USE_SEARCH_TO_SELECT"));
3546 }
3547
3548 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
3549
3550 $sql = 'SELECT b.rowid, b.ref, b.label as bomLabel, p.label as productLabel';
3551 $sql .= ' FROM ' . $this->db->prefix() . 'bom_bom as b';
3552 $sql .= ' INNER JOIN ' . $this->db->prefix() . 'product as p ON b.fk_product = p.rowid';
3553 $sql .= ' WHERE b.entity IN (' . getEntity('bom') . ')';
3554 if (!empty($status)) {
3555 $sql .= ' AND status = ' . (int) $status;
3556 }
3557 if (!empty($type)) {
3558 $sql .= ' AND bomtype = ' . (int) $type;
3559 }
3560 if (!empty($TProducts)) {
3561 $sql .= ' AND fk_product IN (' . $this->db->sanitize(implode(',', $TProducts)) . ')';
3562 }
3563 if (!empty($limit)) {
3564 $sql .= ' LIMIT ' . (int) $limit;
3565 }
3566 $resql = $this->db->query($sql);
3567 if ($resql) {
3568 if ($showempty) {
3569 $out .= '<option value="-1"';
3570 if (empty($selected)) {
3571 $out .= ' selected';
3572 }
3573 $out .= '>&nbsp;</option>';
3574 }
3575 while ($obj = $this->db->fetch_object($resql)) {
3576 $out .= '<option value="' . $obj->rowid . '"';
3577 if ($obj->rowid == $selected) {
3578 $out .= 'selected';
3579 }
3580 $out .= '>' . $obj->ref . ' - ' . $obj->productLabel . ' - ' . $obj->bomLabel . '</option>';
3581 }
3582 } else {
3583 $error++;
3584 dol_print_error($this->db);
3585 }
3586 $out .= '</select>';
3587 if (empty($nooutput)) {
3588 print $out;
3589 } else {
3590 return $out;
3591 }
3592 }
3593
3594 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3595
3622 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)
3623 {
3624 // phpcs:enable
3625 global $langs;
3626 global $hookmanager;
3627
3628 $out = '';
3629 $outarray = array();
3630
3631 // Units
3632 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
3633 $langs->load('other');
3634 }
3635
3636 $warehouseStatusArray = array();
3637 if (!empty($warehouseStatus)) {
3638 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
3639 if (preg_match('/warehouseclosed/', $warehouseStatus)) {
3640 $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
3641 }
3642 if (preg_match('/warehouseopen/', $warehouseStatus)) {
3643 $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
3644 }
3645 if (preg_match('/warehouseinternal/', $warehouseStatus)) {
3646 $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
3647 }
3648 }
3649
3650 $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";
3651 if (count($warehouseStatusArray)) {
3652 $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
3653 } else {
3654 $selectFieldsGrouped = ", " . $this->db->ifsql("p.stock IS NULL", '0', "p.stock") . " AS stock";
3655 }
3656
3657 $sql = "SELECT ";
3658
3659 // Add select from hooks
3660 $parameters = array();
3661 $reshook = $hookmanager->executeHooks('selectProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
3662 if (empty($reshook)) {
3663 $sql .= $selectFields.$selectFieldsGrouped.$hookmanager->resPrint;
3664 } else {
3665 $sql .= $hookmanager->resPrint;
3666 }
3667
3668 if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
3669 // Take randomly the first category of product to allow a sort on it. Bugged feature !
3670 $sql .= ", (SELECT " . $this->db->prefix() . "categorie_product.fk_categorie
3671 FROM " . $this->db->prefix() . "categorie_product
3672 WHERE " . $this->db->prefix() . "categorie_product.fk_product = p.rowid
3673 LIMIT 1
3674 ) AS categorie_product_id";
3675 }
3676
3677 // Price by customer
3678 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
3679 $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
3680 $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';
3681 $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref, custdiscount_percent";
3682 }
3683 // Units
3684 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
3685 $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";
3686 $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';
3687 }
3688
3689 // Multilang : we add translation
3690 if (getDolGlobalInt('MAIN_MULTILANGS')) {
3691 $sql .= ", pl.label as label_translated";
3692 $sql .= ", pl.description as description_translated";
3693 $selectFields .= ", label_translated";
3694 $selectFields .= ", description_translated";
3695 }
3696 // Price by quantity
3697 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
3698 $sql .= ", (SELECT pp.rowid FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid";
3699 if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
3700 $sql .= " AND price_level = " . ((int) $price_level);
3701 }
3702 $sql .= " ORDER BY date_price";
3703 $sql .= " DESC LIMIT 1) as price_rowid";
3704 $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
3705 if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
3706 $sql .= " AND price_level = " . ((int) $price_level);
3707 }
3708 $sql .= " ORDER BY date_price";
3709 $sql .= " DESC LIMIT 1) as price_by_qty";
3710 $selectFields .= ", price_rowid, price_by_qty";
3711 }
3712
3713 //$sqlfields = $sql; // $sql fields to remove for count total
3714
3715 $sql .= " FROM ".$this->db->prefix()."product as p";
3716
3717 if (getDolGlobalString('MAIN_SEARCH_PRODUCT_FORCE_INDEX')) {
3718 $sql .= " USE INDEX (" . $this->db->sanitize(getDolGlobalString('MAIN_PRODUCT_FORCE_INDEX')) . ")";
3719 }
3720
3721 // Add from (left join) from hooks
3722 $parameters = array(
3723 'socid' => $socid,
3724 );
3725 $reshook = $hookmanager->executeHooks('selectProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
3726 $sql .= $hookmanager->resPrint;
3727
3728 if (count($warehouseStatusArray)) {
3729 // Return line if product is inside the selected stock. If not, e.* and p.* will be null so we will count 0.
3730 // Replace this with a AND EXISTS ? Not possible as we need the ps.reel field for the SUM or 0 if no link.
3731 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as ps ON ps.fk_product = p.rowid";
3732 $sql .= " LEFT JOIN " . $this->db->prefix() . "entrepot as e ON ps.fk_entrepot = e.rowid AND e.entity IN (" . getEntity('stock') . ")";
3733 $sql .= ' AND e.statut IN (' . $this->db->sanitize($this->db->escape(implode(',', $warehouseStatusArray))) . ')';
3734 }
3735
3736 // Price by customer (Add field pcp for the older price for couple product/thirdparty.
3737 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
3738 $now = dol_now();
3739 $sql .= " LEFT JOIN (";
3740 $sql .= " SELECT pcp1.*";
3741 $sql .= " FROM " . $this->db->prefix() . "product_customer_price AS pcp1";
3742 $sql .= " LEFT JOIN (";
3743 $sql .= " SELECT fk_soc, fk_product, MIN(date_begin) AS date_begin";
3744 $sql .= " FROM " . $this->db->prefix() . "product_customer_price";
3745 $sql .= " WHERE fk_soc = " . ((int) $socid);
3746 $sql .= " AND date_begin <= '" . $this->db->idate($now) . "'";
3747 $sql .= " AND (date_end IS NULL OR '" . $this->db->idate($now) . "' <= date_end)";
3748 $sql .= " GROUP BY fk_soc, fk_product";
3749 $sql .= " ) AS pcp2 ON pcp1.fk_soc = pcp2.fk_soc AND pcp1.fk_product = pcp2.fk_product AND pcp1.date_begin = pcp2.date_begin";
3750 $sql .= " WHERE pcp2.fk_soc IS NOT NULL";
3751 $sql .= " ) AS pcp ON pcp.fk_soc = " . ((int) $socid) . " AND pcp.fk_product = p.rowid";
3752 }
3753 // Units : we add unit properties with a link on the primary key of unit
3754 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
3755 $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units as u ON u.rowid = p.fk_unit";
3756 }
3757 // Multilang : we add translation fields with a link on unique key fk_product/lang.
3758 if (getDolGlobalInt('MAIN_MULTILANGS')) {
3759 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_lang as pl ON pl.fk_product = p.rowid";
3760 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && !empty($socid)) {
3761 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
3762 $soc = new Societe($this->db);
3763 $result = $soc->fetch($socid);
3764 if ($result > 0 && !empty($soc->default_lang)) {
3765 $sql .= " AND pl.lang = '" . $this->db->escape($soc->default_lang) . "'";
3766 } else {
3767 $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
3768 }
3769 } else {
3770 $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
3771 }
3772 }
3773
3774 // Add WHERE conditions
3775 $sql .= ' WHERE p.entity IN (' . getEntity('product') . ')';
3776 if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD')) {
3777 if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD_BUT_ALLOW_SEARCH_IN_EAN13')) {
3778 if (strlen($filterkey) != 13) {
3779 $sql .= " AND NOT EXISTS (SELECT pac.rowid FROM ".$this->db->prefix()."product_attribute_combination as pac WHERE pac.fk_product_child = p.rowid)";
3780 }
3781 } else {
3782 $sql .= " AND NOT EXISTS (SELECT pac.rowid FROM ".$this->db->prefix()."product_attribute_combination as pac WHERE pac.fk_product_child = p.rowid)";
3783 }
3784 }
3785 if ($finished == 0) {
3786 $sql .= " AND p.finished = " . ((int) $finished);
3787 } elseif ($finished == 1) {
3788 $sql .= " AND p.finished = ".((int) $finished);
3789 }
3790 if ($status >= 0) {
3791 $sql .= " AND p.tosell = ".((int) $status);
3792 }
3793 if ($status_purchase >= 0) {
3794 $sql .= " AND p.tobuy = " . ((int) $status_purchase);
3795 }
3796 // Filter by product type
3797 if (strval($filtertype) != '') {
3798 $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
3799 } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
3800 $sql .= " AND p.fk_product_type = 1";
3801 } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
3802 $sql .= " AND p.fk_product_type = 0";
3803 }
3804
3805 if ((int) $warehouseId > 0) {
3806 $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)";
3807 }
3808
3809 // Add where from hooks
3810 $parameters = array(
3811 'filterkey' => &$filterkey,
3812 'socid' => $socid,
3813 );
3814 $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
3815 $sql .= $hookmanager->resPrint;
3816 // Add criteria on ref/label
3817 if ($filterkey != '') {
3818 $sqlSupplierSearch = '';
3819
3820 $sql .= ' AND (';
3821 $prefix = getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
3822 // For natural search
3823 $search_crit = explode(' ', $filterkey);
3824 $i = 0;
3825 if (count($search_crit) > 1) {
3826 $sql .= "(";
3827 }
3828 foreach ($search_crit as $crit) {
3829 if ($i > 0) {
3830 $sql .= " AND ";
3831 }
3832 $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3833 if (getDolGlobalInt('MAIN_MULTILANGS')) {
3834 $sql .= " OR pl.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3835 }
3836 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
3837 $sql .= " OR pcp.ref_customer LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3838 }
3839 if (getDolGlobalString('PRODUCT_AJAX_SEARCH_ON_DESCRIPTION')) {
3840 $sql .= " OR p.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3841 if (getDolGlobalInt('MAIN_MULTILANGS')) {
3842 $sql .= " OR pl.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3843 }
3844 }
3845
3846 // include search in supplier ref
3847 if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF')) {
3848 $sqlSupplierSearch .= !empty($sqlSupplierSearch) ? ' AND ' : '';
3849 $sqlSupplierSearch .= " pfp.ref_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3850 }
3851 $sql .= ")";
3852 $i++;
3853 }
3854 if (count($search_crit) > 1) {
3855 $sql .= ")";
3856 }
3857 if (isModEnabled('barcode')) {
3858 $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
3859 }
3860
3861 // include search in supplier ref
3862 if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF')) {
3863 $sql .= " OR EXISTS (SELECT pfp.fk_product FROM " . $this->db->prefix() . "product_fournisseur_price as pfp WHERE p.rowid = pfp.fk_product";
3864 $sql .= " AND (";
3865 $sql .= $sqlSupplierSearch;
3866 $sql .= "))";
3867 }
3868
3869 $sql .= ')';
3870 }
3871 if (count($warehouseStatusArray)) {
3872 $sql .= " GROUP BY " . $this->db->sanitize($selectFields, 0, 0, 1); // To have the SUM on ps.reel working in the select.
3873 }
3874
3875 // Sort by category
3876 // 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)
3877 if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
3878 $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");
3879 } elseif ((int) $selected > 0) {
3880 $sql .= " ORDER BY CASE WHEN p.rowid = ".((int) $selected)." THEN 0 ELSE 1 END, p.ref ASC";
3881 } else {
3882 $sql .= $this->db->order("p.ref");
3883 }
3884
3885 $limit = getDolGlobalInt('SEARCH_LIMIT_AJAX') ?: $limit; // SEARCH_LIMIT_AJAX is a hidden option that has priority on visible option PRODUIT_LIMIT_SIZE if set.
3886 $sql .= $this->db->plimit($limit, 0);
3887
3888 /* The fast and low memory method to get and count full list converts the sql into a sql count */
3889 /*
3890 $nbtotalofrecords = 0;
3891 $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
3892 $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
3893
3894 $resql = $this->db->query($sqlforcount);
3895 if ($resql) {
3896 $objforcount = $this->db->fetch_object($resql);
3897 $nbtotalofrecords = $objforcount->nbtotalofrecords;
3898 } else {
3899 dol_print_error($this->db);
3900 }
3901 */
3902
3903 // Build output string
3904 dol_syslog(get_class($this) . "::select_produits_list search products", LOG_DEBUG);
3905
3906 // If we have no $limit parameter, this request may hang dur to high number of lines returned.
3907 // This should not happen because this method should not be called directly, iIt is called by select_produit() that always add a $limit parameter.
3908 $result = $this->db->query($sql);
3909
3910 if ($result) {
3911 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
3912 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
3913 require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
3914
3915 $num = $this->db->num_rows($result);
3916
3917 $events = array();
3918
3919 if (!$forcecombo) {
3920 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
3921 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
3922 }
3923
3924 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
3925
3926 $textifempty = '';
3927 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
3928 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
3929 if (getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
3930 if ($showempty && !is_numeric($showempty)) {
3931 $textifempty = $langs->trans($showempty);
3932 } else {
3933 $textifempty .= $langs->trans("All");
3934 }
3935 } else {
3936 if ($showempty && !is_numeric($showempty)) {
3937 $textifempty = $langs->trans($showempty);
3938 }
3939 }
3940 if ($showempty) {
3941 $out .= '<option value="-1" selected>' . ($textifempty ? $textifempty : '&nbsp;') . '</option>';
3942 }
3943
3944 $i = 0;
3945 while ($num && $i < $num) {
3946 $opt = '';
3947 $optJson = array();
3948 $objp = $this->db->fetch_object($result);
3949
3950 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
3951 $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
3952 $sql .= " FROM " . $this->db->prefix() . "product_price_by_qty";
3953 $sql .= " WHERE fk_product_price = " . ((int) $objp->price_rowid);
3954 $sql .= " ORDER BY quantity ASC";
3955
3956 dol_syslog(get_class($this) . "::select_produits_list search prices by qty", LOG_DEBUG);
3957 $result2 = $this->db->query($sql);
3958 if ($result2) {
3959 $nb_prices = $this->db->num_rows($result2);
3960 $j = 0;
3961 while ($nb_prices && $j < $nb_prices) {
3962 $objp2 = $this->db->fetch_object($result2);
3963
3964 $objp->price_by_qty_rowid = $objp2->rowid;
3965 $objp->price_by_qty_price_base_type = $objp2->price_base_type;
3966 $objp->price_by_qty_quantity = $objp2->quantity;
3967 $objp->price_by_qty_unitprice = $objp2->unitprice;
3968 $objp->price_by_qty_remise_percent = $objp2->remise_percent;
3969 // For backward compatibility
3970 $objp->quantity = $objp2->quantity;
3971 $objp->price = $objp2->price;
3972 $objp->unitprice = $objp2->unitprice;
3973 $objp->remise_percent = $objp2->remise_percent;
3974
3975 //$objp->tva_tx is not overwritten by $objp2 value
3976 //$objp->default_vat_code is not overwritten by $objp2 value
3977
3978 $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
3979 '@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';
3980 $j++;
3981
3982 // Add new entry
3983 // "key" value of json key array is used by jQuery automatically as selected value
3984 // "label" value of json key array is used by jQuery automatically as text for combo box
3985 $out .= $opt;
3986 array_push($outarray, $optJson);
3987 }
3988 }
3989 } else {
3990 if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
3991 $price_product = new Product($this->db);
3992 $price_product->fetch($objp->rowid, '', '', '1');
3993
3994 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
3995 $priceparser = new PriceParser($this->db);
3996 $price_result = $priceparser->parseProduct($price_product);
3997 if ($price_result >= 0) {
3998 $objp->price = $price_result;
3999 $objp->unitprice = $price_result;
4000 //Calculate the VAT
4001 $objp->price_ttc = (float) price2num($objp->price) * (1 + ($objp->tva_tx / 100));
4002 $objp->price_ttc = price2num($objp->price_ttc, 'MU');
4003 }
4004 }
4005 if (getDolGlobalInt('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES') && !empty($objp->custprice)) {
4006 $price_level = '';
4007 }
4008 $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
4009 // Add new entry
4010 // "key" value of json key array is used by jQuery automatically as selected value
4011 // "label" value of json key array is used by jQuery automatically as text for combo box
4012 $out .= $opt;
4013 array_push($outarray, $optJson);
4014 }
4015
4016 $i++;
4017 }
4018
4019 $out .= '</select>';
4020
4021 $this->db->free($result);
4022
4023 if (empty($outputmode)) {
4024 return $out;
4025 }
4026
4027 return $outarray;
4028 } else {
4029 dol_print_error($this->db);
4030 }
4031
4032 return '';
4033 }
4034
4050 protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
4051 {
4052 global $langs, $conf, $user;
4053 global $hookmanager;
4054
4055 $outkey = '';
4056 $outval = '';
4057 $outref = '';
4058 $outlabel = '';
4059 $outlabel_translated = '';
4060 $outdesc = '';
4061 $outdesc_translated = '';
4062 $outbarcode = '';
4063 $outorigin = '';
4064 $outtype = '';
4065 $outprice_ht = '';
4066 $outprice_ttc = '';
4067 $outpricebasetype = '';
4068 $outtva_tx = '';
4069 $outdefault_vat_code = '';
4070 $outqty = 1;
4071 $outdiscount = '0';
4072
4073 $maxlengtharticle = getDolGlobalInt('PRODUCT_MAX_LENGTH_COMBO', 48);
4074
4075 $productlabel = $objp->label;
4076 if (!empty($objp->label_translated)) {
4077 $productlabel = $objp->label_translated;
4078 }
4079 $label = $productlabel;
4080 if (!empty($filterkey) && $filterkey != '') {
4081 $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
4082 }
4083
4084 $outkey = $objp->rowid;
4085 $outref = $objp->ref;
4086 $outrefcust = empty($objp->custref) ? '' : $objp->custref;
4087 $outlabel = $objp->label;
4088 $outdesc = $objp->description;
4089 if (getDolGlobalInt('MAIN_MULTILANGS')) {
4090 $outlabel_translated = $objp->label_translated;
4091 $outdesc_translated = $objp->description_translated;
4092 }
4093 $outbarcode = $objp->barcode;
4094 $outorigin = $objp->fk_country;
4095 $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
4096
4097 $outtype = $objp->fk_product_type;
4098 $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
4099 $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
4100
4101 if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
4102 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
4103 }
4104
4105 // Units
4106 $outvalUnits = '';
4107 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4108 if (!empty($objp->unit_short)) {
4109 $outvalUnits .= ' - ' . $objp->unit_short;
4110 }
4111 }
4112 if (getDolGlobalString('PRODUCT_SHOW_DIMENSIONS_IN_COMBO')) {
4113 if (!empty($objp->weight) && $objp->weight_units !== null) {
4114 $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
4115 $outvalUnits .= ' - ' . $unitToShow;
4116 }
4117 if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
4118 $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
4119 $outvalUnits .= ' - ' . $unitToShow;
4120 }
4121 if (!empty($objp->surface) && $objp->surface_units !== null) {
4122 $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
4123 $outvalUnits .= ' - ' . $unitToShow;
4124 }
4125 if (!empty($objp->volume) && $objp->volume_units !== null) {
4126 $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
4127 $outvalUnits .= ' - ' . $unitToShow;
4128 }
4129 }
4130 if ($outdurationvalue && $outdurationunit) {
4131 $da = array(
4132 'h' => $langs->trans('Hour'),
4133 'd' => $langs->trans('Day'),
4134 'w' => $langs->trans('Week'),
4135 'm' => $langs->trans('Month'),
4136 'y' => $langs->trans('Year')
4137 );
4138 if (isset($da[$outdurationunit])) {
4139 $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
4140 }
4141 }
4142
4143 // Set stocktag (stock too low or not or unknown)
4144 $stocktag = 0;
4145 if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
4146 if ($user->hasRight('stock', 'lire')) {
4147 if ($objp->stock > 0) {
4148 $stocktag = 1;
4149 } elseif ($objp->stock <= 0) {
4150 $stocktag = -1;
4151 }
4152 }
4153 }
4154
4155 // Set full plain label for the native <option> text. Select2 uses this text
4156 // as its search corpus, while data-html below keeps the visible label short.
4157 $labeltosearch = '';
4158 $labeltosearch .= $objp->ref;
4159 if (!empty($objp->custref)) {
4160 $labeltosearch .= ' (' . $objp->custref . ')';
4161 }
4162 if ($outbarcode) {
4163 $labeltosearch .= ' (' . $outbarcode . ')';
4164 }
4165 $labeltosearch .= ' - ' . $productlabel;
4166 if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
4167 $labeltosearch .= ' (' . getCountry($outorigin, '1') . ')';
4168 }
4169
4170 // Set $labltoshowhtml
4171 $labeltoshowhtml = '';
4172 $labeltoshowhtml .= $objp->ref;
4173 if (!empty($objp->custref)) {
4174 $labeltoshowhtml .= ' (' . $objp->custref . ')';
4175 }
4176 if (!empty($filterkey) && $filterkey != '') {
4177 $labeltoshowhtml = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $labeltoshowhtml, 1);
4178 }
4179 if ($outbarcode) {
4180 $labeltoshowhtml .= ' (' . $outbarcode . ')';
4181 }
4182 $labeltoshowhtml .= ' - ' . dol_trunc($label, $maxlengtharticle);
4183 if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
4184 $labeltoshowhtml .= ' (' . getCountry($outorigin, '1') . ')';
4185 }
4186
4187 // Stock
4188 $labeltoshowstock = '';
4189 $labeltoshowhtmlstock = '';
4190 if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
4191 if ($user->hasRight('stock', 'lire')) {
4192 $labeltoshowstock .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
4193
4194 if ($objp->stock > 0) {
4195 $labeltoshowhtmlstock .= ' - <span class="product_line_stock_ok">';
4196 } elseif ($objp->stock <= 0) {
4197 $labeltoshowhtmlstock .= ' - <span class="product_line_stock_too_low">';
4198 }
4199 $labeltoshowhtmlstock .= $langs->transnoentities("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
4200 $labeltoshowhtmlstock .= '</span>';
4201
4202 if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
4203 $langs->load("stocks");
4204
4205 $tmpproduct = new Product($this->db);
4206 $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
4207 $tmpproduct->load_virtual_stock();
4208 $virtualstock = $tmpproduct->stock_theorique;
4209
4210 $labeltoshowstock .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
4211
4212 $labeltoshowhtmlstock .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
4213 if ($virtualstock > 0) {
4214 $labeltoshowhtmlstock .= '<span class="product_line_stock_ok">';
4215 } elseif ($virtualstock <= 0) {
4216 $labeltoshowhtmlstock .= '<span class="product_line_stock_too_low">';
4217 }
4218 $labeltoshowhtmlstock .= $virtualstock;
4219 $labeltoshowhtmlstock .= '</span>';
4220
4221 unset($tmpproduct);
4222 }
4223 }
4224 }
4225
4226 // Price
4227 $found = 0;
4228 $labeltoshowprice = '';
4229 $labeltoshowhtmlprice = '';
4230 // If we need a particular price level (from 1 to n)
4231 if (empty($hidepriceinlabel) && $price_level >= 1 && (getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'))) {
4232 $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
4233 $sql .= " FROM " . $this->db->prefix() . "product_price";
4234 $sql .= " WHERE fk_product = " . ((int) $objp->rowid);
4235 $sql .= " AND entity IN (" . getEntity('productprice') . ")";
4236 $sql .= " AND price_level = " . ((int) $price_level);
4237 $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
4238 $sql .= " LIMIT 1";
4239
4240 dol_syslog(get_class($this) . '::constructProductListOption search price for product ' . $objp->rowid . ' AND level ' . $price_level, LOG_DEBUG);
4241 $result2 = $this->db->query($sql);
4242 if ($result2) {
4243 $objp2 = $this->db->fetch_object($result2);
4244 if ($objp2) {
4245 $found = 1;
4246 if ($objp2->price_base_type == 'HT') {
4247 $labeltoshowprice .= ' - ' . price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
4248 $labeltoshowhtmlprice .= ' - ' . price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
4249 } else {
4250 $labeltoshowprice .= ' - ' . price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
4251 $labeltoshowhtmlprice .= ' - ' . price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
4252 }
4253 $outprice_ht = price($objp2->price);
4254 $outprice_ttc = price($objp2->price_ttc);
4255 $outpricebasetype = $objp2->price_base_type;
4256 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
4257 $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
4258 $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
4259 } else {
4260 $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
4261 $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
4262 }
4263 }
4264 } else {
4265 dol_print_error($this->db);
4266 }
4267 }
4268
4269 // Price by quantity
4270 if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'))) {
4271 $found = 1;
4272 $outqty = $objp->quantity;
4273 $outdiscount = $objp->remise_percent;
4274 if ($objp->quantity == 1) {
4275 $labeltoshowprice .= ' - ' . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/";
4276 $labeltoshowhtmlprice .= ' - ' . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/";
4277 $labeltoshowprice .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
4278 $labeltoshowhtmlprice .= $langs->transnoentities("Unit");
4279 } else {
4280 $labeltoshowprice .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
4281 $labeltoshowhtmlprice .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
4282 $labeltoshowprice .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
4283 $labeltoshowhtmlprice .= $langs->transnoentities("Units");
4284 }
4285
4286 $outprice_ht = price($objp->unitprice);
4287 $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
4288 $outpricebasetype = $objp->price_base_type;
4289 $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
4290 $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
4291 }
4292 if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
4293 $labeltoshowprice .= " (" . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
4294 $labeltoshowhtmlprice .= " (" . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
4295 }
4296 if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
4297 $labeltoshowprice .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
4298 $labeltoshowhtmlprice .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
4299 }
4300
4301 // Price by customer
4302 if (empty($hidepriceinlabel) && (getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'))) {
4303 if (!empty($objp->idprodcustprice)) {
4304 $found = 1;
4305
4306 if ($objp->custprice_base_type == 'HT') {
4307 $labeltoshowprice .= ' - ' . price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
4308 $labeltoshowhtmlprice .= ' - ' . price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
4309 } else {
4310 $labeltoshowprice .= ' - ' . price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
4311 $labeltoshowhtmlprice .= ' - ' . price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
4312 }
4313
4314 $outprice_ht = price($objp->custprice);
4315 $outprice_ttc = price($objp->custprice_ttc);
4316 $outpricebasetype = $objp->custprice_base_type;
4317 $outtva_tx = $objp->custtva_tx;
4318 $outdefault_vat_code = $objp->custdefault_vat_code;
4319 $outdiscount = $objp->custdiscount_percent;
4320 }
4321 }
4322
4323 // If level no defined or multiprice not found, we used the default price
4324 if (empty($hidepriceinlabel) && !$found) {
4325 if ($objp->price_base_type == 'HT') {
4326 $labeltoshowprice .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
4327 $labeltoshowhtmlprice .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
4328 } else {
4329 $labeltoshowprice .= ' - ' . price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
4330 $labeltoshowhtmlprice .= ' - ' . price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
4331 }
4332 $outprice_ht = price($objp->price);
4333 $outprice_ttc = price($objp->price_ttc);
4334 $outpricebasetype = $objp->price_base_type;
4335 $outtva_tx = $objp->tva_tx;
4336 $outdefault_vat_code = $objp->default_vat_code;
4337 }
4338
4339 $optiontext = $labeltosearch.$outvalUnits.$labeltoshowprice.$labeltoshowstock;
4340 $optionhtml = $labeltoshowhtml.$outvalUnits.$labeltoshowhtmlprice.$labeltoshowhtmlstock;
4341 $optionhtmlforattribute = dol_escape_htmltag($optionhtml, 0, 0, '', 0, 1);
4342
4343 // Build options
4344 $opt = '<option value="' . $objp->rowid . '"';
4345 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
4346 if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
4347 $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 . '"';
4348 }
4349 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
4350 $opt .= ' data-labeltrans="' . dol_escape_htmltag($outlabel_translated, 0, 0, '', 0, 1) . '"';
4351 $opt .= ' data-desctrans="' . dol_escape_htmltag($outdesc_translated) . '"';
4352 }
4353
4354 if ($stocktag == 1) {
4355 $opt .= ' class="product_line_stock_ok" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml, 0, array('strong')).dolPrintHTMLForAttribute($outvalUnits).$labeltoshowhtmlprice.dolPrintHTMLForAttribute($labeltoshowhtmlstock).'"';
4356 //$opt .= ' class="product_line_stock_ok"';
4357 }
4358 if ($stocktag == -1) {
4359 $opt .= ' class="product_line_stock_too_low" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml, 0, array('strong')).dolPrintHTMLForAttribute($outvalUnits).$labeltoshowhtmlprice.dolPrintHTMLForAttribute($labeltoshowhtmlstock).'"';
4360 //$opt .= ' class="product_line_stock_too_low"';
4361 }
4362 $opt .= ' data-html="'.$optionhtmlforattribute.'" data-select-html="'.$optionhtmlforattribute.'"';
4363
4364 $opt .= '>';
4365
4366 // Ref, barcode, country
4367 $opt .= dol_escape_htmltag($optiontext, 0, 0, '', 0, 1);
4368 $outval .= $labeltoshowhtml;
4369
4370 // Units
4371 $outval .= $outvalUnits;
4372
4373 // Price
4374 $outval .= $labeltoshowhtmlprice;
4375
4376 // Stock
4377 $outval .= $labeltoshowhtmlstock;
4378
4379
4380 $parameters = array('objp' => $objp);
4381 $reshook = $hookmanager->executeHooks('constructProductListOption', $parameters); // Note that $action and $object may have been modified by hook
4382 if (empty($reshook)) {
4383 $opt .= $hookmanager->resPrint;
4384 } else {
4385 $opt = $hookmanager->resPrint;
4386 }
4387
4388 $opt .= "</option>\n";
4389 $optJson = array(
4390 'key' => $outkey,
4391 'value' => $outref,
4392 'label' => $outval,
4393 'label2' => $outlabel,
4394 'desc' => $outdesc,
4395 'type' => $outtype,
4396 'price_ht' => price2num($outprice_ht),
4397 'price_ttc' => price2num($outprice_ttc),
4398 'price_ht_locale' => price(price2num($outprice_ht)),
4399 'price_ttc_locale' => price(price2num($outprice_ttc)),
4400 'pricebasetype' => $outpricebasetype,
4401 'tva_tx' => $outtva_tx,
4402 'default_vat_code' => $outdefault_vat_code,
4403 'qty' => $outqty,
4404 'discount' => $outdiscount,
4405 'duration_value' => $outdurationvalue,
4406 'duration_unit' => $outdurationunit,
4407 'pbq' => $outpbq,
4408 'labeltrans' => $outlabel_translated,
4409 'desctrans' => $outdesc_translated,
4410 'ref_customer' => $outrefcust
4411 );
4412 }
4413
4414 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4415
4432 public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $notused = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '', $nooutput = 0)
4433 {
4434 // phpcs:enable
4435 global $langs, $conf;
4436 global $price_level, $status, $finished;
4437
4438 if (!isset($status)) {
4439 $status = 1;
4440 }
4441
4442 $selected_input_value = '';
4443 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
4444 if ((int) $selected > 0) {
4445 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
4446 $producttmpselect = new Product($this->db);
4447 $producttmpselect->fetch((int) $selected);
4448 $selected_input_value = $producttmpselect->ref;
4449 unset($producttmpselect);
4450 } elseif (preg_match('/^idprod_([0-9]+)$/', (string) $selected, $regtmpsel)) {
4451 // Preselect when a product without supplier price was just created ('idprod_ID' value, used by backtopage of creation popup)
4452 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
4453 $producttmpselect = new Product($this->db);
4454 $producttmpselect->fetch((int) $regtmpsel[1]);
4455 $selected_input_value = $producttmpselect->ref;
4456 unset($producttmpselect);
4457 }
4458
4459 // mode=2 means suppliers products
4460 $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=2&status=' . $status . '&finished=' . $finished . '&alsoproductwithnosupplierprice=' . $alsoproductwithnosupplierprice;
4461
4462 $s = ($hidelabel ? '' : $langs->trans("RefOrLabel") . ' : ') . '<input type="text" class="'.$morecss.'" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . $placeholder . '"' : '') . '>';
4463
4464 $s .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, getDolGlobalInt('PRODUIT_USE_SEARCH_TO_SELECT'), 0, $ajaxoptions);
4465 } else {
4466 $s = $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $notused, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, getDolGlobalInt('SUPPLIER_SHOW_STOCK_IN_PRODUCTS_COMBO'), $placeholder);
4467 }
4468
4469 if ($nooutput) {
4470 return $s;
4471 } else {
4472 print $s;
4473 }
4474 }
4475
4476 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4477
4496 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 = '')
4497 {
4498 // phpcs:enable
4499 global $langs, $conf, $user;
4500 global $hookmanager;
4501
4502 $out = '';
4503 $outarray = array();
4504
4505 $maxlengtharticle = getDolGlobalInt('PRODUCT_MAX_LENGTH_COMBO', 48);
4506
4507 $langs->load('stocks');
4508 // Units
4509 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4510 $langs->load('other');
4511 }
4512
4513 $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,";
4514 $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice, pfp.barcode";
4515 $sql .= ", pfp.multicurrency_code, pfp.multicurrency_unitprice";
4516 $sql .= ", pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name";
4517 $sql .= ", pfp.supplier_reputation";
4518 // if we use supplier description of the products
4519 if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
4520 $sql .= ", pfp.desc_fourn as description";
4521 } else {
4522 $sql .= ", p.description";
4523 }
4524 // Units
4525 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4526 $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";
4527 }
4528
4529 // Add select from hooks
4530 $parameters = [];
4531 $reshook = $hookmanager->executeHooks('selectSuppliersProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
4532 $sql .= $hookmanager->resPrint;
4533
4534 $sql .= " FROM " . $this->db->prefix() . "product as p";
4535
4536 // Add join from hooks
4537 $parameters = [];
4538 $reshook = $hookmanager->executeHooks('selectSuppliersProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
4539 $sql .= $hookmanager->resPrint;
4540
4541 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (" . getEntity('product') . ") )";
4542 if ($socid > 0) {
4543 $sql .= " AND pfp.fk_soc = " . ((int) $socid);
4544 }
4545 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
4546 // Units
4547 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4548 $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
4549 }
4550 $sql .= " WHERE p.entity IN (" . getEntity('product') . ")";
4551 if ($statut != -1) {
4552 $sql .= " AND p.tobuy = " . ((int) $statut);
4553 }
4554 if (strval($filtertype) != '') {
4555 $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
4556 }
4557
4558 // Add where from hooks
4559 $parameters = array();
4560 $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
4561 $sql .= $hookmanager->resPrint;
4562 // Add criteria on ref/label
4563 if ($filterkey != '') {
4564 $sql .= ' AND (';
4565 $prefix = getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
4566 // For natural search
4567 $search_crit = explode(' ', $filterkey);
4568 $i = 0;
4569 if (count($search_crit) > 1) {
4570 $sql .= "(";
4571 }
4572 foreach ($search_crit as $crit) {
4573 if ($i > 0) {
4574 $sql .= " AND ";
4575 }
4576 $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) . "%'";
4577 if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
4578 $sql .= " OR pfp.desc_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
4579 }
4580 $sql .= ")";
4581 $i++;
4582 }
4583 if (count($search_crit) > 1) {
4584 $sql .= ")";
4585 }
4586 if (isModEnabled('barcode')) {
4587 $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
4588 $sql .= " OR pfp.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
4589 }
4590 $sql .= ')';
4591 }
4592 $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
4593 $sql .= $this->db->plimit($limit, 0);
4594
4595 // Build output string
4596
4597 dol_syslog(get_class($this) . "::select_produits_fournisseurs_list", LOG_DEBUG);
4598 $result = $this->db->query($sql);
4599 if ($result) {
4600 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
4601 require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
4602
4603 $num = $this->db->num_rows($result);
4604
4605 //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
4606 $out .= '<select class="flat ' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '">';
4607 if (!$selected) {
4608 $out .= '<option value="-1" selected>' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
4609 } else {
4610 $out .= '<option value="-1">' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
4611 }
4612
4613 $i = 0;
4614 while ($i < $num) {
4615 $objp = $this->db->fetch_object($result);
4616
4617 if (is_null($objp->idprodfournprice)) {
4618 // There is no supplier price found, we will use the vat rate for sale
4619 $objp->tva_tx = $objp->tva_tx_sale;
4620 $objp->default_vat_code = $objp->default_vat_code_sale;
4621 }
4622
4623 $outkey = $objp->idprodfournprice; // id in table of price
4624 if (!$outkey && $alsoproductwithnosupplierprice) {
4625 $outkey = 'idprod_' . $objp->rowid; // id of product
4626 }
4627
4628 $outref = $objp->ref;
4629 $outbarcode = $objp->barcode;
4630 $outqty = 1;
4631 $outdiscount = 0;
4632 $outtype = $objp->fk_product_type;
4633 $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
4634 $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
4635
4636 // Units
4637 $outvalUnits = '';
4638 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4639 if (!empty($objp->unit_short)) {
4640 $outvalUnits .= ' - ' . $objp->unit_short;
4641 }
4642 if (!empty($objp->weight) && $objp->weight_units !== null) {
4643 $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
4644 $outvalUnits .= ' - ' . $unitToShow;
4645 }
4646 if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
4647 $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
4648 $outvalUnits .= ' - ' . $unitToShow;
4649 }
4650 if (!empty($objp->surface) && $objp->surface_units !== null) {
4651 $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
4652 $outvalUnits .= ' - ' . $unitToShow;
4653 }
4654 if (!empty($objp->volume) && $objp->volume_units !== null) {
4655 $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
4656 $outvalUnits .= ' - ' . $unitToShow;
4657 }
4658 if ($outdurationvalue && $outdurationunit) {
4659 $da = array(
4660 'h' => $langs->trans('Hour'),
4661 'd' => $langs->trans('Day'),
4662 'w' => $langs->trans('Week'),
4663 'm' => $langs->trans('Month'),
4664 'y' => $langs->trans('Year')
4665 );
4666 if (isset($da[$outdurationunit])) {
4667 $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
4668 }
4669 }
4670 }
4671
4672 $objRef = $objp->ref;
4673 if ($filterkey && $filterkey != '') {
4674 $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
4675 }
4676 $objRefFourn = $objp->ref_fourn;
4677 if ($filterkey && $filterkey != '') {
4678 $objRefFourn = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRefFourn, 1);
4679 }
4680 $label = $objp->label;
4681 if ($filterkey && $filterkey != '') {
4682 $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
4683 }
4684
4685 switch ($objp->fk_product_type) {
4687 $picto = 'product';
4688 break;
4690 $picto = 'service';
4691 break;
4692 default:
4693 $picto = '';
4694 break;
4695 }
4696
4697 if (empty($picto)) {
4698 $optlabel = '';
4699 } else {
4700 $optlabel = img_object('', $picto, 'class="paddingright classfortooltip"', 0, 0, 1);
4701 }
4702
4703 $optlabel .= $objp->ref;
4704 if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
4705 $optlabel .= ' <span class="opacitymedium">(' . $objp->ref_fourn . ')</span>';
4706 }
4707 if (isModEnabled('barcode') && !empty($objp->barcode)) {
4708 $optlabel .= ' (' . $outbarcode . ')';
4709 }
4710 $optlabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
4711
4712 $outvallabel = $objRef;
4713 if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
4714 $outvallabel .= ' (' . $objRefFourn . ')';
4715 }
4716 if (isModEnabled('barcode') && !empty($objp->barcode)) {
4717 $outvallabel .= ' (' . $outbarcode . ')';
4718 }
4719 $outvallabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
4720
4721 $outsearchlabel = implode(' ', array_filter(array(
4722 (string) $objp->ref,
4723 (string) $objp->ref_fourn,
4724 (string) $objp->barcode,
4725 (string) $objp->label,
4726 dol_string_nohtmltag((string) $objp->description)
4727 ), function (string $value): bool {
4728 return $value !== '';
4729 }));
4730
4731 // Units
4732 $optlabel .= $outvalUnits;
4733 $outvallabel .= $outvalUnits;
4734
4735 if (!empty($objp->idprodfournprice)) {
4736 $outqty = $objp->quantity;
4737 $outdiscount = $objp->remise_percent;
4738 if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
4739 $prod_supplier = new ProductFournisseur($this->db);
4740 $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
4741 $prod_supplier->id = $objp->fk_product;
4742 $prod_supplier->fourn_qty = $objp->quantity;
4743 $prod_supplier->fourn_tva_tx = $objp->tva_tx;
4744 $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
4745
4746 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
4747 $priceparser = new PriceParser($this->db);
4748 $price_result = $priceparser->parseProductSupplier($prod_supplier);
4749 if ($price_result >= 0) {
4750 $objp->fprice = $price_result;
4751 if ($objp->quantity >= 1) {
4752 $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
4753 }
4754 }
4755 }
4756 if ($objp->quantity == 1) {
4757 $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
4758 $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/";
4759 $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
4760 $outvallabel .= $langs->transnoentities("Unit");
4761 } else {
4762 $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
4763 $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
4764 $optlabel .= ' ' . $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
4765 $outvallabel .= ' ' . $langs->transnoentities("Units");
4766 }
4767
4768 if ($objp->quantity != 1) {
4769 $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
4770 $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
4771 }
4772 if ($objp->remise_percent >= 1) {
4773 $optlabel .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
4774 $outvallabel .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
4775 }
4776 if ($objp->duration) {
4777 $optlabel .= " - " . $objp->duration;
4778 $outvallabel .= " - " . $objp->duration;
4779 }
4780 if (!$socid) {
4781 $optlabel .= " - " . dol_trunc($objp->name, 8);
4782 $outvallabel .= " - " . dol_trunc($objp->name, 8);
4783 }
4784 if ($objp->supplier_reputation) {
4785 //TODO dictionary
4786 $reputations = array('' => $langs->trans('Standard'), 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
4787
4788 $optlabel .= " - " . $reputations[$objp->supplier_reputation];
4789 $outvallabel .= " - " . $reputations[$objp->supplier_reputation];
4790 }
4791 } else {
4792 $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
4793 $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
4794 }
4795
4796 if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
4797 $novirtualstock = ($showstockinlist == 2);
4798
4799 if ($user->hasRight('stock', 'lire')) {
4800 $outvallabel .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
4801
4802 if ($objp->stock > 0) {
4803 $optlabel .= ' - <span class="product_line_stock_ok">';
4804 } elseif ($objp->stock <= 0) {
4805 $optlabel .= ' - <span class="product_line_stock_too_low">';
4806 }
4807 $optlabel .= $langs->transnoentities("Stock") . ':' . price(price2num($objp->stock, 'MS'));
4808 $optlabel .= '</span>';
4809 if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
4810 $langs->load("stocks");
4811
4812 $tmpproduct = new Product($this->db);
4813 $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
4814 $tmpproduct->load_virtual_stock();
4815 $virtualstock = $tmpproduct->stock_theorique;
4816
4817 $outvallabel .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
4818
4819 $optlabel .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
4820 if ($virtualstock > 0) {
4821 $optlabel .= '<span class="product_line_stock_ok">';
4822 } elseif ($virtualstock <= 0) {
4823 $optlabel .= '<span class="product_line_stock_too_low">';
4824 }
4825 $optlabel .= $virtualstock;
4826 $optlabel .= '</span>';
4827
4828 unset($tmpproduct);
4829 }
4830 }
4831 }
4832
4833 $optstart = '<option value="' . $outkey . '"';
4834 if ($selected && preg_match('/^idprod_/', (string) $selected) && (string) $selected == 'idprod_'.$objp->rowid) {
4835 $optstart .= ' selected';
4836 } elseif ($selected && (string) $selected == (string) $objp->idprodfournprice) {
4837 $optstart .= ' selected';
4838 }
4839
4840 if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
4841 $optstart .= ' disabled';
4842 }
4843
4844 if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
4845 $optstart .= ' data-product-id="' . dol_escape_htmltag($objp->rowid) . '"';
4846 $optstart .= ' data-price-id="' . dol_escape_htmltag($objp->idprodfournprice) . '"';
4847 $optstart .= ' data-qty="' . dol_escape_htmltag($objp->quantity) . '"';
4848 $optstart .= ' data-up="' . dol_escape_htmltag(price2num($objp->unitprice)) . '"'; // the price with numeric international format
4849 $optstart .= ' data-up-locale="' . dol_escape_htmltag(price($objp->unitprice)) . '"'; // the price formatted in user language
4850 $optstart .= ' data-discount="' . dol_escape_htmltag((string) $outdiscount) . '"';
4851 $optstart .= ' data-tvatx="' . dol_escape_htmltag(price2num($objp->tva_tx)) . '"'; // the rate with numeric international format
4852 $optstart .= ' data-tvatx-formated="' . dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)) . '"'; // the rate formatted in user language
4853 $optstart .= ' data-default-vat-code="' . dol_escape_htmltag($objp->default_vat_code) . '"';
4854 $optstart .= ' data-supplier-ref="' . dol_escape_htmltag($objp->ref_fourn) . '"';
4855 if (isModEnabled('multicurrency')) {
4856 $optstart .= ' data-multicurrency-code="' . dol_escape_htmltag($objp->multicurrency_code) . '"';
4857 $optstart .= ' data-multicurrency-unitprice="' . dol_escape_htmltag(price2num($objp->multicurrency_unitprice)) . '"'; // the price with numeric international format
4858 }
4859 }
4860 $optstart .= ' data-description="' . dol_escape_htmltag($objp->description, 0, 1) . '"';
4861 $optstart .= ' data-search="' . dol_escape_htmltag($outsearchlabel) . '"';
4862
4863 // set $parameters to call hook
4864 $outarrayentry = array(
4865 'key' => $outkey,
4866 'value' => $outref,
4867 'label' => $outvallabel,
4868 'labelhtml' => $optlabel,
4869 'qty' => $outqty,
4870 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
4871 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
4872 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
4873 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
4874 'tva_tx' => price2num($objp->tva_tx),
4875 'default_vat_code' => $objp->default_vat_code,
4876 'supplier_ref' => $objp->ref_fourn,
4877 'discount' => $outdiscount,
4878 'type' => $outtype,
4879 'duration_value' => $outdurationvalue,
4880 'duration_unit' => $outdurationunit,
4881 'disabled' => empty($objp->idprodfournprice),
4882 'description' => $objp->description
4883 );
4884 if (isModEnabled('multicurrency')) {
4885 $outarrayentry['multicurrency_code'] = $objp->multicurrency_code;
4886 $outarrayentry['multicurrency_unitprice'] = price2num($objp->multicurrency_unitprice, 'MU');
4887 }
4888 $parameters = array(
4889 'objp' => &$objp,
4890 'optstart' => &$optstart,
4891 'optlabel' => &$optlabel,
4892 'outvallabel' => &$outvallabel,
4893 'outarrayentry' => &$outarrayentry,
4894 'fk_soc' => $socid
4895 );
4896 $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
4897
4898
4899 // Add new entry
4900 // "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
4901 // "label" value of json key array is used by jQuery automatically as text for combo box
4902 $out .= $optstart . ' data-html="' . dol_escape_htmltag($optlabel) . '">' . $optlabel . "</option>\n";
4903 $outarraypush = array(
4904 'key' => $outkey,
4905 'value' => $outref,
4906 'label' => $outvallabel,
4907 'labelhtml' => $optlabel,
4908 'qty' => $outqty,
4909 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
4910 'price_qty_ht_locale' => price($objp->fprice),
4911 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
4912 'price_unit_ht_locale' => price($objp->unitprice),
4913 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
4914 'tva_tx_formated' => price($objp->tva_tx),
4915 'tva_tx' => price2num($objp->tva_tx),
4916 'default_vat_code' => $objp->default_vat_code,
4917 'supplier_ref' => $objp->ref_fourn,
4918 'discount' => $outdiscount,
4919 'type' => $outtype,
4920 'duration_value' => $outdurationvalue,
4921 'duration_unit' => $outdurationunit,
4922 'disabled' => empty($objp->idprodfournprice),
4923 'description' => $objp->description
4924 );
4925 if (isModEnabled('multicurrency')) {
4926 $outarraypush['multicurrency_code'] = $objp->multicurrency_code;
4927 $outarraypush['multicurrency_unitprice'] = price2num($objp->multicurrency_unitprice, 'MU');
4928 }
4929 array_push($outarray, $outarraypush);
4930
4931 // Example of var_dump $outarray
4932 // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
4933 // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/unit (20,00 Euros/unit)"
4934 // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
4935 //}
4936 //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
4937 //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unit (20,00 Euros/unit)');
4938 //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
4939
4940 $i++;
4941 }
4942 $out .= '</select>';
4943
4944 $this->db->free($result);
4945
4946 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4947 $out .= ajax_combobox($htmlname);
4948 } else {
4949 dol_print_error($this->db);
4950 }
4951
4952 if (empty($outputmode)) {
4953 return $out;
4954 }
4955 return $outarray;
4956 }
4957
4958 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4959
4968 public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = 0)
4969 {
4970 // phpcs:enable
4971 global $langs, $conf;
4972
4973 $langs->load('stocks');
4974
4975 $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
4976 $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
4977 $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
4978 $sql .= " FROM " . $this->db->prefix() . "product as p";
4979 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
4980 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
4981 $sql .= " WHERE pfp.entity IN (" . getEntity('productsupplierprice') . ")";
4982 $sql .= " AND p.tobuy = 1";
4983 $sql .= " AND s.fournisseur = 1";
4984 $sql .= " AND p.rowid = " . ((int) $productid);
4985 if (!getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED')) {
4986 $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
4987 } else {
4988 $sql .= " ORDER BY pfp.unitprice - pfp.unitprice * pfp.remise_percent / 100 ASC";
4989 }
4990
4991 dol_syslog(get_class($this) . "::select_product_fourn_price", LOG_DEBUG);
4992 $result = $this->db->query($sql);
4993
4994 if ($result) {
4995 $num = $this->db->num_rows($result);
4996
4997 $form = '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
4998
4999 if (!$num) {
5000 $form .= '<option value="0">-- ' . $langs->trans("NoSupplierPriceDefinedForThisProduct") . ' --</option>';
5001 } else {
5002 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
5003 $form .= '<option value="0">&nbsp;</option>';
5004
5005 $i = 0;
5006 while ($i < $num) {
5007 $objp = $this->db->fetch_object($result);
5008
5009 $opt = '<option value="' . $objp->idprodfournprice . '"';
5010 //if there is only one supplier, preselect it
5011 if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED'))) {
5012 $opt .= ' selected';
5013 }
5014 $opt .= '>' . $objp->name . ' - ' . $objp->ref_fourn . ' - ';
5015
5016 if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
5017 $prod_supplier = new ProductFournisseur($this->db);
5018 $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
5019 $prod_supplier->id = $productid;
5020 $prod_supplier->fourn_qty = $objp->quantity;
5021 $prod_supplier->fourn_tva_tx = $objp->tva_tx;
5022 $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
5023
5024 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
5025 $priceparser = new PriceParser($this->db);
5026 $price_result = $priceparser->parseProductSupplier($prod_supplier);
5027 if ($price_result >= 0) {
5028 $objp->fprice = $price_result;
5029 if ($objp->quantity >= 1) {
5030 $objp->unitprice = $objp->fprice / $objp->quantity;
5031 }
5032 }
5033 }
5034 if ($objp->quantity == 1) {
5035 $opt .= price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
5036 }
5037
5038 $opt .= $objp->quantity . ' ';
5039
5040 if ($objp->quantity == 1) {
5041 $opt .= $langs->trans("Unit");
5042 } else {
5043 $opt .= $langs->trans("Units");
5044 }
5045 if ($objp->quantity > 1) {
5046 $opt .= " - ";
5047 $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");
5048 }
5049 if ($objp->duration) {
5050 $opt .= " - " . $objp->duration;
5051 }
5052 $opt .= "</option>\n";
5053
5054 $form .= $opt;
5055 $i++;
5056 }
5057 }
5058
5059 $form .= '</select>';
5060 $this->db->free($result);
5061 return $form;
5062 } else {
5063 dol_print_error($this->db);
5064 return '';
5065 }
5066 }
5067
5068
5069 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5076 {
5077 // phpcs:enable
5078 global $langs, $hookmanager;
5079
5080 $num = count($this->cache_conditions_paiements);
5081 if ($num > 0) {
5082 return 0; // Cache already loaded
5083 }
5084
5085 dol_syslog(__METHOD__, LOG_DEBUG);
5086
5087 $this->cache_conditions_paiements = array();
5088
5089 $sql = "SELECT rowid, code, libelle as label, deposit_percent, entity";
5090 $sql .= " FROM " . $this->db->prefix() . 'c_payment_term';
5091 $sql .= " WHERE entity IN (" . getEntity('c_payment_term') . ")";
5092 $sql .= " AND active > 0";
5093 $sql .= " ORDER BY sortorder";
5094
5095 $resql = $this->db->query($sql);
5096 if ($resql) {
5097 $num = $this->db->num_rows($resql);
5098 $i = 0;
5099 while ($i < $num) {
5100 $obj = $this->db->fetch_object($resql);
5101
5102 // If a translation exists, we use it, otherwise, we take the label by default
5103 $label = ($langs->trans("PaymentConditionShort" . $obj->code) != "PaymentConditionShort" . $obj->code ? $langs->trans("PaymentConditionShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
5104
5105 $this->cache_conditions_paiements[$obj->rowid]['code'] = (string) $obj->code;
5106 $this->cache_conditions_paiements[$obj->rowid]['label'] = (string) $label;
5107 $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = (string) $obj->deposit_percent;
5108 $this->cache_conditions_paiements[$obj->rowid]['entity'] = (int) $obj->entity;
5109
5110 $i++;
5111 }
5112
5113 $parameters = array('context' => 'paymentterm');
5114 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
5115 if (empty($reshook)) {
5116 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
5117 $this->cache_conditions_paiements = array_merge($this->cache_conditions_paiements, $hookmanager->resArray);
5118 }
5119 } else {
5120 $this->cache_conditions_paiements = $hookmanager->resArray;
5121 }
5122
5123 //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
5124
5125 return $num;
5126 } else {
5127 dol_print_error($this->db);
5128 return -1;
5129 }
5130 }
5131
5132 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5133
5140 {
5141 // phpcs:enable
5142 $factureRec = new FactureRec($this->db);
5143
5144 $this->cache_rule_for_lines_dates = $factureRec->fields['rule_for_lines_dates']['arrayofkeyval'];
5145
5146 if (empty($this->cache_rule_for_lines_dates)) {
5147 return -1;
5148 }
5149
5150 return 1;
5151 }
5152
5153 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5154
5160 public function load_cache_availability()
5161 {
5162 // phpcs:enable
5163 global $langs;
5164
5165 $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
5166 if ($num > 0) {
5167 return 0; // Cache already loaded
5168 }
5169
5170 dol_syslog(__METHOD__, LOG_DEBUG);
5171
5172 $this->cache_availability = array();
5173
5174 $langs->load('propal');
5175
5176 $sql = "SELECT rowid, code, label, position";
5177 $sql .= " FROM " . $this->db->prefix() . 'c_availability';
5178 $sql .= " WHERE active > 0";
5179
5180 $resql = $this->db->query($sql);
5181 if ($resql) {
5182 $num = $this->db->num_rows($resql);
5183 $i = 0;
5184 while ($i < $num) {
5185 $obj = $this->db->fetch_object($resql);
5186
5187 // If a translation exists, we use is, otherwise, we take the label by default
5188 $label = ($langs->trans("AvailabilityType" . $obj->code) != "AvailabilityType" . $obj->code ? $langs->trans("AvailabilityType" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
5189 $this->cache_availability[$obj->rowid]['code'] = (string) $obj->code;
5190 $this->cache_availability[$obj->rowid]['label'] = (string) $label;
5191 $this->cache_availability[$obj->rowid]['position'] = (int) $obj->position;
5192 $i++;
5193 }
5194
5195 // @phan-suppress-next-line PhanTypeMismatchProperty PhanTypeMismatchDimFetch
5196 $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
5197
5198 return $num;
5199 } else {
5200 dol_print_error($this->db);
5201 return -1;
5202 }
5203 }
5204
5216 public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '', $noouput = 0)
5217 {
5218 global $langs, $user;
5219
5220 $this->load_cache_availability();
5221
5222 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
5223
5224 $out = '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
5225 if ($addempty) {
5226 $out .= '<option value="-1">'.(is_numeric($addempty) ? '&nbsp;' : $langs->trans($addempty)).'</option>';
5227 }
5228 foreach ($this->cache_availability as $id => $arrayavailability) {
5229 if ($selected == $id) {
5230 $out .= '<option value="' . $id . '" selected>';
5231 } else {
5232 $out .= '<option value="' . $id . '">';
5233 }
5234 $out .= dol_escape_htmltag($arrayavailability['label']);
5235 $out .= '</option>';
5236 }
5237 $out .= '</select>';
5238 if ($user->admin) {
5239 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5240 }
5241 $out .= ajax_combobox($htmlname);
5242
5243 if ($noouput) {
5244 return $out;
5245 } else {
5246 print $out;
5247 return '';
5248 }
5249 }
5250
5256 public function loadCacheInputReason()
5257 {
5258 global $langs;
5259
5260 $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
5261 if ($num > 0) {
5262 return 0; // Cache already loaded
5263 }
5264
5265 $sql = "SELECT rowid, code, label";
5266 $sql .= " FROM " . $this->db->prefix() . 'c_input_reason';
5267 $sql .= " WHERE active > 0";
5268
5269 $resql = $this->db->query($sql);
5270 if ($resql) {
5271 $num = $this->db->num_rows($resql);
5272 $i = 0;
5274 $tmparray = array();
5275 while ($i < $num) {
5276 $obj = $this->db->fetch_object($resql);
5277
5278 // If a translation exists, we use is, otherwise, we take the label by default
5279 $label = ($obj->label != '-' ? (string) $obj->label : '');
5280 if ($langs->trans("DemandReasonType" . $obj->code) != "DemandReasonType" . $obj->code) {
5281 $label = $langs->trans("DemandReasonType" . $obj->code); // So translation key DemandReasonTypeSRC_XXX will work
5282 }
5283 if ($langs->trans($obj->code) != $obj->code) {
5284 $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
5285 }
5286
5287 $tmparray[(int) $obj->rowid]
5288 = array(
5289 'id' => (int) $obj->rowid,
5290 'code' => (string) $obj->code,
5291 'label' => $label,
5292 );
5293 $i++;
5294 }
5295
5296 $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
5297
5298 unset($tmparray);
5299 return $num;
5300 } else {
5301 dol_print_error($this->db);
5302 return -1;
5303 }
5304 }
5305
5318 public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
5319 {
5320 global $langs, $user;
5321
5322 $this->loadCacheInputReason();
5323
5324 print '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="select_' . $htmlname . '" name="' . $htmlname . '">';
5325 if ($addempty) {
5326 print '<option value="0"' . (empty($selected) ? ' selected' : '') . '>&nbsp;</option>';
5327 }
5328 foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
5329 if ($arraydemandreason['code'] == $exclude) {
5330 continue;
5331 }
5332
5333 if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
5334 print '<option value="' . $arraydemandreason['id'] . '" selected>';
5335 } else {
5336 print '<option value="' . $arraydemandreason['id'] . '">';
5337 }
5338 $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
5339 print $langs->trans($label);
5340 print '</option>';
5341 }
5342 print '</select>';
5343 if ($user->admin && empty($notooltip)) {
5344 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5345 }
5346 print ajax_combobox('select_' . $htmlname);
5347 }
5348
5349 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5350
5357 {
5358 // phpcs:enable
5359 global $langs, $hookmanager;
5360
5361 $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
5362 if ($num > 0) {
5363 return $num; // Cache already loaded
5364 }
5365
5366 dol_syslog(__METHOD__, LOG_DEBUG);
5367
5368 $this->cache_types_paiements = array();
5369
5370 $sql = "SELECT id, code, libelle as label, type, entity, active";
5371 $sql .= " FROM " . $this->db->prefix() . "c_paiement";
5372 $sql .= " WHERE entity IN (" . getEntity('c_paiement') . ")";
5373
5374 $resql = $this->db->query($sql);
5375 if ($resql) {
5376 $num = $this->db->num_rows($resql);
5377 $i = 0;
5378 while ($i < $num) {
5379 $obj = $this->db->fetch_object($resql);
5380
5381 // If a translation exists, we use is, otherwise, we take the label by default
5382 $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
5383 $this->cache_types_paiements[(int) $obj->id]['id'] = (int) $obj->id;
5384 $this->cache_types_paiements[(int) $obj->id]['code'] = (string) $obj->code;
5385 $this->cache_types_paiements[(int) $obj->id]['label'] = (string) $label;
5386 $this->cache_types_paiements[(int) $obj->id]['type'] = (int) $obj->type;
5387 $this->cache_types_paiements[(int) $obj->id]['entity'] = (int) $obj->entity;
5388 $this->cache_types_paiements[(int) $obj->id]['active'] = (int) $obj->active;
5389 $i++;
5390 }
5391
5392 $parameters = array('context' => 'paymenttype');
5393 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
5394 if (empty($reshook)) {
5395 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
5396 $this->cache_types_paiements = array_merge($this->cache_types_paiements, $hookmanager->resArray);
5397 }
5398 } else {
5399 $this->cache_types_paiements = $hookmanager->resArray;
5400 }
5401
5402 $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
5403
5404 return $num;
5405 } else {
5406 dol_print_error($this->db);
5407 return -1;
5408 }
5409 }
5410
5411
5412 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5413
5432 public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1, $noprint = 0)
5433 {
5434 // phpcs:enable
5435 $out = $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
5436 if (empty($noprint)) {
5437 print $out;
5438 } else {
5439 return $out;
5440 }
5441 }
5442
5443
5460 public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
5461 {
5462 global $langs, $user;
5463
5464 $out = '';
5465 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
5466
5468
5469 // Set default value if not already set by caller
5470 if (empty($selected) && strpos($htmlname, 'search_') !== 0 && getDolGlobalInt('MAIN_DEFAULT_PAYMENT_TERM_ID')) {
5471 dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TERM_ID", LOG_NOTICE);
5472 $selected = getDolGlobalInt('MAIN_DEFAULT_PAYMENT_TERM_ID');
5473 }
5474
5475 $out .= '<select id="' . $htmlname . '" class="flat selectpaymentterms' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
5476 if ($addempty) {
5477 $out .= '<option value="0">&nbsp;</option>';
5478 }
5479
5480 $selectedDepositPercent = null;
5481
5482 foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
5483 if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
5484 continue;
5485 }
5486
5487 if ($selected == $id) {
5488 $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
5489 $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
5490 } else {
5491 $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
5492 }
5493 $label = $arrayconditions['label'];
5494
5495 if (!empty($arrayconditions['deposit_percent'])) {
5496 $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
5497 }
5498
5499 $out .= $label;
5500 $out .= '</option>';
5501 }
5502 $out .= '</select>';
5503 if ($user->admin && empty($noinfoadmin)) {
5504 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5505 }
5506 $out .= ajax_combobox($htmlname);
5507
5508 if ($deposit_percent >= 0) {
5509 $out .= ' <span id="' . $htmlname . '_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
5510 $out .= $langs->trans('DepositPercent') . ' : ';
5511 $out .= '<input id="' . $htmlname . '_deposit_percent" name="' . $htmlname . '_deposit_percent" class="maxwidth50" value="' . $deposit_percent . '" />';
5512 $out .= '</span>';
5513 $out .= '
5514 <script nonce="' . getNonce() . '">
5515 $(document).ready(function () {
5516 $("#' . $htmlname . '").change(function () {
5517 let $selected = $(this).find("option:selected");
5518 let depositPercent = $selected.attr("data-deposit_percent");
5519
5520 if (depositPercent.length > 0) {
5521 $("#' . $htmlname . '_deposit_percent_container").show().find("#' . $htmlname . '_deposit_percent").val(depositPercent);
5522 } else {
5523 $("#' . $htmlname . '_deposit_percent_container").hide();
5524 }
5525
5526 return true;
5527 });
5528 });
5529 </script>';
5530 }
5531
5532 return $out;
5533 }
5534
5535
5544 public function getSelectRuleForLinesDates($selected = '', $htmlname = 'rule_for_lines_dates', $addempty = 0)
5545 {
5546 global $langs;
5547
5548 $out = '';
5549
5551
5552 $out .= '<select id="' . $htmlname . '" class="flat selectbillingterm" name="' . $htmlname . '">';
5553 if ($addempty) {
5554 $out .= '<option value="-1">&nbsp;</option>';
5555 }
5556
5557
5558 foreach ($this->cache_rule_for_lines_dates as $rule_for_lines_dates_key => $rule_for_lines_dates_name) {
5559 if ($selected == $rule_for_lines_dates_key) {
5560 $out .= '<option value="' . $rule_for_lines_dates_key . '" selected>';
5561 } else {
5562 $out .= '<option value="' . $rule_for_lines_dates_key . '">';
5563 }
5564
5565 $out .= $langs->trans($rule_for_lines_dates_name);
5566 $out .= '</option>';
5567 }
5568 $out .= '</select>';
5569
5570 $out .= ajax_combobox($htmlname);
5571
5572 return $out;
5573 }
5574
5575
5576 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5577
5594 public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
5595 {
5596 // phpcs:enable
5597 global $langs, $user;
5598
5599 $out = '';
5600
5601 dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
5602
5603 $filterarray = array();
5604 if ($filtertype == 'CRDT') {
5605 $filterarray = array(0, 2, 3);
5606 } elseif ($filtertype == 'DBIT') {
5607 $filterarray = array(1, 2, 3);
5608 } elseif ($filtertype != '' && $filtertype != '-1') {
5609 $filterarray = explode(',', $filtertype);
5610 }
5611
5613
5614 // Set default value if not already set by caller
5615 if (empty($selected) && strpos($htmlname, 'search_') !== 0 && getDolGlobalString('MAIN_DEFAULT_PAYMENT_TYPE_ID')) {
5616 dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TYPE_ID", LOG_NOTICE);
5617 $selected = getDolGlobalString('MAIN_DEFAULT_PAYMENT_TYPE_ID');
5618 }
5619
5620 $out .= '<select id="select' . $htmlname . '" class="flat selectpaymenttypes' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
5621 if ($empty) {
5622 $out .= '<option value="">&nbsp;</option>';
5623 }
5624 foreach ($this->cache_types_paiements as $id => $arraytypes) {
5625 // If not good status
5626 if ($active >= 0 && $arraytypes['active'] != $active) {
5627 continue;
5628 }
5629
5630 // We skip of the user requested to filter on specific payment methods
5631 if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
5632 continue;
5633 }
5634
5635 // We discard empty lines if showempty is on because an empty line has already been output.
5636 if ($empty && empty($arraytypes['code'])) {
5637 continue;
5638 }
5639
5640 if ($format == 0) {
5641 $out .= '<option value="' . $id . '" data-code="'.$arraytypes['code'].'"';
5642 } elseif ($format == 1) {
5643 $out .= '<option value="' . $arraytypes['code'] . '"';
5644 } elseif ($format == 2) {
5645 $out .= '<option value="' . $arraytypes['code'] . '"';
5646 } elseif ($format == 3) {
5647 $out .= '<option value="' . $id . '"';
5648 }
5649 // Print attribute selected or not
5650 if ($format == 1 || $format == 2) {
5651 if ($selected == $arraytypes['code']) {
5652 $out .= ' selected';
5653 }
5654 } else {
5655 if ($selected == $id) {
5656 $out .= ' selected';
5657 }
5658 }
5659 $out .= '>';
5660 $value = '';
5661 if ($format == 0) {
5662 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
5663 } elseif ($format == 1) {
5664 $value = $arraytypes['code'];
5665 } elseif ($format == 2) {
5666 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
5667 } elseif ($format == 3) {
5668 $value = $arraytypes['code'];
5669 }
5670 $out .= $value ? $value : '&nbsp;';
5671 $out .= '</option>';
5672 }
5673 $out .= '</select>';
5674 if ($user->admin && !$noadmininfo) {
5675 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5676 }
5677 $out .= ajax_combobox('select' . $htmlname);
5678
5679 if (empty($nooutput)) {
5680 print $out;
5681 } else {
5682 return $out;
5683 }
5684 }
5685
5686
5695 public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
5696 {
5697 global $langs;
5698
5699 $return = '<select class="flat maxwidth100" id="select_' . $htmlname . '" name="' . $htmlname . '">';
5700 $options = array(
5701 'HT' => $langs->trans("HT"),
5702 'TTC' => $langs->trans("TTC")
5703 );
5704 foreach ($options as $id => $value) {
5705 if ($selected == $id) {
5706 $return .= '<option value="' . $id . '" selected>' . $value;
5707 } else {
5708 $return .= '<option value="' . $id . '">' . $value;
5709 }
5710 $return .= '</option>';
5711 }
5712 $return .= '</select>';
5713 if ($addjscombo) {
5714 $return .= ajax_combobox('select_' . $htmlname);
5715 }
5716
5717 return $return;
5718 }
5719
5720 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5721
5728 {
5729 // phpcs:enable
5730 global $langs;
5731
5732 $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
5733 if ($num > 0) {
5734 return $num; // Cache already loaded
5735 }
5736
5737 dol_syslog(__METHOD__, LOG_DEBUG);
5738
5739 $this->cache_transport_mode = array();
5740
5741 $sql = "SELECT rowid, code, label, active";
5742 $sql .= " FROM " . $this->db->prefix() . "c_transport_mode";
5743 $sql .= " WHERE entity IN (" . getEntity('c_transport_mode') . ")";
5744
5745 $resql = $this->db->query($sql);
5746 if ($resql) {
5747 $num = $this->db->num_rows($resql);
5748 $i = 0;
5749 while ($i < $num) {
5750 $obj = $this->db->fetch_object($resql);
5751
5752 // If traduction exist, we use it else we take the default label
5753 $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
5754 $this->cache_transport_mode[(int) $obj->rowid]
5755 = array(
5756 'rowid' => (int) $obj->rowid,
5757 'code' => (string) $obj->code,
5758 'label' => (string) $label,
5759 'active' => (int) $obj->active,
5760 );
5761 $i++;
5762 }
5763
5764 $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
5765
5766 return $num;
5767 } else {
5768 dol_print_error($this->db);
5769 return -1;
5770 }
5771 }
5772
5786 public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
5787 {
5788 global $langs, $user;
5789
5790 dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $format, LOG_DEBUG);
5791
5793
5794 print '<select id="select' . $htmlname . '" class="flat selectmodetransport' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
5795 if ($empty) {
5796 print '<option value="">&nbsp;</option>';
5797 }
5798 foreach ($this->cache_transport_mode as $id => $arraytypes) {
5799 // If not good status
5800 if ($active >= 0 && $arraytypes['active'] != $active) {
5801 continue;
5802 }
5803
5804 // We discard empty line if showempty is on because an empty line has already been output.
5805 if ($empty && empty($arraytypes['code'])) {
5806 continue;
5807 }
5808
5809 if ($format == 0) {
5810 print '<option value="' . $id . '"';
5811 } elseif ($format == 1) {
5812 print '<option value="' . $arraytypes['code'] . '"';
5813 } elseif ($format == 2) {
5814 print '<option value="' . $arraytypes['code'] . '"';
5815 } elseif ($format == 3) {
5816 print '<option value="' . $id . '"';
5817 }
5818 // If text is selected, we compare with code, else with id
5819 if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
5820 print ' selected';
5821 } elseif ($selected == $id) {
5822 print ' selected';
5823 }
5824 print '>';
5825 $value = '';
5826 if ($format == 0) {
5827 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
5828 } elseif ($format == 1) {
5829 $value = $arraytypes['code'];
5830 } elseif ($format == 2) {
5831 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
5832 } elseif ($format == 3) {
5833 $value = $arraytypes['code'];
5834 }
5835 print $value ? $value : '&nbsp;';
5836 print '</option>';
5837 }
5838 print '</select>';
5839
5840 print ajax_combobox("select".$htmlname);
5841
5842 if ($user->admin && !$noadmininfo) {
5843 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5844 }
5845 }
5846
5859 public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
5860 {
5861 global $langs, $user;
5862
5863 $langs->loadLangs(array("admin", "sendings"));
5864
5865 $sql = "SELECT rowid, code, libelle as label";
5866 $sql .= " FROM " . $this->db->prefix() . "c_shipment_mode";
5867 $sql .= " WHERE active > 0";
5868 if ($filtre) {
5869 $sql .= forgeSQLFromUniversalSearchCriteria($filtre);
5870 }
5871 $sql .= " ORDER BY libelle ASC";
5872
5873 dol_syslog(get_class($this) . "::selectShippingMode", LOG_DEBUG);
5874
5875 $result = $this->db->query($sql);
5876 if ($result) {
5877 $num = $this->db->num_rows($result);
5878 $i = 0;
5879 if ($num) {
5880 print '<select id="select' . $htmlname . '" class="flat selectshippingmethod' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
5881 if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
5882 print '<option value="-1">&nbsp;</option>';
5883 }
5884 while ($i < $num) {
5885 $obj = $this->db->fetch_object($result);
5886 if ($selected == $obj->rowid) {
5887 print '<option value="' . $obj->rowid . '" selected>';
5888 } else {
5889 print '<option value="' . $obj->rowid . '">';
5890 }
5891 print ($langs->trans("SendingMethod" . strtoupper($obj->code)) != "SendingMethod" . strtoupper($obj->code)) ? $langs->trans("SendingMethod" . strtoupper($obj->code)) : $obj->label;
5892 print '</option>';
5893 $i++;
5894 }
5895 print "</select>";
5896 if ($user->admin && empty($noinfoadmin)) {
5897 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5898 }
5899
5900 print ajax_combobox('select' . $htmlname);
5901 } else {
5902 print $langs->trans("NoShippingMethodDefined");
5903 }
5904 } else {
5905 dol_print_error($this->db);
5906 }
5907 }
5908
5918 public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
5919 {
5920 global $langs;
5921
5922 $langs->load("sendings");
5923
5924 if ($htmlname != "none") {
5925 print '<form method="POST" action="' . $page . '">';
5926 print '<input type="hidden" name="action" value="setshippingmethod">';
5927 print '<input type="hidden" name="token" value="' . newToken() . '">';
5928 $this->selectShippingMethod($selected, $htmlname, '', $addempty);
5929 print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
5930 print '</form>';
5931 } else {
5932 if ($selected) {
5933 $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
5934 print $langs->trans("SendingMethod" . strtoupper($code));
5935 } else {
5936 print "&nbsp;";
5937 }
5938 }
5939 }
5940
5949 public function selectSituationInvoices($selected = '', $socid = 0)
5950 {
5951 global $langs;
5952
5953 $langs->load('bills');
5954
5955 $opt = '';
5956
5957 $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
5958 $sql .= ' FROM ' . $this->db->prefix() . 'facture';
5959 $sql .= ' WHERE entity IN (' . getEntity('invoice') . ')';
5960 $sql .= ' AND situation_counter >= 1';
5961 $sql .= ' AND fk_soc = ' . (int) $socid;
5962 $sql .= ' AND type <> 2';
5963 $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
5964 $resql = $this->db->query($sql);
5965
5966 $nbSituationInvoiceForThirdparty = 0;
5967
5968 if ($resql && $this->db->num_rows($resql) > 0) {
5969 // Last seen cycle
5970 $ref = 0;
5971 while ($obj = $this->db->fetch_object($resql)) {
5972 //Same cycle ?
5973 if ($obj->situation_cycle_ref != $ref) {
5974 // Just seen this cycle
5975 $ref = $obj->situation_cycle_ref;
5976 //not final ?
5977 if ($obj->situation_final != 1) {
5978 //Not prov?
5979 if (substr($obj->ref, 1, 4) != 'PROV') {
5980 $nbSituationInvoiceForThirdparty++;
5981
5982 if ($selected == $obj->rowid) {
5983 $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
5984 } else {
5985 $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
5986 }
5987 }
5988 }
5989 }
5990 }
5991 } else {
5992 dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
5993 }
5994
5995 if ($nbSituationInvoiceForThirdparty > 0) {
5996 $opt = '<option class="minwidth100" value="" selected>&nbsp;</option>'.$opt;
5997 } else {
5998 $opt = '<option class="minwidth100" value="-1" selected>'.$langs->trans('NoSituations').'</option>';
5999 }
6000
6001 return $opt;
6002 }
6003
6013 public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
6014 {
6015 global $langs;
6016
6017 $langs->load('products');
6018
6019 $return = '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
6020
6021 $sql = "SELECT rowid, label, code FROM " . $this->db->prefix() . "c_units";
6022 $sql .= ' WHERE active > 0';
6023 if (!empty($unit_type)) {
6024 $sql .= " AND unit_type = '" . $this->db->escape($unit_type) . "'";
6025 }
6026 $sql .= " ORDER BY sortorder";
6027
6028 $resql = $this->db->query($sql);
6029 if ($resql && $this->db->num_rows($resql) > 0) {
6030 if ($showempty) {
6031 $return .= '<option value="-1"></option>';
6032 }
6033
6034 while ($res = $this->db->fetch_object($resql)) {
6035 $unitLabel = $res->label;
6036 if (!empty($langs->tab_translate['unit' . $res->code])) { // check if Translation is available before
6037 $unitLabel = $langs->trans('unit' . $res->code) != $res->label ? $langs->trans('unit' . $res->code) : $res->label;
6038 }
6039
6040 if ($selected == $res->rowid) {
6041 $return .= '<option value="' . $res->rowid . '" selected>' . $unitLabel . '</option>';
6042 } else {
6043 $return .= '<option value="' . $res->rowid . '">' . $unitLabel . '</option>';
6044 }
6045 }
6046 $return .= '</select>';
6047
6048 $return .= ajax_combobox($htmlname);
6049 }
6050 return $return;
6051 }
6052
6053 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6054
6070 public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0, $addentrynone = 0)
6071 {
6072 // phpcs:enable
6073 global $langs;
6074
6075 $out = '';
6076
6077 $langs->loadLangs(array("admin", "banks"));
6078 $num = 0;
6079
6080 $sql = "SELECT rowid, label, bank, clos as status, currency_code";
6081 $sql .= " FROM " . $this->db->prefix() . "bank_account";
6082 $sql .= " WHERE entity IN (" . getEntity('bank_account') . ")";
6083 if ($status != 2) {
6084 $sql .= " AND clos = " . (int) $status;
6085 }
6086 if ($filtre) {
6087 $sql .= forgeSQLFromUniversalSearchCriteria($filtre);
6088 }
6089 $sql .= " ORDER BY label";
6090
6091 dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
6092 $result = $this->db->query($sql);
6093 if ($result) {
6094 $num = $this->db->num_rows($result);
6095 $i = 0;
6096
6097 $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
6098
6099 if ($num == 0) {
6100 if ($status == 0) {
6101 $out .= '<option class="opacitymedium" value="-1">' . $langs->trans("NoActiveBankAccountDefined") . '</span>';
6102 } else {
6103 $out .= '<option class="opacitymedium" value="-1">' . $langs->trans("NoBankAccountDefined") . '</span>';
6104 }
6105 } else {
6106 if (!empty($useempty) && !is_numeric($useempty)) {
6107 $out .= '<option value="-1">'.$langs->trans($useempty).'</option>';
6108 } elseif ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6109 $out .= '<option value="-1">&nbsp;</option>';
6110 }
6111 }
6112
6113 while ($i < $num) {
6114 $obj = $this->db->fetch_object($result);
6115
6116 $labeltoshow = trim($obj->label);
6117 $labeltoshowhtml = trim($obj->label);
6118 if ($showcurrency) {
6119 $labeltoshow .= ' (' . $obj->currency_code . ')';
6120 $labeltoshowhtml .= ' <span class="opacitymedium">(' . $obj->currency_code . ')</span>';
6121 }
6122 if ($status == 2 && $obj->status == 1) {
6123 $labeltoshow .= ' (' . $langs->trans("Closed") . ')';
6124 $labeltoshowhtml .= ' <span class="opacitymedium">(' . $langs->trans("Closed") . ')</span>';
6125 }
6126
6127 if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
6128 $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml).'" selected>';
6129 } else {
6130 $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml).'">';
6131 }
6132 $out .= $labeltoshow;
6133 $out .= '</option>';
6134 $i++;
6135 }
6136
6137 if (!empty($addentrynone)) {
6138 $out .= '<option value="-2"'.($selected == -2 ? ' selected="selected"' : '').' data-html="'.dolPrintHTMLForAttribute('<span class="opacitymedium">'.$langs->trans("None").'</span>').'">'.$langs->trans("None").'</option>';
6139 }
6140
6141 $out .= "</select>";
6142 $out .= ajax_combobox('select' . $htmlname);
6143 } else {
6144 dol_print_error($this->db);
6145 }
6146
6147 // Output or return
6148 if (empty($nooutput)) {
6149 print $out;
6150 } else {
6151 return $out;
6152 }
6153
6154 return $num;
6155 }
6156
6170 public function selectRib($selected = '', $htmlname = 'ribcompanyid', $filtre = '', $useempty = 0, $moreattrib = '', $showibanbic = 0, $morecss = '', $nooutput = 0)
6171 {
6172 // phpcs:enable
6173 global $langs;
6174
6175 $out = '';
6176
6177 $langs->loadLangs(array("admin", "banks"));
6178 $num = 0;
6179
6180 $sql = "SELECT rowid, label, bank, status, iban_prefix, bic, default_rib";
6181 $sql .= " FROM " . $this->db->prefix() . "societe_rib";
6182 $sql .= " WHERE type = 'ban'";
6183 if ($filtre) {
6184 $sql .= forgeSQLFromUniversalSearchCriteria($filtre);
6185 }
6186 $sql .= " ORDER BY label";
6187 dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
6188 $result = $this->db->query($sql);
6189 if ($result) {
6190 $num = $this->db->num_rows($result);
6191 $i = 0;
6192
6193 $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
6194
6195 if ($num == 0) {
6196 $out .= '<option class="opacitymedium" value="-1">' . $langs->trans("NoBankAccountDefined") . '</span>';
6197 } else {
6198 if (!empty($useempty) && !is_numeric($useempty)) {
6199 $out .= '<option value="-1">'.$langs->trans($useempty).'</option>';
6200 } elseif ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6201 $out .= '<option value="-1">&nbsp;</option>';
6202 }
6203 }
6204
6205 while ($i < $num) {
6206 $obj = $this->db->fetch_object($result);
6207 $iban = dolDecrypt($obj->iban_prefix);
6208 if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
6209 $out .= '<option value="' . $obj->rowid . '" data-iban-prefix="' . $iban . ' data-bic="' . $obj->bic . '" selected>';
6210 } else {
6211 $out .= '<option value="' . $obj->rowid . '" data-iban-prefix="' . $iban . ' data-bic="' . $obj->bic . '">';
6212 }
6213 $out .= trim($obj->label);
6214 if ($showibanbic) {
6215 $out .= ' (' . $iban . '/' .$obj->bic. ')' . ($obj->default_rib ? ' ['.$langs->trans("ByDefault").']' : '');
6216 }
6217 $out .= '</option>';
6218 $i++;
6219 }
6220 $out .= "</select>";
6221 $out .= ajax_combobox('select' . $htmlname);
6222 } else {
6223 dol_print_error($this->db);
6224 }
6225
6226 // Output or return
6227 if (empty($nooutput)) {
6228 print $out;
6229 } else {
6230 return $out;
6231 }
6232
6233 return $num;
6234 }
6235
6247 public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
6248 {
6249 global $langs;
6250
6251 $langs->load("admin");
6252 $num = 0;
6253
6254 $sql = "SELECT rowid, name, fk_country, status, entity";
6255 $sql .= " FROM " . $this->db->prefix() . "establishment";
6256 $sql .= " WHERE 1=1";
6257 if ($status != 2) {
6258 $sql .= " AND status = " . (int) $status;
6259 }
6260 if ($filtre) {
6261 $sql .= forgeSQLFromUniversalSearchCriteria($filtre);
6262 }
6263 $sql .= " ORDER BY name";
6264
6265 dol_syslog(get_class($this) . "::select_establishment", LOG_DEBUG);
6266 $result = $this->db->query($sql);
6267 if ($result) {
6268 $num = $this->db->num_rows($result);
6269 $i = 0;
6270 if ($num) {
6271 print '<select id="select' . $htmlname . '" class="flat selectestablishment" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
6272 if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6273 print '<option value="-1">&nbsp;</option>';
6274 }
6275
6276 while ($i < $num) {
6277 $obj = $this->db->fetch_object($result);
6278 if ($selected == $obj->rowid) {
6279 print '<option value="' . $obj->rowid . '" selected>';
6280 } else {
6281 print '<option value="' . $obj->rowid . '">';
6282 }
6283 print trim($obj->name);
6284 if ($status == 2 && $obj->status == 1) {
6285 print ' (' . $langs->trans("Closed") . ')';
6286 }
6287 print '</option>';
6288 $i++;
6289 }
6290 print "</select>";
6291 } else {
6292 if ($status == 0) {
6293 print '<span class="opacitymedium">' . $langs->trans("NoActiveEstablishmentDefined") . '</span>';
6294 } else {
6295 print '<span class="opacitymedium">' . $langs->trans("NoEstablishmentFound") . '</span>';
6296 }
6297 }
6298
6299 return $num;
6300 } else {
6301 dol_print_error($this->db);
6302 return -1;
6303 }
6304 }
6305
6315 public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
6316 {
6317 global $langs;
6318 if ($htmlname != "none") {
6319 print '<form method="POST" action="' . $page . '">';
6320 print '<input type="hidden" name="action" value="setbankaccount">';
6321 print '<input type="hidden" name="token" value="' . newToken() . '">';
6322 print img_picto('', 'bank_account', 'class="pictofixedwidth"');
6323 $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
6324 if ($nbaccountfound > 0) {
6325 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
6326 }
6327 print '</form>';
6328 } else {
6329 $langs->load('banks');
6330
6331 if ($selected) {
6332 require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
6333 $bankstatic = new Account($this->db);
6334 $result = $bankstatic->fetch((int) $selected);
6335 if ($result) {
6336 print $bankstatic->getNomUrl(1);
6337 }
6338 } else {
6339 print "&nbsp;";
6340 }
6341 }
6342 }
6343
6355 public function formRib($page, $selected = '', $htmlname = 'ribcompanyid', $filtre = '', $addempty = 0, $showibanbic = 0)
6356 {
6357 global $langs;
6358 if ($htmlname != "none") {
6359 print '<form method="POST" action="' . $page . '">';
6360 print '<input type="hidden" name="action" value="setbankaccountcustomer">';
6361 print '<input type="hidden" name="token" value="' . newToken() . '">';
6362 $nbaccountfound = $this->selectRib($selected, $htmlname, $filtre, $addempty, '', $showibanbic);
6363 if ($nbaccountfound > 0) {
6364 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
6365 }
6366 print '</form>';
6367 } else {
6368 $langs->load('banks');
6369
6370 if ($selected) {
6371 require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
6372 $bankstatic = new CompanyBankAccount($this->db);
6373 $result = $bankstatic->fetch((int) $selected);
6374 if ($result) {
6375 print $bankstatic->label;
6376 if ($showibanbic) {
6377 print ' (' . $bankstatic->iban . '/' .$bankstatic->bic. ')';
6378 }
6379 }
6380 } else {
6381 print "&nbsp;";
6382 }
6383 }
6384 }
6385
6395 public function selectCategories($categtype, $htmlname, $object = null)
6396 {
6397 global $langs;
6398
6399 $out = '';
6400
6401 $cate_arbo = $this->select_all_categories($categtype, '', '', 64, 0, 3);
6402
6403 $arrayselected = array();
6404 if (GETPOSTISARRAY($htmlname)) {
6405 $arrayselected = GETPOST($htmlname, 'array:int');
6406 } elseif (is_object($object) && $object->id > 0) {
6407 $c = new Categorie($this->db);
6408 $cats = $c->containing($object->id, $categtype);
6409 $arrayselected = array();
6410 foreach ($cats as $cat) {
6411 $arrayselected[] = $cat->id;
6412 }
6413 }
6414
6415 $out .= img_picto('', 'category', 'class="pictofixedwidth"');
6416 $out .= $this->multiselectarray($htmlname, $cate_arbo, $arrayselected, 0, 0, 'minwidth100 widthcentpercentminusxx', 0, 0);
6417
6418 if (!getDolGlobalString('CATEGORY_EDIT_IN_MENU_NOT_IN_POPUP')) {
6419 // Add html code to add the edit button and go back
6420 $jsonclose = 'doJsCodeAfterPopupClose'.dol_sanitizeKeyCode($htmlname).'()';
6421 $urltoopen = '/categories/categorie_list.php?type='.urlencode($categtype).'&nosearch=1';
6422
6423 $s = dolButtonToOpenUrlInDialogPopup($htmlname, $langs->transnoentitiesnoconv("Categories"), img_picto('', 'add', 'class="editfielda"'), $urltoopen, '', '', '', $jsonclose);
6424 $out .= $s;
6425 // Add js code to add the edit button and go back
6426 $out .= '<!-- Add js code to open the popup for category/edit/add -->'."\n";
6427 $out .= '<script>function doJsCodeAfterPopupClose'.dol_sanitizeKeyCode($htmlname).'() {
6428 console.log("doJsCodeAfterPopupClose'.dol_sanitizeKeyCode($htmlname).' has been called, we refresh the combo content + refresh select2...");
6429
6430 // Call an ajax to reload values and update the select
6431
6432 $.ajax({
6433 url: \''.DOL_URL_ROOT.'/core/ajax/fetchCategories.php\',
6434 data: {
6435 action: \'getCategories\',
6436 type: \''.dol_escape_htmltag($categtype).'\'
6437 },
6438 type: \'GET\',
6439 dataType: \'json\',
6440 success: function (data) {
6441 var $select = $(\'#'.dol_sanitizeKeyCode($htmlname).'\');
6442 var selectedValues = $select.val(); // This is an array of selected values
6443 console.log(selectedValues);
6444 $select.empty();
6445 $.each(data, function (index, item) {
6446 $select.append(\'<option value="\' + item.id + \'" data-html="\' + item.htmlforattribute + \'">\' + item.htmlforoption + \'</option>\');
6447 });
6448 $select.val(selectedValues);
6449 },
6450 error: function (xhr, status, error) {
6451 console.log("Error when loading ajax page : " + error);
6452 }
6453 });
6454
6455 // Refresh select2 to take account of new values (enough for small change)
6456 $("#'.dol_sanitizeKeyCode($htmlname).'").trigger("change");
6457
6458 // Alternative if change in select is complex
6459 /*
6460 $("#'.dol_sanitizeKeyCode($htmlname).'").select2("destroy");
6461 $("#'.dol_sanitizeKeyCode($htmlname).'").select2();
6462 */
6463 }</script>';
6464 }
6465
6466 return $out;
6467 }
6468
6469
6470 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6490 public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $fromid = 0, $outputmode = 0, $include = 0, $morecss = '', $useempty = 1)
6491 {
6492 // phpcs:enable
6493 global $langs;
6494
6495 include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
6496
6497 $cat = new Categorie($this->db);
6498
6499 if (is_numeric($type)) {
6500 $type = array_search($type, $cat->MAP_ID); // For backward compatibility
6501 }
6502
6503 $cate_arbo = $cat->get_full_arbo($type, $fromid, $include);
6504
6505 $outarray = array();
6506 $outarrayrichhtml = array();
6507
6508
6509 $output = '<select class="flat minwidth100' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
6510 $num = 0;
6511 if (is_array($cate_arbo)) {
6512 $num = count($cate_arbo);
6513
6514 if (!$num) {
6515 $langs->load("categories");
6516 $output .= '<option value="-1" disabled>' . $langs->trans("NoCategoriesDefined") . '</option>';
6517 } else {
6518 if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6519 $output .= '<option value="-1">&nbsp;</option>';
6520 }
6521 foreach ($cate_arbo as $key => $value) {
6522 if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
6523 $add = 'selected ';
6524 } else {
6525 $add = '';
6526 }
6527
6528 $labeltoshow = img_picto('', 'category', 'class="pictofixedwidth"'.(empty($cate_arbo[$key]['color']) ? '' : ' style="color: #' . $cate_arbo[$key]['color'] . '"'));
6529 $labeltoshow .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
6530
6531 $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
6532
6533 $outarrayrichhtml[$cate_arbo[$key]['id']] = $labeltoshow;
6534
6535 $output .= '<option ' . $add . 'value="' . $cate_arbo[$key]['id'] . '"';
6536 $output .= ' data-html="' . dol_escape_htmltag($labeltoshow) . '"';
6537 $output .= '>';
6538 // The visible (truncated) label is rendered via data-html in
6539 // templateResult of the select2 combobox; the bare option text
6540 // must keep the full label so that the select2 search matcher
6541 // (ajax_combobox in core/lib/ajax.lib.php) can find a hit on
6542 // characters that lie outside the truncated portion.
6543 $output .= dol_escape_htmltag($cate_arbo[$key]['fulllabel']);
6544 $output .= '</option>';
6545
6546 $cate_arbo[$key]['data-html'] = $labeltoshow;
6547 }
6548 }
6549 }
6550 $output .= '</select>';
6551 $output .= "\n";
6552
6553 $this->num = $num;
6554
6555 if ($outputmode == 2) {
6556 // TODO: handle error when $cate_arbo is not an array
6557 return $cate_arbo;
6558 } elseif ($outputmode == 1) {
6559 return $outarray;
6560 } elseif ($outputmode == 3) {
6561 return $outarrayrichhtml;
6562 }
6563 return $output;
6564 }
6565
6574 public function getHelpBlock($content, $icon = 'fa-question-circle')
6575 {
6576 global $langs;
6577
6578 // Sanitize content (assuming it might contain HTML, but escaping text nodes if needed)
6579 // We trust the caller to pass safe HTML or translated strings.
6580
6581 $html = '<details class="dolibarr-help-block" style="margin-top:8px;">';
6582 $html .= '<summary style="cursor:pointer; color:#0056b3; font-weight:normal; list-style:none; font-size:0.9em; display:flex; align-items:center;">';
6583 $html .= '<span class="fa ' . $icon . '" style="margin-right:6px;"></span>';
6584 $html .= $langs->trans("Help"); // Standardized title
6585 $html .= '</summary>';
6586 $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;">';
6587 $html .= $content;
6588 $html .= '</div>';
6589 $html .= '</details>';
6590
6591 return $html;
6592 }
6593
6594 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6595
6614 public function form_confirm($page, $title, $question, $action, $formquestion = array(), $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
6615 {
6616 // phpcs:enable
6617 dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
6618 print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
6619 }
6620
6650 public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 600, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No', $helpContent = '')
6651 {
6652 global $langs, $conf;
6653
6654 $more = '';
6655 $formconfirm = '<!-- formconfirm - before call, page=' . dol_escape_htmltag($page) . ' -->';
6656
6657 $inputok = array();
6658 $inputko = array();
6659
6660 // Clean parameters
6661 $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
6662 if ($conf->browser->layout == 'phone') {
6663 $width = '95%';
6664 }
6665
6666 // Set height automatically if not defined
6667 if (empty($height)) {
6668 $height = 185;
6669 if (is_array($formquestion)) {
6670 $height += (count($formquestion) * 40);
6671 }
6672 if ($question) {
6673 $height += dol_nboflines_bis($question, 80) * 40;
6674 }
6675 }
6676
6677 if (is_array($formquestion) && !empty($formquestion)) {
6678 // First add hidden fields and value
6679 foreach ($formquestion as $key => $input) {
6680 if (is_array($input) && !empty($input)) {
6681 if ($input['type'] == 'hidden') {
6682 $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
6683 $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
6684
6685 $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
6686 }
6687 }
6688 }
6689
6690 // Now add questions
6691 $moreonecolumn = '';
6692 $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">' . "\n";
6693 foreach ($formquestion as $key => $input) {
6694 if (is_array($input) && !empty($input)) {
6695 $size = (!empty($input['size']) ? ' size="' . $input['size'] . '"' : ''); // deprecated. Use morecss instead.
6696 $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
6697 $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
6698
6699 if ($input['type'] == 'text' || $input['type'] == 'input') { // traditional input
6700 $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";
6701 } elseif ($input['type'] == 'password') {
6702 $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";
6703 } elseif ($input['type'] == 'textarea') {
6704 $moreonecolumn .= '<div class="margintoponly">';
6705 $moreonecolumn .= $input['label'] . '<br>';
6706 $moreonecolumn .= '<textarea name="' . dol_escape_htmltag($input['name']) . '" id="' . dol_escape_htmltag($input['name']) . '" class="' . $morecss . '"' . $moreattr . '>';
6707 $moreonecolumn .= $input['value'];
6708 $moreonecolumn .= '</textarea>';
6709 $moreonecolumn .= '</div>';
6710 } elseif (in_array($input['type'], ['select', 'multiselect'])) {
6711 if (empty($morecss)) {
6712 $morecss = 'minwidth100';
6713 }
6714
6715 $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
6716 $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
6717 $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
6718 $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
6719 $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
6720 $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
6721 $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
6722
6723 $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">';
6724 if (!empty($input['label'])) {
6725 $more .= $input['label'] . '</div><div class="tagtd left">';
6726 }
6727 if ($input['type'] == 'select') {
6728 $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);
6729 } else {
6730 $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);
6731 }
6732 $more .= '</div></div>' . "\n";
6733 } elseif ($input['type'] == 'checkbox') {
6734 $more .= '<div class="tagtr">';
6735 $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '"><label for="' . dol_escape_htmltag($input['name']) . '">' . $input['label'] . '</label></div><div class="tagtd">';
6736 $more .= '<input type="checkbox" class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $moreattr;
6737 if (isset($input['value']) && !is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
6738 $more .= ' checked';
6739 }
6740 if (isset($input['value']) && is_bool($input['value']) && $input['value']) {
6741 $more .= ' checked';
6742 }
6743 if (isset($input['disabled'])) {
6744 $more .= ' disabled';
6745 }
6746 $more .= ' /></div>';
6747 $more .= '</div>' . "\n";
6748 } elseif ($input['type'] == 'radio') {
6749 $i = 0;
6750 foreach ($input['values'] as $selkey => $selval) {
6751 $more .= '<div class="tagtr">';
6752 if (isset($input['label'])) {
6753 if ($i == 0) {
6754 $more .= '<div class="tagtd' . (empty($input['tdclass']) ? ' tdtop' : (' tdtop ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
6755 } else {
6756 $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' "' . $input['tdclass'])) . '">&nbsp;</div>';
6757 }
6758 }
6759 $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;
6760 if (!empty($input['disabled'])) {
6761 $more .= ' disabled';
6762 }
6763 if (isset($input['default']) && $input['default'] === $selkey) {
6764 $more .= ' checked="checked"';
6765 }
6766 $more .= ' /> ';
6767 $more .= '<label for="' . dol_escape_htmltag($input['name'] . $selkey) . '" class="valignmiddle">' . $selval . '</label>';
6768 $more .= '</div></div>' . "\n";
6769 $i++;
6770 }
6771 } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
6772 $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
6773 $more .= '<div class="tagtd">';
6774 $addnowlink = (empty($input['datenow']) ? 0 : 1);
6775 $h = $m = 0;
6776 if ($input['type'] == 'datetime') {
6777 $h = isset($input['hours']) ? $input['hours'] : 1;
6778 $m = isset($input['minutes']) ? $input['minutes'] : 1;
6779 }
6780 $more .= $this->selectDate(isset($input['value']) ? $input['value'] : -1, $input['name'], $h, $m, 0, '', 1, $addnowlink);
6781 $more .= '</div></div>'."\n";
6782 $formquestion[] = array('name' => $input['name'].'day');
6783 $formquestion[] = array('name' => $input['name'].'month');
6784 $formquestion[] = array('name' => $input['name'].'year');
6785 $formquestion[] = array('name' => $input['name'].'hour');
6786 $formquestion[] = array('name' => $input['name'].'min');
6787 } elseif ($input['type'] == 'other') { // can be 1 column or 2 depending if label is set or not
6788 $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
6789 if (!empty($input['label'])) {
6790 $more .= $input['label'] . '</div><div class="tagtd">';
6791 }
6792 if (!empty($input['value'])) {
6793 $more .= $input['value'];
6794 }
6795 $more .= '</div></div>' . "\n";
6796 } elseif ($input['type'] == 'onecolumn') {
6797 $moreonecolumn .= '<div class="margintoponly">';
6798 $moreonecolumn .= $input['value'];
6799 $moreonecolumn .= '</div>' . "\n";
6800 } elseif ($input['type'] == 'hidden') {
6801 // Do nothing more, already added by a previous loop
6802 } elseif ($input['type'] == 'separator') {
6803 $more .= '<br>';
6804 } else {
6805 $more .= 'Error type ' . $input['type'] . ' for the confirm box is not a supported type';
6806 }
6807 }
6808 }
6809 $more .= '</div>' . "\n";
6810 $more .= $moreonecolumn;
6811 }
6812
6813 // JQUERY method dialog is broken with smartphone, we use standard HTML.
6814 // 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
6815 // See page product/card.php for example
6816 if (!empty($conf->dol_use_jmobile)) {
6817 $useajax = 0;
6818 }
6819 if (empty($conf->use_javascript_ajax)) {
6820 $useajax = 0;
6821 }
6822
6823 if ($useajax) {
6824 $autoOpen = true;
6825 $dialogconfirm = 'dialog-confirm';
6826 $button = '';
6827 if (!is_numeric($useajax)) {
6828 $button = $useajax;
6829 $useajax = 1;
6830 $autoOpen = false;
6831 $dialogconfirm .= '-' . $button;
6832 }
6833 $pageyes = $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=yes';
6834 $pageno = ($useajax == 2 ? $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=no' : '');
6835
6836 // Add input fields into list of fields to read during submit (inputok and inputko)
6837 if (is_array($formquestion)) {
6838 foreach ($formquestion as $key => $input) {
6839 //print "xx ".$key." rr ".is_array($input)."<br>\n";
6840 // Add name of fields to propagate with the GET when submitting the form with button OK.
6841 if (is_array($input) && isset($input['name'])) {
6842 if (strpos($input['name'], ',') > 0) {
6843 $inputok = array_merge($inputok, explode(',', $input['name']));
6844 } else {
6845 array_push($inputok, $input['name']);
6846 }
6847 }
6848 // Add name of fields to propagate with the GET when submitting the form with button KO.
6849 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
6850 if (is_array($input) && isset($input['inputko']) && $input['inputko'] == 1 && isset($input['name'])) {
6851 array_push($inputko, $input['name']);
6852 }
6853 }
6854 }
6855
6856 // Show JQuery confirm box.
6857 // Add 'flex-direction: column' and 'justify-content: space-between' to push content to top and buttons to bottom
6858 $formconfirm .= '<div id="' . $dialogconfirm . '" title="' . dol_escape_htmltag($title) . '" style="display: none;">';
6859 $formconfirm .= '<div style="display: flex; flex-direction: column; height: 100%;">';
6860 if (is_array($formquestion) && array_key_exists('text', $formquestion) && !empty($formquestion['text'])) {
6861 $formconfirm .= '<div class="confirmtext">' . $formquestion['text'] . '</div>' . "\n";
6862 }
6863 if (!empty($more)) {
6864 $formconfirm .= '<div class="confirmquestions">' . $more . '</div>' . "\n";
6865 }
6866 // NEW: Add help block if content provided
6867 if (!empty($helpContent)) {
6868 $formconfirm .= '<div style="text-align:left; margin-top:12px; padding-top:8px; border-top:1px solid #eee; clear:both;">';
6869 $formconfirm .= $this->getHelpBlock($helpContent);
6870 $formconfirm .= '</div>';
6871 }
6872 if (!empty($question)) {
6873 $formconfirm .= '<div class="confirmmessage" style="padding-top: 15px;">';
6874 $formconfirm .= img_help(0, '') . ' ' . $question;
6875 $formconfirm .= '</div>';
6876 }
6877 $formconfirm .= '</div>';
6878 $formconfirm .= '</div>' . "\n";
6879
6880 $formconfirm .= "\n<!-- begin code of popup for formconfirm page=" . $page . " -->\n";
6881 $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
6882 $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
6883 $formconfirm .= 'jQuery(document).ready(function() {
6884 $(function() {
6885 $( "#' . $dialogconfirm . '" ).dialog({
6886 autoOpen: ' . ($autoOpen ? "true" : "false") . ',';
6887 if ($newselectedchoice == 'no') {
6888 $formconfirm .= '
6889 open: function() {
6890 $(this).parent().find("button.ui-button:eq(2)").focus();
6891 },';
6892 }
6893
6894 $jsforcursor = '';
6895 if ($useajax == 1) {
6896 $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor' . "\n";
6897 $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");' . "\n";
6898 }
6899
6900 $postconfirmas = 'GET';
6901
6902 $formconfirm .= '
6903 resizable: false,
6904 height: \'' . dol_escape_js($height) . '\',
6905 width: \'' . dol_escape_js($width) . '\',
6906 modal: true,
6907 closeOnEscape: false,
6908 buttons: {
6909 "' . dol_escape_js($langs->transnoentities($labelbuttonyes)) . '": function() {
6910 var options = "token=' . urlencode(newToken()) . '";
6911 var inputok = ' . json_encode($inputok) . '; /* List of fields into form */
6912 var page = \'' . dol_escape_js(!empty($page) ? $page : '') . '\';
6913 var pageyes = \'' . dol_escape_js(!empty($pageyes) ? $pageyes : '') . '\';
6914
6915 if (inputok.length > 0) {
6916 $.each(inputok, function(i, inputname) {
6917 var more = "";
6918 var inputvalue;
6919 if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
6920 inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
6921 } else {
6922 if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
6923 inputvalue = $("#" + inputname + more).val();
6924 }
6925 if (typeof inputvalue == "undefined") { inputvalue=""; }
6926 console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
6927 options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
6928 });
6929 }
6930 var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
6931 if (pageyes.length > 0) {';
6932 if ($postconfirmas == 'GET') {
6933 $formconfirm .= 'location.href = urljump;';
6934 } else {
6935 $formconfirm .= $jsforcursor;
6936 $formconfirm .= 'var post = $.post(
6937 pageyes,
6938 options,
6939 function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
6940 );';
6941 }
6942 $formconfirm .= '
6943 console.log("after post ok");
6944 }
6945 $(this).dialog("close");
6946 },
6947 "' . dol_escape_js($langs->transnoentities($labelbuttonno)) . '": function() {
6948 var options = "token=' . urlencode(newToken()) . '";
6949 var inputko = ' . json_encode($inputko) . '; /* List of fields into form */
6950 var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
6951 var pageno="' . dol_escape_js(!empty($pageno) ? $pageno : '') . '";
6952 if (inputko.length > 0) {
6953 $.each(inputko, function(i, inputname) {
6954 var more = "";
6955 if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
6956 var inputvalue = $("#" + inputname + more).val();
6957 if (typeof inputvalue == "undefined") { inputvalue=""; }
6958 options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
6959 });
6960 }
6961 var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
6962 //alert(urljump);
6963 if (pageno.length > 0) {';
6964 if ($postconfirmas == 'GET') {
6965 $formconfirm .= 'location.href = urljump;';
6966 } else {
6967 $formconfirm .= $jsforcursor;
6968 $formconfirm .= 'var post = $.post(
6969 pageno,
6970 options,
6971 function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
6972 );';
6973 }
6974 $formconfirm .= '
6975 console.log("after post ko");
6976 }
6977 $(this).dialog("close");
6978 }
6979 }
6980 }
6981 );
6982
6983 var button = "' . $button . '";
6984 if (button.length > 0) {
6985 $( "#" + button ).click(function() {
6986 $("#' . $dialogconfirm . '").dialog("open");
6987 });
6988 }
6989 });
6990 });
6991 </script>';
6992 $formconfirm .= "<!-- end ajax formconfirm -->\n";
6993 } else {
6994 $formconfirm .= "\n<!-- begin formconfirm page=" . dol_escape_htmltag($page) . " -->\n";
6995
6996 if (empty($disableformtag)) {
6997 $formconfirm .= '<form method="POST" action="' . $page . '" class="notoptoleftnoright">' . "\n";
6998 }
6999
7000 $formconfirm .= '<input type="hidden" name="action" value="' . $action . '">' . "\n";
7001 $formconfirm .= '<input type="hidden" name="token" value="' . newToken() . '">' . "\n";
7002
7003 $formconfirm .= '<div class="valid">' . "\n";
7004
7005 // Line title
7006 $formconfirm .= '<div class="validtitre">';
7007 $formconfirm .= img_picto('', 'pictoconfirm') . ' ' . $title;
7008 $formconfirm .= '</div>' . "\n";
7009
7010 // Line text
7011 if (is_array($formquestion) && array_key_exists('text', $formquestion) && !empty($formquestion['text'])) {
7012 $formconfirm .= '<div class="valid">' . $formquestion['text'] . '</div>' . "\n";
7013 }
7014
7015 // Line form fields
7016 if ($more) {
7017 $formconfirm .= '<div>' . "\n";
7018 $formconfirm .= $more;
7019 $formconfirm .= '</div>' . "\n";
7020 }
7021
7022 // NEW: Help block row (between form fields and question)
7023 if (!empty($helpContent)) {
7024 $formconfirm .= '<div style="padding-top:8px; border-top:1px solid #888;">';
7025 $formconfirm .= $this->getHelpBlock($helpContent);
7026 $formconfirm .= '</div>' . "\n";
7027 }
7028
7029 // Let's add a row that acts as a spacer.
7030 $formconfirm .= '<div style="padding-top: 20px;"></div>' . "\n";
7031
7032 // Question row
7033 $formconfirm .= '<div class="inline-block">' . $question . '</div>';
7034
7035 $formconfirm .= '<div class="inline-block">';
7036 $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
7037 $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="' . $langs->trans("Validate") . '">';
7038 $formconfirm .= '</div>';
7039
7040 $formconfirm .= '</div>';
7041
7042 if (empty($disableformtag)) {
7043 $formconfirm .= "</form>\n";
7044 }
7045 $formconfirm .= '<br>';
7046
7047 if (!empty($conf->use_javascript_ajax)) {
7048 $formconfirm .= '<!-- code to disable button to avoid double clic -->';
7049 $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
7050 $formconfirm .= '
7051 $(document).ready(function () {
7052 $(".confirmvalidatebutton").on("click", function() {
7053 console.log("We click on button confirmvalidatebutton");
7054 $(this).attr("disabled", "disabled");
7055 setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
7056 //console.log($(this).closest("form"));
7057 $(this).closest("form").submit();
7058 });
7059 });
7060 ';
7061 $formconfirm .= '</script>' . "\n";
7062 }
7063
7064 $formconfirm .= "<!-- end formconfirm -->\n";
7065 }
7066
7067 return $formconfirm;
7068 }
7069
7070 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7071
7088 public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '', $option = '')
7089 {
7090 // phpcs:enable
7091 global $langs;
7092
7093 require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
7094 require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
7095
7096 $out = '';
7097
7098 $formproject = new FormProjets($this->db);
7099
7100 $langs->load("project");
7101 if ($htmlname != "none") {
7102 $out .= '<form method="post" action="' . $page . '">';
7103 $out .= '<input type="hidden" name="action" value="classin">';
7104 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7105 $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
7106 $out .= '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7107 $out .= '</form>';
7108 } else {
7109 $out .= '<span class="project_head_block">';
7110 if ($selected instanceof Project) {
7111 $out .= $selected->getNomUrl(0, $option, 1);
7112 } elseif (is_numeric($selected)) {
7113 $projet = new Project($this->db);
7114 $projet->fetch((int) $selected);
7115 $out .= $projet->getNomUrl(0, $option, 1);
7116 } else {
7117 $out .= '<span class="opacitymedium">' . $textifnoproject . '</span>';
7118 }
7119 $out .= '</span>';
7120 }
7121
7122 if (empty($nooutput)) {
7123 print $out;
7124 return '';
7125 }
7126 return $out;
7127 }
7128
7129 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7130
7146 public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
7147 {
7148 // phpcs:enable
7149 global $langs;
7150
7151 $selected = (int) $selected;
7152
7153 $out = '';
7154
7155 if ($htmlname != "none") {
7156 $out .= '<form method="POST" action="' . $page . '">';
7157 $out .= '<input type="hidden" name="action" value="setconditions">';
7158 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7159 if ($type) {
7160 $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
7161 }
7162 $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
7163 $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7164 $out .= '</form>';
7165 } else {
7166 if ($selected) {
7167 $this->load_cache_conditions_paiements();
7168
7169 if (isset($this->cache_conditions_paiements[$selected])) {
7170 $label = $this->cache_conditions_paiements[$selected]['label'];
7171
7172 if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
7173 $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
7174 }
7175
7176 $out .= $label;
7177 } else {
7178 $langs->load('errors');
7179 $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions', $selected);
7180 }
7181 } else {
7182 $out .= '&nbsp;';
7183 }
7184 }
7185
7186 if (empty($nooutput)) {
7187 print $out;
7188 return '';
7189 }
7190 return $out;
7191 }
7192
7193 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7194
7205 public function form_rule_for_lines_dates($page, $selected = '', $htmlname = 'rule_for_lines_dates', $addempty = 0, $nooutput = 0): string
7206 {
7207 // phpcs:enable
7208 global $langs;
7209
7210 $out = '';
7211
7212 if ($htmlname != 'none') {
7213 $out .= '<form method="POST" action="' . $page . '">';
7214 $out .= '<input type="hidden" name="action" value="setruleforlinesdates">';
7215 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7216 $out .= $this->getSelectRuleForLinesDates($selected, $htmlname, $addempty);
7217 $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7218 $out .= '</form>';
7219 } else {
7220 if (isset($selected)) {
7221 $this->load_cache_rule_for_lines_dates();
7222 if (isset($this->cache_rule_for_lines_dates[$selected])) {
7223 $label = $this->cache_rule_for_lines_dates[$selected];
7224 $out .= $langs->trans($label);
7225 }
7226 } else {
7227 $out .= '&nbsp;';
7228 }
7229 }
7230
7231 if (empty($nooutput)) {
7232 print $out;
7233 return '';
7234 }
7235
7236 return $out;
7237 }
7238
7239 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7240
7250 public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
7251 {
7252 dol_syslog(__METHOD__, LOG_DEBUG);
7253 // phpcs:enable
7254 global $langs;
7255 if ($htmlname != "none") {
7256 print '<form method="post" action="' . $page . '">';
7257 print '<input type="hidden" name="action" value="setavailability">';
7258 print '<input type="hidden" name="token" value="' . newToken() . '">';
7259 print $this->selectAvailabilityDelay($selected, $htmlname, '', $addempty, '', 1);
7260 print '<input type="submit" name="modify" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7261 print '<input type="submit" name="cancel" class="button smallpaddingimp" value="' . $langs->trans("Cancel") . '">';
7262 print '</form>';
7263 } else {
7264 if ($selected) {
7265 $this->load_cache_availability();
7266 // @phan-suppress-next-line PhanTypeMismatchProperty
7267 if (isset($this->cache_availability[$selected])) {
7268 print $this->cache_availability[$selected]['label'];
7269 } else {
7270 print "&nbsp;";
7271 }
7272 } else {
7273 print "&nbsp;";
7274 }
7275 }
7276 }
7277
7289 public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0, $morecss = '')
7290 {
7291 global $langs;
7292 if ($htmlname != "none") {
7293 print '<form method="post" action="' . $page . '">';
7294 print '<input type="hidden" name="action" value="setdemandreason">';
7295 print '<input type="hidden" name="token" value="' . newToken() . '">';
7296 $this->selectInputReason($selected, $htmlname, '-1', $addempty, $morecss);
7297 print '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
7298 print '</form>';
7299 } else {
7300 if ($selected) {
7301 $this->loadCacheInputReason();
7302 foreach ($this->cache_demand_reason as $key => $val) {
7303 if ($val['id'] == $selected) {
7304 print $val['label'];
7305 break;
7306 }
7307 }
7308 } else {
7309 print "&nbsp;";
7310 }
7311 }
7312 }
7313
7314 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7315
7329 public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
7330 {
7331 // phpcs:enable
7332 global $langs;
7333
7334 $ret = '';
7335
7336 if ($htmlname != "none") {
7337 $ret .= '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
7338 $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
7339 $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
7340 if ($type) {
7341 $ret .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
7342 }
7343 $ret .= '<table class="nobordernopadding">';
7344 $ret .= '<tr><td>';
7345 $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form' . $htmlname, 1, 0);
7346 $ret .= '</td>';
7347 $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
7348 $ret .= '</tr></table></form>';
7349 } else {
7350 if ($displayhour) {
7351 $ret .= dol_print_date($selected, 'dayhour');
7352 } else {
7353 $ret .= dol_print_date($selected, 'day');
7354 }
7355 }
7356
7357 if (empty($nooutput)) {
7358 print $ret;
7359 }
7360 return $ret;
7361 }
7362
7363
7364 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7365
7376 public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = array(), $include = array())
7377 {
7378 // phpcs:enable
7379 global $langs;
7380
7381 if ($htmlname != "none") {
7382 print '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
7383 print '<input type="hidden" name="action" value="set' . $htmlname . '">';
7384 print '<input type="hidden" name="token" value="' . newToken() . '">';
7385 print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
7386 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7387 print '</form>';
7388 } else {
7389 if ($selected) {
7390 require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
7391 $theuser = new User($this->db);
7392 $theuser->fetch((int) $selected);
7393 print $theuser->getNomUrl(1);
7394 } else {
7395 print "&nbsp;";
7396 }
7397 }
7398 }
7399
7400
7401 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7402
7416 public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
7417 {
7418 // phpcs:enable
7419 global $langs;
7420
7421 $out = '';
7422 if ($htmlname != "none") {
7423 $out .= '<form method="POST" action="' . $page . '">';
7424 $out .= '<input type="hidden" name="action" value="setmode">';
7425 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7426 if ($type) {
7427 $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
7428 }
7429 $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
7430 $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7431 $out .= '</form>';
7432 } else {
7433 if ($selected) {
7434 $this->load_cache_types_paiements();
7435 // @phan-suppress-next-line PhanTypeMismatchProperty
7436 $out .= isset($this->cache_types_paiements[(int) $selected]['label']) ? $this->cache_types_paiements[(int) $selected]['label'] : '';
7437 } else {
7438 $out .= "&nbsp;";
7439 }
7440 }
7441
7442 if ($nooutput) {
7443 return $out;
7444 } else {
7445 print $out;
7446 }
7447 return '';
7448 }
7449
7460 public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
7461 {
7462 global $langs;
7463 if ($htmlname != "none") {
7464 print '<form method="POST" action="' . $page . '">';
7465 print '<input type="hidden" name="action" value="settransportmode">';
7466 print '<input type="hidden" name="token" value="' . newToken() . '">';
7467 $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
7468 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7469 print '</form>';
7470 } else {
7471 if ($selected) {
7472 $this->load_cache_transport_mode();
7473 print $this->cache_transport_mode[$selected]['label'];
7474 } else {
7475 print "&nbsp;";
7476 }
7477 }
7478 }
7479
7480 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7481
7490 public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
7491 {
7492 // phpcs:enable
7493 global $langs;
7494 if ($htmlname != "none") {
7495 print '<form method="POST" action="' . $page . '">';
7496 print '<input type="hidden" name="action" value="setmulticurrencycode">';
7497 print '<input type="hidden" name="token" value="' . newToken() . '">';
7498 print $this->selectMultiCurrency($selected, $htmlname, 0);
7499 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7500 print '</form>';
7501 } else {
7502 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
7503 print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
7504 }
7505 }
7506
7507 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7508
7519 public function form_multicurrency_rate($page, $rate = 0.0, $htmlname = 'multicurrency_tx', $currency = '', $rate_direct = 0.0)
7520 {
7521 // phpcs:enable
7522 global $langs, $conf;
7523
7524 if ($htmlname != "none") {
7525 print '<form method="POST" action="' . $page . '">';
7526 print '<input type="hidden" name="action" value="setmulticurrencyrate">';
7527 print '<input type="hidden" name="token" value="' . newToken() . '">';
7528 print '<input type="text" class="maxwidth75" name="' . $htmlname . '" value="' . (!empty($rate) ? price(price2num($rate, 'CU')) : 1) . '" spellcheck="false" /> ';
7529 print '<select name="calculation_mode" id="calculation_mode">';
7530 print '<option value="1">Change ' . $langs->trans("PriceUHT") . ' of lines</option>';
7531 print '<option value="2">Change ' . $langs->trans("PriceUHTCurrency") . ' of lines</option>';
7532 print '</select> ';
7533 print ajax_combobox("calculation_mode");
7534 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7535 print '</form>';
7536 } else {
7537 if (!empty($rate)) {
7538 print price($rate, 1, $langs, 0, 0);
7539 if ($currency && $rate != 1) {
7545 if (getDolGlobalString('MULTICURRENCY_USE_RATE_DIRECT')) {
7546 print ' &nbsp; <span class="opacitymedium">(' . price($rate_direct, 1, $langs, 0, 0) . ' ' . $conf->currency . ' = 1 ' . $currency . ')</span>';
7547 } else {
7548 print ' &nbsp; <span class="opacitymedium">(' . price($rate, 1, $langs, 0, 0) . ' ' . $currency . ' = 1 ' . $conf->currency . ')</span>';
7549 }
7550 }
7551 } else {
7552 print 1;
7553 }
7554 }
7555 }
7556
7557 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7558
7576 public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0, $filterabsolutediscount = 0, $filtercreditnote = 0)
7577 {
7578 // phpcs:enable
7579 global $conf, $langs;
7580
7581 if ($htmlname != "none") {
7582 print '<form method="post" action="' . $page . '" class="inline-block">';
7583 print '<input type="hidden" name="action" value="setabsolutediscount">';
7584 print '<input type="hidden" name="token" value="' . newToken() . '">';
7585 print '<div class="inline-block">';
7586 if (!empty($discount_type)) {
7587 if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
7588 if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
7589 $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be subtracted to payments only and not to total of final invoice
7590 } else {
7591 $translationKey = 'HasCreditNoteFromSupplier';
7592 }
7593 } else {
7594 if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
7595 $translationKey = 'HasAbsoluteDiscountFromSupplier';
7596 } else {
7597 $translationKey = 'HasCreditNoteFromSupplier';
7598 }
7599 }
7600 } else {
7601 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
7602 if (!$filter || $filter == "fk_facture_source IS NULL") {
7603 $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be subtracted to payments only and not to total of final invoice
7604 } else {
7605 $translationKey = 'CompanyHasCreditNote';
7606 }
7607 } else {
7608 if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
7609 $translationKey = 'CompanyHasAbsoluteDiscount';
7610 } else {
7611 $translationKey = 'CompanyHasCreditNote';
7612 }
7613 }
7614 }
7615 print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
7616 if (empty($hidelist)) {
7617 print ' ';
7618 }
7619 print '</div>';
7620 if (empty($hidelist)) {
7621 print '<div class="inline-block" style="padding-right: 10px">';
7622 $newfilter = 'discount_type = ' . intval($discount_type);
7623 if (!empty($discount_type)) {
7624 $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
7625 } else {
7626 $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
7627 }
7628 if ($filter) {
7629 $sanitizedfilter = $filter; // @phan-suppress-current-line SqlInjection
7630 $newfilter .= ' AND (' . $sanitizedfilter . ')';
7631 }
7632 // output the combo of discounts
7633 $nbqualifiedlines = $this->select_remises((string) $selected, $htmlname, $newfilter, $socid, $maxvalue);
7634 if ($nbqualifiedlines > 0) {
7635 print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("UseLine")) . '"';
7636 if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
7637 print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
7638 }
7639 if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
7640 print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
7641 }
7642
7643 print '>';
7644 }
7645 print '</div>';
7646 }
7647 if ($more) {
7648 print '<div class="inline-block">';
7649 print $more;
7650 print '</div>';
7651 }
7652 print '</form>';
7653 } else {
7654 if ($selected) {
7655 print $selected;
7656 } else {
7657 print "0";
7658 }
7659 }
7660 }
7661
7662
7663 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7664
7674 public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
7675 {
7676 // phpcs:enable
7677 global $langs;
7678
7679 if ($htmlname != "none") {
7680 print '<form method="post" action="' . $page . '">';
7681 print '<input type="hidden" name="action" value="set_contact">';
7682 print '<input type="hidden" name="token" value="' . newToken() . '">';
7683 print '<table class="nobordernopadding">';
7684 print '<tr><td>';
7685 print $this->selectcontacts($societe->id, $selected, $htmlname);
7686 $num = $this->num;
7687 if ($num == 0) {
7688 $addcontact = (getDolGlobalString('SOCIETE_ADDRESSES_MANAGEMENT') ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
7689 print '<a href="' . DOL_URL_ROOT . '/contact/card.php?socid=' . $societe->id . '&action=create&backtoreferer=1">' . $addcontact . '</a>';
7690 }
7691 print '</td>';
7692 print '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
7693 print '</tr></table></form>';
7694 } else {
7695 if ($selected) {
7696 require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
7697 $contact = new Contact($this->db);
7698 $contact->fetch((int) $selected);
7699 print $contact->getFullName($langs);
7700 } else {
7701 print "&nbsp;";
7702 }
7703 }
7704 }
7705
7706 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7707
7724 public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
7725 {
7726 // phpcs:enable
7727 global $langs;
7728
7729 $out = '';
7730 if ($htmlname != "none") {
7731 $limit = getDolGlobalInt('THIRDPARTY_LIMIT_SIZE');
7732
7733 $out .= '<form method="post" action="' . $page . '">';
7734 $out .= '<input type="hidden" name="action" value="set_thirdparty">';
7735 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7736 $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, $limit, 'minwidth100', '', '', 1, array(), false, $excludeids);
7737 $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7738 $out .= '</form>';
7739 } else {
7740 if ($selected) {
7741 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
7742 $soc = new Societe($this->db);
7743 $soc->fetch((int) $selected);
7744 $out .= $soc->getNomUrl(0, '');
7745 } else {
7746 $out .= '<span class="opacitymedium">' . $textifnothirdparty . '</span>';
7747 }
7748 }
7749
7750 if ($nooutput) {
7751 return $out;
7752 } else {
7753 print $out;
7754 }
7755
7756 return '';
7757 }
7758
7759 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7760
7769 public function select_currency($selected = '', $htmlname = 'currency_id')
7770 {
7771 // phpcs:enable
7772 print $this->selectCurrency($selected, $htmlname);
7773 }
7774
7784 public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
7785 {
7786 global $langs, $user;
7787
7788 $langs->loadCacheCurrencies('');
7789
7790 $out = '';
7791
7792 if ($selected == 'euro' || $selected == 'euros') {
7793 $selected = 'EUR'; // Pour compatibilite
7794 }
7795
7796 $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="' . $htmlname . '" id="' . $htmlname . '">';
7797 if ($useempty) {
7798 $out .= '<option value="-1" selected></option>';
7799 }
7800 foreach ($langs->cache_currencies as $code_iso => $currency) {
7801 $labeltoshow = $currency['label'];
7802 if ($mode == 1) {
7803 $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso . ')</span>';
7804 } elseif ($mode == 2) {
7805 $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso.' - '.$langs->getCurrencySymbol($code_iso) . ')</span>';
7806 } else {
7807 $labeltoshow .= ' <span class="opacitymedium">(' . $langs->getCurrencySymbol($code_iso) . ')</span>';
7808 }
7809
7810 if ($selected && $selected == $code_iso) {
7811 $out .= '<option value="' . $code_iso . '" selected data-html="' . dol_escape_htmltag($labeltoshow) . '">';
7812 } else {
7813 $out .= '<option value="' . $code_iso . '" data-html="' . dol_escape_htmltag($labeltoshow) . '">';
7814 }
7815 $out .= dol_string_nohtmltag($labeltoshow);
7816 $out .= '</option>';
7817 }
7818 $out .= '</select>';
7819 if ($user->admin) {
7820 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
7821 }
7822
7823 // Make select dynamic
7824 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
7825 $out .= ajax_combobox($htmlname);
7826
7827 return $out;
7828 }
7829
7842 public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = 'maxwidth200 widthcentpercentminusx')
7843 {
7844 global $conf, $langs;
7845
7846 $langs->loadCacheCurrencies(''); // Load ->cache_currencies
7847
7848 $TCurrency = array();
7849
7850 $sql = "SELECT code FROM " . $this->db->prefix() . "multicurrency";
7851 $sql .= " WHERE entity IN ('" . getEntity('multicurrency') . "')";
7852 if ($filter) {
7853 $sql .= forgeSQLFromUniversalSearchCriteria($filter);
7854 }
7855 $resql = $this->db->query($sql);
7856 if ($resql) {
7857 while ($obj = $this->db->fetch_object($resql)) {
7858 $TCurrency[$obj->code] = $obj->code;
7859 }
7860 }
7861
7862 $out = '';
7863 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
7864 if ($useempty) {
7865 $out .= '<option value="">&nbsp;</option>';
7866 }
7867 // If company current currency not in table, we add it into list. Should always be available.
7868 if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
7869 $TCurrency[$conf->currency] = $conf->currency;
7870 }
7871 if (count($TCurrency) > 0) {
7872 foreach ($langs->cache_currencies as $code_iso => $currency) {
7873 if (isset($TCurrency[$code_iso])) {
7874 if (!empty($selected) && $selected == $code_iso) {
7875 $out .= '<option value="' . $code_iso . '" selected="selected">';
7876 } else {
7877 $out .= '<option value="' . $code_iso . '">';
7878 }
7879
7880 $out .= $currency['label'];
7881 $out .= ' (' . $langs->getCurrencySymbol($code_iso) . ')';
7882 $out .= '</option>';
7883 }
7884 }
7885 }
7886
7887 $out .= '</select>';
7888
7889 // Make select dynamic
7890 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
7891 $out .= ajax_combobox($htmlname);
7892
7893 return $out;
7894 }
7895
7896 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7897
7904 public function load_cache_vatrates($country_code)
7905 {
7906 // phpcs:enable
7907 global $langs, $user;
7908
7909 $num = count($this->cache_vatrates);
7910 if ($num > 0) {
7911 return $num; // Cache already loaded
7912 }
7913
7914 dol_syslog(__METHOD__, LOG_DEBUG);
7915
7916 $sql = "SELECT t.rowid, t.type_vat, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly, t.einvoice_vatex";
7917 $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
7918 $sql .= " WHERE t.fk_pays = c.rowid";
7919 $sql .= " AND t.active > 0";
7920 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
7921 $sql .= " AND c.code IN (" . $this->db->sanitize($country_code, 1) . ")";
7922 $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
7923
7924 $resql = $this->db->query($sql);
7925 if ($resql) {
7926 $num = $this->db->num_rows($resql);
7927 if ($num) {
7928 for ($i = 0; $i < $num; $i++) {
7929 $obj = $this->db->fetch_object($resql);
7930
7931 $tmparray = array();
7932 $tmparray['rowid'] = (int) $obj->rowid;
7933 $tmparray['type_vat'] = ($obj->type_vat <= 0 ? 0 : $obj->type_vat); // Some version have type_vat corrupted with value -1
7934 $tmparray['code'] = $obj->code;
7935 $tmparray['txtva'] = $obj->taux;
7936 $tmparray['nprtva'] = $obj->recuperableonly;
7937 $tmparray['localtax1'] = $obj->localtax1;
7938 $tmparray['localtax1_type'] = $obj->localtax1_type;
7939 $tmparray['localtax2'] = $obj->localtax2;
7940 $tmparray['localtax2_type'] = $obj->localtax1_type;
7941 $tmparray['einvoice_vatex'] = $obj->einvoice_vatex;
7942
7943 $tmparray['label'] = $obj->taux . '%' . ($obj->code ? ' (' . $obj->code . ')' : ''); // Label must contains only 0-9 , . % or *
7944 $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
7945 $positiverates = '';
7946 if ($obj->taux) {
7947 $positiverates .= ($positiverates ? '/' : '') . $obj->taux;
7948 }
7949 if ($obj->localtax1) {
7950 $positiverates .= ($positiverates ? '/' : '') . $obj->localtax1;
7951 }
7952 if ($obj->localtax2) {
7953 $positiverates .= ($positiverates ? '/' : '') . $obj->localtax2;
7954 }
7955 if (empty($positiverates)) {
7956 $positiverates = '0';
7957 }
7958 $tmparray['labelpositiverates'] = $positiverates . ($obj->code ? ' (' . $obj->code . ')' : ''); // Must never be used as key, only label
7959
7960 $this->cache_vatrates[$obj->rowid] = $tmparray;
7961 }
7962
7963 return $num;
7964 } else {
7965 $this->error = '<span class="error">';
7966 $this->error .= $langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code);
7967 $reg = array();
7968 if (!empty($user) && $user->admin && preg_match('/\'(..)\'/', $country_code, $reg)) {
7969 $langs->load("errors");
7970 $new_country_code = $reg[1];
7971 $country_id = dol_getIdFromCode($this->db, $new_country_code, 'c_country', 'code', 'rowid');
7972 $this->error .= '<br>'.$langs->trans("ErrorFixThisHere", DOL_URL_ROOT.'/admin/dict.php?id=10'.($country_id > 0 ? '&countryidforinsert='.$country_id : ''));
7973 }
7974 $this->error .= '</span>';
7975 return -1;
7976 }
7977 } else {
7978 $this->error = '<span class="error">' . $this->db->error() . '</span>';
7979 return -2;
7980 }
7981 }
7982
7983 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7984
8007 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)
8008 {
8009 // phpcs:enable
8010 global $langs, $mysoc, $hookmanager;
8011
8012 $langs->load('errors');
8013
8014 $return = '';
8015 // Bypass the default method
8016 $hookmanager->initHooks(array('commonobject'));
8017 $info_bits == 1 ? $is_npr = 1 : $is_npr = 0;
8018 $parameters = array(
8019 'htmlname' => $htmlname,
8020 'selectedrate' => $selectedrate,
8021 'seller' => $societe_vendeuse,
8022 'buyer' => $societe_acheteuse,
8023 'idprod' => $idprod,
8024 'is_npr' => $is_npr,
8025 'type' => $type,
8026 'options_only' => $options_only,
8027 'mode' => $mode,
8028 'type_vat' => $type_vat
8029 );
8030 $reshook = $hookmanager->executeHooks('load_tva', $parameters);
8031 if ($reshook > 0) {
8032 return $hookmanager->resPrint;
8033 } elseif ($reshook === 0) {
8034 $return .= $hookmanager->resPrint;
8035 }
8036
8037 // Define defaultnpr, defaultttx and defaultcode
8038 $defaultnpr = ($info_bits & 0x01);
8039 $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
8040 $defaulttx = str_replace('*', '', $selectedrate);
8041 $defaultcode = '';
8042 $reg = array();
8043 if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
8044 $defaultcode = $reg[1];
8045 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
8046 }
8047 //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
8048
8049 // Check parameters
8050 if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
8051 if ($societe_vendeuse->id == $mysoc->id) {
8052 $return .= '<span class="error">' . $langs->trans("ErrorYourCountryIsNotDefined") . '</span>';
8053 } else {
8054 $return .= '<span class="error">' . $langs->trans("ErrorSupplierCountryIsNotDefined") . '</span>';
8055 }
8056 return $return;
8057 }
8058
8059 //var_dump($societe_acheteuse);
8060 //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";
8061 //exit;
8062
8063 // Define list of countries to use to search VAT rates to show
8064 // First we defined code_country to use to find list.
8065 // country_code must be a c_country ISO code (e.g. 'FR', 'CH'). In some setups it may hold a
8066 // country label (e.g. 'Suisse') instead, which would make the "c.code IN (...)" lookup done by
8067 // load_cache_vatrates() match nothing and wrongly force the VAT rate to 0%. A valid ISO code is
8068 // always 2 chars, so when the value is not a well formed ISO code (empty or a label) and we have
8069 // a valid country id, we recover the ISO code from the authoritative country id. This way we do
8070 // not run any SQL on each page access when we already have a valid ISO code.
8071 $sellercountrycode = is_object($societe_vendeuse) ? $societe_vendeuse->country_code : $mysoc->country_code;
8072 $sellercountryid = is_object($societe_vendeuse) ? $societe_vendeuse->country_id : $mysoc->country_id;
8073 if ((int) $sellercountryid > 0 && strlen((string) $sellercountrycode) != 2) {
8074 $tmpcountrycode = dol_getIdFromCode($this->db, (string) $sellercountryid, 'c_country', 'rowid', 'code');
8075 if (!empty($tmpcountrycode) && !is_numeric($tmpcountrycode)) {
8076 $sellercountrycode = $tmpcountrycode;
8077 }
8078 }
8079 $code_country = "'" . $sellercountrycode . "'"; // Pour compatibilite ascendente
8080
8081 if ($societe_vendeuse == $mysoc && getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) { // If option to have vat for end customer for services is on
8082 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
8083 // If SERVICE_ARE_ECOMMERCE_200238EC=1 combo list vat rate of purchaser and seller countries
8084 // If SERVICE_ARE_ECOMMERCE_200238EC=2 combo list only the vat rate of the purchaser country
8085 $selectVatComboMode = getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC');
8086 if (is_object($societe_vendeuse) && is_object($societe_acheteuse) && isInEEC($societe_vendeuse) && isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()) {
8087 // We also add the buyer country code
8088 if (is_numeric($type)) {
8089 if ($type == 1) { // We know product is a service
8090 switch ($selectVatComboMode) {
8091 case '1':
8092 $code_country .= ",'" . $societe_acheteuse->country_code . "'";
8093 break;
8094 case '2':
8095 $code_country = "'" . $societe_acheteuse->country_code . "'";
8096 break;
8097 }
8098 }
8099 } elseif (!$idprod) { // We don't know type of product
8100 switch ($selectVatComboMode) {
8101 case '1':
8102 $code_country .= ",'" . $societe_acheteuse->country_code . "'";
8103 break;
8104 case '2':
8105 $code_country = "'" . $societe_acheteuse->country_code . "'";
8106 break;
8107 }
8108 } else {
8109 $prodstatic = new Product($this->db);
8110 $prodstatic->fetch($idprod);
8111 if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
8112 $code_country .= ",'" . $societe_acheteuse->country_code . "'";
8113 }
8114 }
8115 }
8116 }
8117
8118 // Now we load the list of VAT
8119 $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
8120
8121 // Keep only the VAT qualified for $type_vat (0 means all types)
8122 $arrayofvatrates = array();
8123 foreach ($this->cache_vatrates as $cachevalue) {
8124 if ($type_vat == 0 || empty($cachevalue['type_vat']) || $cachevalue['type_vat'] == $type_vat) {
8125 $arrayofvatrates[] = $cachevalue;
8126 }
8127 }
8128
8129 $num = count($arrayofvatrates);
8130 if ($num > 0) {
8131 // Define the vat rate to preselect (if defaulttx not forced so is -1 or '')
8132 if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
8133 // Define a default thirdparty to use if the seller or buyer is not defined
8134 $tmpthirdparty = new Societe($this->db);
8135 $tmpthirdparty->country_code = $mysoc->country_code;
8136
8137 $defaulttx = get_default_tva(is_object($societe_vendeuse) ? $societe_vendeuse : $tmpthirdparty, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
8138 $defaultnpr = get_default_npr(is_object($societe_vendeuse) ? $societe_vendeuse : $tmpthirdparty, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
8139
8140 if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
8141 $defaultcode = $reg[1];
8142 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
8143 }
8144 if (empty($defaulttx)) {
8145 $defaultnpr = 0;
8146 }
8147 }
8148
8149 // If we fails to find a default vat rate, we take the last one in list
8150 // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
8151 if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
8152 if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
8153 // We take the last one found in list
8154 $defaulttx = $arrayofvatrates[$num - 1]['txtva'];
8155 } else {
8156 // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
8157 $defaulttx = '';
8158 if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
8159 $defaulttx = getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS');
8160 }
8161 if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
8162 $defaultcode = $reg[1];
8163 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
8164 }
8165 }
8166 }
8167
8168 // Disabled is true if the seller is not subject to VAT
8169 $disabled = false;
8170 $title = '';
8171 if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && empty($societe_vendeuse->tva_assuj)) {
8172 // 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
8173 // EXPENSEREPORT_OVERRIDE_VAT is a strange option that allow to override/enable VAT regardless of sellet vat option - needed for expense report if
8174 // expense report used for business expenses instead of using supplier invoices (but this is a very bad idea !)
8175 if (!getDolGlobalString('EXPENSEREPORT_OVERRIDE_VAT')) {
8176 $title = ' title="' . dol_escape_htmltag($langs->trans('VATIsNotUsed')) . '"';
8177 $disabled = true;
8178 }
8179 }
8180
8181 if (!$options_only) {
8182 $return .= '<select class="flat valignmiddle minwidth75imp maxwidth100 right" id="' . $htmlname . '" name="' . $htmlname . '"' . ($disabled ? ' disabled' : '') . $title . '>';
8183 }
8184
8185 $selectedfound = false;
8186 foreach ($arrayofvatrates as $rate) {
8187 // Keep only 0 if seller is not subject to VAT
8188 if ($disabled && $rate['txtva'] != 0) {
8189 continue;
8190 }
8191
8192 // Define key to use into select list
8193 $key = $rate['txtva'];
8194 $key .= $rate['nprtva'] ? '*' : '';
8195 if ($mode > 0 && $rate['code']) {
8196 $key .= ' (' . $rate['code'] . ')';
8197 }
8198 if ($mode < 0) {
8199 $key = $rate['rowid'];
8200 }
8201
8202 $return .= '<option value="' . $key . '" data-vatid="'.$rate['rowid'].'"';
8203 if (!$selectedfound) {
8204 if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
8205 if ($defaultcode == $rate['code']) {
8206 $return .= ' selected';
8207 $selectedfound = true;
8208 }
8209 } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
8210 $return .= ' selected';
8211 $selectedfound = true;
8212 }
8213 }
8214 $return .= '>';
8215
8216 // Show label of VAT
8217 if ($mysoc->country_code == 'IN' || getDolGlobalString('MAIN_VAT_LABEL_IS_POSITIVE_RATES')) {
8218 // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
8219 $return .= $rate['labelpositiverates'];
8220 } else {
8221 // Simple label
8222 $return .= vatrate($rate['label']);
8223 }
8224
8225 //$return.=($rate['code']?' '.$rate['code']:'');
8226 $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
8227
8228 $return .= '</option>';
8229 }
8230
8231 if (!$options_only) {
8232 $return .= '</select>';
8233 //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
8234 }
8235 } else {
8236 $return .= $this->error;
8237 }
8238
8239 $this->num = $num;
8240 return $return;
8241 }
8242
8243
8244 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8245
8270 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 = '')
8271 {
8272 // phpcs:enable
8273 dol_syslog(__METHOD__ . ': using select_date is deprecated. Use selectDate instead.', LOG_WARNING);
8274 $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
8275 if (!empty($nooutput)) {
8276 return $retstring;
8277 }
8278 print $retstring;
8279
8280 return '';
8281 }
8282
8298 public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
8299 {
8300 global $langs;
8301
8302 $ret = $this->selectDate($set_time, $prefix . '_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
8303 if ($forcenewline) {
8304 $ret .= '<br>';
8305 }
8306 $ret .= $this->selectDate($set_time_end, $prefix . '_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
8307 return $ret;
8308 }
8309
8338 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 = '')
8339 {
8340 global $conf, $langs;
8341
8342 if ($gm === 'auto') {
8343 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
8344 }
8345
8346 $retstring = '';
8347
8348 if ($prefix == '') {
8349 $prefix = 're';
8350 }
8351 if ($h == '') {
8352 $h = 0;
8353 }
8354 if ($m == '') {
8355 $m = 0;
8356 }
8357 $emptydate = 0;
8358 $emptyhours = 0;
8359 if ($stepminutes <= 0 || $stepminutes > 30) {
8360 $stepminutes = 1;
8361 }
8362 if ($empty == 1) {
8363 $emptydate = 1;
8364 $emptyhours = 1;
8365 }
8366 if ($empty == 2) {
8367 $emptydate = 0;
8368 $emptyhours = 1;
8369 }
8370 $orig_set_time = $set_time;
8371
8372 if ($set_time === '' && $emptydate == 0) {
8373 include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
8374 if ($gm == 'tzuser' || $gm == 'tzuserrel') {
8375 $set_time = dol_now($gm);
8376 } else {
8377 $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
8378 }
8379 }
8380
8381 // Analysis of the preselected date
8382 $reg = array();
8383 $shour = '';
8384 $smin = '';
8385 $ssec = '';
8386 if (!empty($set_time) && preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', (string) $set_time, $reg)) { // deprecated usage
8387 // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
8388 $syear = (!empty($reg[1]) ? $reg[1] : '');
8389 $smonth = (!empty($reg[2]) ? $reg[2] : '');
8390 $sday = (!empty($reg[3]) ? $reg[3] : '');
8391 $shour = (!empty($reg[4]) ? $reg[4] : '');
8392 $smin = (!empty($reg[5]) ? $reg[5] : '');
8393 } elseif (strval($set_time) != '' && $set_time != -1) {
8394 // set_time est un timestamps (0 possible)
8395 $syear = dol_print_date($set_time, "%Y", $gm);
8396 $smonth = dol_print_date($set_time, "%m", $gm);
8397 $sday = dol_print_date($set_time, "%d", $gm);
8398 if ($orig_set_time != '') {
8399 $shour = dol_print_date($set_time, "%H", $gm);
8400 $smin = dol_print_date($set_time, "%M", $gm);
8401 $ssec = dol_print_date($set_time, "%S", $gm);
8402 }
8403 } else {
8404 // Date est '' ou vaut -1
8405 $syear = '';
8406 $smonth = '';
8407 $sday = '';
8408 $shour = getDolGlobalString('MAIN_DEFAULT_DATE_HOUR', ($h == -1 ? '23' : ''));
8409 $smin = getDolGlobalString('MAIN_DEFAULT_DATE_MIN', ($h == -1 ? '59' : ''));
8410 $ssec = getDolGlobalString('MAIN_DEFAULT_DATE_SEC', ($h == -1 ? '59' : ''));
8411 }
8412 if ($h == 3 || $h == 4) {
8413 $shour = '';
8414 }
8415 if ($m == 3) {
8416 $smin = '';
8417 }
8418
8419 $nowgmt = dol_now('gmt');
8420 //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
8421
8422 // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
8423 $usecalendar = 'combo';
8424 if (!empty($conf->use_javascript_ajax) && (!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') != "none")) {
8425 $usecalendar = ((!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') == 'eldy') ? 'jquery' : getDolGlobalString("MAIN_POPUP_CALENDAR"));
8426 }
8427 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
8428 // If we use a text browser or screen reader, we use the 'combo' date selector
8429 $usecalendar = 'html';
8430 }
8431
8432 if ($d) {
8433 // Show date with popup
8434 if ($usecalendar != 'combo') {
8435 // Set $format and $formatjs and $formatjquery
8436 $reduceformat = (!empty($conf->dol_optimize_smallscreen) ? 1 : 0); // Test on original $format param.
8437 if ($reduceformat) {
8438 $format = str_replace('%Y', '%y', $langs->transnoentitiesnoconv("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
8439 $formatjslong = $langs->transnoentitiesnoconv("FormatDateShortJavaInput"); // don't trust the name
8440 $formatjs = str_replace('yyyy', 'yy', $langs->transnoentitiesnoconv("FormatDateShortJavaInput"));
8441 $formatjquery = str_replace('yyyy', 'yy', $langs->trans("FormatDateShortJQueryInput"));
8442 } else {
8443 $format = $langs->transnoentitiesnoconv("FormatDateShortInput"); // FormatDateShortInput for dol_print_date is same than FormatDateShortJavaInput for javascript
8444 $formatjslong = $langs->transnoentitiesnoconv("FormatDateShortJavaInput"); // don't trust the name
8445 $formatjs = $langs->transnoentitiesnoconv("FormatDateShortJavaInput"); // FormatDateShortInput for dol_print_date is same than FormatDateShortJavaInput for javascript
8446 $formatjquery = $langs->trans("FormatDateShortJQueryInput");
8447 }
8448
8449 // Set formatted_date (for example: '%d/%m/%Y', '%m-%d-%y', ...
8450 $formatted_date = '';
8451 if (strval($set_time) != '' && $set_time != -1) {
8452 $formatted_date = dol_print_date($set_time, $format, $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
8453 }
8454
8455 // Calendrier popup version eldy
8456 if ($usecalendar == "eldy") {
8457 // To have this manager working back, you must retrieve all functions showDP child found into the lib_head.js of v4 for example
8458 // and load the js that contains them so the call of showDP will works.
8459 /*
8460 // Input area to enter date manually
8461 $retstring .= '<!-- datepicker usecalendar=eldy --><input id="' . $prefix . '" name="' . $prefix . '" type="text" class="maxwidthdate center" maxlength="11" value="' . $formatted_date . '"';
8462 $retstring .= ($disabled ? ' disabled' : '');
8463 $retstring .= ' onChange="dpChangeDay(\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($formatjslong")) . '\'); "'; // FormatDateShortInput for dol_print_date is same than FormatDateShortJavaInput for javascript
8464 $retstring .= ' autocomplete="off">';
8465
8466 // Icon calendar
8467 $retstringbuttom = '';
8468 if (!$disabled) {
8469 $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons"';
8470 $base = DOL_URL_ROOT . '/core/';
8471 $retstringbuttom .= ' onClick="showDP(\'' . dol_escape_js($base) . '\',\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($langs->trans("FormatDateShortJavaInput")) . '\',\'' . dol_escape_js($langs->defaultlang) . '\');"';
8472 $retstringbuttom .= '>' . img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink paddingright"') . '</button>';
8473 } else {
8474 $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink paddingright"') . '</button>';
8475 }
8476 $retstring = $retstringbuttom . $retstring;
8477
8478 $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
8479 $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
8480 $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
8481 */
8482 } elseif ($usecalendar == 'jquery' || $usecalendar == 'html') {
8483 if (!$disabled && $usecalendar != 'html') {
8484 // Output javascript for datepicker
8485 $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (idate('Y') - 100));
8486 $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (idate('Y') + 100));
8487
8488 $retstring .= '<!-- datepicker usecalendar='.$usecalendar.' --><script nonce="' . getNonce() . '" type="text/javascript">';
8489 $retstring .= "$(function(){ $('#" . $prefix . "').datepicker({
8490 dateFormat: '" . dol_escape_js($formatjquery) . "',
8491 autoclose: true,
8492 todayHighlight: true,
8493 yearRange: '" . $minYear . ":" . $maxYear . "',";
8494 if (!empty($conf->dol_use_jmobile)) {
8495 $retstring .= "
8496 beforeShow: function (input, datePicker) {
8497 input.disabled = true;
8498 },
8499 onClose: function (dateText, datePicker) {
8500 this.disabled = false;
8501 },
8502 ";
8503 }
8504 // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
8505 if (!getDolGlobalString('MAIN_POPUP_CALENDAR_ON_FOCUS')) {
8506 $buttonImage = $calendarpicto ?: DOL_URL_ROOT . "/theme/" . dol_escape_js($conf->theme) . "/img/object_calendarday.png";
8507 $retstring .= "
8508 showOn: 'button', /* both has problem with autocompletion */
8509 buttonImage: '" . $buttonImage . "',
8510 buttonImageOnly: true";
8511 }
8512 $retstring .= "
8513 }) });";
8514 $retstring .= "</script>";
8515 }
8516
8517 // Input area to enter date manually
8518 $retstring .= '<div class="nowraponall inline-block divfordateinput">';
8519 $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="'.($usecalendar == 'html' ? "date" : "text").'" class="maxwidthdate'.(getDolUserString('MAIN_OPTIMIZEFORTEXTBROWSER') ? ' textbrowser' : '').' center" maxlength="11" value="'.$formatted_date.'"';
8520 $retstring .= ($disabled ? ' disabled' : '');
8521 $retstring .= ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '');
8522 $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
8523 $retstring .= ' autocomplete="off">';
8524
8525 // Icon calendar
8526 if ($disabled) {
8527 $retstringbutton = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink ui-datepicker-notrigger"') . '</button>';
8528 $retstring .= $retstringbutton;
8529 }
8530
8531 $retstring .= '</div>';
8532 $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
8533 $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
8534 $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
8535 } else {
8536 $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
8537 }
8538 } else {
8539 // Show date with combo selects
8540 // Day
8541 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50imp" id="' . $prefix . 'day" name="' . $prefix . 'day">';
8542
8543 if ($emptydate || $set_time == -1) {
8544 $retstring .= '<option value="0" selected>&nbsp;</option>';
8545 }
8546
8547 for ($day = 1; $day <= 31; $day++) {
8548 $retstring .= '<option value="' . $day . '"' . ($day == $sday ? ' selected' : '') . '>' . $day . '</option>';
8549 }
8550
8551 $retstring .= "</select>";
8552
8553 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'month" name="' . $prefix . 'month">';
8554 if ($emptydate || $set_time == -1) {
8555 $retstring .= '<option value="0" selected>&nbsp;</option>';
8556 }
8557
8558 // Month
8559 for ($month = 1; $month <= 12; $month++) {
8560 $retstring .= '<option value="' . $month . '"' . ($month == $smonth ? ' selected' : '') . '>';
8561 $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
8562 $retstring .= "</option>";
8563 }
8564 $retstring .= "</select>";
8565
8566 // Year
8567 if ($emptydate || $set_time == -1) {
8568 $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 . '">';
8569 } else {
8570 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'year" name="' . $prefix . 'year">';
8571
8572 $syear = (int) $syear;
8573 for ($year = $syear - 10; $year < (int) $syear + 10; $year++) {
8574 $retstring .= '<option value="' . $year . '"' . ($year == $syear ? ' selected' : '') . '>' . $year . '</option>';
8575 }
8576 $retstring .= "</select>\n";
8577 }
8578 }
8579 }
8580
8581 if ($d && $h) {
8582 $retstring .= (($h == 2 || $h == 4) ? '<br>' : ' ');
8583 $retstring .= '<span class="nowraponall">';
8584 }
8585
8586 if ($h) {
8587 $hourstart = 0;
8588 $hourend = 24;
8589 if ($openinghours != '') {
8590 $openinghours = explode(',', $openinghours);
8591 $hourstart = $openinghours[0];
8592 $hourend = $openinghours[1];
8593 if ($hourend < $hourstart) {
8594 $hourend = $hourstart;
8595 }
8596 }
8597
8598 // Show hour
8599 $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
8600 $retstring .= ($fullday ? $fullday . 'hour' : '') . '" id="' . $prefix . 'hour" name="' . $prefix . 'hour">';
8601 if ($emptyhours) {
8602 $retstring .= '<option value="-1">&nbsp;</option>';
8603 }
8604 for ($hour = $hourstart; $hour < $hourend; $hour++) {
8605 if (strlen($hour) < 2) {
8606 $hour = "0" . $hour;
8607 }
8608 $retstring .= '<option value="' . $hour . '"' . (($hour == $shour) ? ' selected' : '') . '>' . $hour;
8609 $retstring .= '</option>';
8610 }
8611 $retstring .= '</select>';
8612
8613 if ($disabled) {
8614 $retstring .= '<input type="hidden" id="' . $prefix . 'hour" name="' . $prefix . 'hour" value="' . $shour . '">' . "\n";
8615 }
8616 if ($m) {
8617 $retstring .= ":";
8618 }
8619 }
8620
8621 if ($m) {
8622 // Show minutes
8623 $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
8624 $retstring .= ($fullday ? $fullday . 'min' : '') . '" id="' . $prefix . 'min" name="' . $prefix . 'min">';
8625 if ($emptyhours) {
8626 $retstring .= '<option value="-1">&nbsp;</option>';
8627 }
8628 for ($min = 0; $min < 60; $min += $stepminutes) {
8629 $min_str = sprintf("%02d", $min);
8630 $retstring .= '<option value="' . $min_str . '"' . (($min_str == $smin) ? ' selected' : '') . '>' . $min_str . '</option>';
8631 }
8632 $retstring .= '</select>';
8633 if ($disabled) {
8634 $retstring .= '<input type="hidden" id="' . $prefix . 'min" name="' . $prefix . 'min" value="' . $smin . '">' . "\n";
8635 }
8636 // Add also seconds
8637 $retstring .= '<input type="hidden" name="' . $prefix . 'sec" value="' . $ssec . '">';
8638 }
8639
8640 if ($d && $h) {
8641 $retstring .= '</span>';
8642 }
8643
8644 // Add a "Now" link
8645 if (!empty($conf->use_javascript_ajax) && $addnowlink && !$disabled) {
8646 // Script which will be inserted in the onClick of the "Now" link
8647 $reset_scripts = "";
8648 if ($addnowlink == 2) { // local computer time
8649 // pad add leading 0 on numbers
8650 $reset_scripts .= "Number.prototype.pad = function(size) {
8651 var s = String(this);
8652 while (s.length < (size || 2)) {s = '0' + s;}
8653 return s;
8654 };
8655 var d = new Date();";
8656 }
8657
8658 // Generate the date part, depending on the use or not of the javascript calendar
8659 if ($addnowlink == 1) { // server time expressed in user time setup
8660 $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
8661 $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
8662 $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
8663 $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
8664 } elseif ($addnowlink == 2) {
8665 /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
8666 * This break application for foreign languages.
8667 $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
8668 $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
8669 $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
8670 $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
8671 */
8672 $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
8673 $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
8674 $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
8675 $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
8676 }
8677 /*if ($usecalendar == "eldy")
8678 {
8679 $base=DOL_URL_ROOT.'/core/';
8680 $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
8681 }
8682 else
8683 {
8684 $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
8685 $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
8686 $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
8687 }*/
8688 // Update the hour part
8689 if ($h) {
8690 if ($fullday) {
8691 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
8692 }
8693 //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
8694 if ($addnowlink == 1) {
8695 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
8696 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
8697 } elseif ($addnowlink == 2) {
8698 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(d.getHours().pad());';
8699 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
8700 }
8701
8702 if ($fullday) {
8703 $reset_scripts .= ' } ';
8704 }
8705 }
8706 // Update the minute part
8707 if ($m) {
8708 if ($fullday) {
8709 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
8710 }
8711 //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
8712 if ($addnowlink == 1) {
8713 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
8714 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
8715 } elseif ($addnowlink == 2) {
8716 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(d.getMinutes().pad());';
8717 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
8718 }
8719 if ($fullday) {
8720 $reset_scripts .= ' } ';
8721 }
8722 }
8723 // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
8724 if ($reset_scripts && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
8725 $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonNow" type="button" name="_useless" value="now" onClick="' . $reset_scripts . '">';
8726 $retstring .= $langs->trans("Now");
8727 $retstring .= '</button> ';
8728 }
8729 }
8730
8731 // Add a "Plus one hour" link
8732 if ($conf->use_javascript_ajax && $addplusone && !$disabled) {
8733 // Script which will be inserted in the onClick of the "Add plusone" link
8734 $reset_scripts = "";
8735
8736 // Generate the date part, depending on the use or not of the javascript calendar
8737 $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel') . '\');';
8738 $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
8739 $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
8740 $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
8741 // Update the hour part
8742 if ($h) {
8743 if ($fullday) {
8744 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
8745 }
8746 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
8747 if ($fullday) {
8748 $reset_scripts .= ' } ';
8749 }
8750 }
8751 // Update the minute part
8752 if ($m) {
8753 if ($fullday) {
8754 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
8755 }
8756 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
8757 if ($fullday) {
8758 $reset_scripts .= ' } ';
8759 }
8760 }
8761 // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
8762 if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
8763 $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="' . $reset_scripts . '">';
8764 $retstring .= $langs->trans("DateStartPlusOne");
8765 $retstring .= '</button> ';
8766 }
8767 }
8768
8769 // Add a link to set data
8770 if ($conf->use_javascript_ajax && !empty($adddateof) && !$disabled) {
8771 if (!is_array($adddateof)) {
8772 $arrayofdateof = array(array('adddateof' => $adddateof, 'labeladddateof' => $labeladddateof));
8773 } else {
8774 $arrayofdateof = $adddateof;
8775 }
8776 foreach ($arrayofdateof as $valuedateof) {
8777 $tmpadddateof = empty($valuedateof['adddateof']) ? 0 : $valuedateof['adddateof'];
8778 $tmplabeladddateof = empty($valuedateof['labeladddateof']) ? '' : $valuedateof['labeladddateof'];
8779 $tmparray = dol_getdate($tmpadddateof);
8780 if (empty($tmplabeladddateof)) {
8781 $tmplabeladddateof = $langs->trans("DateInvoice");
8782 }
8783 $reset_scripts = 'console.log(\'Click on now link\'); ';
8784 $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($tmpadddateof, 'dayinputnoreduce').'\');';
8785 $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.$tmparray['mday'].'\');';
8786 $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.$tmparray['mon'].'\');';
8787 $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.$tmparray['year'].'\');';
8788 $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="'.$reset_scripts.'">'.$tmplabeladddateof.'</button>';
8789 }
8790 }
8791
8792 return $retstring;
8793 }
8794
8804 public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array(), $morecss = 'minwidth75 maxwidth100')
8805 {
8806 global $langs;
8807
8808 $TDurationTypes = $this->getDurationTypes($langs);
8809
8810 // Removed undesired duration types
8811 foreach ($excludetypes as $value) {
8812 unset($TDurationTypes[$value]);
8813 }
8814
8815 $retstring = '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_' . $prefix . 'type_duration" name="' . $prefix . 'type_duration">';
8816 foreach ($TDurationTypes as $key => $typeduration) {
8817 $retstring .= '<option value="' . $key . '"';
8818 if ($key == $selected) {
8819 $retstring .= " selected";
8820 }
8821 $retstring .= ">" . $typeduration . "</option>";
8822 }
8823 $retstring .= "</select>";
8824
8825 $retstring .= ajax_combobox('select_' . $prefix . 'type_duration');
8826
8827 return $retstring;
8828 }
8829
8830 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8831
8845 public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
8846 {
8847 // phpcs:enable
8848 global $langs;
8849
8850 $retstring = '<span class="nowraponall">';
8851
8852 $hourSelected = '';
8853 $minSelected = '';
8854
8855 // Hours
8856 if ($iSecond != '') {
8857 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
8858
8859 $hourSelected = convertSecondToTime($iSecond, 'allhour');
8860 $minSelected = convertSecondToTime($iSecond, 'min');
8861 }
8862
8863 if ($typehour == 'select') {
8864 $retstring .= '<select class="flat" id="select_' . $prefix . 'hour" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . '>';
8865 for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
8866 $retstring .= '<option value="' . $hour . '"';
8867 if (is_numeric($hourSelected) && $hourSelected == $hour) {
8868 $retstring .= " selected";
8869 }
8870 $retstring .= ">" . $hour . "</option>";
8871 }
8872 $retstring .= "</select>";
8873 } elseif ($typehour == 'text' || $typehour == 'textselect') {
8874 $retstring .= '<input placeholder="' . $langs->trans('HourShort') . '" type="number" min="0" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputhour right" value="' . (($hourSelected != '') ? ((int) $hourSelected) : '') . '">';
8875 } else {
8876 return 'BadValueForParameterTypeHour';
8877 }
8878
8879 if ($typehour != 'text') {
8880 $retstring .= ' ' . $langs->trans('HourShort');
8881 } else {
8882 $retstring .= '<span class="">:</span>';
8883 }
8884
8885 // Minutes
8886 if ($minunderhours) {
8887 $retstring .= '<br>';
8888 } else {
8889 if ($typehour != 'text') {
8890 $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
8891 }
8892 }
8893
8894 if ($typehour == 'select' || $typehour == 'textselect') {
8895 $retstring .= '<select class="flat" id="select_' . $prefix . 'min" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . '>';
8896 $step = getDolGlobalInt('MAIN_DURATION_STEP');
8897 $duration_step = ($step > 0) ? $step : 5;
8898 for ($min = 0; $min <= 59; $min += $duration_step) {
8899 $retstring .= '<option value="' . $min . '"';
8900 if (is_numeric($minSelected) && $minSelected == $min) {
8901 $retstring .= ' selected';
8902 }
8903 $retstring .= '>' . $min . '</option>';
8904 }
8905 $retstring .= "</select>";
8906 } elseif ($typehour == 'text') {
8907 $retstring .= '<input placeholder="' . $langs->trans('MinuteShort') . '" type="number" min="0" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputminute right" value="' . (($minSelected != '') ? ((int) $minSelected) : '') . '">';
8908 }
8909
8910 if ($typehour != 'text') {
8911 $retstring .= ' ' . $langs->trans('MinuteShort');
8912 }
8913
8914 $retstring .= "</span>";
8915
8916 if (!empty($nooutput)) {
8917 return $retstring;
8918 }
8919
8920 print $retstring;
8921
8922 return '';
8923 }
8924
8944 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)
8945 {
8946 global $langs, $conf;
8947
8948 $out = '';
8949
8950 // check parameters
8951 if (is_null($ajaxoptions)) {
8952 $ajaxoptions = array();
8953 }
8954
8955 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
8956 $placeholder = '';
8957
8958 if ($selected && empty($selected_input_value)) {
8959 require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
8960 $tickettmpselect = new Ticket($this->db);
8961 $tickettmpselect->fetch((int) $selected);
8962 $selected_input_value = $tickettmpselect->ref;
8963 unset($tickettmpselect);
8964 }
8965
8966 $urloption = '';
8967 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
8968
8969 if (empty($hidelabel)) {
8970 $out .= $langs->trans("RefOrLabel") . ' : ';
8971 } elseif ($hidelabel > 1) {
8972 $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
8973 if ($hidelabel == 2) {
8974 $out .= img_picto($langs->trans("Search"), 'search');
8975 }
8976 }
8977 $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
8978 if ($hidelabel == 3) {
8979 $out .= img_picto($langs->trans("Search"), 'search');
8980 }
8981 } else {
8982 $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, '', $status, 0, $showempty, $forcecombo, $morecss);
8983 }
8984
8985 if (empty($nooutput)) {
8986 print $out;
8987 } else {
8988 return $out;
8989 }
8990 return '';
8991 }
8992
8993
9010 public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
9011 {
9012 global $langs;
9013
9014 $out = '';
9015 $outarray = array();
9016
9017 $selectFields = " p.rowid, p.ref, p.message";
9018
9019 $sql = "SELECT ";
9020 $sql .= $this->db->sanitize($selectFields, 0, 0, 1);
9021 $sql .= " FROM " . $this->db->prefix() . "ticket as p";
9022 $sql .= ' WHERE p.entity IN (' . getEntity('ticket') . ')';
9023
9024 // Add criteria on ref/label
9025 if ($filterkey != '') {
9026 $sql .= ' AND (';
9027 $prefix = getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if TICKET_DONOTSEARCH_ANYWHERE is on
9028 // For natural search
9029 $search_crit = explode(' ', $filterkey);
9030 $i = 0;
9031 if (count($search_crit) > 1) {
9032 $sql .= "(";
9033 }
9034 foreach ($search_crit as $crit) {
9035 if ($i > 0) {
9036 $sql .= " AND ";
9037 }
9038 $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.subject LIKE '" . $this->db->escape($prefix . $crit) . "%'";
9039 $sql .= ")";
9040 $i++;
9041 }
9042 if (count($search_crit) > 1) {
9043 $sql .= ")";
9044 }
9045 $sql .= ')';
9046 }
9047
9048 $sql .= $this->db->plimit($limit, 0);
9049
9050 // Build output string
9051 dol_syslog(get_class($this) . "::selectTicketsList search tickets", LOG_DEBUG);
9052 $result = $this->db->query($sql);
9053 if ($result) {
9054 require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
9055 require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php';
9056
9057 $num = $this->db->num_rows($result);
9058
9059 $events = array();
9060
9061 if (!$forcecombo) {
9062 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
9063 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt('TICKET_USE_SEARCH_TO_SELECT'));
9064 }
9065
9066 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
9067
9068 $textifempty = '';
9069 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
9070 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
9071 if (getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
9072 if ($showempty && !is_numeric($showempty)) {
9073 $textifempty = $langs->trans($showempty);
9074 } else {
9075 $textifempty .= $langs->trans("All");
9076 }
9077 } else {
9078 if ($showempty && !is_numeric($showempty)) {
9079 $textifempty = $langs->trans($showempty);
9080 }
9081 }
9082 if ($showempty) {
9083 $out .= '<option value="0" selected>' . $textifempty . '</option>';
9084 }
9085
9086 $i = 0;
9087 while ($num && $i < $num) {
9088 $opt = '';
9089 $optJson = array();
9090 $objp = $this->db->fetch_object($result);
9091
9092 $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
9093 '@phan-var-force array{key:string,value:mixed,type:int} $optJson';
9094 // Add new entry
9095 // "key" value of json key array is used by jQuery automatically as selected value
9096 // "label" value of json key array is used by jQuery automatically as text for combo box
9097 $out .= $opt;
9098 array_push($outarray, $optJson);
9099
9100 $i++;
9101 }
9102
9103 $out .= '</select>';
9104
9105 $this->db->free($result);
9106
9107 if (empty($outputmode)) {
9108 return $out;
9109 }
9110 return $outarray;
9111 } else {
9112 dol_print_error($this->db);
9113 }
9114
9115 return array();
9116 }
9117
9129 protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
9130 {
9131 $outkey = '';
9132 $outref = '';
9133 $outtype = '';
9134
9135 $outkey = $objp->rowid;
9136 $outref = $objp->ref;
9137
9138 $opt = '<option value="' . $objp->rowid . '"';
9139 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
9140 $opt .= '>';
9141 $opt .= $objp->ref;
9142 $objRef = $objp->ref;
9143 if (!empty($filterkey) && $filterkey != '') {
9144 $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
9145 }
9146
9147 $opt .= "</option>\n";
9148 $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
9149 }
9150
9170 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)
9171 {
9172 global $langs, $conf;
9173
9174 $out = '';
9175
9176 // check parameters
9177 if (is_null($ajaxoptions)) {
9178 $ajaxoptions = array();
9179 }
9180
9181 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
9182 $placeholder = '';
9183
9184 if ($selected && empty($selected_input_value)) {
9185 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
9186 $projecttmpselect = new Project($this->db);
9187 $projecttmpselect->fetch((int) $selected);
9188 $selected_input_value = $projecttmpselect->ref;
9189 unset($projecttmpselect);
9190 }
9191
9192 $urloption = '';
9193 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
9194
9195 if (empty($hidelabel)) {
9196 $out .= $langs->trans("RefOrLabel") . ' : ';
9197 } elseif ($hidelabel > 1) {
9198 $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
9199 if ($hidelabel == 2) {
9200 $out .= img_picto($langs->trans("Search"), 'search');
9201 }
9202 }
9203 $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
9204 if ($hidelabel == 3) {
9205 $out .= img_picto($langs->trans("Search"), 'search');
9206 }
9207 } else {
9208 $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, '', $status, 0, $showempty, $forcecombo, $morecss);
9209 }
9210
9211 if (empty($nooutput)) {
9212 print $out;
9213 } else {
9214 return $out;
9215 }
9216 return '';
9217 }
9218
9235 public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
9236 {
9237 global $langs, $conf;
9238
9239 $out = '';
9240 $outarray = array();
9241
9242 $selectFields = " p.rowid, p.ref";
9243
9244 $sql = "SELECT ";
9245 $sql .= $this->db->sanitize($selectFields, 0, 0, 1);
9246 $sql .= " FROM " . $this->db->prefix() . "projet as p";
9247 $sql .= ' WHERE p.entity IN (' . getEntity('project') . ')';
9248
9249 // Add criteria on ref/label
9250 if ($filterkey != '') {
9251 $sql .= ' AND (';
9252 $prefix = !getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
9253 // For natural search
9254 $search_crit = explode(' ', $filterkey);
9255 $i = 0;
9256 if (count($search_crit) > 1) {
9257 $sql .= "(";
9258 }
9259 foreach ($search_crit as $crit) {
9260 if ($i > 0) {
9261 $sql .= " AND ";
9262 }
9263 $sql .= "p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%'";
9264 $sql .= "";
9265 $i++;
9266 }
9267 if (count($search_crit) > 1) {
9268 $sql .= ")";
9269 }
9270 $sql .= ')';
9271 }
9272
9273 $sql .= $this->db->plimit($limit, 0);
9274
9275 // Build output string
9276 dol_syslog(get_class($this) . "::selectProjectsList search projects", LOG_DEBUG);
9277 $result = $this->db->query($sql);
9278 if ($result) {
9279 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
9280 require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
9281
9282 $num = $this->db->num_rows($result);
9283
9284 $events = array();
9285
9286 if (!$forcecombo) {
9287 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
9288 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt('PROJECT_USE_SEARCH_TO_SELECT'));
9289 }
9290
9291 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
9292
9293 $textifempty = '';
9294 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
9295 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
9296 if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
9297 if ($showempty && !is_numeric($showempty)) {
9298 $textifempty = $langs->trans($showempty);
9299 } else {
9300 $textifempty .= $langs->trans("All");
9301 }
9302 } else {
9303 if ($showempty && !is_numeric($showempty)) {
9304 $textifempty = $langs->trans($showempty);
9305 }
9306 }
9307 if ($showempty) {
9308 $out .= '<option value="0" selected>' . $textifempty . '</option>';
9309 }
9310
9311 $i = 0;
9312 while ($num && $i < $num) {
9313 $opt = '';
9314 $optJson = array();
9315 $objp = $this->db->fetch_object($result);
9316
9317 $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
9318 // Add new entry
9319 // "key" value of json key array is used by jQuery automatically as selected value
9320 // "label" value of json key array is used by jQuery automatically as text for combo box
9321 $out .= $opt;
9322 array_push($outarray, $optJson);
9323
9324 $i++;
9325 }
9326
9327 $out .= '</select>';
9328
9329 $this->db->free($result);
9330
9331 if (empty($outputmode)) {
9332 return $out;
9333 }
9334 return $outarray;
9335 } else {
9336 dol_print_error($this->db);
9337 }
9338
9339 return array();
9340 }
9341
9355 protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
9356 {
9357 $outkey = '';
9358 $outref = '';
9359 $outtype = '';
9360
9361 $label = $objp->label;
9362
9363 $outkey = $objp->rowid;
9364 $outref = $objp->ref;
9365 $outlabel = $objp->label;
9366 $outtype = $objp->fk_product_type;
9367
9368 $opt = '<option value="' . $objp->rowid . '"';
9369 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
9370 $opt .= '>';
9371 $opt .= $objp->ref;
9372 $objRef = $objp->ref;
9373 if (!empty($filterkey) && $filterkey != '') {
9374 $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', (string) $objRef, 1);
9375 }
9376
9377 $opt .= "</option>\n";
9378 $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
9379 }
9380
9381
9402 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())
9403 {
9404 global $langs, $conf;
9405
9406 $out = '';
9407
9408 // check parameters
9409 if (is_null($ajaxoptions)) {
9410 $ajaxoptions = array();
9411 }
9412
9413 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
9414 $placeholder = '';
9415
9416 if ($selected && empty($selected_input_value)) {
9417 require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
9418 $adherenttmpselect = new Adherent($this->db);
9419 $adherenttmpselect->fetch((int) $selected);
9420 $selected_input_value = $adherenttmpselect->ref;
9421 unset($adherenttmpselect);
9422 }
9423
9424 $urloption = '';
9425
9426 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
9427
9428 if (empty($hidelabel)) {
9429 $out .= $langs->trans("RefOrLabel") . ' : ';
9430 } elseif ($hidelabel > 1) {
9431 $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
9432 if ($hidelabel == 2) {
9433 $out .= img_picto($langs->trans("Search"), 'search');
9434 }
9435 }
9436 $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
9437 if ($hidelabel == 3) {
9438 $out .= img_picto($langs->trans("Search"), 'search');
9439 }
9440 } else {
9441 $filterkey = '';
9442
9443 $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss, $excludeids);
9444 }
9445
9446 if (empty($nooutput)) {
9447 print $out;
9448 } else {
9449 return $out;
9450 }
9451 return '';
9452 }
9453
9471 public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $excludeids = array())
9472 {
9473 global $langs, $conf;
9474
9475 $out = '';
9476 $outarray = array();
9477
9478 $selectFields = " p.rowid, p.ref, p.firstname, p.lastname, p.fk_adherent_type";
9479
9480 $sql = "SELECT ";
9481 $sql .= $this->db->sanitize($selectFields, 0, 0, 1);
9482 $sql .= " FROM " . $this->db->prefix() . "adherent as p";
9483 $sql .= ' WHERE p.entity IN (' . getEntity('adherent') . ')';
9484
9485 // Add criteria on ref/label
9486 if ($filterkey != '') {
9487 $sql .= ' AND (';
9488 $prefix = !getDolGlobalString('MEMBER_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
9489 // For natural search
9490 $search_crit = explode(' ', $filterkey);
9491 $i = 0;
9492 if (count($search_crit) > 1) {
9493 $sql .= "(";
9494 }
9495 foreach ($search_crit as $crit) {
9496 if ($i > 0) {
9497 $sql .= " AND ";
9498 }
9499 $sql .= "(p.firstname LIKE '" . $this->db->escape($prefix . $crit) . "%'";
9500 $sql .= " OR p.lastname LIKE '" . $this->db->escape($prefix . $crit) . "%')";
9501 $i++;
9502 }
9503 if (count($search_crit) > 1) {
9504 $sql .= ")";
9505 }
9506 $sql .= ')';
9507 }
9508 if ($status != -1) {
9509 $sql .= ' AND statut = ' . ((int) $status);
9510 }
9511 if (!empty($excludeids)) {
9512 $sql .= " AND p.rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeids)) . ")";
9513 }
9514 $sql .= $this->db->plimit($limit, 0);
9515
9516 // Build output string
9517 dol_syslog(get_class($this) . "::selectMembersList search adherents", LOG_DEBUG);
9518 $result = $this->db->query($sql);
9519 if ($result) {
9520 require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
9521 require_once DOL_DOCUMENT_ROOT . '/core/lib/member.lib.php';
9522
9523 $num = $this->db->num_rows($result);
9524
9525 $events = array();
9526
9527 if (!$forcecombo) {
9528 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
9529 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt('PROJECT_USE_SEARCH_TO_SELECT'));
9530 }
9531
9532 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
9533
9534 $textifempty = '';
9535 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
9536 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
9537 if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
9538 if ($showempty && !is_numeric($showempty)) {
9539 $textifempty = $langs->trans($showempty);
9540 } else {
9541 $textifempty .= $langs->trans("All");
9542 }
9543 } else {
9544 if ($showempty && !is_numeric($showempty)) {
9545 $textifempty = $langs->trans($showempty);
9546 }
9547 }
9548 if ($showempty) {
9549 $out .= '<option value="-1" selected>' . $textifempty . '</option>';
9550 }
9551
9552 $i = 0;
9553 while ($num && $i < $num) {
9554 $opt = '';
9555 $optJson = array();
9556 $objp = $this->db->fetch_object($result);
9557
9558 $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
9559
9560 // Add new entry
9561 // "key" value of json key array is used by jQuery automatically as selected value
9562 // "label" value of json key array is used by jQuery automatically as text for combo box
9563 $out .= $opt;
9564 array_push($outarray, $optJson);
9565
9566 $i++;
9567 }
9568
9569 $out .= '</select>';
9570
9571 $this->db->free($result);
9572
9573 if (empty($outputmode)) {
9574 return $out;
9575 }
9576 return $outarray;
9577 } else {
9578 dol_print_error($this->db);
9579 }
9580
9581 return array();
9582 }
9583
9595 protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
9596 {
9597 $outkey = '';
9598 $outlabel = '';
9599 $outtype = '';
9600
9601 $outkey = $objp->rowid;
9602 $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
9603 $outtype = $objp->fk_adherent_type;
9604
9605 $opt = '<option value="' . $objp->rowid . '"';
9606 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
9607 $opt .= '>';
9608 if (!empty($filterkey) && $filterkey != '') {
9609 $outlabel = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $outlabel, 1);
9610 }
9611 $opt .= $outlabel;
9612 $opt .= "</option>\n";
9613
9614 $optJson = array('key' => $outkey, 'value' => $outlabel, 'type' => $outtype);
9615 }
9616
9638 public function selectForForms($objectdesc, $htmlname, $preSelectedValue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '', $objectfield = '')
9639 {
9640 global $conf, $extrafields, $user, $hookmanager, $action;
9641
9642 // Example of common usage for a link to a thirdparty
9643
9644 // We got this in a modulebuilder form of "MyObject" of module "mymodule".
9645 // 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
9646 // $objectdesc = 'Societe'
9647 // $objectfield = Method 1: 'myobject@mymodule:fk_soc' ('fk_soc' is code to retrieve myobject->fields['fk_soc'])
9648 // 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__))" ...)
9649
9650 // We got this when showing an extrafields on resource that is a link to societe
9651 // 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
9652 // $objectdesc = 'Societe'
9653 // $objectfield = Method 1: 'resource:options_link_to_societe'
9654 // Method 2 recommended (it can be the array): array("type"=>'Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))" ...)
9655
9656 // With old usage:
9657 // $objectdesc = 'Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))'
9658 // $objectfield = ''
9659
9660 //var_dump($objectdesc.' '.$objectfield);
9661 //debug_print_backtrace();
9662
9663 $objectdescorig = $objectdesc;
9664 $objecttmp = null;
9665 $InfoFieldList = array();
9666 $classname = '';
9667 $filter = ''; // Ensure filter has value (for static analysis)
9668 $sortfield = ''; // Ensure filter has value (for static analysis)
9669
9670 if (is_array($objectfield)) { // objectfield is an array
9671 $objectdesc = $objectfield['type'];
9672 $objectdesc = preg_replace('/^integer[^:]*:/', '', $objectdesc);
9673 } 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.
9674 // Example: $objectfield = 'product:options_package' or 'myobject@mymodule:options_myfield'
9675 $tmparray = explode(':', $objectfield);
9676
9677 // Get instance of object from $element
9678 $objectforfieldstmp = fetchObjectByElement(0, strtolower($tmparray[0]));
9679
9680 if (is_object($objectforfieldstmp)) {
9681 $objectdesc = '';
9682
9683 $reg = array();
9684 if (preg_match('/^options_(.*)$/', $tmparray[1], $reg)) {
9685 // For a property in extrafields
9686 $key = $reg[1];
9687 // fetch optionals attributes and labels
9688 $extrafields->fetch_name_optionals_label($objectforfieldstmp->table_element);
9689
9690 if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key]) && $extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key] == 'link') {
9691 if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options'])) {
9692 $tmpextrafields = array_keys($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options']);
9693 $objectdesc = $tmpextrafields[0];
9694 }
9695 }
9696 } else {
9697 // For a property in ->fields
9698 if (array_key_exists($tmparray[1], $objectforfieldstmp->fields)) {
9699 $objectdesc = $objectforfieldstmp->fields[$tmparray[1]]['type'];
9700 $objectdesc = preg_replace('/^integer[^:]*:/', '', $objectdesc);
9701 }
9702 }
9703 }
9704 }
9705
9706 if ($objectdesc) {
9707 // Example of value for $objectdesc:
9708 // Bom:bom/class/bom.class.php:0:t.status=1
9709 // Bom:bom/class/bom.class.php:0:t.status=1:ref
9710 // Bom:bom/class/bom.class.php:0:(t.status:=:1) OR (t.field2:=:2):ref
9711 $InfoFieldList = explode(":", $objectdesc, 4);
9712 $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
9713 $reg = array();
9714 if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
9715 $InfoFieldList[4] = $reg[1]; // take the sort field
9716 }
9717 $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
9718
9719 $classname = $InfoFieldList[0];
9720 $classpath = empty($InfoFieldList[1]) ? '' : $InfoFieldList[1];
9721 //$addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
9722 $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
9723 $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
9724
9725 // Load object according to $id and $element
9726 $objecttmp = fetchObjectByElement(0, strtolower($InfoFieldList[0]));
9727
9728 // Fallback to another solution to get $objecttmp
9729 if (empty($objecttmp) && !empty($classpath)) {
9730 dol_include_once($classpath);
9731
9732 if ($classname && class_exists($classname)) {
9733 $objecttmp = new $classname($this->db);
9734 }
9735 }
9736 }
9737
9738 // Make some replacement in $filter. May not be used if we used the ajax mode with $objectfield. In such a case
9739 // we propagate the $objectfield and not the filter and replacement is done by the ajax/selectobject.php component.
9740 $sharedentities = (is_object($objecttmp) && property_exists($objecttmp, 'element')) ? getEntity($objecttmp->element) : strtolower($classname);
9741 $filter = str_replace(
9742 array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
9743 array($conf->entity, $sharedentities, $user->id),
9744 $filter
9745 );
9746
9747 if (!is_object($objecttmp)) {
9748 dol_syslog('selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.(is_array($objectfield) ? 'array' : $objectfield).', objectdesc='.$objectdesc, LOG_WARNING);
9749 return 'selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.(is_array($objectfield) ? 'array' : $objectfield).', objectdesc='.$objectdesc;
9750 }
9751 '@phan-var-force CommonObject $objecttmp';
9753 //var_dump($filter);
9754 $prefixforautocompletemode = $objecttmp->element;
9755 if ($prefixforautocompletemode == 'societe') {
9756 $prefixforautocompletemode = 'company';
9757 }
9758 if ($prefixforautocompletemode == 'product') {
9759 $prefixforautocompletemode = 'produit';
9760 }
9761
9762 $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
9763
9764 dol_syslog(get_class($this) . "::selectForForms filter=" . $filter, LOG_DEBUG);
9765
9766 // Generate the combo HTML component
9767 $out = '';
9768 if (!empty($conf->use_javascript_ajax) && getDolGlobalString($confkeyforautocompletemode) && !$forcecombo) {
9769 // No immediate load of all database
9770 $placeholder = '';
9771
9772 if ($preSelectedValue && empty($selected_input_value)) {
9773 $objecttmp->fetch($preSelectedValue);
9774 $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
9775
9776 $oldValueForShowOnCombobox = 0;
9777 foreach ($objecttmp->fields as $fieldK => $fielV) {
9778 if (!array_key_exists('showoncombobox', $fielV) || !$fielV['showoncombobox'] || empty($objecttmp->$fieldK)) {
9779 continue;
9780 }
9781
9782 if (!$oldValueForShowOnCombobox) {
9783 $selected_input_value = '';
9784 }
9785
9786 $selected_input_value .= $oldValueForShowOnCombobox ? ' - ' : '';
9787 $selected_input_value .= $objecttmp->$fieldK;
9788 $oldValueForShowOnCombobox = empty($fielV['showoncombobox']) ? 0 : $fielV['showoncombobox'];
9789 }
9790 }
9791
9792 // Set url and param to call to get json of the search results
9793 $urlforajaxcall = DOL_URL_ROOT . '/core/ajax/selectobject.php';
9794 $urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1&objectdesc=' . urlencode($objectdescorig) . (is_scalar($objectfield) ? '&objectfield='.urlencode($objectfield) : '') . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
9795 //$urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1'.(is_scalar($objectfield) ? '&objectfield='.urlencode($objectfield) : '') . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
9796
9797 // Hook 'selectForFormsListUrl' - Added to allow modules to modify the AJAX URL
9798 $parameters = array(
9799 'urloption' => $urloption,
9800 'object' => $objecttmp,
9801 'htmlname' => $htmlname,
9802 'filter' => $filter,
9803 'searchkey' => $searchkey,
9804 );
9805 $reshook = $hookmanager->executeHooks('selectForFormsListUrl', $parameters, $objecttmp, $action);
9806 if (!empty($reshook)) {
9807 $urloption = $hookmanager->resPrint;
9808 $hookmanager->resPrint = '';
9809 }
9810
9811 // Activate the auto complete using ajax call.
9812 $out .= ajax_autocompleter((string) $preSelectedValue, $htmlname, $urlforajaxcall, $urloption, getDolGlobalInt($confkeyforautocompletemode), 0);
9813 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
9814 $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) . '"' : '') . ' />';
9815 } else {
9816 // Immediate load of table record.
9817 $out .= $this->selectForFormsList($objecttmp, $htmlname, $preSelectedValue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
9818 }
9819
9820 return $out;
9821 }
9822
9823
9845 public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '', $sortorder = 'ASC')
9846 {
9847 global $langs, $user, $hookmanager;
9848
9849 //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
9850
9851 $prefixforautocompletemode = $objecttmp->element;
9852 if ($prefixforautocompletemode == 'societe') {
9853 $prefixforautocompletemode = 'company';
9854 }
9855 $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
9856
9857 $fieldstoshow = '';
9858 if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
9859 $tmpfieldstoshow = '';
9860 foreach ($objecttmp->fields as $key => $val) {
9861 if (! (int) dol_eval((string) $val['enabled'], 1, 1, '1')) {
9862 continue;
9863 }
9864 if (!empty($val['showoncombobox'])) {
9865 $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '') . 't.' . $key;
9866 }
9867 }
9868 if ($tmpfieldstoshow) {
9869 $fieldstoshow = $tmpfieldstoshow;
9870 }
9871 } elseif ($objecttmp->element === 'category') {
9872 $fieldstoshow = 't.label';
9873 } else {
9874 // For backward compatibility
9875 $objecttmp->fields['ref'] = array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'position' => 10, 'visible' => 4, 'showoncombobox' => 1);
9876 }
9877
9878 if (empty($fieldstoshow)) {
9879 if (!empty($objecttmp->parent_element)) {
9880 $fieldstoshow = 'o.ref';
9881 if (empty($sortfield)) {
9882 $sortfield = 'o.ref';
9883 }
9884 if (in_array($objecttmp->element, ['commandedet', 'propaldet', 'facturedet', 'expeditiondet'])) {
9885 $fieldstoshow .= ',p.ref AS p_ref,p.label,t.description';
9886 $sortfield .= ', p.ref';
9887 }
9888 } elseif (isset($objecttmp->fields['ref'])) {
9889 $fieldstoshow = 't.ref';
9890 } else {
9891 $langs->load("errors");
9892 $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
9893 return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
9894 }
9895 }
9896
9897 $out = '';
9898 $outarray = array();
9899 $tmparray = array();
9900
9901 $num = 0;
9902
9903 $sanitizedfieldstoshow = $fieldstoshow;
9904
9905 // Search data
9906 $sql = "SELECT t.rowid, " . $sanitizedfieldstoshow . " FROM " . $this->db->prefix() . $this->db->sanitize($objecttmp->table_element) . " as t";
9907 if (!empty($objecttmp->isextrafieldmanaged)) {
9908 $extrafieldTable = $objecttmp->table_element;
9909 if ($extrafieldTable == 'categorie') {
9910 $extrafieldTable = 'categories'; // For compatibility
9911 }
9912 $sql .= " LEFT JOIN " . $this->db->prefix() . $this->db->sanitize($extrafieldTable) . "_extrafields as e ON t.rowid = e.fk_object";
9913 }
9914 if (!empty($objecttmp->parent_element)) { // If parent_element is defined
9915 '@phan-var-force CommonObjectLine $objecttmp';
9916 $parent_properties = getElementProperties($objecttmp->parent_element);
9917 // @phan-suppress-next-line SqlInjection
9918 $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);
9919 }
9920 if (!empty($objecttmp->parent_element) && in_array($objecttmp->parent_element, ['commande', 'propal', 'facture', 'expedition'])) {
9921 $sql .= " LEFT JOIN " . $this->db->prefix() . "product as p ON p.rowid = t.fk_product";
9922 }
9923 if (!empty($objecttmp->ismultientitymanaged)) {
9924 if ($objecttmp->ismultientitymanaged == 1) { // @phan-suppress-current-line PhanPluginEmptyStatementIf
9925 // No need to join/link another table
9926 }
9927 if (!is_numeric($objecttmp->ismultientitymanaged)) {
9928 $tmparray = explode('@', $objecttmp->ismultientitymanaged);
9929 $sql .= " INNER JOIN " . $this->db->prefix() . $this->db->sanitize($tmparray[1]) . " as parenttable ON parenttable.rowid = t." . $this->db->sanitize($tmparray[0]);
9930 }
9931 }
9932
9933 // Add where from hooks
9934 $parameters = array(
9935 'object' => $objecttmp,
9936 'htmlname' => $htmlname,
9937 'filter' => $filter,
9938 'searchkey' => $searchkey
9939 );
9940
9941 $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
9942 if (!empty($hookmanager->resPrint)) {
9943 $sql .= $hookmanager->resPrint;
9944 } else {
9945 $sql .= " WHERE 1=1";
9946
9947 // If table need a multientity restriction
9948 if (!empty($objecttmp->ismultientitymanaged)) {
9949 if ($objecttmp->ismultientitymanaged == 1) {
9950 $sql .= " AND t.entity IN (" . getEntity($objecttmp->element) . ")";
9951 }
9952 if (!is_numeric($objecttmp->ismultientitymanaged)) {
9953 $sql .= " AND parenttable.entity = t." . $this->db->sanitize($tmparray[0]);
9954 }
9955 // If the parent table is llx_societe and user is not an external user (a more robust test done later for external users),
9956 // then we must also check that user has permissions
9957 if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
9958 if (!$user->hasRight('societe', 'client', 'voir') && empty($user->socid)) {
9959 $sql .= " AND EXISTS (SELECT sc.rowid FROM ".$this->db->prefix() . "societe_commerciaux as sc";
9960 $sql .= " WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $user->id).")";
9961 }
9962 }
9963 }
9964
9965 // If user is external user, we must also make a test on thirdparty
9966 if (!empty($user->socid)) {
9967 if ($objecttmp->element == 'societe') {
9968 $sql .= " AND t.rowid = " . ((int) $user->socid);
9969 } elseif (!empty($objecttmp->fields['fk_soc']) || !empty($objecttmp->fields['t.fk_soc']) || property_exists($objecttmp, 'fk_soc') || property_exists($objecttmp, 'socid')) {
9970 $sql .= " AND t.fk_soc = " . ((int) $user->socid);
9971 } elseif (!empty($objecttmp->parent_element)) {
9972 $tmpparent = fetchObjectByElement(0, $objecttmp->parent_element, '', 1);
9973 if (is_object($tmpparent) && (!empty($tmpparent->fields['fk_soc']) || !empty($tmpparent->fields['t.fk_soc']) || property_exists($tmpparent, 'fk_soc') || property_exists($tmpparent, 'socid'))) {
9974 $sql .= " AND o.fk_soc = " . ((int) $user->socid);
9975 }
9976 }
9977 }
9978
9979 $splittedfieldstoshow = explode(',', $fieldstoshow);
9980 foreach ($splittedfieldstoshow as &$field2) {
9981 if (is_numeric($pos = strpos($field2, ' '))) {
9982 $field2 = substr($field2, 0, $pos);
9983 }
9984 }
9985 if ($searchkey != '') {
9986 $sql .= natural_search($splittedfieldstoshow, $searchkey);
9987 }
9988
9989 if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:>:'20160101')"
9990 $errormessage = '';
9991 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
9992 if ($errormessage) {
9993 return 'Error forging a SQL request from an universal criteria: ' . $errormessage;
9994 }
9995 }
9996 }
9997 $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, $sortorder);
9998 //$sql.=$this->db->plimit($limit, 0);
9999 //print $sql;
10000
10001 // Build output string
10002 $resql = $this->db->query($sql);
10003 if ($resql) {
10004 // Construct $out and $outarray
10005 $out .= '<select id="' . $htmlname . '" class="flat minwidth100' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ($moreparams ? ' ' . $moreparams : '') . ' name="' . $htmlname . '">' . "\n";
10006
10007 // 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
10008 $textifempty = '&nbsp;';
10009
10010 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
10011 if (getDolGlobalInt($confkeyforautocompletemode)) {
10012 if ($showempty && !is_numeric($showempty)) {
10013 $textifempty = $langs->trans($showempty);
10014 } else {
10015 $textifempty .= $langs->trans("All");
10016 }
10017 }
10018 if ($showempty) {
10019 $out .= '<option value="-1">' . $textifempty . '</option>' . "\n";
10020 }
10021
10022 $num = $this->db->num_rows($resql);
10023 $i = 0;
10024 if ($num) {
10025 while ($i < $num) {
10026 $obj = $this->db->fetch_object($resql);
10027 $label = '';
10028 $labelhtml = '';
10029 $tmparray = explode(',', $fieldstoshow);
10030 $oldvalueforshowoncombobox = 0;
10031 foreach ($tmparray as $key => $val) {
10032 $val = preg_replace('/(t|p|o)\./', '', $val);
10033 $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
10034 $labelhtml .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
10035 $label .= $obj->$val;
10036 $labelhtml .= $obj->$val;
10037
10038 $oldvalueforshowoncombobox = empty($objecttmp->fields[$val]['showoncombobox']) ? 0 : $objecttmp->fields[$val]['showoncombobox'];
10039 }
10040 if (empty($outputmode)) {
10041 if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
10042 $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>';
10043 } else {
10044 $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
10045 }
10046 } else {
10047 array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label));
10048 }
10049
10050 $i++;
10051 if (($i % 10) == 0) {
10052 $out .= "\n";
10053 }
10054 }
10055 }
10056
10057 $out .= '</select>' . "\n";
10058
10059 if (!$forcecombo) {
10060 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
10061 $out .= ajax_combobox($htmlname, array(), getDolGlobalInt($confkeyforautocompletemode, 0));
10062 }
10063 } else {
10064 dol_print_error($this->db);
10065 }
10066
10067 $this->result = array('nbofelement' => $num);
10068
10069 if ($outputmode) {
10070 return $outarray;
10071 }
10072 return $out;
10073 }
10074
10085 public static function radio($htmlName, $radioItems, $selected = '', $moreGlobalParams = [])
10086 {
10087 // Default parameters for each radio input
10088 $defaultParams = [
10089 'disabled' => false,
10090 'attr' => [
10091 'type' => 'radio',
10092 'name' => $htmlName,
10093 ],
10094 'attrLabel' => [],
10095 'labelIsHtml' => false
10096 ];
10097
10098 // Merge global parameters with defaults
10099 $params = array_merge_recursive_distinct($defaultParams, $moreGlobalParams);
10100
10101 $out = '';
10102 if (!empty($radioItems)) {
10103 foreach ($radioItems as $key => $item) {
10104 // Normalize item to array structure if it's a simple string
10105 if (!is_array($item)) {
10106 $item = [
10107 'attr' => [
10108 'value' => $key,
10109 ],
10110 'label' => $item
10111 ];
10112 }
10113
10114 // Default properties for individual item
10115 $defaultItem = [
10116 'attr' => [
10117 'value' => !isset($item['attr']['value']) ? $key : '',
10118 ],
10119 'label' => '',
10120 ];
10121
10122 // Merge defaults with global params and item-specific properties
10123 $defaultItem = array_merge_recursive_distinct($params, $defaultItem);
10124 $item = array_merge_recursive_distinct($defaultItem, $item);
10125
10126 // Determine if this radio should be checked
10127 if ((is_array($selected) && in_array($item['attr']['value'], $selected, true)) || $selected === $item['attr']['value']) {
10128 $item['attr']['checked'] = true;
10129 }
10130
10131 // Build HTML attributes for input and label
10132 $inputAttributes = implode(' ', commonHtmlAttributeBuilder($item['attr']));
10133 $labelAttributes = implode(' ', commonHtmlAttributeBuilder($item['attrLabel']));
10134
10135 // prevent accidental Xss todo : escape $item['label'] but html friendly compatible
10136 $text = $item['labelIsHtml'] ? $item['label'] : htmlspecialchars($item['label'], ENT_QUOTES | ENT_SUBSTITUTE);
10137
10138 // Generate HTML
10139 $out .= '<label ' . $labelAttributes . '><input ' . $inputAttributes . ' /> ' . $text . '</label> ';
10140 }
10141 }
10142
10143 return $out;
10144 }
10145
10146
10170 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)
10171 {
10172 global $conf, $langs;
10173
10174 // Do we want a multiselect ?
10175 //$jsbeautify = 0;
10176 //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
10177 $jsbeautify = 1;
10178
10179 if ($value_as_key) {
10180 $array = array_combine($array, $array);
10181 }
10182
10183 '@phan-var-force array{label:string,data-html:string,disable?:int<0,1>,css?:string} $array'; // Array combine breaks information
10184
10185 $out = '';
10186
10187 if ($addjscombo < 0) {
10188 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
10189 $addjscombo = 1;
10190 } else {
10191 $addjscombo = 0;
10192 }
10193 }
10194 $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
10195 $out .= '<select id="' . preg_replace('/^\./', '', $idname) . '" ' . ($disabled ? 'disabled="disabled" ' : '') . 'class="flat ' . (preg_replace('/^\./', '', $htmlname)) . ($morecss ? ' ' . $morecss : '') . ' selectformat"';
10196 $out .= ' name="' . preg_replace('/^\./', '', $htmlname) . '" ' . ($moreparam ? $moreparam : '');
10197 $out .= '>'."\n";
10198
10199 if ($show_empty) {
10200 $textforempty = ' ';
10201 if (!empty($conf->use_javascript_ajax)) {
10202 $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
10203 }
10204 if (!is_numeric($show_empty)) {
10205 $textforempty = $show_empty;
10206 }
10207 $out .= '<option class="optiongrey" ' . ($moreparamonempty ? $moreparamonempty . ' ' : '') . 'value="' . (((int) $show_empty) < 0 ? $show_empty : -1) . '"' . ($id == $show_empty ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
10208 }
10209 if (is_array($array)) {
10210 // Translate
10211 if ($translate) {
10212 foreach ($array as $key => $value) {
10213 if (!is_array($value)) {
10214 $array[$key] = $langs->trans($value);
10215 } else {
10216 $array[$key]['label'] = $langs->trans($value['label']);
10217 }
10218 }
10219 }
10220 // Sort
10221 if ($sort == 'ASC') {
10222 asort($array);
10223 } elseif ($sort == 'DESC') {
10224 arsort($array);
10225 }
10226
10227 foreach ($array as $key => $tmpvalue) {
10228 if (is_array($tmpvalue)) {
10229 $value = $tmpvalue['label'];
10230 //$valuehtml = empty($tmpvalue['data-html']) ? $value : $tmpvalue['data-html'];
10231 $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
10232 $style = empty($tmpvalue['css']) ? '' : ' class="' . $tmpvalue['css'] . '"';
10233 } else {
10234 $value = $tmpvalue;
10235 //$valuehtml = $tmpvalue;
10236 $disabled = '';
10237 $style = '';
10238 }
10239 if (!empty($disablebademail)) {
10240 if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
10241 || ($disablebademail == 2 && preg_match('/---/', $value))) {
10242 $disabled = ' disabled';
10243 $style = ' class="warning"';
10244 }
10245 }
10246 if ($key_in_label) {
10247 if (empty($nohtmlescape)) {
10248 $selectOptionValue = dol_escape_htmltag($key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value));
10249 } else {
10250 $selectOptionValue = $key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value);
10251 }
10252 } else {
10253 if (empty($nohtmlescape)) {
10254 $selectOptionValue = dol_escape_htmltag($maxlen ? dol_trunc($value, $maxlen) : $value);
10255 } else {
10256 $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
10257 }
10258 if ($value == '' || $value == '-') {
10259 $selectOptionValue = '&nbsp;';
10260 }
10261 }
10262 $out .= '<option value="' . $key . '"';
10263 $out .= $style . $disabled;
10264 $out .= is_array($tmpvalue) && !empty($tmpvalue['parent']) ? ' parent="' . dolPrintHTMLForAttribute($tmpvalue['parent']) . '"' : '';
10265 if (is_array($id)) {
10266 if (in_array($key, $id) && !$disabled) {
10267 $out .= ' selected'; // To preselect a value
10268 }
10269 } else {
10270 $id = (string) $id; // if $id = 0, then $id = '0'
10271 if ($id != '' && (($id == (string) $key) || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
10272 $out .= ' selected'; // To preselect a value
10273 }
10274 }
10275
10276 if (is_array($tmpvalue)) {
10277 foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
10278 if ($keyforvalue == 'labelhtml') {
10279 $keyforvalue = 'data-html';
10280 }
10281 if (preg_match('/^data-/', $keyforvalue)) { // The best solution if you want to use HTML values into the list is to use data-html.
10282 $out .= ' '.dol_escape_htmltag($keyforvalue).'="'.dol_escape_htmltag($valueforvalue).'"';
10283 }
10284 }
10285 } elseif (!empty($nohtmlescape)) { // deprecated. Use instead the previous cas, an array with 'data-html', 'data-xxx' ... to use HTML content in the select
10286 $out .= ' data-html="' . dol_escape_htmltag($selectOptionValue) . '"';
10287 }
10288
10289 $out .= '>';
10290 $out .= $selectOptionValue;
10291 $out .= "</option>\n";
10292 }
10293 }
10294 $out .= "</select>";
10295
10296 // Add code for jquery to use multiselect
10297 if ($addjscombo && $jsbeautify) {
10298 // Enhance with select2
10299 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
10300 $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', (((int) $show_empty) < 0 ? (string) $show_empty : '-1'), $morecss);
10301 }
10302
10303 return $out;
10304 }
10305
10324 public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
10325 {
10326 global $conf;
10327 global $delayedhtmlcontent; // Will be used later outside of this function
10328
10329 // TODO Use an internal dolibarr component instead of select2
10330 if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
10331 return '';
10332 }
10333
10334 $out = '<select type="text" class="' . $htmlname . ($morecss ? ' ' . $morecss : '') . '" ' . ($moreparam ? $moreparam . ' ' : '') . 'name="' . $htmlname . '"></select>';
10335
10336 $outdelayed = '';
10337 if (!empty($conf->use_javascript_ajax)) {
10338 $tmpplugin = 'select2';
10339 $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
10340 <script nonce="' . getNonce() . '">
10341 $(document).ready(function () {
10342
10343 ' . ($callurlonselect ? 'var saveRemoteData = [];' : '') . '
10344
10345 $(".' . $htmlname . '").select2({
10346 ajax: {
10347 dir: "ltr",
10348 url: "' . $url . '",
10349 dataType: \'json\',
10350 delay: 250,
10351 data: function (params) {
10352 return {
10353 q: params.term, // search term
10354 page: params.page
10355 }
10356 },
10357 processResults: function (data) {
10358 // parse the results into the format expected by Select2.
10359 // since we are using custom formatting functions we do not need to alter the remote JSON data
10360 //console.log(data);
10361 saveRemoteData = data;
10362 /* format json result for select2 */
10363 result = []
10364 $.each( data, function( key, value ) {
10365 result.push({id: key, text: value.text});
10366 });
10367 //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
10368 //console.log(result);
10369 return {results: result, more: false}
10370 },
10371 cache: true
10372 },
10373 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage,
10374 containerCssClass: \':all:\', /* Line to add class from the original SELECT propagated to the new <span class="select2-selection...> tag */
10375 placeholder: \'' . dol_escape_js($placeholder) . '\',
10376 escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
10377 minimumInputLength: ' . ((int) $minimumInputLength) . ',
10378 formatResult: function (result, container, query, escapeMarkup) {
10379 return escapeMarkup(result.text);
10380 },
10381 });
10382
10383 ' . ($callurlonselect ? '
10384 /* Code to execute a GET when we select a value */
10385 $(".' . $htmlname . '").change(function() {
10386 var selected = $(\'.' . dol_escape_js($htmlname) . '\').val();
10387 console.log("We select in selectArrayAjax the entry "+selected)
10388 $(\'.' . dol_escape_js($htmlname) . '\').val(""); /* reset visible combo value */
10389 $.each( saveRemoteData, function( key, value ) {
10390 if (key == selected)
10391 {
10392 console.log("selectArrayAjax - Do a redirect to "+value.url)
10393 location.assign(value.url);
10394 }
10395 });
10396 });' : '') . '
10397
10398 });
10399 </script>';
10400 }
10401
10402 if ($acceptdelayedhtml) {
10403 $delayedhtmlcontent .= $outdelayed;
10404 } else {
10405 $out .= $outdelayed;
10406 }
10407 return $out;
10408 }
10409
10429 public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0, $textfortitle = '')
10430 {
10431 global $conf;
10432 global $delayedhtmlcontent; // Will be used later outside of this function
10433
10434 // TODO Use an internal dolibarr component instead of select2
10435 if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
10436 return '';
10437 }
10438
10439 $out = '<select type="text"'.($textfortitle ? ' title="'.dol_escape_htmltag($textfortitle).'"' : '').' id="'.$htmlname.'" class="'.$htmlname.($morecss ? ' ' . $morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.'"><option></option></select>';
10440
10441 $formattedarrayresult = array();
10442
10443 foreach ($array as $key => $value) {
10444 $o = new stdClass();
10445 $o->id = $key;
10446 $o->text = $value['text'];
10447 $o->url = $value['url'];
10448 $formattedarrayresult[] = $o;
10449 }
10450
10451 $outdelayed = '';
10452 if (!empty($conf->use_javascript_ajax)) {
10453 $tmpplugin = 'select2';
10454 $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
10455 <script nonce="' . getNonce() . '">
10456 $(document).ready(function () {
10457 var data = ' . json_encode($formattedarrayresult) . ';
10458
10459 ' . ($callurlonselect ? 'var saveRemoteData = ' . json_encode($array) . ';' : '') . '
10460
10461 $(\'.' . dol_escape_js($htmlname) . '\').select2({
10462 data: data,
10463 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage,
10464 containerCssClass: \':all:\', /* Line to add class from the original SELECT propagated to the new <span class="select2-selection...> tag */
10465 placeholder: \'' . dol_escape_js($placeholder) . '\',
10466 escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
10467 minimumInputLength: ' . ((int) $minimumInputLength) . ',
10468 formatResult: function (result, container, query, escapeMarkup) {
10469 return escapeMarkup(result.text);
10470 },
10471 matcher: function (params, data) {
10472
10473 if(! data.id) return null;';
10474
10475 if ($callurlonselect) {
10476 // We forge the url with 'sall='
10477 $outdelayed .= '
10478
10479 var urlBase = data.url;
10480 var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
10481 /* console.log("params.term="+params.term); */
10482 /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
10483 saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
10484 }
10485
10486 if (!$disableFiltering) {
10487 $outdelayed .= '
10488
10489 if(data.text.match(new RegExp(params.term))) {
10490 return data;
10491 }
10492
10493 return null;';
10494 } else {
10495 $outdelayed .= '
10496
10497 return data;';
10498 }
10499
10500 $outdelayed .= '
10501 }
10502 });
10503
10504 ' . ($callurlonselect ? '
10505 /* Code to execute a GET when we select a value */
10506 $(\'.' . dol_escape_js($htmlname) . '\').change(function() {
10507 var selected = $(\'.' . dol_escape_js($htmlname) . '\').val();
10508 console.log("We select "+selected)
10509
10510 $(\'.' . dol_escape_js($htmlname) . '\').val(""); /* reset visible combo value */
10511 $.each( saveRemoteData, function( key, value ) {
10512 if (key == selected)
10513 {
10514 console.log("selectArrayFilter - Do a redirect to "+value.url)
10515 location.assign(value.url);
10516 }
10517 });
10518 });' : '') . '
10519
10520 });
10521 </script>';
10522 }
10523
10524 if ($acceptdelayedhtml) {
10525 $delayedhtmlcontent .= $outdelayed;
10526 } else {
10527 $out .= $outdelayed;
10528 }
10529 return $out;
10530 }
10531
10550 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)
10551 {
10552 global $conf, $langs;
10553 $out = '';
10554
10555 if ($addjscombo < 0) {
10556 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
10557 $addjscombo = 1;
10558 } else {
10559 $addjscombo = 0;
10560 }
10561 }
10562
10563 $useenhancedmultiselect = 0;
10564 if (!empty($conf->use_javascript_ajax) && !defined('MAIN_DO_NOT_USE_JQUERY_MULTISELECT') && (getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT'))) {
10565 if ($addjscombo) {
10566 $useenhancedmultiselect = 1; // Use the js multiselect in one line. Possible only if $addjscombo not 0.
10567 }
10568 }
10569
10570 $out .= '<span class="multiselectarray'.$htmlname.'">';
10571
10572 // We need a hidden field because when using the multiselect, if we unselect all, there is no
10573 // variable submitted at all, so no way to make a difference between variable not submitted and variable
10574 // submitted to nothing.
10575 $out .= '<input type="hidden" name="'.$htmlname.'_multiselect" value="1">';
10576 // Output select component
10577 $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";
10578 if (is_array($array) && !empty($array)) {
10579 if ($value_as_key) {
10580 $array = array_combine($array, $array);
10581 }
10582
10583 if (!empty($array)) {
10584 foreach ($array as $key => $value) {
10585 $tmpkey = $key;
10586 $tmplabel = $value;
10587 $tmplabelhtml = '';
10588 $tmpcolor = '';
10589 $tmppicto = '';
10590 $tmpdisabled = '';
10591 if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
10592 $tmpkey = $value['id'];
10593 $tmplabel = empty($value['label']) ? '' : $value['label'];
10594 $tmplabelhtml = empty($value['labelhtml']) ? (empty($value['data-html']) ? '' : $value['data-html']) : $value['labelhtml'];
10595 $tmpcolor = empty($value['color']) ? '' : $value['color'];
10596 $tmppicto = empty($value['picto']) ? '' : $value['picto'];
10597 $tmpdisabled = empty($value['disabled']) ? '' : $value['disabled'];
10598 }
10599 $newval = ($translate ? $langs->trans($tmplabel) : $tmplabel);
10600 $newval = ($key_in_label ? $tmpkey . ' - ' . $newval : $newval);
10601
10602 $tmplabelhtml = ($translate ? $langs->trans($tmplabelhtml) : $tmplabelhtml);
10603 $tmplabelhtml = ($key_in_label ? $tmpkey . ' - ' . $tmplabelhtml : $tmplabelhtml);
10604
10605 $out .= '<option value="' . $tmpkey . '"';
10606 if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
10607 $out .= ' selected';
10608 }
10609 $out .= is_array($value) && array_key_exists('parent', $value) && !empty($value['parent']) ? ' parent="' . dolPrintHTMLForAttribute($value['parent']) . '"' : '';
10610 if ($tmpdisabled) {
10611 $out .= ' disabled="disabled"';
10612 }
10613 if (!empty($tmplabelhtml)) {
10614 $out .= ' data-html="' . dolPrintHTMLForAttribute($tmplabelhtml) . '"';
10615 } else {
10616 $tmplabelhtml = ($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #' . $tmpcolor . '"') : '') . $newval;
10617 $out .= ' data-html="' . dolPrintHTMLForAttribute($tmplabelhtml) . '"';
10618 }
10619 $out .= '>';
10620 $out .= dol_htmlentitiesbr($newval);
10621 $out .= '</option>' . "\n";
10622 }
10623 }
10624 }
10625 $out .= '</select>' . "\n";
10626
10627 $out .= '</span>';
10628
10629 // Add code for jquery to use multiselect
10630 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT')) {
10631 $out .= "\n" . '<!-- JS CODE TO ENABLE select for id ' . $htmlname . ', addjscombo=' . $addjscombo . ' -->';
10632 $out .= "\n" . '<script nonce="' . getNonce() . '">' . "\n";
10633 if ($addjscombo == 1) {
10634 $tmpplugin = getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT', (defined('REQUIRE_JQUERY_MULTISELECT') ? constant('REQUIRE_JQUERY_MULTISELECT') : 'select2'));
10635
10636 // If property data-html set, we decode html entities and use this.
10637 // Note that HTML content must have been sanitized from js with dol_escape_htmltag(xxx, 0, 0, '', 0, 1) when building the select option.
10638 // TODO Move this into common js ?
10639 $out .= 'function formatResult(record, container) {' . "\n";
10640 $out .= ' if ($(record.element).attr("data-html") != undefined && typeof htmlEntityDecodeJs === "function") {';
10641 $out .= ' return htmlEntityDecodeJs($(record.element).attr("data-html"));';
10642 $out .= ' }'."\n";
10643 $out .= ' return record.text;';
10644 $out .= '}' . "\n";
10645
10646 $out .= 'function formatSelection(record) {' . "\n";
10647 $out .= ' return record.text;';
10648 $out .= '}' . "\n";
10649
10650 // Load the select2 enhancer
10651 //$out .= 'console.log(\'addjscombo=1 for htmlname=' . dol_escape_js($htmlname) . '\');';
10652 $out .= '$(document).ready(function () {
10653 $(\'#' . dol_escape_js($htmlname) . '\').' . $tmpplugin . '({';
10654 if ($placeholder) {
10655 $out .= '
10656 placeholder: {
10657 id: \'-1\',
10658 text: \''.dol_escape_js($placeholder).'\'
10659 },';
10660 }
10661 $out .= ' dir: \'ltr\',
10662 containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag (ko with multiselect) */
10663 dropdownCssClass: \'' . dol_escape_js($morecss) . '\', /* Line to add class on the new <span class="select2-selection...> tag (ok with multiselect). Need full version of select2. */
10664 // Specify format function for dropdown item
10665 formatResult: formatResult,
10666 templateResult: formatResult, /* For 4.0 */
10667 escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
10668 // Specify format function for selected item
10669 formatSelection: formatSelection,
10670 templateSelection: formatSelection, /* For 4.0 */
10671 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage
10672 });
10673
10674 /* Add also morecss to the css .select2 that is after the #htmlname, for component that are shown dynamically after load, because select2 set
10675 the size only if component is not hidden by default on load */
10676 $(\'#' . dol_escape_js($htmlname) . ' + .select2\').addClass(\'' . dol_escape_js($morecss) . '\');
10677 });' . "\n";
10678 } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
10679 // Add other js lib
10680 // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
10681 // ...
10682 $out .= 'console.log(\'addjscombo=2 for htmlname=' . dol_escape_js($htmlname) . '\');';
10683 $out .= '$(document).ready(function () {
10684 $(\'#' . dol_escape_js($htmlname) . '\').multiSelect({
10685 containerHTML: \'<div class="multi-select-container">\',
10686 menuHTML: \'<div class="multi-select-menu">\',
10687 buttonHTML: \'<span class="multi-select-button ' . dol_escape_js($morecss) . '">\',
10688 menuItemHTML: \'<label class="multi-select-menuitem">\',
10689 activeClass: \'multi-select-container--open\',
10690 noneText: \'' . dol_escape_js($placeholder) . '\'
10691 });
10692 })';
10693 }
10694 $out .= '</script>';
10695 }
10696
10697 return $out;
10698 }
10699
10700
10714 public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '', $draganddrop = 0)
10715 {
10716 global $conf, $langs, $user;
10717
10718 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
10719 return '';
10720 }
10721 if (empty($array)) {
10722 return '';
10723 }
10724
10725 $tmpvar = "MAIN_SELECTEDFIELDS_" . $varpage; // To get list of saved selected fields to show
10726
10727 if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
10728 $tmparray = explode(',', $user->conf->$tmpvar);
10729 foreach ($array as $key => $val) {
10730 //var_dump($key);
10731 //var_dump($tmparray);
10732 if (in_array($key, $tmparray)) {
10733 $array[$key]['checked'] = 1;
10734 } else {
10735 $array[$key]['checked'] = 0;
10736 }
10737 }
10738 } else { // There is no list of fields already customized for user
10739 foreach ($array as $key => $val) {
10740 if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
10741 $array[$key]['checked'] = 0;
10742 }
10743 }
10744 }
10745
10746 $listoffieldsforselection = '';
10747 $listcheckedstring = '';
10748
10749 foreach ($array as $key => $val) {
10750 // var_dump($val);
10751 // var_dump(array_key_exists('enabled', $val));
10752 // var_dump(!$val['enabled']);
10753 if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
10754 unset($array[$key]); // We don't want this field
10755 continue;
10756 }
10757 if (!empty($val['type']) && $val['type'] == 'separate') {
10758 // Field remains in array but we don't add it into $listoffieldsforselection
10759 //$listoffieldsforselection .= '<li>-----</li>';
10760 continue;
10761 }
10762 if (!empty($val['label']) && $val['label']) {
10763 if (!empty($val['langfile']) && is_object($langs)) {
10764 $langs->load($val['langfile']);
10765 }
10766
10767 // Note: $val['checked'] <> 0 means we must show the field into the combo list @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
10768 $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']).'" />';
10769 $listoffieldsforselection .= '<label for="checkbox' . $key . '" class="paddingleft">';
10770 $listoffieldsforselection .= dolPrintHTML(dol_string_nohtmltag($langs->trans($val['label'])));
10771 $listoffieldsforselection .= '</label>';
10772 if (!empty($draganddrop)) {
10773 $listoffieldsforselection .= img_picto($langs->trans("MoveField", !empty($key) ? $key : 'none'), 'grip_title', 'class="opacitymedium boxhandle hideonsmartphone cursormove marginleftonly"');
10774 }
10775 $listoffieldsforselection .= '</li>';
10776 $listcheckedstring .= (empty($val['checked']) ? '' : $key . ',');
10777 }
10778 }
10779
10780 $out = '<!-- Component multiSelectArrayWithCheckbox ' . $htmlname . ' -->
10781
10782 <dl class="dropdown">
10783 <dt>
10784 <a href="#' . $htmlname . '" class="multiselectpicto">
10785 ' . img_picto('', 'list') . '
10786 </a>
10787 <input type="hidden" class="' . $htmlname . '" name="' . $htmlname . '" value="' . $listcheckedstring . '">
10788 </dt>
10789 <dd class="dropdowndd">
10790 <div class="multiselectcheckbox'.$htmlname.'">
10791 <ul class="'.$htmlname.(((string) $pos == '1' || (string) $pos == 'left') ? 'left' : '').(!empty($draganddrop) ? ' sortable' : '').'">
10792 <li class="liinputsearch">
10793 <input class="inputsearch_dropdownselectedfields width90p minwidth200imp" style="width:90%;" type="text" placeholder="'.$langs->trans('Search').'">
10794 </li>
10795 '.$listoffieldsforselection.'
10796 </ul>
10797 </div>
10798 </dd>
10799 </dl>
10800
10801 <script>
10802 function updateFieldOrder() {
10803 var positionfields = $(".sortable").sortable("toArray");
10804 $.ajax({
10805 url: \''.DOL_URL_ROOT.'/core/ajax/changepositionfields.php?positionfields=\'+positionfields+\'&token='.newToken().'&action=listafterchangingpositionfields&contextpage='.$varpage.'&userid='.$user->id.'\',
10806 async: false,
10807 success: function () {
10808 // reload page
10809 window.location.href = "'.$_SERVER["PHP_SELF"].'";
10810 }
10811 });
10812 }
10813 $( ".sortable" ).sortable({
10814 handle: \'.boxhandle\',
10815 revert: \'invalid\',
10816 items: \'.fieldsortable\',
10817 stop: function(event, ui) {
10818 console.log("We moved box so we call updateBoxOrder with ajax actions");
10819 updateFieldOrder(); /* 1 to avoid message after a move */
10820 }
10821 });
10822 </script>
10823
10824 <script nonce="' . getNonce() . '" type="text/javascript">
10825 jQuery(document).ready(function () {
10826 $(\'.multiselectcheckbox' . $htmlname . ' input[type="checkbox"]\').on("click", function () {
10827 console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
10828
10829 $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
10830
10831 var title = $(this).val() + ",";
10832 if ($(this).is(\':checked\')) {
10833 $(\'.' . $htmlname . '\').val(title + $(\'.' . $htmlname . '\').val());
10834 }
10835 else {
10836 $(\'.' . $htmlname . '\').val( $(\'.' . $htmlname . '\').val().replace(title, \'\') )
10837 }
10838 // Now, we submit page
10839 //$(this).parents(\'form:first\').submit();
10840 });
10841
10842 $("input.inputsearch_dropdownselectedfields").on("keyup", function() {
10843 console.log("keyup on inputsearch_dropdownselectedfields");
10844 var value = $(this).val().toLowerCase();
10845 $(\'.multiselectcheckbox'.$htmlname.' li > label\').filter(function() {
10846 $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
10847 });
10848 });
10849 ';
10850 if (empty($conf->browser->layout) || $conf->browser->layout != 'phone') {
10851 $out .= '
10852 $(".dropdown dt a").on("click", function () {
10853 console.log("Click on dropdown, we set focus to search field");
10854 setTimeout(() => { $(\'.inputsearch_dropdownselectedfields\').focus(); }, 200);
10855 });';
10856 }
10857 $out .= '
10858 });
10859 </script>
10860
10861 ';
10862 return $out;
10863 }
10864
10874 public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
10875 {
10876 global $conf;
10877
10878 include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
10879
10880 $cat = new Categorie($this->db);
10881 $categories = $cat->containing($id, $type);
10882
10883 if ($rendermode == 1 || $rendermode == 2) {
10884 $toprint = array();
10885 foreach ($categories as $c) {
10886 $ways = $c->print_all_ways('auto', ($nolink ? 'none' : ''), 0, 1, ($rendermode == 2 ? 0 : 1)); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
10887 foreach ($ways as $way) {
10888 $color = $c->color;
10889 $sfortag = '<li class="select2-search-choice-dolibarr noborderoncategories'.(empty($toprint) ? ' nomarginleft' : '');
10890 $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.
10891 if ($c->color && colorIsLight($c->color)) {
10892 $forced_color = 'categtextblack';
10893 }
10894 $sfortag .= ' '.$forced_color;
10895 $sfortag .= '"';
10896 $sfortag .= ($color ? ' style="background: #' . $color . ';"' : ' style="background: #bbb"');
10897 $titlestring = $ways[0];
10898 $titlestring = str_replace('>', ' - ', dol_string_nohtmltag($titlestring));
10899 $sfortag .= ' title="' . dolPrintHTMLForAttribute($titlestring) . '"';
10900 $sfortag .= '>';
10901 if ($rendermode == 1) {
10902 $sfortag .= '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.((int) $c->id).'&type='.urlencode($c->type).'" class="'.$forced_color.'">';
10903 $sfortag .= img_picto('', 'category', 'class="paddingright"');
10904 if ($conf->dol_optimize_smallscreen) {
10905 $sfortag .= dolPrintHTML(dol_trunc($c->label, 8));
10906 } else {
10907 $sfortag .= dolPrintHTML($c->label);
10908 }
10909 $sfortag .= '</a>';
10910 } else {
10911 $sfortag .= $way;
10912 }
10913 $sfortag .= '</li>';
10914
10915 $toprint[] = $sfortag; // Add tag in list of tag to show
10916 }
10917 }
10918 if (empty($toprint)) {
10919 return '';
10920 } else {
10921 return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
10922 }
10923 }
10924
10925 if ($rendermode == 0) {
10926 $arrayselected = array();
10927 $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 3);
10928 foreach ($categories as $c) {
10929 $arrayselected[(string) $c->id] = (string) $c->id;
10930 }
10931
10932 return $this->multiselectarray('categories', $cate_arbo, $arrayselected, 0, 0, '', 0, '100%', 'disabled', 'category');
10933 }
10934
10935 return 'ErrorBadValueForParameterRenderMode'; // Should not happened
10936 }
10937
10947 public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = array(), $title = 'RelatedObjects')
10948 {
10949 global $conf, $langs, $hookmanager;
10950 global $action;
10951 global $db, $user; // Will be used into tpl
10952
10953 dol_syslog(__METHOD__, LOG_DEBUG);
10954
10955 $object->fetchObjectLinked();
10956
10957 // Bypass the default method
10958 $hookmanager->initHooks(array('commonobject'));
10959 $parameters = array(
10960 'morehtmlright' => $morehtmlright,
10961 'compatibleImportElementsList' => &$compatibleImportElementsList,
10962 );
10963 $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
10964
10965 $nbofdifferenttypes = count($object->linkedObjects);
10966
10967 if (empty($reshook)) {
10968 print '<!-- showLinkedObjectBlock -->';
10969 print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, '', 'showlinkedobjectblock');
10970
10971
10972 print '<div class="div-table-responsive-no-min">';
10973 print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="' . $object->element . '" data-elementid="' . $object->id . '" >';
10974
10975 print '<tr class="liste_titre">';
10976 print '<td>' . $langs->trans("Type") . '</td>';
10977 print '<td>' . $langs->trans("Ref") . '</td>';
10978 print '<td></td>';
10979 print '<td></td>';
10980 print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
10981 print '<td class="right">' . $langs->trans("Status") . '</td>';
10982 print '<td></td>';
10983 print '</tr>';
10984
10985 $nboftypesoutput = 0;
10986
10987 foreach ($object->linkedObjects as $objecttype => $objects) {
10988 $tplpath = $element = $subelement = $objecttype;
10989
10990 // to display import button on tpl
10991 global $showImportButton; // Will be used into tpl
10992 $showImportButton = false;
10993 if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
10994 $showImportButton = true;
10995 }
10996
10997 $regs = array();
10998
10999 if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
11000 $element = $regs[1];
11001 $subelement = $regs[2];
11002 $tplpath = $element . '/' . $subelement;
11003 }
11004 $tplname = 'linkedobjectblock';
11005
11006 // If we ask a resource form external module (instead of default path)
11007 if (preg_match('/^([^@]+)@([^@]+)$/i', $objecttype, $regs)) { // 'myobject@mymodule'
11008 $element = $regs[1];
11009 $module = $regs[2];
11010 $tplpath = $module. '/' . $element;
11011 $tplname = $tplname.'_'.$element;
11012 }
11013
11014 // To work with non standard path
11015 if ($objecttype == 'facture') {
11016 $tplpath = 'compta/' . $element;
11017 if (!isModEnabled('invoice')) {
11018 continue; // Do not show if module disabled
11019 }
11020 } elseif ($objecttype == 'facturerec') {
11021 $tplpath = 'compta/facture';
11022 $tplname = 'linkedobjectblockForRec';
11023 if (!isModEnabled('invoice')) {
11024 continue; // Do not show if module disabled
11025 }
11026 } elseif ($objecttype == 'propal') {
11027 $tplpath = 'comm/' . $element;
11028 if (!isModEnabled('propal')) {
11029 continue; // Do not show if module disabled
11030 }
11031 } elseif ($objecttype == 'supplier_proposal') {
11032 if (!isModEnabled('supplier_proposal')) {
11033 continue; // Do not show if module disabled
11034 }
11035 } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
11036 $tplpath = 'expedition';
11037 if (!isModEnabled('shipping')) {
11038 continue; // Do not show if module disabled
11039 }
11040 } elseif ($objecttype == 'reception') {
11041 $tplpath = 'reception';
11042 if (!isModEnabled('reception')) {
11043 continue; // Do not show if module disabled
11044 }
11045 } elseif ($objecttype == 'delivery') {
11046 $tplpath = 'delivery';
11047 if (!getDolGlobalInt('MAIN_SUBMODULE_DELIVERY')) {
11048 continue; // Do not show if sub module disabled
11049 }
11050 } elseif ($objecttype == 'ficheinter') {
11051 $tplpath = 'fichinter';
11052 if (!isModEnabled('intervention')) {
11053 continue; // Do not show if module disabled
11054 }
11055 } elseif ($objecttype == 'invoice_supplier') {
11056 $tplpath = 'fourn/facture';
11057 } elseif ($objecttype == 'order_supplier') {
11058 $tplpath = 'fourn/commande';
11059 } elseif ($objecttype == 'expensereport') {
11060 $tplpath = 'expensereport';
11061 } elseif ($objecttype == 'subscription') {
11062 $tplpath = 'adherents';
11063 } elseif ($objecttype == 'conferenceorbooth') {
11064 $tplpath = 'eventorganization';
11065 } elseif ($objecttype == 'conferenceorboothattendee') {
11066 $tplpath = 'eventorganization';
11067 } elseif ($objecttype == 'mo') {
11068 $tplpath = 'mrp';
11069 if (!isModEnabled('mrp')) {
11070 continue; // Do not show if module disabled
11071 }
11072 } elseif ($objecttype == 'project_task') {
11073 $tplpath = 'projet/tasks';
11074 }
11075
11076 global $linkedObjectBlock; // Will be used into tpl
11077 $linkedObjectBlock = $objects;
11078
11079 // Output template part (modules that overwrite templates must declare this into descriptor)
11080 $dirtpls = array_merge($conf->modules_parts['tpl'], array('/' . $tplpath . '/tpl'));
11081
11082 foreach ($dirtpls as $reldir) {
11083 $reldir = rtrim($reldir, '/');
11084 if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
11085 global $noMoreLinkedObjectBlockAfter; // Will be used into tpl
11086 $noMoreLinkedObjectBlockAfter = 1;
11087 }
11088 $file = dol_buildpath($reldir . '/' . $tplname . '.tpl.php');
11089 if (file_exists($file)) {
11090 $res = @include $file;
11091 if ($res) {
11092 $nboftypesoutput++;
11093 break;
11094 }
11095 }
11096 }
11097 }
11098
11099 if (!$nboftypesoutput) {
11100 print '<tr><td colspan="7"><span class="opacitymedium">' . $langs->trans("None") . '</span></td></tr>';
11101 }
11102
11103 print '</table>';
11104
11105 if (!empty($compatibleImportElementsList)) {
11106 $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
11107 }
11108
11109 print '</div>';
11110 }
11111
11112 return $nbofdifferenttypes;
11113 }
11114
11124 public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array(), $nooutput = 0)
11125 {
11126 global $conf, $langs, $hookmanager, $form;
11127 global $action;
11128
11129 dol_syslog(__METHOD__, LOG_DEBUG);
11130
11131 if (empty($form)) {
11132 $form = new Form($this->db);
11133 }
11134
11135 $linktoelem = '';
11136 $linktoelemlist = '';
11137 $listofidcompanytoscan = '';
11138
11139 if (!is_object($object->thirdparty)) {
11140 if ($object->element == 'subscription' && isset($object->fk_adherent)) {
11141 $subby = new Subscription($object->db);
11142 $subby->fetch($object->id);
11143 $adh = new Adherent($object->db);
11144 //$fk_adherent = $object->fk_adherent;
11145 // creating new subscription object only to fetch the adherent which obviously exists given the if statement above are Inefficient, but else phan complains
11146 $fk_adherent = $subby->fk_adherent;
11147 $adh->fetch($fk_adherent);
11148 $thirdparty_id = $adh->fetch_thirdparty();
11149 }
11150 } else {
11151 $thirdparty_id = $object->thirdparty->id;
11152 }
11153
11154 $possiblelinks = array();
11155
11156 $dontIncludeCompletedItems = getDolGlobalString('DONT_INCLUDE_COMPLETED_ELEMENTS_LINKS');
11157
11158 if (!empty($thirdparty_id) && $thirdparty_id > 0) {
11159 $listofidcompanytoscan = (int) $thirdparty_id;
11160 if (is_object($object->thirdparty) && ($object->thirdparty->parent > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PARENT_IN_LINKTO')) {
11161 $listofidcompanytoscan .= ',' . (int) $object->thirdparty->parent;
11162 }
11163 if (($object->fk_project > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO')) {
11164 include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
11165 $tmpproject = new Project($this->db);
11166 $tmpproject->fetch((int) $object->fk_project);
11167 if ($tmpproject->socid > 0 && ($tmpproject->socid != $thirdparty_id)) {
11168 $listofidcompanytoscan .= ',' . (int) $tmpproject->socid;
11169 }
11170 unset($tmpproject);
11171 }
11172
11173 $possiblelinks = array(
11174 'propal' => array(
11175 'enabled' => isModEnabled('propal'),
11176 'perms' => 1,
11177 'label' => 'LinkToProposal',
11178 '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' : ''),
11179 ),
11180 'shipping' => array(
11181 'enabled' => isModEnabled('shipping'),
11182 'perms' => 1,
11183 'label' => 'LinkToExpedition',
11184 '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' : ''),
11185 ),
11186 'order' => array(
11187 'enabled' => isModEnabled('order'),
11188 'perms' => 1,
11189 'label' => 'LinkToOrder',
11190 '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' : ''),
11191 'linkname' => 'commande',
11192 ),
11193 'subscription' => array(
11194 'enabled' => isModEnabled('member'),
11195 'perms' => 1,
11196 'label' => 'LinkToMemberSubscription',
11197 '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') . ')',
11198 'linkname' => 'subscription',
11199 ),
11200 'conferenceorboothattendee' => array(
11201 'enabled' => isModEnabled('eventorganization'),
11202 'perms' => 1,
11203 'label' => 'LinkToConferenceOrBoothAttendee',
11204 '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 " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "eventorganization_conferenceorboothattendee as a WHERE a.fk_soc = s.rowid AND a.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND s.entity IN (' . getEntity('conferenceorboothattendee') . ')' . (empty($object->fk_project) ? '' : ' AND a.fk_project = ' . (int) $object->fk_project),
11205 'linkname' => 'attendee'
11206 ),
11207 'invoice' => array(
11208 'enabled' => isModEnabled('invoice'),
11209 'perms' => 1,
11210 'label' => 'LinkToInvoice',
11211 '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' : ''),
11212 'linkname' => 'facture',
11213 ),
11214 'invoice_template' => array(
11215 'enabled' => isModEnabled('invoice'),
11216 'perms' => 1,
11217 'label' => 'LinkToTemplateInvoice',
11218 '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') . ')',
11219 ),
11220 'contrat' => array(
11221 'enabled' => isModEnabled('contract'),
11222 'perms' => 1,
11223 'label' => 'LinkToContract',
11224 '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
11225 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',
11226 ),
11227 'fichinter' => array(
11228 'enabled' => isModEnabled('intervention'),
11229 'perms' => 1,
11230 'label' => 'LinkToIntervention',
11231 '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') . ')',
11232 ),
11233 'supplier_proposal' => array(
11234 'enabled' => isModEnabled('supplier_proposal'),
11235 'perms' => 1,
11236 'label' => 'LinkToSupplierProposal',
11237 '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' : ''),
11238 ),
11239 'order_supplier' => array(
11240 'enabled' => isModEnabled("supplier_order"),
11241 'perms' => 1,
11242 'label' => 'LinkToSupplierOrder',
11243 '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' : ''),
11244 ),
11245 'invoice_supplier' => array(
11246 'enabled' => isModEnabled("supplier_invoice"),
11247 'perms' => 1, 'label' => 'LinkToSupplierInvoice',
11248 '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' : ''),
11249 ),
11250 'ticket' => array(
11251 'enabled' => isModEnabled('ticket'),
11252 'perms' => 1,
11253 'label' => 'LinkToTicket',
11254 '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' : ''),
11255 ),
11256 'mo' => array(
11257 'enabled' => isModEnabled('mrp'),
11258 'perms' => 1,
11259 'label' => 'LinkToMo',
11260 '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' : ''),
11261 ),
11262 );
11263 }
11264
11265 if ($object->table_element == 'commande_fournisseur') {
11266 $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' : '');
11267 } elseif ($object->table_element == 'mrp_mo') {
11268 $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' : '');
11269 }
11270
11271 $reshook = 0; // Ensure $reshook is defined for static analysis
11272 if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
11273 // Can complete the possiblelink array
11274 $hookmanager->initHooks(array('commonobject'));
11275 $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
11276 $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
11277 }
11278
11279 if (empty($reshook)) {
11280 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
11281 $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
11282 }
11283 } elseif ($reshook > 0) {
11284 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
11285 $possiblelinks = $hookmanager->resArray;
11286 }
11287 }
11288
11289 if (!empty($possiblelinks)) {
11290 $object->fetchObjectLinked();
11291 }
11292
11293 // Build the html part with possible suggested links
11294 $htmltoenteralink = '';
11295 foreach ($possiblelinks as $key => $possiblelink) {
11296 $num = 0;
11297 if (empty($possiblelink['enabled'])) {
11298 continue;
11299 }
11300
11301
11302 // If we ask a resource form external module (instead of default path)
11303 $module = '';
11304 if (preg_match('/^([^@]+)@([^@]+)$/i', $key, $regs)) { // 'myobject@mymodule'
11305 $key = $regs[1];
11306 $module = $regs[2];
11307 }
11308
11309 if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
11310 $htmltoenteralink .= '<div id="' . $key . 'list"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display:none"') . '>';
11311
11312 // Section for free ref input
11313 if (!getDolGlobalString('MAIN_HIDE_LINK_BY_REF_IN_LINKTO')) {
11314 $htmltoenteralink .= '<br>'."\n";
11315 $htmltoenteralink .= '<!-- form to add a link from anywhere -->'."\n";
11316 $htmltoenteralink .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
11317 $htmltoenteralink .= '<input type="hidden" name="token" value="' . newToken() . '">';
11318 $htmltoenteralink .= '<input type="hidden" name="action" value="addlinkbyref">';
11319 $htmltoenteralink .= '<input type="hidden" name="id" value="' . $object->id . '">';
11320 $htmltoenteralink .= '<input type="hidden" name="addlink" value="' . $key .(!empty($module) ? '@'.$module : ''). '">';
11321 $htmltoenteralink .= '<table class="noborder">';
11322 $htmltoenteralink .= '<tr class="liste_titre">';
11323 //print '<td>' . $langs->trans("Ref") . '</td>';
11324 $htmltoenteralink .= '<td class="center"><input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Ref")).'" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">';
11325 $htmltoenteralink .= '<br>';
11326 $htmltoenteralink .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;';
11327 $htmltoenteralink .= '<input type="submit" class="button smallpaddingimp" name="cancel" value="' . $langs->trans('Cancel') . '">';
11328 $htmltoenteralink .= '</td>';
11329 $htmltoenteralink .= '</tr>';
11330 $htmltoenteralink .= '</table>';
11331 $htmltoenteralink .= '</form>';
11332 }
11333
11334 $sql = $possiblelink['sql'];
11335
11336 $resqllist = $this->db->query($sql);
11337 if ($resqllist) {
11338 $num = $this->db->num_rows($resqllist);
11339
11340 if ($num > 0) {
11341 // Section for free predefined list
11342 if (getDolGlobalString('MAIN_HIDE_LINK_BY_REF_IN_LINKTO')) {
11343 $htmltoenteralink .= '<br>';
11344 }
11345 $htmltoenteralink .= '<!-- form to add a link from object to same thirdparty -->'."\n";
11346 $htmltoenteralink .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinked' . $key . '">';
11347 $htmltoenteralink .= '<input type="hidden" name="token" value="' . newToken() . '">';
11348 $htmltoenteralink .= '<input type="hidden" name="action" value="addlink">';
11349 $htmltoenteralink .= '<input type="hidden" name="id" value="' . $object->id . '">';
11350 $htmltoenteralink .= '<input type="hidden" name="addlink" value="' . $key . (!empty($module) ? '@'.$module : ''). '">';
11351 $htmltoenteralink .= '<table class="noborder">';
11352
11353 switch ($key) {
11354 case 'conferenceorboothattendee':
11355 // Custom logic for linking to attendees
11356 $htmltoenteralink .= $this->makeAddLinkToAttendee($object, $key, $possiblelink, $num, $resqllist);
11357 break;
11358
11359 default:
11360 // Standard logic for all other object types
11361 $htmltoenteralink .= $this->makeAddLinkToObject($object, $key, $possiblelink, $num, $resqllist);
11362 break;
11363 }
11364
11365 $htmltoenteralink .= '</table>';
11366 $htmltoenteralink .= '<div class="center">';
11367 if ($num) {
11368 $htmltoenteralink .= '<input type="submit" class="button valignmiddle marginleftonly marginrightonly smallpaddingimp" value="' . $langs->trans('ToLink') . '">';
11369 }
11370 if (empty($conf->use_javascript_ajax)) {
11371 $htmltoenteralink .= '<input type="submit" class="button button-cancel marginleftonly marginrightonly smallpaddingimp" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
11372 } else {
11373 $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>';
11374 }
11375 $htmltoenteralink .= '</form>';
11376 }
11377
11378 $this->db->free($resqllist);
11379 } else {
11380 dol_print_error($this->db);
11381 }
11382 $htmltoenteralink .= '</div>';
11383
11384
11385 // Complete the list for the combo box
11386 if ($num > 0 || !getDolGlobalString('MAIN_HIDE_LINK_BY_REF_IN_LINKTO')) {
11387 $linktoelemlist .= '<li><a href="#linkto' . $key . '" class="linkto dropdowncloseonclick" rel="' . $key . '">' . $langs->trans($possiblelink['label']) . ' (' . $num . ')</a></li>';
11388 // } else $linktoelem.=$langs->trans($possiblelink['label']);
11389 } else {
11390 $linktoelemlist .= '<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
11391 }
11392 }
11393 }
11394
11395 if ($linktoelemlist) {
11396 $linktoelem = '
11397 <dl class="dropdown" id="linktoobjectname">
11398 ';
11399 if (!empty($conf->use_javascript_ajax)) {
11400 $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>' . $langs->trans("LinkTo") . '...</a></dt>';
11401 }
11402 $linktoelem .= '<dd>
11403 <div class="multiselectlinkto">
11404 <ul class="ulselectedfields">' . $linktoelemlist . '
11405 </ul>
11406 </div>
11407 </dd>
11408 </dl>';
11409 } else {
11410 $linktoelem = '';
11411 }
11412
11413 if (!empty($conf->use_javascript_ajax)) {
11414 print '<!-- Add js to show linkto box -->
11415 <script nonce="' . getNonce() . '">
11416 jQuery(document).ready(function() {
11417 jQuery(".linkto").click(function() {
11418 console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
11419 jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
11420 });
11421 });
11422 </script>
11423 ';
11424 }
11425
11426 if ($nooutput) {
11427 return array('linktoelem' => $linktoelem, 'htmltoenteralink' => $htmltoenteralink);
11428 } else {
11429 print $htmltoenteralink;
11430 }
11431
11432 return $linktoelem;
11433 }
11434
11449 public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = 'yesno width75', $labelyes = 'Yes', $labelno = 'No')
11450 {
11451 global $langs;
11452
11453 $yes = "yes";
11454 $no = "no";
11455 if ($option) {
11456 $yes = "1";
11457 $no = "0";
11458 }
11459
11460 $disabled = ($disabled ? ' disabled' : '');
11461
11462 $resultyesno = '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '"' . $disabled . '>' . "\n";
11463 if ($useempty) {
11464 $resultyesno .= '<option value="-1"' . (($value < 0) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
11465 }
11466 if (("$value" == 'yes') || ($value == 1)) {
11467 $resultyesno .= '<option value="' . $yes . '" selected>' . $langs->trans($labelyes) . '</option>' . "\n";
11468 $resultyesno .= '<option value="' . $no . '">' . $langs->trans($labelno) . '</option>' . "\n";
11469 } else {
11470 $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
11471 $resultyesno .= '<option value="' . $yes . '">' . $langs->trans($labelyes) . '</option>' . "\n";
11472 $resultyesno .= '<option value="' . $no . '"' . $selected . '>' . $langs->trans($labelno) . '</option>' . "\n";
11473 }
11474 $resultyesno .= '</select>' . "\n";
11475
11476 if ($addjscombo) {
11477 $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
11478 }
11479
11480 return $resultyesno;
11481 }
11482
11483 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
11484
11494 public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
11495 {
11496 // phpcs:enable
11497 $sql = "SELECT rowid, label";
11498 $sql .= " FROM " . $this->db->prefix() . "export_model";
11499 $sql .= " WHERE type = '" . $this->db->escape($type) . "'";
11500 $sql .= " ORDER BY rowid";
11501 $result = $this->db->query($sql);
11502 if ($result) {
11503 print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
11504 if ($useempty) {
11505 print '<option value="-1">&nbsp;</option>';
11506 }
11507
11508 $num = $this->db->num_rows($result);
11509 $i = 0;
11510 while ($i < $num) {
11511 $obj = $this->db->fetch_object($result);
11512 if ($selected == $obj->rowid) {
11513 print '<option value="' . $obj->rowid . '" selected>';
11514 } else {
11515 print '<option value="' . $obj->rowid . '">';
11516 }
11517 print $obj->label;
11518 print '</option>';
11519 $i++;
11520 }
11521 print "</select>";
11522 } else {
11523 dol_print_error($this->db);
11524 }
11525 }
11526
11545 public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
11546 {
11547 global $conf, $langs, $hookmanager, $extralanguages;
11548
11549 $ret = '';
11550 if (empty($fieldid)) {
11551 $fieldid = 'rowid';
11552 }
11553 if (empty($fieldref)) {
11554 $fieldref = 'ref';
11555 }
11556
11557 // Preparing gender's display if there is one
11558 $addgendertxt = '';
11559 if (property_exists($object, 'gender') && !empty($object->gender)) {
11560 $addgendertxt = ' ';
11561 switch ($object->gender) {
11562 case 'man':
11563 $addgendertxt .= '<i class="fas fa-mars valignmiddle"></i>';
11564 break;
11565 case 'woman':
11566 $addgendertxt .= '<i class="fas fa-venus valignmiddle"></i>';
11567 break;
11568 case 'other':
11569 $addgendertxt .= '<i class="fas fa-transgender valignmiddle"></i>';
11570 break;
11571 }
11572 }
11573
11574 // Add where from hooks
11575 if (is_object($hookmanager)) {
11576 $parameters = array('showrefnav' => true);
11577 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
11578 if (!empty($hookmanager->resPrint)) {
11579 if (empty($object->next_prev_filter) && preg_match('/^\s*AND/i', $hookmanager->resPrint)) {
11580 $object->next_prev_filter = (string) preg_replace('/^\s*AND\s*/i', '', $hookmanager->resPrint);
11581 } elseif (!empty($object->next_prev_filter) && !preg_match('/^\s*AND/i', $hookmanager->resPrint)) {
11582 $object->next_prev_filter .= ' AND '.$hookmanager->resPrint;
11583 } else {
11584 $object->next_prev_filter .= $hookmanager->resPrint;
11585 }
11586 }
11587 }
11588
11589 $previous_ref = $next_ref = '';
11590 if ($shownav) {
11591 //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,fieldid=$fieldid,filedref=$fieldref,morehtmlref=$morehtmlref,moreparam=$moreparam";
11592 $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
11593
11594 $navurl = $_SERVER["PHP_SELF"];
11595
11596 // Special case for token card
11597 if ($paramid == 'api_token_card') {
11598 if (preg_match('/\/user\/api_token/', $navurl)) {
11599 $navurl = preg_replace('/card/', 'list', $navurl);
11600 $paramid = 'id';
11601 }
11602 }
11603
11604 // Special case for project/task page
11605 if ($paramid == 'project_ref') {
11606 if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
11607 $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
11608 $paramid = 'ref';
11609 }
11610 }
11611
11612 $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>';
11613 $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>';
11614 }
11615
11616 //print "xx".$previous_ref."x".$next_ref;
11617 $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
11618
11619 // Right part of banner
11620 if ($morehtmlright) {
11621 $ret .= '<div class="inline-block floatleft">' . $morehtmlright . '</div>';
11622 }
11623
11624 if ($previous_ref || $next_ref || $morehtml) {
11625 $ret .= '<div class="pagination paginationref"><ul class="right">';
11626 }
11627 if ($morehtml && getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
11628 $ret .= '<!-- morehtml --><li class="noborder litext' . (($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '') . '">' . $morehtml . '</li>';
11629 }
11630 if ($shownav && ($previous_ref || $next_ref)) {
11631 $ret .= '<li class="pagination">' . $previous_ref . '</li>';
11632 $ret .= '<li class="pagination">' . $next_ref . '</li>';
11633 }
11634 if ($previous_ref || $next_ref || $morehtml) {
11635 $ret .= '</ul></div>';
11636 }
11637
11638 // Status
11639 $parameters = array('morehtmlstatus' => $morehtmlstatus);
11640 $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
11641 if (empty($reshook)) {
11642 $morehtmlstatus .= $hookmanager->resPrint;
11643 } else {
11644 $morehtmlstatus = $hookmanager->resPrint;
11645 }
11646 if ($morehtmlstatus) {
11647 $ret .= '<!-- status --><div class="statusref">' . $morehtmlstatus . '</div>';
11648 }
11649
11650 $parameters = array();
11651 $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
11652 if (empty($reshook)) {
11653 $morehtmlref .= $hookmanager->resPrint;
11654 } elseif ($reshook > 0) {
11655 $morehtmlref = $hookmanager->resPrint;
11656 }
11657
11658 // Left part of banner
11659 if ($morehtmlleft) {
11660 if ($conf->browser->layout == 'phone') {
11661 $ret .= '<!-- morehtmlleft --><div class="floatleft">' . $morehtmlleft . '</div>';
11662 } else {
11663 $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">' . $morehtmlleft . '</div>';
11664 }
11665 }
11666
11667 //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
11668 $ret .= '<!-- Ref or ID --><div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid' . (($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '') . '">';
11669
11670 // For thirdparty, contact, user, member, the ref is the id, so we show something else
11671 if ($object->element == 'societe') {
11672 $ret .= '<span class="valignmiddle">'.dolPrintHTML((string) $object->name).'</span>';
11673
11674 // List of extra languages
11675 $arrayoflangcode = array();
11676 if (getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE')) {
11677 $arrayoflangcode[] = getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE');
11678 }
11679
11680 if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
11681 if (!is_object($extralanguages)) {
11682 include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
11683 $extralanguages = new ExtraLanguages($this->db);
11684 }
11685 $extralanguages->fetch_name_extralanguages('societe');
11686
11687 // Guard against PHP 8 'Undefined array key' when MAIN_USE_ALTERNATE_TRANSLATION_FOR
11688 // is not configured and fetch_name_extralanguages() leaves attributes empty (issue #34596).
11689 if (!empty($extralanguages->attributes['societe']) && !empty($extralanguages->attributes['societe']['name'])) {
11690 $object->fetchValuesForExtraLanguages();
11691
11692 $htmltext = '';
11693 // If there is extra languages
11694 foreach ($arrayoflangcode as $extralangcode) {
11695 $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
11696 if ($object->array_languages['name'][$extralangcode]) {
11697 $htmltext .= $object->array_languages['name'][$extralangcode];
11698 } else {
11699 $htmltext .= '<span class="opacitymedium">' . $langs->trans("SwitchInEditModeToAddTranslation") . '</span>';
11700 }
11701 }
11702 $ret .= '<!-- Show translations of name -->' . "\n";
11703 $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
11704 }
11705 }
11706 } elseif ($object->element == 'member') {
11707 '@phan-var-force Adherent $object';
11708 $ret .= $object->ref . '<br>';
11709 $fullname = $object->getFullName($langs);
11710 if ($object->morphy == 'mor' && $object->societe) {
11711 $ret .= '<span class="valignmiddle">'.dolPrintHTML((string) $object->societe) . ((!empty($fullname) && $object->societe != $fullname) ? ' (' . dol_htmlentities($fullname) . $addgendertxt . ')' : '').'</span>';
11712 } else {
11713 $ret .= '<span class="valignmiddle">'.dolPrintHTML($fullname) . $addgendertxt . ((!empty($object->societe) && $object->societe != $fullname) ? ' (' . dol_htmlentities((string) $object->societe) . ')' : '').'</span>';
11714 }
11715 } elseif (in_array($object->element, array('contact', 'user'))) {
11716 $ret .= '<span class="valignmiddle">'.dolPrintHTML($object->getFullName($langs)).'</span>'.$addgendertxt;
11717 } elseif ($object->element == 'usergroup') {
11718 $ret .= dol_htmlentities((string) $object->name);
11719 } elseif (in_array($object->element, array('action', 'agenda'))) {
11720 '@phan-var-force ActionComm $object';
11721 $ret .= $object->ref . '<br>' . $object->label;
11722 } elseif (in_array($object->element, array('adherent_type'))) {
11723 $ret .= $object->label;
11724 } elseif ($object->element == 'ecm_directories') {
11725 $ret .= '';
11726 } elseif ($object->element == 'accountingbookkeeping' && !empty($object->context['mode']) && $object->context['mode'] == '_tmp') {
11727 $ret .= '<span class="valignmiddle">'.$langs->trans("Draft").'</span>';
11728 } elseif ($object instanceof Ticket) {
11729 '@phan-var-force Ticket $object';
11730 $ret .= '<span class="valignmiddle">'.dolPrintHTML(!empty($object->$fieldref) ? $object->$fieldref : "").'</span>';
11731 $ret .= ' &nbsp; <span class="nobold small" title="'.dolPrintHTMLForAttribute($langs->trans("TicketTrackId")).'">('.$object->track_id.')</span>';
11732 } elseif ($fieldref != 'none') {
11733 // Generic case
11734 $ret .= '<span class="valignmiddle">'.dolPrintHTML(!empty($object->$fieldref) ? $object->$fieldref : "").'</span>';
11735 }
11736 if ($morehtmlref) {
11737 // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
11738 if (substr($morehtmlref, 0, 4) != '<div') {
11739 $ret .= ' ';
11740 }
11741
11742 $ret .= '<!-- morehtmlref -->'.$morehtmlref;
11743 }
11744
11745 $ret .= '</div>';
11746
11747 $ret .= '</div><!-- End banner content -->';
11748
11749 return $ret;
11750 }
11751
11752
11761 public function showbarcode(&$object, $width = 100, $morecss = '')
11762 {
11763 //Check if barcode is filled in the card
11764 if (empty($object->barcode)) {
11765 return '';
11766 }
11767
11768 // Complete object if not complete
11769 if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
11770 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
11771 $result = $object->fetchBarCode();
11772 //Check if fetchBarCode() failed
11773 if ($result < 1) {
11774 return '<!-- ErrorFetchBarcode -->';
11775 }
11776 }
11777
11778 // Barcode image @phan-suppress-next-line PhanUndeclaredProperty
11779 $url = DOL_URL_ROOT . '/viewimage.php?modulepart=barcode&generator=' . urlencode($object->barcode_type_coder) . '&code=' . urlencode($object->barcode) . '&encoding=' . urlencode($object->barcode_type_code);
11780 $out = '<!-- url barcode = ' . $url . ' -->';
11781 $out .= '<img src="' . $url . '"' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
11782
11783 return $out;
11784 }
11785
11804 public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0, $usesharelinkifavailable = 0)
11805 {
11806 global $conf, $db, $langs;
11807
11808 $entity = (empty($object->entity) ? $conf->entity : $object->entity);
11809 $id = (empty($object->id) ? $object->rowid : $object->id); // @phan-suppress-current-line PhanUndeclaredProperty (->rowid)
11810
11811 $dir = '';
11812 $file = '';
11813 $originalfile = '';
11814 $altfile = '';
11815 $email = '';
11816 $capture = '';
11817 if ($modulepart == 'societe') {
11818 $dir = $conf->societe->multidir_output[$entity];
11819 if (!empty($object->logo)) {
11820 if (dolIsAllowedForPreview($object->logo)) {
11821 if ((string) $imagesize == 'mini') {
11822 $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
11823 } elseif ((string) $imagesize == 'small') {
11824 $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_small');
11825 } else {
11826 $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
11827 }
11828 $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
11829 }
11830 }
11831 $email = $object->email;
11832 } elseif ($modulepart == 'contact') {
11833 $dir = $conf->societe->multidir_output[$entity] . '/contact';
11834 $photo = $object->photo; // Copy to help static analysis
11835 if (!empty($photo)) {
11836 if (dolIsAllowedForPreview($photo)) {
11837 if ((string) $imagesize == 'mini') {
11838 $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($photo, '_mini');
11839 } elseif ((string) $imagesize == 'small') {
11840 $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($photo, '_small');
11841 } else {
11842 $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $photo;
11843 }
11844 $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $photo;
11845 }
11846 }
11847 $email = $object->email;
11848 $capture = 'user';
11849 } elseif ($modulepart == 'userphoto') {
11850 $dir = $conf->user->dir_output;
11851 $photo = $object->photo; // Copy to help static analysis
11852 if (!empty($photo)) {
11853 if (dolIsAllowedForPreview($photo)) {
11854 if ((string) $imagesize == 'mini') {
11855 $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($photo, '_mini');
11856 } elseif ((string) $imagesize == 'small') {
11857 $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($photo, '_small');
11858 } else {
11859 $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $photo;
11860 }
11861 $originalfile = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $photo;
11862 }
11863 }
11864 if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
11865 $altfile = $object->id . ".jpg"; // For backward compatibility
11866 }
11867 $email = $object->email;
11868 $capture = 'user';
11869 } elseif ($modulepart == 'memberphoto') {
11870 $dir = $conf->member->dir_output;
11871 $photo = $object->photo; // Copy to help static analysis
11872 if (!empty($photo)) {
11873 if (dolIsAllowedForPreview($photo)) {
11874 if ((string) $imagesize == 'mini') {
11875 $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($photo, '_mini');
11876 } elseif ((string) $imagesize == 'small') {
11877 $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($photo, '_small');
11878 } else {
11879 $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $photo;
11880 }
11881 $originalfile = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $photo;
11882 }
11883 }
11884 if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
11885 $altfile = $object->id . ".jpg"; // For backward compatibility
11886 }
11887 $email = $object->email;
11888 $capture = 'user';
11889 } else {
11890 // Generic case to show photos
11891 // TODO Implement this method in previous objects so we can always use this generic method.
11892 if ($modulepart != "unknown" && method_exists($object, 'getDataToShowPhoto')) {
11893 $tmpdata = $object->getDataToShowPhoto($modulepart, $imagesize);
11894
11895 $dir = $tmpdata['dir'];
11896 $file = $tmpdata['file'];
11897 $originalfile = $tmpdata['originalfile'];
11898 $altfile = $tmpdata['altfile'];
11899 $email = $tmpdata['email'];
11900 $capture = $tmpdata['capture'];
11901 }
11902 }
11903
11904 if ($forcecapture) {
11905 $capture = $forcecapture;
11906 }
11907
11908 $ret = '';
11909
11910 if ($dir) {
11911 if ($file && file_exists($dir . "/" . $file)) {
11912 if ($addlinktofullsize) {
11913 $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
11914 if ($urladvanced) {
11915 $ret .= '<a href="' . $urladvanced . '">';
11916 } else {
11917 $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
11918 }
11919 }
11920
11921 $sharekey = '';
11922 if ($usesharelinkifavailable) {
11923 // $dir is a full path '/home/.../dolibarr_documents/module'
11924 $relativefileforecm = preg_replace('/^'.preg_quote(DOL_DATA_ROOT.'/', '/').'/', '', $dir.'/'.$originalfile);
11925 // $relativefileforecme = 'module/...'
11926 require_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
11927 $ecmfiles = new EcmFiles($db);
11928 $ecmfiles->fetch(0, '', $relativefileforecm);
11929
11930 $sharekey = (string) $ecmfiles->share;
11931 }
11932
11933 if (!empty($sharekey)) {
11934 $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) . '">';
11935 } else {
11936 $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) . '">';
11937 }
11938 if ($addlinktofullsize) {
11939 $ret .= '</a>';
11940 }
11941 } elseif ($altfile && file_exists($dir . "/" . $altfile)) {
11942 if ($addlinktofullsize) {
11943 $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
11944 if ($urladvanced) {
11945 $ret .= '<a href="' . $urladvanced . '">';
11946 } else {
11947 $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
11948 }
11949 }
11950 $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) . '">';
11951 if ($addlinktofullsize) {
11952 $ret .= '</a>';
11953 }
11954 } else {
11955 $nophoto = '/public/theme/common/nophoto.png';
11956 $defaultimg = 'identicon'; // For gravatar
11957 if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
11958 if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && !empty($object->morphy) && strpos($object->morphy, 'mor') !== false)) {
11959 $nophoto = 'company';
11960 } else {
11961 $nophoto = '/public/theme/common/user_anonymous.png';
11962 if (!empty($object->gender) && $object->gender == 'man') {
11963 $nophoto = '/public/theme/common/user_man.png';
11964 }
11965 if (!empty($object->gender) && $object->gender == 'woman') {
11966 $nophoto = '/public/theme/common/user_woman.png';
11967 }
11968 }
11969 }
11970
11971 if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
11972 // see https://gravatar.com/site/implement/images/php/
11973 $ret .= '<!-- Put link to gravatar -->';
11974 $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 need md5 hash
11975 } else {
11976 if ($nophoto == 'company') {
11977 $ret .= '<div class="divforspanimg valignmiddle inline-block center photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . '>' . img_picto('', 'company') . '</div>';
11978 //$ret .= '<div class="difforspanimgright"></div>';
11979 } else {
11980 $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . $nophoto . '">';
11981 }
11982 }
11983 }
11984
11985 if ($caneditfield) {
11986 if ($object->photo) {
11987 $ret .= "<br>\n";
11988 }
11989 $ret .= '<table class="nobordernopadding centpercent">';
11990 if ($object->photo) {
11991 $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">' . $langs->trans("Delete") . '</label><br><br></td></tr>';
11992 }
11993 $ret .= '<tr><td class="tdoverflow">';
11994 $maxfilesizearray = getMaxFileSizeArray();
11995 $maxmin = $maxfilesizearray['maxmin'];
11996 if ($maxmin > 0) {
11997 $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">'; // MAX_FILE_SIZE must precede the field type=file
11998 }
11999 $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"' . ($capture ? ' capture="' . dolPrintHTMLForAttribute($capture) . '"' : '') . '>';
12000 $ret .= '</td></tr>';
12001 $ret .= '</table>';
12002 }
12003 }
12004
12005 return $ret;
12006 }
12007
12008 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
12009
12026 public function select_dolgroups($selected = 0, $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0', $multiple = false, $morecss = 'minwidth200')
12027 {
12028 // phpcs:enable
12029 global $conf, $user, $langs;
12030
12031 // Allow excluding groups
12032 $excludeGroups = null;
12033 if (is_array($exclude)) {
12034 $excludeGroups = implode(",", $exclude);
12035 }
12036 // Allow including groups
12037 $includeGroups = null;
12038 if (is_array($include)) {
12039 $includeGroups = implode(",", $include);
12040 }
12041
12042 if (!is_array($selected)) {
12043 $selected = array($selected);
12044 }
12045
12046 $out = '';
12047
12048 // Build sql to search groups
12049 $sql = "SELECT ug.rowid, ug.nom as name";
12050 if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
12051 $sql .= ", e.label";
12052 }
12053 $sql .= " FROM " . $this->db->prefix() . "usergroup as ug ";
12054 if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
12055 $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid=ug.entity";
12056 if ($force_entity) {
12057 $sql .= " WHERE ug.entity IN (0, " . ((int) $force_entity) . ")";
12058 } else {
12059 $sql .= " WHERE ug.entity IS NOT NULL";
12060 }
12061 } else {
12062 $sql .= " WHERE ug.entity IN (0, " . ((int) $conf->entity) . ")";
12063 }
12064 if (is_array($exclude) && $excludeGroups) {
12065 $sql .= " AND ug.rowid NOT IN (" . $this->db->sanitize($excludeGroups) . ")";
12066 }
12067 if (is_array($include) && $includeGroups) {
12068 $sql .= " AND ug.rowid IN (" . $this->db->sanitize($includeGroups) . ")";
12069 }
12070 $sql .= " ORDER BY ug.nom ASC";
12071
12072 dol_syslog(get_class($this) . "::select_dolgroups", LOG_DEBUG);
12073 $resql = $this->db->query($sql);
12074 if ($resql) {
12075 // Enhance with select2
12076 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
12077
12078 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
12079
12080 $num = $this->db->num_rows($resql);
12081 $i = 0;
12082 if ($num) {
12083 if ($show_empty && !$multiple) {
12084 $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
12085 }
12086
12087 while ($i < $num) {
12088 $obj = $this->db->fetch_object($resql);
12089 $disableline = 0;
12090 if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
12091 $disableline = 1;
12092 }
12093
12094 $label = $obj->name;
12095 $labelhtml = $obj->name;
12096 if (isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1) {
12097 $label .= " (" . $obj->label . ")";
12098 $labelhtml .= ' <span class="opacitymedium">(' . $obj->label . ')</span>';
12099 }
12100
12101 $out .= '<option value="' . $obj->rowid . '"';
12102 if ($disableline) {
12103 $out .= ' disabled';
12104 }
12105 if ((isset($selected[0]) && is_object($selected[0]) && $selected[0]->id == $obj->rowid)
12106 || ((!isset($selected[0]) || !is_object($selected[0])) && !empty($selected) && in_array($obj->rowid, $selected))) {
12107 $out .= ' selected';
12108 }
12109 $out .= ' data-html="'.dol_escape_htmltag($labelhtml).'"';
12110 $out .= '>';
12111 $out .= $label;
12112 $out .= '</option>';
12113 $i++;
12114 }
12115 } else {
12116 if ($show_empty) {
12117 $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '></option>' . "\n";
12118 }
12119 $out .= '<option value="" disabled>' . $langs->trans("NoUserGroupDefined") . '</option>';
12120 }
12121 $out .= '</select>';
12122
12123 $out .= ajax_combobox($htmlname);
12124 } else {
12125 dol_print_error($this->db);
12126 }
12127
12128 return $out;
12129 }
12130
12131
12138 public function showFilterButtons($pos = '')
12139 {
12140 $out = '<div class="nowraponall">';
12141 $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fas fa-search"></span></button>';
12142 $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fas fa-times"></span></button>';
12143 $out .= '</div>';
12144
12145 return $out;
12146 }
12147
12156 public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
12157 {
12158 global $conf;
12159
12160 $out = '';
12161
12162 if (!empty($conf->use_javascript_ajax)) {
12163 $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="' . $cssclass . 's" name="' . $cssclass . 's" class="checkallactions"></div>';
12164 }
12165 $out .= '<script nonce="' . getNonce() . '">
12166 $(document).ready(function() {
12167 $("#' . $cssclass . 's").click(function() {
12168 if($(this).is(\':checked\')){
12169 console.log("We check all ' . $cssclass . ' and trigger the change method");
12170 $(".' . $cssclass . '").prop(\'checked\', true).trigger(\'change\');
12171 }
12172 else
12173 {
12174 console.log("We uncheck all");
12175 $(".' . $cssclass . '").prop(\'checked\', false).trigger(\'change\');
12176 }' . "\n";
12177 if ($calljsfunction) {
12178 $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "' . $massactionname . '", "' . $cssclass . '"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
12179 }
12180 $out .= ' });
12181/*
12182 $(".' . $cssclass . '").change(function() {
12183 console.log("We check and change the tr class highlight after a change on .'.$cssclass.'");
12184 var $row = $(this).closest("tr");
12185 if ($row.length) {
12186 var anyChecked = $row.find(\'input[type="checkbox"].checkforselect:checked\').length > 0;
12187 console.log("anychecked="+anyChecked);
12188 if (!anyChecked) {
12189 $row.removeClass("highlight");
12190 } else {
12191 $row.addClass("highlight");
12192 }
12193 }
12194 });
12195*/
12196 });
12197 </script>';
12198
12199 return $out;
12200 }
12201
12211 public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
12212 {
12213 $out = $this->showFilterButtons();
12214 if ($addcheckuncheckall) {
12215 $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
12216 }
12217 return $out;
12218 }
12219
12233 public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
12234 {
12235 global $langs, $user;
12236
12237 $out = '';
12238 $sql = "SELECT rowid, label FROM " . $this->db->prefix() . "c_exp_tax_cat WHERE active = 1";
12239 $sql .= " AND entity IN (0," . getEntity('c_exp_tax_cat') . ")";
12240 if (!empty($excludeid)) {
12241 $sql .= " AND rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeid)) . ")";
12242 }
12243 $sql .= " ORDER BY label";
12244
12245 $resql = $this->db->query($sql);
12246 if ($resql) {
12247 $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp maxwidth200">';
12248 if ($useempty) {
12249 $out .= '<option value="0">&nbsp;</option>';
12250 }
12251
12252 while ($obj = $this->db->fetch_object($resql)) {
12253 $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . $langs->trans($obj->label) . '</option>';
12254 }
12255 $out .= '</select>';
12256 $out .= ajax_combobox('select_' . $htmlname);
12257
12258 if (!empty($htmlname) && $user->admin && $info_admin) {
12259 $out .= ' ' . info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
12260 }
12261
12262 if (!empty($target)) {
12263 $sql = "SELECT c.id FROM " . $this->db->prefix() . "c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
12264 $resql = $this->db->query($sql);
12265 if ($resql) {
12266 if ($this->db->num_rows($resql) > 0) {
12267 $obj = $this->db->fetch_object($resql);
12268 $out .= '<script nonce="' . getNonce() . '">
12269 $(function() {
12270 $("select[name=' . $target . ']").on("change", function() {
12271 var current_val = $(this).val();
12272 if (current_val == ' . $obj->id . ') {';
12273 if (!empty($default_selected) || !empty($selected)) {
12274 $out .= '$("select[name=' . $htmlname . ']").val("' . ($default_selected > 0 ? $default_selected : $selected) . '");';
12275 }
12276
12277 $out .= '
12278 $("select[name=' . $htmlname . ']").change();
12279 }
12280 });
12281
12282 $("select[name=' . $htmlname . ']").change(function() {
12283
12284 if ($("select[name=' . $target . ']").val() == ' . $obj->id . ') {
12285 // get price of kilometer to fill the unit price
12286 $.ajax({
12287 method: "POST",
12288 dataType: "json",
12289 data: { fk_c_exp_tax_cat: $(this).val(), token: \'' . currentToken() . '\' },
12290 url: "' . (DOL_URL_ROOT . '/expensereport/ajax/ajaxik.php?' . implode('&', $params)) . '",
12291 }).done(function( data, textStatus, jqXHR ) {
12292 console.log(data);
12293 if (typeof data.up != "undefined") {
12294 $("input[name=value_unit]").val(data.up);
12295 $("select[name=' . $htmlname . ']").attr("title", data.title);
12296 } else {
12297 $("input[name=value_unit]").val("");
12298 $("select[name=' . $htmlname . ']").attr("title", "");
12299 }
12300 });
12301 }
12302 });
12303 });
12304 </script>';
12305 }
12306 }
12307 }
12308 } else {
12309 dol_print_error($this->db);
12310 }
12311
12312 return $out;
12313 }
12314
12323 public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
12324 {
12325 global $langs;
12326
12327 $out = '';
12328 $sql = "SELECT rowid, range_ik FROM " . $this->db->prefix() . "c_exp_tax_range";
12329 $sql .= " WHERE entity IN (0," . getEntity('c_exp_tax_range') . ") AND active = 1";
12330
12331 $resql = $this->db->query($sql);
12332 if ($resql) {
12333 $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
12334 if ($useempty) {
12335 $out .= '<option value="0"></option>';
12336 }
12337
12338 while ($obj = $this->db->fetch_object($resql)) {
12339 $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . price($obj->range_ik, 0, $langs, 1, 0) . '</option>';
12340 }
12341 $out .= '</select>';
12342 } else {
12343 dol_print_error($this->db);
12344 }
12345
12346 return $out;
12347 }
12348
12359 public function selectExpenseFees($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
12360 {
12361 global $langs;
12362
12363 $out = '';
12364 $sql = "SELECT id, code, label";
12365 $sql .= " FROM ".$this->db->prefix()."c_type_fees";
12366 $sql .= " WHERE active = 1";
12367
12368 $resql = $this->db->query($sql);
12369 if ($resql) {
12370 $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
12371 if ($useempty) {
12372 $out .= '<option value="0"></option>';
12373 }
12374 if ($allchoice) {
12375 $out .= '<option value="-1">' . $langs->trans('AllExpenseReport') . '</option>';
12376 }
12377
12378 $field = 'code';
12379 if ($useid) {
12380 $field = 'id';
12381 }
12382
12383 while ($obj = $this->db->fetch_object($resql)) {
12384 $key = $langs->trans($obj->code);
12385 $out .= '<option ' . ($selected == $obj->{$field} ? 'selected="selected"' : '') . ' value="' . $obj->{$field} . '">' . ($key != $obj->code ? $key : $obj->label) . '</option>';
12386 }
12387 $out .= '</select>';
12388
12389 $out .= ajax_combobox('select_'.$htmlname);
12390 } else {
12391 dol_print_error($this->db);
12392 }
12393
12394 return $out;
12395 }
12396
12415 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)
12416 {
12417 global $user, $conf, $langs;
12418
12419 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
12420
12421 if (is_null($usertofilter)) {
12422 $usertofilter = $user;
12423 }
12424
12425 $out = '';
12426
12427 $hideunselectables = false;
12428 if (getDolGlobalString('INVOICE_HIDE_UNSELECTABLES')) {
12429 $hideunselectables = true;
12430 }
12431
12432 if (empty($projectsListId)) {
12433 if (!$usertofilter->hasRight('projet', 'all', 'lire')) {
12434 $projectstatic = new Project($this->db);
12435 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
12436 }
12437 }
12438
12439 // Search all projects
12440 $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";
12441 $sql .= " FROM " . $this->db->prefix() . "facture as f";
12442 $sql .= " INNER JOIN " . $this->db->prefix() . "projet as p ON p.entity IN (" . getEntity('project') . ") AND f.fk_projet = p.rowid";
12443 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON s.rowid = p.fk_soc";
12444 $sql .= " WHERE f.fk_statut = 0"; // Draft invoices only
12445 //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
12446 //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
12447 //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
12448 $sql .= " ORDER BY p.ref, f.ref ASC";
12449
12450 $resql = $this->db->query($sql);
12451 if ($resql) {
12452 // Use select2 selector
12453 if (!empty($conf->use_javascript_ajax)) {
12454 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
12455 $comboenhancement = ajax_combobox($htmlname, array(), 0, $forcefocus);
12456 $out .= $comboenhancement;
12457 $morecss = 'minwidth200imp maxwidth500';
12458 }
12459
12460 if (empty($option_only)) {
12461 $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
12462 }
12463 if (!empty($show_empty)) {
12464 $out .= '<option value="0" class="optiongrey">';
12465 if (!is_numeric($show_empty)) {
12466 $out .= $show_empty;
12467 } else {
12468 $out .= '&nbsp;';
12469 }
12470 $out .= '</option>';
12471 }
12472 $num = $this->db->num_rows($resql);
12473 $i = 0;
12474 if ($num) {
12475 while ($i < $num) {
12476 $obj = $this->db->fetch_object($resql);
12477 // 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.
12478 if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && !$usertofilter->hasRight('societe', 'lire')) {
12479 // Do nothing
12480 } else {
12481 if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
12482 $i++;
12483 continue;
12484 }
12485
12486 $labeltoshow = '';
12487
12488 if ($showproject == 'all') {
12489 $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
12490 if ($obj->name) {
12491 $labeltoshow .= ' - ' . $obj->name; // Soc name
12492 }
12493
12494 $disabled = 0;
12495 if ($obj->fk_statut == Project::STATUS_DRAFT) {
12496 $disabled = 1;
12497 $labeltoshow .= ' - ' . $langs->trans("Draft");
12498 } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
12499 if ($discard_closed == 2) {
12500 $disabled = 1;
12501 }
12502 $labeltoshow .= ' - ' . $langs->trans("Closed");
12503 } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
12504 $disabled = 1;
12505 $labeltoshow .= ' - ' . $langs->trans("LinkedToAnotherCompany");
12506 }
12507 }
12508
12509 if (!empty($selected) && $selected == $obj->rowid) {
12510 $out .= '<option value="' . $obj->rowid . '" selected';
12511 //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
12512 $out .= '>' . $labeltoshow . '</option>';
12513 } else {
12514 if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
12515 $resultat = '';
12516 } else {
12517 $resultat = '<option value="' . $obj->rowid . '"';
12518 if ($disabled) {
12519 $resultat .= ' disabled';
12520 }
12521 //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
12522 //else $labeltoshow.=' ('.$langs->trans("Private").')';
12523 $resultat .= '>';
12524 $resultat .= $labeltoshow;
12525 $resultat .= '</option>';
12526 }
12527 $out .= $resultat;
12528 }
12529 }
12530 $i++;
12531 }
12532 }
12533 if (empty($option_only)) {
12534 $out .= '</select>';
12535 }
12536
12537 $this->db->free($resql);
12538
12539 return $out;
12540 } else {
12541 dol_print_error($this->db);
12542 return '';
12543 }
12544 }
12545
12560 public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
12561 {
12562 global $conf, $langs;
12563
12564 $out = '';
12565
12566 dol_syslog('FactureRec::fetch', LOG_DEBUG);
12567
12568 $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
12569 $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
12570 $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
12571 $sql .= " ORDER BY f.titre ASC";
12572
12573 $resql = $this->db->query($sql);
12574 if ($resql) {
12575 // Use select2 selector
12576 if (!empty($conf->use_javascript_ajax)) {
12577 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
12578 $comboenhancement = ajax_combobox($htmlname, array(), 0, $forcefocus);
12579 $out .= $comboenhancement;
12580 $morecss = 'minwidth200imp maxwidth500';
12581 }
12582
12583 if (empty($option_only)) {
12584 $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
12585 }
12586 if (!empty($show_empty)) {
12587 $out .= '<option value="0" class="optiongrey">';
12588 if (!is_numeric($show_empty)) {
12589 $out .= $show_empty;
12590 } else {
12591 $out .= '&nbsp;';
12592 }
12593 $out .= '</option>';
12594 }
12595 $num = $this->db->num_rows($resql);
12596 if ($num) {
12597 while ($obj = $this->db->fetch_object($resql)) {
12598 $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
12599
12600 $disabled = 0;
12601 if (!empty($obj->suspended)) {
12602 $disabled = 1;
12603 $labeltoshow .= ' - ' . $langs->trans("Closed");
12604 }
12605
12606
12607 if (!empty($selected) && $selected == $obj->rowid) {
12608 $out .= '<option value="' . $obj->rowid . '" selected';
12609 //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
12610 $out .= '>' . $labeltoshow . '</option>';
12611 } else {
12612 if ($disabled && ($selected != $obj->rowid)) {
12613 $resultat = '';
12614 } else {
12615 $resultat = '<option value="' . $obj->rowid . '"';
12616 if ($disabled) {
12617 $resultat .= ' disabled';
12618 }
12619 $resultat .= '>';
12620 $resultat .= $labeltoshow;
12621 $resultat .= '</option>';
12622 }
12623 $out .= $resultat;
12624 }
12625 }
12626 }
12627 if (empty($option_only)) {
12628 $out .= '</select>';
12629 }
12630
12631 print $out;
12632
12633 $this->db->free($resql);
12634 return $num;
12635 } else {
12636 $this->errors[] = $this->db->lasterror;
12637 return -1;
12638 }
12639 }
12640
12641
12652 public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '', $arrayoffiltercriterias = array())
12653 {
12654 // TODO: Use $arrayoffiltercriterias param instead of $arrayofcriterias to include linked object fields in search
12655 global $langs, $form;
12656
12657 //require_once DOL_DOCUMENT_ROOT."/core/class/html.formother.class.php";
12658 //$formother = new FormOther($this->db);
12659
12660 if ($search_component_params_hidden != '' && !preg_match('/^\‍(.*\‍)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
12661 $search_component_params_hidden = '(' . $search_component_params_hidden . ')';
12662 }
12663
12664 $ret = '<!-- searchComponent -->';
12665
12666 $ret .= '<div class="divadvancedsearchfieldcomp centpercent inline-block">';
12667 $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
12668 $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="' . dol_escape_htmltag($langs->trans("Filters")) . '" id="idsubimgproductdistribution"></span>';
12669 $ret .= '</a>';
12670
12671 $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
12672
12673 // Show select fields as tags.
12674 $ret .= '<div id="divsearch_component_params" name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
12675
12676 if ($search_component_params_hidden) {
12677 // Split the criteria on each AND
12678 //var_dump($search_component_params_hidden);
12679
12680 $arrayofandtags = dolForgeExplodeAnd($search_component_params_hidden);
12681
12682 // $arrayofandtags is now array( '...' , '...', ...)
12683 // Show each AND part
12684 foreach ($arrayofandtags as $tmpkey => $tmpval) {
12685 $errormessage = '';
12686 $searchtags = forgeSQLFromUniversalSearchCriteria($tmpval, $errormessage, 1, 1);
12687 if ($errormessage) {
12688 $this->error = 'ERROR in parsing search string: '.$errormessage;
12689 }
12690 // Remove first and last parenthesis but only if first is the opening and last the closing of the same group
12691 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
12692 $searchtags = removeGlobalParenthesis($searchtags);
12693
12694 $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch" data-ufilterid="'.($tmpkey + 1).'" data-ufilter="'.dol_escape_htmltag($tmpval).'">';
12695 $ret .= '<span class="tagsearchdelete select2-selection__choice__remove" data-ufilterid="'.($tmpkey + 1).'">x</span> ';
12696 $ret .= dol_escape_htmltag($searchtags);
12697 $ret .= '</span>';
12698 }
12699 }
12700
12701 //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
12702
12703 //$ret .= search_component_params
12704 //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
12705 //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
12706
12707 $show_search_component_params_hidden = 1;
12708 if ($show_search_component_params_hidden) {
12709 $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
12710 }
12711 $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%')) -->";
12712 $ret .= '<input type="hidden" id="search_component_params_hidden" name="search_component_params_hidden" value="' . dol_escape_htmltag($search_component_params_hidden) . '">';
12713 // $ret .= "<!-- sql= ".forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage)." -->";
12714
12715 // TODO : Use $arrayoffiltercriterias instead of $arrayofcriterias
12716 // For compatibility with forms that show themself the search criteria in addition of this component, we output these fields
12717 foreach ($arrayofcriterias as $criteria) {
12718 foreach ($criteria as $criteriafamilykey => $criteriafamilyval) {
12719 if (in_array('search_' . $criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
12720 continue;
12721 }
12722 if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
12723 continue;
12724 }
12725 if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
12726 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_start">';
12727 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startyear">';
12728 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startmonth">';
12729 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startday">';
12730 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_end">';
12731 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endyear">';
12732 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endmonth">';
12733 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endday">';
12734 } else {
12735 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '">';
12736 }
12737 }
12738 }
12739
12740 $ret .= '</div>';
12741
12742 $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";
12743 $ret .= '<input type="text" placeholder="' . $langs->trans("Filters") . '" id="search_component_params_input" name="search_component_params_input" class="noborderall search_component_input" value="">';
12744
12745 $ret .= '</div>';
12746 $ret .= '</div>';
12747
12748 $ret .= '<script>
12749 jQuery(".tagsearchdelete").click(function(e) {
12750 var filterid = $(this).parents().attr("data-ufilterid");
12751 console.log("We click to delete the criteria nb "+filterid);
12752
12753 // Regenerate the search_component_params_hidden with all data-ufilter except the one to delete, and post the page
12754 var newparamstring = \'\';
12755 $(\'.tagsearch\').each(function(index, element) {
12756 tmpfilterid = $(this).attr("data-ufilterid");
12757 if (tmpfilterid != filterid) {
12758 // We keep this criteria
12759 if (newparamstring == \'\') {
12760 newparamstring = $(this).attr("data-ufilter");
12761 } else {
12762 newparamstring = newparamstring + \' AND \' + $(this).attr("data-ufilter");
12763 }
12764 }
12765 });
12766 console.log("newparamstring = "+newparamstring);
12767
12768 jQuery("#search_component_params_hidden").val(newparamstring);
12769
12770 // We repost the form
12771 $(this).closest(\'form\').submit();
12772 });
12773
12774 jQuery("#search_component_params_input").keydown(function(e) {
12775 console.log("We press a key on the filter field that is "+jQuery("#search_component_params_input").val());
12776 console.log(e.which);
12777 if (jQuery("#search_component_params_input").val() == "" && e.which == 8) {
12778 /* We click on back when the input field is already empty */
12779 event.preventDefault();
12780 jQuery("#divsearch_component_params .tagsearch").last().remove();
12781 /* Regenerate content of search_component_params_hidden from remaining .tagsearch */
12782 var s = "";
12783 jQuery("#divsearch_component_params .tagsearch").each(function( index ) {
12784 if (s != "") {
12785 s = s + " AND ";
12786 }
12787 s = s + $(this).attr("data-ufilter");
12788 });
12789 console.log("New value for search_component_params_hidden = "+s);
12790 jQuery("#search_component_params_hidden").val(s);
12791 }
12792 });
12793
12794 </script>
12795 ';
12796
12797 // Convert $arrayoffiltercriterias into a json object that can be used in jquery to build the search component dynamically
12798 $arrayoffiltercriterias_json = json_encode($arrayoffiltercriterias);
12799 $ret .= '<script>
12800 var arrayoffiltercriterias = ' . $arrayoffiltercriterias_json . ';
12801 </script>';
12802
12803
12804 $arrayoffilterfieldslabel = array();
12805 foreach ($arrayoffiltercriterias as $key => $val) {
12806 $arrayoffilterfieldslabel[$key]['label'] = $val['label'];
12807 $arrayoffilterfieldslabel[$key]['data-type'] = $val['type'];
12808 }
12809
12810 // Adding the div for search assistance
12811 $ret .= '<div class="search-component-assistance">';
12812 $ret .= '<div>';
12813
12814 $ret .= '<p class="assistance-title">' . img_picto('', 'filter') . ' ' . $langs->trans('FilterAssistance') . ' </p>';
12815
12816 $ret .= '<p class="assistance-errors error" style="display:none">' . $langs->trans('AllFieldsRequired') . ' </p>';
12817
12818 $ret .= '<div class="operand">';
12819 $ret .= $form->selectarray('search_filter_field', $arrayoffilterfieldslabel, '', $langs->trans("Fields"), 0, 0, '', 0, 0, 0, '', 'width200 combolargeelem', 1);
12820 $ret .= '</div>';
12821
12822 $ret .= '<span class="separator"></span>';
12823
12824 // Operator selector (will be populated dynamically)
12825 $ret .= '<div class="operator">';
12826 $ret .= '<select class="operator-selector width150" id="operator-selector"">';
12827 $ret .= '</select>';
12828 $ret .= '<script>$(document).ready(function() {';
12829 $ret .= ' $(".operator-selector").select2({';
12830 $ret .= ' placeholder: \'' . dol_escape_js($langs->transnoentitiesnoconv('Operator')) . '\'';
12831 $ret .= ' });';
12832 $ret .= '});</script>';
12833 $ret .= '</div>';
12834
12835 $ret .= '<span class="separator"></span>';
12836
12837 $ret .= '<div class="value">';
12838 // Input field for entering values
12839 $ret .= '<input type="text" class="flat width100 value-input" placeholder="' . dolPrintHTML($langs->trans('Value')) . '">';
12840
12841 // Date selector
12842 $dateOne = '';
12843 $ret .= '<span class="date-one" style="display:none">';
12844 $ret .= $form->selectDate(($dateOne ? $dateOne : -1), 'dateone', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '');
12845 $ret .= '</span>';
12846
12847 // Value selector (will be populated dynamically) based on search_filter_field value if a selected value has an array of values
12848 $ret .= '<select class="value-selector width150" id="value-selector" style="display:none">';
12849 $ret .= '</select>';
12850 $ret .= '<script>
12851 $(document).ready(function() {
12852 $("#value-selector").select2({
12853 placeholder: "' . dol_escape_js($langs->trans('Value')) . '"
12854 });
12855 $("#value-selector").hide();
12856 $("#value-selector").next(".select2-container").hide();
12857 });
12858 </script>';
12859
12860 $ret .= '</div>';
12861
12862 $ret .= '<div class="btn-div">';
12863 $ret .= '<button class="button buttongen button-save add-filter-btn" type="button">' . $langs->trans("addToFilter") . '</button>';
12864 $ret .= '</div>';
12865
12866 $ret .= '</div>';
12867 //$ret .= '</tbody></table>';
12868
12869 // End of the assistance div
12870 $ret .= '</div>';
12871
12872 // Script jQuery to show/hide the floating assistance
12873 $ret .= '<script>
12874 $(document).ready(function() {
12875 $("#search_component_params_input").on("click", function() {
12876 const inputPosition = $(this).offset();
12877 const inputHeight = $(this).outerHeight();
12878 $(".search-component-assistance").css({
12879 top: inputPosition.top + inputHeight + 5 + "px",
12880 left: $("#divsearch_component_params").position().left
12881 }).slideToggle(200);
12882 });
12883 $(document).on("click", function(e) {
12884 if (!$(e.target).closest("#search_component_params_input, .search-component-assistance, #ui-datepicker-div").length) {
12885 $(".search-component-assistance").hide();
12886 }
12887 });
12888 });
12889 </script>';
12890
12891 $ret .= '<script>
12892 $(document).ready(function() {
12893 $(".search_filter_field").on("change", function() {
12894 console.log("We change search_filter_field");
12895
12896 let maybenull = 0;
12897 const selectedField = $(this).find(":selected");
12898 let fieldType = selectedField.data("type");
12899 const selectedFieldValue = selectedField.val();
12900
12901 // If the selected field has an array of values then ask toshow the value selector instead of the value input
12902 if (arrayoffiltercriterias[selectedFieldValue]["arrayofkeyval"] !== undefined) {
12903 fieldType = "select";
12904 }
12905
12906 // If the selected field may be null then ask to append the "IsDefined" and "IsNotDefined" operators
12907 if (arrayoffiltercriterias[selectedFieldValue]["maybenull"] !== undefined) {
12908 maybenull = 1;
12909 }
12910 const operators = getOperatorsForFieldType(fieldType, maybenull);
12911 const operatorSelector = $(".operator-selector");
12912
12913 // Clear existing options
12914 operatorSelector.empty();
12915
12916 // Populate operators
12917 Object.entries(operators).forEach(function([operator, label]) {
12918 operatorSelector.append("<option value=\'" + operator + "\'>" + label + "</option>");
12919 });
12920
12921 operatorSelector.trigger("change.select2");
12922
12923 // Clear and hide all input elements initially
12924 $(".value-input, .dateone, .datemonth, .dateyear").val("").hide();
12925 $("#datemonth, #dateyear").val(null).trigger("change.select2");
12926 $("#dateone").datepicker("setDate", null);
12927 $(".date-one, .date-month, .date-year").hide();
12928 $("#value-selector").val("").hide();
12929 $("#value-selector").next(".select2-container").hide();
12930 $("#value-selector").val(null).trigger("change.select2");
12931
12932 if (fieldType === "date" || fieldType === "datetime" || fieldType === "timestamp") {
12933 $(".date-one").show();
12934 } else if (arrayoffiltercriterias[selectedFieldValue]["arrayofkeyval"] !== undefined) {
12935 var arrayofkeyval = arrayoffiltercriterias[selectedFieldValue]["arrayofkeyval"];
12936 var valueSelector = $("#value-selector");
12937 valueSelector.empty();
12938 Object.entries(arrayofkeyval).forEach(function([key, val]) {
12939 valueSelector.append("<option value=\'" + key + "\'>" + val + "</option>");
12940 });
12941 valueSelector.trigger("change.select2");
12942
12943 $("#value-selector").show();
12944 $("#value-selector").next(".select2-container").show();
12945 } else {
12946 $(".value-input").show();
12947 }
12948 });
12949
12950 $("#operator-selector").on("change", function() {
12951 console.log("We change operator-selector");
12952
12953 const selectedOperator = $(this).find(":selected").val();
12954 if (selectedOperator === "IsDefined" || selectedOperator === "IsNotDefined") {
12955 // Disable all value input elements
12956 $(".value-input, .dateone, .datemonth, .dateyear").val("").prop("disabled", true);
12957 $("#datemonth, #dateyear").val(null).trigger("change.select2");
12958 $("#dateone").datepicker("setDate", null).datepicker("option", "disabled", true);
12959 $(".date-one, .date-month, .date-year").prop("disabled", true);
12960 $("#value-selector").val("").prop("disabled", true);
12961 $("#value-selector").val(null).trigger("change.select2");
12962 } else {
12963 // Enable all value input elements
12964 $(".value-input, .dateone, .datemonth, .dateyear").prop("disabled", false);
12965 $(".date-one, .date-month, .date-year").prop("disabled", false);
12966 $("#dateone").datepicker("option", "disabled", false);
12967 $("#value-selector").prop("disabled", false);
12968 }
12969 });
12970
12971 $(".add-filter-btn").on("click", function(event) {
12972 console.log("We click on add-filter-btn");
12973
12974 event.preventDefault();
12975
12976 const field = $(".search_filter_field").val();
12977 const operator = $(".operator-selector").val();
12978 let value = $(".value-input").val();
12979 const fieldType = $(".search_filter_field").find(":selected").data("type");
12980
12981 if (["date", "datetime", "timestamp"].includes(fieldType)) {
12982 const year = $("#dateoneyear").val().toString().padStart(4, "0");;
12983 const month = $("#dateonemonth").val().toString().padStart(2, "0");
12984 const day = $("#dateoneday").val().toString().padStart(2, "0");
12985 value = `${year}-${month}-${day}`;
12986 console.log("value="+value);
12987 }
12988
12989 // If the selected field has an array of values then take the selected value
12990 if (arrayoffiltercriterias[field]["arrayofkeyval"] !== undefined) {
12991 value = $("#value-selector").val();
12992 }
12993
12994 // If the operator is "IsDefined" or "IsNotDefined" then set the value to 1 (it will not be used)
12995 if (operator === "IsDefined" || operator === "IsNotDefined") {
12996 value = "1";
12997 }
12998
12999 const filterString = generateFilterString(field, operator, value, fieldType);
13000
13001 // Submit the form
13002 if (filterString !== "" && field !== "" && operator !== "" && value !== "") {
13003 $("#search_component_params_input").val($("#search_component_params_input").val() + " " + filterString);
13004 $("#search_component_params_input").closest("form").submit();
13005 } else {
13006 $(".assistance-errors").show();
13007 }
13008 });
13009 });
13010 </script>';
13011
13012 return $ret;
13013 }
13014
13026 public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0, $selected = 0, $morecss = '')
13027 {
13028 global $langs, $user;
13029
13030 $retstring = '';
13031
13032 $TModels = array();
13033
13034 include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
13035 $formmail = new FormMail($this->db);
13036 $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
13037
13038 if ($default) {
13039 $TModels[0] = $langs->trans('DefaultMailModel');
13040 }
13041 if ($result > 0) {
13042 foreach ($formmail->lines_model as $model) {
13043 $TModels[(int) $model->id] = $model->label;
13044 }
13045 }
13046
13047 $retstring .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_' . $prefix . 'model_mail" name="' . $prefix . 'model_mail">';
13048
13049 foreach ($TModels as $id_model => $label_model) {
13050 $retstring .= '<option value="' . $id_model . '"';
13051 if (!empty($selected) && ((int) $selected) == $id_model) {
13052 $retstring .= "selected";
13053 }
13054 $retstring .= ">" . $label_model . "</option>";
13055 }
13056
13057 $retstring .= "</select>";
13058
13059 if ($addjscombo) {
13060 $retstring .= ajax_combobox('select_' . $prefix . 'model_mail');
13061 }
13062
13063 return $retstring;
13064 }
13065
13077 public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = false, $morecss = '', $dol_openinpopup = '')
13078 {
13079 global $langs;
13080
13081 $buttons = array();
13082
13083 $save = array(
13084 'name' => 'save',
13085 'label_key' => $save_label,
13086 );
13087
13088 if ($save_label == 'Create' || $save_label == 'Add') {
13089 $save['name'] = 'add';
13090 } elseif ($save_label == 'Modify') {
13091 $save['name'] = 'edit';
13092 }
13093
13094 $cancel = array(
13095 'name' => 'cancel',
13096 'label_key' => 'Cancel',
13097 );
13098
13099 // If MAIN_BUTTON_POSITION_FIRST_OR_LEFT not set, default is to have main action first, then complementary, then cancel at end
13100 if (!getDolGlobalInt('MAIN_BUTTON_POSITION_FIRST_OR_LEFT')) {
13101 !empty($save_label) ? $buttons[] = $save : '';
13102 if (!empty($morebuttons)) {
13103 $buttons[] = $morebuttons;
13104 }
13105 !empty($cancel_label) ? $buttons[] = $cancel : '';
13106 } else {
13107 if (!empty($morebuttons)) {
13108 $buttons[] = $morebuttons;
13109 }
13110 !empty($cancel_label) ? $buttons[] = $cancel : '';
13111 !empty($save_label) ? $buttons[] = $save : '';
13112 }
13113
13114 $retstring = $withoutdiv ? '' : '<div class="center">';
13115
13116 foreach ($buttons as $button) {
13117 $addclass = empty($button['addclass']) ? '' : $button['addclass'];
13118 $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'])) . '">';
13119 }
13120 $retstring .= $withoutdiv ? '' : '</div>';
13121
13122 if ($dol_openinpopup) {
13123 $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . dol_escape_htmltag($dol_openinpopup) . ' context, so we enable the close of dialog on cancel -->' . "\n";
13124 $retstring .= '<script nonce="' . getNonce() . '">';
13125 $retstring .= 'jQuery(".button-cancel").click(function(e) {
13126 e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . dol_escape_js($dol_openinpopup) . '\');
13127 window.parent.jQuery(\'#idfordialog' . dol_escape_js($dol_openinpopup) . '\').dialog(\'close\');
13128 });';
13129 $retstring .= '</script>';
13130 }
13131
13132 return $retstring;
13133 }
13134
13135
13136 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
13137
13144 {
13145 // phpcs:enable
13146 global $langs;
13147
13148 $num = count($this->cache_invoice_subtype);
13149 if ($num > 0) {
13150 return 0; // Cache already loaded
13151 }
13152
13153 dol_syslog(__METHOD__, LOG_DEBUG);
13154
13155 $sql = "SELECT rowid, code, label as label";
13156 $sql .= " FROM " . MAIN_DB_PREFIX . 'c_invoice_subtype';
13157 $sql .= " WHERE active = 1";
13158
13159 $resql = $this->db->query($sql);
13160 if ($resql) {
13161 $num = $this->db->num_rows($resql);
13162 $i = 0;
13163 while ($i < $num) {
13164 $obj = $this->db->fetch_object($resql);
13165
13166 // If translation exists, we use it, otherwise we take the default wording
13167 $label = ($langs->trans("InvoiceSubtype" . $obj->rowid) != "InvoiceSubtype" . $obj->rowid) ? $langs->trans("InvoiceSubtype" . $obj->rowid) : (($obj->label != '-') ? $obj->label : '');
13168 $this->cache_invoice_subtype[$obj->rowid]['rowid'] = $obj->rowid;
13169 $this->cache_invoice_subtype[$obj->rowid]['code'] = $obj->code;
13170 $this->cache_invoice_subtype[$obj->rowid]['label'] = $label;
13171 $i++;
13172 }
13173
13174 $this->cache_invoice_subtype = dol_sort_array($this->cache_invoice_subtype, 'code', 'asc', 0, 0, 1);
13175
13176 return $num;
13177 } else {
13178 dol_print_error($this->db);
13179 return -1;
13180 }
13181 }
13182
13183
13194 public function getSelectInvoiceSubtype($selected = 0, $htmlname = 'subtypeid', $addempty = 0, $noinfoadmin = 0, $morecss = '')
13195 {
13196 global $langs, $user;
13197
13198 $out = '';
13199 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
13200
13201 $this->load_cache_invoice_subtype();
13202
13203 $out .= '<select id="' . $htmlname . '" class="flat selectsubtype' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
13204 if ($addempty) {
13205 $out .= '<option value="0">&nbsp;</option>';
13206 }
13207
13208 foreach ($this->cache_invoice_subtype as $rowid => $subtype) {
13209 $label = $subtype['label'];
13210 $out .= '<option value="' . $subtype['rowid'] . '"';
13211 if ($selected == $subtype['rowid']) {
13212 $out .= ' selected="selected"';
13213 }
13214 $out .= '>';
13215 $out .= $label;
13216 $out .= '</option>';
13217 }
13218
13219 $out .= '</select>';
13220 if ($user->admin && empty($noinfoadmin)) {
13221 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
13222 }
13223 $out .= ajax_combobox($htmlname);
13224
13225 return $out;
13226 }
13227
13237 public function getSearchFilterToolInput($dataTarget, $htmlName = 'search-tools-input', $value = '', $params = [])
13238 {
13239 global $langs;
13240
13241 $attr = array(
13242 'type' => 'search',
13243 'name' => $htmlName,
13244 'value' => $value,
13245 'class' => "search-tool-input",
13246 'placeholder' => $langs->trans('Search'),
13247 'autocomplete' => 'off'
13248 );
13249
13250 // Optional data attr
13251 // 'autofocus' : will set auto focus on field ,
13252 // data-counter-target : will get count results
13253 // data-no-item-target : will be display if count results is 0
13254
13255 if ($dataTarget !== false) {
13256 $attr['data-search-tool-target'] = $dataTarget;
13257 }
13258
13259 // Override attr
13260 if (!empty($params['attr']) && is_array($params['attr'])) {
13261 foreach ($params['attr'] as $key => $value) {
13262 if ($key == 'class') {
13263 $attr['class'] .= ' '.$value;
13264 } elseif ($key == 'classOverride') {
13265 $attr['class'] = $value;
13266 } else {
13267 $attr[$key] = $value;
13268 }
13269 }
13270 }
13271
13272 // automatic add tooltip when title is detected
13273 if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
13274 $attr['class'] .= ' classfortooltip';
13275 }
13276
13277 $TCompiledAttr = [];
13278 foreach ($attr as $key => $value) {
13279 if (in_array($key, ['data-target'])
13280 || (!empty($params['use_unsecured_unescapedattr']) && is_array($params['use_unsecured_unescapedattr']) && in_array($key, $params['use_unsecured_unescapedattr']))) { // Not recommended
13281 $value = dol_htmlentities($value, ENT_QUOTES | ENT_SUBSTITUTE);
13282 } else {
13283 $value = dolPrintHTMLForAttribute($value);
13284 }
13285
13286 $TCompiledAttr[] = $key . '="' . $value . '"'; // $value has been escaped by the dolPrintHTMLForAttribute... just before
13287 }
13288
13289 $compiledAttributes = implode(' ', $TCompiledAttr);
13290
13291
13292 return '<div class="search-tool-container"><input '.$compiledAttributes.'></div>';
13293 }
13294
13308 public function inputType($type, $name, $value = '', $id = '', $morecss = '', $moreparam = '', $label = '', $addInputLabel = '')
13309 {
13310 $out = '';
13311 if ($label != '') {
13312 $out .= '<label for="' . dolPrintHTMLForAttribute($id) . '">';
13313 }
13314 $out .= '<input type="' . dolPrintHTMLForAttribute($type) . '"';
13315 $out .= ' class="flat valignmiddle maxwidthonsmartphone ' . dolPrintHTMLForAttribute($morecss) . '"';
13316 if ($id != '') {
13317 $out .= ' id="' . dolPrintHTMLForAttribute($id) . '"';
13318 }
13319 $out .= ' name="' . dolPrintHTMLForAttribute($name) . '"';
13320 $out .= ' value="' . dolPrintHTMLForAttribute($value) . '" ';
13321 $out .= ($moreparam ? ' ' . $moreparam : '');
13322 $out .= ' />' . $addInputLabel;
13323 if ($label != '') {
13324 $out .= $label . '</label>';
13325 }
13326
13327 return $out;
13328 }
13329
13342 public function inputSelectAjax($htmlName, $array, $id, $ajaxUrl, $ajaxData = [], $morecss = 'minwidth75', $moreparam = '')
13343 {
13344 $out = "
13345 <script>
13346 $(document).ready(function () {
13347 $('#" . $htmlName . "').select2({
13348 ajax: {
13349 url: '" . $ajaxUrl . "',
13350 dataType: 'json',
13351 delay: 250, // wait 250 milliseconds before triggering the request
13352 data: function (params) {
13353 var query = {
13354 search: params.term,
13355 page: params.page || 1";
13356 if (!empty($ajaxData) && is_array($ajaxData)) {
13357 foreach ($ajaxData as $key => $value) {
13358 $out .= ", " . $key . ": '" . $value . "'";
13359 }
13360 }
13361 $out .= "
13362 }
13363 return query;
13364 }
13365 }
13366 })
13367 });
13368 </script>";
13369
13370 $out .= $this->selectarray($htmlName, $array, $id, 0, 0, 0, $moreparam, 0, 0, 0, '', $morecss);
13371
13372 return $out;
13373 }
13374
13384 public function inputHtml($htmlName, $value, $morecss = '', $moreparam = '')
13385 {
13386 require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
13387 $doleditor = new DolEditor($htmlName, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_5, '90%');
13388
13389 return (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
13390 }
13391
13402 public function inputText($htmlName, $value, $morecss = '', $moreparam = '', $options = array())
13403 {
13404 global $langs;
13405
13406 $out = '';
13407 if (!empty($options)) {
13408 // If the textarea field has a list of arrayofkeyval into its definition, we suggest a combo with possible values to fill the textarea.
13409 $out .= $this->selectarray($htmlName . "_multiinput", $options, '', 1, 0, 0, $moreparam, 0, 0, 0, '', "flat maxwidthonphone" . $morecss);
13410 $out .= '<input id="' . $htmlName . '_multiinputadd" type="button" class="button" value="' . $langs->trans("Add") . '">';
13411 $out .= "<script>";
13412 $out .= '
13413 function handlemultiinputdisabling(htmlname){
13414 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
13415 multiinput = $("#"+htmlname+"_multiinput");
13416 multiinput.find("option").each(function(){
13417 tmpval = $("#"+htmlname).val();
13418 tmpvalarray = tmpval.split("\n");
13419 valtotest = $(this).val();
13420 if(tmpvalarray.includes(valtotest)){
13421 $(this).prop("disabled",true);
13422 } else {
13423 if($(this).prop("disabled") == true){
13424 console.log(valtotest)
13425 $(this).prop("disabled", false);
13426 }
13427 }
13428 });
13429 }
13430
13431 $(document).ready(function () {
13432 $("#' . $htmlName . '_multiinputadd").on("click",function() {
13433 tmpval = $("#' . $htmlName . '").val();
13434 tmpvalarray = tmpval.split(",");
13435 valtotest = $("#' . $htmlName . '_multiinput").val();
13436 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
13437 console.log("We add the selected value to the text area ' . $htmlName . '");
13438 if(tmpval == ""){
13439 tmpval = valtotest;
13440 } else {
13441 tmpval = tmpval + "\n" + valtotest;
13442 }
13443 $("#' . $htmlName . '").val(tmpval);
13444 handlemultiinputdisabling("' . $htmlName . '");
13445 $("#' . $htmlName . '_multiinput").val(-1);
13446 } else {
13447 console.log("We add nothing the text area ' . $htmlName . '");
13448 }
13449 });
13450 $("#' . $htmlName . '").on("change",function(){
13451 handlemultiinputdisabling("' . $htmlName . '");
13452 });
13453 handlemultiinputdisabling("' . $htmlName . '");
13454 })';
13455 $out .= "</script>";
13456 $value = str_replace(',', "\n", $value);
13457 }
13458
13459 require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
13460 $doleditor = new DolEditor($htmlName, (string) $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
13461 $out .= (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
13462
13463 return $out;
13464 }
13465
13476 public function inputRadio($htmlName, $options, $selectedValue, $morecss = '', $moreparam = '')
13477 {
13478 $out = '';
13479 foreach ($options as $optionKey => $optionLabel) {
13480 $selected = ((string) $selectedValue) === ((string) $optionKey) ? ' checked="checked"' : '';
13481 $optionId = $htmlName . '_' . $optionKey;
13482 $out .= '<input class="flat' . $morecss . '" type="radio" name="' . $htmlName . '" id="' . $optionId . '" value="' . dolPrintHTMLForAttribute((string) $optionKey) . '"' . $selected . $moreparam . '/><label for="' . $optionId . '">' . $optionLabel . '</label><br>';
13483 }
13484
13485 return $out;
13486 }
13487
13498 public function inputStars($htmlName, $size, $value, $morecss = '', $moreparam = '')
13499 {
13500 $out = '<input type="hidden" class="flat ' . $morecss . '" name="' . $htmlName . '" id="' . $htmlName . '" value="' . dolPrintHTMLForAttribute((string) $value) . '"' . $moreparam . '>';
13501 $out .= '<div class="star-selection" id="' . $htmlName . '_selection">';
13502 for ($i = 1; $i <= $size; $i++) {
13503 $out .= '<span class="star" data-value="' . $i . '">' . img_picto('', 'fontawesome_star_fas') . '</span>';
13504 }
13505 $out .= '</div>';
13506 $out .= '<script>
13507 jQuery(function($) { /* commonobject.class.php 1 */
13508 let container = $("#' . $htmlName . '_selection");
13509 let selectedStars = parseInt($("#' . $htmlName . '").val()) || 0;
13510 container.find(".star").each(function() {
13511 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
13512 });
13513 container.find(".star").on("mouseover", function() {
13514 let selectedStar = $(this).data("value");
13515 container.find(".star").each(function() {
13516 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
13517 });
13518 });
13519 container.on("mouseout", function() {
13520 container.find(".star").each(function() {
13521 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
13522 });
13523 });
13524 container.find(".star").off("click").on("click", function() {
13525 selectedStars = $(this).data("value");
13526 if (selectedStars === 1 && $("#' . $htmlName . '").val() == 1) {
13527 selectedStars = 0;
13528 }
13529 $("#' . $htmlName . '").val(selectedStars);
13530 container.find(".star").each(function() {
13531 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
13532 });
13533 });
13534 });
13535 </script>';
13536
13537 return $out;
13538 }
13539
13549 public function inputIcon($htmlName, $value, $morecss = '', $moreparam = '')
13550 {
13551 global $langs;
13552
13553 /* External lib inclusion are not allowed in backoffice. Also lib is included several time if there is several icon file.
13554 Some code must be added into main when MAIN_ADD_ICONPICKER_JS is set to add of lib in html header
13555 $out ='<link rel="stylesheet" href="'.dol_buildpath('/myfield/css/fontawesome-iconpicker.min.css', 1).'">';
13556 $out.='<script src="'.dol_buildpath('/myfield/js/fontawesome-iconpicker.min.js', 1).'"></script>';
13557 */
13558 $out = '<input type="text" class="form-control icp icp-auto iconpicker-element iconpicker-input flat ' . $morecss . ' maxwidthonsmartphone"';
13559 $out .= ' name="' . $htmlName . '" id="' . $htmlName . '" value="' . dolPrintHTMLForAttribute((string) $value) . '" ' . ((string) $moreparam) . '>';
13560 if (getDolGlobalInt('MAIN_ADD_ICONPICKER_JS')) {
13561 $out .= '<script>';
13562 $options = "{ title: '<b>" . $langs->trans("IconFieldSelector") . "</b>', placement: 'right', showFooter: false, templates: {";
13563 $options .= "iconpicker: '<div class=\"iconpicker\"><div style=\"background-color:#EFEFEF;\" class=\"iconpicker-items\"></div></div>',";
13564 $options .= "iconpickerItem: '<a role=\"button\" href=\"#\" class=\"iconpicker-item\" style=\"background-color:#DDDDDD;\"><i></i></a>',";
13565 // $options.="buttons: '<button style=\"background-color:#FFFFFF;\" class=\"iconpicker-btn iconpicker-btn-cancel btn btn-default btn-sm\">".$langs->trans("Cancel")."</button>";
13566 // $options.="<button style=\"background-color:#FFFFFF;\" class=\"iconpicker-btn iconpicker-btn-accept btn btn-primary btn-sm\">".$langs->trans("Save")."</button>',";
13567 $options .= "footer: '<div class=\"popover-footer\" style=\"background-color:#EFEFEF;\"></div>',";
13568 $options .= "search: '<input type=\"search\" class\"form-control iconpicker-search\" placeholder=\"" . $langs->trans("TypeToFilter") . "\" />',";
13569 $options .= "popover: '<div class=\"iconpicker-popover popover\">";
13570 $options .= " <div class=\"arrow\" ></div>";
13571 $options .= " <div class=\"popover-title\" style=\"text-align:center;background-color:#EFEFEF;\"></div>";
13572 $options .= " <div class=\"popover-content \" ></div>";
13573 $options .= "</div>'}}";
13574 $out .= "$('#" . $htmlName . "').iconpicker(" . $options . ");";
13575 $out .= '</script>';
13576 }
13577
13578 return $out;
13579 }
13580
13589 public function inputGeoPoint($htmlName, $value, $type = '')
13590 {
13591 require_once DOL_DOCUMENT_ROOT . '/core/class/dolgeophp.class.php';
13592 require_once DOL_DOCUMENT_ROOT . '/core/class/geomapeditor.class.php';
13593 $dolgeophp = new DolGeoPHP($this->db);
13594 $geomapeditor = new GeoMapEditor();
13595
13596 $geojson = '{}';
13597 $centroidjson = getDolGlobalString('MAIN_INFO_SOCIETE_GEO_COORDINATES', '{}');
13598 if (!empty($value)) {
13599 $tmparray = $dolgeophp->parseGeoString($value);
13600 $geojson = $tmparray['geojson'];
13601 $centroidjson = $tmparray['centroidjson'];
13602 }
13603
13604 return $geomapeditor->getHtml($htmlName, $geojson, $centroidjson, $type);
13605 }
13606
13613 public function outputMultiValues($values)
13614 {
13615 $out = '';
13616 $toPrint = array();
13617 $values = is_array($values) ? $values : array();
13618
13619 foreach ($values as $value) {
13620 $toPrint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $value . '</li>';
13621 }
13622 if (!empty($toPrint)) {
13623 $out = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toPrint) . '</ul></div>';
13624 }
13625
13626 return $out;
13627 }
13628
13636 public function outputStars($size, $value)
13637 {
13638 $out = '<div class="star-selection" data-value="' . dolPrintHTMLForAttribute((string) $value) . '">';
13639 for ($i = 1; $i <= $size; $i++) {
13640 $out .= '<span class="star' . ($i <= $value ? ' active' : '') . '" data-value="' . $i . '">' . img_picto('', 'fontawesome_star_fas') . '</span>';
13641 }
13642 $out .= '</div>';
13643
13644 return $out;
13645 }
13646
13653 public function outputIcon($value)
13654 {
13655 $out = '<span class="' . dolPrintHTMLForAttribute((string) $value) . '"></span>';
13656
13657 return $out;
13658 }
13659
13667 public function outputGeoPoint($value, $type)
13668 {
13669 $out = '';
13670
13671 if (!empty($value)) {
13672 require_once DOL_DOCUMENT_ROOT . '/core/class/dolgeophp.class.php';
13673 $dolgeophp = new DolGeoPHP($this->db);
13674 if ($type == 'point') {
13675 $out = $dolgeophp->getXYString($value);
13676 } else { // multipts, linestrg, polygon
13677 $out = $dolgeophp->getPointString($value);
13678 }
13679 }
13680
13681 return $out;
13682 }
13683
13698 public function getNomUrl(&$object, $withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '', $add_label = 0, $sep = ' - ')
13699 {
13700 if (is_object($object) && method_exists($object, 'getNomUrl')) {
13701 $out = $object->getNomUrl($withpicto, $option, $maxlength, $save_lastsearch_value, $notooltip, $morecss, $add_label, $sep);
13702 return $out;
13703 } else {
13704 return '';
13705 }
13706 }
13707}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
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:50
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:476
ajax_multiautocompleter($htmlname, $fields, $url, $option='', $minLength=2, $autoselect=0)
Generic function that return javascript to add to a page to transform a common input text field into ...
Definition ajax.lib.php:325
ajax_event($htmlname, $events)
Add event management script.
Definition ajax.lib.php:599
$c
Definition line.php:334
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 for ConferenceOrBoothAttendee.
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 invoices.
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.
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)
Return select list of users.
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.
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)
Return select list of users.
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.
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_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)
Output html form to select a third party This call select_thirdparty_list() or ajax depending on setu...
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_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='')
Output html form to select a contact This call select_contacts() or ajax depending on setup.
select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array(), $disableautocomplete=0)
Return select list of incoterms.
select_type_of_lines($selected='', $htmlname='type', $showempty=0, $hidetext=0, $forceall=0, $morecss="", $useajaxcombo=1)
Return list of types of lines (product or service) Example: 0=product, 1=service, 9=other (for extern...
selectModelMail($prefix, $modelType='', $default=0, $addjscombo=0, $selected=0, $morecss='')
selectModelMail
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.
static multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='', $nu='', $placeholder='', $addjscombo=-1)
Show a multiselect form from an array.
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.
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='')
Return HTML code of the SELECT of list of all contacts (for a third party or all).
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.
select_type_fees($selected='', $htmlname='type', $showempty=0)
Return list of types of notes.
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.
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.
form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1, $addempty=0, $type='', $nooutput=0)
Show form with payment mode.
constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0, $filterkey='', $novirtualstock=0)
Function to forge the string with OPTIONs of SELECT.
buttonsSaveCancel($save_label='Save', $cancel_label='Cancel', $morebuttons=array(), $withoutdiv=false, $morecss='', $dol_openinpopup='')
Output the buttons to submit a creation/edit form.
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.
select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
Return HTML combo list of absolute discounts.
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)
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.
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)
Output html form to select a third party.
select_users($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly=array(), $force_entity='0')
Return the HTML select list of users.
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.
makeAddLinkToObject($object, $key, $possiblelink, $num, $resqllist)
Generate HTML table rows for standard object linking (invoices, orders, proposals,...
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.
formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=0, $width=600, $disableformtag=0, $labelbuttonyes='Yes', $labelbuttonno='No', $helpContent='')
Show a confirmation HTML form or AJAX popup.
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.
load_cache_types_fees()
Load into cache cache_types_fees, array of types of fees.
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.
makeAddLinkToAttendee($object, $key, $possiblelink, $num, $resqllist)
Generate HTML table rows for conference/booth attendee linking.
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 a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
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 to manage hooks.
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
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
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
dol_print_phone($phone, $countrycode='', $contactid=0, $socid=0, $addlink='', $separ="&nbsp;", $withpicto='', $titlealt='', $adddivfloat=0, $morecss='paddingright')
Format phone numbers according to country.
commonHtmlAttributeBuilder($attr, array $unescapedAttr=[])
Builds an array of safe and properly escaped HTML attributes from a key-value pair list.
img_help($usehelpcursor=1, $usealttitle=1)
Show help logo with cursor "?".
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
dolPrintHTML($s, $allowiframe=0, $moreallowedtags=array())
Return a string (that can be on several lines) ready to be output on a HTML page.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
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.
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.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
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.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
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.
showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no', $use_short_label=0)
Output a dimension with best unit.
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.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
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.
getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
Return URL we can use for advanced preview links.
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
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.
img_edit($titlealt='default', $float=0, $other='')
Show logo edit/modify fiche.
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...
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.
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...
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
a disabled
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
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, $db=null)
Parse a stored phone number into country code and number parts.
Definition phone.lib.php:37
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.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:137
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140
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.
testSqlAndScriptInject($val, $type)
Security: WAF layer for SQL Injection and XSS Injection (scripts) protection (Filters on GET,...
Definition waf.inc.php:103