dolibarr 23.0.4
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-2025 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-2025 MDW <mdeweerd@users.noreply.github.com>
27 * Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
28 *
29 * This program is free software; you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation; either version 3 of the License, or
32 * (at your option) any later version.
33 *
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
38 *
39 * You should have received a copy of the GNU General Public License
40 * along with this program. If not, see <https://www.gnu.org/licenses/>.
41 */
42
56class Form
57{
61 public $db;
62
66 public $error = '';
67
71 public $errors = array();
72
73 // Some properties used to return data by some methods
75 public $result;
76
78 public $num;
79
80 // Cache arrays
82 public $cache_types_paiements = array();
84 public $cache_conditions_paiements = array();
86 public $cache_transport_mode = array();
88 public $cache_availability = array();
90 public $cache_demand_reason = array();
92 public $cache_types_fees = array();
94 public $cache_vatrates = array();
96 public $cache_invoice_subtype = array();
98 public $cache_rule_for_lines_dates = array();
99
100
106 public function __construct($db)
107 {
108 $this->db = $db;
109 }
110
119 public function getDurationTypes(Translate $langs, $plurial = true, $reverse = false)
120 {
121 if ($plurial) {
122 $arrayoftypes = [
123 'y' => $langs->trans('Years'),
124 'm' => $langs->trans('Month'),
125 'w' => $langs->trans('Weeks'),
126 'd' => $langs->trans('Days'),
127 'h' => $langs->trans('Hours'),
128 'i' => $langs->trans('Minutes'),
129 's' => $langs->trans('Seconds'),
130 ];
131 } else {
132 $arrayoftypes = [
133 "y" => $langs->trans("Year"),
134 "m" => $langs->trans("Month"),
135 "w" => $langs->trans("Week"),
136 "d" => $langs->trans("Day"),
137 "h" => $langs->trans("Hour"),
138 "i" => $langs->trans("Minute"),
139 's' => $langs->trans('Second'),
140 ];
141 }
142 if ($reverse) {
143 return array_reverse($arrayoftypes);
144 } else {
145 return $arrayoftypes;
146 }
147 }
148
165 public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
166 {
167 global $langs;
168
169 $ret = '';
170
171 // TODO change for compatibility
172 if (getDolGlobalString('MAIN_USE_JQUERY_JEDITABLE') && !preg_match('/^select;/', $typeofdata)) {
173 if ($perm) {
174 $tmp = explode(':', $typeofdata);
175 $ret .= '<div class="editkey_' . $tmp[0] . (!empty($tmp[1]) ? ' ' . $tmp[1] : '') . '" id="' . $htmlname . '">';
176 if ($fieldrequired) {
177 $ret .= '<span class="fieldrequired">';
178 }
179 if ($help) {
180 $ret .= $this->textwithpicto($langs->trans($text), $help);
181 } else {
182 $ret .= $langs->trans($text);
183 }
184 if ($fieldrequired) {
185 $ret .= '</span>';
186 }
187 $ret .= '</div>' . "\n";
188 } else {
189 if ($fieldrequired) {
190 $ret .= '<span class="fieldrequired">';
191 }
192 if ($help) {
193 $ret .= $this->textwithpicto($langs->trans($text), $help);
194 } else {
195 $ret .= $langs->trans($text);
196 }
197 if ($fieldrequired) {
198 $ret .= '</span>';
199 }
200 }
201 } else {
202 if (empty($notabletag) && $perm) {
203 $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
204 }
205 if ($fieldrequired) {
206 $ret .= '<span class="fieldrequired">';
207 }
208 if ($help) {
209 $ret .= $this->textwithpicto($langs->trans($text), $help);
210 } else {
211 $ret .= $langs->trans($text);
212 }
213 if ($fieldrequired) {
214 $ret .= '</span>';
215 }
216 if (!empty($notabletag)) {
217 $ret .= ' ';
218 }
219 if (empty($notabletag) && $perm) {
220 $ret .= '</td>';
221 }
222 if (empty($notabletag) && $perm) {
223 $ret .= '<td class="right">';
224 }
225 if ($htmlname && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm && is_object($object)) {
226 $ret .= '<a class="editfielda reposition" href="' . dolBuildUrl($_SERVER["PHP_SELF"], ['action' => 'edit' . $htmlname, $paramid => $object->id], true) . $moreparam . '">';
227 $ret .= img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1));
228 $ret .= '</a>';
229 }
230 if (!empty($notabletag) && $notabletag == 1) {
231 if ($text) {
232 $ret .= ' : ';
233 } else {
234 $ret .= ' ';
235 }
236 }
237 if (!empty($notabletag) && $notabletag == 3) {
238 $ret .= ' ';
239 }
240 if (empty($notabletag) && $perm) {
241 $ret .= '</td>';
242 }
243 if (empty($notabletag) && $perm) {
244 $ret .= '</tr></table>';
245 }
246 }
247
248 return $ret;
249 }
250
274 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 = '')
275 {
276 global $conf, $langs;
277
278 $ret = '';
279
280 // Check parameters
281 if (empty($typeofdata)) {
282 return 'ErrorBadParameter typeofdata is empty';
283 }
284 // Clean parameter $typeofdata
285 if ($typeofdata == 'datetime') {
286 $typeofdata = 'dayhour';
287 }
288 $reg = array();
289 if (preg_match('/^(\w+)\‍((\d+)\‍)$/', $typeofdata, $reg)) {
290 if ($reg[1] == 'varchar') {
291 $typeofdata = 'string';
292 } elseif ($reg[1] == 'int') {
293 $typeofdata = 'numeric';
294 } else {
295 return 'ErrorBadParameter ' . $typeofdata;
296 }
297 }
298
299 // When option to edit inline is activated
300 if (getDolGlobalString('MAIN_USE_JQUERY_JEDITABLE') && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) {
301 $ret .= $this->editInPlace($object, $value, $htmlname, ($perm ? 1 : 0), $typeofdata, $editvalue, $extObject, $custommsg);
302 } else {
303 if ($editaction == '') {
304 $editaction = GETPOST('action', 'aZ09');
305 }
306 $editmode = ($editaction == 'edit' . $htmlname);
307 if ($editmode) { // edit mode
308 $ret .= "<!-- formeditfieldval -->\n";
309 $ret .= '<form method="post" action="' . $_SERVER["PHP_SELF"] . ($moreparam ? '?' . $moreparam : '') . '">';
310 $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
311 $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
312 $ret .= '<input type="hidden" name="' . $paramid . '" value="' . $object->id . '">';
313 if (empty($notabletag)) {
314 $ret .= '<table class="nobordernopadding centpercent">';
315 }
316 if (empty($notabletag)) {
317 $ret .= '<tr><td>';
318 }
319 if (preg_match('/^(string|safehtmlstring|email|phone|url)/', $typeofdata)) {
320 $tmp = explode(':', $typeofdata);
321 $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($editvalue ? $editvalue : $value) . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus spellcheck="false">';
322 } elseif (preg_match('/^(integer)/', $typeofdata)) {
323 $tmp = explode(':', $typeofdata);
324 $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
325 $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $valuetoshow . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
326 } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
327 $tmp = explode(':', $typeofdata);
328 $valuetoshow = price2num($editvalue ? $editvalue : $value);
329 $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($valuetoshow != '' ? price($valuetoshow) : '') . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
330 } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
331 $tmp = explode(':', $typeofdata);
332 $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($value ? $value : 'on') . '"' . ($value ? ' checked' : '') . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
333 } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
334 $tmp = explode(':', $typeofdata);
335 $cols = (empty($tmp[2]) ? '' : $tmp[2]);
336 $morealt = '';
337 if (preg_match('/%/', $cols)) {
338 $morealt = ' style="width: ' . $cols . '"';
339 $cols = '';
340 }
341 $valuetoshow = ($editvalue ? $editvalue : $value);
342 $ret .= '<textarea id="' . $htmlname . '" name="' . $htmlname . '" wrap="soft" rows="' . (empty($tmp[1]) ? '20' : $tmp[1]) . '"' . ($cols ? ' cols="' . $cols . '"' : 'class="quatrevingtpercent"') . $morealt . '" autofocus>';
343 // textarea convert automatically entities chars into simple chars.
344 // 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.
345 $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
346 $ret .= dol_htmlwithnojs(dol_string_neverthesehtmltags($valuetoshow, array('textarea')));
347 $ret .= '</textarea><div class="clearboth"></div>';
348 } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
349 $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
350 $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
351 $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
352 $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
353 } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
354 $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
355 $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
356 $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
357 $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
358 } elseif (preg_match('/^select;/', $typeofdata)) {
359 $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
360 $arraylist = array();
361 foreach ($arraydata as $val) {
362 $tmp = explode(':', $val);
363 $tmpkey = str_replace('|', ':', $tmp[0]);
364 $arraylist[$tmpkey] = $tmp[1];
365 }
366 $ret .= $this->selectarray($htmlname, $arraylist, $value);
367 } elseif (preg_match('/^link/', $typeofdata)) {
368 // TODO Not yet implemented. See code for extrafields
369 } elseif (preg_match('/^ckeditor/', $typeofdata)) {
370 $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
371 require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
372 $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]));
373 $ret .= $doleditor->Create(1);
374 } elseif ($typeofdata == 'asis') {
375 $ret .= ($editvalue ? $editvalue : $value);
376 }
377 if (empty($notabletag)) {
378 $ret .= '</td>';
379 }
380
381 // Button save-cancel
382 if (empty($notabletag)) {
383 $ret .= '<td>';
384 }
385 //else $ret.='<div class="clearboth"></div>';
386 $ret .= '<input type="submit" class="smallpaddingimp nomargingtop nomarginbottom button' . (empty($notabletag) ? '' : ' ') . '" name="modify" value="' . $langs->trans("Save") . '">';
387 if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
388 $ret .= '<br>' . "\n";
389 }
390 $ret .= '<input type="submit" class="smallpaddingimp nomargingtop nomarginbottom button button-cancel' . (empty($notabletag) ? '' : ' ') . '" name="cancel" value="' . $langs->trans("Cancel") . '">';
391 if (empty($notabletag)) {
392 $ret .= '</td>';
393 }
394
395 if (empty($notabletag)) {
396 $ret .= '</tr></table>' . "\n";
397 }
398 $ret .= '</form>' . "\n";
399 } else { // view mode
400 if (preg_match('/^email/', $typeofdata)) {
401 $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
402 } elseif (preg_match('/^phone/', $typeofdata)) {
403 $ret .= dol_print_phone($value, '_blank', 32, 1);
404 } elseif (preg_match('/^url/', $typeofdata)) {
405 $ret .= dol_print_url($value, '_blank', 32, 1);
406 } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
407 $ret .= ($value != '' ? price($value, 0, $langs, 0, -1, -1, $conf->currency) : '');
408 } elseif (preg_match('/^checkbox/', $typeofdata)) {
409 $tmp = explode(':', $typeofdata);
410 $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($value ? ' checked' : '') . ($tmp[1] ? $tmp[1] : '') . '/>';
411 } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
413 } elseif (preg_match('/^(safehtmlstring|restricthtml)/', $typeofdata)) { // 'restricthtml' is not an allowed type for editfieldval. Value is 'safehtmlstring'
415 } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
416 $ret .= '<span class="valuedate">' . dol_print_date($value, 'day', $gm) . '</span>';
417 } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
418 $ret .= '<span class="valuedate">' . dol_print_date($value, 'dayhour', $gm) . '</span>';
419 } elseif (preg_match('/^select;/', $typeofdata)) {
420 $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
421 $arraylist = array();
422 foreach ($arraydata as $val) {
423 $tmp = explode(':', $val);
424 $arraylist[$tmp[0]] = $tmp[1];
425 }
426 $ret .= $arraylist[$value];
427 if ($htmlname == 'fk_product_type') {
428 if ($value == 0) {
429 $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
430 } else {
431 $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
432 }
433 }
434 } elseif (preg_match('/^ckeditor/', $typeofdata)) {
435 $tmpcontent = dol_htmlentitiesbr($value);
436 if (getDolGlobalString('MAIN_DISABLE_NOTES_TAB')) {
437 $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
438 $firstline = preg_replace('/[\n\r].*/', '', $firstline);
439 $tmpcontent = $firstline . ((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
440 }
441 // We don't use dol_escape_htmltag to get the html formatting active, but this need we must also
442 // clean data from some dangerous html
444 } else {
445 if (empty($moreoptions['valuealreadyhtmlescaped'])) {
446 $ret .= dol_escape_htmltag($value);
447 } else {
448 $ret .= $value; // $value must be already html escaped.
449 }
450 }
451
452 // Custom format if parameter $formatfunc has been provided
453 if ($formatfunc && method_exists($object, $formatfunc)) {
454 $ret = $object->$formatfunc($ret);
455 }
456 }
457 }
458 return $ret;
459 }
460
472 public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
473 {
474 global $conf, $langs, $extralanguages;
475
476 $result = '';
477
478 // List of extra languages
479 $arrayoflangcode = array();
480 if (getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE')) {
481 $arrayoflangcode[] = getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE');
482 }
483
484 if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
485 if (!is_object($extralanguages)) {
486 include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
487 $extralanguages = new ExtraLanguages($this->db);
488 }
489 $extralanguages->fetch_name_extralanguages('societe');
490
491 // ExtraLanguages::fetch_name_extralanguages() leaves $this->attributes empty
492 // when MAIN_USE_ALTERNATE_TRANSLATION_FOR is not configured, so PHP 8 raises
493 // 'Undefined array key' on the read below if we do not guard it (issue #34596).
494 if (empty($extralanguages->attributes[$object->element]) || !is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
495 return ''; // No extralang field to show
496 }
497
498 $result .= '<!-- Widget for translation -->' . "\n";
499 $result .= '<div class="inline-block paddingleft image-' . $object->element . '-' . $fieldname . '">';
500 $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', 0, 0, 0, '', 'fa-15 editfieldlang');
501 $result .= $s;
502 $result .= '</div>';
503
504 $result .= '<div class="inline-block hidden field-' . $object->element . '-' . $fieldname . '">';
505
506 $resultforextrlang = '';
507 foreach ($arrayoflangcode as $langcode) {
508 $valuetoshow = GETPOSTISSET('field-' . $object->element . "-" . $fieldname . "-" . $langcode) ? GETPOST('field-' . $object->element . '-' . $fieldname . "-" . $langcode, $check) : '';
509 if (empty($valuetoshow)) {
510 $object->fetchValuesForExtraLanguages();
511 //var_dump($object->array_languages);
512 $valuetoshow = $object->array_languages[$fieldname][$langcode];
513 }
514
515 $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
516 $resultforextrlang .= $s;
517
518 // TODO Use the showInputField() method of ExtraLanguages object
519 if ($typeofdata == 'textarea') {
520 $resultforextrlang .= '<textarea name="field-' . $object->element . "-" . $fieldname . "-" . $langcode . '" id="' . $fieldname . "-" . $langcode . '" class="' . $morecss . '" rows="' . ROWS_2 . '" wrap="soft">';
521 $resultforextrlang .= $valuetoshow;
522 $resultforextrlang .= '</textarea>';
523 } else {
524 $resultforextrlang .= '<input type="text" class="inputfieldforlang ' . ($morecss ? ' ' . $morecss : '') . '" name="field-' . $object->element . '-' . $fieldname . '-' . $langcode . '" value="' . $valuetoshow . '">';
525 }
526 }
527 $result .= $resultforextrlang;
528
529 $result .= '</div>';
530 $result .= '<script nonce="' . getNonce() . '">$(".image-' . $object->element . '-' . $fieldname . '").click(function() { console.log("Toggle lang widget"); jQuery(".field-' . $object->element . '-' . $fieldname . '").toggle(); });</script>';
531 }
532
533 return $result;
534 }
535
549 protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
550 {
551 $out = '';
552
553 // Check parameters
554 if (preg_match('/^text/', $inputType)) {
555 $value = dol_nl2br($value);
556 } elseif (preg_match('/^numeric/', $inputType)) {
557 $value = price($value);
558 } elseif ($inputType == 'day' || $inputType == 'datepicker') {
559 $value = dol_print_date($value, 'day');
560 }
561
562 if ($condition) {
563 $element = false;
564 $table_element = false;
565 $fk_element = false;
566 $loadmethod = false;
567 $savemethod = false;
568 $ext_element = false;
569 $button_only = false;
570 $inputOption = '';
571 $rows = '';
572 $cols = '';
573
574 if (is_object($object)) {
575 $element = $object->element;
576 $table_element = $object->table_element;
577 $fk_element = $object->id;
578 }
579
580 if (is_object($extObject)) {
581 $ext_element = $extObject->element;
582 }
583
584 if (preg_match('/^(string|email|numeric)/', $inputType)) {
585 $tmp = explode(':', $inputType);
586 $inputType = $tmp[0];
587 if (!empty($tmp[1])) {
588 $inputOption = $tmp[1];
589 }
590 if (!empty($tmp[2])) {
591 $savemethod = $tmp[2];
592 }
593 $out .= '<input id="width_' . $htmlname . '" value="' . $inputOption . '" type="hidden"/>' . "\n";
594 } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
595 $tmp = explode(':', $inputType);
596 $inputType = $tmp[0];
597 if (!empty($tmp[1])) {
598 $inputOption = $tmp[1];
599 }
600 if (!empty($tmp[2])) {
601 $savemethod = $tmp[2];
602 }
603
604 $out .= '<input id="timestamp" type="hidden"/>' . "\n"; // Use for timestamp format
605 } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
606 $tmp = explode(':', $inputType);
607 $inputType = $tmp[0];
608 $loadmethod = $tmp[1];
609 if (!empty($tmp[2])) {
610 $savemethod = $tmp[2];
611 }
612 if (!empty($tmp[3])) {
613 $button_only = true;
614 }
615 } elseif (preg_match('/^textarea/', $inputType)) {
616 $tmp = explode(':', $inputType);
617 $inputType = $tmp[0];
618 $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
619 $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
620 } elseif (preg_match('/^ckeditor/', $inputType)) {
621 $tmp = explode(':', $inputType);
622 $inputType = $tmp[0];
623 $toolbar = $tmp[1];
624 if (!empty($tmp[2])) {
625 $width = $tmp[2];
626 }
627 if (!empty($tmp[3])) {
628 $height = $tmp[3];
629 }
630 if (!empty($tmp[4])) {
631 $savemethod = $tmp[4];
632 }
633
634 if (isModEnabled('fckeditor')) {
635 $out .= '<input id="ckeditor_toolbar" value="' . $toolbar . '" type="hidden"/>' . "\n";
636 } else {
637 $inputType = 'textarea';
638 }
639 }
640
641 $out .= '<input id="element_' . $htmlname . '" value="' . $element . '" type="hidden"/>' . "\n";
642 $out .= '<input id="table_element_' . $htmlname . '" value="' . $table_element . '" type="hidden"/>' . "\n";
643 $out .= '<input id="fk_element_' . $htmlname . '" value="' . $fk_element . '" type="hidden"/>' . "\n";
644 $out .= '<input id="loadmethod_' . $htmlname . '" value="' . $loadmethod . '" type="hidden"/>' . "\n";
645 if (!empty($savemethod)) {
646 $out .= '<input id="savemethod_' . $htmlname . '" value="' . $savemethod . '" type="hidden"/>' . "\n";
647 }
648 if (!empty($ext_element)) {
649 $out .= '<input id="ext_element_' . $htmlname . '" value="' . $ext_element . '" type="hidden"/>' . "\n";
650 }
651 if (!empty($custommsg)) {
652 if (is_array($custommsg)) {
653 if (!empty($custommsg['success'])) {
654 $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg['success'] . '" type="hidden"/>' . "\n";
655 }
656 if (!empty($custommsg['error'])) {
657 $out .= '<input id="errormsg_' . $htmlname . '" value="' . $custommsg['error'] . '" type="hidden"/>' . "\n";
658 }
659 } else {
660 $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg . '" type="hidden"/>' . "\n";
661 }
662 }
663 if ($inputType == 'textarea') {
664 $out .= '<input id="textarea_' . $htmlname . '_rows" value="' . $rows . '" type="hidden"/>' . "\n";
665 $out .= '<input id="textarea_' . $htmlname . '_cols" value="' . $cols . '" type="hidden"/>' . "\n";
666 }
667 $out .= '<span id="viewval_' . $htmlname . '" class="viewval_' . $inputType . ($button_only ? ' inactive' : ' active') . '">' . $value . '</span>' . "\n";
668 $out .= '<span id="editval_' . $htmlname . '" class="editval_' . $inputType . ($button_only ? ' inactive' : ' active') . ' hideobject">' . (!empty($editvalue) ? $editvalue : $value) . '</span>' . "\n";
669 } else {
670 $out = $value;
671 }
672
673 return $out;
674 }
675
694 public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
695 {
696 if ($incbefore) {
697 $text = $incbefore . $text;
698 }
699 if (!$htmltext) {
700 return $text;
701 }
702 $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
703
704 $tag = 'td';
705 if ($notabs == 2) {
706 $tag = 'div';
707 }
708 if ($notabs == 3) {
709 $tag = 'span';
710 }
711 // Sanitize tooltip
712 $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
713
714 $extrastyle = '';
715 if ($direction < 0) {
716 $extracss = ($extracss ? $extracss : '') . ($notabs != 3 ? ' inline-block' : '');
717 $extrastyle = 'padding: 0px; padding-left: 2px;';
718 }
719 if ($direction > 0) {
720 $extracss = ($extracss ? $extracss : '') . ($notabs != 3 ? ' inline-block' : '');
721 $extrastyle = 'padding: 0px; padding-right: 2px;';
722 }
723
724 $classfortooltip = 'classfortooltip';
725
726 $s = '';
727 $textfordialog = '';
728
729 if ($tooltiptrigger == '') {
730 $htmltext = str_replace('"', '&quot;', $htmltext);
731 } else {
732 $classfortooltip = 'classfortooltiponclick';
733 $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_' . $tooltiptrigger . '" class="classfortooltiponclicktext"';
734 // Set default title of dialog
735 global $langs;
736 if ($langs instanceof Translate) {
737 $textfordialog .= ' title="'.$langs->trans("Note").'"';
738 }
739 $textfordialog .= '>' . $htmltext . '</div>';
740 }
741 if ($tooltipon == 2 || $tooltipon == 3) {
742 $paramfortooltipimg = ' class="' . $classfortooltip . ($notabs != 3 ? ' inline-block' : '') . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '"';
743 if ($tooltiptrigger == '') {
744 $paramfortooltipimg .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1, 0, 'span', 0, 1)) . '"'; // Attribute to put on img tag to store tooltip
745 } else {
746 $paramfortooltipimg .= ' dolid="' . $tooltiptrigger . '"';
747 }
748 } else {
749 $paramfortooltipimg = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribute to put on td text tag
750 }
751 if ($tooltipon == 1 || $tooltipon == 3) {
752 $paramfortooltiptd = ' class="' . ($tooltipon == 3 ? 'cursorpointer ' : '') . $classfortooltip . ($tag != 'td' ? ' inline-block' : '') . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '" ';
753 if ($tooltiptrigger == '') {
754 $paramfortooltiptd .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1, 0, 'span', 0, 1)) . '"'; // Attribute to put on td tag to store tooltip
755 } else {
756 $paramfortooltiptd .= ' dolid="' . $tooltiptrigger . '"';
757 }
758 } else {
759 $paramfortooltiptd = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribute to put on td text tag
760 }
761 if (empty($notabs)) {
762 $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
763 } elseif ($notabs == 2) {
764 $s .= '<div class="inline-block' . ($forcenowrap ? ' nowrap' : '') . '">';
765 }
766 // Define value if value is before
767 if ($direction < 0) {
768 $s .= '<' . $tag . $paramfortooltipimg;
769 if ($tag == 'td') {
770 $s .= ' class="valigntop" width="14"';
771 }
772 $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
773 }
774 // Use another method to help avoid having a space in value in order to use this value with jquery
775 // Define label
776 if ((string) $text != '') {
777 $s .= '<' . $tag . $paramfortooltiptd . '>' . $text . '</' . $tag . '>';
778 }
779 // Define value if value is after
780 if ($direction > 0) {
781 $s .= '<' . $tag . $paramfortooltipimg;
782 if ($tag == 'td') {
783 $s .= ' class="valignmiddle" width="14"';
784 }
785 $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
786 }
787 if (empty($notabs)) {
788 $s .= '</tr></table>';
789 } elseif ($notabs == 2) {
790 $s .= '</div>';
791 }
792
793 return $s;
794 }
795
810 public function textwithpicto($text, $htmltooltip, $direction = 1, $type = 'help', $extracss = 'valignmiddle', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
811 {
812 global $conf, $langs;
813
814 //For backwards compatibility
815 if ($type == '0') {
816 $type = 'info';
817 } elseif ($type == '1') {
818 $type = 'help';
819 }
820 // Clean parameters
821 $tooltiptrigger = preg_replace('/[^a-z0-9]/i', '', $tooltiptrigger);
822
823 if (preg_match('/onsmartphone$/', $tooltiptrigger) && empty($conf->dol_no_mouse_hover)) {
824 $tooltiptrigger = preg_replace('/^.*onsmartphone$/', '', $tooltiptrigger);
825 }
826 $alt = '';
827 if ($tooltiptrigger) {
828 $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
829 }
830
831 // If info or help with no javascript, show only text
832 if (empty($conf->use_javascript_ajax)) {
833 if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
834 return $text;
835 } else {
836 $alt = $htmltooltip;
837 $htmltooltip = '';
838 }
839 }
840
841 // If info or help with smartphone, show only text (tooltip hover can't works)
842 if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
843 if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
844 return $text;
845 }
846 }
847 // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
848 //if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
849 //{
850 //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.'</a>';
851 //}
852
853 $img = '';
854 if ($type == 'info') {
855 $img = img_help(($tooltiptrigger != '' ? 2 : 0), $alt);
856 } elseif ($type == 'help') {
857 $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
858 } elseif ($type == 'helpclickable') {
859 $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
860 } elseif ($type == 'warning') {
861 $img = img_warning($alt);
862 } elseif ($type != 'none') {
863 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
864 $img = img_picto($alt, $type); // $type can be an image path
865 }
866
867 $tooltipon = ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2);
868
869 return $this->textwithtooltip($text, $htmltooltip, $tooltipon, $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
870 }
871
882 public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
883 {
884 global $conf, $langs, $hookmanager;
885
886 $disabled = 0;
887 $ret = '<div class="centpercent center">';
888 $ret .= '<select class="flat' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'select valignmiddle alignstart" id="' . $name . '" name="' . $name . '"' . ($disabled ? ' disabled="disabled"' : '') . '>';
889
890 // 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.
891 $parameters = array();
892 $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
893 // check if there is a mass action
894
895 if (is_array($arrayofaction) && count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
896 return;
897 }
898 if (empty($reshook)) {
899 $ret .= '<option value="0"' . ($disabled ? ' disabled="disabled"' : '') . '>-- ' . $langs->trans("SelectAction") . ' --</option>';
900 if (is_array($arrayofaction)) {
901 foreach ($arrayofaction as $code => $label) {
902 $ret .= '<option value="' . $code . '"' . ($disabled ? ' disabled="disabled"' : '') . ' data-html="' . dol_escape_htmltag($label) . '">' . $label . '</option>';
903 }
904 }
905 }
906 $ret .= $hookmanager->resPrint;
907
908 $ret .= '</select>';
909
910 if (empty($conf->dol_optimize_smallscreen)) {
911 $ret .= ajax_combobox('.' . $name . 'select');
912 }
913
914 // 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
915 $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.
916 $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")) . '">';
917 $ret .= '</div>';
918
919 if (!empty($conf->use_javascript_ajax)) {
920 $ret .= '<!-- JS CODE TO ENABLE mass action select -->
921 <script nonce="' . getNonce() . '">
922 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 */
923 atleastoneselected=0;
924 jQuery("."+cssclass).each(function( index ) {
925 /* console.log( index + ": " + $( this ).text() ); */
926 if ($(this).is(\':checked\')) atleastoneselected++;
927 });
928
929 console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
930
931 if (atleastoneselected || ' . ((int) $alwaysvisible) . ') {
932 jQuery("."+name).show();
933 ' . ($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("' . $selected . '").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '') . '
934 ' . ($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '') . '
935 } else {
936 jQuery("."+name).hide();
937 jQuery("."+name+"other").hide();
938 }
939 }
940
941 jQuery(document).ready(function () {
942 initCheckForSelect(0, "' . $name . '", "' . $cssclass . '");
943 jQuery(".' . $cssclass . '").change(function() {
944 console.log("A change was done on .' . $cssclass . '");
945 initCheckForSelect(1, "' . $name . '", "' . $cssclass . '");
946 });
947 jQuery(".' . $name . 'select").change(function() {
948 var massaction = $( this ).val();
949 var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
950 if (massaction == "builddoc") {
951 urlform = urlform + "#show_files";
952 }
953 $( this ).closest("form").attr("action", urlform);
954 console.log("we select a mass action name=' . $name . ' massaction="+massaction+" - "+urlform);
955 /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
956 if ($(this).val() != \'0\') {
957 jQuery(".' . $name . 'confirmed").prop(\'disabled\', false);
958 jQuery(".' . $name . 'other").hide(); /* To disable if another div was open */
959 jQuery(".' . $name . '"+massaction).show();
960 } else {
961 jQuery(".' . $name . 'confirmed").prop(\'disabled\', true);
962 jQuery(".' . $name . 'other").hide(); /* To disable any div open */
963 }
964 });
965 });
966 </script>
967 ';
968 }
969
970 return $ret;
971 }
972
973 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
974
992 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)
993 {
994 // phpcs:enable
995 global $langs, $mysoc;
996
997 $langs->load("dict");
998
999 $selected = (string) $selected;
1000
1001 $out = '';
1003 $countryArray = array();
1004 $favorite = array();
1005 $label = array();
1006 $atleastonefavorite = 0;
1007
1008 $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
1009 $sql .= " FROM " . $this->db->prefix() . "c_country";
1010 $sql .= " WHERE active > 0";
1011 //$sql.= " ORDER BY code ASC";
1012
1013 dol_syslog(get_class($this) . "::select_country", LOG_DEBUG);
1014
1015 $resql = $this->db->query($sql);
1016 if ($resql) {
1017 $out .= '<select id="select' . $htmlname . '" class="flat maxwidth200onsmartphone selectcountry' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" ' . $htmloption . '>';
1018 $num = $this->db->num_rows($resql);
1019 $i = 0;
1020 if ($num) {
1021 while ($i < $num) {
1022 $obj = $this->db->fetch_object($resql);
1023
1024 $countryArray[$i]
1025 = array(
1026 'rowid' => (int) $obj->rowid,
1027 'code_iso' => (string) $obj->code_iso,
1028 'code_iso3' => (string) $obj->code_iso3,
1029 '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 : '')),
1030 'favorite' => (string) $obj->favorite,
1031 'eec' => (string) $obj->eec,
1032 );
1033 $favorite[$i] = $obj->favorite;
1034 $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
1035 $i++;
1036 }
1037
1038 if (empty($disablefavorites)) {
1039 $array1_sort_order = SORT_DESC;
1040 $array2_sort_order = SORT_ASC;
1041 array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
1042 } else {
1043 $countryArray = dol_sort_array($countryArray, 'label');
1044 }
1045
1046 if ($showempty) {
1047 if (is_numeric($showempty)) {
1048 $out .= '<option value="">&nbsp;</option>' . "\n";
1049 } else {
1050 $out .= '<option value="-1">' . $langs->trans($showempty) . '</option>' . "\n";
1051 }
1052 }
1053
1054 if ($addspecialentries) { // Add dedicated entries for groups of countries
1055 //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
1056 $out .= '<option value="special_allnotme"' . ($selected == 'special_allnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
1057 $out .= '<option value="special_eec"' . ($selected == 'special_eec' ? ' selected' : '') . '>' . $langs->trans("CountriesInEEC") . '</option>';
1058 if ($mysoc->isInEEC()) {
1059 $out .= '<option value="special_eecnotme"' . ($selected == 'special_eecnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
1060 }
1061 $out .= '<option value="special_noteec"' . ($selected == 'special_noteec' ? ' selected' : '') . '>' . $langs->trans("CountriesNotInEEC") . '</option>';
1062 $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
1063 }
1064
1065 foreach ($countryArray as $row) {
1066 //if (empty($showempty) && empty($row['rowid'])) continue;
1067 if (empty($row['rowid'])) {
1068 continue;
1069 }
1070 if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
1071 continue; // exclude some countries
1072 }
1073
1074 if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
1075 $atleastonefavorite++;
1076 }
1077 if (empty($row['favorite']) && $atleastonefavorite) {
1078 $atleastonefavorite = 0;
1079 $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
1080 }
1081
1082 $labeltoshow = '';
1083 if ($row['label']) {
1084 $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
1085 } else {
1086 $labeltoshow .= '&nbsp;';
1087 }
1088 if ($row['code_iso']) {
1089 $labeltoshow .= ' <span class="opacitymedium">(' . $row['code_iso'] . ')</span>';
1090 if (empty($hideflags)) {
1091 $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
1092 $labeltoshow = $tmpflag . ' ' . $labeltoshow;
1093 }
1094 }
1095
1096 if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
1097 $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']) . '">';
1098 } else {
1099 $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']) . '">';
1100 }
1101 $out .= dol_string_nohtmltag($labeltoshow);
1102 $out .= '</option>' . "\n";
1103 }
1104 }
1105 $out .= '</select>';
1106 } else {
1107 dol_print_error($this->db);
1108 }
1109
1110 // Make select dynamic
1111 if (empty($forcecombo)) {
1112 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1113 $out .= ajax_combobox('select' . $htmlname, array(), 0, 0, 'resolve');
1114 }
1115
1116 return $out;
1117 }
1118
1119 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1120
1134 public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
1135 {
1136 // phpcs:enable
1137 global $conf, $langs;
1138
1139 $langs->load("dict");
1140
1141 $out = '';
1142 //$moreattrib = '';
1143 $incotermArray = array();
1144
1145 $sql = "SELECT rowid, code";
1146 $sql .= " FROM " . $this->db->prefix() . "c_incoterms";
1147 $sql .= " WHERE active > 0";
1148 $sql .= " ORDER BY code ASC";
1149
1150 dol_syslog(get_class($this) . "::select_incoterm", LOG_DEBUG);
1151 $resql = $this->db->query($sql);
1152 if ($resql) {
1153 if ($conf->use_javascript_ajax && !$forcecombo) {
1154 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1155 $out .= ajax_combobox($htmlname, $events);
1156 }
1157
1158 if (!empty($page)) {
1159 $out .= '<form method="post" action="' . $page . '">';
1160 $out .= '<input type="hidden" name="action" value="set_incoterms">';
1161 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
1162 }
1163
1164 $out .= '<select id="' . $htmlname . '" class="flat selectincoterm width75" name="' . $htmlname . '" ' . $htmloption . '>';
1165 $out .= '<option value="0">&nbsp;</option>';
1166 $num = $this->db->num_rows($resql);
1167 $i = 0;
1168 if ($num) {
1169 while ($i < $num) {
1170 $obj = $this->db->fetch_object($resql);
1171 $incotermArray[$i]['rowid'] = $obj->rowid;
1172 $incotermArray[$i]['code'] = $obj->code;
1173 $i++;
1174 }
1175
1176 foreach ($incotermArray as $row) {
1177 if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
1178 $out .= '<option value="' . $row['rowid'] . '" selected>';
1179 } else {
1180 $out .= '<option value="' . $row['rowid'] . '">';
1181 }
1182
1183 if ($row['code']) {
1184 $out .= $row['code'];
1185 }
1186
1187 $out .= '</option>';
1188 }
1189 }
1190 $out .= '</select>';
1191 $out .= ajax_combobox($htmlname);
1192
1193 if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
1194 $out .= ajax_multiautocompleter('location_incoterms', array(), DOL_URL_ROOT . '/core/ajax/locationincoterms.php') . "\n";
1195 //$moreattrib .= ' autocomplete="off"';
1196 }
1197 $out .= '<input id="location_incoterms" class="maxwidthonsmartphone heightofcombo" type="text" name="location_incoterms" value="' . $location_incoterms . '">' . "\n";
1198
1199 if (!empty($page)) {
1200 $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="' . $langs->trans("Modify") . '"></form>';
1201 }
1202 } else {
1203 dol_print_error($this->db);
1204 }
1205
1206 return $out;
1207 }
1208
1209 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1210
1224 public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0, $morecss = "", $useajaxcombo = 1)
1225 {
1226 // phpcs:enable
1227 global $langs;
1228
1229 // If product & services are enabled or both disabled.
1230 if ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
1231 || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
1232 if (empty($hidetext)) {
1233 print $langs->trans("Type").'...';
1234 }
1235
1236 print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_' . $htmlname . '" name="' . $htmlname . '">';
1237 if ($showempty) {
1238 print '<option value="-1" class="opacitymedium"'.($useajaxcombo ? '' : ' disabled="disabled"');
1239 if ($selected == -1) {
1240 print ' selected';
1241 }
1242 print '>';
1243 if (is_numeric($showempty)) {
1244 print '&nbsp;';
1245 } else {
1246 print $showempty;
1247 }
1248 print '</option>';
1249 }
1250
1251 print '<option value="0"';
1252 if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
1253 print ' selected';
1254 }
1255 print '>' . $langs->trans("Product");
1256 print '</option>';
1257
1258 print '<option value="1"';
1259 if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
1260 print ' selected';
1261 }
1262 print '>' . $langs->trans("Service");
1263 print '</option>';
1264
1265 print '</select>';
1266
1267 if ($useajaxcombo) {
1268 print ajax_combobox('select_' . $htmlname);
1269 }
1270 //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1271 }
1272 if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
1273 print $langs->trans("Service");
1274 print '<input type="hidden" name="' . $htmlname . '" value="1">';
1275 }
1276 if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
1277 print $langs->trans("Product");
1278 print '<input type="hidden" name="' . $htmlname . '" value="0">';
1279 }
1280 if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
1281 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
1282 }
1283 }
1284
1285 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1286
1292 public function load_cache_types_fees()
1293 {
1294 // phpcs:enable
1295 global $langs;
1296
1297 $num = count($this->cache_types_fees);
1298 if ($num > 0) {
1299 return 0; // Cache already loaded
1300 }
1301
1302 dol_syslog(__METHOD__, LOG_DEBUG);
1303
1304 $langs->load("trips");
1305
1306 $sql = "SELECT c.code, c.label";
1307 $sql .= " FROM " . $this->db->prefix() . "c_type_fees as c";
1308 $sql .= " WHERE active > 0";
1309
1310 $resql = $this->db->query($sql);
1311 if ($resql) {
1312 $num = $this->db->num_rows($resql);
1313 $i = 0;
1314
1315 while ($i < $num) {
1316 $obj = $this->db->fetch_object($resql);
1317
1318 // Si traduction existe, on l'utilise, sinon on prend le libelle par default
1319 $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
1320 $this->cache_types_fees[$obj->code] = $label;
1321 $i++;
1322 }
1323
1324 asort($this->cache_types_fees);
1325
1326 return $num;
1327 } else {
1328 dol_print_error($this->db);
1329 return -1;
1330 }
1331 }
1332
1333 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1334
1343 public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
1344 {
1345 // phpcs:enable
1346 global $user, $langs;
1347
1348 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
1349
1350 $this->load_cache_types_fees();
1351
1352 print '<select id="select_' . $htmlname . '" class="flat" name="' . $htmlname . '">';
1353 if ($showempty) {
1354 print '<option value="-1"';
1355 if ($selected == -1) {
1356 print ' selected';
1357 }
1358 print '>&nbsp;</option>';
1359 }
1360
1361 foreach ($this->cache_types_fees as $key => $value) {
1362 print '<option value="' . $key . '"';
1363 if ($key == $selected) {
1364 print ' selected';
1365 }
1366 print '>';
1367 print $value;
1368 print '</option>';
1369 }
1370
1371 print '</select>';
1372 if ($user->admin) {
1373 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
1374 }
1375 }
1376
1377
1378 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1379
1402 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)
1403 {
1404 // phpcs:enable
1405 global $conf, $langs;
1406
1407 $out = '';
1408
1409 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT') && !$forcecombo) {
1410 if (is_null($ajaxoptions)) {
1411 $ajaxoptions = array();
1412 }
1413
1414 require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1415
1416 // No immediate load of all database
1417 $placeholder = '';
1418 if ($selected && empty($selected_input_value)) {
1419 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1420 $societetmp = new Societe($this->db);
1421 $societetmp->fetch($selected);
1422 $selected_input_value = $societetmp->name;
1423 unset($societetmp);
1424 }
1425
1426 // mode 1
1427 $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)) : '');
1428
1429 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
1430 if (empty($hidelabel)) {
1431 $out .= $langs->trans("RefOrLabel") . ' : ';
1432 } elseif ($hidelabel == 1 && !is_numeric($showempty)) {
1433 $placeholder = $langs->trans($showempty);
1434 } elseif ($hidelabel > 1) {
1435 $placeholder = $langs->trans("RefOrLabel");
1436 if ($hidelabel == 2) {
1437 $out .= img_picto($langs->trans("Search"), 'search');
1438 }
1439 }
1440 $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' : '') . ' />';
1441 if ($hidelabel == 3) {
1442 $out .= img_picto($langs->trans("Search"), 'search');
1443 }
1444
1445 $out .= ajax_event($htmlname, $events);
1446
1447 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, getDolGlobalInt('COMPANY_USE_SEARCH_TO_SELECT'), 0, $ajaxoptions);
1448 } else {
1449 // Immediate load of all database
1450 $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
1451 }
1452
1453 return $out;
1454 }
1455
1456
1457 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1458
1484 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 = '')
1485 {
1486 // phpcs:enable
1487
1488 global $conf, $langs;
1489
1490 $out = '';
1491
1492 $sav = getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT');
1493 if ($nokeyifsocid && $socid > 0) {
1494 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = 0;
1495 }
1496
1497 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT') && !$forcecombo) {
1498 if (is_null($events)) {
1499 $events = array();
1500 }
1501
1502 require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1503
1504 // No immediate load of all database
1505 $placeholder = '';
1506 if ($selected && empty($selected_input_value)) {
1507 require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
1508 $contacttmp = new Contact($this->db);
1509 $contacttmp->fetch($selected);
1510 $selected_input_value = $contacttmp->getFullName($langs);
1511 unset($contacttmp);
1512 }
1513 if (!is_numeric($showempty)) {
1514 $placeholder = $showempty;
1515 }
1516
1517 // mode 1
1518 $urloption = 'htmlname=' . urlencode((string) (str_replace('.', '_', $htmlname))) . '&outjson=1&filter=' . urlencode((string) ($filter)) . (empty($exclude) ? '' : '&exclude=' . urlencode($exclude)) . ($showsoc ? '&showsoc=' . urlencode((string) ($showsoc)) : '');
1519
1520 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
1521
1522 $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' : '') . ' />';
1523
1524 $out .= ajax_event($htmlname, $events);
1525
1526 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/contact/ajax/contact.php', $urloption, getDolGlobalInt('CONTACT_USE_SEARCH_TO_SELECT'), 0, $events);
1527 } else {
1528 // Immediate load of all database
1529 $multiple = false;
1530 $disableifempty = 0;
1531 $options_only = 0;
1532 $limitto = '';
1533
1534 $out .= $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid, $multiple, $disableifempty);
1535 }
1536
1537 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = $sav;
1538
1539 return $out;
1540 }
1541
1542
1543 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1544
1570 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)
1571 {
1572 // phpcs:enable
1573 global $user, $langs;
1574 global $hookmanager;
1575
1576 $langs->loadLangs(array("companies", "suppliers"));
1577
1578 $out = '';
1579 $num = 0;
1580 $outarray = array();
1581
1582 if ($selected === '') {
1583 $selected = array();
1584 } elseif (!is_array($selected)) {
1585 $selected = array($selected);
1586 }
1587
1588 // Clean $filter that may contains sql conditions so sql code
1589 if (function_exists('testSqlAndScriptInject')) {
1590 if (testSqlAndScriptInject($filter, 3) > 0) {
1591 $filter = '';
1592 return 'SQLInjectionTryDetected';
1593 }
1594 }
1595
1596 if ($filter != '') { // If a filter was provided
1597 if (preg_match('/[\‍(\‍)]/', $filter)) {
1598 // If there is one parenthesis inside the criteria, we assume it is an Universal Filter Syntax.
1599 $errormsg = '';
1600 $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
1601
1602 // Redo clean $filter that may contains sql conditions so sql code
1603 if (function_exists('testSqlAndScriptInject')) {
1604 if (testSqlAndScriptInject($filter, 3) > 0) {
1605 $filter = '';
1606 return 'SQLInjectionTryDetected';
1607 }
1608 }
1609 } else {
1610 // If not, we do nothing. We already know that there is no parenthesis
1611 // TODO Disallow this case in a future.
1612 dol_syslog("Warning, select_thirdparty_list was called with a filter criteria not using the Universal Search Syntax.", LOG_WARNING);
1613 }
1614 }
1615
1616 // We search companies
1617 $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
1618 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
1619 $sql .= ", s.address, s.zip, s.town";
1620 $sql .= ", dictp.code as country_code";
1621 }
1622 $sql .= " FROM " . $this->db->prefix() . "societe as s";
1623 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
1624 $sql .= " LEFT JOIN " . $this->db->prefix() . "c_country as dictp ON dictp.rowid = s.fk_pays";
1625 }
1626 if (!$user->hasRight('societe', 'client', 'voir')) {
1627 $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
1628 }
1629 $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")";
1630 if (!empty($user->socid)) {
1631 $sql .= " AND s.rowid = " . ((int) $user->socid);
1632 }
1633 if ($filter) {
1634 // $filter is safe because, if it contains '(' or ')', it has been sanitized by testSqlAndScriptInject() and forgeSQLFromUniversalSearchCriteria()
1635 // if not, by testSqlAndScriptInject() only.
1636 $sql .= " AND (" . $filter . ")";
1637 }
1638 if (!$user->hasRight('societe', 'client', 'voir')) {
1639 $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
1640 }
1641 if (getDolGlobalString('COMPANY_HIDE_INACTIVE_IN_COMBOBOX')) {
1642 $sql .= " AND s.status <> 0";
1643 }
1644 if (!empty($excludeids)) {
1645 $sql .= " AND s.rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeids)) . ")";
1646 }
1647 // Add where from hooks
1648 $parameters = array();
1649 $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
1650 $sql .= $hookmanager->resPrint;
1651 // Add criteria
1652 if ($filterkey && $filterkey != '') {
1653 $sql .= " AND (";
1654 $prefix = !getDolGlobalString('COMPANY_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
1655 // For natural search
1656 $search_crit = explode(' ', $filterkey);
1657 $i = 0;
1658 if (count($search_crit) > 1) {
1659 $sql .= "(";
1660 }
1661 foreach ($search_crit as $crit) {
1662 if ($i > 0) {
1663 $sql .= " AND ";
1664 }
1665 $sql .= "(s.nom LIKE '" . $this->db->escape($prefix . $crit) . "%')";
1666 $i++;
1667 }
1668 if (count($search_crit) > 1) {
1669 $sql .= ")";
1670 }
1671 if (isModEnabled('barcode')) {
1672 $sql .= " OR s.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
1673 }
1674 $sql .= " OR s.code_client LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.code_fournisseur LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
1675 $sql .= " OR s.name_alias LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.tva_intra LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
1676 $sql .= ")";
1677 }
1678 $sql .= $this->db->order("nom", "ASC");
1679 $sql .= $this->db->plimit($limit, 0);
1680
1681 // Build output string
1682 dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
1683 $resql = $this->db->query($sql);
1684 if ($resql) {
1685 // Construct $out and $outarray
1686 $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($moreparam ? ' ' . $moreparam : '') . ' name="' . $htmlname . ($multiple ? '[]' : '') . '"' . ($multiple ? ' multiple' : '') . '>' . "\n";
1687
1688 $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
1689 if (getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT')) {
1690 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
1691 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
1692 if ($showempty && !is_numeric($showempty)) {
1693 $textifempty = $langs->trans($showempty);
1694 } else {
1695 $textifempty .= $langs->trans("All");
1696 }
1697 }
1698 if ($showempty) {
1699 $out .= '<option value="-1" data-html="' . dol_escape_htmltag('<span class="opacitymedium">' . ($textifempty ? $textifempty : '&nbsp;') . '</span>') . '">' . $textifempty . '</option>' . "\n";
1700 }
1701
1702 $companytemp = new Societe($this->db);
1703
1704 $num = $this->db->num_rows($resql);
1705 $i = 0;
1706 if ($num) {
1707 while ($i < $num) {
1708 $obj = $this->db->fetch_object($resql);
1709 $label = '';
1710 if ($showcode || getDolGlobalString('SOCIETE_ADD_REF_IN_LIST')) {
1711 if (($obj->client) && (!empty($obj->code_client))) {
1712 $label = $obj->code_client . ' - ';
1713 }
1714 if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
1715 $label .= $obj->code_fournisseur . ' - ';
1716 }
1717 $label .= ' ' . $obj->name;
1718 } else {
1719 $label = $obj->name;
1720 }
1721
1722 if (!empty($obj->name_alias)) {
1723 $label .= ' (' . $obj->name_alias . ')';
1724 }
1725
1726 if (getDolGlobalString('SOCIETE_SHOW_VAT_IN_LIST') && !empty($obj->tva_intra)) {
1727 $label .= ' - '.$obj->tva_intra;
1728 }
1729
1730 $labelhtml = $label;
1731
1732 if ($showtype) {
1733 $companytemp->id = $obj->rowid;
1734 $companytemp->client = $obj->client;
1735 $companytemp->fournisseur = $obj->fournisseur;
1736 $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
1737 if ($tmptype) {
1738 $labelhtml .= ' ' . $tmptype;
1739 }
1740
1741 if ($obj->client || $obj->fournisseur) {
1742 $label .= ' (';
1743 }
1744 if ($obj->client == 1 || $obj->client == 3) {
1745 $label .= $langs->trans("Customer");
1746 }
1747 if ($obj->client == 2 || $obj->client == 3) {
1748 $label .= ($obj->client == 3 ? ', ' : '') . $langs->trans("Prospect");
1749 }
1750 if ($obj->fournisseur) {
1751 $label .= ($obj->client ? ', ' : '') . $langs->trans("Supplier");
1752 }
1753 if ($obj->client || $obj->fournisseur) {
1754 $label .= ')';
1755 }
1756 }
1757
1758 if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
1759 $s = ($obj->address ? ' - ' . $obj->address : '') . ($obj->zip ? ' - ' . $obj->zip : '') . ($obj->town ? ' ' . $obj->town : '');
1760 if (!empty($obj->country_code)) {
1761 $s .= ', ' . $langs->trans('Country' . $obj->country_code);
1762 }
1763 $label .= $s;
1764 $labelhtml .= $s;
1765 }
1766
1767 if (empty($outputmode)) {
1768 if (in_array($obj->rowid, $selected)) {
1769 $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>';
1770 } else {
1771 $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
1772 }
1773 } else {
1774 array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label, 'labelhtml' => $labelhtml));
1775 }
1776
1777 $i++;
1778 if (($i % 10) == 0) {
1779 $out .= "\n";
1780 }
1781 }
1782 }
1783 $out .= '</select>' . "\n";
1784 if (!$forcecombo) {
1785 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1786 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("COMPANY_USE_SEARCH_TO_SELECT"));
1787 }
1788 } else {
1789 dol_print_error($this->db);
1790 }
1791
1792 $this->result = array('nbofthirdparties' => $num);
1793
1794 if ($outputmode) {
1795 return $outarray;
1796 }
1797 return $out;
1798 }
1799
1800
1826 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 = '')
1827 {
1828 global $conf, $user, $langs, $hookmanager, $action;
1829
1830 $langs->load('companies');
1831
1832 if (empty($htmlid)) {
1833 $htmlid = $htmlname;
1834 }
1835 $num = 0;
1836 $out = '';
1837 $outarray = array();
1838
1839 if ($selected === '') {
1840 $selected = array();
1841 } elseif (!is_array($selected)) {
1842 $selected = array((int) $selected);
1843 }
1844
1845 // Clean $filter that may contains sql conditions so sql code
1846 if (function_exists('testSqlAndScriptInject')) {
1847 if (testSqlAndScriptInject($filter, 3) > 0) {
1848 $filter = '';
1849 return 'SQLInjectionTryDetected';
1850 }
1851 }
1852
1853 if ($filter != '') { // If a filter was provided
1854 if (preg_match('/[\‍(\‍)]/', $filter)) {
1855 // If there is one parenthesis inside the criteria, we assume it is an Universal Filter Syntax.
1856 $errormsg = '';
1857 $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
1858
1859 // Redo clean $filter that may contains sql conditions so sql code
1860 if (function_exists('testSqlAndScriptInject')) {
1861 if (testSqlAndScriptInject($filter, 3) > 0) {
1862 $filter = '';
1863 return 'SQLInjectionTryDetected';
1864 }
1865 }
1866 } else {
1867 // If not, we do nothing. We already know that there is no parenthesis
1868 // TODO Disallow this case in a future by returning an error here.
1869 dol_syslog("Warning, select_thirdparty_list was called with a filter criteria not using the Universal Search Filter Syntax.", LOG_WARNING);
1870 }
1871 }
1872
1873 if (!is_object($hookmanager)) {
1874 include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
1875 $hookmanager = new HookManager($this->db);
1876 }
1877
1878 // We search third parties
1879 $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";
1880 if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
1881 $sql .= ", s.nom as company, s.town AS company_town";
1882 }
1883 $sql .= " FROM " . $this->db->prefix() . "socpeople as sp";
1884 if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
1885 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON s.rowid = sp.fk_soc";
1886 }
1887 $sql .= " WHERE sp.entity IN (" . getEntity('contact') . ")";
1888 $sql .= " AND ((sp.fk_user_creat = ".((int) $user->id)." AND sp.priv = 1) OR sp.priv = 0)"; // check if this is a private contact
1889 if ($socid > 0 || $socid == -1) {
1890 $sql .= " AND sp.fk_soc = " . ((int) $socid);
1891 }
1892 if (getDolGlobalString('CONTACT_HIDE_INACTIVE_IN_COMBOBOX')) {
1893 $sql .= " AND sp.statut <> 0";
1894 }
1895 // filter user access
1896 if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
1897 $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 .")";
1898 }
1899 if ($user->socid > 0) {
1900 $sql .= " AND sp.fk_soc = ".((int) $user->socid);
1901 }
1902 if ($filter) {
1903 // $filter is safe because, if it contains '(' or ')', it has been sanitized by testSqlAndScriptInject() and forgeSQLFromUniversalSearchCriteria()
1904 // if not, by testSqlAndScriptInject() only.
1905 $sql .= " AND (" . $filter . ")";
1906 }
1907 // Add where from hooks
1908 $parameters = array();
1909 $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
1910 $sql .= $hookmanager->resPrint;
1911 $sql .= " ORDER BY sp.lastname ASC";
1912
1913 dol_syslog(get_class($this) . "::selectcontacts", LOG_DEBUG);
1914 $resql = $this->db->query($sql);
1915 if ($resql) {
1916 $num = $this->db->num_rows($resql);
1917
1918 if ($htmlname != 'none' && !$options_only) {
1919 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlid . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . (($num || empty($disableifempty)) ? '' : ' disabled') . ($multiple ? 'multiple' : '') . ' ' . (!empty($moreparam) ? $moreparam : '') . '>';
1920 }
1921
1922 if ($showempty && !is_numeric($showempty)) {
1923 $textforempty = $showempty;
1924 $out .= '<option class="optiongrey" value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>' . $textforempty . '</option>';
1925 } else {
1926 if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
1927 $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>&nbsp;</option>';
1928 }
1929 if ($showempty == 2) {
1930 $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>-- ' . $langs->trans("Internal") . ' --</option>';
1931 }
1932 }
1933
1934 $i = 0;
1935 if ($num) {
1936 include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
1937 $contactstatic = new Contact($this->db);
1938
1939 while ($i < $num) {
1940 $obj = $this->db->fetch_object($resql);
1941
1942 // Set email (or phones) and town extended infos
1943 $extendedInfos = '';
1944 if (getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
1945 $extendedInfos = array();
1946 $email = trim($obj->email);
1947 if (!empty($email)) {
1948 $extendedInfos[] = $email;
1949 } else {
1950 $phone = trim($obj->phone);
1951 $phone_perso = trim($obj->phone_perso);
1952 $phone_mobile = trim($obj->phone_mobile);
1953 if (!empty($phone)) {
1954 $extendedInfos[] = $phone;
1955 }
1956 if (!empty($phone_perso)) {
1957 $extendedInfos[] = $phone_perso;
1958 }
1959 if (!empty($phone_mobile)) {
1960 $extendedInfos[] = $phone_mobile;
1961 }
1962 }
1963 $contact_town = trim($obj->contact_town);
1964 $company_town = trim($obj->company_town);
1965 if (!empty($contact_town)) {
1966 $extendedInfos[] = $contact_town;
1967 } elseif (!empty($company_town)) {
1968 $extendedInfos[] = $company_town;
1969 }
1970 $extendedInfos = implode(' - ', $extendedInfos);
1971 if (!empty($extendedInfos)) {
1972 $extendedInfos = ' - ' . $extendedInfos;
1973 }
1974 }
1975
1976 $contactstatic->id = $obj->rowid;
1977 $contactstatic->lastname = $obj->lastname;
1978 $contactstatic->firstname = $obj->firstname;
1979 if ($obj->statut == 1) {
1980 $tmplabel = '';
1981 if ($htmlname != 'none') {
1982 $disabled = 0;
1983 if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
1984 $disabled = 1;
1985 }
1986 if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
1987 $disabled = 1;
1988 }
1989 if (!empty($selected) && in_array($obj->rowid, $selected)) {
1990 $out .= '<option value="' . $obj->rowid . '"';
1991 if ($disabled) {
1992 $out .= ' disabled';
1993 }
1994 $out .= ' selected>';
1995
1996 $tmplabel = $contactstatic->getFullName($langs) . $extendedInfos;
1997 if ($showfunction && $obj->poste) {
1998 $tmplabel .= ' (' . $obj->poste . ')';
1999 }
2000 if (($showsoc > 0) && $obj->company) {
2001 $tmplabel .= ' - (' . $obj->company . ')';
2002 }
2003
2004 $out .= $tmplabel;
2005 $out .= '</option>';
2006 } else {
2007 $out .= '<option value="' . $obj->rowid . '"';
2008 if ($disabled) {
2009 $out .= ' disabled';
2010 }
2011 $out .= '>';
2012
2013 $tmplabel = $contactstatic->getFullName($langs) . $extendedInfos;
2014 if ($showfunction && $obj->poste) {
2015 $tmplabel .= ' (' . $obj->poste . ')';
2016 }
2017 if (($showsoc > 0) && $obj->company) {
2018 $tmplabel .= ' - (' . $obj->company . ')';
2019 }
2020
2021 $out .= $tmplabel;
2022 $out .= '</option>';
2023 }
2024 } else {
2025 if (in_array($obj->rowid, $selected)) {
2026 $tmplabel = $contactstatic->getFullName($langs) . $extendedInfos;
2027 if ($showfunction && $obj->poste) {
2028 $tmplabel .= ' (' . $obj->poste . ')';
2029 }
2030 if (($showsoc > 0) && $obj->company) {
2031 $tmplabel .= ' - (' . $obj->company . ')';
2032 }
2033
2034 $out .= $tmplabel;
2035 }
2036 }
2037
2038 if ($tmplabel != '') {
2039 array_push($outarray, array('key' => $obj->rowid, 'value' => $tmplabel, 'label' => $tmplabel, 'labelhtml' => $tmplabel));
2040 }
2041 }
2042 $i++;
2043 }
2044 } else {
2045 $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
2046 $out .= '<option class="disabled" value="-1"' . (($showempty == 2 || $multiple) ? '' : ' selected') . ' disabled="disabled">';
2047 $out .= $labeltoshow;
2048 $out .= '</option>';
2049 }
2050
2051 $parameters = array(
2052 'socid' => $socid,
2053 'htmlname' => $htmlname,
2054 'resql' => $resql,
2055 'out' => &$out,
2056 'showfunction' => $showfunction,
2057 'showsoc' => $showsoc,
2058 );
2059
2060 $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2061
2062 if ($htmlname != 'none' && !$options_only) {
2063 $out .= '</select>';
2064 }
2065
2066 if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
2067 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2068 $out .= ajax_combobox($htmlid, $events, getDolGlobalInt("CONTACT_USE_SEARCH_TO_SELECT"));
2069 }
2070
2071 $this->num = $num;
2072
2073 if ($options_only === 2) {
2074 // Return array of options
2075 return $outarray;
2076 } else {
2077 return $out;
2078 }
2079 } else {
2080 dol_print_error($this->db);
2081 return -1;
2082 }
2083 }
2084
2085
2086 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2087
2098 public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
2099 {
2100 // phpcs:enable
2101 global $langs, $conf;
2102
2103 // On recherche les remises
2104 $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
2105 $sql .= " re.description, re.fk_facture_source";
2106 $sql .= " FROM " . $this->db->prefix() . "societe_remise_except as re";
2107 $sql .= " WHERE re.fk_soc = " . (int) $socid;
2108 $sql .= " AND re.entity = " . $conf->entity;
2109 if ($filter) {
2110 $sql .= " AND " . $filter;
2111 }
2112 $sql .= " ORDER BY re.description ASC";
2113
2114 dol_syslog(get_class($this) . "::select_remises", LOG_DEBUG);
2115 $resql = $this->db->query($sql);
2116 if ($resql) {
2117 print '<select id="select_' . $htmlname . '" class="flat maxwidth200onsmartphone" name="' . $htmlname . '">';
2118 $num = $this->db->num_rows($resql);
2119
2120 $qualifiedlines = $num;
2121
2122 $i = 0;
2123 if ($num) {
2124 print '<option value="0">&nbsp;</option>';
2125 while ($i < $num) {
2126 $obj = $this->db->fetch_object($resql);
2127 $desc = dol_trunc($obj->description, 40);
2128 if (preg_match('/\‍(CREDIT_NOTE\‍)/', $desc)) {
2129 $desc = preg_replace('/\‍(CREDIT_NOTE\‍)/', $langs->trans("CreditNote"), $desc);
2130 }
2131 if (preg_match('/\‍(DEPOSIT\‍)/', $desc)) {
2132 $desc = preg_replace('/\‍(DEPOSIT\‍)/', $langs->trans("Deposit"), $desc);
2133 }
2134 if (preg_match('/\‍(EXCESS RECEIVED\‍)/', $desc)) {
2135 $desc = preg_replace('/\‍(EXCESS RECEIVED\‍)/', $langs->trans("ExcessReceived"), $desc);
2136 }
2137 if (preg_match('/\‍(EXCESS PAID\‍)/', $desc)) {
2138 $desc = preg_replace('/\‍(EXCESS PAID\‍)/', $langs->trans("ExcessPaid"), $desc);
2139 }
2140
2141 $selectstring = '';
2142 if ($selected > 0 && $selected == $obj->rowid) {
2143 $selectstring = ' selected';
2144 }
2145
2146 $disabled = '';
2147 if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
2148 $qualifiedlines--;
2149 $disabled = ' disabled';
2150 }
2151
2152 if (getDolGlobalString('MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST') && !empty($obj->fk_facture_source)) {
2153 $tmpfac = new Facture($this->db);
2154 if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
2155 $desc = $desc . ' - ' . $tmpfac->ref;
2156 }
2157 }
2158
2159 print '<option value="' . $obj->rowid . '"' . $selectstring . $disabled . '>' . $desc . ' (' . price($obj->amount_ht) . ' ' . $langs->trans("HT") . ' - ' . price($obj->amount_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
2160 $i++;
2161 }
2162 }
2163 print '</select>';
2164 print ajax_combobox('select_' . $htmlname);
2165
2166 return $qualifiedlines;
2167 } else {
2168 dol_print_error($this->db);
2169 return -1;
2170 }
2171 }
2172
2173
2174 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2175
2191 public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0')
2192 {
2193 // phpcs:enable
2194 print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
2195 }
2196
2197 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2198
2223 public function select_dolusers($selected = '', $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)
2224 {
2225 // phpcs:enable
2226 global $conf, $user, $langs, $hookmanager;
2227 global $action;
2228
2229 // If no preselected user defined, we take current user
2230 if ((is_numeric($selected) && ($selected < -4 || empty($selected))) && !getDolGlobalString('SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE')) {
2231 $selected = $user->id;
2232 }
2233
2234 if ($selected === '') {
2235 $selected = array();
2236 } elseif (!is_array($selected)) {
2237 $selected = array($selected);
2238 }
2239
2240 // Exclude some users in $excludeUsers string
2241 $excludeUsers = null;
2242 if (is_array($exclude)) {
2243 $excludeUsers = implode(",", $exclude);
2244 }
2245
2246 // Include some users in $includeUsers string
2247 $includeUsers = null;
2248 $includeUsersArray = array();
2249 if (is_array($include)) {
2250 $includeUsersArray = $include;
2251 } elseif ($include == 'hierarchy') {
2252 // Build list includeUsersArray to have only hierarchy
2253 $includeUsersArray = $user->getAllChildIds(0);
2254 } elseif ($include == 'hierarchyme') {
2255 // Build list includeUsersArray to have only hierarchy and current user
2256 $includeUsersArray = $user->getAllChildIds(1);
2257 }
2258 // Get list of allowed users
2259 /* 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
2260 * see all other users and element in other. For example in agenda, we can have permission to read all event of otherusers.
2261 * So we disable this.
2262 if (!$user->hasRight('user', 'user', 'lire')) {
2263 if (empty($includeUsersArray)) {
2264 $includeUsers = implode(",", $user->getAllChildIds(1));
2265 } else {
2266 $includeUsers = implode(",", array_intersect($includeUsersArray, $user->getAllChildIds(1)));
2267 }
2268 } else {
2269 $includeUsers = implode(",", $includeUsersArray);
2270 } */
2271 $includeUsers = implode(",", $includeUsersArray);
2272
2273 $num = 0;
2274
2275 $out = '';
2276 $outarray = array();
2277 $outarray2 = array();
2278
2279 // Do we want to show the label of entity into the combo list ?
2280 $showlabelofentity = isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1 && !empty($user->admin) && empty($user->entity) && !preg_match('/^search_/', $htmlname);
2281 $userissuperadminentityone = isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && empty($user->entity);
2282
2283 // Forge request to select users
2284 $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";
2285 if ($showlabelofentity) {
2286 $sql .= ", e.label";
2287 }
2288 $sql .= " FROM " . $this->db->prefix() . "user as u";
2289 if ($showlabelofentity) {
2290 $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid = u.entity";
2291 }
2292 // Condition here should be the same than into societe->getSalesRepresentatives().
2293 if ($userissuperadminentityone && $force_entity !== 'default') {
2294 if (!empty($force_entity)) {
2295 $sql .= " WHERE u.entity IN (0, " . $this->db->sanitize($force_entity) . ")";
2296 } else {
2297 $sql .= " WHERE u.entity IS NOT NULL";
2298 }
2299 } else {
2300 if (isModEnabled('multicompany') && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
2301 $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
2302 } else {
2303 $sql .= " WHERE u.entity IN (" . getEntity('user') . ")";
2304 }
2305 }
2306
2307 if (!empty($user->socid)) {
2308 $sql .= " AND u.fk_soc = " . ((int) $user->socid);
2309 }
2310 if (is_array($exclude) && $excludeUsers) {
2311 $sql .= " AND u.rowid NOT IN (" . $this->db->sanitize($excludeUsers) . ")";
2312 }
2313 if ($includeUsers) {
2314 $sql .= " AND u.rowid IN (" . $this->db->sanitize($includeUsers) . ")";
2315 }
2316 if (getDolGlobalString('USER_HIDE_INACTIVE_IN_COMBOBOX') || $notdisabled) {
2317 $sql .= " AND u.statut <> 0";
2318 }
2319 if (getDolGlobalString('USER_HIDE_NONEMPLOYEE_IN_COMBOBOX') || $notdisabled) {
2320 $sql .= " AND u.employee <> 0";
2321 }
2322 if (getDolGlobalString('USER_HIDE_EXTERNAL_IN_COMBOBOX') || $notdisabled) {
2323 $sql .= " AND u.fk_soc IS NULL";
2324 }
2325 if (!empty($morefilter)) {
2326 $errormessage = '';
2327 $sql .= forgeSQLFromUniversalSearchCriteria($morefilter, $errormessage);
2328 if ($errormessage) {
2329 $this->errors[] = $errormessage;
2330 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
2331 if ($outputmode == 0) {
2332 return 'Error bad param $morefilter';
2333 } else {
2334 return array();
2335 }
2336 }
2337 }
2338
2339 //Add hook to filter on user (for example on usergroup define in custom modules)
2340 $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
2341 if (!empty($reshook)) {
2342 $sql .= $hookmanager->resPrint;
2343 }
2344
2345 if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
2346 $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
2347 } else {
2348 $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
2349 }
2350
2351 dol_syslog(get_class($this) . "::select_dolusers", LOG_DEBUG);
2352
2353 $resql = $this->db->query($sql);
2354 if ($resql) {
2355 $num = $this->db->num_rows($resql);
2356 $i = 0;
2357 if ($num) {
2358 // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
2359 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : ' minwidth200') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
2360 if ($show_empty && !$multiple) {
2361 $textforempty = ' ';
2362 if (!empty($conf->use_javascript_ajax)) {
2363 $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
2364 }
2365 if (!is_numeric($show_empty)) {
2366 $textforempty = $show_empty;
2367 }
2368 $out .= '<option class="optiongrey" value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ((empty($selected) || in_array(-1, $selected)) ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
2369
2370 $outarray[($show_empty < 0 ? $show_empty : -1)] = $textforempty;
2371 $outarray2[($show_empty < 0 ? $show_empty : -1)] = array(
2372 'id' => ($show_empty < 0 ? $show_empty : -1),
2373 'label' => $textforempty,
2374 'labelhtml' => $textforempty,
2375 'color' => '',
2376 'picto' => ''
2377 );
2378 }
2379 if ($showalso == 2 || $showalso == 3) {
2380 $out .= '<option value="-3"' . ((in_array(-3, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("MyTeam") . ' --</option>' . "\n";
2381
2382 $hasAtLeastOneSubordinate = (count($user->getAllChildIds(1)) > 1);
2383 if ($hasAtLeastOneSubordinate) {
2384 //$sql = "SELECT rowid FROM".MAIN_DB_PREFIX."user "
2385 $outarray[-3] = '-- ' . $langs->trans("MyTeam") . ' --';
2386 $outarray2[-3] = array(
2387 'id' => -3,
2388 'label' => '-- ' . $langs->trans("MyTeam") . ' --',
2389 'labelhtml' => '-- ' . $langs->trans("MyTeam") . ' --',
2390 'color' => '',
2391 'picto' => ''
2392 );
2393 }
2394 }
2395 if ($showalso == 1 || $showalso == 3) {
2396 $out .= '<option value="-2"' . ((in_array(-2, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("Everybody") . ' --</option>' . "\n";
2397
2398 $outarray[-2] = '-- ' . $langs->trans("Everybody") . ' --';
2399 $outarray2[-2] = array(
2400 'id' => -2,
2401 'label' => '-- ' . $langs->trans("Everybody") . ' --',
2402 'labelhtml' => '-- ' . $langs->trans("Everybody") . ' --',
2403 'color' => '',
2404 'picto' => ''
2405 );
2406 }
2407 if ($showalso == 4) {
2408 $out .= '<option value="-4"' . ((in_array(-4, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("AllProjectContacts") . ' --</option>' . "\n";
2409
2410 $outarray[-4] = '-- ' . $langs->trans("AllProjectContacts") . ' --';
2411 $outarray2[-4] = array(
2412 'id' => -4,
2413 'label' => '-- ' . $langs->trans("AllProjectContacts") . ' --',
2414 'labelhtml' => '-- ' . $langs->trans("AllProjectContacts") . ' --',
2415 'color' => '',
2416 'picto' => ''
2417 );
2418 }
2419
2420 $userstatic = new User($this->db);
2421
2422 while ($i < $num) {
2423 $obj = $this->db->fetch_object($resql);
2424
2425 $userstatic->id = $obj->rowid;
2426 $userstatic->lastname = $obj->lastname;
2427 $userstatic->firstname = $obj->firstname;
2428 $userstatic->photo = $obj->photo;
2429 $userstatic->status = $obj->status;
2430 $userstatic->entity = $obj->entity;
2431 $userstatic->admin = $obj->admin;
2432 $userstatic->gender = $obj->gender;
2433
2434 $disableline = '';
2435 if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
2436 $disableline = ($enableonlytext ? $enableonlytext : '1');
2437 }
2438
2439 $labeltoshow = '';
2440 $labeltoshowhtml = '';
2441
2442 // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
2443 $fullNameMode = 0;
2444 if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) {
2445 $fullNameMode = 1; //Firstname+lastname
2446 }
2447 $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
2448 $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
2449 if (empty($obj->firstname) && empty($obj->lastname)) {
2450 $labeltoshow .= $obj->login;
2451 $labeltoshowhtml .= $obj->login;
2452 }
2453
2454 // Complete name with a more info string like: ' (info1 - info2 - ...)'
2455 $moreinfo = '';
2456 $moreinfohtml = '';
2457 if (getDolGlobalString('MAIN_SHOW_LOGIN')) {
2458 $moreinfo .= ($moreinfo ? ' - ' : ' (');
2459 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
2460 $moreinfo .= $obj->login;
2461 $moreinfohtml .= $obj->login;
2462 }
2463 if ($showstatus >= 0) {
2464 if ($obj->status == 1 && $showstatus == 1) {
2465 $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Enabled');
2466 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Enabled');
2467 }
2468 if ($obj->status == 0 && $showstatus == 1) {
2469 $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Disabled');
2470 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Disabled');
2471 }
2472 }
2473 if ($showlabelofentity) {
2474 if (empty($obj->entity)) {
2475 $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans("AllEntities");
2476 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans("AllEntities");
2477 } else {
2478 if ($obj->entity != $conf->entity) {
2479 $moreinfo .= ($moreinfo ? ' - ' : ' (') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
2480 $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
2481 }
2482 }
2483 }
2484 $moreinfo .= (!empty($moreinfo) ? ')' : '');
2485 $moreinfohtml .= (!empty($moreinfohtml) ? ')</span>' : '');
2486 if (!empty($disableline) && $disableline != '1') {
2487 // Add text from $enableonlytext parameter
2488 $moreinfo .= ' - ' . $disableline;
2489 $moreinfohtml .= ' - ' . $disableline;
2490 }
2491 $labeltoshow .= $moreinfo;
2492 $labeltoshowhtml .= $moreinfohtml;
2493
2494 $out .= '<option value="' . $obj->rowid . '"';
2495 if (!empty($disableline)) {
2496 $out .= ' disabled';
2497 }
2498 if ((!empty($selected[0]) && is_object($selected[0])) ? $selected[0]->id == $obj->rowid : in_array($obj->rowid, $selected)) {
2499 $out .= ' selected';
2500 }
2501 $out .= ' data-html="';
2502
2503 $outhtml = $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1) . ' ';
2504 if ($showstatus >= 0 && $obj->status == 0) {
2505 $outhtml .= '<strike class="opacitymediumxxx">';
2506 }
2507 $outhtml .= $labeltoshowhtml;
2508 if ($showstatus >= 0 && $obj->status == 0) {
2509 $outhtml .= '</strike>';
2510 }
2511 $labeltoshowhtml = $outhtml;
2512
2513 $out .= dol_escape_htmltag($outhtml);
2514 $out .= '">';
2515 $out .= $labeltoshow;
2516 $out .= '</option>';
2517
2518 $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength) . $moreinfo;
2519 $outarray2[$userstatic->id] = array(
2520 'id' => $userstatic->id,
2521 'label' => $labeltoshow,
2522 'labelhtml' => $labeltoshowhtml,
2523 'color' => '',
2524 'picto' => ''
2525 );
2526
2527 $i++;
2528 }
2529 } else {
2530 $out .= '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '" disabled>';
2531 $out .= '<option value="">' . $langs->trans("None") . '</option>';
2532 }
2533 $out .= '</select>';
2534
2535 if ($num && !$forcecombo) {
2536 // Enhance with select2
2537 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2538 $out .= ajax_combobox($htmlname);
2539 }
2540 } else {
2541 dol_print_error($this->db);
2542 }
2543
2544 $this->num = $num;
2545
2546 if ($outputmode == 2) {
2547 return $outarray2;
2548 } elseif ($outputmode) {
2549 return $outarray;
2550 }
2551
2552 return $out;
2553 }
2554
2555
2556 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2580 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)
2581 {
2582 // phpcs:enable
2583 global $langs, $user;
2584
2585 $userstatic = new User($this->db);
2586 $out = '';
2587
2588 if (!empty($_SESSION['assignedtouser'])) {
2589 $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
2590 if (!is_array($assignedtouser)) {
2591 $assignedtouser = array();
2592 }
2593 } else {
2594 $assignedtouser = array();
2595 }
2596 $nbassignetouser = count($assignedtouser);
2597
2598 //if ($nbassignetouser && $action != 'view') $out .= '<br>';
2599 if ($nbassignetouser) {
2600 $out .= '<ul class="attendees">';
2601 }
2602 $i = 0;
2603 $ownerid = 0;
2604 foreach ($assignedtouser as $key => $value) {
2605 if ($value['id'] == $ownerid) {
2606 continue;
2607 }
2608
2609 $out .= '<li>';
2610
2611 $userstatic->fetch($value['id']);
2612 $out .= $userstatic->getNomUrl(-4);
2613
2614 if ($i == 0) {
2615 $ownerid = $value['id'];
2616 $out .= ' (' . $langs->trans("Owner") . ')';
2617 }
2618 // Add picto to delete owner/assignee
2619 if ($nbassignetouser > 1 && $action != 'view') {
2620 $canremoveassignee = 1;
2621 if ($i == 0) {
2622 // We are on the owner of the event
2623 if (!$canremoveowner) {
2624 $canremoveassignee = 0;
2625 }
2626 if (!$user->hasRight('agenda', 'allactions', 'create')) {
2627 $canremoveassignee = 0; // Can't remove the owner
2628 }
2629 } else {
2630 // We are not on the owner of the event but on a secondary assignee
2631 }
2632 if ($canremoveassignee) {
2633 // If user has all permission, he should be ableto remove a assignee.
2634 // If user has not all permission, he can onlyremove assignee of other (he can't remove itself)
2635 $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 . '">';
2636 }
2637 }
2638 // Show my availability
2639 if ($showproperties) {
2640 if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
2641 $out .= '<div class="myavailability inline-block">';
2642 $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;';
2643 //$out .= '<span class="opacitymedium">' . $langs->trans("Availability") . ':</span>';
2644 $out .= '</span>';
2645 $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>';
2646 $out .= '</div>';
2647 }
2648 }
2649 //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
2650 //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
2651
2652 $out .= '</li>';
2653 $i++;
2654 }
2655 if ($nbassignetouser) {
2656 $out .= '</ul>';
2657 }
2658
2659 // Method with no ajax
2660 if ($action != 'view') {
2661 // Section to add another user
2662 $out .= '<div class="divadduser'.$htmlname.'">';
2663 $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
2664 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
2665 $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
2666 $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
2667 $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#' . $action . 'assignedtouser").attr("disabled", false); }';
2668 $out .= ' else { jQuery("#' . $action . 'assignedtouser").attr("disabled", true); }';
2669 $out .= '});';
2670 $out .= '})</script>';
2671 $out .= img_picto('', 'user', 'class="pictofixedwidth"');
2672 $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter, 0, '', 'minwidth200');
2673 $out .= ' <button type="submit" disabled class="button valignmiddle smallpaddingimp reposition butActionAdd" id="' . $action . 'assignedtouser" name="' . $action . 'assignedtouser" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
2674 $out .= $langs->trans("Add").'</button>';
2675 $out .= '</div>';
2676 //$out .= '<br>';
2677 }
2678
2679 return $out;
2680 }
2681
2682 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2702 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())
2703 {
2704 // phpcs:enable
2705 global $langs;
2706
2707 require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php';
2708 require_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php';
2709 $formresources = new FormResource($this->db);
2710 $resourcestatic = new Dolresource($this->db);
2711
2712 $out = '';
2713 if (!empty($_SESSION['assignedtoresource'])) {
2714 $assignedtoresource = json_decode($_SESSION['assignedtoresource'], true);
2715 if (!is_array($assignedtoresource)) {
2716 $assignedtoresource = array();
2717 }
2718 } else {
2719 $assignedtoresource = array();
2720 }
2721 $nbassignetoresource = count($assignedtoresource);
2722
2723 //if ($nbassignetoresource && $action != 'view') $out .= '<br>';
2724 if ($nbassignetoresource) {
2725 $out .= '<ul class="attendees">';
2726 }
2727 $i = 0;
2728
2729 foreach ($assignedtoresource as $key => $value) {
2730 $out .= '<li>';
2731 $resourcestatic->fetch($value['id']);
2732 $out .= $resourcestatic->getNomUrl(-1);
2733 if ($nbassignetoresource >= 1 && $action != 'view') {
2734 $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 . '">';
2735 }
2736 // Show my availability
2737 if ($showproperties) {
2738 if (is_array($listofresourceid) && count($listofresourceid)) {
2739 $out .= '<div class="myavailability inline-block">';
2740 $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;';
2741 //$out .= '<span class="opacitymedium">' . $langs->trans("Availability") . ': </span>';
2742 $out .= '</span>';
2743 $out .= ' <input title="'.$langs->trans("Availability").'" id="transparencyresource'.$value['id'].'" class="paddingrightonly" ' . ($action == 'view' ? 'disabled' : '') . ' type="checkbox" name="transparency"' . ($listofresourceid[$value['id']]['transparency'] ? ' checked' : '') . '><label for="transparencyresource'.$value['id'].'">' . $langs->trans("Busy") . '</label>';
2744 $out .= '</div>';
2745 }
2746 }
2747 //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
2748 //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
2749
2750 $out .= '</li>';
2751 $i++;
2752 }
2753 if ($nbassignetoresource) {
2754 $out .= '</ul>';
2755 }
2756
2757 // Method with no ajax
2758 if ($action != 'view') {
2759 $out .= '<input type="hidden" class="removedassignedresourcehidden" name="removedassignedresource" value="">';
2760 $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
2761 $out .= 'jQuery(".removedassignedresource").click(function() { jQuery(".removedassignedresourcehidden").val(jQuery(this).val()); });';
2762 $out .= 'jQuery(".assignedtoresource").change(function() { console.log(jQuery(".assignedtoresource option:selected").val());';
2763 $out .= ' if (jQuery(".assignedtoresource option:selected").val() > 0) { jQuery("#' . $action . 'assignedtoresource").attr("disabled", false); }';
2764 $out .= ' else { jQuery("#' . $action . 'assignedtoresource").attr("disabled", true); }';
2765 $out .= '});';
2766 $out .= '})</script>';
2767
2768 $events = array();
2769 if ($nbassignetoresource) {
2770 //$out .= img_picto('', 'add', 'class="pictofixedwidth"');
2771 } else {
2772 $out .= img_picto('', 'resource', 'class="pictofixedwidth"');
2773 }
2774 $out .= $formresources->select_resource_list(0, $htmlname, '', 1, 1, 0, $events, '', 2, 0, 'minwidth200');
2775 //$out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
2776 $out .= ' <button type="submit" disabled class="button valignmiddle smallpaddingimp reposition butActionAdd" id="' . $action . 'assignedtoresource" name="' . $action . 'assignedtoresource" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
2777 $out .= $langs->trans("Add");
2778 $out .= '</button>';
2779 $out .= '<br>';
2780 }
2781
2782 return $out;
2783 }
2784
2785 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2786
2816 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)
2817 {
2818 // phpcs:enable
2819 global $langs, $conf;
2820
2821 $out = '';
2822
2823 // check parameters
2824 $price_level = (!empty($price_level) ? $price_level : 0);
2825 if (is_null($ajaxoptions)) {
2826 $ajaxoptions = array();
2827 }
2828
2829 if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
2830 if (isModEnabled("product") && !isModEnabled('service')) {
2831 $filtertype = '0';
2832 } elseif (!isModEnabled('product') && isModEnabled("service")) {
2833 $filtertype = '1';
2834 }
2835 }
2836
2837 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
2838 $placeholder = (is_numeric($showempty) ? '' : 'placeholder="'.dolPrintHTML($showempty).'"');
2839
2840 if ($selected && empty($selected_input_value)) {
2841 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
2842 $producttmpselect = new Product($this->db);
2843 $producttmpselect->fetch($selected);
2844 $selected_input_value = $producttmpselect->ref;
2845 unset($producttmpselect);
2846 }
2847 // handle case where product or service module is disabled + no filter specified
2848 if ($filtertype == '') {
2849 if (!isModEnabled('product')) { // when product module is disabled, show services only
2850 $filtertype = 1;
2851 } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
2852 $filtertype = 0;
2853 }
2854 }
2855 // mode=1 means customers products
2856 $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;
2857 if ((int) $warehouseId > 0) {
2858 $urloption .= '&warehouseid=' . (int) $warehouseId;
2859 }
2860
2861 if (isModEnabled('variants') && is_array($selected_combinations)) {
2862 // Code to automatically insert with javascript the select of attributes under the select of product
2863 // when a parent of variant has been selected.
2864 // Note: Samecode than for product input using select
2865 $htmltag = 'input';
2866 $out .= '
2867 <!-- script to auto show attributes select tags if a variant was selected -->
2868 <script nonce="' . getNonce() . '">
2869 // auto show attributes fields
2870 selected = ' . json_encode($selected_combinations) . ';
2871 combvalues = {};
2872
2873 jQuery(document).ready(function () {
2874
2875 jQuery("input[name=\'prod_entry_mode\']").change(function () {
2876 if (jQuery(this).val() == \'free\') {
2877 jQuery(\'div#attributes_box\').empty();
2878 }
2879 });
2880
2881 jQuery("'.$htmltag.'#' . $htmlname . '").change(function () {
2882
2883 if (!jQuery(this).val()) {
2884 jQuery(\'div#attributes_box\').empty();
2885 return;
2886 }
2887
2888 console.log("A change has started. We get variants fields to inject html select");
2889
2890 jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
2891 id: jQuery(this).val()
2892 }, function (data) {
2893 jQuery(\'div#attributes_box\').empty();
2894
2895 jQuery.each(data, function (key, val) {
2896
2897 combvalues[val.id] = val.values;
2898
2899 var span = jQuery(document.createElement(\'div\')).css({
2900 \'display\': \'table-row\'
2901 });
2902
2903 span.append(
2904 jQuery(document.createElement(\'div\')).text(val.label).css({
2905 \'font-weight\': \'bold\',
2906 \'display\': \'table-cell\'
2907 })
2908 );
2909
2910 var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
2911 \'margin-left\': \'15px\',
2912 \'white-space\': \'pre\'
2913 }).append(
2914 jQuery(document.createElement(\'option\')).val(\'\')
2915 );
2916
2917 jQuery.each(combvalues[val.id], function (key, val) {
2918 var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
2919
2920 if (selected[val.fk_product_attribute] == val.id) {
2921 tag.attr(\'selected\', \'selected\');
2922 }
2923
2924 html.append(tag);
2925 });
2926
2927 span.append(html);
2928 jQuery(\'div#attributes_box\').append(span);
2929 });
2930 })
2931 });
2932
2933 ' . ($selected ? 'jQuery("'.$htmltag.'#' . $htmlname . '").change();' : '') . '
2934 });
2935 </script>
2936 ';
2937 }
2938
2939 if (empty($hidelabel)) {
2940 $placeholder = ' placeholder="' . dolPrintHTMLForAttribute($langs->trans("RefOrLabel")) . '"';
2941 } elseif ($hidelabel > 1) {
2942 $placeholder = ' placeholder="' . dolPrintHTMLForAttribute($langs->trans("RefOrLabel")) . '"';
2943 if ($hidelabel == 2) {
2944 $out .= img_picto($langs->trans("Search"), 'search');
2945 }
2946 }
2947
2948 $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" />';
2949 if ($hidelabel == 3) {
2950 $out .= img_picto($langs->trans("Search"), 'search');
2951 }
2952
2953 $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);
2954 } else {
2955 $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase, $warehouseId);
2956
2957 if (isModEnabled('variants') && is_array($selected_combinations)) {
2958 // Code to automatically insert with javascript the select of attributes under the select of product
2959 // when a parent of variant has been selected.
2960 // Note: Samecode than for product input using Ajax
2961 $htmltag = 'select';
2962 $out .= '
2963 <!-- script to auto show attributes select tags if a variant was selected -->
2964 <script nonce="' . getNonce() . '">
2965 // auto show attributes fields
2966 selected = ' . json_encode($selected_combinations) . ';
2967 combvalues = {};
2968
2969 jQuery(document).ready(function () {
2970
2971 jQuery("input[name=\'prod_entry_mode\']").change(function () {
2972 if (jQuery(this).val() == \'free\') {
2973 jQuery(\'div#attributes_box\').empty();
2974 }
2975 });
2976
2977 jQuery("'.$htmltag.'#' . $htmlname . '").change(function () {
2978
2979 if (!jQuery(this).val()) {
2980 jQuery(\'div#attributes_box\').empty();
2981 return;
2982 }
2983
2984 console.log("A change has started. We get variants fields to inject html select");
2985
2986 jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
2987 id: jQuery(this).val()
2988 }, function (data) {
2989 jQuery(\'div#attributes_box\').empty();
2990
2991 jQuery.each(data, function (key, val) {
2992
2993 combvalues[val.id] = val.values;
2994
2995 var span = jQuery(document.createElement(\'div\')).css({
2996 \'display\': \'table-row\'
2997 });
2998
2999 span.append(
3000 jQuery(document.createElement(\'div\')).text(val.label).css({
3001 \'font-weight\': \'bold\',
3002 \'display\': \'table-cell\'
3003 })
3004 );
3005
3006 var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
3007 \'margin-left\': \'15px\',
3008 \'white-space\': \'pre\'
3009 }).append(
3010 jQuery(document.createElement(\'option\')).val(\'\')
3011 );
3012
3013 jQuery.each(combvalues[val.id], function (key, val) {
3014 var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
3015
3016 if (selected[val.fk_product_attribute] == val.id) {
3017 tag.attr(\'selected\', \'selected\');
3018 }
3019
3020 html.append(tag);
3021 });
3022
3023 span.append(html);
3024 jQuery(\'div#attributes_box\').append(span);
3025 });
3026 })
3027 });
3028
3029 ' . ($selected ? 'jQuery("'.$htmltag.'#' . $htmlname . '").change();' : '') . '
3030 });
3031 </script>
3032 ';
3033 }
3034 }
3035
3036 if (empty($nooutput)) {
3037 print $out;
3038 } else {
3039 return $out;
3040 }
3041 }
3042
3043 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3044
3060 public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
3061 {
3062 // phpcs:enable
3063
3064 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
3065
3066 $error = 0;
3067 $out = '';
3068
3069 if (!$forcecombo) {
3070 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
3071 $events = array();
3072 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("BOM_USE_SEARCH_TO_SELECT"));
3073 }
3074
3075 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
3076
3077 $sql = 'SELECT b.rowid, b.ref, b.label as bomLabel, p.label as productLabel';
3078 $sql .= ' FROM ' . $this->db->prefix() . 'bom_bom as b';
3079 $sql .= ' INNER JOIN ' . $this->db->prefix() . 'product as p ON b.fk_product = p.rowid';
3080 $sql .= ' WHERE b.entity IN (' . getEntity('bom') . ')';
3081 if (!empty($status)) {
3082 $sql .= ' AND status = ' . (int) $status;
3083 }
3084 if (!empty($type)) {
3085 $sql .= ' AND bomtype = ' . (int) $type;
3086 }
3087 if (!empty($TProducts)) {
3088 $sql .= ' AND fk_product IN (' . $this->db->sanitize(implode(',', $TProducts)) . ')';
3089 }
3090 if (!empty($limit)) {
3091 $sql .= ' LIMIT ' . (int) $limit;
3092 }
3093 $resql = $this->db->query($sql);
3094 if ($resql) {
3095 if ($showempty) {
3096 $out .= '<option value="-1"';
3097 if (empty($selected)) {
3098 $out .= ' selected';
3099 }
3100 $out .= '>&nbsp;</option>';
3101 }
3102 while ($obj = $this->db->fetch_object($resql)) {
3103 $out .= '<option value="' . $obj->rowid . '"';
3104 if ($obj->rowid == $selected) {
3105 $out .= 'selected';
3106 }
3107 $out .= '>' . $obj->ref . ' - ' . $obj->productLabel . ' - ' . $obj->bomLabel . '</option>';
3108 }
3109 } else {
3110 $error++;
3111 dol_print_error($this->db);
3112 }
3113 $out .= '</select>';
3114 if (empty($nooutput)) {
3115 print $out;
3116 } else {
3117 return $out;
3118 }
3119 }
3120
3121 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3122
3149 public function select_produits_list($selected = 0, $htmlname = 'productid', $filtertype = '', $limit = 20, $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)
3150 {
3151 // phpcs:enable
3152 global $langs;
3153 global $hookmanager;
3154
3155 $out = '';
3156 $outarray = array();
3157
3158 // Units
3159 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
3160 $langs->load('other');
3161 }
3162
3163 $warehouseStatusArray = array();
3164 if (!empty($warehouseStatus)) {
3165 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
3166 if (preg_match('/warehouseclosed/', $warehouseStatus)) {
3167 $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
3168 }
3169 if (preg_match('/warehouseopen/', $warehouseStatus)) {
3170 $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
3171 }
3172 if (preg_match('/warehouseinternal/', $warehouseStatus)) {
3173 $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
3174 }
3175 }
3176
3177 $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";
3178 if (count($warehouseStatusArray)) {
3179 $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
3180 } else {
3181 $selectFieldsGrouped = ", " . $this->db->ifsql("p.stock IS NULL", '0', "p.stock") . " AS stock";
3182 }
3183
3184 $sql = "SELECT ";
3185
3186 // Add select from hooks
3187 $parameters = array();
3188 $reshook = $hookmanager->executeHooks('selectProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
3189 if (empty($reshook)) {
3190 $sql .= $selectFields.$selectFieldsGrouped.$hookmanager->resPrint;
3191 } else {
3192 $sql .= $hookmanager->resPrint;
3193 }
3194
3195 if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
3196 // Take randomly the first category of product to allow a sort on it. Bugged feature !
3197 $sql .= ", (SELECT " . $this->db->prefix() . "categorie_product.fk_categorie
3198 FROM " . $this->db->prefix() . "categorie_product
3199 WHERE " . $this->db->prefix() . "categorie_product.fk_product = p.rowid
3200 LIMIT 1
3201 ) AS categorie_product_id";
3202 }
3203
3204 // Price by customer
3205 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
3206 $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
3207 $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';
3208 $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref, custdiscount_percent";
3209 }
3210 // Units
3211 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
3212 $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";
3213 $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';
3214 }
3215
3216 // Multilang : we add translation
3217 if (getDolGlobalInt('MAIN_MULTILANGS')) {
3218 $sql .= ", pl.label as label_translated";
3219 $sql .= ", pl.description as description_translated";
3220 $selectFields .= ", label_translated";
3221 $selectFields .= ", description_translated";
3222 }
3223 // Price by quantity
3224 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
3225 $sql .= ", (SELECT pp.rowid FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid";
3226 if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
3227 $sql .= " AND price_level = " . ((int) $price_level);
3228 }
3229 $sql .= " ORDER BY date_price";
3230 $sql .= " DESC LIMIT 1) as price_rowid";
3231 $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
3232 if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
3233 $sql .= " AND price_level = " . ((int) $price_level);
3234 }
3235 $sql .= " ORDER BY date_price";
3236 $sql .= " DESC LIMIT 1) as price_by_qty";
3237 $selectFields .= ", price_rowid, price_by_qty";
3238 }
3239
3240 //$sqlfields = $sql; // $sql fields to remove for count total
3241
3242 $sql .= " FROM ".$this->db->prefix()."product as p";
3243
3244 if (getDolGlobalString('MAIN_SEARCH_PRODUCT_FORCE_INDEX')) {
3245 $sql .= " USE INDEX (" . $this->db->sanitize(getDolGlobalString('MAIN_PRODUCT_FORCE_INDEX')) . ")";
3246 }
3247
3248 // Add from (left join) from hooks
3249 $parameters = array(
3250 'socid' => $socid,
3251 );
3252 $reshook = $hookmanager->executeHooks('selectProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
3253 $sql .= $hookmanager->resPrint;
3254
3255 if (count($warehouseStatusArray)) {
3256 // Return line if product is inside the selected stock. If not, e.* and p.* will be null so we will count 0.
3257 // Replace this with a AND EXISTS ? Not possible as we need the ps.reel field for the SUM or 0 if no link.
3258 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as ps ON ps.fk_product = p.rowid";
3259 $sql .= " LEFT JOIN " . $this->db->prefix() . "entrepot as e ON ps.fk_entrepot = e.rowid AND e.entity IN (" . getEntity('stock') . ")";
3260 $sql .= ' AND e.statut IN (' . $this->db->sanitize($this->db->escape(implode(',', $warehouseStatusArray))) . ')';
3261 }
3262
3263 // Price by customer (Add field pcp for the older price for couple product/thirdparty.
3264 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
3265 $now = dol_now();
3266 $sql .= " LEFT JOIN (";
3267 $sql .= " SELECT pcp1.*";
3268 $sql .= " FROM " . $this->db->prefix() . "product_customer_price AS pcp1";
3269 $sql .= " LEFT JOIN (";
3270 $sql .= " SELECT fk_soc, fk_product, MIN(date_begin) AS date_begin";
3271 $sql .= " FROM " . $this->db->prefix() . "product_customer_price";
3272 $sql .= " WHERE fk_soc = " . ((int) $socid);
3273 $sql .= " AND date_begin <= '" . $this->db->idate($now) . "'";
3274 $sql .= " AND (date_end IS NULL OR '" . $this->db->idate($now) . "' <= date_end)";
3275 $sql .= " GROUP BY fk_soc, fk_product";
3276 $sql .= " ) AS pcp2 ON pcp1.fk_soc = pcp2.fk_soc AND pcp1.fk_product = pcp2.fk_product AND pcp1.date_begin = pcp2.date_begin";
3277 $sql .= " WHERE pcp2.fk_soc IS NOT NULL";
3278 $sql .= " ) AS pcp ON pcp.fk_soc = " . ((int) $socid) . " AND pcp.fk_product = p.rowid";
3279 }
3280 // Units : we add unit properties with a link on the primary key of unit
3281 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
3282 $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units as u ON u.rowid = p.fk_unit";
3283 }
3284 // Multilang : we add translation fields with a link on unique key fk_product/lang.
3285 if (getDolGlobalInt('MAIN_MULTILANGS')) {
3286 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_lang as pl ON pl.fk_product = p.rowid";
3287 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && !empty($socid)) {
3288 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
3289 $soc = new Societe($this->db);
3290 $result = $soc->fetch($socid);
3291 if ($result > 0 && !empty($soc->default_lang)) {
3292 $sql .= " AND pl.lang = '" . $this->db->escape($soc->default_lang) . "'";
3293 } else {
3294 $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
3295 }
3296 } else {
3297 $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
3298 }
3299 }
3300
3301 // Add WHERE conditions
3302 $sql .= ' WHERE p.entity IN (' . getEntity('product') . ')';
3303 if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD')) {
3304 if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD_BUT_ALLOW_SEARCH_IN_EAN13')) {
3305 if (strlen($filterkey) != 13) {
3306 $sql .= " AND NOT EXISTS (SELECT pac.rowid FROM ".$this->db->prefix()."product_attribute_combination as pac WHERE pac.fk_product_child = p.rowid)";
3307 }
3308 } else {
3309 $sql .= " AND NOT EXISTS (SELECT pac.rowid FROM ".$this->db->prefix()."product_attribute_combination as pac WHERE pac.fk_product_child = p.rowid)";
3310 }
3311 }
3312 if ($finished == 0) {
3313 $sql .= " AND p.finished = " . ((int) $finished);
3314 } elseif ($finished == 1) {
3315 $sql .= " AND p.finished = ".((int) $finished);
3316 }
3317 if ($status >= 0) {
3318 $sql .= " AND p.tosell = ".((int) $status);
3319 }
3320 if ($status_purchase >= 0) {
3321 $sql .= " AND p.tobuy = " . ((int) $status_purchase);
3322 }
3323 // Filter by product type
3324 if (strval($filtertype) != '') {
3325 $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
3326 } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
3327 $sql .= " AND p.fk_product_type = 1";
3328 } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
3329 $sql .= " AND p.fk_product_type = 0";
3330 }
3331
3332 if ((int) $warehouseId > 0) {
3333 $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)";
3334 }
3335
3336 // Add where from hooks
3337 $parameters = array(
3338 'filterkey' => &$filterkey,
3339 'socid' => $socid,
3340 );
3341 $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
3342 $sql .= $hookmanager->resPrint;
3343 // Add criteria on ref/label
3344 if ($filterkey != '') {
3345 $sqlSupplierSearch = '';
3346
3347 $sql .= ' AND (';
3348 $prefix = getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
3349 // For natural search
3350 $search_crit = explode(' ', $filterkey);
3351 $i = 0;
3352 if (count($search_crit) > 1) {
3353 $sql .= "(";
3354 }
3355 foreach ($search_crit as $crit) {
3356 if ($i > 0) {
3357 $sql .= " AND ";
3358 }
3359 $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3360 if (getDolGlobalInt('MAIN_MULTILANGS')) {
3361 $sql .= " OR pl.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3362 }
3363 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
3364 $sql .= " OR pcp.ref_customer LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3365 }
3366 if (getDolGlobalString('PRODUCT_AJAX_SEARCH_ON_DESCRIPTION')) {
3367 $sql .= " OR p.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3368 if (getDolGlobalInt('MAIN_MULTILANGS')) {
3369 $sql .= " OR pl.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3370 }
3371 }
3372
3373 // include search in supplier ref
3374 if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF')) {
3375 $sqlSupplierSearch .= !empty($sqlSupplierSearch) ? ' AND ' : '';
3376 $sqlSupplierSearch .= " pfp.ref_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
3377 }
3378 $sql .= ")";
3379 $i++;
3380 }
3381 if (count($search_crit) > 1) {
3382 $sql .= ")";
3383 }
3384 if (isModEnabled('barcode')) {
3385 $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
3386 }
3387
3388 // include search in supplier ref
3389 if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF')) {
3390 $sql .= " OR EXISTS (SELECT pfp.fk_product FROM " . $this->db->prefix() . "product_fournisseur_price as pfp WHERE p.rowid = pfp.fk_product";
3391 $sql .= " AND (";
3392 $sql .= $sqlSupplierSearch;
3393 $sql .= "))";
3394 }
3395
3396 $sql .= ')';
3397 }
3398 if (count($warehouseStatusArray)) {
3399 $sql .= " GROUP BY " . $selectFields; // To have the SUM on ps.reel working in the select.
3400 }
3401
3402 // Sort by category
3403 if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
3404 $sql .= " ORDER BY categorie_product_id ".(getDolGlobalInt('PRODUCT_SORT_BY_CATEGORY') == 1 ? "ASC" : "DESC");
3405 } else {
3406 $sql .= $this->db->order("p.ref");
3407 }
3408
3409 $limit = getDolGlobalInt('SEARCH_LIMIT_AJAX') ?: $limit;
3410 $sql .= $this->db->plimit($limit, 0);
3411
3412 /* The fast and low memory method to get and count full list converts the sql into a sql count */
3413 /*
3414 $nbtotalofrecords = 0;
3415 $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
3416 $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
3417
3418 $resql = $this->db->query($sqlforcount);
3419 if ($resql) {
3420 $objforcount = $this->db->fetch_object($resql);
3421 $nbtotalofrecords = $objforcount->nbtotalofrecords;
3422 } else {
3423 dol_print_error($this->db);
3424 }
3425 */
3426
3427 // Build output string
3428 dol_syslog(get_class($this) . "::select_produits_list search products", LOG_DEBUG);
3429
3430 // If we have no $limit parameter, this request may hang dur to high number of lines returned.
3431 // This should not happen because this method should not be called directly, iIt is called by select_produit() that always add a $limit parameter.
3432 $result = $this->db->query($sql);
3433
3434 if ($result) {
3435 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
3436 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
3437 require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
3438
3439 $num = $this->db->num_rows($result);
3440
3441 $events = array();
3442
3443 if (!$forcecombo) {
3444 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
3445 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
3446 }
3447
3448 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
3449
3450 $textifempty = '';
3451 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
3452 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
3453 if (getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
3454 if ($showempty && !is_numeric($showempty)) {
3455 $textifempty = $langs->trans($showempty);
3456 } else {
3457 $textifempty .= $langs->trans("All");
3458 }
3459 } else {
3460 if ($showempty && !is_numeric($showempty)) {
3461 $textifempty = $langs->trans($showempty);
3462 }
3463 }
3464 if ($showempty) {
3465 $out .= '<option value="-1" selected>' . ($textifempty ? $textifempty : '&nbsp;') . '</option>';
3466 }
3467
3468 $i = 0;
3469 while ($num && $i < $num) {
3470 $opt = '';
3471 $optJson = array();
3472 $objp = $this->db->fetch_object($result);
3473
3474 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
3475 $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
3476 $sql .= " FROM " . $this->db->prefix() . "product_price_by_qty";
3477 $sql .= " WHERE fk_product_price = " . ((int) $objp->price_rowid);
3478 $sql .= " ORDER BY quantity ASC";
3479
3480 dol_syslog(get_class($this) . "::select_produits_list search prices by qty", LOG_DEBUG);
3481 $result2 = $this->db->query($sql);
3482 if ($result2) {
3483 $nb_prices = $this->db->num_rows($result2);
3484 $j = 0;
3485 while ($nb_prices && $j < $nb_prices) {
3486 $objp2 = $this->db->fetch_object($result2);
3487
3488 $objp->price_by_qty_rowid = $objp2->rowid;
3489 $objp->price_by_qty_price_base_type = $objp2->price_base_type;
3490 $objp->price_by_qty_quantity = $objp2->quantity;
3491 $objp->price_by_qty_unitprice = $objp2->unitprice;
3492 $objp->price_by_qty_remise_percent = $objp2->remise_percent;
3493 // For backward compatibility
3494 $objp->quantity = $objp2->quantity;
3495 $objp->price = $objp2->price;
3496 $objp->unitprice = $objp2->unitprice;
3497 $objp->remise_percent = $objp2->remise_percent;
3498
3499 //$objp->tva_tx is not overwritten by $objp2 value
3500 //$objp->default_vat_code is not overwritten by $objp2 value
3501
3502 $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
3503 '@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';
3504 $j++;
3505
3506 // Add new entry
3507 // "key" value of json key array is used by jQuery automatically as selected value
3508 // "label" value of json key array is used by jQuery automatically as text for combo box
3509 $out .= $opt;
3510 array_push($outarray, $optJson);
3511 }
3512 }
3513 } else {
3514 if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
3515 $price_product = new Product($this->db);
3516 $price_product->fetch($objp->rowid, '', '', '1');
3517
3518 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
3519 $priceparser = new PriceParser($this->db);
3520 $price_result = $priceparser->parseProduct($price_product);
3521 if ($price_result >= 0) {
3522 $objp->price = $price_result;
3523 $objp->unitprice = $price_result;
3524 //Calculate the VAT
3525 $objp->price_ttc = (float) price2num($objp->price) * (1 + ($objp->tva_tx / 100));
3526 $objp->price_ttc = price2num($objp->price_ttc, 'MU');
3527 }
3528 }
3529 if (getDolGlobalInt('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES') && !empty($objp->custprice)) {
3530 $price_level = '';
3531 }
3532 $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
3533 // Add new entry
3534 // "key" value of json key array is used by jQuery automatically as selected value
3535 // "label" value of json key array is used by jQuery automatically as text for combo box
3536 $out .= $opt;
3537 array_push($outarray, $optJson);
3538 }
3539
3540 $i++;
3541 }
3542
3543 $out .= '</select>';
3544
3545 $this->db->free($result);
3546
3547 if (empty($outputmode)) {
3548 return $out;
3549 }
3550
3551 return $outarray;
3552 } else {
3553 dol_print_error($this->db);
3554 }
3555
3556 return '';
3557 }
3558
3574 protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
3575 {
3576 global $langs, $conf, $user;
3577 global $hookmanager;
3578
3579 $outkey = '';
3580 $outval = '';
3581 $outref = '';
3582 $outlabel = '';
3583 $outlabel_translated = '';
3584 $outdesc = '';
3585 $outdesc_translated = '';
3586 $outbarcode = '';
3587 $outorigin = '';
3588 $outtype = '';
3589 $outprice_ht = '';
3590 $outprice_ttc = '';
3591 $outpricebasetype = '';
3592 $outtva_tx = '';
3593 $outdefault_vat_code = '';
3594 $outqty = 1;
3595 $outdiscount = '0';
3596
3597 $maxlengtharticle = getDolGlobalInt('PRODUCT_MAX_LENGTH_COMBO', 48);
3598
3599 $label = $objp->label;
3600 if (!empty($objp->label_translated)) {
3601 $label = $objp->label_translated;
3602 }
3603 if (!empty($filterkey) && $filterkey != '') {
3604 $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
3605 }
3606
3607 $outkey = $objp->rowid;
3608 $outref = $objp->ref;
3609 $outrefcust = empty($objp->custref) ? '' : $objp->custref;
3610 $outlabel = $objp->label;
3611 $outdesc = $objp->description;
3612 if (getDolGlobalInt('MAIN_MULTILANGS')) {
3613 $outlabel_translated = $objp->label_translated;
3614 $outdesc_translated = $objp->description_translated;
3615 }
3616 $outbarcode = $objp->barcode;
3617 $outorigin = $objp->fk_country;
3618 $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
3619
3620 $outtype = $objp->fk_product_type;
3621 $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
3622 $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
3623
3624 if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
3625 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
3626 }
3627
3628 // Units
3629 $outvalUnits = '';
3630 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
3631 if (!empty($objp->unit_short)) {
3632 $outvalUnits .= ' - ' . $objp->unit_short;
3633 }
3634 }
3635 if (getDolGlobalString('PRODUCT_SHOW_DIMENSIONS_IN_COMBO')) {
3636 if (!empty($objp->weight) && $objp->weight_units !== null) {
3637 $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
3638 $outvalUnits .= ' - ' . $unitToShow;
3639 }
3640 if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
3641 $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
3642 $outvalUnits .= ' - ' . $unitToShow;
3643 }
3644 if (!empty($objp->surface) && $objp->surface_units !== null) {
3645 $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
3646 $outvalUnits .= ' - ' . $unitToShow;
3647 }
3648 if (!empty($objp->volume) && $objp->volume_units !== null) {
3649 $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
3650 $outvalUnits .= ' - ' . $unitToShow;
3651 }
3652 }
3653 if ($outdurationvalue && $outdurationunit) {
3654 $da = array(
3655 'h' => $langs->trans('Hour'),
3656 'd' => $langs->trans('Day'),
3657 'w' => $langs->trans('Week'),
3658 'm' => $langs->trans('Month'),
3659 'y' => $langs->trans('Year')
3660 );
3661 if (isset($da[$outdurationunit])) {
3662 $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
3663 }
3664 }
3665
3666 // Set stocktag (stock too low or not or unknown)
3667 $stocktag = 0;
3668 if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
3669 if ($user->hasRight('stock', 'lire')) {
3670 if ($objp->stock > 0) {
3671 $stocktag = 1;
3672 } elseif ($objp->stock <= 0) {
3673 $stocktag = -1;
3674 }
3675 }
3676 }
3677
3678 // Set $labeltoshow
3679 $labeltoshow = '';
3680 $labeltoshow .= $objp->ref;
3681 if (!empty($objp->custref)) {
3682 $labeltoshow .= ' (' . $objp->custref . ')';
3683 }
3684 if ($outbarcode) {
3685 $labeltoshow .= ' (' . $outbarcode . ')';
3686 }
3687 $labeltoshow .= ' - ' . dol_trunc($label, $maxlengtharticle);
3688 if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
3689 $labeltoshow .= ' (' . getCountry($outorigin, '1') . ')';
3690 }
3691
3692 // Set $labltoshowhtml
3693 $labeltoshowhtml = '';
3694 $labeltoshowhtml .= $objp->ref;
3695 if (!empty($objp->custref)) {
3696 $labeltoshowhtml .= ' (' . $objp->custref . ')';
3697 }
3698 if (!empty($filterkey) && $filterkey != '') {
3699 $labeltoshowhtml = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $labeltoshowhtml, 1);
3700 }
3701 if ($outbarcode) {
3702 $labeltoshowhtml .= ' (' . $outbarcode . ')';
3703 }
3704 $labeltoshowhtml .= ' - ' . dol_trunc($label, $maxlengtharticle);
3705 if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
3706 $labeltoshowhtml .= ' (' . getCountry($outorigin, '1') . ')';
3707 }
3708
3709 // Stock
3710 $labeltoshowstock = '';
3711 $labeltoshowhtmlstock = '';
3712 if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
3713 if ($user->hasRight('stock', 'lire')) {
3714 $labeltoshowstock .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
3715
3716 if ($objp->stock > 0) {
3717 $labeltoshowhtmlstock .= ' - <span class="product_line_stock_ok">';
3718 } elseif ($objp->stock <= 0) {
3719 $labeltoshowhtmlstock .= ' - <span class="product_line_stock_too_low">';
3720 }
3721 $labeltoshowhtmlstock .= $langs->transnoentities("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
3722 $labeltoshowhtmlstock .= '</span>';
3723
3724 if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
3725 $langs->load("stocks");
3726
3727 $tmpproduct = new Product($this->db);
3728 $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
3729 $tmpproduct->load_virtual_stock();
3730 $virtualstock = $tmpproduct->stock_theorique;
3731
3732 $labeltoshowstock .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
3733
3734 $labeltoshowhtmlstock .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
3735 if ($virtualstock > 0) {
3736 $labeltoshowhtmlstock .= '<span class="product_line_stock_ok">';
3737 } elseif ($virtualstock <= 0) {
3738 $labeltoshowhtmlstock .= '<span class="product_line_stock_too_low">';
3739 }
3740 $labeltoshowhtmlstock .= $virtualstock;
3741 $labeltoshowhtmlstock .= '</span>';
3742
3743 unset($tmpproduct);
3744 }
3745 }
3746 }
3747
3748 // Price
3749 $found = 0;
3750 $labeltoshowprice = '';
3751 $labeltoshowhtmlprice = '';
3752 // If we need a particular price level (from 1 to n)
3753 if (empty($hidepriceinlabel) && $price_level >= 1 && (getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'))) {
3754 $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
3755 $sql .= " FROM " . $this->db->prefix() . "product_price";
3756 $sql .= " WHERE fk_product = " . ((int) $objp->rowid);
3757 $sql .= " AND entity IN (" . getEntity('productprice') . ")";
3758 $sql .= " AND price_level = " . ((int) $price_level);
3759 $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
3760 $sql .= " LIMIT 1";
3761
3762 dol_syslog(get_class($this) . '::constructProductListOption search price for product ' . $objp->rowid . ' AND level ' . $price_level, LOG_DEBUG);
3763 $result2 = $this->db->query($sql);
3764 if ($result2) {
3765 $objp2 = $this->db->fetch_object($result2);
3766 if ($objp2) {
3767 $found = 1;
3768 if ($objp2->price_base_type == 'HT') {
3769 $labeltoshowprice .= ' - ' . price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
3770 $labeltoshowhtmlprice .= ' - ' . price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
3771 } else {
3772 $labeltoshowprice .= ' - ' . price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
3773 $labeltoshowhtmlprice .= ' - ' . price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
3774 }
3775 $outprice_ht = price($objp2->price);
3776 $outprice_ttc = price($objp2->price_ttc);
3777 $outpricebasetype = $objp2->price_base_type;
3778 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
3779 $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
3780 $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
3781 } else {
3782 $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
3783 $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
3784 }
3785 }
3786 } else {
3787 dol_print_error($this->db);
3788 }
3789 }
3790
3791 // Price by quantity
3792 if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'))) {
3793 $found = 1;
3794 $outqty = $objp->quantity;
3795 $outdiscount = $objp->remise_percent;
3796 if ($objp->quantity == 1) {
3797 $labeltoshowprice .= ' - ' . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/";
3798 $labeltoshowhtmlprice .= ' - ' . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/";
3799 $labeltoshowprice .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
3800 $labeltoshowhtmlprice .= $langs->transnoentities("Unit");
3801 } else {
3802 $labeltoshowprice .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
3803 $labeltoshowhtmlprice .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
3804 $labeltoshowprice .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
3805 $labeltoshowhtmlprice .= $langs->transnoentities("Units");
3806 }
3807
3808 $outprice_ht = price($objp->unitprice);
3809 $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
3810 $outpricebasetype = $objp->price_base_type;
3811 $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
3812 $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
3813 }
3814 if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
3815 $labeltoshowprice .= " (" . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
3816 $labeltoshowhtmlprice .= " (" . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
3817 }
3818 if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
3819 $labeltoshowprice .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
3820 $labeltoshowhtmlprice .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
3821 }
3822
3823 // Price by customer
3824 if (empty($hidepriceinlabel) && (getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'))) {
3825 if (!empty($objp->idprodcustprice)) {
3826 $found = 1;
3827
3828 if ($objp->custprice_base_type == 'HT') {
3829 $labeltoshowprice .= ' - ' . price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
3830 $labeltoshowhtmlprice .= ' - ' . price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
3831 } else {
3832 $labeltoshowprice .= ' - ' . price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
3833 $labeltoshowhtmlprice .= ' - ' . price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
3834 }
3835
3836 $outprice_ht = price($objp->custprice);
3837 $outprice_ttc = price($objp->custprice_ttc);
3838 $outpricebasetype = $objp->custprice_base_type;
3839 $outtva_tx = $objp->custtva_tx;
3840 $outdefault_vat_code = $objp->custdefault_vat_code;
3841 $outdiscount = $objp->custdiscount_percent;
3842 }
3843 }
3844
3845 // If level no defined or multiprice not found, we used the default price
3846 if (empty($hidepriceinlabel) && !$found) {
3847 if ($objp->price_base_type == 'HT') {
3848 $labeltoshowprice .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
3849 $labeltoshowhtmlprice .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
3850 } else {
3851 $labeltoshowprice .= ' - ' . price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
3852 $labeltoshowhtmlprice .= ' - ' . price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
3853 }
3854 $outprice_ht = price($objp->price);
3855 $outprice_ttc = price($objp->price_ttc);
3856 $outpricebasetype = $objp->price_base_type;
3857 $outtva_tx = $objp->tva_tx;
3858 $outdefault_vat_code = $objp->default_vat_code;
3859 }
3860
3861 // Build options
3862 $opt = '<option value="' . $objp->rowid . '"';
3863 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
3864 if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
3865 $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 . '"';
3866 }
3867 if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
3868 $opt .= ' data-labeltrans="' . $outlabel_translated . '"';
3869 $opt .= ' data-desctrans="' . dol_escape_htmltag($outdesc_translated) . '"';
3870 }
3871
3872 if ($stocktag == 1) {
3873 $opt .= ' class="product_line_stock_ok" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml, 0, array('strong')).dolPrintHTMLForAttribute($outvalUnits).$labeltoshowhtmlprice.dolPrintHTMLForAttribute($labeltoshowhtmlstock).'"';
3874 //$opt .= ' class="product_line_stock_ok"';
3875 }
3876 if ($stocktag == -1) {
3877 $opt .= ' class="product_line_stock_too_low" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml, 0, array('strong')).dolPrintHTMLForAttribute($outvalUnits).$labeltoshowhtmlprice.dolPrintHTMLForAttribute($labeltoshowhtmlstock).'"';
3878 //$opt .= ' class="product_line_stock_too_low"';
3879 }
3880
3881 $opt .= '>';
3882
3883 // Ref, barcode, country
3884 $opt .= $labeltoshow;
3885 $outval .= $labeltoshowhtml;
3886
3887 // Units
3888 $opt .= $outvalUnits;
3889 $outval .= $outvalUnits;
3890
3891 // Price
3892 $opt .= $labeltoshowprice;
3893 $outval .= $labeltoshowhtmlprice;
3894
3895 // Stock
3896 $opt .= $labeltoshowstock;
3897 $outval .= $labeltoshowhtmlstock;
3898
3899
3900 $parameters = array('objp' => $objp);
3901 $reshook = $hookmanager->executeHooks('constructProductListOption', $parameters); // Note that $action and $object may have been modified by hook
3902 if (empty($reshook)) {
3903 $opt .= $hookmanager->resPrint;
3904 } else {
3905 $opt = $hookmanager->resPrint;
3906 }
3907
3908 $opt .= "</option>\n";
3909 $optJson = array(
3910 'key' => $outkey,
3911 'value' => $outref,
3912 'label' => $outval,
3913 'label2' => $outlabel,
3914 'desc' => $outdesc,
3915 'type' => $outtype,
3916 'price_ht' => price2num($outprice_ht),
3917 'price_ttc' => price2num($outprice_ttc),
3918 'price_ht_locale' => price(price2num($outprice_ht)),
3919 'price_ttc_locale' => price(price2num($outprice_ttc)),
3920 'pricebasetype' => $outpricebasetype,
3921 'tva_tx' => $outtva_tx,
3922 'default_vat_code' => $outdefault_vat_code,
3923 'qty' => $outqty,
3924 'discount' => $outdiscount,
3925 'duration_value' => $outdurationvalue,
3926 'duration_unit' => $outdurationunit,
3927 'pbq' => $outpbq,
3928 'labeltrans' => $outlabel_translated,
3929 'desctrans' => $outdesc_translated,
3930 'ref_customer' => $outrefcust
3931 );
3932 }
3933
3934 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3935
3952 public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '', $nooutput = 0)
3953 {
3954 // phpcs:enable
3955 global $langs, $conf;
3956 global $price_level, $status, $finished;
3957
3958 if (!isset($status)) {
3959 $status = 1;
3960 }
3961
3962 $selected_input_value = '';
3963 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
3964 if ((int) $selected > 0) {
3965 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
3966 $producttmpselect = new Product($this->db);
3967 $producttmpselect->fetch((int) $selected);
3968 $selected_input_value = $producttmpselect->ref;
3969 unset($producttmpselect);
3970 }
3971
3972 // mode=2 means suppliers products
3973 $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=2&status=' . $status . '&finished=' . $finished . '&alsoproductwithnosupplierprice=' . $alsoproductwithnosupplierprice;
3974
3975 $s = ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, getDolGlobalInt('PRODUIT_USE_SEARCH_TO_SELECT'), 0, $ajaxoptions);
3976
3977 $s .= ($hidelabel ? '' : $langs->trans("RefOrLabel") . ' : ') . '<input type="text" class="'.$morecss.'" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . $placeholder . '"' : '') . '>';
3978 } else {
3979 $s = $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, getDolGlobalInt('SUPPLIER_SHOW_STOCK_IN_PRODUCTS_COMBO'), $placeholder);
3980 }
3981
3982 if ($nooutput) {
3983 return $s;
3984 } else {
3985 print $s;
3986 }
3987 }
3988
3989 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
3990
4009 public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '', $showstockinlist = 0, $placeholder = '')
4010 {
4011 // phpcs:enable
4012 global $langs, $conf, $user;
4013 global $hookmanager;
4014
4015 $out = '';
4016 $outarray = array();
4017
4018 $maxlengtharticle = getDolGlobalInt('PRODUCT_MAX_LENGTH_COMBO', 48);
4019
4020 $langs->load('stocks');
4021 // Units
4022 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4023 $langs->load('other');
4024 }
4025
4026 $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,";
4027 $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice, pfp.barcode";
4028 $sql .= ", pfp.multicurrency_code, pfp.multicurrency_unitprice";
4029 $sql .= ", pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name";
4030 $sql .= ", pfp.supplier_reputation";
4031 // if we use supplier description of the products
4032 if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
4033 $sql .= ", pfp.desc_fourn as description";
4034 } else {
4035 $sql .= ", p.description";
4036 }
4037 // Units
4038 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4039 $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";
4040 }
4041
4042 // Add select from hooks
4043 $parameters = [];
4044 $reshook = $hookmanager->executeHooks('selectSuppliersProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
4045 $sql .= $hookmanager->resPrint;
4046
4047 $sql .= " FROM " . $this->db->prefix() . "product as p";
4048
4049 // Add join from hooks
4050 $parameters = [];
4051 $reshook = $hookmanager->executeHooks('selectSuppliersProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
4052 $sql .= $hookmanager->resPrint;
4053
4054 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (" . getEntity('product') . ") )";
4055 if ($socid > 0) {
4056 $sql .= " AND pfp.fk_soc = " . ((int) $socid);
4057 }
4058 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
4059 // Units
4060 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4061 $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
4062 }
4063 $sql .= " WHERE p.entity IN (" . getEntity('product') . ")";
4064 if ($statut != -1) {
4065 $sql .= " AND p.tobuy = " . ((int) $statut);
4066 }
4067 if (strval($filtertype) != '') {
4068 $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
4069 }
4070 if (!empty($filtre)) {
4071 $sql .= " " . $filtre;
4072 }
4073 // Add where from hooks
4074 $parameters = array();
4075 $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
4076 $sql .= $hookmanager->resPrint;
4077 // Add criteria on ref/label
4078 if ($filterkey != '') {
4079 $sql .= ' AND (';
4080 $prefix = getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
4081 // For natural search
4082 $search_crit = explode(' ', $filterkey);
4083 $i = 0;
4084 if (count($search_crit) > 1) {
4085 $sql .= "(";
4086 }
4087 foreach ($search_crit as $crit) {
4088 if ($i > 0) {
4089 $sql .= " AND ";
4090 }
4091 $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) . "%'";
4092 if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
4093 $sql .= " OR pfp.desc_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
4094 }
4095 $sql .= ")";
4096 $i++;
4097 }
4098 if (count($search_crit) > 1) {
4099 $sql .= ")";
4100 }
4101 if (isModEnabled('barcode')) {
4102 $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
4103 $sql .= " OR pfp.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
4104 }
4105 $sql .= ')';
4106 }
4107 $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
4108 $sql .= $this->db->plimit($limit, 0);
4109
4110 // Build output string
4111
4112 dol_syslog(get_class($this) . "::select_produits_fournisseurs_list", LOG_DEBUG);
4113 $result = $this->db->query($sql);
4114 if ($result) {
4115 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
4116 require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
4117
4118 $num = $this->db->num_rows($result);
4119
4120 //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
4121 $out .= '<select class="flat ' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '">';
4122 if (!$selected) {
4123 $out .= '<option value="-1" selected>' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
4124 } else {
4125 $out .= '<option value="-1">' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
4126 }
4127
4128 $i = 0;
4129 while ($i < $num) {
4130 $objp = $this->db->fetch_object($result);
4131
4132 if (is_null($objp->idprodfournprice)) {
4133 // There is no supplier price found, we will use the vat rate for sale
4134 $objp->tva_tx = $objp->tva_tx_sale;
4135 $objp->default_vat_code = $objp->default_vat_code_sale;
4136 }
4137
4138 $outkey = $objp->idprodfournprice; // id in table of price
4139 if (!$outkey && $alsoproductwithnosupplierprice) {
4140 $outkey = 'idprod_' . $objp->rowid; // id of product
4141 }
4142
4143 $outref = $objp->ref;
4144 $outbarcode = $objp->barcode;
4145 $outqty = 1;
4146 $outdiscount = 0;
4147 $outtype = $objp->fk_product_type;
4148 $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
4149 $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
4150
4151 // Units
4152 $outvalUnits = '';
4153 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
4154 if (!empty($objp->unit_short)) {
4155 $outvalUnits .= ' - ' . $objp->unit_short;
4156 }
4157 if (!empty($objp->weight) && $objp->weight_units !== null) {
4158 $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
4159 $outvalUnits .= ' - ' . $unitToShow;
4160 }
4161 if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
4162 $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
4163 $outvalUnits .= ' - ' . $unitToShow;
4164 }
4165 if (!empty($objp->surface) && $objp->surface_units !== null) {
4166 $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
4167 $outvalUnits .= ' - ' . $unitToShow;
4168 }
4169 if (!empty($objp->volume) && $objp->volume_units !== null) {
4170 $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
4171 $outvalUnits .= ' - ' . $unitToShow;
4172 }
4173 if ($outdurationvalue && $outdurationunit) {
4174 $da = array(
4175 'h' => $langs->trans('Hour'),
4176 'd' => $langs->trans('Day'),
4177 'w' => $langs->trans('Week'),
4178 'm' => $langs->trans('Month'),
4179 'y' => $langs->trans('Year')
4180 );
4181 if (isset($da[$outdurationunit])) {
4182 $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
4183 }
4184 }
4185 }
4186
4187 $objRef = $objp->ref;
4188 if ($filterkey && $filterkey != '') {
4189 $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
4190 }
4191 $objRefFourn = $objp->ref_fourn;
4192 if ($filterkey && $filterkey != '') {
4193 $objRefFourn = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRefFourn, 1);
4194 }
4195 $label = $objp->label;
4196 if ($filterkey && $filterkey != '') {
4197 $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
4198 }
4199
4200 switch ($objp->fk_product_type) {
4202 $picto = 'product';
4203 break;
4205 $picto = 'service';
4206 break;
4207 default:
4208 $picto = '';
4209 break;
4210 }
4211
4212 if (empty($picto)) {
4213 $optlabel = '';
4214 } else {
4215 $optlabel = img_object('', $picto, 'class="paddingright classfortooltip"', 0, 0, 1);
4216 }
4217
4218 $optlabel .= $objp->ref;
4219 if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
4220 $optlabel .= ' <span class="opacitymedium">(' . $objp->ref_fourn . ')</span>';
4221 }
4222 if (isModEnabled('barcode') && !empty($objp->barcode)) {
4223 $optlabel .= ' (' . $outbarcode . ')';
4224 }
4225 $optlabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
4226
4227 $outvallabel = $objRef;
4228 if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
4229 $outvallabel .= ' (' . $objRefFourn . ')';
4230 }
4231 if (isModEnabled('barcode') && !empty($objp->barcode)) {
4232 $outvallabel .= ' (' . $outbarcode . ')';
4233 }
4234 $outvallabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
4235
4236 // Units
4237 $optlabel .= $outvalUnits;
4238 $outvallabel .= $outvalUnits;
4239
4240 if (!empty($objp->idprodfournprice)) {
4241 $outqty = $objp->quantity;
4242 $outdiscount = $objp->remise_percent;
4243 if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
4244 $prod_supplier = new ProductFournisseur($this->db);
4245 $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
4246 $prod_supplier->id = $objp->fk_product;
4247 $prod_supplier->fourn_qty = $objp->quantity;
4248 $prod_supplier->fourn_tva_tx = $objp->tva_tx;
4249 $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
4250
4251 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
4252 $priceparser = new PriceParser($this->db);
4253 $price_result = $priceparser->parseProductSupplier($prod_supplier);
4254 if ($price_result >= 0) {
4255 $objp->fprice = $price_result;
4256 if ($objp->quantity >= 1) {
4257 $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
4258 }
4259 }
4260 }
4261 if ($objp->quantity == 1) {
4262 $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
4263 $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/";
4264 $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
4265 $outvallabel .= $langs->transnoentities("Unit");
4266 } else {
4267 $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
4268 $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
4269 $optlabel .= ' ' . $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
4270 $outvallabel .= ' ' . $langs->transnoentities("Units");
4271 }
4272
4273 if ($objp->quantity != 1) {
4274 $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
4275 $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
4276 }
4277 if ($objp->remise_percent >= 1) {
4278 $optlabel .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
4279 $outvallabel .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
4280 }
4281 if ($objp->duration) {
4282 $optlabel .= " - " . $objp->duration;
4283 $outvallabel .= " - " . $objp->duration;
4284 }
4285 if (!$socid) {
4286 $optlabel .= " - " . dol_trunc($objp->name, 8);
4287 $outvallabel .= " - " . dol_trunc($objp->name, 8);
4288 }
4289 if ($objp->supplier_reputation) {
4290 //TODO dictionary
4291 $reputations = array('' => $langs->trans('Standard'), 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
4292
4293 $optlabel .= " - " . $reputations[$objp->supplier_reputation];
4294 $outvallabel .= " - " . $reputations[$objp->supplier_reputation];
4295 }
4296 } else {
4297 $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
4298 $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
4299 }
4300
4301 if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
4302 $novirtualstock = ($showstockinlist == 2);
4303
4304 if ($user->hasRight('stock', 'lire')) {
4305 $outvallabel .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'), 0, $langs, 0, 0);
4306
4307 if ($objp->stock > 0) {
4308 $optlabel .= ' - <span class="product_line_stock_ok">';
4309 } elseif ($objp->stock <= 0) {
4310 $optlabel .= ' - <span class="product_line_stock_too_low">';
4311 }
4312 $optlabel .= $langs->transnoentities("Stock") . ':' . price(price2num($objp->stock, 'MS'));
4313 $optlabel .= '</span>';
4314 if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
4315 $langs->load("stocks");
4316
4317 $tmpproduct = new Product($this->db);
4318 $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
4319 $tmpproduct->load_virtual_stock();
4320 $virtualstock = $tmpproduct->stock_theorique;
4321
4322 $outvallabel .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
4323
4324 $optlabel .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
4325 if ($virtualstock > 0) {
4326 $optlabel .= '<span class="product_line_stock_ok">';
4327 } elseif ($virtualstock <= 0) {
4328 $optlabel .= '<span class="product_line_stock_too_low">';
4329 }
4330 $optlabel .= $virtualstock;
4331 $optlabel .= '</span>';
4332
4333 unset($tmpproduct);
4334 }
4335 }
4336 }
4337
4338 $optstart = '<option value="' . $outkey . '"';
4339 if ($selected && preg_match('/^idprod_/', (string) $selected) && (string) $selected == 'idprod_'.$objp->rowid) {
4340 $optstart .= ' selected';
4341 } elseif ($selected && (string) $selected == (string) $objp->idprodfournprice) {
4342 $optstart .= ' selected';
4343 }
4344
4345 if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
4346 $optstart .= ' disabled';
4347 }
4348
4349 if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
4350 $optstart .= ' data-product-id="' . dol_escape_htmltag($objp->rowid) . '"';
4351 $optstart .= ' data-price-id="' . dol_escape_htmltag($objp->idprodfournprice) . '"';
4352 $optstart .= ' data-qty="' . dol_escape_htmltag($objp->quantity) . '"';
4353 $optstart .= ' data-up="' . dol_escape_htmltag(price2num($objp->unitprice)) . '"'; // the price with numeric international format
4354 $optstart .= ' data-up-locale="' . dol_escape_htmltag(price($objp->unitprice)) . '"'; // the price formatted in user language
4355 $optstart .= ' data-discount="' . dol_escape_htmltag((string) $outdiscount) . '"';
4356 $optstart .= ' data-tvatx="' . dol_escape_htmltag(price2num($objp->tva_tx)) . '"'; // the rate with numeric international format
4357 $optstart .= ' data-tvatx-formated="' . dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)) . '"'; // the rate formatted in user language
4358 $optstart .= ' data-default-vat-code="' . dol_escape_htmltag($objp->default_vat_code) . '"';
4359 $optstart .= ' data-supplier-ref="' . dol_escape_htmltag($objp->ref_fourn) . '"';
4360 if (isModEnabled('multicurrency')) {
4361 $optstart .= ' data-multicurrency-code="' . dol_escape_htmltag($objp->multicurrency_code) . '"';
4362 $optstart .= ' data-multicurrency-unitprice="' . dol_escape_htmltag(price2num($objp->multicurrency_unitprice)) . '"'; // the price with numeric international format
4363 }
4364 }
4365 $optstart .= ' data-description="' . dol_escape_htmltag($objp->description, 0, 1) . '"';
4366
4367 // set $parameters to call hook
4368 $outarrayentry = array(
4369 'key' => $outkey,
4370 'value' => $outref,
4371 'label' => $outvallabel,
4372 'labelhtml' => $optlabel,
4373 'qty' => $outqty,
4374 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
4375 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
4376 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
4377 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
4378 'tva_tx' => price2num($objp->tva_tx),
4379 'default_vat_code' => $objp->default_vat_code,
4380 'supplier_ref' => $objp->ref_fourn,
4381 'discount' => $outdiscount,
4382 'type' => $outtype,
4383 'duration_value' => $outdurationvalue,
4384 'duration_unit' => $outdurationunit,
4385 'disabled' => empty($objp->idprodfournprice),
4386 'description' => $objp->description
4387 );
4388 if (isModEnabled('multicurrency')) {
4389 $outarrayentry['multicurrency_code'] = $objp->multicurrency_code;
4390 $outarrayentry['multicurrency_unitprice'] = price2num($objp->multicurrency_unitprice, 'MU');
4391 }
4392 $parameters = array(
4393 'objp' => &$objp,
4394 'optstart' => &$optstart,
4395 'optlabel' => &$optlabel,
4396 'outvallabel' => &$outvallabel,
4397 'outarrayentry' => &$outarrayentry,
4398 'fk_soc' => $socid
4399 );
4400 $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
4401
4402
4403 // Add new entry
4404 // "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
4405 // "label" value of json key array is used by jQuery automatically as text for combo box
4406 $out .= $optstart . ' data-html="' . dol_escape_htmltag($optlabel) . '">' . $optlabel . "</option>\n";
4407 $outarraypush = array(
4408 'key' => $outkey,
4409 'value' => $outref,
4410 'label' => $outvallabel,
4411 'labelhtml' => $optlabel,
4412 'qty' => $outqty,
4413 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
4414 'price_qty_ht_locale' => price($objp->fprice),
4415 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
4416 'price_unit_ht_locale' => price($objp->unitprice),
4417 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
4418 'tva_tx_formated' => price($objp->tva_tx),
4419 'tva_tx' => price2num($objp->tva_tx),
4420 'default_vat_code' => $objp->default_vat_code,
4421 'supplier_ref' => $objp->ref_fourn,
4422 'discount' => $outdiscount,
4423 'type' => $outtype,
4424 'duration_value' => $outdurationvalue,
4425 'duration_unit' => $outdurationunit,
4426 'disabled' => empty($objp->idprodfournprice),
4427 'description' => $objp->description
4428 );
4429 if (isModEnabled('multicurrency')) {
4430 $outarraypush['multicurrency_code'] = $objp->multicurrency_code;
4431 $outarraypush['multicurrency_unitprice'] = price2num($objp->multicurrency_unitprice, 'MU');
4432 }
4433 array_push($outarray, $outarraypush);
4434
4435 // Example of var_dump $outarray
4436 // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
4437 // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
4438 // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
4439 //}
4440 //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
4441 //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
4442 //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
4443
4444 $i++;
4445 }
4446 $out .= '</select>';
4447
4448 $this->db->free($result);
4449
4450 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4451 $out .= ajax_combobox($htmlname);
4452 } else {
4453 dol_print_error($this->db);
4454 }
4455
4456 if (empty($outputmode)) {
4457 return $out;
4458 }
4459 return $outarray;
4460 }
4461
4462 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4463
4472 public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = 0)
4473 {
4474 // phpcs:enable
4475 global $langs, $conf;
4476
4477 $langs->load('stocks');
4478
4479 $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
4480 $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
4481 $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
4482 $sql .= " FROM " . $this->db->prefix() . "product as p";
4483 $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
4484 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
4485 $sql .= " WHERE pfp.entity IN (" . getEntity('productsupplierprice') . ")";
4486 $sql .= " AND p.tobuy = 1";
4487 $sql .= " AND s.fournisseur = 1";
4488 $sql .= " AND p.rowid = " . ((int) $productid);
4489 if (!getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED')) {
4490 $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
4491 } else {
4492 $sql .= " ORDER BY pfp.unitprice ASC";
4493 }
4494
4495 dol_syslog(get_class($this) . "::select_product_fourn_price", LOG_DEBUG);
4496 $result = $this->db->query($sql);
4497
4498 if ($result) {
4499 $num = $this->db->num_rows($result);
4500
4501 $form = '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
4502
4503 if (!$num) {
4504 $form .= '<option value="0">-- ' . $langs->trans("NoSupplierPriceDefinedForThisProduct") . ' --</option>';
4505 } else {
4506 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
4507 $form .= '<option value="0">&nbsp;</option>';
4508
4509 $i = 0;
4510 while ($i < $num) {
4511 $objp = $this->db->fetch_object($result);
4512
4513 $opt = '<option value="' . $objp->idprodfournprice . '"';
4514 //if there is only one supplier, preselect it
4515 if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED'))) {
4516 $opt .= ' selected';
4517 }
4518 $opt .= '>' . $objp->name . ' - ' . $objp->ref_fourn . ' - ';
4519
4520 if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
4521 $prod_supplier = new ProductFournisseur($this->db);
4522 $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
4523 $prod_supplier->id = $productid;
4524 $prod_supplier->fourn_qty = $objp->quantity;
4525 $prod_supplier->fourn_tva_tx = $objp->tva_tx;
4526 $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
4527
4528 require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
4529 $priceparser = new PriceParser($this->db);
4530 $price_result = $priceparser->parseProductSupplier($prod_supplier);
4531 if ($price_result >= 0) {
4532 $objp->fprice = $price_result;
4533 if ($objp->quantity >= 1) {
4534 $objp->unitprice = $objp->fprice / $objp->quantity;
4535 }
4536 }
4537 }
4538 if ($objp->quantity == 1) {
4539 $opt .= price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
4540 }
4541
4542 $opt .= $objp->quantity . ' ';
4543
4544 if ($objp->quantity == 1) {
4545 $opt .= $langs->trans("Unit");
4546 } else {
4547 $opt .= $langs->trans("Units");
4548 }
4549 if ($objp->quantity > 1) {
4550 $opt .= " - ";
4551 $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");
4552 }
4553 if ($objp->duration) {
4554 $opt .= " - " . $objp->duration;
4555 }
4556 $opt .= "</option>\n";
4557
4558 $form .= $opt;
4559 $i++;
4560 }
4561 }
4562
4563 $form .= '</select>';
4564 $this->db->free($result);
4565 return $form;
4566 } else {
4567 dol_print_error($this->db);
4568 return '';
4569 }
4570 }
4571
4572
4573 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4580 {
4581 // phpcs:enable
4582 global $langs, $hookmanager;
4583
4584 $num = count($this->cache_conditions_paiements);
4585 if ($num > 0) {
4586 return 0; // Cache already loaded
4587 }
4588
4589 dol_syslog(__METHOD__, LOG_DEBUG);
4590
4591 $this->cache_conditions_paiements = array();
4592
4593 $sql = "SELECT rowid, code, libelle as label, deposit_percent, entity";
4594 $sql .= " FROM " . $this->db->prefix() . 'c_payment_term';
4595 $sql .= " WHERE entity IN (" . getEntity('c_payment_term') . ")";
4596 $sql .= " AND active > 0";
4597 $sql .= " ORDER BY sortorder";
4598
4599 $resql = $this->db->query($sql);
4600 if ($resql) {
4601 $num = $this->db->num_rows($resql);
4602 $i = 0;
4603 while ($i < $num) {
4604 $obj = $this->db->fetch_object($resql);
4605
4606 // Si traduction existe, on l'utilise, sinon on prend le libelle par default
4607 $label = ($langs->trans("PaymentConditionShort" . $obj->code) != "PaymentConditionShort" . $obj->code ? $langs->trans("PaymentConditionShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
4608 $this->cache_conditions_paiements[$obj->rowid]['code'] = (string) $obj->code;
4609 $this->cache_conditions_paiements[$obj->rowid]['label'] = (string) $label;
4610 $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = (string) $obj->deposit_percent;
4611 $this->cache_conditions_paiements[$obj->rowid]['entity'] = (int) $obj->entity;
4612 $i++;
4613 }
4614
4615 $parameters = array('context' => 'paymentterm');
4616 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
4617 if (empty($reshook)) {
4618 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
4619 $this->cache_conditions_paiements = array_merge($this->cache_conditions_paiements, $hookmanager->resArray);
4620 }
4621 } else {
4622 $this->cache_conditions_paiements = $hookmanager->resArray;
4623 }
4624
4625 //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
4626
4627 return $num;
4628 } else {
4629 dol_print_error($this->db);
4630 return -1;
4631 }
4632 }
4633
4634 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4635
4642 {
4643 // phpcs:enable
4644 $factureRec = new FactureRec($this->db);
4645
4646 $this->cache_rule_for_lines_dates = $factureRec->fields['rule_for_lines_dates']['arrayofkeyval'];
4647
4648 if (empty($this->cache_rule_for_lines_dates)) {
4649 return -1;
4650 }
4651
4652 return 1;
4653 }
4654
4655 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4656
4662 public function load_cache_availability()
4663 {
4664 // phpcs:enable
4665 global $langs;
4666
4667 $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
4668 if ($num > 0) {
4669 return 0; // Cache already loaded
4670 }
4671
4672 dol_syslog(__METHOD__, LOG_DEBUG);
4673
4674 $this->cache_availability = array();
4675
4676 $langs->load('propal');
4677
4678 $sql = "SELECT rowid, code, label, position";
4679 $sql .= " FROM " . $this->db->prefix() . 'c_availability';
4680 $sql .= " WHERE active > 0";
4681
4682 $resql = $this->db->query($sql);
4683 if ($resql) {
4684 $num = $this->db->num_rows($resql);
4685 $i = 0;
4686 while ($i < $num) {
4687 $obj = $this->db->fetch_object($resql);
4688
4689 // Si traduction existe, on l'utilise, sinon on prend le libelle par default
4690 $label = ($langs->trans("AvailabilityType" . $obj->code) != "AvailabilityType" . $obj->code ? $langs->trans("AvailabilityType" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
4691 $this->cache_availability[$obj->rowid]['code'] = (string) $obj->code;
4692 $this->cache_availability[$obj->rowid]['label'] = (string) $label;
4693 $this->cache_availability[$obj->rowid]['position'] = (int) $obj->position;
4694 $i++;
4695 }
4696
4697 $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
4698
4699 return $num;
4700 } else {
4701 dol_print_error($this->db);
4702 return -1;
4703 }
4704 }
4705
4716 public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
4717 {
4718 global $langs, $user;
4719
4720 $this->load_cache_availability();
4721
4722 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
4723
4724 print '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
4725 if ($addempty) {
4726 print '<option value="0">&nbsp;</option>';
4727 }
4728 foreach ($this->cache_availability as $id => $arrayavailability) {
4729 if ($selected == $id) {
4730 print '<option value="' . $id . '" selected>';
4731 } else {
4732 print '<option value="' . $id . '">';
4733 }
4734 print dol_escape_htmltag($arrayavailability['label']);
4735 print '</option>';
4736 }
4737 print '</select>';
4738 if ($user->admin) {
4739 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
4740 }
4741 print ajax_combobox($htmlname);
4742 }
4743
4749 public function loadCacheInputReason()
4750 {
4751 global $langs;
4752
4753 $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
4754 if ($num > 0) {
4755 return 0; // Cache already loaded
4756 }
4757
4758 $sql = "SELECT rowid, code, label";
4759 $sql .= " FROM " . $this->db->prefix() . 'c_input_reason';
4760 $sql .= " WHERE active > 0";
4761
4762 $resql = $this->db->query($sql);
4763 if ($resql) {
4764 $num = $this->db->num_rows($resql);
4765 $i = 0;
4767 $tmparray = array();
4768 while ($i < $num) {
4769 $obj = $this->db->fetch_object($resql);
4770
4771 // Si traduction existe, on l'utilise, sinon on prend le libelle par default
4772 $label = ($obj->label != '-' ? (string) $obj->label : '');
4773 if ($langs->trans("DemandReasonType" . $obj->code) != "DemandReasonType" . $obj->code) {
4774 $label = $langs->trans("DemandReasonType" . $obj->code); // So translation key DemandReasonTypeSRC_XXX will work
4775 }
4776 if ($langs->trans($obj->code) != $obj->code) {
4777 $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
4778 }
4779
4780 $tmparray[(int) $obj->rowid]
4781 = array(
4782 'id' => (int) $obj->rowid,
4783 'code' => (string) $obj->code,
4784 'label' => $label,
4785 );
4786 $i++;
4787 }
4788
4789 $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
4790
4791 unset($tmparray);
4792 return $num;
4793 } else {
4794 dol_print_error($this->db);
4795 return -1;
4796 }
4797 }
4798
4811 public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
4812 {
4813 global $langs, $user;
4814
4815 $this->loadCacheInputReason();
4816
4817 print '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="select_' . $htmlname . '" name="' . $htmlname . '">';
4818 if ($addempty) {
4819 print '<option value="0"' . (empty($selected) ? ' selected' : '') . '>&nbsp;</option>';
4820 }
4821 foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
4822 if ($arraydemandreason['code'] == $exclude) {
4823 continue;
4824 }
4825
4826 if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
4827 print '<option value="' . $arraydemandreason['id'] . '" selected>';
4828 } else {
4829 print '<option value="' . $arraydemandreason['id'] . '">';
4830 }
4831 $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
4832 print $langs->trans($label);
4833 print '</option>';
4834 }
4835 print '</select>';
4836 if ($user->admin && empty($notooltip)) {
4837 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
4838 }
4839 print ajax_combobox('select_' . $htmlname);
4840 }
4841
4842 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4843
4850 {
4851 // phpcs:enable
4852 global $langs, $hookmanager;
4853
4854 $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
4855 if ($num > 0) {
4856 return $num; // Cache already loaded
4857 }
4858
4859 dol_syslog(__METHOD__, LOG_DEBUG);
4860
4861 $this->cache_types_paiements = array();
4862
4863 $sql = "SELECT id, code, libelle as label, type, entity, active";
4864 $sql .= " FROM " . $this->db->prefix() . "c_paiement";
4865 $sql .= " WHERE entity IN (" . getEntity('c_paiement') . ")";
4866
4867 $resql = $this->db->query($sql);
4868 if ($resql) {
4869 $num = $this->db->num_rows($resql);
4870 $i = 0;
4871 while ($i < $num) {
4872 $obj = $this->db->fetch_object($resql);
4873
4874 // Si traduction existe, on l'utilise, sinon on prend le libelle par default
4875 $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
4876 $this->cache_types_paiements[$obj->id]['id'] = (int) $obj->id;
4877 $this->cache_types_paiements[$obj->id]['code'] = (string) $obj->code;
4878 $this->cache_types_paiements[$obj->id]['label'] = (string) $label;
4879 $this->cache_types_paiements[$obj->id]['type'] = (int) $obj->type;
4880 $this->cache_types_paiements[$obj->id]['entity'] = (int) $obj->entity;
4881 $this->cache_types_paiements[$obj->id]['active'] = (int) $obj->active;
4882 $i++;
4883 }
4884
4885 $parameters = array('context' => 'paymenttype');
4886 $reshook = $hookmanager->executeHooks('loadDictionaryCache', $parameters, $this); // Note that $action and $object may have been modified by hook
4887 if (empty($reshook)) {
4888 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
4889 $this->cache_types_paiements = array_merge($this->cache_types_paiements, $hookmanager->resArray);
4890 }
4891 } else {
4892 $this->cache_types_paiements = $hookmanager->resArray;
4893 }
4894
4895 $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
4896
4897 return $num;
4898 } else {
4899 dol_print_error($this->db);
4900 return -1;
4901 }
4902 }
4903
4904
4905 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
4906
4925 public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1, $noprint = 0)
4926 {
4927 // phpcs:enable
4928 $out = $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
4929 if (empty($noprint)) {
4930 print $out;
4931 } else {
4932 return $out;
4933 }
4934 }
4935
4936
4953 public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
4954 {
4955 global $langs, $user, $conf;
4956
4957 $out = '';
4958 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
4959
4961
4962 // Set default value if not already set by caller
4963 if (empty($selected) && strpos($htmlname, 'search_') !== 0 && getDolGlobalString('MAIN_DEFAULT_PAYMENT_TERM_ID')) {
4964 dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TERM_ID", LOG_NOTICE);
4965 $selected = getDolGlobalString('MAIN_DEFAULT_PAYMENT_TERM_ID');
4966 }
4967
4968 $out .= '<select id="' . $htmlname . '" class="flat selectpaymentterms' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
4969 if ($addempty) {
4970 $out .= '<option value="0">&nbsp;</option>';
4971 }
4972
4973 $selectedDepositPercent = null;
4974
4975 foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
4976 if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
4977 continue;
4978 }
4979
4980 if ($selected == $id) {
4981 $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
4982 $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
4983 } else {
4984 $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
4985 }
4986 $label = $arrayconditions['label'];
4987
4988 if (!empty($arrayconditions['deposit_percent'])) {
4989 $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
4990 }
4991
4992 $out .= $label;
4993 $out .= '</option>';
4994 }
4995 $out .= '</select>';
4996 if ($user->admin && empty($noinfoadmin)) {
4997 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
4998 }
4999 $out .= ajax_combobox($htmlname);
5000
5001 if ($deposit_percent >= 0) {
5002 $out .= ' <span id="' . $htmlname . '_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
5003 $out .= $langs->trans('DepositPercent') . ' : ';
5004 $out .= '<input id="' . $htmlname . '_deposit_percent" name="' . $htmlname . '_deposit_percent" class="maxwidth50" value="' . $deposit_percent . '" />';
5005 $out .= '</span>';
5006 $out .= '
5007 <script nonce="' . getNonce() . '">
5008 $(document).ready(function () {
5009 $("#' . $htmlname . '").change(function () {
5010 let $selected = $(this).find("option:selected");
5011 let depositPercent = $selected.attr("data-deposit_percent");
5012
5013 if (depositPercent.length > 0) {
5014 $("#' . $htmlname . '_deposit_percent_container").show().find("#' . $htmlname . '_deposit_percent").val(depositPercent);
5015 } else {
5016 $("#' . $htmlname . '_deposit_percent_container").hide();
5017 }
5018
5019 return true;
5020 });
5021 });
5022 </script>';
5023 }
5024
5025 return $out;
5026 }
5027
5028
5037 public function getSelectRuleForLinesDates($selected = '', $htmlname = 'rule_for_lines_dates', $addempty = 0)
5038 {
5039 global $langs;
5040
5041 $out = '';
5042
5044
5045 $out .= '<select id="' . $htmlname . '" class="flat selectbillingterm" name="' . $htmlname . '">';
5046 if ($addempty) {
5047 $out .= '<option value="-1">&nbsp;</option>';
5048 }
5049
5050
5051 foreach ($this->cache_rule_for_lines_dates as $rule_for_lines_dates_key => $rule_for_lines_dates_name) {
5052 if ($selected == $rule_for_lines_dates_key) {
5053 $out .= '<option value="' . $rule_for_lines_dates_key . '" selected>';
5054 } else {
5055 $out .= '<option value="' . $rule_for_lines_dates_key . '">';
5056 }
5057
5058 $out .= $langs->trans($rule_for_lines_dates_name);
5059 $out .= '</option>';
5060 }
5061 $out .= '</select>';
5062
5063 $out .= ajax_combobox($htmlname);
5064
5065 return $out;
5066 }
5067
5068
5069 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5070
5087 public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
5088 {
5089 // phpcs:enable
5090 global $langs, $user, $conf;
5091
5092 $out = '';
5093
5094 dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
5095
5096 $filterarray = array();
5097 if ($filtertype == 'CRDT') {
5098 $filterarray = array(0, 2, 3);
5099 } elseif ($filtertype == 'DBIT') {
5100 $filterarray = array(1, 2, 3);
5101 } elseif ($filtertype != '' && $filtertype != '-1') {
5102 $filterarray = explode(',', $filtertype);
5103 }
5104
5106
5107 // Set default value if not already set by caller
5108 if (empty($selected) && strpos($htmlname, 'search_') !== 0 && getDolGlobalString('MAIN_DEFAULT_PAYMENT_TYPE_ID')) {
5109 dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TYPE_ID", LOG_NOTICE);
5110 $selected = getDolGlobalString('MAIN_DEFAULT_PAYMENT_TYPE_ID');
5111 }
5112
5113 $out .= '<select id="select' . $htmlname . '" class="flat selectpaymenttypes' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
5114 if ($empty) {
5115 $out .= '<option value="">&nbsp;</option>';
5116 }
5117 foreach ($this->cache_types_paiements as $id => $arraytypes) {
5118 // If not good status
5119 if ($active >= 0 && $arraytypes['active'] != $active) {
5120 continue;
5121 }
5122
5123 // We skip of the user requested to filter on specific payment methods
5124 if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
5125 continue;
5126 }
5127
5128 // We discard empty lines if showempty is on because an empty line has already been output.
5129 if ($empty && empty($arraytypes['code'])) {
5130 continue;
5131 }
5132
5133 if ($format == 0) {
5134 $out .= '<option value="' . $id . '" data-code="'.$arraytypes['code'].'"';
5135 } elseif ($format == 1) {
5136 $out .= '<option value="' . $arraytypes['code'] . '"';
5137 } elseif ($format == 2) {
5138 $out .= '<option value="' . $arraytypes['code'] . '"';
5139 } elseif ($format == 3) {
5140 $out .= '<option value="' . $id . '"';
5141 }
5142 // Print attribute selected or not
5143 if ($format == 1 || $format == 2) {
5144 if ($selected == $arraytypes['code']) {
5145 $out .= ' selected';
5146 }
5147 } else {
5148 if ($selected == $id) {
5149 $out .= ' selected';
5150 }
5151 }
5152 $out .= '>';
5153 $value = '';
5154 if ($format == 0) {
5155 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
5156 } elseif ($format == 1) {
5157 $value = $arraytypes['code'];
5158 } elseif ($format == 2) {
5159 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
5160 } elseif ($format == 3) {
5161 $value = $arraytypes['code'];
5162 }
5163 $out .= $value ? $value : '&nbsp;';
5164 $out .= '</option>';
5165 }
5166 $out .= '</select>';
5167 if ($user->admin && !$noadmininfo) {
5168 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5169 }
5170 $out .= ajax_combobox('select' . $htmlname);
5171
5172 if (empty($nooutput)) {
5173 print $out;
5174 } else {
5175 return $out;
5176 }
5177 }
5178
5179
5188 public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
5189 {
5190 global $langs;
5191
5192 $return = '<select class="flat maxwidth100" id="select_' . $htmlname . '" name="' . $htmlname . '">';
5193 $options = array(
5194 'HT' => $langs->trans("HT"),
5195 'TTC' => $langs->trans("TTC")
5196 );
5197 foreach ($options as $id => $value) {
5198 if ($selected == $id) {
5199 $return .= '<option value="' . $id . '" selected>' . $value;
5200 } else {
5201 $return .= '<option value="' . $id . '">' . $value;
5202 }
5203 $return .= '</option>';
5204 }
5205 $return .= '</select>';
5206 if ($addjscombo) {
5207 $return .= ajax_combobox('select_' . $htmlname);
5208 }
5209
5210 return $return;
5211 }
5212
5213 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5214
5221 {
5222 // phpcs:enable
5223 global $langs;
5224
5225 $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
5226 if ($num > 0) {
5227 return $num; // Cache already loaded
5228 }
5229
5230 dol_syslog(__METHOD__, LOG_DEBUG);
5231
5232 $this->cache_transport_mode = array();
5233
5234 $sql = "SELECT rowid, code, label, active";
5235 $sql .= " FROM " . $this->db->prefix() . "c_transport_mode";
5236 $sql .= " WHERE entity IN (" . getEntity('c_transport_mode') . ")";
5237
5238 $resql = $this->db->query($sql);
5239 if ($resql) {
5240 $num = $this->db->num_rows($resql);
5241 $i = 0;
5242 while ($i < $num) {
5243 $obj = $this->db->fetch_object($resql);
5244
5245 // If traduction exist, we use it else we take the default label
5246 $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
5247 $this->cache_transport_mode[(int) $obj->rowid]
5248 = array(
5249 'rowid' => (int) $obj->rowid,
5250 'code' => (string) $obj->code,
5251 'label' => (string) $label,
5252 'active' => (int) $obj->active,
5253 );
5254 $i++;
5255 }
5256
5257 $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
5258
5259 return $num;
5260 } else {
5261 dol_print_error($this->db);
5262 return -1;
5263 }
5264 }
5265
5279 public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
5280 {
5281 global $langs, $user;
5282
5283 dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $format, LOG_DEBUG);
5284
5286
5287 print '<select id="select' . $htmlname . '" class="flat selectmodetransport' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
5288 if ($empty) {
5289 print '<option value="">&nbsp;</option>';
5290 }
5291 foreach ($this->cache_transport_mode as $id => $arraytypes) {
5292 // If not good status
5293 if ($active >= 0 && $arraytypes['active'] != $active) {
5294 continue;
5295 }
5296
5297 // We discard empty line if showempty is on because an empty line has already been output.
5298 if ($empty && empty($arraytypes['code'])) {
5299 continue;
5300 }
5301
5302 if ($format == 0) {
5303 print '<option value="' . $id . '"';
5304 } elseif ($format == 1) {
5305 print '<option value="' . $arraytypes['code'] . '"';
5306 } elseif ($format == 2) {
5307 print '<option value="' . $arraytypes['code'] . '"';
5308 } elseif ($format == 3) {
5309 print '<option value="' . $id . '"';
5310 }
5311 // If text is selected, we compare with code, else with id
5312 if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
5313 print ' selected';
5314 } elseif ($selected == $id) {
5315 print ' selected';
5316 }
5317 print '>';
5318 $value = '';
5319 if ($format == 0) {
5320 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
5321 } elseif ($format == 1) {
5322 $value = $arraytypes['code'];
5323 } elseif ($format == 2) {
5324 $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
5325 } elseif ($format == 3) {
5326 $value = $arraytypes['code'];
5327 }
5328 print $value ? $value : '&nbsp;';
5329 print '</option>';
5330 }
5331 print '</select>';
5332
5333 print ajax_combobox("select".$htmlname);
5334
5335 if ($user->admin && !$noadmininfo) {
5336 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5337 }
5338 }
5339
5352 public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
5353 {
5354 global $langs, $user;
5355
5356 $langs->loadLangs(array("admin", "sendings"));
5357
5358 $sql = "SELECT rowid, code, libelle as label";
5359 $sql .= " FROM " . $this->db->prefix() . "c_shipment_mode";
5360 $sql .= " WHERE active > 0";
5361 if ($filtre) {
5362 $sql .= " AND " . $filtre;
5363 }
5364 $sql .= " ORDER BY libelle ASC";
5365
5366 dol_syslog(get_class($this) . "::selectShippingMode", LOG_DEBUG);
5367 $result = $this->db->query($sql);
5368 if ($result) {
5369 $num = $this->db->num_rows($result);
5370 $i = 0;
5371 if ($num) {
5372 print '<select id="select' . $htmlname . '" class="flat selectshippingmethod' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
5373 if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
5374 print '<option value="-1">&nbsp;</option>';
5375 }
5376 while ($i < $num) {
5377 $obj = $this->db->fetch_object($result);
5378 if ($selected == $obj->rowid) {
5379 print '<option value="' . $obj->rowid . '" selected>';
5380 } else {
5381 print '<option value="' . $obj->rowid . '">';
5382 }
5383 print ($langs->trans("SendingMethod" . strtoupper($obj->code)) != "SendingMethod" . strtoupper($obj->code)) ? $langs->trans("SendingMethod" . strtoupper($obj->code)) : $obj->label;
5384 print '</option>';
5385 $i++;
5386 }
5387 print "</select>";
5388 if ($user->admin && empty($noinfoadmin)) {
5389 print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
5390 }
5391
5392 print ajax_combobox('select' . $htmlname);
5393 } else {
5394 print $langs->trans("NoShippingMethodDefined");
5395 }
5396 } else {
5397 dol_print_error($this->db);
5398 }
5399 }
5400
5410 public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
5411 {
5412 global $langs;
5413
5414 $langs->load("sendings");
5415
5416 if ($htmlname != "none") {
5417 print '<form method="POST" action="' . $page . '">';
5418 print '<input type="hidden" name="action" value="setshippingmethod">';
5419 print '<input type="hidden" name="token" value="' . newToken() . '">';
5420 $this->selectShippingMethod($selected, $htmlname, '', $addempty);
5421 print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
5422 print '</form>';
5423 } else {
5424 if ($selected) {
5425 $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
5426 print $langs->trans("SendingMethod" . strtoupper($code));
5427 } else {
5428 print "&nbsp;";
5429 }
5430 }
5431 }
5432
5441 public function selectSituationInvoices($selected = '', $socid = 0)
5442 {
5443 global $langs;
5444
5445 $langs->load('bills');
5446
5447 $opt = '';
5448
5449 $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
5450 $sql .= ' FROM ' . $this->db->prefix() . 'facture';
5451 $sql .= ' WHERE entity IN (' . getEntity('invoice') . ')';
5452 $sql .= ' AND situation_counter >= 1';
5453 $sql .= ' AND fk_soc = ' . (int) $socid;
5454 $sql .= ' AND type <> 2';
5455 $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
5456 $resql = $this->db->query($sql);
5457
5458 $nbSituationInvoiceForThirdparty = 0;
5459
5460 if ($resql && $this->db->num_rows($resql) > 0) {
5461 // Last seen cycle
5462 $ref = 0;
5463 while ($obj = $this->db->fetch_object($resql)) {
5464 //Same cycle ?
5465 if ($obj->situation_cycle_ref != $ref) {
5466 // Just seen this cycle
5467 $ref = $obj->situation_cycle_ref;
5468 //not final ?
5469 if ($obj->situation_final != 1) {
5470 //Not prov?
5471 if (substr($obj->ref, 1, 4) != 'PROV') {
5472 $nbSituationInvoiceForThirdparty++;
5473
5474 if ($selected == $obj->rowid) {
5475 $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
5476 } else {
5477 $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
5478 }
5479 }
5480 }
5481 }
5482 }
5483 } else {
5484 dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
5485 }
5486
5487 if ($nbSituationInvoiceForThirdparty > 0) {
5488 $opt = '<option class="minwidth100" value="" selected>&nbsp;</option>'.$opt;
5489 } else {
5490 $opt = '<option class="minwidth100" value="-1" selected>'.$langs->trans('NoSituations').'</option>';
5491 }
5492
5493 return $opt;
5494 }
5495
5505 public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
5506 {
5507 global $langs;
5508
5509 $langs->load('products');
5510
5511 $return = '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
5512
5513 $sql = "SELECT rowid, label, code FROM " . $this->db->prefix() . "c_units";
5514 $sql .= ' WHERE active > 0';
5515 if (!empty($unit_type)) {
5516 $sql .= " AND unit_type = '" . $this->db->escape($unit_type) . "'";
5517 }
5518 $sql .= " ORDER BY sortorder";
5519
5520 $resql = $this->db->query($sql);
5521 if ($resql && $this->db->num_rows($resql) > 0) {
5522 if ($showempty) {
5523 $return .= '<option value="-1"></option>';
5524 }
5525
5526 while ($res = $this->db->fetch_object($resql)) {
5527 $unitLabel = $res->label;
5528 if (!empty($langs->tab_translate['unit' . $res->code])) { // check if Translation is available before
5529 $unitLabel = $langs->trans('unit' . $res->code) != $res->label ? $langs->trans('unit' . $res->code) : $res->label;
5530 }
5531
5532 if ($selected == $res->rowid) {
5533 $return .= '<option value="' . $res->rowid . '" selected>' . $unitLabel . '</option>';
5534 } else {
5535 $return .= '<option value="' . $res->rowid . '">' . $unitLabel . '</option>';
5536 }
5537 }
5538 $return .= '</select>';
5539
5540 $return .= ajax_combobox($htmlname);
5541 }
5542 return $return;
5543 }
5544
5545 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5546
5562 public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0, $addentrynone = 0)
5563 {
5564 // phpcs:enable
5565 global $langs;
5566
5567 $out = '';
5568
5569 $langs->loadLangs(array("admin", "banks"));
5570 $num = 0;
5571
5572 $sql = "SELECT rowid, label, bank, clos as status, currency_code";
5573 $sql .= " FROM " . $this->db->prefix() . "bank_account";
5574 $sql .= " WHERE entity IN (" . getEntity('bank_account') . ")";
5575 if ($status != 2) {
5576 $sql .= " AND clos = " . (int) $status;
5577 }
5578 if ($filtre) { // TODO Support USF
5579 $sql .= " AND " . $filtre;
5580 }
5581 $sql .= " ORDER BY label";
5582
5583 dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
5584 $result = $this->db->query($sql);
5585 if ($result) {
5586 $num = $this->db->num_rows($result);
5587 $i = 0;
5588
5589 $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
5590
5591 if ($num == 0) {
5592 if ($status == 0) {
5593 $out .= '<option class="opacitymedium" value="-1">' . $langs->trans("NoActiveBankAccountDefined") . '</span>';
5594 } else {
5595 $out .= '<option class="opacitymedium" value="-1">' . $langs->trans("NoBankAccountDefined") . '</span>';
5596 }
5597 } else {
5598 if (!empty($useempty) && !is_numeric($useempty)) {
5599 $out .= '<option value="-1">'.$langs->trans($useempty).'</option>';
5600 } elseif ($useempty == 1 || ($useempty == 2 && $num > 1)) {
5601 $out .= '<option value="-1">&nbsp;</option>';
5602 }
5603 }
5604
5605 while ($i < $num) {
5606 $obj = $this->db->fetch_object($result);
5607
5608 $labeltoshow = trim($obj->label);
5609 $labeltoshowhtml = trim($obj->label);
5610 if ($showcurrency) {
5611 $labeltoshow .= ' (' . $obj->currency_code . ')';
5612 $labeltoshowhtml .= ' <span class="opacitymedium">(' . $obj->currency_code . ')</span>';
5613 }
5614 if ($status == 2 && $obj->status == 1) {
5615 $labeltoshow .= ' (' . $langs->trans("Closed") . ')';
5616 $labeltoshowhtml .= ' <span class="opacitymedium">(' . $langs->trans("Closed") . ')</span>';
5617 }
5618
5619 if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
5620 $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml).'" selected>';
5621 } else {
5622 $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" data-html="'.dolPrintHTMLForAttribute($labeltoshowhtml).'">';
5623 }
5624 $out .= $labeltoshow;
5625 $out .= '</option>';
5626 $i++;
5627 }
5628
5629 if (!empty($addentrynone)) {
5630 $out .= '<option value="-2"'.($selected == -2 ? ' selected="selected"': '').' data-html="'.dolPrintHTMLForAttribute('<span class="opacitymedium">'.$langs->trans("None").'</span>').'">'.$langs->trans("None").'</option>';
5631 }
5632
5633 $out .= "</select>";
5634 $out .= ajax_combobox('select' . $htmlname);
5635 } else {
5636 dol_print_error($this->db);
5637 }
5638
5639 // Output or return
5640 if (empty($nooutput)) {
5641 print $out;
5642 } else {
5643 return $out;
5644 }
5645
5646 return $num;
5647 }
5648
5662 public function selectRib($selected = '', $htmlname = 'ribcompanyid', $filtre = '', $useempty = 0, $moreattrib = '', $showibanbic = 0, $morecss = '', $nooutput = 0)
5663 {
5664 // phpcs:enable
5665 global $langs;
5666
5667 $out = '';
5668
5669 $langs->loadLangs(array("admin", "banks"));
5670 $num = 0;
5671
5672 $sql = "SELECT rowid, label, bank, status, iban_prefix, bic";
5673 $sql .= " FROM " . $this->db->prefix() . "societe_rib";
5674 $sql .= " WHERE type = 'ban'";
5675 if ($filtre) { // TODO Support USF
5676 $sql .= " AND " . $filtre;
5677 }
5678 $sql .= " ORDER BY label";
5679 dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
5680 $result = $this->db->query($sql);
5681 if ($result) {
5682 $num = $this->db->num_rows($result);
5683 $i = 0;
5684
5685 $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
5686
5687 if ($num == 0) {
5688 $out .= '<option class="opacitymedium" value="-1">' . $langs->trans("NoBankAccountDefined") . '</span>';
5689 } else {
5690 if (!empty($useempty) && !is_numeric($useempty)) {
5691 $out .= '<option value="-1">'.$langs->trans($useempty).'</option>';
5692 } elseif ($useempty == 1 || ($useempty == 2 && $num > 1)) {
5693 $out .= '<option value="-1">&nbsp;</option>';
5694 }
5695 }
5696
5697 while ($i < $num) {
5698 $obj = $this->db->fetch_object($result);
5699 $iban = dolDecrypt($obj->iban_prefix);
5700 if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
5701 $out .= '<option value="' . $obj->rowid . '" data-iban-prefix="' . $iban . ' data-bic="' . $obj->bic . '" selected>';
5702 } else {
5703 $out .= '<option value="' . $obj->rowid . '" data-iban-prefix="' . $iban . ' data-bic="' . $obj->bic . '">';
5704 }
5705 $out .= trim($obj->label);
5706 if ($showibanbic) {
5707 $out .= ' (' . $iban . '/' .$obj->bic. ')';
5708 }
5709 $out .= '</option>';
5710 $i++;
5711 }
5712 $out .= "</select>";
5713 $out .= ajax_combobox('select' . $htmlname);
5714 } else {
5715 dol_print_error($this->db);
5716 }
5717
5718 // Output or return
5719 if (empty($nooutput)) {
5720 print $out;
5721 } else {
5722 return $out;
5723 }
5724
5725 return $num;
5726 }
5727
5739 public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
5740 {
5741 global $langs;
5742
5743 $langs->load("admin");
5744 $num = 0;
5745
5746 $sql = "SELECT rowid, name, fk_country, status, entity";
5747 $sql .= " FROM " . $this->db->prefix() . "establishment";
5748 $sql .= " WHERE 1=1";
5749 if ($status != 2) {
5750 $sql .= " AND status = " . (int) $status;
5751 }
5752 if ($filtre) { // TODO Support USF
5753 $sql .= " AND " . $filtre;
5754 }
5755 $sql .= " ORDER BY name";
5756
5757 dol_syslog(get_class($this) . "::select_establishment", LOG_DEBUG);
5758 $result = $this->db->query($sql);
5759 if ($result) {
5760 $num = $this->db->num_rows($result);
5761 $i = 0;
5762 if ($num) {
5763 print '<select id="select' . $htmlname . '" class="flat selectestablishment" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
5764 if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
5765 print '<option value="-1">&nbsp;</option>';
5766 }
5767
5768 while ($i < $num) {
5769 $obj = $this->db->fetch_object($result);
5770 if ($selected == $obj->rowid) {
5771 print '<option value="' . $obj->rowid . '" selected>';
5772 } else {
5773 print '<option value="' . $obj->rowid . '">';
5774 }
5775 print trim($obj->name);
5776 if ($status == 2 && $obj->status == 1) {
5777 print ' (' . $langs->trans("Closed") . ')';
5778 }
5779 print '</option>';
5780 $i++;
5781 }
5782 print "</select>";
5783 } else {
5784 if ($status == 0) {
5785 print '<span class="opacitymedium">' . $langs->trans("NoActiveEstablishmentDefined") . '</span>';
5786 } else {
5787 print '<span class="opacitymedium">' . $langs->trans("NoEstablishmentFound") . '</span>';
5788 }
5789 }
5790
5791 return $num;
5792 } else {
5793 dol_print_error($this->db);
5794 return -1;
5795 }
5796 }
5797
5807 public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
5808 {
5809 global $langs;
5810 if ($htmlname != "none") {
5811 print '<form method="POST" action="' . $page . '">';
5812 print '<input type="hidden" name="action" value="setbankaccount">';
5813 print '<input type="hidden" name="token" value="' . newToken() . '">';
5814 print img_picto('', 'bank_account', 'class="pictofixedwidth"');
5815 $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
5816 if ($nbaccountfound > 0) {
5817 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
5818 }
5819 print '</form>';
5820 } else {
5821 $langs->load('banks');
5822
5823 if ($selected) {
5824 require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
5825 $bankstatic = new Account($this->db);
5826 $result = $bankstatic->fetch((int) $selected);
5827 if ($result) {
5828 print $bankstatic->getNomUrl(1);
5829 }
5830 } else {
5831 print "&nbsp;";
5832 }
5833 }
5834 }
5835
5847 public function formRib($page, $selected = '', $htmlname = 'ribcompanyid', $filtre = '', $addempty = 0, $showibanbic = 0)
5848 {
5849 global $langs;
5850 if ($htmlname != "none") {
5851 print '<form method="POST" action="' . $page . '">';
5852 print '<input type="hidden" name="action" value="setbankaccountcustomer">';
5853 print '<input type="hidden" name="token" value="' . newToken() . '">';
5854 $nbaccountfound = $this->selectRib($selected, $htmlname, $filtre, $addempty, '', $showibanbic);
5855 if ($nbaccountfound > 0) {
5856 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
5857 }
5858 print '</form>';
5859 } else {
5860 $langs->load('banks');
5861
5862 if ($selected) {
5863 require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
5864 $bankstatic = new CompanyBankAccount($this->db);
5865 $result = $bankstatic->fetch((int) $selected);
5866 if ($result) {
5867 print $bankstatic->label;
5868 if ($showibanbic) {
5869 print ' (' . $bankstatic->iban . '/' .$bankstatic->bic. ')';
5870 }
5871 }
5872 } else {
5873 print "&nbsp;";
5874 }
5875 }
5876 }
5877
5887 public function selectCategories($categtype, $htmlname, $object = null)
5888 {
5889 global $langs;
5890
5891 $out = '';
5892
5893 $cate_arbo = $this->select_all_categories($categtype, '', '', 64, 0, 3);
5894
5895 $arrayselected = array();
5896 if (GETPOSTISARRAY($htmlname)) {
5897 $arrayselected = GETPOST($htmlname, 'array:int');
5898 } elseif (is_object($object) && $object->id > 0) {
5899 $c = new Categorie($this->db);
5900 $cats = $c->containing($object->id, $categtype);
5901 $arrayselected = array();
5902 foreach ($cats as $cat) {
5903 $arrayselected[] = $cat->id;
5904 }
5905 }
5906
5907 $out .= img_picto('', 'category', 'class="pictofixedwidth"');
5908 $out .= $this->multiselectarray($htmlname, $cate_arbo, $arrayselected, 0, 0, 'minwidth100 widthcentpercentminusxx', 0, 0);
5909
5910 if (!getDolGlobalString('CATEGORY_EDIT_IN_MENU_NOT_IN_POPUP')) {
5911 // Add html code to add the edit button and go back
5912 $jsonclose = 'doJsCodeAfterPopupClose'.$htmlname.'()';
5913 $urltoopen = '/categories/categorie_list.php?type='.urlencode($categtype).'&nosearch=1';
5914
5915 $s = dolButtonToOpenUrlInDialogPopup($htmlname, $langs->transnoentitiesnoconv("Categories"), img_picto('', 'add', 'class="editfielda"'), $urltoopen, '', '', '', $jsonclose);
5916 $out .= $s;
5917 // Add js code to add the edit button and go back
5918 $out .= '<!-- Add js code to open the popup for category/edit/add -->'."\n";
5919 $out .= '<script>function doJsCodeAfterPopupClose'.$htmlname.'() {
5920 console.log("doJsCodeAfterPopupClose'.$htmlname.' has been called, we refresh the combo content + refresh select2...");
5921
5922 // Call an ajax to reload values and update the select
5923 // $("#'.dol_escape_js($htmlname).'").append(new Option("Option 4", "4"));
5924
5925 // Refresh select2 to take account of new values (enough for small change)
5926
5927 $.ajax({
5928 url: \''.DOL_URL_ROOT.'/core/ajax/fetchCategories.php\',
5929 data: {
5930 action: \'getCategories\',
5931 type: \''.dol_escape_htmltag($categtype).'\'
5932 },
5933 type: \'GET\',
5934 dataType: \'json\',
5935 success: function (data) {
5936 var $select = $(\'#'.dol_escape_js($htmlname).'\');
5937 var selectedValues = $select.val(); // This is an array of selected values
5938 console.log(selectedValues);
5939 $select.empty();
5940 $.each(data, function (index, item) {
5941 $select.append(\'<option value="\' + item.id + \'" data-html="\' + item.htmlforattribute + \'">\' + item.htmlforoption + \'</option>\');
5942 });
5943 $select.val(selectedValues);
5944 },
5945 error: function (xhr, status, error) {
5946 console.log("Error when loading ajax page : " + error);
5947 }
5948 });
5949
5950 $("#'.dol_escape_js($htmlname).'").trigger("change");
5951 // Alternative if change in select is complex
5952 /*
5953 $("#'.dol_escape_js($htmlname).'").select2("destroy");
5954 $("#'.dol_escape_js($htmlname).'").select2();
5955 */
5956 }</script>';
5957 }
5958
5959 return $out;
5960 }
5961
5962
5963 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
5983 public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $fromid = 0, $outputmode = 0, $include = 0, $morecss = '', $useempty = 1)
5984 {
5985 // phpcs:enable
5986 global $langs;
5987
5988 include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
5989
5990 $cat = new Categorie($this->db);
5991
5992 if (is_numeric($type)) {
5993 $type = array_search($type, $cat->MAP_ID); // For backward compatibility
5994 }
5995
5996 $cate_arbo = $cat->get_full_arbo($type, $fromid, $include);
5997
5998 $outarray = array();
5999 $outarrayrichhtml = array();
6000
6001
6002 $output = '<select class="flat minwidth100' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
6003 $num = 0;
6004 if (is_array($cate_arbo)) {
6005 $num = count($cate_arbo);
6006
6007 if (!$num) {
6008 $langs->load("categories");
6009 $output .= '<option value="-1" disabled>' . $langs->trans("NoCategoriesDefined") . '</option>';
6010 } else {
6011 if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
6012 $output .= '<option value="-1">&nbsp;</option>';
6013 }
6014 foreach ($cate_arbo as $key => $value) {
6015 if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
6016 $add = 'selected ';
6017 } else {
6018 $add = '';
6019 }
6020
6021 $labeltoshow = img_picto('', 'category', 'class="pictofixedwidth"'.(empty($cate_arbo[$key]['color']) ? '' : ' style="color: #' . $cate_arbo[$key]['color'] . '"'));
6022 $labeltoshow .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
6023
6024 $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
6025
6026 $outarrayrichhtml[$cate_arbo[$key]['id']] = $labeltoshow;
6027
6028 $output .= '<option ' . $add . 'value="' . $cate_arbo[$key]['id'] . '"';
6029 $output .= ' data-html="' . dol_escape_htmltag($labeltoshow) . '"';
6030 $output .= '>';
6031 $output .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
6032 $output .= '</option>';
6033
6034 $cate_arbo[$key]['data-html'] = $labeltoshow;
6035 }
6036 }
6037 }
6038 $output .= '</select>';
6039 $output .= "\n";
6040
6041 $this->num = $num;
6042
6043 if ($outputmode == 2) {
6044 // TODO: handle error when $cate_arbo is not an array
6045 return $cate_arbo;
6046 } elseif ($outputmode == 1) {
6047 return $outarray;
6048 } elseif ($outputmode == 3) {
6049 return $outarrayrichhtml;
6050 }
6051 return $output;
6052 }
6053
6054 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6055
6074 public function form_confirm($page, $title, $question, $action, $formquestion = array(), $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
6075 {
6076 // phpcs:enable
6077 dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
6078 print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
6079 }
6080
6107 public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
6108 {
6109 global $langs, $conf;
6110
6111 $more = '';
6112 $formconfirm = '<!-- formconfirm - before call, page=' . dol_escape_htmltag($page) . ' -->';
6113
6114 $inputok = array();
6115 $inputko = array();
6116
6117 // Clean parameters
6118 $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
6119 if ($conf->browser->layout == 'phone') {
6120 $width = '95%';
6121 }
6122
6123 // Set height automatically if not defined
6124 if (empty($height)) {
6125 $height = 250;
6126 if (is_array($formquestion) && count($formquestion) > 2) {
6127 $height += ((count($formquestion) - 2) * 24) + 5;
6128 }
6129 }
6130
6131 if (is_array($formquestion) && !empty($formquestion)) {
6132 // First add hidden fields and value
6133 foreach ($formquestion as $key => $input) {
6134 if (is_array($input) && !empty($input)) {
6135 if ($input['type'] == 'hidden') {
6136 $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
6137 $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
6138
6139 $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
6140 }
6141 }
6142 }
6143
6144 // Now add questions
6145 $moreonecolumn = '';
6146 $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">' . "\n";
6147 foreach ($formquestion as $key => $input) {
6148 if (is_array($input) && !empty($input)) {
6149 $size = (!empty($input['size']) ? ' size="' . $input['size'] . '"' : ''); // deprecated. Use morecss instead.
6150 $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
6151 $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
6152
6153 if ($input['type'] == 'text' || $input['type'] == 'input') { // traditional input
6154 $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";
6155 } elseif ($input['type'] == 'password') {
6156 $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";
6157 } elseif ($input['type'] == 'textarea') {
6158 $moreonecolumn .= '<div class="margintoponly">';
6159 $moreonecolumn .= $input['label'] . '<br>';
6160 $moreonecolumn .= '<textarea name="' . dol_escape_htmltag($input['name']) . '" id="' . dol_escape_htmltag($input['name']) . '" class="' . $morecss . '"' . $moreattr . '>';
6161 $moreonecolumn .= $input['value'];
6162 $moreonecolumn .= '</textarea>';
6163 $moreonecolumn .= '</div>';
6164 } elseif (in_array($input['type'], ['select', 'multiselect'])) {
6165 if (empty($morecss)) {
6166 $morecss = 'minwidth100';
6167 }
6168
6169 $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
6170 $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
6171 $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
6172 $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
6173 $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
6174 $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
6175 $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
6176
6177 $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">';
6178 if (!empty($input['label'])) {
6179 $more .= $input['label'] . '</div><div class="tagtd left">';
6180 }
6181 if ($input['type'] == 'select') {
6182 $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);
6183 } else {
6184 $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);
6185 }
6186 $more .= '</div></div>' . "\n";
6187 } elseif ($input['type'] == 'checkbox') {
6188 $more .= '<div class="tagtr">';
6189 $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '"><label for="' . dol_escape_htmltag($input['name']) . '">' . $input['label'] . '</label></div><div class="tagtd">';
6190 $more .= '<input type="checkbox" class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $moreattr;
6191 if (isset($input['value']) && !is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
6192 $more .= ' checked';
6193 }
6194 if (isset($input['value']) && is_bool($input['value']) && $input['value']) {
6195 $more .= ' checked';
6196 }
6197 if (isset($input['disabled'])) {
6198 $more .= ' disabled';
6199 }
6200 $more .= ' /></div>';
6201 $more .= '</div>' . "\n";
6202 } elseif ($input['type'] == 'radio') {
6203 $i = 0;
6204 foreach ($input['values'] as $selkey => $selval) {
6205 $more .= '<div class="tagtr">';
6206 if (isset($input['label'])) {
6207 if ($i == 0) {
6208 $more .= '<div class="tagtd' . (empty($input['tdclass']) ? ' tdtop' : (' tdtop ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
6209 } else {
6210 $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' "' . $input['tdclass'])) . '">&nbsp;</div>';
6211 }
6212 }
6213 $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;
6214 if (!empty($input['disabled'])) {
6215 $more .= ' disabled';
6216 }
6217 if (isset($input['default']) && $input['default'] === $selkey) {
6218 $more .= ' checked="checked"';
6219 }
6220 $more .= ' /> ';
6221 $more .= '<label for="' . dol_escape_htmltag($input['name'] . $selkey) . '" class="valignmiddle">' . $selval . '</label>';
6222 $more .= '</div></div>' . "\n";
6223 $i++;
6224 }
6225 } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
6226 $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
6227 $more .= '<div class="tagtd">';
6228 $addnowlink = (empty($input['datenow']) ? 0 : 1);
6229 $h = $m = 0;
6230 if ($input['type'] == 'datetime') {
6231 $h = isset($input['hours']) ? $input['hours'] : 1;
6232 $m = isset($input['minutes']) ? $input['minutes'] : 1;
6233 }
6234 $more .= $this->selectDate(isset($input['value']) ? $input['value'] : -1, $input['name'], $h, $m, 0, '', 1, $addnowlink);
6235 $more .= '</div></div>'."\n";
6236 $formquestion[] = array('name' => $input['name'].'day');
6237 $formquestion[] = array('name' => $input['name'].'month');
6238 $formquestion[] = array('name' => $input['name'].'year');
6239 $formquestion[] = array('name' => $input['name'].'hour');
6240 $formquestion[] = array('name' => $input['name'].'min');
6241 } elseif ($input['type'] == 'other') { // can be 1 column or 2 depending if label is set or not
6242 $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
6243 if (!empty($input['label'])) {
6244 $more .= $input['label'] . '</div><div class="tagtd">';
6245 }
6246 if (!empty($input['value'])) {
6247 $more .= $input['value'];
6248 }
6249 $more .= '</div></div>' . "\n";
6250 } elseif ($input['type'] == 'onecolumn') {
6251 $moreonecolumn .= '<div class="margintoponly">';
6252 $moreonecolumn .= $input['value'];
6253 $moreonecolumn .= '</div>' . "\n";
6254 } elseif ($input['type'] == 'hidden') {
6255 // Do nothing more, already added by a previous loop
6256 } elseif ($input['type'] == 'separator') {
6257 $more .= '<br>';
6258 } else {
6259 $more .= 'Error type ' . $input['type'] . ' for the confirm box is not a supported type';
6260 }
6261 }
6262 }
6263 $more .= '</div>' . "\n";
6264 $more .= $moreonecolumn;
6265 }
6266
6267 // JQUERY method dialog is broken with smartphone, we use standard HTML.
6268 // 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
6269 // See page product/card.php for example
6270 if (!empty($conf->dol_use_jmobile)) {
6271 $useajax = 0;
6272 }
6273 if (empty($conf->use_javascript_ajax)) {
6274 $useajax = 0;
6275 }
6276
6277 if ($useajax) {
6278 $autoOpen = true;
6279 $dialogconfirm = 'dialog-confirm';
6280 $button = '';
6281 if (!is_numeric($useajax)) {
6282 $button = $useajax;
6283 $useajax = 1;
6284 $autoOpen = false;
6285 $dialogconfirm .= '-' . $button;
6286 }
6287 $pageyes = $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=yes';
6288 $pageno = ($useajax == 2 ? $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=no' : '');
6289
6290 // Add input fields into list of fields to read during submit (inputok and inputko)
6291 if (is_array($formquestion)) {
6292 foreach ($formquestion as $key => $input) {
6293 //print "xx ".$key." rr ".is_array($input)."<br>\n";
6294 // Add name of fields to propagate with the GET when submitting the form with button OK.
6295 if (is_array($input) && isset($input['name'])) {
6296 if (strpos($input['name'], ',') > 0) {
6297 $inputok = array_merge($inputok, explode(',', $input['name']));
6298 } else {
6299 array_push($inputok, $input['name']);
6300 }
6301 }
6302 // Add name of fields to propagate with the GET when submitting the form with button KO.
6303 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
6304 if (is_array($input) && isset($input['inputko']) && $input['inputko'] == 1 && isset($input['name'])) {
6305 array_push($inputko, $input['name']);
6306 }
6307 }
6308 }
6309
6310 // Show JQuery confirm box.
6311 $formconfirm .= '<div id="' . $dialogconfirm . '" title="' . dol_escape_htmltag($title) . '" style="display: none;">';
6312 if (is_array($formquestion) && array_key_exists('text', $formquestion) && !empty($formquestion['text'])) {
6313 $formconfirm .= '<div class="confirmtext">' . $formquestion['text'] . '</div>' . "\n";
6314 }
6315 if (!empty($more)) {
6316 $formconfirm .= '<div class="confirmquestions">' . $more . '</div>' . "\n";
6317 }
6318 $formconfirm .= ($question ? '<div class="confirmmessage">' . img_help(0, '') . ' ' . $question . '</div>' : '');
6319 $formconfirm .= '</div>' . "\n";
6320
6321 $formconfirm .= "\n<!-- begin code of popup for formconfirm page=" . $page . " -->\n";
6322 $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
6323 $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
6324 $formconfirm .= 'jQuery(document).ready(function() {
6325 $(function() {
6326 $( "#' . $dialogconfirm . '" ).dialog({
6327 autoOpen: ' . ($autoOpen ? "true" : "false") . ',';
6328 if ($newselectedchoice == 'no') {
6329 $formconfirm .= '
6330 open: function() {
6331 $(this).parent().find("button.ui-button:eq(2)").focus();
6332 },';
6333 }
6334
6335 $jsforcursor = '';
6336 if ($useajax == 1) {
6337 $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor' . "\n";
6338 $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");' . "\n";
6339 }
6340
6341 $postconfirmas = 'GET';
6342
6343 $formconfirm .= '
6344 resizable: false,
6345 height: \'' . dol_escape_js($height) . '\',
6346 width: \'' . dol_escape_js($width) . '\',
6347 modal: true,
6348 closeOnEscape: false,
6349 buttons: {
6350 "' . dol_escape_js($langs->transnoentities($labelbuttonyes)) . '": function() {
6351 var options = "token=' . urlencode(newToken()) . '";
6352 var inputok = ' . json_encode($inputok) . '; /* List of fields into form */
6353 var page = \'' . dol_escape_js(!empty($page) ? $page : '') . '\';
6354 var pageyes = \'' . dol_escape_js(!empty($pageyes) ? $pageyes : '') . '\';
6355
6356 if (inputok.length > 0) {
6357 $.each(inputok, function(i, inputname) {
6358 var more = "";
6359 var inputvalue;
6360 if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
6361 inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
6362 } else {
6363 if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
6364 inputvalue = $("#" + inputname + more).val();
6365 }
6366 if (typeof inputvalue == "undefined") { inputvalue=""; }
6367 console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
6368 options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
6369 });
6370 }
6371 var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
6372 if (pageyes.length > 0) {';
6373 if ($postconfirmas == 'GET') {
6374 $formconfirm .= 'location.href = urljump;';
6375 } else {
6376 $formconfirm .= $jsforcursor;
6377 $formconfirm .= 'var post = $.post(
6378 pageyes,
6379 options,
6380 function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
6381 );';
6382 }
6383 $formconfirm .= '
6384 console.log("after post ok");
6385 }
6386 $(this).dialog("close");
6387 },
6388 "' . dol_escape_js($langs->transnoentities($labelbuttonno)) . '": function() {
6389 var options = "token=' . urlencode(newToken()) . '";
6390 var inputko = ' . json_encode($inputko) . '; /* List of fields into form */
6391 var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
6392 var pageno="' . dol_escape_js(!empty($pageno) ? $pageno : '') . '";
6393 if (inputko.length > 0) {
6394 $.each(inputko, function(i, inputname) {
6395 var more = "";
6396 if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
6397 var inputvalue = $("#" + inputname + more).val();
6398 if (typeof inputvalue == "undefined") { inputvalue=""; }
6399 options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
6400 });
6401 }
6402 var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
6403 //alert(urljump);
6404 if (pageno.length > 0) {';
6405 if ($postconfirmas == 'GET') {
6406 $formconfirm .= 'location.href = urljump;';
6407 } else {
6408 $formconfirm .= $jsforcursor;
6409 $formconfirm .= 'var post = $.post(
6410 pageno,
6411 options,
6412 function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
6413 );';
6414 }
6415 $formconfirm .= '
6416 console.log("after post ko");
6417 }
6418 $(this).dialog("close");
6419 }
6420 }
6421 }
6422 );
6423
6424 var button = "' . $button . '";
6425 if (button.length > 0) {
6426 $( "#" + button ).click(function() {
6427 $("#' . $dialogconfirm . '").dialog("open");
6428 });
6429 }
6430 });
6431 });
6432 </script>';
6433 $formconfirm .= "<!-- end ajax formconfirm -->\n";
6434 } else {
6435 $formconfirm .= "\n<!-- begin formconfirm page=" . dol_escape_htmltag($page) . " -->\n";
6436
6437 if (empty($disableformtag)) {
6438 $formconfirm .= '<form method="POST" action="' . $page . '" class="notoptoleftnoright">' . "\n";
6439 }
6440
6441 $formconfirm .= '<input type="hidden" name="action" value="' . $action . '">' . "\n";
6442 $formconfirm .= '<input type="hidden" name="token" value="' . newToken() . '">' . "\n";
6443
6444 $formconfirm .= '<table class="valid centpercent">' . "\n";
6445
6446 // Line title
6447 $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
6448 $formconfirm .= img_picto('', 'pictoconfirm') . ' ' . $title;
6449 $formconfirm .= '</td></tr>' . "\n";
6450
6451 // Line text
6452 if (is_array($formquestion) && array_key_exists('text', $formquestion) && !empty($formquestion['text'])) {
6453 $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . $formquestion['text'] . '</td></tr>' . "\n";
6454 }
6455
6456 // Line form fields
6457 if ($more) {
6458 $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . "\n";
6459 $formconfirm .= $more;
6460 $formconfirm .= '</td></tr>' . "\n";
6461 }
6462
6463 // Line with question
6464 $formconfirm .= '<tr class="valid">';
6465 $formconfirm .= '<td class="valid">' . $question . '</td>';
6466 $formconfirm .= '<td class="valid center">';
6467 $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
6468 $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="' . $langs->trans("Validate") . '">';
6469 $formconfirm .= '</td>';
6470 $formconfirm .= '</tr>' . "\n";
6471
6472 $formconfirm .= '</table>' . "\n";
6473
6474 if (empty($disableformtag)) {
6475 $formconfirm .= "</form>\n";
6476 }
6477 $formconfirm .= '<br>';
6478
6479 if (!empty($conf->use_javascript_ajax)) {
6480 $formconfirm .= '<!-- code to disable button to avoid double clic -->';
6481 $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
6482 $formconfirm .= '
6483 $(document).ready(function () {
6484 $(".confirmvalidatebutton").on("click", function() {
6485 console.log("We click on button confirmvalidatebutton");
6486 $(this).attr("disabled", "disabled");
6487 setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
6488 //console.log($(this).closest("form"));
6489 $(this).closest("form").submit();
6490 });
6491 });
6492 ';
6493 $formconfirm .= '</script>' . "\n";
6494 }
6495
6496 $formconfirm .= "<!-- end formconfirm -->\n";
6497 }
6498
6499 return $formconfirm;
6500 }
6501
6502
6503 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6504
6520 public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '')
6521 {
6522 // phpcs:enable
6523 global $langs;
6524
6525 require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
6526 require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
6527
6528 $out = '';
6529
6530 $formproject = new FormProjets($this->db);
6531
6532 $langs->load("project");
6533 if ($htmlname != "none") {
6534 $out .= '<form method="post" action="' . $page . '">';
6535 $out .= '<input type="hidden" name="action" value="classin">';
6536 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
6537 $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
6538 $out .= '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
6539 $out .= '</form>';
6540 } else {
6541 $out .= '<span class="project_head_block">';
6542 if ($selected instanceof Project) {
6543 $out .= $selected->getNomUrl(0, '', 1);
6544 } elseif (is_numeric($selected)) {
6545 $projet = new Project($this->db);
6546 $projet->fetch((int) $selected);
6547 $out .= $projet->getNomUrl(0, '', 1);
6548 } else {
6549 $out .= '<span class="opacitymedium">' . $textifnoproject . '</span>';
6550 }
6551 $out .= '</span>';
6552 }
6553
6554 if (empty($nooutput)) {
6555 print $out;
6556 return '';
6557 }
6558 return $out;
6559 }
6560
6561 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6562
6578 public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
6579 {
6580 // phpcs:enable
6581 global $langs;
6582
6583 $out = '';
6584
6585 if ($htmlname != "none") {
6586 $out .= '<form method="POST" action="' . $page . '">';
6587 $out .= '<input type="hidden" name="action" value="setconditions">';
6588 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
6589 if ($type) {
6590 $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
6591 }
6592 $out .= $this->getSelectConditionsPaiements((int) $selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
6593 $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
6594 $out .= '</form>';
6595 } else {
6596 if ($selected) {
6597 $this->load_cache_conditions_paiements();
6598 if (isset($this->cache_conditions_paiements[$selected])) {
6599 $label = $this->cache_conditions_paiements[$selected]['label'];
6600
6601 if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
6602 $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
6603 }
6604
6605 $out .= $label;
6606 } else {
6607 $langs->load('errors');
6608 $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions');
6609 }
6610 } else {
6611 $out .= '&nbsp;';
6612 }
6613 }
6614
6615 if (empty($nooutput)) {
6616 print $out;
6617 return '';
6618 }
6619 return $out;
6620 }
6621
6622 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6623
6634 public function form_rule_for_lines_dates($page, $selected = '', $htmlname = 'rule_for_lines_dates', $addempty = 0, $nooutput = 0): string
6635 {
6636 // phpcs:enable
6637 global $langs;
6638
6639 $out = '';
6640
6641 if ($htmlname != 'none') {
6642 $out .= '<form method="POST" action="' . $page . '">';
6643 $out .= '<input type="hidden" name="action" value="setruleforlinesdates">';
6644 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
6645 $out .= $this->getSelectRuleForLinesDates($selected, $htmlname, $addempty);
6646 $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
6647 $out .= '</form>';
6648 } else {
6649 if (isset($selected)) {
6650 $this->load_cache_rule_for_lines_dates();
6651 if (isset($this->cache_rule_for_lines_dates[$selected])) {
6652 $label = $this->cache_rule_for_lines_dates[$selected];
6653 $out .= $langs->trans($label);
6654 }
6655 } else {
6656 $out .= '&nbsp;';
6657 }
6658 }
6659
6660 if (empty($nooutput)) {
6661 print $out;
6662 return '';
6663 }
6664
6665 return $out;
6666 }
6667
6668 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6669
6679 public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
6680 {
6681 // phpcs:enable
6682 global $langs;
6683 if ($htmlname != "none") {
6684 print '<form method="post" action="' . $page . '">';
6685 print '<input type="hidden" name="action" value="setavailability">';
6686 print '<input type="hidden" name="token" value="' . newToken() . '">';
6687 $this->selectAvailabilityDelay($selected, $htmlname, '', $addempty);
6688 print '<input type="submit" name="modify" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
6689 print '<input type="submit" name="cancel" class="button smallpaddingimp" value="' . $langs->trans("Cancel") . '">';
6690 print '</form>';
6691 } else {
6692 if ($selected) {
6693 $this->load_cache_availability();
6694 if (isset($this->cache_availability[$selected])) {
6695 print $this->cache_availability[$selected]['label'];
6696 } else {
6697 print "&nbsp;";
6698 }
6699 } else {
6700 print "&nbsp;";
6701 }
6702 }
6703 }
6704
6716 public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0, $morecss = '')
6717 {
6718 global $langs;
6719 if ($htmlname != "none") {
6720 print '<form method="post" action="' . $page . '">';
6721 print '<input type="hidden" name="action" value="setdemandreason">';
6722 print '<input type="hidden" name="token" value="' . newToken() . '">';
6723 $this->selectInputReason($selected, $htmlname, '-1', $addempty, $morecss);
6724 print '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
6725 print '</form>';
6726 } else {
6727 if ($selected) {
6728 $this->loadCacheInputReason();
6729 foreach ($this->cache_demand_reason as $key => $val) {
6730 if ($val['id'] == $selected) {
6731 print $val['label'];
6732 break;
6733 }
6734 }
6735 } else {
6736 print "&nbsp;";
6737 }
6738 }
6739 }
6740
6741 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6742
6756 public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
6757 {
6758 // phpcs:enable
6759 global $langs;
6760
6761 $ret = '';
6762
6763 if ($htmlname != "none") {
6764 $ret .= '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
6765 $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
6766 $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
6767 if ($type) {
6768 $ret .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
6769 }
6770 $ret .= '<table class="nobordernopadding">';
6771 $ret .= '<tr><td>';
6772 $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form' . $htmlname, 1, 0);
6773 $ret .= '</td>';
6774 $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
6775 $ret .= '</tr></table></form>';
6776 } else {
6777 if ($displayhour) {
6778 $ret .= dol_print_date($selected, 'dayhour');
6779 } else {
6780 $ret .= dol_print_date($selected, 'day');
6781 }
6782 }
6783
6784 if (empty($nooutput)) {
6785 print $ret;
6786 }
6787 return $ret;
6788 }
6789
6790
6791 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6792
6803 public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = array(), $include = array())
6804 {
6805 // phpcs:enable
6806 global $langs;
6807
6808 if ($htmlname != "none") {
6809 print '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
6810 print '<input type="hidden" name="action" value="set' . $htmlname . '">';
6811 print '<input type="hidden" name="token" value="' . newToken() . '">';
6812 print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
6813 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
6814 print '</form>';
6815 } else {
6816 if ($selected) {
6817 require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
6818 $theuser = new User($this->db);
6819 $theuser->fetch((int) $selected);
6820 print $theuser->getNomUrl(1);
6821 } else {
6822 print "&nbsp;";
6823 }
6824 }
6825 }
6826
6827
6828 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6829
6843 public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
6844 {
6845 // phpcs:enable
6846 global $langs;
6847
6848 $out = '';
6849 if ($htmlname != "none") {
6850 $out .= '<form method="POST" action="' . $page . '">';
6851 $out .= '<input type="hidden" name="action" value="setmode">';
6852 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
6853 if ($type) {
6854 $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
6855 }
6856 $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
6857 $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
6858 $out .= '</form>';
6859 } else {
6860 if ($selected) {
6861 $this->load_cache_types_paiements();
6862 $out .= isset($this->cache_types_paiements[$selected]['label']) ? $this->cache_types_paiements[$selected]['label'] : '';
6863 } else {
6864 $out .= "&nbsp;";
6865 }
6866 }
6867
6868 if ($nooutput) {
6869 return $out;
6870 } else {
6871 print $out;
6872 }
6873 return '';
6874 }
6875
6886 public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
6887 {
6888 global $langs;
6889 if ($htmlname != "none") {
6890 print '<form method="POST" action="' . $page . '">';
6891 print '<input type="hidden" name="action" value="settransportmode">';
6892 print '<input type="hidden" name="token" value="' . newToken() . '">';
6893 $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
6894 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
6895 print '</form>';
6896 } else {
6897 if ($selected) {
6898 $this->load_cache_transport_mode();
6899 print $this->cache_transport_mode[$selected]['label'];
6900 } else {
6901 print "&nbsp;";
6902 }
6903 }
6904 }
6905
6906 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6907
6916 public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
6917 {
6918 // phpcs:enable
6919 global $langs;
6920 if ($htmlname != "none") {
6921 print '<form method="POST" action="' . $page . '">';
6922 print '<input type="hidden" name="action" value="setmulticurrencycode">';
6923 print '<input type="hidden" name="token" value="' . newToken() . '">';
6924 print $this->selectMultiCurrency($selected, $htmlname, 0);
6925 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
6926 print '</form>';
6927 } else {
6928 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
6929 print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
6930 }
6931 }
6932
6933 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6934
6944 public function form_multicurrency_rate($page, $rate = 0.0, $htmlname = 'multicurrency_tx', $currency = '')
6945 {
6946 // phpcs:enable
6947 global $langs, $conf;
6948
6949 if ($htmlname != "none") {
6950 print '<form method="POST" action="' . $page . '">';
6951 print '<input type="hidden" name="action" value="setmulticurrencyrate">';
6952 print '<input type="hidden" name="token" value="' . newToken() . '">';
6953 print '<input type="text" class="maxwidth75" name="' . $htmlname . '" value="' . (!empty($rate) ? price(price2num($rate, 'CU')) : 1) . '" spellcheck="false" /> ';
6954 print '<select name="calculation_mode" id="calculation_mode">';
6955 print '<option value="1">Change ' . $langs->trans("PriceUHT") . ' of lines</option>';
6956 print '<option value="2">Change ' . $langs->trans("PriceUHTCurrency") . ' of lines</option>';
6957 print '</select> ';
6958 print ajax_combobox("calculation_mode");
6959 print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
6960 print '</form>';
6961 } else {
6962 if (!empty($rate)) {
6963 print price($rate, 1, $langs, 0, 0);
6964 if ($currency && $rate != 1) {
6965 print ' &nbsp; <span class="opacitymedium">(' . price($rate, 1, $langs, 0, 0) . ' ' . $currency . ' = 1 ' . $conf->currency . ')</span>';
6966 }
6967 } else {
6968 print 1;
6969 }
6970 }
6971 }
6972
6973 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
6974
6990 public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
6991 {
6992 // phpcs:enable
6993 global $conf, $langs;
6994
6995 if ($htmlname != "none") {
6996 print '<form method="post" action="' . $page . '" class="inline-block">';
6997 print '<input type="hidden" name="action" value="setabsolutediscount">';
6998 print '<input type="hidden" name="token" value="' . newToken() . '">';
6999 print '<div class="inline-block">';
7000 if (!empty($discount_type)) {
7001 if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
7002 if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
7003 $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be subtracted to payments only and not to total of final invoice
7004 } else {
7005 $translationKey = 'HasCreditNoteFromSupplier';
7006 }
7007 } else {
7008 if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
7009 $translationKey = 'HasAbsoluteDiscountFromSupplier';
7010 } else {
7011 $translationKey = 'HasCreditNoteFromSupplier';
7012 }
7013 }
7014 } else {
7015 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
7016 if (!$filter || $filter == "fk_facture_source IS NULL") {
7017 $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be subtracted to payments only and not to total of final invoice
7018 } else {
7019 $translationKey = 'CompanyHasCreditNote';
7020 }
7021 } else {
7022 if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
7023 $translationKey = 'CompanyHasAbsoluteDiscount';
7024 } else {
7025 $translationKey = 'CompanyHasCreditNote';
7026 }
7027 }
7028 }
7029 print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
7030 if (empty($hidelist)) {
7031 print ' ';
7032 }
7033 print '</div>';
7034 if (empty($hidelist)) {
7035 print '<div class="inline-block" style="padding-right: 10px">';
7036 $newfilter = 'discount_type=' . intval($discount_type);
7037 if (!empty($discount_type)) {
7038 $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
7039 } else {
7040 $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
7041 }
7042 if ($filter) {
7043 $newfilter .= ' AND (' . $filter . ')';
7044 }
7045 // output the combo of discounts
7046 $nbqualifiedlines = $this->select_remises((string) $selected, $htmlname, $newfilter, $socid, $maxvalue);
7047 if ($nbqualifiedlines > 0) {
7048 print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("UseLine")) . '"';
7049 if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
7050 print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
7051 }
7052 if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
7053 print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
7054 }
7055
7056 print '>';
7057 }
7058 print '</div>';
7059 }
7060 if ($more) {
7061 print '<div class="inline-block">';
7062 print $more;
7063 print '</div>';
7064 }
7065 print '</form>';
7066 } else {
7067 if ($selected) {
7068 print $selected;
7069 } else {
7070 print "0";
7071 }
7072 }
7073 }
7074
7075
7076 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7077
7087 public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
7088 {
7089 // phpcs:enable
7090 global $langs;
7091
7092 if ($htmlname != "none") {
7093 print '<form method="post" action="' . $page . '">';
7094 print '<input type="hidden" name="action" value="set_contact">';
7095 print '<input type="hidden" name="token" value="' . newToken() . '">';
7096 print '<table class="nobordernopadding">';
7097 print '<tr><td>';
7098 print $this->selectcontacts($societe->id, $selected, $htmlname);
7099 $num = $this->num;
7100 if ($num == 0) {
7101 $addcontact = (getDolGlobalString('SOCIETE_ADDRESSES_MANAGEMENT') ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
7102 print '<a href="' . DOL_URL_ROOT . '/contact/card.php?socid=' . $societe->id . '&action=create&backtoreferer=1">' . $addcontact . '</a>';
7103 }
7104 print '</td>';
7105 print '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
7106 print '</tr></table></form>';
7107 } else {
7108 if ($selected) {
7109 require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
7110 $contact = new Contact($this->db);
7111 $contact->fetch((int) $selected);
7112 print $contact->getFullName($langs);
7113 } else {
7114 print "&nbsp;";
7115 }
7116 }
7117 }
7118
7119 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7120
7137 public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
7138 {
7139 // phpcs:enable
7140 global $langs;
7141
7142 $out = '';
7143 if ($htmlname != "none") {
7144 $out .= '<form method="post" action="' . $page . '">';
7145 $out .= '<input type="hidden" name="action" value="set_thirdparty">';
7146 $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
7147 $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
7148 $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
7149 $out .= '</form>';
7150 } else {
7151 if ($selected) {
7152 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
7153 $soc = new Societe($this->db);
7154 $soc->fetch((int) $selected);
7155 $out .= $soc->getNomUrl(0, '');
7156 } else {
7157 $out .= '<span class="opacitymedium">' . $textifnothirdparty . '</span>';
7158 }
7159 }
7160
7161 if ($nooutput) {
7162 return $out;
7163 } else {
7164 print $out;
7165 }
7166
7167 return '';
7168 }
7169
7170 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7171
7180 public function select_currency($selected = '', $htmlname = 'currency_id')
7181 {
7182 // phpcs:enable
7183 print $this->selectCurrency($selected, $htmlname);
7184 }
7185
7195 public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
7196 {
7197 global $langs, $user;
7198
7199 $langs->loadCacheCurrencies('');
7200
7201 $out = '';
7202
7203 if ($selected == 'euro' || $selected == 'euros') {
7204 $selected = 'EUR'; // Pour compatibilite
7205 }
7206
7207 $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="' . $htmlname . '" id="' . $htmlname . '">';
7208 if ($useempty) {
7209 $out .= '<option value="-1" selected></option>';
7210 }
7211 foreach ($langs->cache_currencies as $code_iso => $currency) {
7212 $labeltoshow = $currency['label'];
7213 if ($mode == 1) {
7214 $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso . ')</span>';
7215 } elseif ($mode == 2) {
7216 $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso.' - '.$langs->getCurrencySymbol($code_iso) . ')</span>';
7217 } else {
7218 $labeltoshow .= ' <span class="opacitymedium">(' . $langs->getCurrencySymbol($code_iso) . ')</span>';
7219 }
7220
7221 if ($selected && $selected == $code_iso) {
7222 $out .= '<option value="' . $code_iso . '" selected data-html="' . dol_escape_htmltag($labeltoshow) . '">';
7223 } else {
7224 $out .= '<option value="' . $code_iso . '" data-html="' . dol_escape_htmltag($labeltoshow) . '">';
7225 }
7226 $out .= dol_string_nohtmltag($labeltoshow);
7227 $out .= '</option>';
7228 }
7229 $out .= '</select>';
7230 if ($user->admin) {
7231 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
7232 }
7233
7234 // Make select dynamic
7235 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
7236 $out .= ajax_combobox($htmlname);
7237
7238 return $out;
7239 }
7240
7253 public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = 'maxwidth200 widthcentpercentminusx')
7254 {
7255 global $conf, $langs;
7256
7257 $langs->loadCacheCurrencies(''); // Load ->cache_currencies
7258
7259 $TCurrency = array();
7260
7261 $sql = "SELECT code FROM " . $this->db->prefix() . "multicurrency";
7262 $sql .= " WHERE entity IN ('" . getEntity('multicurrency') . "')";
7263 if ($filter) {
7264 $sql .= " AND " . $filter;
7265 }
7266 $resql = $this->db->query($sql);
7267 if ($resql) {
7268 while ($obj = $this->db->fetch_object($resql)) {
7269 $TCurrency[$obj->code] = $obj->code;
7270 }
7271 }
7272
7273 $out = '';
7274 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
7275 if ($useempty) {
7276 $out .= '<option value="">&nbsp;</option>';
7277 }
7278 // If company current currency not in table, we add it into list. Should always be available.
7279 if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
7280 $TCurrency[$conf->currency] = $conf->currency;
7281 }
7282 if (count($TCurrency) > 0) {
7283 foreach ($langs->cache_currencies as $code_iso => $currency) {
7284 if (isset($TCurrency[$code_iso])) {
7285 if (!empty($selected) && $selected == $code_iso) {
7286 $out .= '<option value="' . $code_iso . '" selected="selected">';
7287 } else {
7288 $out .= '<option value="' . $code_iso . '">';
7289 }
7290
7291 $out .= $currency['label'];
7292 $out .= ' (' . $langs->getCurrencySymbol($code_iso) . ')';
7293 $out .= '</option>';
7294 }
7295 }
7296 }
7297
7298 $out .= '</select>';
7299
7300 // Make select dynamic
7301 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
7302 $out .= ajax_combobox($htmlname);
7303
7304 return $out;
7305 }
7306
7307 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7308
7315 public function load_cache_vatrates($country_code)
7316 {
7317 // phpcs:enable
7318 global $langs, $user;
7319
7320 $num = count($this->cache_vatrates);
7321 if ($num > 0) {
7322 return $num; // Cache already loaded
7323 }
7324
7325 dol_syslog(__METHOD__, LOG_DEBUG);
7326
7327 $sql = "SELECT t.rowid, t.type_vat, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
7328 $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
7329 $sql .= " WHERE t.fk_pays = c.rowid";
7330 $sql .= " AND t.active > 0";
7331 $sql .= " AND t.entity IN (".getEntity('c_tva').")";
7332 $sql .= " AND c.code IN (" . $this->db->sanitize($country_code, 1) . ")";
7333 $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
7334
7335 $resql = $this->db->query($sql);
7336 if ($resql) {
7337 $num = $this->db->num_rows($resql);
7338 if ($num) {
7339 for ($i = 0; $i < $num; $i++) {
7340 $obj = $this->db->fetch_object($resql);
7341
7342 $tmparray = array();
7343 $tmparray['rowid'] = (int) $obj->rowid;
7344 $tmparray['type_vat'] = ($obj->type_vat <= 0 ? 0 : $obj->type_vat); // Some version have type_vat corrupted with value -1
7345 $tmparray['code'] = $obj->code;
7346 $tmparray['txtva'] = $obj->taux;
7347 $tmparray['nprtva'] = $obj->recuperableonly;
7348 $tmparray['localtax1'] = $obj->localtax1;
7349 $tmparray['localtax1_type'] = $obj->localtax1_type;
7350 $tmparray['localtax2'] = $obj->localtax2;
7351 $tmparray['localtax2_type'] = $obj->localtax1_type;
7352 $tmparray['label'] = $obj->taux . '%' . ($obj->code ? ' (' . $obj->code . ')' : ''); // Label must contains only 0-9 , . % or *
7353 $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
7354 $positiverates = '';
7355 if ($obj->taux) {
7356 $positiverates .= ($positiverates ? '/' : '') . $obj->taux;
7357 }
7358 if ($obj->localtax1) {
7359 $positiverates .= ($positiverates ? '/' : '') . $obj->localtax1;
7360 }
7361 if ($obj->localtax2) {
7362 $positiverates .= ($positiverates ? '/' : '') . $obj->localtax2;
7363 }
7364 if (empty($positiverates)) {
7365 $positiverates = '0';
7366 }
7367 $tmparray['labelpositiverates'] = $positiverates . ($obj->code ? ' (' . $obj->code . ')' : ''); // Must never be used as key, only label
7368
7369 $this->cache_vatrates[$obj->rowid] = $tmparray;
7370 }
7371
7372 return $num;
7373 } else {
7374 $this->error = '<span class="error">';
7375 $this->error .= $langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code);
7376 $reg = array();
7377 if (!empty($user) && $user->admin && preg_match('/\'(..)\'/', $country_code, $reg)) {
7378 $langs->load("errors");
7379 $new_country_code = $reg[1];
7380 $country_id = dol_getIdFromCode($this->db, $new_country_code, 'c_country', 'code', 'rowid');
7381 $this->error .= '<br>'.$langs->trans("ErrorFixThisHere", DOL_URL_ROOT.'/admin/dict.php?id=10'.($country_id > 0 ? '&countryidforinsert='.$country_id : ''));
7382 }
7383 $this->error .= '</span>';
7384 return -1;
7385 }
7386 } else {
7387 $this->error = '<span class="error">' . $this->db->error() . '</span>';
7388 return -2;
7389 }
7390 }
7391
7392 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7393
7416 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)
7417 {
7418 // phpcs:enable
7419 global $langs, $mysoc, $hookmanager;
7420
7421 $langs->load('errors');
7422
7423 $return = '';
7424 // Bypass the default method
7425 $hookmanager->initHooks(array('commonobject'));
7426 $info_bits == 1 ? $is_npr = 1 : $is_npr = 0;
7427 $parameters = array(
7428 'htmlname' => $htmlname,
7429 'selectedrate' => $selectedrate,
7430 'seller' => $societe_vendeuse,
7431 'buyer' => $societe_acheteuse,
7432 'idprod' => $idprod,
7433 'is_npr' => $is_npr,
7434 'type' => $type,
7435 'options_only' => $options_only,
7436 'mode' => $mode,
7437 'type_vat' => $type_vat
7438 );
7439 $reshook = $hookmanager->executeHooks('load_tva', $parameters);
7440 if ($reshook > 0) {
7441 return $hookmanager->resPrint;
7442 } elseif ($reshook === 0) {
7443 $return .= $hookmanager->resPrint;
7444 }
7445
7446 // Define defaultnpr, defaultttx and defaultcode
7447 $defaultnpr = ($info_bits & 0x01);
7448 $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
7449 $defaulttx = str_replace('*', '', $selectedrate);
7450 $defaultcode = '';
7451 $reg = array();
7452 if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
7453 $defaultcode = $reg[1];
7454 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
7455 }
7456 //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
7457
7458 // Check parameters
7459 if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
7460 if ($societe_vendeuse->id == $mysoc->id) {
7461 $return .= '<span class="error">' . $langs->trans("ErrorYourCountryIsNotDefined") . '</span>';
7462 } else {
7463 $return .= '<span class="error">' . $langs->trans("ErrorSupplierCountryIsNotDefined") . '</span>';
7464 }
7465 return $return;
7466 }
7467
7468 //var_dump($societe_acheteuse);
7469 //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";
7470 //exit;
7471
7472 // Define list of countries to use to search VAT rates to show
7473 // First we defined code_country to use to find list
7474 if (is_object($societe_vendeuse)) {
7475 $code_country = "'" . $societe_vendeuse->country_code . "'";
7476 } else {
7477 $code_country = "'" . $mysoc->country_code . "'"; // Pour compatibilite ascendente
7478 }
7479
7480 if ($societe_vendeuse == $mysoc && getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) { // If option to have vat for end customer for services is on
7481 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
7482 // If SERVICE_ARE_ECOMMERCE_200238EC=1 combo list vat rate of purchaser and seller countries
7483 // If SERVICE_ARE_ECOMMERCE_200238EC=2 combo list only the vat rate of the purchaser country
7484 $selectVatComboMode = getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC');
7485 if (is_object($societe_vendeuse) && is_object($societe_acheteuse) && isInEEC($societe_vendeuse) && isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()) {
7486 // We also add the buyer country code
7487 if (is_numeric($type)) {
7488 if ($type == 1) { // We know product is a service
7489 switch ($selectVatComboMode) {
7490 case '1':
7491 $code_country .= ",'" . $societe_acheteuse->country_code . "'";
7492 break;
7493 case '2':
7494 $code_country = "'" . $societe_acheteuse->country_code . "'";
7495 break;
7496 }
7497 }
7498 } elseif (!$idprod) { // We don't know type of product
7499 switch ($selectVatComboMode) {
7500 case '1':
7501 $code_country .= ",'" . $societe_acheteuse->country_code . "'";
7502 break;
7503 case '2':
7504 $code_country = "'" . $societe_acheteuse->country_code . "'";
7505 break;
7506 }
7507 } else {
7508 $prodstatic = new Product($this->db);
7509 $prodstatic->fetch($idprod);
7510 if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
7511 $code_country .= ",'" . $societe_acheteuse->country_code . "'";
7512 }
7513 }
7514 }
7515 }
7516
7517 // Now we load the list of VAT
7518 $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
7519
7520 // Keep only the VAT qualified for $type_vat (0 means all types)
7521 $arrayofvatrates = array();
7522 foreach ($this->cache_vatrates as $cachevalue) {
7523 if ($type_vat == 0 || empty($cachevalue['type_vat']) || $cachevalue['type_vat'] == $type_vat) {
7524 $arrayofvatrates[] = $cachevalue;
7525 }
7526 }
7527
7528 $num = count($arrayofvatrates);
7529 if ($num > 0) {
7530 // Define the vat rate to pre-select (if defaulttx not forced so is -1 or '')
7531 if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
7532 // Define a default thirdparty to use if the seller or buyer is not defined
7533 $tmpthirdparty = new Societe($this->db);
7534 $tmpthirdparty->country_code = $mysoc->country_code;
7535
7536 $defaulttx = get_default_tva(is_object($societe_vendeuse) ? $societe_vendeuse : $tmpthirdparty, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
7537 $defaultnpr = get_default_npr(is_object($societe_vendeuse) ? $societe_vendeuse : $tmpthirdparty, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
7538
7539 if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
7540 $defaultcode = $reg[1];
7541 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
7542 }
7543 if (empty($defaulttx)) {
7544 $defaultnpr = 0;
7545 }
7546 }
7547
7548 // If we fails to find a default vat rate, we take the last one in list
7549 // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
7550 if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
7551 if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
7552 // We take the last one found in list
7553 $defaulttx = $arrayofvatrates[$num - 1]['txtva'];
7554 } else {
7555 // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
7556 $defaulttx = '';
7557 if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
7558 $defaulttx = getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS');
7559 }
7560 if (preg_match('/\‍((.*)\‍)/', $defaulttx, $reg)) {
7561 $defaultcode = $reg[1];
7562 $defaulttx = preg_replace('/\s*\‍(.*\‍)/', '', $defaulttx);
7563 }
7564 }
7565 }
7566
7567 // Disabled is true if the seller is not subject to VAT
7568 $disabled = false;
7569 $title = '';
7570 if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && empty($societe_vendeuse->tva_assuj)) {
7571 // 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
7572 // EXPENSEREPORT_OVERRIDE_VAT is a strange option that allow to override/enable VAT regardless of sellet vat option - needed for expense report if
7573 // expense report used for business expenses instead of using supplier invoices (but this is a very bad idea !)
7574 if (!getDolGlobalString('EXPENSEREPORT_OVERRIDE_VAT')) {
7575 $title = ' title="' . dol_escape_htmltag($langs->trans('VATIsNotUsed')) . '"';
7576 $disabled = true;
7577 }
7578 }
7579
7580 if (!$options_only) {
7581 $return .= '<select class="flat valignmiddle minwidth75imp maxwidth100 right" id="' . $htmlname . '" name="' . $htmlname . '"' . ($disabled ? ' disabled' : '') . $title . '>';
7582 }
7583
7584 $selectedfound = false;
7585 foreach ($arrayofvatrates as $rate) {
7586 // Keep only 0 if seller is not subject to VAT
7587 if ($disabled && $rate['txtva'] != 0) {
7588 continue;
7589 }
7590
7591 // Define key to use into select list
7592 $key = $rate['txtva'];
7593 $key .= $rate['nprtva'] ? '*' : '';
7594 if ($mode > 0 && $rate['code']) {
7595 $key .= ' (' . $rate['code'] . ')';
7596 }
7597 if ($mode < 0) {
7598 $key = $rate['rowid'];
7599 }
7600
7601 $return .= '<option value="' . $key . '" data-vatid="'.$rate['rowid'].'"';
7602 if (!$selectedfound) {
7603 if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
7604 if ($defaultcode == $rate['code']) {
7605 $return .= ' selected';
7606 $selectedfound = true;
7607 }
7608 } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
7609 $return .= ' selected';
7610 $selectedfound = true;
7611 }
7612 }
7613 $return .= '>';
7614
7615 // Show label of VAT
7616 if ($mysoc->country_code == 'IN' || getDolGlobalString('MAIN_VAT_LABEL_IS_POSITIVE_RATES')) {
7617 // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
7618 $return .= $rate['labelpositiverates'];
7619 } else {
7620 // Simple label
7621 $return .= vatrate($rate['label']);
7622 }
7623
7624 //$return.=($rate['code']?' '.$rate['code']:'');
7625 $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
7626
7627 $return .= '</option>';
7628 }
7629
7630 if (!$options_only) {
7631 $return .= '</select>';
7632 //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
7633 }
7634 } else {
7635 $return .= $this->error;
7636 }
7637
7638 $this->num = $num;
7639 return $return;
7640 }
7641
7642
7643 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
7644
7669 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 = '')
7670 {
7671 // phpcs:enable
7672 dol_syslog(__METHOD__ . ': using select_date is deprecated. Use selectDate instead.', LOG_WARNING);
7673 $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
7674 if (!empty($nooutput)) {
7675 return $retstring;
7676 }
7677 print $retstring;
7678
7679 return '';
7680 }
7681
7697 public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
7698 {
7699 global $langs;
7700
7701 $ret = $this->selectDate($set_time, $prefix . '_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
7702 if ($forcenewline) {
7703 $ret .= '<br>';
7704 }
7705 $ret .= $this->selectDate($set_time_end, $prefix . '_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
7706 return $ret;
7707 }
7708
7737 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 = '')
7738 {
7739 global $conf, $langs;
7740
7741 if ($gm === 'auto') {
7742 $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
7743 }
7744
7745 $retstring = '';
7746
7747 if ($prefix == '') {
7748 $prefix = 're';
7749 }
7750 if ($h == '') {
7751 $h = 0;
7752 }
7753 if ($m == '') {
7754 $m = 0;
7755 }
7756 $emptydate = 0;
7757 $emptyhours = 0;
7758 if ($stepminutes <= 0 || $stepminutes > 30) {
7759 $stepminutes = 1;
7760 }
7761 if ($empty == 1) {
7762 $emptydate = 1;
7763 $emptyhours = 1;
7764 }
7765 if ($empty == 2) {
7766 $emptydate = 0;
7767 $emptyhours = 1;
7768 }
7769 $orig_set_time = $set_time;
7770
7771 if ($set_time === '' && $emptydate == 0) {
7772 include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
7773 if ($gm == 'tzuser' || $gm == 'tzuserrel') {
7774 $set_time = dol_now($gm);
7775 } else {
7776 $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
7777 }
7778 }
7779
7780 // Analysis of the pre-selection date
7781 $reg = array();
7782 $shour = '';
7783 $smin = '';
7784 $ssec = '';
7785 if (!empty($set_time) && preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', (string) $set_time, $reg)) { // deprecated usage
7786 // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
7787 $syear = (!empty($reg[1]) ? $reg[1] : '');
7788 $smonth = (!empty($reg[2]) ? $reg[2] : '');
7789 $sday = (!empty($reg[3]) ? $reg[3] : '');
7790 $shour = (!empty($reg[4]) ? $reg[4] : '');
7791 $smin = (!empty($reg[5]) ? $reg[5] : '');
7792 } elseif (strval($set_time) != '' && $set_time != -1) {
7793 // set_time est un timestamps (0 possible)
7794 $syear = dol_print_date($set_time, "%Y", $gm);
7795 $smonth = dol_print_date($set_time, "%m", $gm);
7796 $sday = dol_print_date($set_time, "%d", $gm);
7797 if ($orig_set_time != '') {
7798 $shour = dol_print_date($set_time, "%H", $gm);
7799 $smin = dol_print_date($set_time, "%M", $gm);
7800 $ssec = dol_print_date($set_time, "%S", $gm);
7801 }
7802 } else {
7803 // Date est '' ou vaut -1
7804 $syear = '';
7805 $smonth = '';
7806 $sday = '';
7807 $shour = getDolGlobalString('MAIN_DEFAULT_DATE_HOUR', ($h == -1 ? '23' : ''));
7808 $smin = getDolGlobalString('MAIN_DEFAULT_DATE_MIN', ($h == -1 ? '59' : ''));
7809 $ssec = getDolGlobalString('MAIN_DEFAULT_DATE_SEC', ($h == -1 ? '59' : ''));
7810 }
7811 if ($h == 3 || $h == 4) {
7812 $shour = '';
7813 }
7814 if ($m == 3) {
7815 $smin = '';
7816 }
7817
7818 $nowgmt = dol_now('gmt');
7819 //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
7820
7821 // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
7822 $usecalendar = 'combo';
7823 if (!empty($conf->use_javascript_ajax) && (!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') != "none")) {
7824 $usecalendar = ((!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') == 'eldy') ? 'jquery' : getDolGlobalString("MAIN_POPUP_CALENDAR"));
7825 }
7826 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
7827 // If we use a text browser or screen reader, we use the 'combo' date selector
7828 $usecalendar = 'html';
7829 }
7830
7831 if ($d) {
7832 // Show date with popup
7833 if ($usecalendar != 'combo') {
7834 // Set $format and $formatjs and $formatjquery
7835 $reduceformat = (!empty($conf->dol_optimize_smallscreen) ? 1 : 0); // Test on original $format param.
7836 if ($reduceformat) {
7837 $format = str_replace('%Y', '%y', $langs->transnoentitiesnoconv("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
7838 $formatjslong = $langs->transnoentitiesnoconv("FormatDateShortJavaInput"); // don't trust the name
7839 $formatjs = str_replace('yyyy', 'yy', $langs->transnoentitiesnoconv("FormatDateShortJavaInput"));
7840 $formatjquery = str_replace('yyyy', 'yy', $langs->trans("FormatDateShortJQueryInput"));
7841 } else {
7842 $format = $langs->transnoentitiesnoconv("FormatDateShortInput"); // FormatDateShortInput for dol_print_date is same than FormatDateShortJavaInput for javascript
7843 $formatjslong = $langs->transnoentitiesnoconv("FormatDateShortJavaInput"); // don't trust the name
7844 $formatjs = $langs->transnoentitiesnoconv("FormatDateShortJavaInput"); // FormatDateShortInput for dol_print_date is same than FormatDateShortJavaInput for javascript
7845 $formatjquery = $langs->trans("FormatDateShortJQueryInput");
7846 }
7847
7848 // Set formatted_date (for example: '%d/%m/%Y', '%m-%d-%y', ...
7849 $formatted_date = '';
7850 if (strval($set_time) != '' && $set_time != -1) {
7851 $formatted_date = dol_print_date($set_time, $format, $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
7852 }
7853
7854 // Calendrier popup version eldy
7855 if ($usecalendar == "eldy") {
7856 // To have this manager working back, you must retrieve all functions showDP child found into the lib_head.js of v4 for example
7857 // and load the js that contains them so the call of showDP will works.
7858 /*
7859 // Input area to enter date manually
7860 $retstring .= '<!-- datepicker usecalendar=eldy --><input id="' . $prefix . '" name="' . $prefix . '" type="text" class="maxwidthdate center" maxlength="11" value="' . $formatted_date . '"';
7861 $retstring .= ($disabled ? ' disabled' : '');
7862 $retstring .= ' onChange="dpChangeDay(\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($formatjslong")) . '\'); "'; // FormatDateShortInput for dol_print_date is same than FormatDateShortJavaInput for javascript
7863 $retstring .= ' autocomplete="off">';
7864
7865 // Icon calendar
7866 $retstringbuttom = '';
7867 if (!$disabled) {
7868 $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons"';
7869 $base = DOL_URL_ROOT . '/core/';
7870 $retstringbuttom .= ' onClick="showDP(\'' . dol_escape_js($base) . '\',\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($langs->trans("FormatDateShortJavaInput")) . '\',\'' . dol_escape_js($langs->defaultlang) . '\');"';
7871 $retstringbuttom .= '>' . img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink paddingright"') . '</button>';
7872 } else {
7873 $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink paddingright"') . '</button>';
7874 }
7875 $retstring = $retstringbuttom . $retstring;
7876
7877 $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
7878 $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
7879 $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
7880 */
7881 } elseif ($usecalendar == 'jquery' || $usecalendar == 'html') {
7882 if (!$disabled && $usecalendar != 'html') {
7883 // Output javascript for datepicker
7884 $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (idate('Y') - 100));
7885 $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (idate('Y') + 100));
7886
7887 $retstring .= '<!-- datepicker usecalendar='.$usecalendar.' --><script nonce="' . getNonce() . '" type="text/javascript">';
7888 $retstring .= "$(function(){ $('#" . $prefix . "').datepicker({
7889 dateFormat: '" . dol_escape_js($formatjquery) . "',
7890 autoclose: true,
7891 todayHighlight: true,
7892 yearRange: '" . $minYear . ":" . $maxYear . "',";
7893 if (!empty($conf->dol_use_jmobile)) {
7894 $retstring .= "
7895 beforeShow: function (input, datePicker) {
7896 input.disabled = true;
7897 },
7898 onClose: function (dateText, datePicker) {
7899 this.disabled = false;
7900 },
7901 ";
7902 }
7903 // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
7904 if (!getDolGlobalString('MAIN_POPUP_CALENDAR_ON_FOCUS')) {
7905 $buttonImage = $calendarpicto ?: DOL_URL_ROOT . "/theme/" . dol_escape_js($conf->theme) . "/img/object_calendarday.png";
7906 $retstring .= "
7907 showOn: 'button', /* both has problem with autocompletion */
7908 buttonImage: '" . $buttonImage . "',
7909 buttonImageOnly: true";
7910 }
7911 $retstring .= "
7912 }) });";
7913 $retstring .= "</script>";
7914 }
7915
7916 // Input area to enter date manually
7917 $retstring .= '<div class="nowraponall inline-block divfordateinput">';
7918 $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="'.($usecalendar == 'html' ? "date" : "text").'" class="maxwidthdate'.(getDolUserString('MAIN_OPTIMIZEFORTEXTBROWSER') ? ' textbrowser' : '').' center" maxlength="11" value="'.$formatted_date.'"';
7919 $retstring .= ($disabled ? ' disabled' : '');
7920 $retstring .= ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '');
7921 $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
7922 $retstring .= ' autocomplete="off">';
7923
7924 // Icon calendar
7925 if ($disabled) {
7926 $retstringbutton = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink ui-datepicker-notrigger"') . '</button>';
7927 $retstring .= $retstringbutton;
7928 }
7929
7930 $retstring .= '</div>';
7931 $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
7932 $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
7933 $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
7934 } else {
7935 $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
7936 }
7937 } else {
7938 // Show date with combo selects
7939 // Day
7940 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50imp" id="' . $prefix . 'day" name="' . $prefix . 'day">';
7941
7942 if ($emptydate || $set_time == -1) {
7943 $retstring .= '<option value="0" selected>&nbsp;</option>';
7944 }
7945
7946 for ($day = 1; $day <= 31; $day++) {
7947 $retstring .= '<option value="' . $day . '"' . ($day == $sday ? ' selected' : '') . '>' . $day . '</option>';
7948 }
7949
7950 $retstring .= "</select>";
7951
7952 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'month" name="' . $prefix . 'month">';
7953 if ($emptydate || $set_time == -1) {
7954 $retstring .= '<option value="0" selected>&nbsp;</option>';
7955 }
7956
7957 // Month
7958 for ($month = 1; $month <= 12; $month++) {
7959 $retstring .= '<option value="' . $month . '"' . ($month == $smonth ? ' selected' : '') . '>';
7960 $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
7961 $retstring .= "</option>";
7962 }
7963 $retstring .= "</select>";
7964
7965 // Year
7966 if ($emptydate || $set_time == -1) {
7967 $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 . '">';
7968 } else {
7969 $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'year" name="' . $prefix . 'year">';
7970
7971 $syear = (int) $syear;
7972 for ($year = $syear - 10; $year < (int) $syear + 10; $year++) {
7973 $retstring .= '<option value="' . $year . '"' . ($year == $syear ? ' selected' : '') . '>' . $year . '</option>';
7974 }
7975 $retstring .= "</select>\n";
7976 }
7977 }
7978 }
7979
7980 if ($d && $h) {
7981 $retstring .= (($h == 2 || $h == 4) ? '<br>' : ' ');
7982 $retstring .= '<span class="nowraponall">';
7983 }
7984
7985 if ($h) {
7986 $hourstart = 0;
7987 $hourend = 24;
7988 if ($openinghours != '') {
7989 $openinghours = explode(',', $openinghours);
7990 $hourstart = $openinghours[0];
7991 $hourend = $openinghours[1];
7992 if ($hourend < $hourstart) {
7993 $hourend = $hourstart;
7994 }
7995 }
7996
7997 // Show hour
7998 $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
7999 $retstring .= ($fullday ? $fullday . 'hour' : '') . '" id="' . $prefix . 'hour" name="' . $prefix . 'hour">';
8000 if ($emptyhours) {
8001 $retstring .= '<option value="-1">&nbsp;</option>';
8002 }
8003 for ($hour = $hourstart; $hour < $hourend; $hour++) {
8004 if (strlen($hour) < 2) {
8005 $hour = "0" . $hour;
8006 }
8007 $retstring .= '<option value="' . $hour . '"' . (($hour == $shour) ? ' selected' : '') . '>' . $hour;
8008 $retstring .= '</option>';
8009 }
8010 $retstring .= '</select>';
8011
8012 if ($disabled) {
8013 $retstring .= '<input type="hidden" id="' . $prefix . 'hour" name="' . $prefix . 'hour" value="' . $shour . '">' . "\n";
8014 }
8015 if ($m) {
8016 $retstring .= ":";
8017 }
8018 }
8019
8020 if ($m) {
8021 // Show minutes
8022 $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
8023 $retstring .= ($fullday ? $fullday . 'min' : '') . '" id="' . $prefix . 'min" name="' . $prefix . 'min">';
8024 if ($emptyhours) {
8025 $retstring .= '<option value="-1">&nbsp;</option>';
8026 }
8027 for ($min = 0; $min < 60; $min += $stepminutes) {
8028 $min_str = sprintf("%02d", $min);
8029 $retstring .= '<option value="' . $min_str . '"' . (($min_str == $smin) ? ' selected' : '') . '>' . $min_str . '</option>';
8030 }
8031 $retstring .= '</select>';
8032 if ($disabled) {
8033 $retstring .= '<input type="hidden" id="' . $prefix . 'min" name="' . $prefix . 'min" value="' . $smin . '">' . "\n";
8034 }
8035 // Add also seconds
8036 $retstring .= '<input type="hidden" name="' . $prefix . 'sec" value="' . $ssec . '">';
8037 }
8038
8039 if ($d && $h) {
8040 $retstring .= '</span>';
8041 }
8042
8043 // Add a "Now" link
8044 if (!empty($conf->use_javascript_ajax) && $addnowlink && !$disabled) {
8045 // Script which will be inserted in the onClick of the "Now" link
8046 $reset_scripts = "";
8047 if ($addnowlink == 2) { // local computer time
8048 // pad add leading 0 on numbers
8049 $reset_scripts .= "Number.prototype.pad = function(size) {
8050 var s = String(this);
8051 while (s.length < (size || 2)) {s = '0' + s;}
8052 return s;
8053 };
8054 var d = new Date();";
8055 }
8056
8057 // Generate the date part, depending on the use or not of the javascript calendar
8058 if ($addnowlink == 1) { // server time expressed in user time setup
8059 $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
8060 $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
8061 $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
8062 $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
8063 } elseif ($addnowlink == 2) {
8064 /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
8065 * This break application for foreign languages.
8066 $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
8067 $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
8068 $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
8069 $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
8070 */
8071 $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
8072 $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
8073 $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
8074 $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
8075 }
8076 /*if ($usecalendar == "eldy")
8077 {
8078 $base=DOL_URL_ROOT.'/core/';
8079 $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
8080 }
8081 else
8082 {
8083 $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
8084 $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
8085 $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
8086 }*/
8087 // Update the hour part
8088 if ($h) {
8089 if ($fullday) {
8090 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
8091 }
8092 //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
8093 if ($addnowlink == 1) {
8094 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
8095 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
8096 } elseif ($addnowlink == 2) {
8097 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(d.getHours().pad());';
8098 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
8099 }
8100
8101 if ($fullday) {
8102 $reset_scripts .= ' } ';
8103 }
8104 }
8105 // Update the minute part
8106 if ($m) {
8107 if ($fullday) {
8108 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
8109 }
8110 //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
8111 if ($addnowlink == 1) {
8112 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
8113 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
8114 } elseif ($addnowlink == 2) {
8115 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(d.getMinutes().pad());';
8116 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
8117 }
8118 if ($fullday) {
8119 $reset_scripts .= ' } ';
8120 }
8121 }
8122 // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
8123 if ($reset_scripts && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
8124 $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonNow" type="button" name="_useless" value="now" onClick="' . $reset_scripts . '">';
8125 $retstring .= $langs->trans("Now");
8126 $retstring .= '</button> ';
8127 }
8128 }
8129
8130 // Add a "Plus one hour" link
8131 if ($conf->use_javascript_ajax && $addplusone && !$disabled) {
8132 // Script which will be inserted in the onClick of the "Add plusone" link
8133 $reset_scripts = "";
8134
8135 // Generate the date part, depending on the use or not of the javascript calendar
8136 $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel') . '\');';
8137 $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
8138 $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
8139 $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
8140 // Update the hour part
8141 if ($h) {
8142 if ($fullday) {
8143 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
8144 }
8145 $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
8146 if ($fullday) {
8147 $reset_scripts .= ' } ';
8148 }
8149 }
8150 // Update the minute part
8151 if ($m) {
8152 if ($fullday) {
8153 $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
8154 }
8155 $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
8156 if ($fullday) {
8157 $reset_scripts .= ' } ';
8158 }
8159 }
8160 // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
8161 if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
8162 $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="' . $reset_scripts . '">';
8163 $retstring .= $langs->trans("DateStartPlusOne");
8164 $retstring .= '</button> ';
8165 }
8166 }
8167
8168 // Add a link to set data
8169 if ($conf->use_javascript_ajax && !empty($adddateof) && !$disabled) {
8170 if (!is_array($adddateof)) {
8171 $arrayofdateof = array(array('adddateof' => $adddateof, 'labeladddateof' => $labeladddateof));
8172 } else {
8173 $arrayofdateof = $adddateof;
8174 }
8175 foreach ($arrayofdateof as $valuedateof) {
8176 $tmpadddateof = empty($valuedateof['adddateof']) ? 0 : $valuedateof['adddateof'];
8177 $tmplabeladddateof = empty($valuedateof['labeladddateof']) ? '' : $valuedateof['labeladddateof'];
8178 $tmparray = dol_getdate($tmpadddateof);
8179 if (empty($tmplabeladddateof)) {
8180 $tmplabeladddateof = $langs->trans("DateInvoice");
8181 }
8182 $reset_scripts = 'console.log(\'Click on now link\'); ';
8183 $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($tmpadddateof, 'dayinputnoreduce').'\');';
8184 $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.$tmparray['mday'].'\');';
8185 $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.$tmparray['mon'].'\');';
8186 $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.$tmparray['year'].'\');';
8187 $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="'.$reset_scripts.'">'.$tmplabeladddateof.'</button>';
8188 }
8189 }
8190
8191 return $retstring;
8192 }
8193
8203 public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array(), $morecss = 'minwidth75 maxwidth100')
8204 {
8205 global $langs;
8206
8207 $TDurationTypes = $this->getDurationTypes($langs);
8208
8209 // Removed undesired duration types
8210 foreach ($excludetypes as $value) {
8211 unset($TDurationTypes[$value]);
8212 }
8213
8214 $retstring = '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_' . $prefix . 'type_duration" name="' . $prefix . 'type_duration">';
8215 foreach ($TDurationTypes as $key => $typeduration) {
8216 $retstring .= '<option value="' . $key . '"';
8217 if ($key == $selected) {
8218 $retstring .= " selected";
8219 }
8220 $retstring .= ">" . $typeduration . "</option>";
8221 }
8222 $retstring .= "</select>";
8223
8224 $retstring .= ajax_combobox('select_' . $prefix . 'type_duration');
8225
8226 return $retstring;
8227 }
8228
8229 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
8230
8244 public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
8245 {
8246 // phpcs:enable
8247 global $langs;
8248
8249 $retstring = '<span class="nowraponall">';
8250
8251 $hourSelected = '';
8252 $minSelected = '';
8253
8254 // Hours
8255 if ($iSecond != '') {
8256 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
8257
8258 $hourSelected = convertSecondToTime($iSecond, 'allhour');
8259 $minSelected = convertSecondToTime($iSecond, 'min');
8260 }
8261
8262 if ($typehour == 'select') {
8263 $retstring .= '<select class="flat" id="select_' . $prefix . 'hour" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . '>';
8264 for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
8265 $retstring .= '<option value="' . $hour . '"';
8266 if (is_numeric($hourSelected) && $hourSelected == $hour) {
8267 $retstring .= " selected";
8268 }
8269 $retstring .= ">" . $hour . "</option>";
8270 }
8271 $retstring .= "</select>";
8272 } elseif ($typehour == 'text' || $typehour == 'textselect') {
8273 $retstring .= '<input placeholder="' . $langs->trans('HourShort') . '" type="number" min="0" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputhour right" value="' . (($hourSelected != '') ? ((int) $hourSelected) : '') . '">';
8274 } else {
8275 return 'BadValueForParameterTypeHour';
8276 }
8277
8278 if ($typehour != 'text') {
8279 $retstring .= ' ' . $langs->trans('HourShort');
8280 } else {
8281 $retstring .= '<span class="">:</span>';
8282 }
8283
8284 // Minutes
8285 if ($minunderhours) {
8286 $retstring .= '<br>';
8287 } else {
8288 if ($typehour != 'text') {
8289 $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
8290 }
8291 }
8292
8293 if ($typehour == 'select' || $typehour == 'textselect') {
8294 $retstring .= '<select class="flat" id="select_' . $prefix . 'min" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . '>';
8295 $step = getDolGlobalInt('MAIN_DURATION_STEP');
8296 $duration_step = ($step > 0) ? $step : 5;
8297 for ($min = 0; $min <= 59; $min += $duration_step) {
8298 $retstring .= '<option value="' . $min . '"';
8299 if (is_numeric($minSelected) && $minSelected == $min) {
8300 $retstring .= ' selected';
8301 }
8302 $retstring .= '>' . $min . '</option>';
8303 }
8304 $retstring .= "</select>";
8305 } elseif ($typehour == 'text') {
8306 $retstring .= '<input placeholder="' . $langs->trans('MinuteShort') . '" type="number" min="0" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputminute right" value="' . (($minSelected != '') ? ((int) $minSelected) : '') . '">';
8307 }
8308
8309 if ($typehour != 'text') {
8310 $retstring .= ' ' . $langs->trans('MinuteShort');
8311 }
8312
8313 $retstring .= "</span>";
8314
8315 if (!empty($nooutput)) {
8316 return $retstring;
8317 }
8318
8319 print $retstring;
8320
8321 return '';
8322 }
8323
8343 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)
8344 {
8345 global $langs, $conf;
8346
8347 $out = '';
8348
8349 // check parameters
8350 if (is_null($ajaxoptions)) {
8351 $ajaxoptions = array();
8352 }
8353
8354 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
8355 $placeholder = '';
8356
8357 if ($selected && empty($selected_input_value)) {
8358 require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
8359 $tickettmpselect = new Ticket($this->db);
8360 $tickettmpselect->fetch((int) $selected);
8361 $selected_input_value = $tickettmpselect->ref;
8362 unset($tickettmpselect);
8363 }
8364
8365 $urloption = '';
8366 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
8367
8368 if (empty($hidelabel)) {
8369 $out .= $langs->trans("RefOrLabel") . ' : ';
8370 } elseif ($hidelabel > 1) {
8371 $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
8372 if ($hidelabel == 2) {
8373 $out .= img_picto($langs->trans("Search"), 'search');
8374 }
8375 }
8376 $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
8377 if ($hidelabel == 3) {
8378 $out .= img_picto($langs->trans("Search"), 'search');
8379 }
8380 } else {
8381 $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, '', $status, 0, $showempty, $forcecombo, $morecss);
8382 }
8383
8384 if (empty($nooutput)) {
8385 print $out;
8386 } else {
8387 return $out;
8388 }
8389 return '';
8390 }
8391
8392
8409 public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
8410 {
8411 global $langs;
8412
8413 $out = '';
8414 $outarray = array();
8415
8416 $selectFields = " p.rowid, p.ref, p.message";
8417
8418 $sql = "SELECT ";
8419 $sql .= $selectFields;
8420 $sql .= " FROM " . $this->db->prefix() . "ticket as p";
8421 $sql .= ' WHERE p.entity IN (' . getEntity('ticket') . ')';
8422
8423 // Add criteria on ref/label
8424 if ($filterkey != '') {
8425 $sql .= ' AND (';
8426 $prefix = getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '' : '%'; // Can use index if TICKET_DONOTSEARCH_ANYWHERE is on
8427 // For natural search
8428 $search_crit = explode(' ', $filterkey);
8429 $i = 0;
8430 if (count($search_crit) > 1) {
8431 $sql .= "(";
8432 }
8433 foreach ($search_crit as $crit) {
8434 if ($i > 0) {
8435 $sql .= " AND ";
8436 }
8437 $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.subject LIKE '" . $this->db->escape($prefix . $crit) . "%'";
8438 $sql .= ")";
8439 $i++;
8440 }
8441 if (count($search_crit) > 1) {
8442 $sql .= ")";
8443 }
8444 $sql .= ')';
8445 }
8446
8447 $sql .= $this->db->plimit($limit, 0);
8448
8449 // Build output string
8450 dol_syslog(get_class($this) . "::selectTicketsList search tickets", LOG_DEBUG);
8451 $result = $this->db->query($sql);
8452 if ($result) {
8453 require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
8454 require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php';
8455
8456 $num = $this->db->num_rows($result);
8457
8458 $events = array();
8459
8460 if (!$forcecombo) {
8461 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
8462 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt('TICKET_USE_SEARCH_TO_SELECT'));
8463 }
8464
8465 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
8466
8467 $textifempty = '';
8468 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
8469 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
8470 if (getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
8471 if ($showempty && !is_numeric($showempty)) {
8472 $textifempty = $langs->trans($showempty);
8473 } else {
8474 $textifempty .= $langs->trans("All");
8475 }
8476 } else {
8477 if ($showempty && !is_numeric($showempty)) {
8478 $textifempty = $langs->trans($showempty);
8479 }
8480 }
8481 if ($showempty) {
8482 $out .= '<option value="0" selected>' . $textifempty . '</option>';
8483 }
8484
8485 $i = 0;
8486 while ($num && $i < $num) {
8487 $opt = '';
8488 $optJson = array();
8489 $objp = $this->db->fetch_object($result);
8490
8491 $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
8492 '@phan-var-force array{key:string,value:mixed,type:int} $optJson';
8493 // Add new entry
8494 // "key" value of json key array is used by jQuery automatically as selected value
8495 // "label" value of json key array is used by jQuery automatically as text for combo box
8496 $out .= $opt;
8497 array_push($outarray, $optJson);
8498
8499 $i++;
8500 }
8501
8502 $out .= '</select>';
8503
8504 $this->db->free($result);
8505
8506 if (empty($outputmode)) {
8507 return $out;
8508 }
8509 return $outarray;
8510 } else {
8511 dol_print_error($this->db);
8512 }
8513
8514 return array();
8515 }
8516
8528 protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
8529 {
8530 $outkey = '';
8531 $outref = '';
8532 $outtype = '';
8533
8534 $outkey = $objp->rowid;
8535 $outref = $objp->ref;
8536
8537 $opt = '<option value="' . $objp->rowid . '"';
8538 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
8539 $opt .= '>';
8540 $opt .= $objp->ref;
8541 $objRef = $objp->ref;
8542 if (!empty($filterkey) && $filterkey != '') {
8543 $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
8544 }
8545
8546 $opt .= "</option>\n";
8547 $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
8548 }
8549
8569 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)
8570 {
8571 global $langs, $conf;
8572
8573 $out = '';
8574
8575 // check parameters
8576 if (is_null($ajaxoptions)) {
8577 $ajaxoptions = array();
8578 }
8579
8580 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
8581 $placeholder = '';
8582
8583 if ($selected && empty($selected_input_value)) {
8584 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
8585 $projecttmpselect = new Project($this->db);
8586 $projecttmpselect->fetch((int) $selected);
8587 $selected_input_value = $projecttmpselect->ref;
8588 unset($projecttmpselect);
8589 }
8590
8591 $urloption = '';
8592 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
8593
8594 if (empty($hidelabel)) {
8595 $out .= $langs->trans("RefOrLabel") . ' : ';
8596 } elseif ($hidelabel > 1) {
8597 $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
8598 if ($hidelabel == 2) {
8599 $out .= img_picto($langs->trans("Search"), 'search');
8600 }
8601 }
8602 $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
8603 if ($hidelabel == 3) {
8604 $out .= img_picto($langs->trans("Search"), 'search');
8605 }
8606 } else {
8607 $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, '', $status, 0, $showempty, $forcecombo, $morecss);
8608 }
8609
8610 if (empty($nooutput)) {
8611 print $out;
8612 } else {
8613 return $out;
8614 }
8615 return '';
8616 }
8617
8634 public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
8635 {
8636 global $langs, $conf;
8637
8638 $out = '';
8639 $outarray = array();
8640
8641 $selectFields = " p.rowid, p.ref";
8642
8643 $sql = "SELECT ";
8644 $sql .= $selectFields;
8645 $sql .= " FROM " . $this->db->prefix() . "projet as p";
8646 $sql .= ' WHERE p.entity IN (' . getEntity('project') . ')';
8647
8648 // Add criteria on ref/label
8649 if ($filterkey != '') {
8650 $sql .= ' AND (';
8651 $prefix = !getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
8652 // For natural search
8653 $search_crit = explode(' ', $filterkey);
8654 $i = 0;
8655 if (count($search_crit) > 1) {
8656 $sql .= "(";
8657 }
8658 foreach ($search_crit as $crit) {
8659 if ($i > 0) {
8660 $sql .= " AND ";
8661 }
8662 $sql .= "p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%'";
8663 $sql .= "";
8664 $i++;
8665 }
8666 if (count($search_crit) > 1) {
8667 $sql .= ")";
8668 }
8669 $sql .= ')';
8670 }
8671
8672 $sql .= $this->db->plimit($limit, 0);
8673
8674 // Build output string
8675 dol_syslog(get_class($this) . "::selectProjectsList search projects", LOG_DEBUG);
8676 $result = $this->db->query($sql);
8677 if ($result) {
8678 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
8679 require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
8680
8681 $num = $this->db->num_rows($result);
8682
8683 $events = array();
8684
8685 if (!$forcecombo) {
8686 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
8687 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt('PROJECT_USE_SEARCH_TO_SELECT'));
8688 }
8689
8690 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
8691
8692 $textifempty = '';
8693 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
8694 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
8695 if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
8696 if ($showempty && !is_numeric($showempty)) {
8697 $textifempty = $langs->trans($showempty);
8698 } else {
8699 $textifempty .= $langs->trans("All");
8700 }
8701 } else {
8702 if ($showempty && !is_numeric($showempty)) {
8703 $textifempty = $langs->trans($showempty);
8704 }
8705 }
8706 if ($showempty) {
8707 $out .= '<option value="0" selected>' . $textifempty . '</option>';
8708 }
8709
8710 $i = 0;
8711 while ($num && $i < $num) {
8712 $opt = '';
8713 $optJson = array();
8714 $objp = $this->db->fetch_object($result);
8715
8716 $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
8717 // Add new entry
8718 // "key" value of json key array is used by jQuery automatically as selected value
8719 // "label" value of json key array is used by jQuery automatically as text for combo box
8720 $out .= $opt;
8721 array_push($outarray, $optJson);
8722
8723 $i++;
8724 }
8725
8726 $out .= '</select>';
8727
8728 $this->db->free($result);
8729
8730 if (empty($outputmode)) {
8731 return $out;
8732 }
8733 return $outarray;
8734 } else {
8735 dol_print_error($this->db);
8736 }
8737
8738 return array();
8739 }
8740
8754 protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
8755 {
8756 $outkey = '';
8757 $outref = '';
8758 $outtype = '';
8759
8760 $label = $objp->label;
8761
8762 $outkey = $objp->rowid;
8763 $outref = $objp->ref;
8764 $outlabel = $objp->label;
8765 $outtype = $objp->fk_product_type;
8766
8767 $opt = '<option value="' . $objp->rowid . '"';
8768 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
8769 $opt .= '>';
8770 $opt .= $objp->ref;
8771 $objRef = $objp->ref;
8772 if (!empty($filterkey) && $filterkey != '') {
8773 $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
8774 }
8775
8776 $opt .= "</option>\n";
8777 $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
8778 }
8779
8780
8801 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())
8802 {
8803 global $langs, $conf;
8804
8805 $out = '';
8806
8807 // check parameters
8808 if (is_null($ajaxoptions)) {
8809 $ajaxoptions = array();
8810 }
8811
8812 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
8813 $placeholder = '';
8814
8815 if ($selected && empty($selected_input_value)) {
8816 require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
8817 $adherenttmpselect = new Adherent($this->db);
8818 $adherenttmpselect->fetch((int) $selected);
8819 $selected_input_value = $adherenttmpselect->ref;
8820 unset($adherenttmpselect);
8821 }
8822
8823 $urloption = '';
8824
8825 $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
8826
8827 if (empty($hidelabel)) {
8828 $out .= $langs->trans("RefOrLabel") . ' : ';
8829 } elseif ($hidelabel > 1) {
8830 $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
8831 if ($hidelabel == 2) {
8832 $out .= img_picto($langs->trans("Search"), 'search');
8833 }
8834 }
8835 $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
8836 if ($hidelabel == 3) {
8837 $out .= img_picto($langs->trans("Search"), 'search');
8838 }
8839 } else {
8840 $filterkey = '';
8841
8842 $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss, $excludeids);
8843 }
8844
8845 if (empty($nooutput)) {
8846 print $out;
8847 } else {
8848 return $out;
8849 }
8850 return '';
8851 }
8852
8870 public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $excludeids = array())
8871 {
8872 global $langs, $conf;
8873
8874 $out = '';
8875 $outarray = array();
8876
8877 $selectFields = " p.rowid, p.ref, p.firstname, p.lastname, p.fk_adherent_type";
8878
8879 $sql = "SELECT ";
8880 $sql .= $selectFields;
8881 $sql .= " FROM " . $this->db->prefix() . "adherent as p";
8882 $sql .= ' WHERE p.entity IN (' . getEntity('adherent') . ')';
8883
8884 // Add criteria on ref/label
8885 if ($filterkey != '') {
8886 $sql .= ' AND (';
8887 $prefix = !getDolGlobalString('MEMBER_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
8888 // For natural search
8889 $search_crit = explode(' ', $filterkey);
8890 $i = 0;
8891 if (count($search_crit) > 1) {
8892 $sql .= "(";
8893 }
8894 foreach ($search_crit as $crit) {
8895 if ($i > 0) {
8896 $sql .= " AND ";
8897 }
8898 $sql .= "(p.firstname LIKE '" . $this->db->escape($prefix . $crit) . "%'";
8899 $sql .= " OR p.lastname LIKE '" . $this->db->escape($prefix . $crit) . "%')";
8900 $i++;
8901 }
8902 if (count($search_crit) > 1) {
8903 $sql .= ")";
8904 }
8905 $sql .= ')';
8906 }
8907 if ($status != -1) {
8908 $sql .= ' AND statut = ' . ((int) $status);
8909 }
8910 if (!empty($excludeids)) {
8911 $sql .= " AND p.rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeids)) . ")";
8912 }
8913 $sql .= $this->db->plimit($limit, 0);
8914
8915 // Build output string
8916 dol_syslog(get_class($this) . "::selectMembersList search adherents", LOG_DEBUG);
8917 $result = $this->db->query($sql);
8918 if ($result) {
8919 require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
8920 require_once DOL_DOCUMENT_ROOT . '/core/lib/member.lib.php';
8921
8922 $num = $this->db->num_rows($result);
8923
8924 $events = array();
8925
8926 if (!$forcecombo) {
8927 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
8928 $out .= ajax_combobox($htmlname, $events, getDolGlobalInt('PROJECT_USE_SEARCH_TO_SELECT'));
8929 }
8930
8931 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
8932
8933 $textifempty = '';
8934 // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
8935 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
8936 if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
8937 if ($showempty && !is_numeric($showempty)) {
8938 $textifempty = $langs->trans($showempty);
8939 } else {
8940 $textifempty .= $langs->trans("All");
8941 }
8942 } else {
8943 if ($showempty && !is_numeric($showempty)) {
8944 $textifempty = $langs->trans($showempty);
8945 }
8946 }
8947 if ($showempty) {
8948 $out .= '<option value="-1" selected>' . $textifempty . '</option>';
8949 }
8950
8951 $i = 0;
8952 while ($num && $i < $num) {
8953 $opt = '';
8954 $optJson = array();
8955 $objp = $this->db->fetch_object($result);
8956
8957 $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
8958
8959 // Add new entry
8960 // "key" value of json key array is used by jQuery automatically as selected value
8961 // "label" value of json key array is used by jQuery automatically as text for combo box
8962 $out .= $opt;
8963 array_push($outarray, $optJson);
8964
8965 $i++;
8966 }
8967
8968 $out .= '</select>';
8969
8970 $this->db->free($result);
8971
8972 if (empty($outputmode)) {
8973 return $out;
8974 }
8975 return $outarray;
8976 } else {
8977 dol_print_error($this->db);
8978 }
8979
8980 return array();
8981 }
8982
8994 protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
8995 {
8996 $outkey = '';
8997 $outlabel = '';
8998 $outtype = '';
8999
9000 $outkey = $objp->rowid;
9001 $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
9002 $outtype = $objp->fk_adherent_type;
9003
9004 $opt = '<option value="' . $objp->rowid . '"';
9005 $opt .= ($objp->rowid == $selected) ? ' selected' : '';
9006 $opt .= '>';
9007 if (!empty($filterkey) && $filterkey != '') {
9008 $outlabel = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $outlabel, 1);
9009 }
9010 $opt .= $outlabel;
9011 $opt .= "</option>\n";
9012
9013 $optJson = array('key' => $outkey, 'value' => $outlabel, 'type' => $outtype);
9014 }
9015
9037 public function selectForForms($objectdesc, $htmlname, $preSelectedValue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '', $objectfield = '')
9038 {
9039 global $conf, $extrafields, $user;
9040
9041 // Example of common usage for a link to a thirdparty
9042
9043 // We got this in a modulebuilder form of "MyObject" of module "mymodule".
9044 // 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
9045 // $objectdesc = 'Societe'
9046 // $objectfield = Method 1: 'myobject@mymodule:fk_soc' ('fk_soc' is code to retrieve myobject->fields['fk_soc'])
9047 // 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__))" ...)
9048
9049 // We got this when showing an extrafields on resource that is a link to societe
9050 // 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
9051 // $objectdesc = 'Societe'
9052 // $objectfield = Method 1: 'resource:options_link_to_societe'
9053 // Method 2 recommended (it can be the array): array("type"=>'Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))" ...)
9054
9055 // With old usage:
9056 // $objectdesc = 'Societe:societe/class/societe.class.php:1:((status:=:1) AND (entity:IN:__SHARED_ENTITIES__))'
9057 // $objectfield = ''
9058
9059 //var_dump($objectdesc.' '.$objectfield);
9060 //debug_print_backtrace();
9061
9062 $objectdescorig = $objectdesc;
9063 $objecttmp = null;
9064 $InfoFieldList = array();
9065 $classname = '';
9066 $filter = ''; // Ensure filter has value (for static analysis)
9067 $sortfield = ''; // Ensure filter has value (for static analysis)
9068
9069 if (is_array($objectfield)) { // objectfield is an array
9070 $objectdesc = $objectfield['type'];
9071 $objectdesc = preg_replace('/^integer[^:]*:/', '', $objectdesc);
9072 } 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.
9073 // Example: $objectfield = 'product:options_package' or 'myobject@mymodule:options_myfield'
9074 $tmparray = explode(':', $objectfield);
9075
9076 // Get instance of object from $element
9077 $objectforfieldstmp = fetchObjectByElement(0, strtolower($tmparray[0]));
9078
9079 if (is_object($objectforfieldstmp)) {
9080 $objectdesc = '';
9081
9082 $reg = array();
9083 if (preg_match('/^options_(.*)$/', $tmparray[1], $reg)) {
9084 // For a property in extrafields
9085 $key = $reg[1];
9086 // fetch optionals attributes and labels
9087 $extrafields->fetch_name_optionals_label($objectforfieldstmp->table_element);
9088
9089 if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key]) && $extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key] == 'link') {
9090 if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options'])) {
9091 $tmpextrafields = array_keys($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options']);
9092 $objectdesc = $tmpextrafields[0];
9093 }
9094 }
9095 } else {
9096 // For a property in ->fields
9097 if (array_key_exists($tmparray[1], $objectforfieldstmp->fields)) {
9098 $objectdesc = $objectforfieldstmp->fields[$tmparray[1]]['type'];
9099 $objectdesc = preg_replace('/^integer[^:]*:/', '', $objectdesc);
9100 }
9101 }
9102 }
9103 }
9104
9105 if ($objectdesc) {
9106 // Example of value for $objectdesc:
9107 // Bom:bom/class/bom.class.php:0:t.status=1
9108 // Bom:bom/class/bom.class.php:0:t.status=1:ref
9109 // Bom:bom/class/bom.class.php:0:(t.status:=:1) OR (t.field2:=:2):ref
9110 $InfoFieldList = explode(":", $objectdesc, 4);
9111 $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
9112 $reg = array();
9113 if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
9114 $InfoFieldList[4] = $reg[1]; // take the sort field
9115 }
9116 $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
9117
9118 $classname = $InfoFieldList[0];
9119 $classpath = empty($InfoFieldList[1]) ? '' : $InfoFieldList[1];
9120 //$addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
9121 $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
9122 $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
9123
9124 // Load object according to $id and $element
9125 $objecttmp = fetchObjectByElement(0, strtolower($InfoFieldList[0]));
9126
9127 // Fallback to another solution to get $objecttmp
9128 if (empty($objecttmp) && !empty($classpath)) {
9129 dol_include_once($classpath);
9130
9131 if ($classname && class_exists($classname)) {
9132 $objecttmp = new $classname($this->db);
9133 }
9134 }
9135 }
9136
9137 // Make some replacement in $filter. May not be used if we used the ajax mode with $objectfield. In such a case
9138 // we propagate the $objectfield and not the filter and replacement is done by the ajax/selectobject.php component.
9139 $sharedentities = (is_object($objecttmp) && property_exists($objecttmp, 'element')) ? getEntity($objecttmp->element) : strtolower($classname);
9140 $filter = str_replace(
9141 array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
9142 array($conf->entity, $sharedentities, $user->id),
9143 $filter
9144 );
9145
9146 if (!is_object($objecttmp)) {
9147 dol_syslog('selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.(is_array($objectfield) ? 'array' : $objectfield).', objectdesc='.$objectdesc, LOG_WARNING);
9148 return 'selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.(is_array($objectfield) ? 'array' : $objectfield).', objectdesc='.$objectdesc;
9149 }
9150 '@phan-var-force CommonObject $objecttmp';
9152 //var_dump($filter);
9153 $prefixforautocompletemode = $objecttmp->element;
9154 if ($prefixforautocompletemode == 'societe') {
9155 $prefixforautocompletemode = 'company';
9156 }
9157 if ($prefixforautocompletemode == 'product') {
9158 $prefixforautocompletemode = 'produit';
9159 }
9160
9161 $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
9162
9163 dol_syslog(get_class($this) . "::selectForForms filter=" . $filter, LOG_DEBUG);
9164
9165 // Generate the combo HTML component
9166 $out = '';
9167 if (!empty($conf->use_javascript_ajax) && getDolGlobalString($confkeyforautocompletemode) && !$forcecombo) {
9168 // No immediate load of all database
9169 $placeholder = '';
9170
9171 if ($preSelectedValue && empty($selected_input_value)) {
9172 $objecttmp->fetch($preSelectedValue);
9173 $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
9174
9175 $oldValueForShowOnCombobox = 0;
9176 foreach ($objecttmp->fields as $fieldK => $fielV) {
9177 if (!array_key_exists('showoncombobox', $fielV) || !$fielV['showoncombobox'] || empty($objecttmp->$fieldK)) {
9178 continue;
9179 }
9180
9181 if (!$oldValueForShowOnCombobox) {
9182 $selected_input_value = '';
9183 }
9184
9185 $selected_input_value .= $oldValueForShowOnCombobox ? ' - ' : '';
9186 $selected_input_value .= $objecttmp->$fieldK;
9187 $oldValueForShowOnCombobox = empty($fielV['showoncombobox']) ? 0 : $fielV['showoncombobox'];
9188 }
9189 }
9190
9191 // Set url and param to call to get json of the search results
9192 $urlforajaxcall = DOL_URL_ROOT . '/core/ajax/selectobject.php';
9193 $urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1&objectdesc=' . urlencode($objectdescorig) . (is_scalar($objectfield) ? '&objectfield='.urlencode($objectfield) : '') . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
9194 //$urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1'.(is_scalar($objectfield) ? '&objectfield='.urlencode($objectfield) : '') . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
9195
9196 // Activate the auto complete using ajax call.
9197 $out .= ajax_autocompleter((string) $preSelectedValue, $htmlname, $urlforajaxcall, $urloption, getDolGlobalInt($confkeyforautocompletemode), 0);
9198 $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
9199 $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) . '"' : '') . ' />';
9200 } else {
9201 // Immediate load of table record.
9202 $out .= $this->selectForFormsList($objecttmp, $htmlname, $preSelectedValue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
9203 }
9204
9205 return $out;
9206 }
9207
9208
9230 public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '', $sortorder = 'ASC')
9231 {
9232 global $langs, $user, $hookmanager;
9233
9234 //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
9235
9236 $prefixforautocompletemode = $objecttmp->element;
9237 if ($prefixforautocompletemode == 'societe') {
9238 $prefixforautocompletemode = 'company';
9239 }
9240 $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
9241
9242 if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
9243 $tmpfieldstoshow = '';
9244 foreach ($objecttmp->fields as $key => $val) {
9245 if (! (int) dol_eval((string) $val['enabled'], 1, 1, '1')) {
9246 continue;
9247 }
9248 if (!empty($val['showoncombobox'])) {
9249 $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '') . 't.' . $key;
9250 }
9251 }
9252 if ($tmpfieldstoshow) {
9253 $fieldstoshow = $tmpfieldstoshow;
9254 }
9255 } elseif ($objecttmp->element === 'category') {
9256 $fieldstoshow = 't.label';
9257 } else {
9258 // For backward compatibility
9259 $objecttmp->fields['ref'] = array('type' => 'varchar(30)', 'label' => 'Ref', 'enabled' => 1, 'position' => 10, 'visible' => 4, 'showoncombobox' => 1);
9260 }
9261
9262 if (empty($fieldstoshow)) {
9263 if (!empty($objecttmp->parent_element)) {
9264 $fieldstoshow = 'o.ref';
9265 if (empty($sortfield)) {
9266 $sortfield = 'o.ref';
9267 }
9268 if (in_array($objecttmp->element, ['commandedet', 'propaldet', 'facturedet', 'expeditiondet'])) {
9269 $fieldstoshow .= ',p.ref AS p_ref,p.label,t.description';
9270 $sortfield .= ', p.ref';
9271 }
9272 } elseif (isset($objecttmp->fields['ref'])) {
9273 $fieldstoshow = 't.ref';
9274 } else {
9275 $langs->load("errors");
9276 $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
9277 return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
9278 }
9279 }
9280
9281 $out = '';
9282 $outarray = array();
9283 $tmparray = array();
9284
9285 $num = 0;
9286
9287 // Search data
9288 $sql = "SELECT t.rowid, " . $fieldstoshow . " FROM " . $this->db->prefix() . $this->db->sanitize($objecttmp->table_element) . " as t";
9289 if (!empty($objecttmp->isextrafieldmanaged)) {
9290 $extrafieldTable = $objecttmp->table_element;
9291 if ($extrafieldTable == 'categorie') {
9292 $extrafieldTable = 'categories'; // For compatibility
9293 }
9294 $sql .= " LEFT JOIN " . $this->db->prefix() . $this->db->sanitize($extrafieldTable) . "_extrafields as e ON t.rowid = e.fk_object";
9295 }
9296 if (!empty($objecttmp->parent_element)) { // If parent_element is defined
9297 '@phan-var-force CommonObjectLine $objecttmp';
9298 $parent_properties = getElementProperties($objecttmp->parent_element);
9299 $sql .= " INNER JOIN " . $this->db->prefix() . $this->db->sanitize($parent_properties['table_element']) . " as o ON o.rowid = t.".$objecttmp->fk_parent_attribute;
9300 }
9301 if (!empty($objecttmp->parent_element) && in_array($objecttmp->parent_element, ['commande', 'propal', 'facture', 'expedition'])) {
9302 $sql .= " LEFT JOIN " . $this->db->prefix() . "product as p ON p.rowid = t.fk_product";
9303 }
9304 if (!empty($objecttmp->ismultientitymanaged)) {
9305 if ($objecttmp->ismultientitymanaged == 1) { // @phan-suppress-current-line PhanPluginEmptyStatementIf
9306 // No need to join/link another table
9307 }
9308 if (!is_numeric($objecttmp->ismultientitymanaged)) {
9309 $tmparray = explode('@', $objecttmp->ismultientitymanaged);
9310 $sql .= " INNER JOIN " . $this->db->prefix() . $this->db->sanitize($tmparray[1]) . " as parenttable ON parenttable.rowid = t." . $this->db->sanitize($tmparray[0]);
9311 }
9312 }
9313
9314 // Add where from hooks
9315 $parameters = array(
9316 'object' => $objecttmp,
9317 'htmlname' => $htmlname,
9318 'filter' => $filter,
9319 'searchkey' => $searchkey
9320 );
9321
9322 $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
9323 if (!empty($hookmanager->resPrint)) {
9324 $sql .= $hookmanager->resPrint;
9325 } else {
9326 $sql .= " WHERE 1=1";
9327
9328 // If table need a multientity restriction
9329 if (!empty($objecttmp->ismultientitymanaged)) {
9330 if ($objecttmp->ismultientitymanaged == 1) {
9331 $sql .= " AND t.entity IN (" . getEntity($objecttmp->element) . ")";
9332 }
9333 if (!is_numeric($objecttmp->ismultientitymanaged)) {
9334 $sql .= " AND parenttable.entity = t." . $this->db->sanitize($tmparray[0]);
9335 }
9336 // If the parent table is llx_societe and user is not an external user (a more robust test done later for external users),
9337 // then we must also check that user has permissions
9338 if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
9339 if (!$user->hasRight('societe', 'client', 'voir') && empty($user->socid)) {
9340 $sql .= " AND EXISTS (SELECT sc.rowid FROM ".$this->db->prefix() . "societe_commerciaux as sc";
9341 $sql .= " WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $user->id).")";
9342 }
9343 }
9344 }
9345
9346 // If user is external user, we must also make a test on llx_societe_commerciaux
9347 if (!empty($user->socid)) {
9348 if ($objecttmp->element == 'societe') {
9349 $sql .= " AND t.rowid = " . ((int) $user->socid);
9350 } elseif (!empty($objecttmp->fields['fk_soc']) || !empty($objecttmp->fields['t.fk_soc']) || property_exists($objecttmp, 'fk_soc') || property_exists($objecttmp, 'socid')) {
9351 $sql .= " AND t.fk_soc = " . ((int) $user->socid);
9352 }
9353 }
9354
9355 $splittedfieldstoshow = explode(',', $fieldstoshow);
9356 foreach ($splittedfieldstoshow as &$field2) {
9357 if (is_numeric($pos = strpos($field2, ' '))) {
9358 $field2 = substr($field2, 0, $pos);
9359 }
9360 }
9361 if ($searchkey != '') {
9362 $sql .= natural_search($splittedfieldstoshow, $searchkey);
9363 }
9364
9365 if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
9366 $errormessage = '';
9367 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
9368 if ($errormessage) {
9369 return 'Error forging a SQL request from an universal criteria: ' . $errormessage;
9370 }
9371 }
9372 }
9373 $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, $sortorder);
9374 //$sql.=$this->db->plimit($limit, 0);
9375 //print $sql;
9376
9377 // Build output string
9378 $resql = $this->db->query($sql);
9379 if ($resql) {
9380 // Construct $out and $outarray
9381 $out .= '<select id="' . $htmlname . '" class="flat minwidth100' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ($moreparams ? ' ' . $moreparams : '') . ' name="' . $htmlname . '">' . "\n";
9382
9383 // 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
9384 $textifempty = '&nbsp;';
9385
9386 //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
9387 if (getDolGlobalInt($confkeyforautocompletemode)) {
9388 if ($showempty && !is_numeric($showempty)) {
9389 $textifempty = $langs->trans($showempty);
9390 } else {
9391 $textifempty .= $langs->trans("All");
9392 }
9393 }
9394 if ($showempty) {
9395 $out .= '<option value="-1">' . $textifempty . '</option>' . "\n";
9396 }
9397
9398 $num = $this->db->num_rows($resql);
9399 $i = 0;
9400 if ($num) {
9401 while ($i < $num) {
9402 $obj = $this->db->fetch_object($resql);
9403 $label = '';
9404 $labelhtml = '';
9405 $tmparray = explode(',', $fieldstoshow);
9406 $oldvalueforshowoncombobox = 0;
9407 foreach ($tmparray as $key => $val) {
9408 $val = preg_replace('/(t|p|o)\./', '', $val);
9409 $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
9410 $labelhtml .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
9411 $label .= $obj->$val;
9412 $labelhtml .= $obj->$val;
9413
9414 $oldvalueforshowoncombobox = empty($objecttmp->fields[$val]['showoncombobox']) ? 0 : $objecttmp->fields[$val]['showoncombobox'];
9415 }
9416 if (empty($outputmode)) {
9417 if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
9418 $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>';
9419 } else {
9420 $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
9421 }
9422 } else {
9423 array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label));
9424 }
9425
9426 $i++;
9427 if (($i % 10) == 0) {
9428 $out .= "\n";
9429 }
9430 }
9431 }
9432
9433 $out .= '</select>' . "\n";
9434
9435 if (!$forcecombo) {
9436 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
9437 $out .= ajax_combobox($htmlname, array(), getDolGlobalInt($confkeyforautocompletemode, 0));
9438 }
9439 } else {
9440 dol_print_error($this->db);
9441 }
9442
9443 $this->result = array('nbofelement' => $num);
9444
9445 if ($outputmode) {
9446 return $outarray;
9447 }
9448 return $out;
9449 }
9450
9461 public static function radio($htmlName, $radioItems, $selected = '', $moreGlobalParams = [])
9462 {
9463 // Default parameters for each radio input
9464 $defaultParams = [
9465 'disabled' => false,
9466 'attr' => [
9467 'type' => 'radio',
9468 'name' => $htmlName,
9469 ],
9470 'unescapedAttr' => [],
9471 'attrLabel' => [],
9472 'unescapedAttrLabel' => [],
9473 'labelIsHtml' => false
9474 ];
9475
9476 // Merge global parameters with defaults
9477 $params = array_merge_recursive_distinct($defaultParams, $moreGlobalParams);
9478
9479 $out = '';
9480 if (!empty($radioItems)) {
9481 foreach ($radioItems as $key => $item) {
9482 // Normalize item to array structure if it's a simple string
9483 if (!is_array($item)) {
9484 $item = [
9485 'attr' => [
9486 'value' => $key,
9487 ],
9488 'label' => $item
9489 ];
9490 }
9491
9492 // Default properties for individual item
9493 $defaultItem = [
9494 'attr' => [
9495 'value' => !isset($item['attr']['value']) ? $key : '',
9496 ],
9497 'label' => '',
9498 ];
9499
9500 // Merge defaults with global params and item-specific properties
9501 $defaultItem = array_merge_recursive_distinct($params, $defaultItem);
9502 $item = array_merge_recursive_distinct($defaultItem, $item);
9503
9504 // Determine if this radio should be checked
9505 if ((is_array($selected) && in_array($item['attr']['value'], $selected, true)) || $selected === $item['attr']['value']) {
9506 $item['attr']['checked'] = true;
9507 }
9508
9509 // Build HTML attributes for input and label
9510 $inputAttributes = implode(' ', commonHtmlAttributeBuilder($item['attr'], $item['unescapedAttr']));
9511 $labelAttributes = implode(' ', commonHtmlAttributeBuilder($item['attrLabel'], $item['unescapedAttrLabel']));
9512
9513 // prevent accidental Xss todo : escape $item['label'] but html friendly compatible
9514 $text = $item['labelIsHtml'] ? $item['label'] : htmlspecialchars($item['label'], ENT_QUOTES | ENT_SUBSTITUTE);
9515
9516 // Generate HTML
9517 $out .= '<label ' . $labelAttributes . '><input ' . $inputAttributes . ' /> ' . $text . '</label> ';
9518 }
9519 }
9520
9521 return $out;
9522 }
9523
9524
9548 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)
9549 {
9550 global $conf, $langs;
9551
9552 // Do we want a multiselect ?
9553 //$jsbeautify = 0;
9554 //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
9555 $jsbeautify = 1;
9556
9557 if ($value_as_key) {
9558 $array = array_combine($array, $array);
9559 }
9560
9561 '@phan-var-force array{label:string,data-html:string,disable?:int<0,1>,css?:string} $array'; // Array combine breaks information
9562
9563 $out = '';
9564
9565 if ($addjscombo < 0) {
9566 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
9567 $addjscombo = 1;
9568 } else {
9569 $addjscombo = 0;
9570 }
9571 }
9572 $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
9573 $out .= '<select id="' . preg_replace('/^\./', '', $idname) . '" ' . ($disabled ? 'disabled="disabled" ' : '') . 'class="flat ' . (preg_replace('/^\./', '', $htmlname)) . ($morecss ? ' ' . $morecss : '') . ' selectformat"';
9574 $out .= ' name="' . preg_replace('/^\./', '', $htmlname) . '" ' . ($moreparam ? $moreparam : '');
9575 $out .= '>'."\n";
9576
9577 if ($show_empty) {
9578 $textforempty = ' ';
9579 if (!empty($conf->use_javascript_ajax)) {
9580 $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
9581 }
9582 if (!is_numeric($show_empty)) {
9583 $textforempty = $show_empty;
9584 }
9585 $out .= '<option class="optiongrey" ' . ($moreparamonempty ? $moreparamonempty . ' ' : '') . 'value="' . (((int) $show_empty) < 0 ? $show_empty : -1) . '"' . ($id == $show_empty ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
9586 }
9587 if (is_array($array)) {
9588 // Translate
9589 if ($translate) {
9590 foreach ($array as $key => $value) {
9591 if (!is_array($value)) {
9592 $array[$key] = $langs->trans($value);
9593 } else {
9594 $array[$key]['label'] = $langs->trans($value['label']);
9595 }
9596 }
9597 }
9598 // Sort
9599 if ($sort == 'ASC') {
9600 asort($array);
9601 } elseif ($sort == 'DESC') {
9602 arsort($array);
9603 }
9604
9605 foreach ($array as $key => $tmpvalue) {
9606 if (is_array($tmpvalue)) {
9607 $value = $tmpvalue['label'];
9608 //$valuehtml = empty($tmpvalue['data-html']) ? $value : $tmpvalue['data-html'];
9609 $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
9610 $style = empty($tmpvalue['css']) ? '' : ' class="' . $tmpvalue['css'] . '"';
9611 } else {
9612 $value = $tmpvalue;
9613 //$valuehtml = $tmpvalue;
9614 $disabled = '';
9615 $style = '';
9616 }
9617 if (!empty($disablebademail)) {
9618 if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
9619 || ($disablebademail == 2 && preg_match('/---/', $value))) {
9620 $disabled = ' disabled';
9621 $style = ' class="warning"';
9622 }
9623 }
9624 if ($key_in_label) {
9625 if (empty($nohtmlescape)) {
9626 $selectOptionValue = dol_escape_htmltag($key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value));
9627 } else {
9628 $selectOptionValue = $key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value);
9629 }
9630 } else {
9631 if (empty($nohtmlescape)) {
9632 $selectOptionValue = dol_escape_htmltag($maxlen ? dol_trunc($value, $maxlen) : $value);
9633 } else {
9634 $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
9635 }
9636 if ($value == '' || $value == '-') {
9637 $selectOptionValue = '&nbsp;';
9638 }
9639 }
9640 $out .= '<option value="' . $key . '"';
9641 $out .= $style . $disabled;
9642 $out .= is_array($tmpvalue) && !empty($tmpvalue['parent']) ? ' parent="' . dolPrintHTMLForAttribute($tmpvalue['parent']) . '"' : '';
9643 if (is_array($id)) {
9644 if (in_array($key, $id) && !$disabled) {
9645 $out .= ' selected'; // To preselect a value
9646 }
9647 } else {
9648 $id = (string) $id; // if $id = 0, then $id = '0'
9649 if ($id != '' && (($id == (string) $key) || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
9650 $out .= ' selected'; // To preselect a value
9651 }
9652 }
9653
9654 if (is_array($tmpvalue)) {
9655 foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
9656 if ($keyforvalue == 'labelhtml') {
9657 $keyforvalue = 'data-html';
9658 }
9659 if (preg_match('/^data-/', $keyforvalue)) { // The best solution if you want to use HTML values into the list is to use data-html.
9660 $out .= ' '.dol_escape_htmltag($keyforvalue).'="'.dol_escape_htmltag($valueforvalue).'"';
9661 }
9662 }
9663 } elseif (!empty($nohtmlescape)) { // deprecated. Use instead the previous cas, an array with 'data-html', 'data-xxx' ... to use HTML content in the select
9664 $out .= ' data-html="' . dol_escape_htmltag($selectOptionValue) . '"';
9665 }
9666
9667 $out .= '>';
9668 $out .= $selectOptionValue;
9669 $out .= "</option>\n";
9670 }
9671 }
9672 $out .= "</select>";
9673
9674 // Add code for jquery to use multiselect
9675 if ($addjscombo && $jsbeautify) {
9676 // Enhance with select2
9677 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
9678 $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', (((int) $show_empty) < 0 ? (string) $show_empty : '-1'), $morecss);
9679 }
9680
9681 return $out;
9682 }
9683
9702 public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
9703 {
9704 global $conf;
9705 global $delayedhtmlcontent; // Will be used later outside of this function
9706
9707 // TODO Use an internal dolibarr component instead of select2
9708 if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
9709 return '';
9710 }
9711
9712 $out = '<select type="text" class="' . $htmlname . ($morecss ? ' ' . $morecss : '') . '" ' . ($moreparam ? $moreparam . ' ' : '') . 'name="' . $htmlname . '"></select>';
9713
9714 $outdelayed = '';
9715 if (!empty($conf->use_javascript_ajax)) {
9716 $tmpplugin = 'select2';
9717 $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
9718 <script nonce="' . getNonce() . '">
9719 $(document).ready(function () {
9720
9721 ' . ($callurlonselect ? 'var saveRemoteData = [];' : '') . '
9722
9723 $(".' . $htmlname . '").select2({
9724 ajax: {
9725 dir: "ltr",
9726 url: "' . $url . '",
9727 dataType: \'json\',
9728 delay: 250,
9729 data: function (params) {
9730 return {
9731 q: params.term, // search term
9732 page: params.page
9733 }
9734 },
9735 processResults: function (data) {
9736 // parse the results into the format expected by Select2.
9737 // since we are using custom formatting functions we do not need to alter the remote JSON data
9738 //console.log(data);
9739 saveRemoteData = data;
9740 /* format json result for select2 */
9741 result = []
9742 $.each( data, function( key, value ) {
9743 result.push({id: key, text: value.text});
9744 });
9745 //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
9746 //console.log(result);
9747 return {results: result, more: false}
9748 },
9749 cache: true
9750 },
9751 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage,
9752 containerCssClass: \':all:\', /* Line to add class from the original SELECT propagated to the new <span class="select2-selection...> tag */
9753 placeholder: \'' . dol_escape_js($placeholder) . '\',
9754 escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
9755 minimumInputLength: ' . ((int) $minimumInputLength) . ',
9756 formatResult: function (result, container, query, escapeMarkup) {
9757 return escapeMarkup(result.text);
9758 },
9759 });
9760
9761 ' . ($callurlonselect ? '
9762 /* Code to execute a GET when we select a value */
9763 $(".' . $htmlname . '").change(function() {
9764 var selected = $(\'.' . dol_escape_js($htmlname) . '\').val();
9765 console.log("We select in selectArrayAjax the entry "+selected)
9766 $(\'.' . dol_escape_js($htmlname) . '\').val(""); /* reset visible combo value */
9767 $.each( saveRemoteData, function( key, value ) {
9768 if (key == selected)
9769 {
9770 console.log("selectArrayAjax - Do a redirect to "+value.url)
9771 location.assign(value.url);
9772 }
9773 });
9774 });' : '') . '
9775
9776 });
9777 </script>';
9778 }
9779
9780 if ($acceptdelayedhtml) {
9781 $delayedhtmlcontent .= $outdelayed;
9782 } else {
9783 $out .= $outdelayed;
9784 }
9785 return $out;
9786 }
9787
9807 public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0, $textfortitle = '')
9808 {
9809 global $conf;
9810 global $delayedhtmlcontent; // Will be used later outside of this function
9811
9812 // TODO Use an internal dolibarr component instead of select2
9813 if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
9814 return '';
9815 }
9816
9817 $out = '<select type="text"'.($textfortitle ? ' title="'.dol_escape_htmltag($textfortitle).'"' : '').' id="'.$htmlname.'" class="'.$htmlname.($morecss ? ' ' . $morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.'"><option></option></select>';
9818
9819 $formattedarrayresult = array();
9820
9821 foreach ($array as $key => $value) {
9822 $o = new stdClass();
9823 $o->id = $key;
9824 $o->text = $value['text'];
9825 $o->url = $value['url'];
9826 $formattedarrayresult[] = $o;
9827 }
9828
9829 $outdelayed = '';
9830 if (!empty($conf->use_javascript_ajax)) {
9831 $tmpplugin = 'select2';
9832 $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
9833 <script nonce="' . getNonce() . '">
9834 $(document).ready(function () {
9835 var data = ' . json_encode($formattedarrayresult) . ';
9836
9837 ' . ($callurlonselect ? 'var saveRemoteData = ' . json_encode($array) . ';' : '') . '
9838
9839 $(\'.' . dol_escape_js($htmlname) . '\').select2({
9840 data: data,
9841 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage,
9842 containerCssClass: \':all:\', /* Line to add class from the original SELECT propagated to the new <span class="select2-selection...> tag */
9843 placeholder: \'' . dol_escape_js($placeholder) . '\',
9844 escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
9845 minimumInputLength: ' . ((int) $minimumInputLength) . ',
9846 formatResult: function (result, container, query, escapeMarkup) {
9847 return escapeMarkup(result.text);
9848 },
9849 matcher: function (params, data) {
9850
9851 if(! data.id) return null;';
9852
9853 if ($callurlonselect) {
9854 // We forge the url with 'sall='
9855 $outdelayed .= '
9856
9857 var urlBase = data.url;
9858 var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
9859 /* console.log("params.term="+params.term); */
9860 /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
9861 saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
9862 }
9863
9864 if (!$disableFiltering) {
9865 $outdelayed .= '
9866
9867 if(data.text.match(new RegExp(params.term))) {
9868 return data;
9869 }
9870
9871 return null;';
9872 } else {
9873 $outdelayed .= '
9874
9875 return data;';
9876 }
9877
9878 $outdelayed .= '
9879 }
9880 });
9881
9882 ' . ($callurlonselect ? '
9883 /* Code to execute a GET when we select a value */
9884 $(\'.' . dol_escape_js($htmlname) . '\').change(function() {
9885 var selected = $(\'.' . dol_escape_js($htmlname) . '\').val();
9886 console.log("We select "+selected)
9887
9888 $(\'.' . dol_escape_js($htmlname) . '\').val(""); /* reset visible combo value */
9889 $.each( saveRemoteData, function( key, value ) {
9890 if (key == selected)
9891 {
9892 console.log("selectArrayFilter - Do a redirect to "+value.url)
9893 location.assign(value.url);
9894 }
9895 });
9896 });' : '') . '
9897
9898 });
9899 </script>';
9900 }
9901
9902 if ($acceptdelayedhtml) {
9903 $delayedhtmlcontent .= $outdelayed;
9904 } else {
9905 $out .= $outdelayed;
9906 }
9907 return $out;
9908 }
9909
9928 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)
9929 {
9930 global $conf, $langs;
9931 $out = '';
9932
9933 if ($addjscombo < 0) {
9934 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
9935 $addjscombo = 1;
9936 } else {
9937 $addjscombo = 0;
9938 }
9939 }
9940
9941 $useenhancedmultiselect = 0;
9942 if (!empty($conf->use_javascript_ajax) && !defined('MAIN_DO_NOT_USE_JQUERY_MULTISELECT') && (getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT'))) {
9943 if ($addjscombo) {
9944 $useenhancedmultiselect = 1; // Use the js multiselect in one line. Possible only if $addjscombo not 0.
9945 }
9946 }
9947
9948 $out .= '<span class="multiselectarray'.$htmlname.'">';
9949
9950 // We need a hidden field because when using the multiselect, if we unselect all, there is no
9951 // variable submitted at all, so no way to make a difference between variable not submitted and variable
9952 // submitted to nothing.
9953 $out .= '<input type="hidden" name="'.$htmlname.'_multiselect" value="1">';
9954 // Output select component
9955 $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";
9956 if (is_array($array) && !empty($array)) {
9957 if ($value_as_key) {
9958 $array = array_combine($array, $array);
9959 }
9960
9961 if (!empty($array)) {
9962 foreach ($array as $key => $value) {
9963 $tmpkey = $key;
9964 $tmplabel = $value;
9965 $tmplabelhtml = '';
9966 $tmpcolor = '';
9967 $tmppicto = '';
9968 $tmpdisabled = '';
9969 if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
9970 $tmpkey = $value['id'];
9971 $tmplabel = empty($value['label']) ? '' : $value['label'];
9972 $tmplabelhtml = empty($value['labelhtml']) ? (empty($value['data-html']) ? '' : $value['data-html']) : $value['labelhtml'];
9973 $tmpcolor = empty($value['color']) ? '' : $value['color'];
9974 $tmppicto = empty($value['picto']) ? '' : $value['picto'];
9975 $tmpdisabled = empty($value['disabled']) ? '' : $value['disabled'];
9976 }
9977 $newval = ($translate ? $langs->trans($tmplabel) : $tmplabel);
9978 $newval = ($key_in_label ? $tmpkey . ' - ' . $newval : $newval);
9979
9980 $tmplabelhtml = ($translate ? $langs->trans($tmplabelhtml) : $tmplabelhtml);
9981 $tmplabelhtml = ($key_in_label ? $tmpkey . ' - ' . $tmplabelhtml : $tmplabelhtml);
9982
9983 $out .= '<option value="' . $tmpkey . '"';
9984 if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
9985 $out .= ' selected';
9986 }
9987 $out .= is_array($value) && array_key_exists('parent', $value) && !empty($value['parent']) ? ' parent="' . dolPrintHTMLForAttribute($value['parent']) . '"' : '';
9988 if ($tmpdisabled) {
9989 $out .= ' disabled="disabled"';
9990 }
9991 if (!empty($tmplabelhtml)) {
9992 $out .= ' data-html="' . dolPrintHTMLForAttribute($tmplabelhtml) . '"';
9993 } else {
9994 $tmplabelhtml = ($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #' . $tmpcolor . '"') : '') . $newval;
9995 $out .= ' data-html="' . dolPrintHTMLForAttribute($tmplabelhtml) . '"';
9996 }
9997 $out .= '>';
9998 $out .= dol_htmlentitiesbr($newval);
9999 $out .= '</option>' . "\n";
10000 }
10001 }
10002 }
10003 $out .= '</select>' . "\n";
10004
10005 $out .= '</span>';
10006
10007 // Add code for jquery to use multiselect
10008 if (!empty($conf->use_javascript_ajax) && getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT')) {
10009 $out .= "\n" . '<!-- JS CODE TO ENABLE select for id ' . $htmlname . ', addjscombo=' . $addjscombo . ' -->';
10010 $out .= "\n" . '<script nonce="' . getNonce() . '">' . "\n";
10011 if ($addjscombo == 1) {
10012 $tmpplugin = getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT', (defined('REQUIRE_JQUERY_MULTISELECT') ? constant('REQUIRE_JQUERY_MULTISELECT') : 'select2'));
10013
10014 // If property data-html set, we decode html entities and use this.
10015 // Note that HTML content must have been sanitized from js with dol_escape_htmltag(xxx, 0, 0, '', 0, 1) when building the select option.
10016 // TODO Move this into common js ?
10017 $out .= 'function formatResult(record, container) {' . "\n";
10018 $out .= ' if ($(record.element).attr("data-html") != undefined && typeof htmlEntityDecodeJs === "function") {';
10019 $out .= ' return htmlEntityDecodeJs($(record.element).attr("data-html"));';
10020 $out .= ' }'."\n";
10021 $out .= ' return record.text;';
10022 $out .= '}' . "\n";
10023
10024 $out .= 'function formatSelection(record) {' . "\n";
10025 $out .= ' return record.text;';
10026 $out .= '}' . "\n";
10027
10028 // Load the select2 enhancer
10029 //$out .= 'console.log(\'addjscombo=1 for htmlname=' . dol_escape_js($htmlname) . '\');';
10030 $out .= '$(document).ready(function () {
10031 $(\'#' . dol_escape_js($htmlname) . '\').' . $tmpplugin . '({';
10032 if ($placeholder) {
10033 $out .= '
10034 placeholder: {
10035 id: \'-1\',
10036 text: \''.dol_escape_js($placeholder).'\'
10037 },';
10038 }
10039 $out .= ' dir: \'ltr\',
10040 containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag (ko with multiselect) */
10041 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. */
10042 // Specify format function for dropdown item
10043 formatResult: formatResult,
10044 templateResult: formatResult, /* For 4.0 */
10045 escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
10046 // Specify format function for selected item
10047 formatSelection: formatSelection,
10048 templateSelection: formatSelection, /* For 4.0 */
10049 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage
10050 });
10051
10052 /* Add also morecss to the css .select2 that is after the #htmlname, for component that are shown dynamically after load, because select2 set
10053 the size only if component is not hidden by default on load */
10054 $(\'#' . dol_escape_js($htmlname) . ' + .select2\').addClass(\'' . dol_escape_js($morecss) . '\');
10055 });' . "\n";
10056 } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
10057 // Add other js lib
10058 // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
10059 // ...
10060 $out .= 'console.log(\'addjscombo=2 for htmlname=' . dol_escape_js($htmlname) . '\');';
10061 $out .= '$(document).ready(function () {
10062 $(\'#' . dol_escape_js($htmlname) . '\').multiSelect({
10063 containerHTML: \'<div class="multi-select-container">\',
10064 menuHTML: \'<div class="multi-select-menu">\',
10065 buttonHTML: \'<span class="multi-select-button ' . dol_escape_js($morecss) . '">\',
10066 menuItemHTML: \'<label class="multi-select-menuitem">\',
10067 activeClass: \'multi-select-container--open\',
10068 noneText: \'' . dol_escape_js($placeholder) . '\'
10069 });
10070 })';
10071 }
10072 $out .= '</script>';
10073 }
10074
10075 return $out;
10076 }
10077
10078
10090 public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
10091 {
10092 global $conf, $langs, $user;
10093
10094 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
10095 return '';
10096 }
10097 if (empty($array)) {
10098 return '';
10099 }
10100
10101 $tmpvar = "MAIN_SELECTEDFIELDS_" . $varpage; // To get list of saved selected fields to show
10102
10103 if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
10104 $tmparray = explode(',', $user->conf->$tmpvar);
10105 foreach ($array as $key => $val) {
10106 //var_dump($key);
10107 //var_dump($tmparray);
10108 if (in_array($key, $tmparray)) {
10109 $array[$key]['checked'] = 1;
10110 } else {
10111 $array[$key]['checked'] = 0;
10112 }
10113 }
10114 } else { // There is no list of fields already customized for user
10115 foreach ($array as $key => $val) {
10116 if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
10117 $array[$key]['checked'] = 0;
10118 }
10119 }
10120 }
10121
10122 $listoffieldsforselection = '';
10123 $listcheckedstring = '';
10124
10125 foreach ($array as $key => $val) {
10126 // var_dump($val);
10127 // var_dump(array_key_exists('enabled', $val));
10128 // var_dump(!$val['enabled']);
10129 if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
10130 unset($array[$key]); // We don't want this field
10131 continue;
10132 }
10133 if (!empty($val['type']) && $val['type'] == 'separate') {
10134 // Field remains in array but we don't add it into $listoffieldsforselection
10135 //$listoffieldsforselection .= '<li>-----</li>';
10136 continue;
10137 }
10138 if (!empty($val['label']) && $val['label']) {
10139 if (!empty($val['langfile']) && is_object($langs)) {
10140 $langs->load($val['langfile']);
10141 }
10142
10143 // Note: $val['checked'] <> 0 means we must show the field into the combo list @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
10144 $listoffieldsforselection .= '<li><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']).'" />';
10145 $listoffieldsforselection .= '<label for="checkbox' . $key . '" class="paddingleft">';
10146 $listoffieldsforselection .= dolPrintHTML(dol_string_nohtmltag($langs->trans($val['label'])));
10147 $listoffieldsforselection .= '</label></li>';
10148 $listcheckedstring .= (empty($val['checked']) ? '' : $key . ',');
10149 }
10150 }
10151
10152 $out = '<!-- Component multiSelectArrayWithCheckbox ' . $htmlname . ' -->
10153
10154 <dl class="dropdown">
10155 <dt>
10156 <a href="#' . $htmlname . '" class="multiselectpicto">
10157 ' . img_picto('', 'list') . '
10158 </a>
10159 <input type="hidden" class="' . $htmlname . '" name="' . $htmlname . '" value="' . $listcheckedstring . '">
10160 </dt>
10161 <dd class="dropdowndd">
10162 <div class="multiselectcheckbox'.$htmlname.'">
10163 <ul class="'.$htmlname.(((string) $pos == '1' || (string) $pos == 'left') ? 'left' : '').'">
10164 <li class="liinputsearch">
10165 <input class="inputsearch_dropdownselectedfields width90p minwidth200imp" style="width:90%;" type="text" placeholder="'.$langs->trans('Search').'">
10166 </li>
10167 '.$listoffieldsforselection.'
10168 </ul>
10169 </div>
10170 </dd>
10171 </dl>
10172
10173 <script nonce="' . getNonce() . '" type="text/javascript">
10174 jQuery(document).ready(function () {
10175 $(\'.multiselectcheckbox' . $htmlname . ' input[type="checkbox"]\').on("click", function () {
10176 console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
10177
10178 $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
10179
10180 var title = $(this).val() + ",";
10181 if ($(this).is(\':checked\')) {
10182 $(\'.' . $htmlname . '\').val(title + $(\'.' . $htmlname . '\').val());
10183 }
10184 else {
10185 $(\'.' . $htmlname . '\').val( $(\'.' . $htmlname . '\').val().replace(title, \'\') )
10186 }
10187 // Now, we submit page
10188 //$(this).parents(\'form:first\').submit();
10189 });
10190
10191 $("input.inputsearch_dropdownselectedfields").on("keyup", function() {
10192 console.log("keyup on inputsearch_dropdownselectedfields");
10193 var value = $(this).val().toLowerCase();
10194 $(\'.multiselectcheckbox'.$htmlname.' li > label\').filter(function() {
10195 $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
10196 });
10197 });
10198 ';
10199 if (empty($conf->browser->layout) || $conf->browser->layout != 'phone') {
10200 $out .= '
10201 $(".dropdown dt a").on("click", function () {
10202 console.log("Click on dropdown, we set focus to search field");
10203 setTimeout(() => { $(\'.inputsearch_dropdownselectedfields\').focus(); }, 200);
10204 });';
10205 }
10206 $out .= '
10207 });
10208 </script>
10209
10210 ';
10211 return $out;
10212 }
10213
10223 public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
10224 {
10225 include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
10226
10227 $cat = new Categorie($this->db);
10228 $categories = $cat->containing($id, $type);
10229
10230 if ($rendermode == 1) {
10231 $toprint = array();
10232 foreach ($categories as $c) {
10233 $ways = $c->print_all_ways('auto', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text
10234 foreach ($ways as $way) {
10235 $color = $c->color;
10236 $sfortag = '<li class="select2-search-choice-dolibarr noborderoncategories'.(empty($toprint) ? ' nomarginleft' : '').'"' . ($color ? ' style="background: #' . $color . ';"' : ' style="background: #bbb"') . '>';
10237 $sfortag .= $way;
10238 $sfortag .= '</li>';
10239 $toprint[] = $sfortag;
10240 }
10241 }
10242 if (empty($toprint)) {
10243 return '';
10244 } else {
10245 return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
10246 }
10247 }
10248
10249 if ($rendermode == 0) {
10250 $arrayselected = array();
10251 $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 3);
10252 foreach ($categories as $c) {
10253 $arrayselected[(string) $c->id] = (string) $c->id;
10254 }
10255
10256 return $this->multiselectarray('categories', $cate_arbo, $arrayselected, 0, 0, '', 0, '100%', 'disabled', 'category');
10257 }
10258
10259 return 'ErrorBadValueForParameterRenderMode'; // Should not happened
10260 }
10261
10271 public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = array(), $title = 'RelatedObjects')
10272 {
10273 global $conf, $langs, $hookmanager;
10274 global $action;
10275 global $db, $user; // Will be used into tpl
10276
10277 $object->fetchObjectLinked();
10278
10279 // Bypass the default method
10280 $hookmanager->initHooks(array('commonobject'));
10281 $parameters = array(
10282 'morehtmlright' => $morehtmlright,
10283 'compatibleImportElementsList' => &$compatibleImportElementsList,
10284 );
10285 $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
10286
10287 $nbofdifferenttypes = count($object->linkedObjects);
10288
10289 if (empty($reshook)) {
10290 print '<!-- showLinkedObjectBlock -->';
10291 print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, '', 'showlinkedobjectblock');
10292
10293
10294 print '<div class="div-table-responsive-no-min">';
10295 print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="' . $object->element . '" data-elementid="' . $object->id . '" >';
10296
10297 print '<tr class="liste_titre">';
10298 print '<td>' . $langs->trans("Type") . '</td>';
10299 print '<td>' . $langs->trans("Ref") . '</td>';
10300 print '<td class="center"></td>';
10301 print '<td class="center">' . $langs->trans("Date") . '</td>';
10302 print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
10303 print '<td class="right">' . $langs->trans("Status") . '</td>';
10304 print '<td></td>';
10305 print '</tr>';
10306
10307 $nboftypesoutput = 0;
10308
10309 foreach ($object->linkedObjects as $objecttype => $objects) {
10310 $tplpath = $element = $subelement = $objecttype;
10311
10312 // to display import button on tpl
10313 global $showImportButton; // Will be used into tpl
10314 $showImportButton = false;
10315 if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
10316 $showImportButton = true;
10317 }
10318
10319 $regs = array();
10320
10321 if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
10322 $element = $regs[1];
10323 $subelement = $regs[2];
10324 $tplpath = $element . '/' . $subelement;
10325 }
10326 $tplname = 'linkedobjectblock';
10327
10328 // If we ask a resource form external module (instead of default path)
10329 if (preg_match('/^([^@]+)@([^@]+)$/i', $objecttype, $regs)) { // 'myobject@mymodule'
10330 $element = $regs[1];
10331 $module = $regs[2];
10332 $tplpath = $module. '/' . $element;
10333 $tplname = $tplname.'_'.$element;
10334 }
10335
10336 // To work with non standard path
10337 if ($objecttype == 'facture') {
10338 $tplpath = 'compta/' . $element;
10339 if (!isModEnabled('invoice')) {
10340 continue; // Do not show if module disabled
10341 }
10342 } elseif ($objecttype == 'facturerec') {
10343 $tplpath = 'compta/facture';
10344 $tplname = 'linkedobjectblockForRec';
10345 if (!isModEnabled('invoice')) {
10346 continue; // Do not show if module disabled
10347 }
10348 } elseif ($objecttype == 'propal') {
10349 $tplpath = 'comm/' . $element;
10350 if (!isModEnabled('propal')) {
10351 continue; // Do not show if module disabled
10352 }
10353 } elseif ($objecttype == 'supplier_proposal') {
10354 if (!isModEnabled('supplier_proposal')) {
10355 continue; // Do not show if module disabled
10356 }
10357 } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
10358 $tplpath = 'expedition';
10359 if (!isModEnabled('shipping')) {
10360 continue; // Do not show if module disabled
10361 }
10362 } elseif ($objecttype == 'reception') {
10363 $tplpath = 'reception';
10364 if (!isModEnabled('reception')) {
10365 continue; // Do not show if module disabled
10366 }
10367 } elseif ($objecttype == 'delivery') {
10368 $tplpath = 'delivery';
10369 if (!getDolGlobalInt('MAIN_SUBMODULE_DELIVERY')) {
10370 continue; // Do not show if sub module disabled
10371 }
10372 } elseif ($objecttype == 'ficheinter') {
10373 $tplpath = 'fichinter';
10374 if (!isModEnabled('intervention')) {
10375 continue; // Do not show if module disabled
10376 }
10377 } elseif ($objecttype == 'invoice_supplier') {
10378 $tplpath = 'fourn/facture';
10379 } elseif ($objecttype == 'order_supplier') {
10380 $tplpath = 'fourn/commande';
10381 } elseif ($objecttype == 'expensereport') {
10382 $tplpath = 'expensereport';
10383 } elseif ($objecttype == 'subscription') {
10384 $tplpath = 'adherents';
10385 } elseif ($objecttype == 'conferenceorbooth') {
10386 $tplpath = 'eventorganization';
10387 } elseif ($objecttype == 'conferenceorboothattendee') {
10388 $tplpath = 'eventorganization';
10389 } elseif ($objecttype == 'mo') {
10390 $tplpath = 'mrp';
10391 if (!isModEnabled('mrp')) {
10392 continue; // Do not show if module disabled
10393 }
10394 } elseif ($objecttype == 'project_task') {
10395 $tplpath = 'projet/tasks';
10396 }
10397
10398 global $linkedObjectBlock; // Will be used into tpl
10399 $linkedObjectBlock = $objects;
10400
10401 // Output template part (modules that overwrite templates must declare this into descriptor)
10402 $dirtpls = array_merge($conf->modules_parts['tpl'], array('/' . $tplpath . '/tpl'));
10403
10404 foreach ($dirtpls as $reldir) {
10405 $reldir = rtrim($reldir, '/');
10406 if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
10407 global $noMoreLinkedObjectBlockAfter; // Will be used into tpl
10408 $noMoreLinkedObjectBlockAfter = 1;
10409 }
10410 $file = dol_buildpath($reldir . '/' . $tplname . '.tpl.php');
10411 if (file_exists($file)) {
10412 $res = @include $file;
10413 if ($res) {
10414 $nboftypesoutput++;
10415 break;
10416 }
10417 }
10418 }
10419 }
10420
10421 if (!$nboftypesoutput) {
10422 print '<tr><td colspan="7"><span class="opacitymedium">' . $langs->trans("None") . '</span></td></tr>';
10423 }
10424
10425 print '</table>';
10426
10427 if (!empty($compatibleImportElementsList)) {
10428 $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
10429 }
10430
10431 print '</div>';
10432 }
10433
10434 return $nbofdifferenttypes;
10435 }
10436
10446 public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array(), $nooutput = 0)
10447 {
10448 global $conf, $langs, $hookmanager, $form;
10449 global $action;
10450
10451 if (empty($form)) {
10452 $form = new Form($this->db);
10453 }
10454
10455 $linktoelem = '';
10456 $linktoelemlist = '';
10457 $listofidcompanytoscan = '';
10458
10459 if (!is_object($object->thirdparty)) {
10460 $object->fetch_thirdparty();
10461 }
10462
10463 $possiblelinks = array();
10464
10465 $dontIncludeCompletedItems = getDolGlobalString('DONT_INCLUDE_COMPLETED_ELEMENTS_LINKS');
10466
10467 if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
10468 $listofidcompanytoscan = (int) $object->thirdparty->id;
10469 if (($object->thirdparty->parent > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PARENT_IN_LINKTO')) {
10470 $listofidcompanytoscan .= ',' . (int) $object->thirdparty->parent;
10471 }
10472 if (($object->fk_project > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO')) {
10473 include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
10474 $tmpproject = new Project($this->db);
10475 $tmpproject->fetch($object->fk_project);
10476 if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
10477 $listofidcompanytoscan .= ',' . (int) $tmpproject->socid;
10478 }
10479 unset($tmpproject);
10480 }
10481
10482 $possiblelinks = array(
10483 'propal' => array(
10484 'enabled' => isModEnabled('propal'),
10485 'perms' => 1,
10486 'label' => 'LinkToProposal',
10487 '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' : ''),
10488 ),
10489 'shipping' => array(
10490 'enabled' => isModEnabled('shipping'),
10491 'perms' => 1,
10492 'label' => 'LinkToExpedition',
10493 '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' : ''),
10494 ),
10495 'order' => array(
10496 'enabled' => isModEnabled('order'),
10497 'perms' => 1,
10498 'label' => 'LinkToOrder',
10499 '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' : ''),
10500 'linkname' => 'commande',
10501 'subscription' => array(
10502 'enabled' => isModEnabled('member'),
10503 'perms' => 1,
10504 'label' => 'LinkToMemberSubscription',
10505 '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') . ')',
10506 'linkname' => 'subscription'),
10507 ),
10508 'invoice' => array(
10509 'enabled' => isModEnabled('invoice'),
10510 'perms' => 1,
10511 'label' => 'LinkToInvoice',
10512 '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' : ''),
10513 'linkname' => 'facture',
10514 ),
10515 'invoice_template' => array(
10516 'enabled' => isModEnabled('invoice'),
10517 'perms' => 1,
10518 'label' => 'LinkToTemplateInvoice',
10519 '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') . ')',
10520 ),
10521 'contrat' => array(
10522 'enabled' => isModEnabled('contract'),
10523 'perms' => 1,
10524 'label' => 'LinkToContract',
10525 '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
10526 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',
10527 ),
10528 'fichinter' => array(
10529 'enabled' => isModEnabled('intervention'),
10530 'perms' => 1,
10531 'label' => 'LinkToIntervention',
10532 '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') . ')',
10533 ),
10534 'supplier_proposal' => array(
10535 'enabled' => isModEnabled('supplier_proposal'),
10536 'perms' => 1,
10537 'label' => 'LinkToSupplierProposal',
10538 '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' : ''),
10539 ),
10540 'order_supplier' => array(
10541 'enabled' => isModEnabled("supplier_order"),
10542 'perms' => 1,
10543 'label' => 'LinkToSupplierOrder',
10544 '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' : ''),
10545 ),
10546 'invoice_supplier' => array(
10547 'enabled' => isModEnabled("supplier_invoice"),
10548 'perms' => 1, 'label' => 'LinkToSupplierInvoice',
10549 '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' : ''),
10550 ),
10551 'ticket' => array(
10552 'enabled' => isModEnabled('ticket'),
10553 'perms' => 1,
10554 'label' => 'LinkToTicket',
10555 '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' : ''),
10556 ),
10557 'mo' => array(
10558 'enabled' => isModEnabled('mrp'),
10559 'perms' => 1,
10560 'label' => 'LinkToMo',
10561 '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' : ''),
10562 ),
10563 );
10564 }
10565
10566 if ($object->table_element == 'commande_fournisseur') {
10567 $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' : '');
10568 } elseif ($object->table_element == 'mrp_mo') {
10569 $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' : '');
10570 }
10571
10572 $reshook = 0; // Ensure $reshook is defined for static analysis
10573 if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
10574 // Can complete the possiblelink array
10575 $hookmanager->initHooks(array('commonobject'));
10576 $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
10577 $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
10578 }
10579
10580 if (empty($reshook)) {
10581 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
10582 $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
10583 }
10584 } elseif ($reshook > 0) {
10585 if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
10586 $possiblelinks = $hookmanager->resArray;
10587 }
10588 }
10589
10590 if (!empty($possiblelinks)) {
10591 $object->fetchObjectLinked();
10592 }
10593
10594 // Build the html part with possible suggested links
10595 $htmltoenteralink = '';
10596 foreach ($possiblelinks as $key => $possiblelink) {
10597 $num = 0;
10598 if (empty($possiblelink['enabled'])) {
10599 continue;
10600 }
10601
10602
10603 // If we ask a resource form external module (instead of default path)
10604 $module = '';
10605 if (preg_match('/^([^@]+)@([^@]+)$/i', $key, $regs)) { // 'myobject@mymodule'
10606 $key = $regs[1];
10607 $module = $regs[2];
10608 }
10609
10610 if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
10611 $htmltoenteralink .= '<div id="' . $key . 'list"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display:none"') . '>';
10612
10613 // Section for free ref input
10614 if (!getDolGlobalString('MAIN_HIDE_LINK_BY_REF_IN_LINKTO')) {
10615 $htmltoenteralink .= '<br>'."\n";
10616 $htmltoenteralink .= '<!-- form to add a link from anywhere -->'."\n";
10617 $htmltoenteralink .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
10618 $htmltoenteralink .= '<input type="hidden" name="token" value="' . newToken() . '">';
10619 $htmltoenteralink .= '<input type="hidden" name="action" value="addlinkbyref">';
10620 $htmltoenteralink .= '<input type="hidden" name="id" value="' . $object->id . '">';
10621 $htmltoenteralink .= '<input type="hidden" name="addlink" value="' . $key .(!empty($module) ? '@'.$module : ''). '">';
10622 $htmltoenteralink .= '<table class="noborder">';
10623 $htmltoenteralink .= '<tr class="liste_titre">';
10624 //print '<td>' . $langs->trans("Ref") . '</td>';
10625 $htmltoenteralink .= '<td class="center"><input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Ref")).'" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;';
10626 $htmltoenteralink .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;';
10627 $htmltoenteralink .= '<input type="submit" class="button smallpaddingimp" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
10628 $htmltoenteralink .= '</tr>';
10629 $htmltoenteralink .= '</table>';
10630 $htmltoenteralink .= '</form>';
10631 }
10632
10633 $sql = $possiblelink['sql'];
10634
10635 $resqllist = $this->db->query($sql);
10636 if ($resqllist) {
10637 $num = $this->db->num_rows($resqllist);
10638 $i = 0;
10639
10640 if ($num > 0) {
10641 // Section for free predefined list
10642 if (getDolGlobalString('MAIN_HIDE_LINK_BY_REF_IN_LINKTO')) {
10643 $htmltoenteralink .= '<br>';
10644 }
10645 $htmltoenteralink .= '<!-- form to add a link from object to same thirdparty -->'."\n";
10646 $htmltoenteralink .= '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinked' . $key . '">';
10647 $htmltoenteralink .= '<input type="hidden" name="token" value="' . newToken() . '">';
10648 $htmltoenteralink .= '<input type="hidden" name="action" value="addlink">';
10649 $htmltoenteralink .= '<input type="hidden" name="id" value="' . $object->id . '">';
10650 $htmltoenteralink .= '<input type="hidden" name="addlink" value="' . $key . (!empty($module) ? '@'.$module : ''). '">';
10651 $htmltoenteralink .= '<table class="noborder">';
10652 $htmltoenteralink .= '<tr class="liste_titre">';
10653 $htmltoenteralink .= '<td class="nowrap"></td>';
10654 $htmltoenteralink .= '<td>' . $langs->trans("Ref") . '</td>';
10655 $htmltoenteralink .= '<td>' . $langs->trans("RefCustomer") . '</td>';
10656 $htmltoenteralink .= '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
10657 $htmltoenteralink .= '<td>' . $langs->trans("Company") . '</td>';
10658 $htmltoenteralink .= '</tr>';
10659 while ($i < $num) {
10660 $objp = $this->db->fetch_object($resqllist);
10661 $alreadylinked = false;
10662 if (!empty($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key])) {
10663 if (in_array($objp->rowid, array_values($object->linkedObjectsIds[$possiblelink['linkname'] ?? $key]))) {
10664 $alreadylinked = true;
10665 }
10666 }
10667 $htmltoenteralink .= '<tr class="oddeven">';
10668 $htmltoenteralink .= '<td>';
10669 if ($alreadylinked) {
10670 $htmltoenteralink .= img_picto('', 'link');
10671 } else {
10672 $htmltoenteralink .= '<input type="checkbox" name="idtolinkto[' . $key . '_' . $objp->rowid . ']" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
10673 }
10674 $htmltoenteralink .= '</td>';
10675 $htmltoenteralink .= '<td><label for="' . $key . '_' . $objp->rowid . '">' . $objp->ref . '</label></td>';
10676 $htmltoenteralink .= '<td>' . (!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')) . '</td>';
10677 $htmltoenteralink .= '<td class="right">';
10678 if ($possiblelink['label'] == 'LinkToContract') {
10679 $htmltoenteralink .= $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")) . ' ';
10680 }
10681 $htmltoenteralink .= '<span class="amount">' . (isset($objp->total_ht) ? price($objp->total_ht) : '') . '</span>';
10682 $htmltoenteralink .= '</td>';
10683 $htmltoenteralink .= '<td>' . $objp->name . '</td>';
10684 $htmltoenteralink .= '</tr>';
10685 $i++;
10686 }
10687 $htmltoenteralink .= '</table>';
10688 $htmltoenteralink .= '<div class="center">';
10689 if ($num) {
10690 $htmltoenteralink .= '<input type="submit" class="button valignmiddle marginleftonly marginrightonly smallpaddingimp" value="' . $langs->trans('ToLink') . '">';
10691 }
10692 if (empty($conf->use_javascript_ajax)) {
10693 $htmltoenteralink .= '<input type="submit" class="button button-cancel marginleftonly marginrightonly smallpaddingimp" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
10694 } else {
10695 $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>';
10696 }
10697 $htmltoenteralink .= '</form>';
10698 }
10699
10700 $this->db->free($resqllist);
10701 } else {
10702 dol_print_error($this->db);
10703 }
10704 $htmltoenteralink .= '</div>';
10705
10706
10707 // Complete the list for the combo box
10708 if ($num > 0 || !getDolGlobalString('MAIN_HIDE_LINK_BY_REF_IN_LINKTO')) {
10709 $linktoelemlist .= '<li><a href="#linkto' . $key . '" class="linkto dropdowncloseonclick" rel="' . $key . '">' . $langs->trans($possiblelink['label']) . ' (' . $num . ')</a></li>';
10710 // } else $linktoelem.=$langs->trans($possiblelink['label']);
10711 } else {
10712 $linktoelemlist .= '<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
10713 }
10714 }
10715 }
10716
10717 if ($linktoelemlist) {
10718 $linktoelem = '
10719 <dl class="dropdown" id="linktoobjectname">
10720 ';
10721 if (!empty($conf->use_javascript_ajax)) {
10722 $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>' . $langs->trans("LinkTo") . '...</a></dt>';
10723 }
10724 $linktoelem .= '<dd>
10725 <div class="multiselectlinkto">
10726 <ul class="ulselectedfields">' . $linktoelemlist . '
10727 </ul>
10728 </div>
10729 </dd>
10730 </dl>';
10731 } else {
10732 $linktoelem = '';
10733 }
10734
10735 if (!empty($conf->use_javascript_ajax)) {
10736 print '<!-- Add js to show linkto box -->
10737 <script nonce="' . getNonce() . '">
10738 jQuery(document).ready(function() {
10739 jQuery(".linkto").click(function() {
10740 console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
10741 jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
10742 });
10743 });
10744 </script>
10745 ';
10746 }
10747
10748 if ($nooutput) {
10749 return array('linktoelem' => $linktoelem, 'htmltoenteralink' => $htmltoenteralink);
10750 } else {
10751 print $htmltoenteralink;
10752 }
10753
10754 return $linktoelem;
10755 }
10756
10771 public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = 'yesno width75', $labelyes = 'Yes', $labelno = 'No')
10772 {
10773 global $langs;
10774
10775 $yes = "yes";
10776 $no = "no";
10777 if ($option) {
10778 $yes = "1";
10779 $no = "0";
10780 }
10781
10782 $disabled = ($disabled ? ' disabled' : '');
10783
10784 $resultyesno = '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '"' . $disabled . '>' . "\n";
10785 if ($useempty) {
10786 $resultyesno .= '<option value="-1"' . (($value < 0) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
10787 }
10788 if (("$value" == 'yes') || ($value == 1)) {
10789 $resultyesno .= '<option value="' . $yes . '" selected>' . $langs->trans($labelyes) . '</option>' . "\n";
10790 $resultyesno .= '<option value="' . $no . '">' . $langs->trans($labelno) . '</option>' . "\n";
10791 } else {
10792 $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
10793 $resultyesno .= '<option value="' . $yes . '">' . $langs->trans($labelyes) . '</option>' . "\n";
10794 $resultyesno .= '<option value="' . $no . '"' . $selected . '>' . $langs->trans($labelno) . '</option>' . "\n";
10795 }
10796 $resultyesno .= '</select>' . "\n";
10797
10798 if ($addjscombo) {
10799 $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
10800 }
10801
10802 return $resultyesno;
10803 }
10804
10805 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
10806
10816 public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
10817 {
10818 // phpcs:enable
10819 $sql = "SELECT rowid, label";
10820 $sql .= " FROM " . $this->db->prefix() . "export_model";
10821 $sql .= " WHERE type = '" . $this->db->escape($type) . "'";
10822 $sql .= " ORDER BY rowid";
10823 $result = $this->db->query($sql);
10824 if ($result) {
10825 print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
10826 if ($useempty) {
10827 print '<option value="-1">&nbsp;</option>';
10828 }
10829
10830 $num = $this->db->num_rows($result);
10831 $i = 0;
10832 while ($i < $num) {
10833 $obj = $this->db->fetch_object($result);
10834 if ($selected == $obj->rowid) {
10835 print '<option value="' . $obj->rowid . '" selected>';
10836 } else {
10837 print '<option value="' . $obj->rowid . '">';
10838 }
10839 print $obj->label;
10840 print '</option>';
10841 $i++;
10842 }
10843 print "</select>";
10844 } else {
10845 dol_print_error($this->db);
10846 }
10847 }
10848
10867 public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
10868 {
10869 global $conf, $langs, $hookmanager, $extralanguages;
10870
10871 $ret = '';
10872 if (empty($fieldid)) {
10873 $fieldid = 'rowid';
10874 }
10875 if (empty($fieldref)) {
10876 $fieldref = 'ref';
10877 }
10878
10879 // Preparing gender's display if there is one
10880 $addgendertxt = '';
10881 if (property_exists($object, 'gender') && !empty($object->gender)) {
10882 $addgendertxt = ' ';
10883 switch ($object->gender) {
10884 case 'man':
10885 $addgendertxt .= '<i class="fas fa-mars valignmiddle"></i>';
10886 break;
10887 case 'woman':
10888 $addgendertxt .= '<i class="fas fa-venus valignmiddle"></i>';
10889 break;
10890 case 'other':
10891 $addgendertxt .= '<i class="fas fa-transgender valignmiddle"></i>';
10892 break;
10893 }
10894 }
10895
10896 // Add where from hooks
10897 if (is_object($hookmanager)) {
10898 $parameters = array('showrefnav' => true);
10899 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
10900 if (!empty($hookmanager->resPrint)) {
10901 if (empty($object->next_prev_filter) && preg_match('/^\s*AND/i', $hookmanager->resPrint)) {
10902 $object->next_prev_filter = preg_replace('/^\s*AND\s*/i', '', $hookmanager->resPrint);
10903 } elseif (!empty($object->next_prev_filter) && !preg_match('/^\s*AND/i', $hookmanager->resPrint)) {
10904 $object->next_prev_filter .= ' AND '.$hookmanager->resPrint;
10905 } else {
10906 $object->next_prev_filter .= $hookmanager->resPrint;
10907 }
10908 }
10909 }
10910
10911 $previous_ref = $next_ref = '';
10912 if ($shownav) {
10913 //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,fieldid=$fieldid,filedref=$fieldref,morehtmlref=$morehtmlref,moreparam=$moreparam";
10914 $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
10915
10916 $navurl = $_SERVER["PHP_SELF"];
10917
10918 // Special case for token card
10919 if ($paramid == 'api_token_card') {
10920 if (preg_match('/\/user\/api_token/', $navurl)) {
10921 $navurl = preg_replace('/card/', 'list', $navurl);
10922 $paramid = 'id';
10923 }
10924 }
10925
10926 // Special case for project/task page
10927 if ($paramid == 'project_ref') {
10928 if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
10929 $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
10930 $paramid = 'ref';
10931 }
10932 }
10933
10934 $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>';
10935 $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>';
10936 }
10937
10938 //print "xx".$previous_ref."x".$next_ref;
10939 $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
10940
10941 // Right part of banner
10942 if ($morehtmlright) {
10943 $ret .= '<div class="inline-block floatleft">' . $morehtmlright . '</div>';
10944 }
10945
10946 if ($previous_ref || $next_ref || $morehtml) {
10947 $ret .= '<div class="pagination paginationref"><ul class="right">';
10948 }
10949 if ($morehtml && getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) {
10950 $ret .= '<!-- morehtml --><li class="noborder litext' . (($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '') . '">' . $morehtml . '</li>';
10951 }
10952 if ($shownav && ($previous_ref || $next_ref)) {
10953 $ret .= '<li class="pagination">' . $previous_ref . '</li>';
10954 $ret .= '<li class="pagination">' . $next_ref . '</li>';
10955 }
10956 if ($previous_ref || $next_ref || $morehtml) {
10957 $ret .= '</ul></div>';
10958 }
10959
10960 // Status
10961 $parameters = array('morehtmlstatus' => $morehtmlstatus);
10962 $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
10963 if (empty($reshook)) {
10964 $morehtmlstatus .= $hookmanager->resPrint;
10965 } else {
10966 $morehtmlstatus = $hookmanager->resPrint;
10967 }
10968 if ($morehtmlstatus) {
10969 $ret .= '<!-- status --><div class="statusref">' . $morehtmlstatus . '</div>';
10970 }
10971
10972 $parameters = array();
10973 $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
10974 if (empty($reshook)) {
10975 $morehtmlref .= $hookmanager->resPrint;
10976 } elseif ($reshook > 0) {
10977 $morehtmlref = $hookmanager->resPrint;
10978 }
10979
10980 // Left part of banner
10981 if ($morehtmlleft) {
10982 if ($conf->browser->layout == 'phone') {
10983 $ret .= '<!-- morehtmlleft --><div class="floatleft">' . $morehtmlleft . '</div>';
10984 } else {
10985 $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">' . $morehtmlleft . '</div>';
10986 }
10987 }
10988
10989 //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
10990 $ret .= '<!-- Ref or ID --><div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid' . (($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '') . '">';
10991
10992 // For thirdparty, contact, user, member, the ref is the id, so we show something else
10993 if ($object->element == 'societe') {
10994 $ret .= '<span class="valignmiddle">'.dol_htmlentities((string) $object->name).'</span>';
10995
10996 // List of extra languages
10997 $arrayoflangcode = array();
10998 if (getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE')) {
10999 $arrayoflangcode[] = getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE');
11000 }
11001
11002 if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
11003 if (!is_object($extralanguages)) {
11004 include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
11005 $extralanguages = new ExtraLanguages($this->db);
11006 }
11007 $extralanguages->fetch_name_extralanguages('societe');
11008
11009 // Guard against PHP 8 'Undefined array key' when MAIN_USE_ALTERNATE_TRANSLATION_FOR
11010 // is not configured and fetch_name_extralanguages() leaves attributes empty (issue #34596).
11011 if (!empty($extralanguages->attributes['societe']) && !empty($extralanguages->attributes['societe']['name'])) {
11012 $object->fetchValuesForExtraLanguages();
11013
11014 $htmltext = '';
11015 // If there is extra languages
11016 foreach ($arrayoflangcode as $extralangcode) {
11017 $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
11018 if ($object->array_languages['name'][$extralangcode]) {
11019 $htmltext .= $object->array_languages['name'][$extralangcode];
11020 } else {
11021 $htmltext .= '<span class="opacitymedium">' . $langs->trans("SwitchInEditModeToAddTranslation") . '</span>';
11022 }
11023 }
11024 $ret .= '<!-- Show translations of name -->' . "\n";
11025 $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
11026 }
11027 }
11028 } elseif ($object->element == 'member') {
11029 '@phan-var-force Adherent $object';
11030 $ret .= $object->ref . '<br>';
11031 $fullname = $object->getFullName($langs);
11032 if ($object->morphy == 'mor' && $object->societe) {
11033 $ret .= '<span class="valignmiddle">'.dol_htmlentities((string) $object->societe) . ((!empty($fullname) && $object->societe != $fullname) ? ' (' . dol_htmlentities($fullname) . $addgendertxt . ')' : '').'</span>';
11034 } else {
11035 $ret .= '<span class="valignmiddle">'.dol_htmlentities($fullname) . $addgendertxt . ((!empty($object->societe) && $object->societe != $fullname) ? ' (' . dol_htmlentities((string) $object->societe) . ')' : '').'</span>';
11036 }
11037 } elseif (in_array($object->element, array('contact', 'user'))) {
11038 $ret .= '<span class="valignmiddle">'.dol_htmlentities($object->getFullName($langs)).'</span>'.$addgendertxt;
11039 } elseif ($object->element == 'usergroup') {
11040 $ret .= dol_htmlentities((string) $object->name);
11041 } elseif (in_array($object->element, array('action', 'agenda'))) {
11042 '@phan-var-force ActionComm $object';
11043 $ret .= $object->ref . '<br>' . $object->label;
11044 } elseif (in_array($object->element, array('adherent_type'))) {
11045 $ret .= $object->label;
11046 } elseif ($object->element == 'ecm_directories') {
11047 $ret .= '';
11048 } elseif ($object->element == 'accountingbookkeeping' && !empty($object->context['mode']) && $object->context['mode'] == '_tmp') {
11049 $ret .= '<span class="valignmiddle">'.$langs->trans("Draft").'</span>';
11050 } elseif ($fieldref != 'none') {
11051 $ret .= '<span class="valignmiddle">'.dol_htmlentities(!empty($object->$fieldref) ? $object->$fieldref : "").'</span>';
11052 }
11053 if ($morehtmlref) {
11054 // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
11055 if (substr($morehtmlref, 0, 4) != '<div') {
11056 $ret .= ' ';
11057 }
11058
11059 $ret .= '<!-- morehtmlref -->'.$morehtmlref;
11060 }
11061
11062 $ret .= '</div>';
11063
11064 $ret .= '</div><!-- End banner content -->';
11065
11066 return $ret;
11067 }
11068
11069
11078 public function showbarcode(&$object, $width = 100, $morecss = '')
11079 {
11080 global $conf;
11081
11082 //Check if barcode is filled in the card
11083 if (empty($object->barcode)) {
11084 return '';
11085 }
11086
11087 // Complete object if not complete
11088 if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
11089 // @phan-suppress-next-line PhanPluginUnknownObjectMethodCall
11090 $result = $object->fetchBarCode();
11091 //Check if fetchBarCode() failed
11092 if ($result < 1) {
11093 return '<!-- ErrorFetchBarcode -->';
11094 }
11095 }
11096
11097 // Barcode image @phan-suppress-next-line PhanUndeclaredProperty
11098 $url = DOL_URL_ROOT . '/viewimage.php?modulepart=barcode&generator=' . urlencode($object->barcode_type_coder) . '&code=' . urlencode($object->barcode) . '&encoding=' . urlencode($object->barcode_type_code);
11099 $out = '<!-- url barcode = ' . $url . ' -->';
11100 $out .= '<img src="' . $url . '"' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
11101
11102 return $out;
11103 }
11104
11123 public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0, $usesharelinkifavailable = 0)
11124 {
11125 global $conf, $db, $langs;
11126
11127 $entity = (empty($object->entity) ? $conf->entity : $object->entity);
11128 $id = (empty($object->id) ? $object->rowid : $object->id); // @phan-suppress-current-line PhanUndeclaredProperty (->rowid)
11129
11130 $dir = '';
11131 $file = '';
11132 $originalfile = '';
11133 $altfile = '';
11134 $email = '';
11135 $capture = '';
11136 if ($modulepart == 'societe') {
11137 $dir = $conf->societe->multidir_output[$entity];
11138 if (!empty($object->logo)) {
11139 if (dolIsAllowedForPreview($object->logo)) {
11140 if ((string) $imagesize == 'mini') {
11141 $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
11142 } elseif ((string) $imagesize == 'small') {
11143 $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_small');
11144 } else {
11145 $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
11146 }
11147 $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
11148 }
11149 }
11150 $email = $object->email;
11151 } elseif ($modulepart == 'contact') {
11152 $dir = $conf->societe->multidir_output[$entity] . '/contact';
11153 $photo = $object->photo; // Copy to help static analysis
11154 if (!empty($photo)) {
11155 if (dolIsAllowedForPreview($photo)) {
11156 if ((string) $imagesize == 'mini') {
11157 $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($photo, '_mini');
11158 } elseif ((string) $imagesize == 'small') {
11159 $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($photo, '_small');
11160 } else {
11161 $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $photo;
11162 }
11163 $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $photo;
11164 }
11165 }
11166 $email = $object->email;
11167 $capture = 'user';
11168 } elseif ($modulepart == 'userphoto') {
11169 $dir = $conf->user->dir_output;
11170 $photo = $object->photo; // Copy to help static analysis
11171 if (!empty($photo)) {
11172 if (dolIsAllowedForPreview($photo)) {
11173 if ((string) $imagesize == 'mini') {
11174 $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($photo, '_mini');
11175 } elseif ((string) $imagesize == 'small') {
11176 $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($photo, '_small');
11177 } else {
11178 $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $photo;
11179 }
11180 $originalfile = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $photo;
11181 }
11182 }
11183 if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
11184 $altfile = $object->id . ".jpg"; // For backward compatibility
11185 }
11186 $email = $object->email;
11187 $capture = 'user';
11188 } elseif ($modulepart == 'memberphoto') {
11189 $dir = $conf->adherent->dir_output;
11190 $photo = $object->photo; // Copy to help static analysis
11191 if (!empty($photo)) {
11192 if (dolIsAllowedForPreview($photo)) {
11193 if ((string) $imagesize == 'mini') {
11194 $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($photo, '_mini');
11195 } elseif ((string) $imagesize == 'small') {
11196 $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($photo, '_small');
11197 } else {
11198 $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $photo;
11199 }
11200 $originalfile = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $photo;
11201 }
11202 }
11203 if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
11204 $altfile = $object->id . ".jpg"; // For backward compatibility
11205 }
11206 $email = $object->email;
11207 $capture = 'user';
11208 } else {
11209 // Generic case to show photos
11210 // TODO Implement this method in previous objects so we can always use this generic method.
11211 if ($modulepart != "unknown" && method_exists($object, 'getDataToShowPhoto')) {
11212 $tmpdata = $object->getDataToShowPhoto($modulepart, $imagesize);
11213
11214 $dir = $tmpdata['dir'];
11215 $file = $tmpdata['file'];
11216 $originalfile = $tmpdata['originalfile'];
11217 $altfile = $tmpdata['altfile'];
11218 $email = $tmpdata['email'];
11219 $capture = $tmpdata['capture'];
11220 }
11221 }
11222
11223 if ($forcecapture) {
11224 $capture = $forcecapture;
11225 }
11226
11227 $ret = '';
11228
11229 if ($dir) {
11230 if ($file && file_exists($dir . "/" . $file)) {
11231 if ($addlinktofullsize) {
11232 $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
11233 if ($urladvanced) {
11234 $ret .= '<a href="' . $urladvanced . '">';
11235 } else {
11236 $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
11237 }
11238 }
11239
11240 $sharekey = '';
11241 if ($usesharelinkifavailable) {
11242 // $dir is a full path '/home/.../dolibarr_documents/module'
11243 $relativefileforecm = preg_replace('/^'.preg_quote(DOL_DATA_ROOT.'/', '/').'/', '', $dir.'/'.$originalfile);
11244 // $relativefileforecme = 'module/...'
11245 require_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
11246 $ecmfiles = new EcmFiles($db);
11247 $ecmfiles->fetch(0, '', $relativefileforecm);
11248
11249 $sharekey = (string) $ecmfiles->share;
11250 }
11251
11252 if (!empty($sharekey)) {
11253 $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) . '">';
11254 } else {
11255 $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=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($file) . '&cache=' . $cache . '">';
11256 }
11257 if ($addlinktofullsize) {
11258 $ret .= '</a>';
11259 }
11260 } elseif ($altfile && file_exists($dir . "/" . $altfile)) {
11261 if ($addlinktofullsize) {
11262 $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
11263 if ($urladvanced) {
11264 $ret .= '<a href="' . $urladvanced . '">';
11265 } else {
11266 $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
11267 }
11268 }
11269 $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="Photo alt" id="photologo' . (preg_replace('/[^a-z]/i', '_', $file)) . '" class="' . $cssclass . '" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($altfile) . '&cache=' . $cache . '">';
11270 if ($addlinktofullsize) {
11271 $ret .= '</a>';
11272 }
11273 } else {
11274 $nophoto = '/public/theme/common/nophoto.png';
11275 $defaultimg = 'identicon'; // For gravatar
11276 if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
11277 if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && !empty($object->morphy) && strpos($object->morphy, 'mor') !== false)) {
11278 $nophoto = 'company';
11279 } else {
11280 $nophoto = '/public/theme/common/user_anonymous.png';
11281 if (!empty($object->gender) && $object->gender == 'man') {
11282 $nophoto = '/public/theme/common/user_man.png';
11283 }
11284 if (!empty($object->gender) && $object->gender == 'woman') {
11285 $nophoto = '/public/theme/common/user_woman.png';
11286 }
11287 }
11288 }
11289
11290 if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
11291 // see https://gravatar.com/site/implement/images/php/
11292 $ret .= '<!-- Put link to gravatar -->';
11293 $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
11294 } else {
11295 if ($nophoto == 'company') {
11296 $ret .= '<div class="divforspanimg valignmiddle center photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . '>' . img_picto('', 'company') . '</div>';
11297 //$ret .= '<div class="difforspanimgright"></div>';
11298 } else {
11299 $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . $nophoto . '">';
11300 }
11301 }
11302 }
11303
11304 if ($caneditfield) {
11305 if ($object->photo) {
11306 $ret .= "<br>\n";
11307 }
11308 $ret .= '<table class="nobordernopadding centpercent">';
11309 if ($object->photo) {
11310 $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">' . $langs->trans("Delete") . '</label><br><br></td></tr>';
11311 }
11312 $ret .= '<tr><td class="tdoverflow">';
11313 $maxfilesizearray = getMaxFileSizeArray();
11314 $maxmin = $maxfilesizearray['maxmin'];
11315 if ($maxmin > 0) {
11316 $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">'; // MAX_FILE_SIZE must precede the field type=file
11317 }
11318 $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"' . ($capture ? ' capture="' . dolPrintHTMLForAttribute($capture) . '"' : '') . '>';
11319 $ret .= '</td></tr>';
11320 $ret .= '</table>';
11321 }
11322 }
11323
11324 return $ret;
11325 }
11326
11327 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
11328
11345 public function select_dolgroups($selected = 0, $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0', $multiple = false, $morecss = 'minwidth200')
11346 {
11347 // phpcs:enable
11348 global $conf, $user, $langs;
11349
11350 // Allow excluding groups
11351 $excludeGroups = null;
11352 if (is_array($exclude)) {
11353 $excludeGroups = implode(",", $exclude);
11354 }
11355 // Allow including groups
11356 $includeGroups = null;
11357 if (is_array($include)) {
11358 $includeGroups = implode(",", $include);
11359 }
11360
11361 if (!is_array($selected)) {
11362 $selected = array($selected);
11363 }
11364
11365 $out = '';
11366
11367 // Build sql to search groups
11368 $sql = "SELECT ug.rowid, ug.nom as name";
11369 if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
11370 $sql .= ", e.label";
11371 }
11372 $sql .= " FROM " . $this->db->prefix() . "usergroup as ug ";
11373 if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
11374 $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid=ug.entity";
11375 if ($force_entity) {
11376 $sql .= " WHERE ug.entity IN (0, " . $force_entity . ")";
11377 } else {
11378 $sql .= " WHERE ug.entity IS NOT NULL";
11379 }
11380 } else {
11381 $sql .= " WHERE ug.entity IN (0, " . $conf->entity . ")";
11382 }
11383 if (is_array($exclude) && $excludeGroups) {
11384 $sql .= " AND ug.rowid NOT IN (" . $this->db->sanitize($excludeGroups) . ")";
11385 }
11386 if (is_array($include) && $includeGroups) {
11387 $sql .= " AND ug.rowid IN (" . $this->db->sanitize($includeGroups) . ")";
11388 }
11389 $sql .= " ORDER BY ug.nom ASC";
11390
11391 dol_syslog(get_class($this) . "::select_dolgroups", LOG_DEBUG);
11392 $resql = $this->db->query($sql);
11393 if ($resql) {
11394 // Enhance with select2
11395 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
11396
11397 $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
11398
11399 $num = $this->db->num_rows($resql);
11400 $i = 0;
11401 if ($num) {
11402 if ($show_empty && !$multiple) {
11403 $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
11404 }
11405
11406 while ($i < $num) {
11407 $obj = $this->db->fetch_object($resql);
11408 $disableline = 0;
11409 if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
11410 $disableline = 1;
11411 }
11412
11413 $label = $obj->name;
11414 $labelhtml = $obj->name;
11415 if (isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1) {
11416 $label .= " (" . $obj->label . ")";
11417 $labelhtml .= ' <span class="opacitymedium">(' . $obj->label . ')</span>';
11418 }
11419
11420 $out .= '<option value="' . $obj->rowid . '"';
11421 if ($disableline) {
11422 $out .= ' disabled';
11423 }
11424 if ((isset($selected[0]) && is_object($selected[0]) && $selected[0]->id == $obj->rowid)
11425 || ((!isset($selected[0]) || !is_object($selected[0])) && !empty($selected) && in_array($obj->rowid, $selected))) {
11426 $out .= ' selected';
11427 }
11428 $out .= ' data-html="'.dol_escape_htmltag($labelhtml).'"';
11429 $out .= '>';
11430 $out .= $label;
11431 $out .= '</option>';
11432 $i++;
11433 }
11434 } else {
11435 if ($show_empty) {
11436 $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '></option>' . "\n";
11437 }
11438 $out .= '<option value="" disabled>' . $langs->trans("NoUserGroupDefined") . '</option>';
11439 }
11440 $out .= '</select>';
11441
11442 $out .= ajax_combobox($htmlname);
11443 } else {
11444 dol_print_error($this->db);
11445 }
11446
11447 return $out;
11448 }
11449
11450
11457 public function showFilterButtons($pos = '')
11458 {
11459 $out = '<div class="nowraponall">';
11460 $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fas fa-search"></span></button>';
11461 $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fas fa-times"></span></button>';
11462 $out .= '</div>';
11463
11464 return $out;
11465 }
11466
11475 public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
11476 {
11477 global $conf;
11478
11479 $out = '';
11480
11481 if (!empty($conf->use_javascript_ajax)) {
11482 $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="' . $cssclass . 's" name="' . $cssclass . 's" class="checkallactions"></div>';
11483 }
11484 $out .= '<script nonce="' . getNonce() . '">
11485 $(document).ready(function() {
11486 $("#' . $cssclass . 's").click(function() {
11487 if($(this).is(\':checked\')){
11488 console.log("We check all ' . $cssclass . ' and trigger the change method");
11489 $(".' . $cssclass . '").prop(\'checked\', true).trigger(\'change\');
11490 }
11491 else
11492 {
11493 console.log("We uncheck all");
11494 $(".' . $cssclass . '").prop(\'checked\', false).trigger(\'change\');
11495 }' . "\n";
11496 if ($calljsfunction) {
11497 $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "' . $massactionname . '", "' . $cssclass . '"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
11498 }
11499 $out .= ' });
11500/*
11501 $(".' . $cssclass . '").change(function() {
11502 console.log("We check and change the tr class highlight after a change on .'.$cssclass.'");
11503 var $row = $(this).closest("tr");
11504 if ($row.length) {
11505 var anyChecked = $row.find(\'input[type="checkbox"].checkforselect:checked\').length > 0;
11506 console.log("anychecked="+anyChecked);
11507 if (!anyChecked) {
11508 $row.removeClass("highlight");
11509 } else {
11510 $row.addClass("highlight");
11511 }
11512 }
11513 });
11514*/
11515 });
11516 </script>';
11517
11518 return $out;
11519 }
11520
11530 public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
11531 {
11532 $out = $this->showFilterButtons();
11533 if ($addcheckuncheckall) {
11534 $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
11535 }
11536 return $out;
11537 }
11538
11552 public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
11553 {
11554 global $langs, $user;
11555
11556 $out = '';
11557 $sql = "SELECT rowid, label FROM " . $this->db->prefix() . "c_exp_tax_cat WHERE active = 1";
11558 $sql .= " AND entity IN (0," . getEntity('exp_tax_cat') . ")";
11559 if (!empty($excludeid)) {
11560 $sql .= " AND rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeid)) . ")";
11561 }
11562 $sql .= " ORDER BY label";
11563
11564 $resql = $this->db->query($sql);
11565 if ($resql) {
11566 $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp maxwidth200">';
11567 if ($useempty) {
11568 $out .= '<option value="0">&nbsp;</option>';
11569 }
11570
11571 while ($obj = $this->db->fetch_object($resql)) {
11572 $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . $langs->trans($obj->label) . '</option>';
11573 }
11574 $out .= '</select>';
11575 $out .= ajax_combobox('select_' . $htmlname);
11576
11577 if (!empty($htmlname) && $user->admin && $info_admin) {
11578 $out .= ' ' . info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
11579 }
11580
11581 if (!empty($target)) {
11582 $sql = "SELECT c.id FROM " . $this->db->prefix() . "c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
11583 $resql = $this->db->query($sql);
11584 if ($resql) {
11585 if ($this->db->num_rows($resql) > 0) {
11586 $obj = $this->db->fetch_object($resql);
11587 $out .= '<script nonce="' . getNonce() . '">
11588 $(function() {
11589 $("select[name=' . $target . ']").on("change", function() {
11590 var current_val = $(this).val();
11591 if (current_val == ' . $obj->id . ') {';
11592 if (!empty($default_selected) || !empty($selected)) {
11593 $out .= '$("select[name=' . $htmlname . ']").val("' . ($default_selected > 0 ? $default_selected : $selected) . '");';
11594 }
11595
11596 $out .= '
11597 $("select[name=' . $htmlname . ']").change();
11598 }
11599 });
11600
11601 $("select[name=' . $htmlname . ']").change(function() {
11602
11603 if ($("select[name=' . $target . ']").val() == ' . $obj->id . ') {
11604 // get price of kilometer to fill the unit price
11605 $.ajax({
11606 method: "POST",
11607 dataType: "json",
11608 data: { fk_c_exp_tax_cat: $(this).val(), token: \'' . currentToken() . '\' },
11609 url: "' . (DOL_URL_ROOT . '/expensereport/ajax/ajaxik.php?' . implode('&', $params)) . '",
11610 }).done(function( data, textStatus, jqXHR ) {
11611 console.log(data);
11612 if (typeof data.up != "undefined") {
11613 $("input[name=value_unit]").val(data.up);
11614 $("select[name=' . $htmlname . ']").attr("title", data.title);
11615 } else {
11616 $("input[name=value_unit]").val("");
11617 $("select[name=' . $htmlname . ']").attr("title", "");
11618 }
11619 });
11620 }
11621 });
11622 });
11623 </script>';
11624 }
11625 }
11626 }
11627 } else {
11628 dol_print_error($this->db);
11629 }
11630
11631 return $out;
11632 }
11633
11642 public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
11643 {
11644 global $conf, $langs;
11645
11646 $out = '';
11647 $sql = "SELECT rowid, range_ik FROM " . $this->db->prefix() . "c_exp_tax_range";
11648 $sql .= " WHERE entity = " . $conf->entity . " AND active = 1";
11649
11650 $resql = $this->db->query($sql);
11651 if ($resql) {
11652 $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
11653 if ($useempty) {
11654 $out .= '<option value="0"></option>';
11655 }
11656
11657 while ($obj = $this->db->fetch_object($resql)) {
11658 $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . price($obj->range_ik, 0, $langs, 1, 0) . '</option>';
11659 }
11660 $out .= '</select>';
11661 } else {
11662 dol_print_error($this->db);
11663 }
11664
11665 return $out;
11666 }
11667
11678 public function selectExpenseFees($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
11679 {
11680 global $langs;
11681
11682 $out = '';
11683 $sql = "SELECT id, code, label";
11684 $sql .= " FROM ".$this->db->prefix()."c_type_fees";
11685 $sql .= " WHERE active = 1";
11686
11687 $resql = $this->db->query($sql);
11688 if ($resql) {
11689 $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
11690 if ($useempty) {
11691 $out .= '<option value="0"></option>';
11692 }
11693 if ($allchoice) {
11694 $out .= '<option value="-1">' . $langs->trans('AllExpenseReport') . '</option>';
11695 }
11696
11697 $field = 'code';
11698 if ($useid) {
11699 $field = 'id';
11700 }
11701
11702 while ($obj = $this->db->fetch_object($resql)) {
11703 $key = $langs->trans($obj->code);
11704 $out .= '<option ' . ($selected == $obj->{$field} ? 'selected="selected"' : '') . ' value="' . $obj->{$field} . '">' . ($key != $obj->code ? $key : $obj->label) . '</option>';
11705 }
11706 $out .= '</select>';
11707
11708 $out .= ajax_combobox('select_'.$htmlname);
11709 } else {
11710 dol_print_error($this->db);
11711 }
11712
11713 return $out;
11714 }
11715
11734 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)
11735 {
11736 global $user, $conf, $langs;
11737
11738 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
11739
11740 if (is_null($usertofilter)) {
11741 $usertofilter = $user;
11742 }
11743
11744 $out = '';
11745
11746 $hideunselectables = false;
11747 if (getDolGlobalString('INVOICE_HIDE_UNSELECTABLES')) {
11748 $hideunselectables = true;
11749 }
11750
11751 if (empty($projectsListId)) {
11752 if (!$usertofilter->hasRight('projet', 'all', 'lire')) {
11753 $projectstatic = new Project($this->db);
11754 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
11755 }
11756 }
11757
11758 // Search all projects
11759 $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";
11760 $sql .= " FROM " . $this->db->prefix() . "facture as f";
11761 $sql .= " INNER JOIN " . $this->db->prefix() . "projet as p ON p.entity IN (" . getEntity('project') . ") AND f.fk_projet = p.rowid";
11762 $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON s.rowid = p.fk_soc";
11763 $sql .= " WHERE f.fk_statut = 0"; // Draft invoices only
11764 //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
11765 //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
11766 //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
11767 $sql .= " ORDER BY p.ref, f.ref ASC";
11768
11769 $resql = $this->db->query($sql);
11770 if ($resql) {
11771 // Use select2 selector
11772 if (!empty($conf->use_javascript_ajax)) {
11773 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
11774 $comboenhancement = ajax_combobox($htmlname, array(), 0, $forcefocus);
11775 $out .= $comboenhancement;
11776 $morecss = 'minwidth200imp maxwidth500';
11777 }
11778
11779 if (empty($option_only)) {
11780 $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
11781 }
11782 if (!empty($show_empty)) {
11783 $out .= '<option value="0" class="optiongrey">';
11784 if (!is_numeric($show_empty)) {
11785 $out .= $show_empty;
11786 } else {
11787 $out .= '&nbsp;';
11788 }
11789 $out .= '</option>';
11790 }
11791 $num = $this->db->num_rows($resql);
11792 $i = 0;
11793 if ($num) {
11794 while ($i < $num) {
11795 $obj = $this->db->fetch_object($resql);
11796 // 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.
11797 if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && !$usertofilter->hasRight('societe', 'lire')) {
11798 // Do nothing
11799 } else {
11800 if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
11801 $i++;
11802 continue;
11803 }
11804
11805 $labeltoshow = '';
11806
11807 if ($showproject == 'all') {
11808 $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
11809 if ($obj->name) {
11810 $labeltoshow .= ' - ' . $obj->name; // Soc name
11811 }
11812
11813 $disabled = 0;
11814 if ($obj->fk_statut == Project::STATUS_DRAFT) {
11815 $disabled = 1;
11816 $labeltoshow .= ' - ' . $langs->trans("Draft");
11817 } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
11818 if ($discard_closed == 2) {
11819 $disabled = 1;
11820 }
11821 $labeltoshow .= ' - ' . $langs->trans("Closed");
11822 } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
11823 $disabled = 1;
11824 $labeltoshow .= ' - ' . $langs->trans("LinkedToAnotherCompany");
11825 }
11826 }
11827
11828 if (!empty($selected) && $selected == $obj->rowid) {
11829 $out .= '<option value="' . $obj->rowid . '" selected';
11830 //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
11831 $out .= '>' . $labeltoshow . '</option>';
11832 } else {
11833 if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
11834 $resultat = '';
11835 } else {
11836 $resultat = '<option value="' . $obj->rowid . '"';
11837 if ($disabled) {
11838 $resultat .= ' disabled';
11839 }
11840 //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
11841 //else $labeltoshow.=' ('.$langs->trans("Private").')';
11842 $resultat .= '>';
11843 $resultat .= $labeltoshow;
11844 $resultat .= '</option>';
11845 }
11846 $out .= $resultat;
11847 }
11848 }
11849 $i++;
11850 }
11851 }
11852 if (empty($option_only)) {
11853 $out .= '</select>';
11854 }
11855
11856 $this->db->free($resql);
11857
11858 return $out;
11859 } else {
11860 dol_print_error($this->db);
11861 return '';
11862 }
11863 }
11864
11879 public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
11880 {
11881 global $conf, $langs;
11882
11883 $out = '';
11884
11885 dol_syslog('FactureRec::fetch', LOG_DEBUG);
11886
11887 $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
11888 $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
11889 $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
11890 $sql .= " ORDER BY f.titre ASC";
11891
11892 $resql = $this->db->query($sql);
11893 if ($resql) {
11894 // Use select2 selector
11895 if (!empty($conf->use_javascript_ajax)) {
11896 include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
11897 $comboenhancement = ajax_combobox($htmlname, array(), 0, $forcefocus);
11898 $out .= $comboenhancement;
11899 $morecss = 'minwidth200imp maxwidth500';
11900 }
11901
11902 if (empty($option_only)) {
11903 $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
11904 }
11905 if (!empty($show_empty)) {
11906 $out .= '<option value="0" class="optiongrey">';
11907 if (!is_numeric($show_empty)) {
11908 $out .= $show_empty;
11909 } else {
11910 $out .= '&nbsp;';
11911 }
11912 $out .= '</option>';
11913 }
11914 $num = $this->db->num_rows($resql);
11915 if ($num) {
11916 while ($obj = $this->db->fetch_object($resql)) {
11917 $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
11918
11919 $disabled = 0;
11920 if (!empty($obj->suspended)) {
11921 $disabled = 1;
11922 $labeltoshow .= ' - ' . $langs->trans("Closed");
11923 }
11924
11925
11926 if (!empty($selected) && $selected == $obj->rowid) {
11927 $out .= '<option value="' . $obj->rowid . '" selected';
11928 //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
11929 $out .= '>' . $labeltoshow . '</option>';
11930 } else {
11931 if ($disabled && ($selected != $obj->rowid)) {
11932 $resultat = '';
11933 } else {
11934 $resultat = '<option value="' . $obj->rowid . '"';
11935 if ($disabled) {
11936 $resultat .= ' disabled';
11937 }
11938 $resultat .= '>';
11939 $resultat .= $labeltoshow;
11940 $resultat .= '</option>';
11941 }
11942 $out .= $resultat;
11943 }
11944 }
11945 }
11946 if (empty($option_only)) {
11947 $out .= '</select>';
11948 }
11949
11950 print $out;
11951
11952 $this->db->free($resql);
11953 return $num;
11954 } else {
11955 $this->errors[] = $this->db->lasterror;
11956 return -1;
11957 }
11958 }
11959
11960
11971 public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '', $arrayoffiltercriterias = array())
11972 {
11973 // TODO: Use $arrayoffiltercriterias param instead of $arrayofcriterias to include linked object fields in search
11974 global $langs, $form;
11975
11976 //require_once DOL_DOCUMENT_ROOT."/core/class/html.formother.class.php";
11977 //$formother = new FormOther($this->db);
11978
11979 if ($search_component_params_hidden != '' && !preg_match('/^\‍(.*\‍)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
11980 $search_component_params_hidden = '(' . $search_component_params_hidden . ')';
11981 }
11982
11983 $ret = '<!-- searchComponent -->';
11984
11985 $ret .= '<div class="divadvancedsearchfieldcomp centpercent inline-block">';
11986 $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
11987 $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="' . dol_escape_htmltag($langs->trans("Filters")) . '" id="idsubimgproductdistribution"></span>';
11988 $ret .= '</a>';
11989
11990 $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
11991
11992 // Show select fields as tags.
11993 $ret .= '<div id="divsearch_component_params" name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
11994
11995 if ($search_component_params_hidden) {
11996 // Split the criteria on each AND
11997 //var_dump($search_component_params_hidden);
11998
11999 $arrayofandtags = dolForgeExplodeAnd($search_component_params_hidden);
12000
12001 // $arrayofandtags is now array( '...' , '...', ...)
12002 // Show each AND part
12003 foreach ($arrayofandtags as $tmpkey => $tmpval) {
12004 $errormessage = '';
12005 $searchtags = forgeSQLFromUniversalSearchCriteria($tmpval, $errormessage, 1, 1);
12006 if ($errormessage) {
12007 $this->error = 'ERROR in parsing search string: '.$errormessage;
12008 }
12009 // Remove first and last parenthesis but only if first is the opening and last the closing of the same group
12010 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
12011 $searchtags = removeGlobalParenthesis($searchtags);
12012
12013 $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch" data-ufilterid="'.($tmpkey + 1).'" data-ufilter="'.dol_escape_htmltag($tmpval).'">';
12014 $ret .= '<span class="tagsearchdelete select2-selection__choice__remove" data-ufilterid="'.($tmpkey + 1).'">x</span> ';
12015 $ret .= dol_escape_htmltag($searchtags);
12016 $ret .= '</span>';
12017 }
12018 }
12019
12020 //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
12021
12022 //$ret .= search_component_params
12023 //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
12024 //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
12025
12026 $show_search_component_params_hidden = 1;
12027 if ($show_search_component_params_hidden) {
12028 $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
12029 }
12030 $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%')) -->";
12031 $ret .= '<input type="hidden" id="search_component_params_hidden" name="search_component_params_hidden" value="' . dol_escape_htmltag($search_component_params_hidden) . '">';
12032 // $ret .= "<!-- sql= ".forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage)." -->";
12033
12034 // TODO : Use $arrayoffiltercriterias instead of $arrayofcriterias
12035 // For compatibility with forms that show themself the search criteria in addition of this component, we output these fields
12036 foreach ($arrayofcriterias as $criteria) {
12037 foreach ($criteria as $criteriafamilykey => $criteriafamilyval) {
12038 if (in_array('search_' . $criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
12039 continue;
12040 }
12041 if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
12042 continue;
12043 }
12044 if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
12045 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_start">';
12046 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startyear">';
12047 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startmonth">';
12048 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startday">';
12049 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_end">';
12050 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endyear">';
12051 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endmonth">';
12052 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endday">';
12053 } else {
12054 $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '">';
12055 }
12056 }
12057 }
12058
12059 $ret .= '</div>';
12060
12061 $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";
12062 $ret .= '<input type="text" placeholder="' . $langs->trans("Filters") . '" id="search_component_params_input" name="search_component_params_input" class="noborderall search_component_input" value="">';
12063
12064 $ret .= '</div>';
12065 $ret .= '</div>';
12066
12067 $ret .= '<script>
12068 jQuery(".tagsearchdelete").click(function(e) {
12069 var filterid = $(this).parents().attr("data-ufilterid");
12070 console.log("We click to delete the criteria nb "+filterid);
12071
12072 // Regenerate the search_component_params_hidden with all data-ufilter except the one to delete, and post the page
12073 var newparamstring = \'\';
12074 $(\'.tagsearch\').each(function(index, element) {
12075 tmpfilterid = $(this).attr("data-ufilterid");
12076 if (tmpfilterid != filterid) {
12077 // We keep this criteria
12078 if (newparamstring == \'\') {
12079 newparamstring = $(this).attr("data-ufilter");
12080 } else {
12081 newparamstring = newparamstring + \' AND \' + $(this).attr("data-ufilter");
12082 }
12083 }
12084 });
12085 console.log("newparamstring = "+newparamstring);
12086
12087 jQuery("#search_component_params_hidden").val(newparamstring);
12088
12089 // We repost the form
12090 $(this).closest(\'form\').submit();
12091 });
12092
12093 jQuery("#search_component_params_input").keydown(function(e) {
12094 console.log("We press a key on the filter field that is "+jQuery("#search_component_params_input").val());
12095 console.log(e.which);
12096 if (jQuery("#search_component_params_input").val() == "" && e.which == 8) {
12097 /* We click on back when the input field is already empty */
12098 event.preventDefault();
12099 jQuery("#divsearch_component_params .tagsearch").last().remove();
12100 /* Regenerate content of search_component_params_hidden from remaining .tagsearch */
12101 var s = "";
12102 jQuery("#divsearch_component_params .tagsearch").each(function( index ) {
12103 if (s != "") {
12104 s = s + " AND ";
12105 }
12106 s = s + $(this).attr("data-ufilter");
12107 });
12108 console.log("New value for search_component_params_hidden = "+s);
12109 jQuery("#search_component_params_hidden").val(s);
12110 }
12111 });
12112
12113 </script>
12114 ';
12115
12116 // Convert $arrayoffiltercriterias into a json object that can be used in jquery to build the search component dynamically
12117 $arrayoffiltercriterias_json = json_encode($arrayoffiltercriterias);
12118 $ret .= '<script>
12119 var arrayoffiltercriterias = ' . $arrayoffiltercriterias_json . ';
12120 </script>';
12121
12122
12123 $arrayoffilterfieldslabel = array();
12124 foreach ($arrayoffiltercriterias as $key => $val) {
12125 $arrayoffilterfieldslabel[$key]['label'] = $val['label'];
12126 $arrayoffilterfieldslabel[$key]['data-type'] = $val['type'];
12127 }
12128
12129 // Adding the div for search assistance
12130 $ret .= '<div class="search-component-assistance">';
12131 $ret .= '<div>';
12132
12133 $ret .= '<p class="assistance-title">' . img_picto('', 'filter') . ' ' . $langs->trans('FilterAssistance') . ' </p>';
12134
12135 $ret .= '<p class="assistance-errors error" style="display:none">' . $langs->trans('AllFieldsRequired') . ' </p>';
12136
12137 $ret .= '<div class="operand">';
12138 $ret .= $form->selectarray('search_filter_field', $arrayoffilterfieldslabel, '', $langs->trans("Fields"), 0, 0, '', 0, 0, 0, '', 'width200 combolargeelem', 1);
12139 $ret .= '</div>';
12140
12141 $ret .= '<span class="separator"></span>';
12142
12143 // Operator selector (will be populated dynamically)
12144 $ret .= '<div class="operator">';
12145 $ret .= '<select class="operator-selector width150" id="operator-selector"">';
12146 $ret .= '</select>';
12147 $ret .= '<script>$(document).ready(function() {';
12148 $ret .= ' $(".operator-selector").select2({';
12149 $ret .= ' placeholder: \'' . dol_escape_js($langs->transnoentitiesnoconv('Operator')) . '\'';
12150 $ret .= ' });';
12151 $ret .= '});</script>';
12152 $ret .= '</div>';
12153
12154 $ret .= '<span class="separator"></span>';
12155
12156 $ret .= '<div class="value">';
12157 // Input field for entering values
12158 $ret .= '<input type="text" class="flat width100 value-input" placeholder="' . dolPrintHTML($langs->trans('Value')) . '">';
12159
12160 // Date selector
12161 $dateOne = '';
12162 $ret .= '<span class="date-one" style="display:none">';
12163 $ret .= $form->selectDate(($dateOne ? $dateOne : -1), 'dateone', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '');
12164 $ret .= '</span>';
12165
12166 // Value selector (will be populated dynamically) based on search_filter_field value if a selected value has an array of values
12167 $ret .= '<select class="value-selector width150" id="value-selector" style="display:none">';
12168 $ret .= '</select>';
12169 $ret .= '<script>
12170 $(document).ready(function() {
12171 $("#value-selector").select2({
12172 placeholder: "' . dol_escape_js($langs->trans('Value')) . '"
12173 });
12174 $("#value-selector").hide();
12175 $("#value-selector").next(".select2-container").hide();
12176 });
12177 </script>';
12178
12179 $ret .= '</div>';
12180
12181 $ret .= '<div class="btn-div">';
12182 $ret .= '<button class="button buttongen button-save add-filter-btn" type="button">' . $langs->trans("addToFilter") . '</button>';
12183 $ret .= '</div>';
12184
12185 $ret .= '</div>';
12186 //$ret .= '</tbody></table>';
12187
12188 // End of the assistance div
12189 $ret .= '</div>';
12190
12191 // Script jQuery to show/hide the floating assistance
12192 $ret .= '<script>
12193 $(document).ready(function() {
12194 $("#search_component_params_input").on("click", function() {
12195 const inputPosition = $(this).offset();
12196 const inputHeight = $(this).outerHeight();
12197 $(".search-component-assistance").css({
12198 top: inputPosition.top + inputHeight + 5 + "px",
12199 left: $("#divsearch_component_params").position().left
12200 }).slideToggle(200);
12201 });
12202 $(document).on("click", function(e) {
12203 if (!$(e.target).closest("#search_component_params_input, .search-component-assistance, #ui-datepicker-div").length) {
12204 $(".search-component-assistance").hide();
12205 }
12206 });
12207 });
12208 </script>';
12209
12210 $ret .= '<script>
12211 $(document).ready(function() {
12212 $(".search_filter_field").on("change", function() {
12213 console.log("We change search_filter_field");
12214
12215 let maybenull = 0;
12216 const selectedField = $(this).find(":selected");
12217 let fieldType = selectedField.data("type");
12218 const selectedFieldValue = selectedField.val();
12219
12220 // If the selected field has an array of values then ask toshow the value selector instead of the value input
12221 if (arrayoffiltercriterias[selectedFieldValue]["arrayofkeyval"] !== undefined) {
12222 fieldType = "select";
12223 }
12224
12225 // If the selected field may be null then ask to append the "IsDefined" and "IsNotDefined" operators
12226 if (arrayoffiltercriterias[selectedFieldValue]["maybenull"] !== undefined) {
12227 maybenull = 1;
12228 }
12229 const operators = getOperatorsForFieldType(fieldType, maybenull);
12230 const operatorSelector = $(".operator-selector");
12231
12232 // Clear existing options
12233 operatorSelector.empty();
12234
12235 // Populate operators
12236 Object.entries(operators).forEach(function([operator, label]) {
12237 operatorSelector.append("<option value=\'" + operator + "\'>" + label + "</option>");
12238 });
12239
12240 operatorSelector.trigger("change.select2");
12241
12242 // Clear and hide all input elements initially
12243 $(".value-input, .dateone, .datemonth, .dateyear").val("").hide();
12244 $("#datemonth, #dateyear").val(null).trigger("change.select2");
12245 $("#dateone").datepicker("setDate", null);
12246 $(".date-one, .date-month, .date-year").hide();
12247 $("#value-selector").val("").hide();
12248 $("#value-selector").next(".select2-container").hide();
12249 $("#value-selector").val(null).trigger("change.select2");
12250
12251 if (fieldType === "date" || fieldType === "datetime" || fieldType === "timestamp") {
12252 $(".date-one").show();
12253 } else if (arrayoffiltercriterias[selectedFieldValue]["arrayofkeyval"] !== undefined) {
12254 var arrayofkeyval = arrayoffiltercriterias[selectedFieldValue]["arrayofkeyval"];
12255 var valueSelector = $("#value-selector");
12256 valueSelector.empty();
12257 Object.entries(arrayofkeyval).forEach(function([key, val]) {
12258 valueSelector.append("<option value=\'" + key + "\'>" + val + "</option>");
12259 });
12260 valueSelector.trigger("change.select2");
12261
12262 $("#value-selector").show();
12263 $("#value-selector").next(".select2-container").show();
12264 } else {
12265 $(".value-input").show();
12266 }
12267 });
12268
12269 $("#operator-selector").on("change", function() {
12270 console.log("We change operator-selector");
12271
12272 const selectedOperator = $(this).find(":selected").val();
12273 if (selectedOperator === "IsDefined" || selectedOperator === "IsNotDefined") {
12274 // Disable all value input elements
12275 $(".value-input, .dateone, .datemonth, .dateyear").val("").prop("disabled", true);
12276 $("#datemonth, #dateyear").val(null).trigger("change.select2");
12277 $("#dateone").datepicker("setDate", null).datepicker("option", "disabled", true);
12278 $(".date-one, .date-month, .date-year").prop("disabled", true);
12279 $("#value-selector").val("").prop("disabled", true);
12280 $("#value-selector").val(null).trigger("change.select2");
12281 } else {
12282 // Enable all value input elements
12283 $(".value-input, .dateone, .datemonth, .dateyear").prop("disabled", false);
12284 $(".date-one, .date-month, .date-year").prop("disabled", false);
12285 $("#dateone").datepicker("option", "disabled", false);
12286 $("#value-selector").prop("disabled", false);
12287 }
12288 });
12289
12290 $(".add-filter-btn").on("click", function(event) {
12291 console.log("We click on add-filter-btn");
12292
12293 event.preventDefault();
12294
12295 const field = $(".search_filter_field").val();
12296 const operator = $(".operator-selector").val();
12297 let value = $(".value-input").val();
12298 const fieldType = $(".search_filter_field").find(":selected").data("type");
12299
12300 if (["date", "datetime", "timestamp"].includes(fieldType)) {
12301 const year = $("#dateoneyear").val().toString().padStart(4, "0");;
12302 const month = $("#dateonemonth").val().toString().padStart(2, "0");
12303 const day = $("#dateoneday").val().toString().padStart(2, "0");
12304 value = `${year}-${month}-${day}`;
12305 console.log("value="+value);
12306 }
12307
12308 // If the selected field has an array of values then take the selected value
12309 if (arrayoffiltercriterias[field]["arrayofkeyval"] !== undefined) {
12310 value = $("#value-selector").val();
12311 }
12312
12313 // If the operator is "IsDefined" or "IsNotDefined" then set the value to 1 (it will not be used)
12314 if (operator === "IsDefined" || operator === "IsNotDefined") {
12315 value = "1";
12316 }
12317
12318 const filterString = generateFilterString(field, operator, value, fieldType);
12319
12320 // Submit the form
12321 if (filterString !== "" && field !== "" && operator !== "" && value !== "") {
12322 $("#search_component_params_input").val($("#search_component_params_input").val() + " " + filterString);
12323 $("#search_component_params_input").closest("form").submit();
12324 } else {
12325 $(".assistance-errors").show();
12326 }
12327 });
12328 });
12329 </script>';
12330
12331 return $ret;
12332 }
12333
12345 public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0, $selected = 0, $morecss = '')
12346 {
12347 global $langs, $user;
12348
12349 $retstring = '';
12350
12351 $TModels = array();
12352
12353 include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
12354 $formmail = new FormMail($this->db);
12355 $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
12356
12357 if ($default) {
12358 $TModels[0] = $langs->trans('DefaultMailModel');
12359 }
12360 if ($result > 0) {
12361 foreach ($formmail->lines_model as $model) {
12362 $TModels[(int) $model->id] = $model->label;
12363 }
12364 }
12365
12366 $retstring .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_' . $prefix . 'model_mail" name="' . $prefix . 'model_mail">';
12367
12368 foreach ($TModels as $id_model => $label_model) {
12369 $retstring .= '<option value="' . $id_model . '"';
12370 if (!empty($selected) && ((int) $selected) == $id_model) {
12371 $retstring .= "selected";
12372 }
12373 $retstring .= ">" . $label_model . "</option>";
12374 }
12375
12376 $retstring .= "</select>";
12377
12378 if ($addjscombo) {
12379 $retstring .= ajax_combobox('select_' . $prefix . 'model_mail');
12380 }
12381
12382 return $retstring;
12383 }
12384
12396 public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = false, $morecss = '', $dol_openinpopup = '')
12397 {
12398 global $langs;
12399
12400 $buttons = array();
12401
12402 $save = array(
12403 'name' => 'save',
12404 'label_key' => $save_label,
12405 );
12406
12407 if ($save_label == 'Create' || $save_label == 'Add') {
12408 $save['name'] = 'add';
12409 } elseif ($save_label == 'Modify') {
12410 $save['name'] = 'edit';
12411 }
12412
12413 $cancel = array(
12414 'name' => 'cancel',
12415 'label_key' => 'Cancel',
12416 );
12417
12418 // If MAIN_BUTTON_POSITION_FIRST_OR_LEFT not set, default is to have main action first, then complementary, then cancel at end
12419 if (!getDolGlobalInt('MAIN_BUTTON_POSITION_FIRST_OR_LEFT')) {
12420 !empty($save_label) ? $buttons[] = $save : '';
12421 if (!empty($morebuttons)) {
12422 $buttons[] = $morebuttons;
12423 }
12424 !empty($cancel_label) ? $buttons[] = $cancel : '';
12425 } else {
12426 if (!empty($morebuttons)) {
12427 $buttons[] = $morebuttons;
12428 }
12429 !empty($cancel_label) ? $buttons[] = $cancel : '';
12430 !empty($save_label) ? $buttons[] = $save : '';
12431 }
12432
12433 $retstring = $withoutdiv ? '' : '<div class="center">';
12434
12435 foreach ($buttons as $button) {
12436 $addclass = empty($button['addclass']) ? '' : $button['addclass'];
12437 $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'])) . '">';
12438 }
12439 $retstring .= $withoutdiv ? '' : '</div>';
12440
12441 if ($dol_openinpopup) {
12442 $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . dol_escape_htmltag($dol_openinpopup) . ' context, so we enable the close of dialog on cancel -->' . "\n";
12443 $retstring .= '<script nonce="' . getNonce() . '">';
12444 $retstring .= 'jQuery(".button-cancel").click(function(e) {
12445 e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . dol_escape_js($dol_openinpopup) . '\');
12446 window.parent.jQuery(\'#idfordialog' . dol_escape_js($dol_openinpopup) . '\').dialog(\'close\');
12447 });';
12448 $retstring .= '</script>';
12449 }
12450
12451 return $retstring;
12452 }
12453
12454
12455 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
12456
12463 {
12464 // phpcs:enable
12465 global $langs;
12466
12467 $num = count($this->cache_invoice_subtype);
12468 if ($num > 0) {
12469 return 0; // Cache already loaded
12470 }
12471
12472 dol_syslog(__METHOD__, LOG_DEBUG);
12473
12474 $sql = "SELECT rowid, code, label as label";
12475 $sql .= " FROM " . MAIN_DB_PREFIX . 'c_invoice_subtype';
12476 $sql .= " WHERE active = 1";
12477
12478 $resql = $this->db->query($sql);
12479 if ($resql) {
12480 $num = $this->db->num_rows($resql);
12481 $i = 0;
12482 while ($i < $num) {
12483 $obj = $this->db->fetch_object($resql);
12484
12485 // If translation exists, we use it, otherwise we take the default wording
12486 $label = ($langs->trans("InvoiceSubtype" . $obj->rowid) != "InvoiceSubtype" . $obj->rowid) ? $langs->trans("InvoiceSubtype" . $obj->rowid) : (($obj->label != '-') ? $obj->label : '');
12487 $this->cache_invoice_subtype[$obj->rowid]['rowid'] = $obj->rowid;
12488 $this->cache_invoice_subtype[$obj->rowid]['code'] = $obj->code;
12489 $this->cache_invoice_subtype[$obj->rowid]['label'] = $label;
12490 $i++;
12491 }
12492
12493 $this->cache_invoice_subtype = dol_sort_array($this->cache_invoice_subtype, 'code', 'asc', 0, 0, 1);
12494
12495 return $num;
12496 } else {
12497 dol_print_error($this->db);
12498 return -1;
12499 }
12500 }
12501
12502
12513 public function getSelectInvoiceSubtype($selected = 0, $htmlname = 'subtypeid', $addempty = 0, $noinfoadmin = 0, $morecss = '')
12514 {
12515 global $langs, $user;
12516
12517 $out = '';
12518 dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
12519
12520 $this->load_cache_invoice_subtype();
12521
12522 $out .= '<select id="' . $htmlname . '" class="flat selectsubtype' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
12523 if ($addempty) {
12524 $out .= '<option value="0">&nbsp;</option>';
12525 }
12526
12527 foreach ($this->cache_invoice_subtype as $rowid => $subtype) {
12528 $label = $subtype['label'];
12529 $out .= '<option value="' . $subtype['rowid'] . '"';
12530 if ($selected == $subtype['rowid']) {
12531 $out .= ' selected="selected"';
12532 }
12533 $out .= '>';
12534 $out .= $label;
12535 $out .= '</option>';
12536 }
12537
12538 $out .= '</select>';
12539 if ($user->admin && empty($noinfoadmin)) {
12540 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
12541 }
12542 $out .= ajax_combobox($htmlname);
12543
12544 return $out;
12545 }
12546
12556 public function getSearchFilterToolInput($dataTarget, $htmlName = 'search-tools-input', $value = '', $params = [])
12557 {
12558 global $langs;
12559
12560 $attr = array(
12561 'type' => 'search',
12562 'name' => $htmlName,
12563 'value' => $value,
12564 'class' => "search-tool-input",
12565 'placeholder' => $langs->trans('Search'),
12566 'autocomplete' => 'off'
12567 );
12568
12569 // Optional data attr
12570 // 'autofocus' : will set auto focus on field ,
12571 // data-counter-target : will get count results
12572 // data-no-item-target : will be display if count results is 0
12573
12574 if ($dataTarget !== false) {
12575 $attr['data-search-tool-target'] = $dataTarget;
12576 }
12577
12578 // Override attr
12579 if (!empty($params['attr']) && is_array($params['attr'])) {
12580 foreach ($params['attr'] as $key => $value) {
12581 if ($key == 'class') {
12582 $attr['class'] .= ' '.$value;
12583 } elseif ($key == 'classOverride') {
12584 $attr['class'] = $value;
12585 } else {
12586 $attr[$key] = $value;
12587 }
12588 }
12589 }
12590
12591 // automatic add tooltip when title is detected
12592 if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
12593 $attr['class'] .= ' classfortooltip';
12594 }
12595
12596 $TCompiledAttr = [];
12597 foreach ($attr as $key => $value) {
12598 if (in_array($key, ['data-target'])
12599 || (!empty($params['use_unsecured_unescapedattr']) && is_array($params['use_unsecured_unescapedattr']) && in_array($key, $params['use_unsecured_unescapedattr']))) { // Not recommended
12600 $value = dol_htmlentities($value, ENT_QUOTES | ENT_SUBSTITUTE);
12601 } else {
12602 $value = dolPrintHTMLForAttribute($value);
12603 }
12604
12605 $TCompiledAttr[] = $key . '="' . $value . '"'; // $value has been escaped by the dolPrintHTMLForAttribute... just before
12606 }
12607
12608 $compiledAttributes = implode(' ', $TCompiledAttr);
12609
12610
12611 return '<div class="search-tool-container"><input '.$compiledAttributes.'></div>';
12612 }
12613
12627 public function inputType($type, $name, $value = '', $id = '', $morecss = '', $moreparam = '', $label = '', $addInputLabel = '')
12628 {
12629 $out = '';
12630 if ($label != '') {
12631 $out .= '<label for="' . dolPrintHTMLForAttribute($id) . '">';
12632 }
12633 $out .= '<input type="' . dolPrintHTMLForAttribute($type) . '"';
12634 $out .= ' class="flat valignmiddle maxwidthonsmartphone ' . dolPrintHTMLForAttribute($morecss) . '"';
12635 if ($id != '') {
12636 $out .= ' id="' . dolPrintHTMLForAttribute($id) . '"';
12637 }
12638 $out .= ' name="' . dolPrintHTMLForAttribute($name) . '"';
12639 $out .= ' value="' . dolPrintHTMLForAttribute($value) . '" ';
12640 $out .= ($moreparam ? ' ' . $moreparam : '');
12641 $out .= ' />' . $addInputLabel;
12642 if ($label != '') {
12643 $out .= $label . '</label>';
12644 }
12645
12646 return $out;
12647 }
12648
12661 public function inputSelectAjax($htmlName, $array, $id, $ajaxUrl, $ajaxData = [], $morecss = 'minwidth75', $moreparam = '')
12662 {
12663 $out = "
12664 <script>
12665 $(document).ready(function () {
12666 $('#" . $htmlName . "').select2({
12667 ajax: {
12668 url: '" . $ajaxUrl . "',
12669 dataType: 'json',
12670 delay: 250, // wait 250 milliseconds before triggering the request
12671 data: function (params) {
12672 var query = {
12673 search: params.term,
12674 page: params.page || 1";
12675 if (!empty($ajaxData) && is_array($ajaxData)) {
12676 foreach ($ajaxData as $key => $value) {
12677 $out .= ", " . $key . ": '" . $value . "'";
12678 }
12679 }
12680 $out .= "
12681 }
12682 return query;
12683 }
12684 }
12685 })
12686 });
12687 </script>";
12688
12689 $out .= $this->selectarray($htmlName, $array, $id, 0, 0, 0, $moreparam, 0, 0, 0, '', $morecss);
12690
12691 return $out;
12692 }
12693
12703 public function inputHtml($htmlName, $value, $morecss = '', $moreparam = '')
12704 {
12705 require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
12706 $doleditor = new DolEditor($htmlName, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && getDolGlobalInt('FCKEDITOR_ENABLE_SOCIETE'), ROWS_5, '90%');
12707
12708 return (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
12709 }
12710
12721 public function inputText($htmlName, $value, $morecss = '', $moreparam = '', $options = array())
12722 {
12723 global $langs;
12724
12725 $out = '';
12726 if (!empty($options)) {
12727 // If the textarea field has a list of arrayofkeyval into its definition, we suggest a combo with possible values to fill the textarea.
12728 $out .= $this->selectarray($htmlName . "_multiinput", $options, '', 1, 0, 0, $moreparam, 0, 0, 0, '', "flat maxwidthonphone" . $morecss);
12729 $out .= '<input id="' . $htmlName . '_multiinputadd" type="button" class="button" value="' . $langs->trans("Add") . '">';
12730 $out .= "<script>";
12731 $out .= '
12732 function handlemultiinputdisabling(htmlname){
12733 console.log("We handle the disabling of used options for "+htmlname+"_multiinput");
12734 multiinput = $("#"+htmlname+"_multiinput");
12735 multiinput.find("option").each(function(){
12736 tmpval = $("#"+htmlname).val();
12737 tmpvalarray = tmpval.split("\n");
12738 valtotest = $(this).val();
12739 if(tmpvalarray.includes(valtotest)){
12740 $(this).prop("disabled",true);
12741 } else {
12742 if($(this).prop("disabled") == true){
12743 console.log(valtotest)
12744 $(this).prop("disabled", false);
12745 }
12746 }
12747 });
12748 }
12749
12750 $(document).ready(function () {
12751 $("#' . $htmlName . '_multiinputadd").on("click",function() {
12752 tmpval = $("#' . $htmlName . '").val();
12753 tmpvalarray = tmpval.split(",");
12754 valtotest = $("#' . $htmlName . '_multiinput").val();
12755 if(valtotest != -1 && !tmpvalarray.includes(valtotest)){
12756 console.log("We add the selected value to the text area ' . $htmlName . '");
12757 if(tmpval == ""){
12758 tmpval = valtotest;
12759 } else {
12760 tmpval = tmpval + "\n" + valtotest;
12761 }
12762 $("#' . $htmlName . '").val(tmpval);
12763 handlemultiinputdisabling("' . $htmlName . '");
12764 $("#' . $htmlName . '_multiinput").val(-1);
12765 } else {
12766 console.log("We add nothing the text area ' . $htmlName . '");
12767 }
12768 });
12769 $("#' . $htmlName . '").on("change",function(){
12770 handlemultiinputdisabling("' . $htmlName . '");
12771 });
12772 handlemultiinputdisabling("' . $htmlName . '");
12773 })';
12774 $out .= "</script>";
12775 $value = str_replace(',', "\n", $value);
12776 }
12777
12778 require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
12779 $doleditor = new DolEditor($htmlName, (string) $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
12780 $out .= (string) $doleditor->Create(1, '', true, '', '', $moreparam, $morecss);
12781
12782 return $out;
12783 }
12784
12795 public function inputRadio($htmlName, $options, $selectedValue, $morecss = '', $moreparam = '')
12796 {
12797 $out = '';
12798 foreach ($options as $optionKey => $optionLabel) {
12799 $selected = ((string) $selectedValue) === ((string) $optionKey) ? ' checked="checked"' : '';
12800 $optionId = $htmlName . '_' . $optionKey;
12801 $out .= '<input class="flat' . $morecss . '" type="radio" name="' . $htmlName . '" id="' . $optionId . '" value="' . dolPrintHTMLForAttribute((string) $optionKey) . '"' . $selected . $moreparam . '/><label for="' . $optionId . '">' . $optionLabel . '</label><br>';
12802 }
12803
12804 return $out;
12805 }
12806
12817 public function inputStars($htmlName, $size, $value, $morecss = '', $moreparam = '')
12818 {
12819 $out = '<input type="hidden" class="flat ' . $morecss . '" name="' . $htmlName . '" id="' . $htmlName . '" value="' . dolPrintHTMLForAttribute((string) $value) . '"' . $moreparam . '>';
12820 $out .= '<div class="star-selection" id="' . $htmlName . '_selection">';
12821 for ($i = 1; $i <= $size; $i++) {
12822 $out .= '<span class="star" data-value="' . $i . '">' . img_picto('', 'fontawesome_star_fas') . '</span>';
12823 }
12824 $out .= '</div>';
12825 $out .= '<script>
12826 jQuery(function($) { /* commonobject.class.php 1 */
12827 let container = $("#' . $htmlName . '_selection");
12828 let selectedStars = parseInt($("#' . $htmlName . '").val()) || 0;
12829 container.find(".star").each(function() {
12830 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
12831 });
12832 container.find(".star").on("mouseover", function() {
12833 let selectedStar = $(this).data("value");
12834 container.find(".star").each(function() {
12835 $(this).toggleClass("active", $(this).data("value") <= selectedStar);
12836 });
12837 });
12838 container.on("mouseout", function() {
12839 container.find(".star").each(function() {
12840 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
12841 });
12842 });
12843 container.find(".star").off("click").on("click", function() {
12844 selectedStars = $(this).data("value");
12845 if (selectedStars === 1 && $("#' . $htmlName . '").val() == 1) {
12846 selectedStars = 0;
12847 }
12848 $("#' . $htmlName . '").val(selectedStars);
12849 container.find(".star").each(function() {
12850 $(this).toggleClass("active", $(this).data("value") <= selectedStars);
12851 });
12852 });
12853 });
12854 </script>';
12855
12856 return $out;
12857 }
12858
12868 public function inputIcon($htmlName, $value, $morecss = '', $moreparam = '')
12869 {
12870 global $langs;
12871
12872 /* External lib inclusion are not allowed in backoffice. Also lib is included several time if there is several icon file.
12873 Some code must be added into main when MAIN_ADD_ICONPICKER_JS is set to add of lib in html header
12874 $out ='<link rel="stylesheet" href="'.dol_buildpath('/myfield/css/fontawesome-iconpicker.min.css', 1).'">';
12875 $out.='<script src="'.dol_buildpath('/myfield/js/fontawesome-iconpicker.min.js', 1).'"></script>';
12876 */
12877 $out = '<input type="text" class="form-control icp icp-auto iconpicker-element iconpicker-input flat ' . $morecss . ' maxwidthonsmartphone"';
12878 $out .= ' name="' . $htmlName . '" id="' . $htmlName . '" value="' . dolPrintHTMLForAttribute((string) $value) . '" ' . ((string) $moreparam) . '>';
12879 if (getDolGlobalInt('MAIN_ADD_ICONPICKER_JS')) {
12880 $out .= '<script>';
12881 $options = "{ title: '<b>" . $langs->trans("IconFieldSelector") . "</b>', placement: 'right', showFooter: false, templates: {";
12882 $options .= "iconpicker: '<div class=\"iconpicker\"><div style=\"background-color:#EFEFEF;\" class=\"iconpicker-items\"></div></div>',";
12883 $options .= "iconpickerItem: '<a role=\"button\" href=\"#\" class=\"iconpicker-item\" style=\"background-color:#DDDDDD;\"><i></i></a>',";
12884 // $options.="buttons: '<button style=\"background-color:#FFFFFF;\" class=\"iconpicker-btn iconpicker-btn-cancel btn btn-default btn-sm\">".$langs->trans("Cancel")."</button>";
12885 // $options.="<button style=\"background-color:#FFFFFF;\" class=\"iconpicker-btn iconpicker-btn-accept btn btn-primary btn-sm\">".$langs->trans("Save")."</button>',";
12886 $options .= "footer: '<div class=\"popover-footer\" style=\"background-color:#EFEFEF;\"></div>',";
12887 $options .= "search: '<input type=\"search\" class\"form-control iconpicker-search\" placeholder=\"" . $langs->trans("TypeToFilter") . "\" />',";
12888 $options .= "popover: '<div class=\"iconpicker-popover popover\">";
12889 $options .= " <div class=\"arrow\" ></div>";
12890 $options .= " <div class=\"popover-title\" style=\"text-align:center;background-color:#EFEFEF;\"></div>";
12891 $options .= " <div class=\"popover-content \" ></div>";
12892 $options .= "</div>'}}";
12893 $out .= "$('#" . $htmlName . "').iconpicker(" . $options . ");";
12894 $out .= '</script>';
12895 }
12896
12897 return $out;
12898 }
12899
12908 public function inputGeoPoint($htmlName, $value, $type = '')
12909 {
12910 require_once DOL_DOCUMENT_ROOT . '/core/class/dolgeophp.class.php';
12911 require_once DOL_DOCUMENT_ROOT . '/core/class/geomapeditor.class.php';
12912 $dolgeophp = new DolGeoPHP($this->db);
12913 $geomapeditor = new GeoMapEditor();
12914
12915 $geojson = '{}';
12916 $centroidjson = getDolGlobalString('MAIN_INFO_SOCIETE_GEO_COORDINATES', '{}');
12917 if (!empty($value)) {
12918 $tmparray = $dolgeophp->parseGeoString($value);
12919 $geojson = $tmparray['geojson'];
12920 $centroidjson = $tmparray['centroidjson'];
12921 }
12922
12923 return $geomapeditor->getHtml($htmlName, $geojson, $centroidjson, $type);
12924 }
12925
12932 public function outputMultiValues($values)
12933 {
12934 $out = '';
12935 $toPrint = array();
12936 $values = is_array($values) ? $values : array();
12937
12938 foreach ($values as $value) {
12939 $toPrint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #bbb">' . $value . '</li>';
12940 }
12941 if (!empty($toPrint)) {
12942 $out = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toPrint) . '</ul></div>';
12943 }
12944
12945 return $out;
12946 }
12947
12955 public function outputStars($size, $value)
12956 {
12957 $out = '<div class="star-selection" data-value="' . dolPrintHTMLForAttribute((string) $value) . '">';
12958 for ($i = 1; $i <= $size; $i++) {
12959 $out .= '<span class="star' . ($i <= $value ? ' active' : '') . '" data-value="' . $i . '">' . img_picto('', 'fontawesome_star_fas') . '</span>';
12960 }
12961 $out .= '</div>';
12962
12963 return $out;
12964 }
12965
12972 public function outputIcon($value)
12973 {
12974 $out = '<span class="' . dolPrintHTMLForAttribute((string) $value) . '"></span>';
12975
12976 return $out;
12977 }
12978
12986 public function outputGeoPoint($value, $type)
12987 {
12988 $out = '';
12989
12990 if (!empty($value)) {
12991 require_once DOL_DOCUMENT_ROOT . '/core/class/dolgeophp.class.php';
12992 $dolgeophp = new DolGeoPHP($this->db);
12993 if ($type == 'point') {
12994 $out = $dolgeophp->getXYString($value);
12995 } else { // multipts, linestrg, polygon
12996 $out = $dolgeophp->getPointString($value);
12997 }
12998 }
12999
13000 return $out;
13001 }
13002
13017 public function getNomUrl(&$object, $withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '', $add_label = 0, $sep = ' - ')
13018 {
13019 if (is_object($object) && method_exists($object, 'getNomUrl')) {
13020 $out = $object->getNomUrl($withpicto, $option, $maxlength, $save_lastsearch_value, $notooltip, $morecss, $add_label, $sep);
13021 return $out;
13022 } else {
13023 return '';
13024 }
13025 }
13026}
$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:49
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:475
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:324
ajax_event($htmlname, $events)
Add event management script.
Definition ajax.lib.php:588
$c
Definition line.php:331
Class to manage bank accounts.
Class to manage categories.
Class to manage bank accounts description of third parties.
Class to manage contact/addresses.
Class to manage a WYSIWYG editor.
Class to manage Geo processing Usage: $dolgeophp=new DolGeoPHP($db);.
DAO Resource object.
Class to manage ECM files.
const STATUS_OPEN_INTERNAL
Warehouse open and only operations for stock transfers/corrections allowed (not for customer shipping...
const STATUS_OPEN_ALL
Warehouse open and any operations are allowed (customer shipping, supplier dispatch,...
const STATUS_CLOSED
Warehouse closed, inactive.
Class to manage standard extra languages.
Class to manage 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.
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.
formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=0, $width=500, $disableformtag=0, $labelbuttonyes='Yes', $labelbuttonno='No')
Show a confirmation HTML form or AJAX popup.
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')
Retourne la liste des devises, dans la langue de l'utilisateur.
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.
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.
select_produits_list($selected=0, $htmlname='productid', $filtertype='', $limit=20, $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.
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.
form_multicurrency_rate($page, $rate=0.0, $htmlname='multicurrency_tx', $currency='')
Show form with multicurrency rate.
load_cache_availability()
Load int a cache property the list of possible delivery delays.
select_dolusers($selected='', $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.
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.
editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
Output edit in place form.
selectUnits($selected='', $htmlname='units', $showempty=0, $unit_type='')
Creates HTML units selector (code => label)
select_produits_fournisseurs_list($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $filterkey='', $statut=-1, $outputmode=0, $limit=100, $alsoproductwithnosupplierprice=0, $morecss='', $showstockinlist=0, $placeholder='')
Return list of suppliers products.
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.
form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0)
Show a select box with available absolute discounts.
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_confirm($page, $title, $question, $action, $formquestion=array(), $selectedchoice="", $useajax=0, $height=170, $width=500)
load_cache_conditions_paiements()
form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0, $textifnoproject='', $morecss='')
Show a form to select a project.
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.
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.
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.
select_export_model($selected='', $htmlname='exportmodelid', $type='', $useempty=0)
Return list of export templates.
selectDateToDate($set_time='', $set_time_end='', $prefix='re', $empty=0, $forcenewline=0)
Show 2 HTML widget to input a date or combo list for day, month, years and optionally hours and minut...
outputMultiValues($values)
Html for show selected multiple values.
textwithtooltip($text, $htmltext, $tooltipon=1, $direction=0, $img='', $extracss='', $notabs=3, $incbefore='', $noencodehtmltext=0, $tooltiptrigger='', $forcenowrap=0)
Show a text and picto with tooltip on text or picto.
selectCategories($categtype, $htmlname, $object=null)
Return HTML component to select a category.
outputIcon($value)
Html for show icon.
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()
selectAvailabilityDelay($selected='', $htmlname='availid', $filtertype='', $addempty=0, $morecss='')
Return the list of type of delay available.
selectCurrency($selected='', $htmlname='currency_id', $mode=0, $useempty='')
Retourne la liste des devises, dans la langue de l'utilisateur.
select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $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...
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.
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 permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new Form...
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 translations.
Class to manage Dolibarr users.
Class toolbox to validate values.
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:171
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:86
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.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
dolPrintHTML($s, $allowiframe=0)
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'.
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.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
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.
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, ....
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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.
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.
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.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='')
Show information in HTML for admin users or standard users.
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...
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_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
treeview li table
No Email.
a disabled
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:132
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:135
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
getMaxFileSizeArray()
Return the max allowed for file upload.
dolDecrypt($chain, $key='')
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