Passed
Pull Request — dev (#6)
by Rafael
79:24 queued 24:08
created

FormAdmin::select_language()   F

Complexity

Conditions 37
Paths > 20000

Size

Total Lines 105
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 37
eloc 64
nc 1135296
nop 13
dl 0
loc 105
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
3
/* Copyright (C) 2004-2014  Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2005-2011  Regis Houssin               <[email protected]>
5
 * Copyright (C) 2007       Patrick Raguin 		        <[email protected]>
6
 * Copyright (C) 2024       Frédéric France             <[email protected]>
7
 * Copyright (C) 2024       Rafael San José             <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 */
22
23
namespace Dolibarr\Code\Core\Classes;
24
25
use DoliDB;
26
27
/**
28
 *      \file       htdocs/core/class/html.formadmin.class.php
29
 *      \ingroup    core
30
 *      \brief      File of class for html functions for admin pages
31
 */
32
33
34
/**
35
 *      Class to generate html code for admin pages
36
 */
37
class FormAdmin
38
{
39
    /**
40
     * @var DoliDB Database handler.
41
     */
42
    public $db;
43
44
    /**
45
     * @var string error message
46
     */
47
    public $error;
48
49
50
    /**
51
     *  Constructor
52
     *
53
     *  @param      DoliDB|null      $db      Database handler
54
     */
55
    public function __construct($db)
56
    {
57
        $this->db = $db;
58
    }
59
60
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
61
    /**
62
     *  Return html select list with available languages (key='en_US', value='United States' for example)
63
     *
64
     *  @param      string|array    $selected       Language pre-selected. Can be an array if $multiselect is 1.
65
     *  @param      string          $htmlname       Name of HTML select
66
     *  @param      int             $showauto       Show 'auto' choice
67
     *  @param      array           $filter         Array of keys to exclude in list (opposite of $onlykeys)
68
     *  @param      int|string      $showempty      '1'=Add empty value or 'string to show'
69
     *  @param      int             $showwarning    Show a warning if language is not complete
70
     *  @param      int             $disabled       Disable edit of select
71
     *  @param      string          $morecss        Add more css styles
72
     *  @param      int             $showcode       1=Add language code into label at beginning, 2=Add language code into label at end
73
     *  @param      int             $forcecombo     Force to use combo box (so no ajax beautify effect)
74
     *  @param      int             $multiselect    Make the combo a multiselect
75
     *  @param      array           $onlykeys       Array of language keys to restrict list with the following keys (opposite of $filter). Example array('fr', 'es', ...)
76
     *  @param      int             $mainlangonly   1=Show only main languages ('fr_FR' no' fr_BE', 'es_ES' not 'es_MX', ...)
77
     *  @return     string                          Return HTML select string with list of languages
78
     */
79
    public function select_language($selected = '', $htmlname = 'lang_id', $showauto = 0, $filter = array(), $showempty = '', $showwarning = 0, $disabled = 0, $morecss = '', $showcode = 0, $forcecombo = 0, $multiselect = 0, $onlykeys = array(), $mainlangonly = 0)
80
    {
81
		// phpcs:enable
82
        global $langs;
83
84
        if (getDolGlobalString('MAIN_DEFAULT_LANGUAGE_FILTER')) {
85
            if (!is_array($filter)) {
86
                $filter = array();
87
            }
88
            $filter[getDolGlobalString('MAIN_DEFAULT_LANGUAGE_FILTER')] = 1;
89
        }
90
91
        $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 12, 0, $mainlangonly);
92
93
        // If empty value is not allowed and the language to select is not inside the list of available language and we must find
94
        // an alternative of the language code to pre-select (to avoid to have first element in list pre-selected).
95
        if ($selected && empty($showempty)) {
96
            if (!is_array($selected) && !array_key_exists($selected, $langs_available)) {
97
                $tmparray = explode('_', $selected);
98
                if (!empty($tmparray[1])) {
99
                    $selected = getLanguageCodeFromCountryCode($tmparray[1]);
100
                }
101
                if (empty($selected)) {
102
                    $selected = $langs->defaultlang;
103
                }
104
            } else {
105
                // If the preselected value is an array, we do not try to find alternative to preselect
106
            }
107
        }
108
109
        $out = '';
110
111
        $out .= '<select ' . ($multiselect ? 'multiple="multiple" ' : '') . 'class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiselect ? '[]' : '') . '"' . ($disabled ? ' disabled' : '') . '>';
112
        if ($showempty && !$multiselect) {
113
            if (is_numeric($showempty)) {
114
                $out .= '<option value="0"';
115
            } else {
116
                $out .= '<option value="-1"';
117
            }
118
            if ($selected === '') {
119
                $out .= ' selected';
120
            }
121
            $out .= '>';
122
            if ($showempty != '1') {
123
                $out .= $showempty;
124
            } else {
125
                $out .= '&nbsp;';
126
            }
127
            $out .= '</option>';
128
        }
129
        if ($showauto) {
130
            $out .= '<option value="auto"';
131
            if ($selected === 'auto') {
132
                $out .= ' selected';
133
            }
134
            $out .= '>' . $langs->trans("AutoDetectLang") . '</option>';
135
        }
136
137
        asort($langs_available);    // array('XX' => 'Language (Country)', ...)
138
139
        foreach ($langs_available as $key => $value) {
140
            $valuetoshow = $value;
141
            if ($showcode == 1) {
142
                if ($mainlangonly) {
143
                    $valuetoshow = '<span class="opacitymedium">' . preg_replace('/[_-].*$/', '', $key) . '</span> - ' . $value;
144
                } else {
145
                    $valuetoshow = '<span class="opacitymedium">' . $key . '</span> - ' . $value;
146
                }
147
            }
148
            if ($showcode == 2) {
149
                if ($mainlangonly) {
150
                    $valuetoshow = $value . ' <span class="opacitymedium">(' . preg_replace('/[_-].*$/', '', $key) . ')</span>';
151
                } else {
152
                    $valuetoshow = $value . ' <span class="opacitymedium">(' . $key . ')</span>';
153
                }
154
            }
155
156
            $keytouse = $key;
157
            if ($mainlangonly) {
158
                $keytouse = preg_replace('/[_-].*$/', '', $key);
159
            }
160
161
            if ($filter && is_array($filter) && array_key_exists($keytouse, $filter)) {
162
                continue;
163
            }
164
            if ($onlykeys && is_array($onlykeys) && !array_key_exists($keytouse, $onlykeys)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $onlykeys of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
165
                continue;
166
            }
167
168
            $valuetoshow = picto_from_langcode($key, 'class="saturatemedium"') . ' ' . $valuetoshow;
169
            if ((is_string($selected) && (string) $selected == (string) $keytouse) || (is_array($selected) && in_array($keytouse, $selected))) {
170
                $out .= '<option value="' . $keytouse . '" selected data-html="' . dol_escape_htmltag($valuetoshow) . '">' . $valuetoshow . '</option>';
171
            } else {
172
                $out .= '<option value="' . $keytouse . '" data-html="' . dol_escape_htmltag($valuetoshow) . '">' . $valuetoshow . '</option>';
173
            }
174
        }
175
        $out .= '</select>';
176
177
        // Make select dynamic
178
        if (!$forcecombo) {
179
            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
180
            $out .= ajax_combobox($htmlname);
181
        }
182
183
        return $out;
184
    }
185
186
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
187
    /**
188
     *    Return list of available menus (eldy_backoffice, ...)
189
     *
190
     *    @param    string      $selected        Preselected menu value
191
     *    @param    string      $htmlname        Name of html select
192
     *    @param    array       $dirmenuarray    Array of directories to scan
193
     *    @param    string      $moreattrib      More attributes on html select tag
194
     *    @return   integer|void
195
     */
196
    public function select_menu($selected, $htmlname, $dirmenuarray, $moreattrib = '')
197
    {
198
		// phpcs:enable
199
        global $langs, $conf;
200
201
        // Clean parameters
202
203
204
        // Check parameters
205
        if (!is_array($dirmenuarray)) {
206
            return -1;
207
        }
208
209
        $menuarray = array();
210
        foreach ($conf->file->dol_document_root as $dirroot) {
211
            foreach ($dirmenuarray as $dirtoscan) {
212
                $dir = $dirroot . $dirtoscan;
213
                //print $dir.'<br>';
214
                if (is_dir($dir)) {
215
                    $handle = opendir($dir);
216
                    if (is_resource($handle)) {
217
                        while (($file = readdir($handle)) !== false) {
218
                            if (is_file($dir . "/" . $file) && substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS' && substr($file, 0, 5) != 'index') {
219
                                if (preg_match('/lib\.php$/i', $file)) {
220
                                    continue; // We exclude library files
221
                                }
222
                                if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i', $file)) {
223
                                    continue; // We exclude all menu manager files
224
                                }
225
                                if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i', $file)) {
226
                                    continue; // We exclude all menu manager files
227
                                }
228
                                if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i', $file)) {
229
                                    continue; // We exclude all menu manager files
230
                                }
231
232
                                $filelib = preg_replace('/\.php$/i', '', $file);
233
                                $prefix = '';
234
                                // 0=Recommended, 1=Experimental, 2=Development, 3=Other
235
                                if (preg_match('/^eldy/i', $file)) {
236
                                    $prefix = '0';
237
                                } elseif (preg_match('/^smartphone/i', $file)) {
238
                                    $prefix = '2';
239
                                } else {
240
                                    $prefix = '3';
241
                                }
242
243
                                $morelabel = '';
244
                                if (preg_match('/^auguria/i', $file)) {
245
                                    $morelabel .= ' <span class="opacitymedium">(' . $langs->trans("Unstable") . ')</span>';
246
                                }
247
                                if ($file == $selected) {
248
                                    $menuarray[$prefix . '_' . $file] = '<option value="' . $file . '" selected data-html="' . dol_escape_htmltag($filelib . $morelabel) . '">' . $filelib . $morelabel;
249
                                    $menuarray[$prefix . '_' . $file] .= '</option>';
250
                                } else {
251
                                    $menuarray[$prefix . '_' . $file] = '<option value="' . $file . '" data-html="' . dol_escape_htmltag($filelib . $morelabel) . '">' . $filelib . $morelabel;
252
                                    $menuarray[$prefix . '_' . $file] .= '</option>';
253
                                }
254
                            }
255
                        }
256
                        closedir($handle);
257
                    }
258
                }
259
            }
