Passed
Push — master ( 65bdac...4e88da )
by Alxarafe
32:38
created

Form::editfieldval()   F

Complexity

Conditions 59
Paths > 20000

Size

Total Lines 114
Code Lines 92

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 59
eloc 92
nc 29720
nop 13
dl 0
loc 114
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* Copyright (c) 2002-2007  Rodolphe Quiedeville    <[email protected]>
3
 * Copyright (C) 2004-2012  Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2004       Benoit Mortier          <[email protected]>
5
 * Copyright (C) 2004       Sebastien Di Cintio     <[email protected]>
6
 * Copyright (C) 2004       Eric Seigne             <[email protected]>
7
 * Copyright (C) 2005-2017  Regis Houssin           <[email protected]>
8
 * Copyright (C) 2006       Andre Cianfarani        <[email protected]>
9
 * Copyright (C) 2006       Marc Barilley/Ocebo     <[email protected]>
10
 * Copyright (C) 2007       Franky Van Liedekerke   <[email protected]>
11
 * Copyright (C) 2007       Patrick Raguin          <[email protected]>
12
 * Copyright (C) 2010       Juanjo Menent           <[email protected]>
13
 * Copyright (C) 2010-2014  Philippe Grand          <[email protected]>
14
 * Copyright (C) 2011       Herve Prot              <[email protected]>
15
 * Copyright (C) 2012-2016  Marcos García           <[email protected]>
16
 * Copyright (C) 2012       Cedric Salvador         <[email protected]>
17
 * Copyright (C) 2012-2015  Raphaël Doursenaud      <[email protected]>
18
 * Copyright (C) 2014       Alexandre Spangaro      <[email protected]>
19
 * Copyright (C) 2018       Ferran Marcet           <[email protected]>
20
 * Copyright (C) 2018       Frédéric France         <[email protected]>
21
 * Copyright (C) 2018       Nicolas ZABOURI	        <[email protected]>
22
 * Copyright (C) 2018       Christophe Battarel     <[email protected]>
23
 * Copyright (C) 2018       Josep Lluis Amador      <[email protected]>
24
 * Copyright (C) 2018-2019  Alxarafe                <[email protected]>
25
 *
26
 * This program is free software; you can redistribute it and/or modify
27
 * it under the terms of the GNU General Public License as published by
28
 * the Free Software Foundation; either version 3 of the License, or
29
 * (at your option) any later version.
30
 *
31
 * This program is distributed in the hope that it will be useful,
32
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34
 * GNU General Public License for more details.
35
 *
36
 * You should have received a copy of the GNU General Public License
37
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38
 */
39
namespace Alixar\Base;
40
41
/**
42
 * 	\file       htdocs/core/class/html.form.class.php
43
 *  \ingroup    core
44
 * 	\brief      File of class with all html predefined components
45
 */
46
47
/**
48
 * 	Class to manage generation of HTML components
49
 * 	Only common components must be here.
50
 *
51
 *  TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
52
 */
53
class Form
54
{
55
56
    /**
57
     * @var DoliDB Database handler.
58
     */
59
    // public $db;
60
61
    /**
62
     * @var string Error code (or message)
63
     */
64
    public $error = '';
65
66
    /**
67
     * @var string[]    Array of error strings
68
     */
69
    public $errors = array();
70
    public $num;
71
    // Cache arrays
72
    public $cache_types_paiements = array();
73
    public $cache_conditions_paiements = array();
74
    public $cache_availability = array();
75
    public $cache_demand_reason = array();
76
    public $cache_types_fees = array();
77
    public $cache_vatrates = array();
78
79
    /**
80
     * Constructor
81
     *
82
     * @param		DoliDB		$db      Database handler
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Base\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
83
     */
84
    public function __construct()
85
    {
86
        // $this->db = $db;
87
    }
88
89
    /**
90
     * Output key field for an editable field
91
     *
92
     * @param   string	$text			Text of label or key to translate
93
     * @param   string	$htmlname		Name of select field ('edit' prefix will be added)
94
     * @param   string	$preselected    Value to show/edit (not used in this function)
95
     * @param	object	$object			Object
96
     * @param	boolean	$perm			Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
97
     * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
98
     * @param	string	$moreparam		More param to add on a href URL.
99
     * @param   int     $fieldrequired  1 if we want to show field as mandatory using the "fieldrequired" CSS.
100
     * @param   int     $notabletag     1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
101
     * @param	string	$paramid		Key of parameter for id ('id', 'socid')
102
     * @return	string					HTML edit field
103
     */
104
    function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id')
105
    {
106
        global $conf, $langs;
107
108
        $ret = '';
109
110
        // TODO change for compatibility
111
        if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
112
            if (!empty($perm)) {
113
                $tmp = explode(':', $typeofdata);
114
                $ret .= '<div class="editkey_' . $tmp[0] . (!empty($tmp[1]) ? ' ' . $tmp[1] : '') . '" id="' . $htmlname . '">';
115
                if ($fieldrequired)
116
                    $ret .= '<span class="fieldrequired">';
117
                $ret .= $langs->trans($text);
118
                if ($fieldrequired)
119
                    $ret .= '</span>';
120
                $ret .= '</div>' . "\n";
121
            }
122
            else {
123
                if ($fieldrequired)
124
                    $ret .= '<span class="fieldrequired">';
125
                $ret .= $langs->trans($text);
126
                if ($fieldrequired)
127
                    $ret .= '</span>';
128
            }
129
        }
130
        else {
131
            if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
132
                $ret .= '<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
133
            }
134
            if ($fieldrequired) {
135
                $ret .= '<span class="fieldrequired">';
136
            }
137
            $ret .= $langs->trans($text);
138
            if ($fieldrequired) {
139
                $ret .= '</span>';
140
            }
141
            if (!empty($notabletag)) {
142
                $ret .= ' ';
143
            }
144
            if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
145
                $ret .= '</td>';
146
            }