260
        }
261
        ksort($menuarray);
262
263
        // Output combo list of menus
264
        print '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
265
        $oldprefix = '';
266
        foreach ($menuarray as $key => $val) {
267
            $tab = explode('_', $key);
268
            $newprefix = $tab[0];
269
270
            if ($newprefix == '1' && (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1)) {
271
                continue;
272
            }
273
            if ($newprefix == '2' && (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2)) {
274
                continue;
275
            }
276
            if ($newprefix != $oldprefix) { // Add separators
277
                // Affiche titre
278
                print '<option value="-2" disabled>';
279
                if ($newprefix == '0') {
280
                    print '-- ' . $langs->trans("VersionRecommanded") . ' --';
281
                }
282
                if ($newprefix == '1') {
283
                    print '-- ' . $langs->trans("VersionExperimental") . ' --';
284
                }
285
                if ($newprefix == '2') {
286
                    print '-- ' . $langs->trans("VersionDevelopment") . ' --';
287
                }
288
                if ($newprefix == '3') {
289
                    print '-- ' . $langs->trans("Other") . ' --';
290
                }
291
                print '</option>';
292
                $oldprefix = $newprefix;
293
            }
294
295
            print $val . "\n"; // Show menu entry ($val contains the <option> tags
296
        }
297
        print '</select>';