147
            if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
148
                $ret .= '<td align="right">';
149
            }
150
            if ($htmlname && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
151
                $ret .= '<a href="' . $_SERVER["PHP_SELF"] . '?action=edit' . $htmlname . '&amp;' . $paramid . '=' . $object->id . $moreparam . '">' . img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)) . '</a>';
152
            }
153
            if (!empty($notabletag) && $notabletag == 1) {
154
                $ret .= ' : ';
155
            }
156
            if (!empty($notabletag) && $notabletag == 3) {
157
                $ret .= ' ';
158
            }
159
            if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
160
                $ret .= '</td>';
161
            }
162
            if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
163
                $ret .= '</tr></table>';
164
            }
165
        }
166
167
        return $ret;
168
    }
169
170
    /**
171
     * Output value of a field for an editable field
172
     *
173
     * @param	string	$text			Text of label (not used in this function)
174
     * @param	string	$htmlname		Name of select field
175
     * @param	string	$value			Value to show/edit
176
     * @param	object	$object			Object
177
     * @param	boolean	$perm			Permission to allow button to edit parameter
178
     * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...)
179
     * @param	string	$editvalue		When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value
180
     * @param	object	$extObject		External object
181
     * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
182
     * @param	string	$moreparam		More param to add on the form action href URL
183
     * @param   int     $notabletag     Do no output table tags
184
     * @param	string	$formatfunc		Call a specific function to output field
185
     * @param	string	$paramid		Key of parameter for id ('id', 'socid')
186
     * @return  string					HTML edit field
187
     */
188
    function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id')
189
    {
190
        global $conf, $langs, $db;
191
192
        $ret = '';
193
194
        // Check parameters
195
        if (empty($typeofdata))
196
            return 'ErrorBadParameter';
197
198
        // When option to edit inline is activated
199
        if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker
200
            $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
201
        } else {
202
            if (GETPOST('action', 'aZ09') == 'edit' . $htmlname) {
203
                $ret .= "\n";
204
                $ret .= '<form method="post" action="' . $_SERVER["PHP_SELF"] . ($moreparam ? '?' . $moreparam : '') . '">';
205
                $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
206
                $ret .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
207
                $ret .= '<input type="hidden" name="' . $paramid . '" value="' . $object->id . '">';
208
                if (empty($notabletag))
209
                    $ret .= '<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
210
                if (empty($notabletag))
211
                    $ret .= '<tr><td>';
212
                if (preg_match('/^(string|email)/', $typeofdata)) {
213
                    $tmp = explode(':', $typeofdata);
214
                    $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($editvalue ? $editvalue : $value) . '"' . ($tmp[1] ? ' size="' . $tmp[1] . '"' : '') . '>';
215
                } else if (preg_match('/^(numeric|amount)/', $typeofdata)) {
216
                    $tmp = explode(':', $typeofdata);
217
                    $valuetoshow = price2num($editvalue ? $editvalue : $value);
218
                    $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($valuetoshow != '' ? price($valuetoshow) : '') . '"' . ($tmp[1] ? ' size="' . $tmp[1] . '"' : '') . '>';
219
                } else if (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
220
                    $tmp = explode(':', $typeofdata);
221
                    $cols = $tmp[2];
222
                    $morealt = '';
223
                    if (preg_match('/%/', $cols)) {
224
                        $morealt = ' style="width: ' . $cols . '"';
225
                        $cols = '';
226
                    }
227
228
                    $valuetoshow = ($editvalue ? $editvalue : $value);
229
230
                    $ret .= '<textarea id="' . $htmlname . '" name="' . $htmlname . '" wrap="soft" rows="' . ($tmp[1] ? $tmp[1] : '20') . '"' . ($cols ? ' cols="' . $cols . '"' : 'class="quatrevingtpercent"') . $morealt . '">';
231
                    $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
232
                    $ret .= '</textarea>';
233
                } else if ($typeofdata == 'day' || $typeofdata == 'datepicker') {
234
                    $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form' . $htmlname, 1, 0);
235
                } else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
236
                    $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form' . $htmlname, 1, 0);
237
                } else if (preg_match('/^select;/', $typeofdata)) {
238
                    $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
239
                    foreach ($arraydata as $val) {
240
                        $tmp = explode(':', $val);
241
                        $arraylist[$tmp[0]] = $tmp[1];
242
                    }
243
                    $ret .= $this->selectarray($htmlname, $arraylist, $value);
0 ignored issues
show
Comprehensibility Best Practice introduced by alxarafe
The variable $arraylist seems to be defined by a foreach iteration on line 239. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
244
                } else if (preg_match('/^ckeditor/', $typeofdata)) {
245
                    $tmp = explode(':', $typeofdata);  // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols
246
                    require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
247
                    $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), ($tmp[2] ? $tmp[2] : ''), ($tmp[3] ? $tmp[3] : '100'), ($tmp[1] ? $tmp[1] : 'dolibarr_notes'), 'In', ($tmp[5] ? $tmp[5] : 0), true, true, ($tmp[6] ? $tmp[6] : '20'), ($tmp[7] ? $tmp[7] : '100'));
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Base\DolEditor was not found. Did you mean DolEditor? If so, make sure to prefix the type with \.
Loading history...
248
                    $ret .= $doleditor->Create(1);
249
                }
250
                if (empty($notabletag))
251
                    $ret .= '</td>';
252
253
                if (empty($notabletag))
254
                    $ret .= '<td align="left">';
255
                //else $ret.='<div class="clearboth"></div>';
256
                $ret .= '<input type="submit" class="button' . (empty($notabletag) ? '' : ' ') . '" name="modify" value="' . $langs->trans("Modify") . '">';
257
                if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag))
258
                    $ret .= '<br>' . "\n";
259
                $ret .= '<input type="submit" class="button' . (empty($notabletag) ? '' : ' ') . '" name="cancel" value="' . $langs->trans("Cancel") . '">';
260
                if (empty($notabletag))
261
                    $ret .= '</td>';
262
263
                if (empty($notabletag))
264
                    $ret .= '</tr></table>' . "\n";
265
                $ret .= '</form>' . "\n";
266
            }
267
            else {
268
                if (preg_match('/^(email)/', $typeofdata))
269
                    $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
270
                elseif (preg_match('/^(amount|numeric)/', $typeofdata))
271
                    $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
272
                elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata))
273
                    $ret .= dol_htmlentitiesbr($value);
274
                elseif ($typeofdata == 'day' || $typeofdata == 'datepicker')
275
                    $ret .= dol_print_date($value, 'day');
276
                elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
277
                    $ret .= dol_print_date($value, 'dayhour');
278
                else if (preg_match('/^select;/', $typeofdata)) {
279
                    $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
280
                    foreach ($arraydata as $val) {
281
                        $tmp = explode(':', $val);
282
                        $arraylist[$tmp[0]] = $tmp[1];
283
                    }
284
                    $ret .= $arraylist[$value];
285
                } else if (preg_match('/^ckeditor/', $typeofdata)) {
286
                    $tmpcontent = dol_htmlentitiesbr($value);
287
                    if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
288
                        $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
289
                        $firstline = preg_replace('/[\n\r].*/', '', $firstline);
290
                        $tmpcontent = $firstline . ((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
291
                    }
292
                    $ret .= $tmpcontent;
293
                } else
294
                    $ret .= $value;
295
296
                if ($formatfunc && method_exists($object, $formatfunc)) {
297
                    $ret = $object->$formatfunc($ret);
298
                }
299
            }
300
        }
301
        return $ret;
302
    }
303
304
    /**
305
     * Output edit in place form
306
     *
307
     * @param	object	$object			Object
308
     * @param	string	$value			Value to show/edit
309
     * @param	string	$htmlname		DIV ID (field name)
310
     * @param	int		$condition		Condition to edit
311
     * @param	string	$inputType		Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx')
312
     * @param	string	$editvalue		When in edit mode, use this value as $value instead of value
313
     * @param	object	$extObject		External object
314
     * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
315
     * @return	string   		      	HTML edit in place
316
     */
317
    private function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
318
    {
319
        global $conf;
320
321
        $out = '';
322
323
        // Check parameters
324
        if (preg_match('/^text/', $inputType))
325
            $value = dol_nl2br($value);
326
        else if (preg_match('/^numeric/', $inputType))
327
            $value = price($value);
328
        else if ($inputType == 'day' || $inputType == 'datepicker')
329
            $value = dol_print_date($value, 'day');
330
331
        if ($condition) {
332
            $element = false;
333
            $table_element = false;
334
            $fk_element = false;
335
            $loadmethod = false;
336
            $savemethod = false;
337
            $ext_element = false;
338
            $button_only = false;
339
            $inputOption = '';
340
341
            if (is_object($object)) {
342
                $element = $object->element;
343
                $table_element = $object->table_element;
344
                $fk_element = $object->id;
345
            }
346
347
            if (is_object($extObject)) {
348
                $ext_element = $extObject->element;
349
            }
350
351
            if (preg_match('/^(string|email|numeric)/', $inputType)) {
352
                $tmp = explode(':', $inputType);
353
                $inputType = $tmp[0];
354
                if (!empty($tmp[1]))
355
                    $inputOption = $tmp[1];
356
                if (!empty($tmp[2]))
357
                    $savemethod = $tmp[2];
358
                $out .= '<input id="width_' . $htmlname . '" value="' . $inputOption . '" type="hidden"/>' . "\n";
359
            }
360
            else if ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
361
                $tmp = explode(':', $inputType);
362
                $inputType = $tmp[0];
363
                if (!empty($tmp[1]))
364
                    $inputOption = $tmp[1];
365
                if (!empty($tmp[2]))
366
                    $savemethod = $tmp[2];
367
368
                $out .= '<input id="timestamp" type="hidden"/>' . "\n"; // Use for timestamp format
369
            }
370
            else if (preg_match('/^(select|autocomplete)/', $inputType)) {
371
                $tmp = explode(':', $inputType);
372
                $inputType = $tmp[0];
373
                $loadmethod = $tmp[1];
374
                if (!empty($tmp[2]))
375
                    $savemethod = $tmp[2];
376
                if (!empty($tmp[3]))
377
                    $button_only = true;
378
            }
379
            else if (preg_match('/^textarea/', $inputType)) {
380
                $tmp = explode(':', $inputType);
381
                $inputType = $tmp[0];
382
                $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
383
                $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
384
            } else if (preg_match('/^ckeditor/', $inputType)) {
385
                $tmp = explode(':', $inputType);
386
                $inputType = $tmp[0];
387
                $toolbar = $tmp[1];
388
                if (!empty($tmp[2]))
389
                    $width = $tmp[2];
390
                if (!empty($tmp[3]))
391
                    $heigth = $tmp[3];
392
                if (!empty($tmp[4]))
393
                    $savemethod = $tmp[4];
394
395
                if (!empty($conf->fckeditor->enabled)) {
396
                    $out .= '<input id="ckeditor_toolbar" value="' . $toolbar . '" type="hidden"/>' . "\n";
397
                } else {
398
                    $inputType = 'textarea';
399
                }
400
            }
401
402
            $out .= '<input id="element_' . $htmlname . '" value="' . $element . '" type="hidden"/>' . "\n";
403
            $out .= '<input id="table_element_' . $htmlname . '" value="' . $table_element . '" type="hidden"/>' . "\n";
404
            $out .= '<input id="fk_element_' . $htmlname . '" value="' . $fk_element . '" type="hidden"/>' . "\n";
405
            $out .= '<input id="loadmethod_' . $htmlname . '" value="' . $loadmethod . '" type="hidden"/>' . "\n";
406
            if (!empty($savemethod))
407
                $out .= '<input id="savemethod_' . $htmlname . '" value="' . $savemethod . '" type="hidden"/>' . "\n";
408
            if (!empty($ext_element))
409
                $out .= '<input id="ext_element_' . $htmlname . '" value="' . $ext_element . '" type="hidden"/>' . "\n";
410
            if (!empty($custommsg)) {
411
                if (is_array($custommsg)) {
412
                    if (!empty($custommsg['success']))
413
                        $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg['success'] . '" type="hidden"/>' . "\n";
414
                    if (!empty($custommsg['error']))
415
                        $out .= '<input id="errormsg_' . $htmlname . '" value="' . $custommsg['error'] . '" type="hidden"/>' . "\n";
416
                } else
417
                    $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg . '" type="hidden"/>' . "\n";
418
            }
419
            if ($inputType == 'textarea') {
420
                $out .= '<input id="textarea_' . $htmlname . '_rows" value="' . $rows . '" type="hidden"/>' . "\n";
421
                $out .= '<input id="textarea_' . $htmlname . '_cols" value="' . $cols . '" type="hidden"/>' . "\n";
422
            }
423
            $out .= '<span id="viewval_' . $htmlname . '" class="viewval_' . $inputType . ($button_only ? ' inactive' : ' active') . '">' . $value . '</span>' . "\n";
424
            $out .= '<span id="editval_' . $htmlname . '" class="editval_' . $inputType . ($button_only ? ' inactive' : ' active') . ' hideobject">' . (!empty($editvalue) ? $editvalue : $value) . '</span>' . "\n";
425
        } else {
426
            $out = $value;
427
        }