298
299
        print ajax_combobox($htmlname);
300
301
        return;
302
    }
303
304
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
305
    /**
306
     *  Return combo list of available menu families
307
     *
308
     *  @param  string      $selected        Menu pre-selected
309
     *  @param  string      $htmlname        Name of html select
310
     *  @param  string[]    $dirmenuarray    Directories to scan
311
     *  @return void
312
     */
313
    public function select_menu_families($selected, $htmlname, $dirmenuarray)
314
    {
315
		// phpcs:enable
316
        global $langs, $conf;
317
318
        //$expdevmenu=array('smartphone_backoffice.php','smartphone_frontoffice.php');  // Menu to disable if $conf->global->MAIN_FEATURES_LEVEL is not set
319
        $expdevmenu = array();
320
321
        $menuarray = array();
322
323
        foreach ($dirmenuarray as $dirmenu) {
324
            foreach ($conf->file->dol_document_root as $dirroot) {
325
                $dir = $dirroot . $dirmenu;
326
                if (is_dir($dir)) {
327
                    $handle = opendir($dir);
328
                    if (is_resource($handle)) {
329
                        while (($file = readdir($handle)) !== false) {
330
                            if (is_file($dir . "/" . $file) && substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS') {
331
                                $filelib = preg_replace('/(_backoffice|_frontoffice)?\.php$/i', '', $file);
332
                                if (preg_match('/^index/i', $filelib)) {
333
                                    continue;
334
                                }
335
                                if (preg_match('/^default/i', $filelib)) {
336
                                    continue;
337
                                }
338
                                if (preg_match('/^empty/i', $filelib)) {
339
                                    continue;
340
                                }
341
                                if (preg_match('/\.lib/i', $filelib)) {
342
                                    continue;
343
                                }
344
                                if (getDolGlobalInt('MAIN_FEATURES_LEVEL') == 0 && in_array($file, $expdevmenu)) {
345
                                    continue;
346
                                }
347
348
                                $menuarray[$filelib] = 1;
349
                            }
350
                            $menuarray['all'] = 1;
351
                        }
352
                        closedir($handle);
353
                    }
354
                }
355
            }
356
        }
357
358
        ksort($menuarray);
359
360
        // Show combo list of menu handlers
361
        print '<select class="flat maxwidth150" id="' . $htmlname . '" name="' . $htmlname . '">';
362
        foreach ($menuarray as $key => $val) {
363
            $tab = explode('_', $key);
364
            print '<option value="' . $key . '"';
365
            if ($key == $selected) {
366
                print '	selected';
367
            }
368
            print '>';
369
            if ($key == 'all') {
370
                print $langs->trans("AllMenus");
371
            } else {
372
                print $key;
373
            }
374
            print '</option>' . "\n";
375
        }
376
        print '</select>';
377
378
        print ajax_combobox($htmlname);
379
    }