428
429
        return $out;
430
    }
431
432
    /**
433
     * 	Show a text and picto with tooltip on text or picto.
434
     *  Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
435
     *
436
     * 	@param	string		$text				Text to show
437
     * 	@param	string		$htmltext			HTML content of tooltip. Must be HTML/UTF8 encoded.
438
     * 	@param	int			$tooltipon			1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
439
     * 	@param	int			$direction			-1=image is before, 0=no image, 1=image is after
440
     * 	@param	string		$img				Html code for image (use img_xxx() function to get it)
441
     * 	@param	string		$extracss			Add a CSS style to td tags
442
     * 	@param	int			$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
443
     * 	@param	string		$incbefore			Include code before the text
444
     * 	@param	int			$noencodehtmltext	Do not encode into html entity the htmltext
445
     *  @param  string      $tooltiptrigger		''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
446
     *  @param	int			$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
447
     * 	@return	string							Code html du tooltip (texte+picto)
448
     * 	@see	Use function textwithpicto if you can.
449
     *  TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
450
     */
451
    function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
452
    {
453
        global $conf;
454
455
        if ($incbefore) {
456
            $text = $incbefore . $text;
457
        }
458
        if (!$htmltext) {
459
            return $text;
460
        }
461
462
        $tag = 'td';
463
        if ($notabs == 2) {
464
            $tag = 'div';
465
        }
466
        if ($notabs == 3) {
467
            $tag = 'span';
468
        }
469
        // Sanitize tooltip
470
        $htmltext = str_replace("\\", "\\\\", $htmltext);
471
        $htmltext = str_replace("\r", "", $htmltext);
472
        $htmltext = str_replace("\n", "", $htmltext);
473
474
        $extrastyle = '';
475
        if ($direction < 0) {
476
            $extracss = ($extracss ? $extracss . ' ' : '') . 'inline-block';
477
            $extrastyle = 'padding: 0px; padding-left: 3px !important;';
478
        }
479
        if ($direction > 0) {
480
            $extracss = ($extracss ? $extracss . ' ' : '') . 'inline-block';
481
            $extrastyle = 'padding: 0px; padding-right: 3px !important;';
482
        }
483
484
        $classfortooltip = 'classfortooltip';
485
486
        $s = '';
487
        $textfordialog = '';
488
489
        if ($tooltiptrigger == '') {
490
            $htmltext = str_replace('"', "&quot;", $htmltext);
491
        } else {
492
            $classfortooltip = 'classfortooltiponclick';
493
            $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_' . $tooltiptrigger . '" class="classfortooltiponclicktext">' . $htmltext . '</div>';
494
        }
495
        if ($tooltipon == 2 || $tooltipon == 3) {
496
            $paramfortooltipimg = ' class="' . $classfortooltip . ' inline-block' . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '"';
497
            if ($tooltiptrigger == '') {
498
                $paramfortooltipimg .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on img tag to store tooltip
499
            } else {
500
                $paramfortooltipimg .= ' dolid="' . $tooltiptrigger . '"';
501
            }
502
        } else {
503
            $paramfortooltipimg = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
504
        }
505
        if ($tooltipon == 1 || $tooltipon == 3) {
506
            $paramfortooltiptd = ' class="' . ($tooltipon == 3 ? 'cursorpointer ' : '') . $classfortooltip . ' inline-block' . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '" ';
507
            if ($tooltiptrigger == '') {
508
                $paramfortooltiptd .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on td tag to store tooltip
509
            } else {
510
                $paramfortooltiptd .= ' dolid="' . $tooltiptrigger . '"';
511
            }
512
        } else {
513
            $paramfortooltiptd = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
514
        }
515
        if (empty($notabs)) {
516
            $s .= '<table class="nobordernopadding" summary=""><tr style="height: auto;">';
517
        } elseif ($notabs == 2) {
518
            $s .= '<div class="inline-block' . ($forcenowrap ? ' nowrap' : '') . '">';
519
        }
520
        // Define value if value is before
521
        if ($direction < 0) {
522
            $s .= '<' . $tag . $paramfortooltipimg;
523
            if ($tag == 'td') {
524
                $s .= ' valign="top" width="14"';
525
            }
526
            $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
527
        }
528
        // Use another method to help avoid having a space in value in order to use this value with jquery
529
        // Define label
530
        if ((string) $text != '') {
531
            $s .= '<' . $tag . $paramfortooltiptd . '>' . $text . '</' . $tag . '>';
532
        }
533
        // Define value if value is after
534
        if ($direction > 0) {
535
            $s .= '<' . $tag . $paramfortooltipimg;
536
            if ($tag == 'td') {
537
                $s .= ' valign="middle" width="14"';
538
            }
539
            $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
540
        }
541
        if (empty($notabs)) {
542
            $s .= '</tr></table>';
543
        } elseif ($notabs == 2) {
544
            $s .= '</div>';
545
        }
546
547
        return $s;
548
    }
549
550
    /**
551
     * 	Show a text with a picto and a tooltip on picto
552
     *
553
     * 	@param	string	$text				Text to show
554
     * 	@param  string	$htmltext	     	Content of tooltip
555
     * 	@param	int		$direction			1=Icon is after text, -1=Icon is before text, 0=no icon
556
     * 	@param	string	$type				Type of picto ('info', 'help', 'warning', 'superadmin', '[email protected]', ...) or image filepath
557
     *  @param  string	$extracss           Add a CSS style to td, div or span tag
558
     *  @param  int		$noencodehtmltext   Do not encode into html entity the htmltext
559
     *  @param	int		$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
560
     *  @param  string  $tooltiptrigger     ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
561
     *  @param	int		$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
562
     * 	@return	string						HTML code of text, picto, tooltip
563
     */
564
    function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger = '', $forcenowrap = 0)
565
    {
566
        global $conf, $langs;
567
568
        $alt = '';
569
        if ($tooltiptrigger)
570
            $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
571
572
        //For backwards compatibility
573
        if ($type == '0')
574
            $type = 'info';
575
        elseif ($type == '1')
576
            $type = 'help';
577
578
        // If info or help with no javascript, show only text
579
        if (empty($conf->use_javascript_ajax)) {
580
            if ($type == 'info' || $type == 'help')
581
                return $text;
582
            else {
583
                $alt = $htmltext;
584
                $htmltext = '';
585
            }
586
        }
587
588
        // If info or help with smartphone, show only text (tooltip hover can't works)
589
        if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
590
            if ($type == 'info' || $type == 'help')
591
                return $text;
592
        }
593
        // If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)
594
        if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger)) {
595
            if ($type == 'info' || $type == 'help')
596
                return $text;
597
        }
598
599
        if ($type == 'info')
600
            $img = img_help(0, $alt);
601
        elseif ($type == 'help')
602
            $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
603
        elseif ($type == 'superadmin')
604
            $img = img_picto($alt, 'redstar');
605
        elseif ($type == 'admin')
606
            $img = img_picto($alt, 'star');
607
        elseif ($type == 'warning')
608
            $img = img_warning($alt);
609
        else
610
            $img = img_picto($alt, $type);
611
612
        return $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && !$img) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
613
    }
614
615
    /**
616
     * Generate select HTML to choose massaction
617
     *
618
     * @param	string	$selected		Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
619
     * @param	int		$arrayofaction	array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
620
     * @param   int     $alwaysvisible  1=select button always visible
621
     * @return	string					Select list
622
     */
623
    function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0)
624
    {
625
        global $conf, $langs, $hookmanager;
626
627
        if (count($arrayofaction) == 0)
628
            return;
629
630
        $disabled = 0;
631
        $ret = '<div class="centpercent center">';
632
        $ret .= '<select class="flat' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' massaction massactionselect" name="massaction"' . ($disabled ? ' disabled="disabled"' : '') . '>';
633
634
        // 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.
635
        $parameters = array();
636
        $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters);    // Note that $action and $object may have been modified by hook
637
        if (empty($reshook)) {
638
            $ret .= '<option value="0"' . ($disabled ? ' disabled="disabled"' : '') . '>-- ' . $langs->trans("SelectAction") . ' --</option>';
639
            foreach ($arrayofaction as $code => $label) {
0 ignored issues
show
Bug introduced by alxarafe
The expression $arrayofaction of type integer is not traversable.
Loading history...
640
                $ret .= '<option value="' . $code . '"' . ($disabled ? ' disabled="disabled"' : '') . '>' . $label . '</option>';
641
            }
642
        }
643
        $ret .= $hookmanager->resPrint;
644
645
        $ret .= '</select>';
646
        // 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
647
        $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.
648
        $ret .= '<input type="submit" disabled name="confirmmassaction" class="button' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' massaction massactionconfirmed" value="' . dol_escape_htmltag($langs->trans("Confirm")) . '">';
649
        $ret .= '</div>';