380
381
382
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
383
    /**
384
     *  Return a HTML select list of timezones
385
     *
386
     *  @param  string      $selected        Menu pre-selectionnee
387
     *  @param  string      $htmlname        Nom de la zone select
388
     *  @return void
389
     */
390
    public function select_timezone($selected, $htmlname)
391
    {
392
		// phpcs:enable
393
        print '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
394
        print '<option value="-1">&nbsp;</option>';
395
396
        $arraytz = array(
397
            "Pacific/Midway" => "GMT-11:00",
398
            "Pacific/Fakaofo" => "GMT-10:00",
399
            "America/Anchorage" => "GMT-09:00",
400
            "America/Los_Angeles" => "GMT-08:00",
401
            "America/Dawson_Creek" => "GMT-07:00",
402
            "America/Chicago" => "GMT-06:00",
403
            "America/Bogota" => "GMT-05:00",
404
            "America/Anguilla" => "GMT-04:00",
405
            "America/Araguaina" => "GMT-03:00",
406
            "America/Noronha" => "GMT-02:00",
407
            "Atlantic/Azores" => "GMT-01:00",
408
            "Africa/Abidjan" => "GMT+00:00",
409
            "Europe/Paris" => "GMT+01:00",
410
            "Europe/Helsinki" => "GMT+02:00",
411
            "Europe/Moscow" => "GMT+03:00",
412
            "Asia/Dubai" => "GMT+04:00",
413
            "Asia/Karachi" => "GMT+05:00",
414
            "Indian/Chagos" => "GMT+06:00",
415
            "Asia/Jakarta" => "GMT+07:00",
416
            "Asia/Hong_Kong" => "GMT+08:00",
417
            "Asia/Tokyo" => "GMT+09:00",
418
            "Australia/Sydney" => "GMT+10:00",
419
            "Pacific/Noumea" => "GMT+11:00",
420
            "Pacific/Auckland" => "GMT+12:00",
421
            "Pacific/Enderbury" => "GMT+13:00"
422
        );
423
        foreach ($arraytz as $lib => $gmt) {
424
            print '<option value="' . $lib . '"';
425
            if ($selected == $lib || $selected == $gmt) {
426
                print ' selected';
427
            }
428
            print '>' . $gmt . '</option>' . "\n";
429
        }
430
        print '</select>';
431
    }
432
433
434
435
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
436
    /**
437
     *  Return html select list with available languages (key='en_US', value='United States' for example)
438
     *
439
     *  @param      string  $selected       Paper format pre-selected
440
     *  @param      string  $htmlname       Name of HTML select field
441
     *  @param      string  $filter         Value to filter on code
442
     *  @param      int     $showempty      Add empty value
443
     *  @param      int     $forcecombo     Force to load all values and output a standard combobox (with no beautification)
444
     *  @return     string                  Return HTML output
445
     */
446
    public function select_paper_format($selected = '', $htmlname = 'paperformat_id', $filter = '', $showempty = 0, $forcecombo = 0)
447
    {
448
		// phpcs:enable
449
        global $langs;
450
451
        $langs->load("dict");
452
453
        $sql = "SELECT code, label, width, height, unit";
454
        $sql .= " FROM " . $this->db->prefix() . "c_paper_format";
455
        $sql .= " WHERE active=1";
456
        if ($filter) {
457
            $sql .= " AND code LIKE '%" . $this->db->escape($filter) . "%'";
458
        }
459
460
        $paperformat = array();
461
462
        $resql = $this->db->query($sql);
463
        if ($resql) {
464
            $num = $this->db->num_rows($resql);
465
            $i = 0;
466
            while ($i < $num) {
467
                $obj = $this->db->fetch_object($resql);
468
                $unitKey = $langs->trans('SizeUnit' . $obj->unit);
469
470
                $paperformat[$obj->code] = $langs->trans('PaperFormat' . strtoupper($obj->code)) . ' - ' . round($obj->width) . 'x' . round($obj->height) . ' ' . ($unitKey == 'SizeUnit' . $obj->unit ? $obj->unit : $unitKey);
471
472
                $i++;
473
            }
474
        } else {
475
            dol_print_error($this->db);
476
            return '';
477
        }
478
        $out = '';
479
480
        $out .= '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
481
        if ($showempty) {
482
            $out .= '<option value=""';
483
            if ($selected == '') {
484
                $out .= ' selected';
485
            }
486
            $out .= '>&nbsp;</option>';
487
        }
488
        foreach ($paperformat as $key => $value) {
489
            if ($selected == $key) {
490
                $out .= '<option value="' . $key . '" selected>' . $value . '</option>';
491
            } else {
492
                $out .= '<option value="' . $key . '">' . $value . '</option>';
493
            }
494
        }
495
        $out .= '</select>';
496
497
        if (!$forcecombo) {
498
            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
499
            $out .= ajax_combobox($htmlname);
500
        }
501
502
        return $out;
503
    }
504
505
506
    /**
507
     * Function to show the combo select to chose a type of field (varchar, int, email, ...)
508
     *
509
     * @param   string  $htmlname               Name of HTML select component
510
     * @param   string  $type                   Type preselected
511
     * @param   array   $typewecanchangeinto    Array of possible switch combination from 1 type to another one. This will grey not possible combinations.
512
     * @return  string                          The combo HTML select component
513
     */
514
    public function selectTypeOfFields($htmlname, $type, $typewecanchangeinto = array())
515
    {
516
        global $type2label; // TODO Remove this
517
518
        $out = '';
519
520
        $out .= '<select class="flat type" id="' . $htmlname . '" name="' . $htmlname . '">';
521
        foreach ($type2label as $key => $val) {
522
            $selected = '';
523
            if ($key == $type) {
524
                $selected = ' selected="selected"';
525
            }
526
527
            // Set $valhtml with the picto for the type
528
            $valhtml = ($key ? getPictoForType($key) : '') . $val;
529
530
            if (empty($typewecanchangeinto) || in_array($key, $typewecanchangeinto[$type])) {
531
                $out .= '<option value="' . $key . '"' . $selected . ' data-html="' . dol_escape_htmltag($valhtml) . '">' . ($val ? $val : '&nbsp;') . '</option>';
532
            } else {
533
                $out .= '<option value="' . $key . '" disabled="disabled"' . $selected . ' data-html="' . dol_escape_htmltag($valhtml) . '">' . ($val ? $val : '&nbsp;') . '</option>';
534
            }
535
        }
536
        $out .= '</select>';
537
        $out .= ajax_combobox('type');
538
539
        return $out;
540
    }
541
}
542