650
651
        if (!empty($conf->use_javascript_ajax)) {
652
            $ret .= '<!-- JS CODE TO ENABLE mass action select -->
653
    		<script type="text/javascript">
654
        		function initCheckForSelect(mode)	/* mode is 0 during init of page or click all, 1 when we click on 1 checkbox */
655
        		{
656
        			atleastoneselected=0;
657
    	    		jQuery(".checkforselect").each(function( index ) {
658
    	  				/* console.log( index + ": " + $( this ).text() ); */
659
    	  				if ($(this).is(\':checked\')) atleastoneselected++;
660
    	  			});
661
					console.log("initCheckForSelect mode="+mode+" atleastoneselected="+atleastoneselected);
662
    	  			if (atleastoneselected || ' . $alwaysvisible . ')
663
    	  			{
664
    	  				jQuery(".massaction").show();
665
        			    ' . ($selected ? 'if (atleastoneselected) { jQuery(".massactionselect").val("' . $selected . '"); jQuery(".massactionconfirmed").prop(\'disabled\', false); }' : '') . '
666
        			    ' . ($selected ? 'if (! atleastoneselected) { jQuery(".massactionselect").val("0"); jQuery(".massactionconfirmed").prop(\'disabled\', true); } ' : '') . '
667
    	  			}
668
    	  			else
669
    	  			{
670
    	  				jQuery(".massaction").hide();
671
    	            }
672
        		}
673
674
        	jQuery(document).ready(function () {
675
        		initCheckForSelect(0);
676
        		jQuery(".checkforselect").click(function() {
677
        			initCheckForSelect(1);
678
    	  		});
679
    	  		jQuery(".massactionselect").change(function() {
680
        			var massaction = $( this ).val();
681
        			var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
682
        			if (massaction == "builddoc")
683
                    {
684
                        urlform = urlform + "#show_files";
685
    	            }
686
        			$( this ).closest("form").attr("action", urlform);
687
                    console.log("we select a mass action "+massaction+" - "+urlform);
688
        	        /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
689
        			if ($(this).val() != \'0\')
690
    	  			{
691
    	  				jQuery(".massactionconfirmed").prop(\'disabled\', false);
692
    	  			}
693
    	  			else
694
    	  			{
695
    	  				jQuery(".massactionconfirmed").prop(\'disabled\', true);
696
    	  			}
697
    	        });
698
        	});
699
    		</script>
700
        	';
701
        }
702
703
        return $ret;
704
    }
705
706
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
707
    /**
708
     *  Return combo list of activated countries, into language of user
709
     *
710
     *  @param	string	$selected       	Id or Code or Label of preselected country
711
     *  @param  string	$htmlname       	Name of html select object
712
     *  @param  string	$htmloption     	Options html on select object
713
     *  @param	integer	$maxlength			Max length for labels (0=no limit)
714
     *  @param	string	$morecss			More css class
715
     *  @param	string	$usecodeaskey		''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
716
     *  @param	int		$showempty			Show empty choice
717
     *  @param	int		$disablefavorites	1=Disable favorites,
718
     *  @param	int		$addspecialentries	1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
719
     *  @return string           			HTML string with select
720
     */
721
    function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0)
722
    {
723
        // phpcs:enable
724
        global $conf, $langs, $mysoc;
725
726
        $langs->load("dict");
727
728
        $out = '';
729
        $countryArray = array();
730
        $favorite = array();
731
        $label = array();
732
        $atleastonefavorite = 0;
733
734
        $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
735
        $sql .= " FROM " . MAIN_DB_PREFIX . "c_country";
736
        $sql .= " WHERE active > 0";
737
        //$sql.= " ORDER BY code ASC";
738
739
        dol_syslog(get_class($this) . "::select_country", LOG_DEBUG);
740
        $resql = $this->db->query($sql);
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\Form. Did you maybe forget to declare it?
Loading history...
741
        if ($resql) {
742
            $out .= '<select id="select' . $htmlname . '" class="flat maxwidth200onsmartphone selectcountry' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" ' . $htmloption . '>';
743
            $num = $this->db->num_rows($resql);
744
            $i = 0;
745
            if ($num) {
746
                $foundselected = false;
747
748
                while ($i < $num) {
749
                    $obj = $this->db->fetch_object($resql);
750
                    $countryArray[$i]['rowid'] = $obj->rowid;
751
                    $countryArray[$i]['code_iso'] = $obj->code_iso;
752
                    $countryArray[$i]['code_iso3'] = $obj->code_iso3;
753
                    $countryArray[$i]['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country" . $obj->code_iso) != "Country" . $obj->code_iso ? $langs->transnoentitiesnoconv("Country" . $obj->code_iso) : ($obj->label != '-' ? $obj->label : ''));
754
                    $countryArray[$i]['favorite'] = $obj->favorite;
755
                    $favorite[$i] = $obj->favorite;
756
                    $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
757
                    $i++;
758
                }
759
760
                if (empty($disablefavorites))
761
                    array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
762
                else
763
                    $countryArray = dol_sort_array($countryArray, 'label');
764
765
                if ($showempty) {
766
                    $out .= '<option value="">&nbsp;</option>' . "\n";
767
                }
768
769
                if ($addspecialentries) { // Add dedicated entries for groups of countries
770
                    //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
771
                    $out .= '<option value="special_allnotme"' . ($selected == 'special_allnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
772
                    $out .= '<option value="special_eec"' . ($selected == 'special_eec' ? ' selected' : '') . '>' . $langs->trans("CountriesInEEC") . '</option>';
773
                    if ($mysoc->isInEEC())
774
                        $out .= '<option value="special_eecnotme"' . ($selected == 'special_eecnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
775
                    $out .= '<option value="special_noteec"' . ($selected == 'special_noteec' ? ' selected' : '') . '>' . $langs->trans("CountriesNotInEEC") . '</option>';
776
                    $out .= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
777
                }
778
779
                foreach ($countryArray as $row) {
780
                    //if (empty($showempty) && empty($row['rowid'])) continue;
781
                    if (empty($row['rowid'])) {
782
                        continue;
783
                    }
784
785
                    if (empty($disablefavorites) && $row['favorite'] && $row['code_iso'])
786
                        $atleastonefavorite++;
787
                    if (empty($row['favorite']) && $atleastonefavorite) {
788
                        $atleastonefavorite = 0;
789
                        $out .= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
790
                    }
791
                    if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
792
                        $foundselected = true;
793
                        $out .= '<option value="' . ($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']) . '" selected>';
794
                    } else {
795
                        $out .= '<option value="' . ($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']) . '">';
796
                    }
797
                    if ($row['label'])
798
                        $out .= dol_trunc($row['label'], $maxlength, 'middle');
799
                    else
800
                        $out .= '&nbsp;';
801
                    if ($row['code_iso'])
802
                        $out .= ' (' . $row['code_iso'] . ')';
803
                    $out .= '</option>';
804
                }
805
            }
806
            $out .= '</select>';
807
        }
808
        else {
809
            dol_print_error($this->db);
810
        }
811
812
        // Make select dynamic
813
        include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
814
        $out .= ajax_combobox('select' . $htmlname);
815
816
        return $out;
817
    }
818
819
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
820
    /**
821
     *  Return select list of incoterms
822
     *
823
     *  @param	string	$selected       		Id or Code of preselected incoterm
824
     *  @param	string	$location_incoterms     Value of input location
825
     *  @param	string	$page       			Defined the form action
826
     *  @param  string	$htmlname       		Name of html select object
827
     *  @param  string	$htmloption     		Options html on select object
828
     * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
829
     *  @param	array	$events					Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
830
     *  @return string           				HTML string with select and input
831
     */
832
    function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
833
    {
834
        // phpcs:enable
835
        global $conf, $langs;
836
837
        $langs->load("dict");
838
839
        $out = '';
840
        $incotermArray = array();
841
842
        $sql = "SELECT rowid, code";
843
        $sql .= " FROM " . MAIN_DB_PREFIX . "c_incoterms";
844
        $sql .= " WHERE active > 0";
845
        $sql .= " ORDER BY code ASC";
846
847
        dol_syslog(get_class($this) . "::select_incoterm", LOG_DEBUG);
848
        $resql = $this->db->query($sql);
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\Form. Did you maybe forget to declare it?
Loading history...
849
        if ($resql) {
850
            if ($conf->use_javascript_ajax && !$forcecombo) {
851
                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
852
                $out .= ajax_combobox($htmlname, $events);
853
            }
854
855
            if (!empty($page)) {
856
                $out .= '<form method="post" action="' . $page . '">';
857
                $out .= '<input type="hidden" name="action" value="set_incoterms">';
858
                $out .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
859
            }
860
861
            $out .= '<select id="' . $htmlname . '" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="' . $htmlname . '" ' . $htmloption . '>';
862
            $out .= '<option value="0">&nbsp;</option>';
863
            $num = $this->db->num_rows($resql);
864
            $i = 0;
865
            if ($num) {
866
                $foundselected = false;
867
868
                while ($i < $num) {
869
                    $obj = $this->db->fetch_object($resql);
870
                    $incotermArray[$i]['rowid'] = $obj->rowid;
871
                    $incotermArray[$i]['code'] = $obj->code;
872
                    $i++;
873
                }
874
875
                foreach ($incotermArray as $row) {
876
                    if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
877
                        $out .= '<option value="' . $row['rowid'] . '" selected>';
878
                    } else {
879
                        $out .= '<option value="' . $row['rowid'] . '">';
880
                    }
881
882
                    if ($row['code'])
883
                        $out .= $row['code'];
884
885
                    $out .= '</option>';
886
                }
887
            }
888
            $out .= '</select>';
889
890
            $out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="' . $location_incoterms . '">';
891
892
            if (!empty($page)) {
893
                $out .= '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '"></form>';
894
            }
895
        } else {
896
            dol_print_error($this->db);
897
        }
898
899
        return $out;
900
    }
901
902
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
903
    /**
904
     * 	Return list of types of lines (product or service)
905
     * 	Example: 0=product, 1=service, 9=other (for external module)
906
     *
907
     * 	@param  string	$selected       Preselected type
908
     * 	@param  string	$htmlname       Name of field in html form
909
     * 	@param	int		$showempty		Add an empty field
910
     * 	@param	int		$hidetext		Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
911
     * 	@param	integer	$forceall		1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service')
912
     *  @return	void
913
     */
914
    function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
915
    {
916
        // phpcs:enable
917
        global $db, $langs, $user, $conf;
918
919
        // If product & services are enabled or both disabled.
920
        if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled)) || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled))) {
921
            if (empty($hidetext))
922
                print $langs->trans("Type") . ': ';
923
            print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
924
            if ($showempty) {
925
                print '<option value="-1"';
926
                if ($selected == -1)
927
                    print ' selected';
928
                print '>&nbsp;</option>';
929
            }
930
931
            print '<option value="0"';
932
            if (0 == $selected)
933
                print ' selected';
934
            print '>' . $langs->trans("Product");
935
936
            print '<option value="1"';
937
            if (1 == $selected)
938
                print ' selected';
939
            print '>' . $langs->trans("Service");
940
941
            print '</select>';
942
            //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
943
        }
944
        if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3) {
945
            print $langs->trans("Service");
946
            print '<input type="hidden" name="' . $htmlname . '" value="1">';
947
        }
948
        if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2) {
949
            print $langs->trans("Product");
950
            print '<input type="hidden" name="' . $htmlname . '" value="0">';
951
        }
952
        if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
953
            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
954
        }
955
    }
956
957
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
958
    /**
959
     * 	Load into cache cache_types_fees, array of types of fees
960
     *
961
     * 	@return     int             Nb of lines loaded, <0 if KO
962
     */
963
    function load_cache_types_fees()
964
    {
965
        // phpcs:enable
966
        global $langs;
967
968
        $num = count($this->cache_types_fees);
969
        if ($num > 0)
970
            return 0;    // Cache already loaded
971
972
        dol_syslog(__METHOD__, LOG_DEBUG);
973
974
        $langs->load("trips");
975
976
        $sql = "SELECT c.code, c.label";
977
        $sql .= " FROM " . MAIN_DB_PREFIX . "c_type_fees as c";
978
        $sql .= " WHERE active > 0";
979
980
        $resql = $this->db->query($sql);
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\Form. Did you maybe forget to declare it?
Loading history...
981
        if ($resql) {
982
            $num = $this->db->num_rows($resql);
983
            $i = 0;
984
985
            while ($i < $num) {
986
                $obj = $this->db->fetch_object($resql);
987
988
                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
989
                $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
990
                $this->cache_types_fees[$obj->code] = $label;
991
                $i++;
992
            }
993
994
            asort($this->cache_types_fees);
995
996
            return $num;
997
        } else {
998
            dol_print_error($this->db);
999
            return -1;
1000
        }
1001
    }
1002
1003
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1004
    /**
1005
     * 	Return list of types of notes
1006
     *
1007
     * 	@param	string		$selected		Preselected type
1008
     * 	@param  string		$htmlname		Name of field in form
1009
     * 	@param	int			$showempty		Add an empty field
1010
     * 	@return	void
1011
     */
1012
    function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
1013
    {
1014
        // phpcs:enable
1015
        global $user, $langs;
1016
1017
        dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
1018
1019
        $this->load_cache_types_fees();
1020
1021
        print '<select id="select_' . $htmlname . '" class="flat" name="' . $htmlname . '">';
1022
        if ($showempty) {
1023
            print '<option value="-1"';
1024
            if ($selected == -1)
1025
                print ' selected';
1026
            print '>&nbsp;</option>';
1027
        }
1028
1029
        foreach ($this->cache_types_fees as $key => $value) {
1030
            print '<option value="' . $key . '"';
1031
            if ($key == $selected)
1032
                print ' selected';
1033
            print '>';
1034
            print $value;
1035
            print '</option>';
1036
        }
1037
1038
        print '</select>';
1039
        if ($user->admin)
1040
            print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
1041
    }
1042
1043
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1044
    /**
1045
     *  Return HTML code to select a company.
1046
     *
1047
     *  @param		int			$selected				Preselected products
1048
     *  @param		string		$htmlname				Name of HTML select field (must be unique in page)
1049
     *  @param		int			$filter					Filter on thirdparty
1050
     *  @param		int			$limit					Limit on number of returned lines
1051
     *  @param		array		$ajaxoptions			Options for ajax_autocompleter
1052
     * 	@param		int			$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1053
     *  @return		string								Return select box for thirdparty.
1054
     *  @deprecated	3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)
1055
     */
1056
    function select_thirdparty($selected = '', $htmlname = 'socid', $filter = '', $limit = 20, $ajaxoptions = array(), $forcecombo = 0)
1057
    {
1058
        // phpcs:enable
1059
        return $this->select_thirdparty_list($selected, $htmlname, $filter, 1, 0, $forcecombo, array(), '', 0, $limit);
1060
    }
1061
1062
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1063
    /**
1064
     *  Output html form to select a third party
1065
     *
1066
     * 	@param	string	$selected       		Preselected type
1067
     * 	@param  string	$htmlname       		Name of field in form
1068
     *  @param  string	$filter         		optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')
1069
     * 	@param	string	$showempty				Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
1070
     * 	@param	int		$showtype				Show third party type in combolist (customer, prospect or supplier)
1071
     * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1072
     *  @param	array	$events					Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1073
     * 	@param	int		$limit					Maximum number of elements
1074
     *  @param	string	$morecss				Add more css styles to the SELECT component
1075
     * 	@param  string	$moreparam      		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1076
     * 	@param	string	$selected_input_value	Value of preselected input text (for use with ajax)
1077
     *  @param	int		$hidelabel				Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
1078
     *  @param	array	$ajaxoptions			Options for ajax_autocompleter
1079
     * 	@param  bool	$multiple				add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
1080
     * 	@return	string							HTML string with select box for thirdparty.
1081
     */
1082
    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)
1083
    {
1084
        // phpcs:enable
1085
        global $conf, $user, $langs;
1086
1087
        $out = '';
1088
1089
        if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
1090
            // No immediate load of all database
1091
            $placeholder = '';
1092
            if ($selected && empty($selected_input_value)) {
1093
                require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1094
                $societetmp = new Societe($this->db);
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\Form. Did you maybe forget to declare it?
Loading history...
Bug introduced by alxarafe
The type Alixar\Base\Societe was not found. Did you mean Societe? If so, make sure to prefix the type with \.
Loading history...
1095
                $societetmp->fetch($selected);
1096
                $selected_input_value = $societetmp->name;
1097
                unset($societetmp);
1098
            }
1099
            // mode 1
1100
            $urloption = 'htmlname=' . $htmlname . '&outjson=1&filter=' . $filter . ($showtype ? '&showtype=' . $showtype : '');
1101
            $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1102
            $out .= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';