Passed
Branch develop (0646b1)
by
unknown
28:14
created

FormOther::selectyear()   C

Complexity

Conditions 13
Paths 72

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 22
c 0
b 0
f 0
nc 72
nop 9
dl 0
loc 37
rs 6.6166

How to fix   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-2012 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) 2019       Thibault FOUCART        <[email protected]>
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 3 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26
 */
27
28
/**
29
 *	\file       htdocs/core/class/html.formother.class.php
30
 *  \ingroup    core
31
 *	\brief      Fichier de la classe des fonctions predefinie de composants html autre
32
 */
33
34
35
/**
36
 *	Classe permettant la generation de composants html autre
37
 *	Only common components are here.
38
 */
39
class FormOther
40
{
41
    private $db;
42
43
    /**
44
	 * @var string Error code (or message)
45
	 */
46
	public $error;
47
48
49
    /**
50
     *	Constructor
51
     *
52
     *	@param	DoliDB		$db      Database handler
53
     */
54
    public function __construct($db)
55
    {
56
        $this->db = $db;
57
    }
58
59
60
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
61
    /**
62
     *    Return HTML select list of export models
63
     *
64
     *    @param    string	$selected          Id modele pre-selectionne
65
     *    @param    string	$htmlname          Nom de la zone select
66
     *    @param    string	$type              Type des modeles recherches
67
     *    @param    int		$useempty          Show an empty value in list
68
     *    @param    int		$fk_user           User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on)
69
     *    @return	void
70
     */
71
    public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0, $fk_user = null)
72
    {
73
        // phpcs:enable
74
        global $conf, $langs, $user;
75
76
    	$sql = "SELECT rowid, label, fk_user";
77
        $sql .= " FROM ".MAIN_DB_PREFIX."export_model";
78
        $sql .= " WHERE type = '".$this->db->escape($type)."'";
79
		if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model
80
        $sql .= " ORDER BY rowid";
81
        $result = $this->db->query($sql);
82
        if ($result)
83
        {
84
            print '<select class="flat minwidth200" name="'.$htmlname.'" id="'.$htmlname.'">';
85
            if ($useempty)
86
            {
87
                print '<option value="-1">&nbsp;</option>';
88
            }
89
90
            $num = $this->db->num_rows($result);
91
            $i = 0;
92
            while ($i < $num)
93
            {
94
                $obj = $this->db->fetch_object($result);
95
96
                $label = $obj->label;
97
                if ($obj->fk_user == 0) {
98
                	$label .= ' <span class="opacitymedium">('.$langs->trans("Everybody").')</span>';
99
                }
100
                elseif (! empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) {
101
                	$tmpuser = new User($this->db);
102
                	$tmpuser->fetch($obj->fk_user);
103
                	$label .= ' <span class="opacitymedium">('.$tmpuser->getFullName($langs).')</span>';
104
                }
105
106
                if ($selected == $obj->rowid)
107
                {
108
                    print '<option value="'.$obj->rowid.'" selected data-html="'.dol_escape_htmltag($label).'">';
109
                }
110
                else
111
                {
112
                    print '<option value="'.$obj->rowid.'" data-html="'.dol_escape_htmltag($label).'">';
113
                }
114
                print $label;
115
                print '</option>';
116
                $i++;
117
            }
118
            print "</select>";
119
            print ajax_combobox($htmlname);
120
        }
121
        else {
122
            dol_print_error($this->db);
123
        }
124
    }
125
126
127
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
128
    /**
129
     *    Return list of export models
130
     *
131
     *    @param    string	$selected          Id modele pre-selectionne
132
     *    @param    string	$htmlname          Nom de la zone select
133
     *    @param    string	$type              Type des modeles recherches
134
     *    @param    int		$useempty          Affiche valeur vide dans liste
135
     *    @param    int		$fk_user           User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on)
136
     *    @return	void
137
     */
138
    public function select_import_model($selected = '', $htmlname = 'importmodelid', $type = '', $useempty = 0, $fk_user = null)
139
    {
140
        // phpcs:enable
141
    	global $conf, $langs, $user;
142
143
        $sql = "SELECT rowid, label, fk_user";
144
        $sql .= " FROM ".MAIN_DB_PREFIX."import_model";
145
        $sql .= " WHERE type = '".$this->db->escape($type)."'";
146
        if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model
147
        $sql .= " ORDER BY rowid";
148
        $result = $this->db->query($sql);
149
        if ($result)
150
        {
151
            print '<select class="flat minwidth200" name="'.$htmlname.'" id="'.$htmlname.'">';
152
            if ($useempty)
153
            {
154
                print '<option value="-1">&nbsp;</option>';
155
            }
156
157
            $num = $this->db->num_rows($result);
158
            $i = 0;
159
            while ($i < $num)
160
            {
161
                $obj = $this->db->fetch_object($result);
162
163
                $label = $obj->label;
164
                if ($obj->fk_user == 0) {
165
                	$label .= ' <span class="opacitymedium">('.$langs->trans("Everybody").')</span>';
166
                }
167
                elseif (! empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) {
168
                	$tmpuser = new User($this->db);
169
                	$tmpuser->fetch($obj->fk_user);
170
                	$label .= ' <span class="opacitymedium">('.$tmpuser->getFullName($langs).')</span>';
171
                }
172
173
                if ($selected == $obj->rowid)
174
                {
175
                    print '<option value="'.$obj->rowid.'" selected data-html="'.dol_escape_htmltag($label).'">';
176
                }
177
                else
178
                {
179
                    print '<option value="'.$obj->rowid.'" data-html="'.dol_escape_htmltag($label).'">';
180
                }
181
                print $label;
182
                print '</option>';
183
                $i++;
184
            }
185
            print "</select>";
186
            print ajax_combobox($htmlname);
187
        }
188
        else {
189
            dol_print_error($this->db);
190
        }
191
    }
192
193
194
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
195
    /**
196
     *    Return list of ecotaxes with label
197
     *
198
     *    @param	string	$selected   Preselected ecotaxes
199
     *    @param    string	$htmlname	Name of combo list
200
     *    @return	integer
201
     */
202
    public function select_ecotaxes($selected = '', $htmlname = 'ecotaxe_id')
203
    {
204
        // phpcs:enable
205
        global $langs;
206
207
        $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,";
208
        $sql .= " c.label as country";
209
        $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c";
210
        $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid";
211
        $sql .= " ORDER BY country, e.organization ASC, e.code ASC";
212
213
    	dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG);
214
        $resql = $this->db->query($sql);
215
        if ($resql)
216
        {
217
            print '<select class="flat" name="'.$htmlname.'">';
218
            $num = $this->db->num_rows($resql);
219
            $i = 0;
220
            print '<option value="-1">&nbsp;</option>'."\n";
221
            if ($num)
222
            {
223
                while ($i < $num)
224
                {
225
                    $obj = $this->db->fetch_object($resql);
226
                    if ($selected && $selected == $obj->rowid)
227
                    {
228
                        print '<option value="'.$obj->rowid.'" selected>';
229
                    }
230
                    else
231
                    {
232
                        print '<option value="'.$obj->rowid.'">';
233
                        //print '<option onmouseover="showtip(\''.$obj->label.'\')" onMouseout="hidetip()" value="'.$obj->rowid.'">';
234
                    }
235
                    $selectOptionValue = $obj->code.' - '.$obj->label.' : '.price($obj->price).' '.$langs->trans("HT").' ('.$obj->organization.')';
236
                    print $selectOptionValue;
237
                    print '</option>';
238
                    $i++;
239
                }
240
            }
241
            print '</select>';
242
            return 0;
243
        }
244
        else
245
        {
246
            dol_print_error($this->db);
247
            return 1;
248
        }
249
    }
250
251
252
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
253
    /**
254
     *    Return list of revenue stamp for country
255
     *
256
     *    @param	string	$selected   	Value of preselected revenue stamp
257
     *    @param    string	$htmlname   	Name of combo list
258
     *    @param    string	$country_code   Country Code
259
     *    @return	string					HTML select list
260
     */
261
    public function select_revenue_stamp($selected = '', $htmlname = 'revenuestamp', $country_code = '')
262
    {
263
        // phpcs:enable
264
    	global $langs;
265
266
    	$out = '';
267
268
    	$sql = "SELECT r.taux, r.revenuestamp_type";
269
    	$sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c";
270
    	$sql .= " WHERE r.active = 1 AND r.fk_pays = c.rowid";
271
    	$sql .= " AND c.code = '".$country_code."'";
272
273
    	dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG);
274
    	$resql = $this->db->query($sql);
275
    	if ($resql)
276
    	{
277
    		$out .= '<select class="flat" name="'.$htmlname.'">';
278
    		$num = $this->db->num_rows($resql);
279
    		$i = 0;
280
    		$out .= '<option value="0">&nbsp;</option>'."\n";
281
    		if ($num)
282
    		{
283
    			while ($i < $num)
284
    			{
285
    				$obj = $this->db->fetch_object($resql);
286
    				if (($selected && $selected == $obj->taux) || $num == 1)
287
    				{
288
    					$out .= '<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').' selected>';
289
    				}
290
    				else
291
    				{
292
    					$out .= '<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').'>';
293
    					//print '<option onmouseover="showtip(\''.$obj->libelle.'\')" onMouseout="hidetip()" value="'.$obj->rowid.'">';
294
    				}
295
    				$out .= $obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '');
296
    				$out .= '</option>';
297
    				$i++;
298
    			}
299
    		}
300
    		$out .= '</select>';
301
    		return $out;
302
    	}
303
    	else
304
    	{
305
    		dol_print_error($this->db);
306
    		return '';
307
    	}
308
    }
309
310
311
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
312
    /**
313
     *    Return a HTML select list to select a percent
314
     *
315
     *    @param	integer	$selected      	pourcentage pre-selectionne
316
     *    @param    string	$htmlname      	nom de la liste deroulante
317
     *    @param	int		$disabled		Disabled or not
318
     *    @param    int		$increment     	increment value
319
     *    @param    int		$start         	start value
320
     *    @param    int		$end           	end value
321
     *    @param    int     $showempty      Add also an empty line
322
     *    @return   string					HTML select string
323
     */
324
    public function select_percent($selected = 0, $htmlname = 'percent', $disabled = 0, $increment = 5, $start = 0, $end = 100, $showempty = 0)
325
    {
326
        // phpcs:enable
327
        $return = '<select class="flat" name="'.$htmlname.'" '.($disabled ? 'disabled' : '').'>';
328
        if ($showempty) $return .= '<option value="-1"'.(($selected == -1 || $selected == '') ? ' selected' : '').'>&nbsp;</option>';
329
330
        for ($i = $start; $i <= $end; $i += $increment)
331
        {
332
            if ($selected != '' && (int) $selected == $i)
333
            {
334
                $return .= '<option value="'.$i.'" selected>';
335
            }
336
            else
337
            {
338
                $return .= '<option value="'.$i.'">';
339
            }
340
            $return .= $i.' % ';
341
            $return .= '</option>';
342
        }
343
344
        $return .= '</select>';
345
346
        return $return;
347
    }
348
349
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
350
    /**
351
     * Return select list for categories (to use in form search selectors)
352
     *
353
     * @param	int		$type			Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
354
     * @param   integer	$selected     	Preselected value
355
     * @param   string	$htmlname      	Name of combo list
356
     * @param	int		$nocateg		Show also an entry "Not categorized"
357
     * @param   int     $showempty      Add also an empty line
358
     * @param   string  $morecss        More CSS
359
     * @return  string		        	Html combo list code
360
     * @see	select_all_categories()
361
     */
362
    public function select_categories($type, $selected = 0, $htmlname = 'search_categ', $nocateg = 0, $showempty = 1, $morecss = '')
363
    {
364
        // phpcs:enable
365
        global $conf, $langs;
366
        require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
367
368
        // For backward compatibility
369
        if (is_numeric($type))
370
        {
371
            dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
372
        }
373
374
        // Load list of "categories"
375
        $static_categs = new Categorie($this->db);
376
        $tab_categs = $static_categs->get_full_arbo($type);
377
378
        $moreforfilter = '';
379
        // Enhance with select2
380
        if ($conf->use_javascript_ajax)
381
        {
382
            include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
383
            $comboenhancement = ajax_combobox('select_categ_'.$htmlname);
384
            $moreforfilter .= $comboenhancement;
385
        }
386
387
        // Print a select with each of them
388
        $moreforfilter .= '<select class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" id="select_categ_'.$htmlname.'" name="'.$htmlname.'">';
389
        if ($showempty) $moreforfilter .= '<option value="0">&nbsp;</option>'; // Should use -1 to say nothing
390
391
        if (is_array($tab_categs))
0 ignored issues
show
introduced by
The condition is_array($tab_categs) is always false.
Loading history...
392
        {
393
            foreach ($tab_categs as $categ)
394
            {
395
                $moreforfilter .= '<option value="'.$categ['id'].'"';
396
                if ($categ['id'] == $selected) $moreforfilter .= ' selected';
397
                $moreforfilter .= '>'.dol_trunc($categ['fulllabel'], 50, 'middle').'</option>';
398
            }
399
        }
400
        if ($nocateg)
401
        {
402
        	$langs->load("categories");
403
        	$moreforfilter .= '<option value="-2"'.($selected == -2 ? ' selected' : '').'>- '.$langs->trans("NotCategorized").' -</option>';
404
        }
405
        $moreforfilter .= '</select>';
406
407
        return $moreforfilter;
408
    }
409
410
411
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
412
    /**
413
     *  Return select list for categories (to use in form search selectors)
414
     *
415
     *  @param	string	$selected     		Preselected value
416
     *  @param  string	$htmlname      		Name of combo list (example: 'search_sale')
417
     *  @param  User	$user           	Object user
418
     *  @param	int		$showstatus			0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
419
     *  @param	int		$showempty			1=show also an empty value
420
     *  @param	string	$morecss			More CSS
421
     *  @param	int		$norepresentative	Show also an entry "Not categorized"
422
     *  @return string						Html combo list code
423
     */
424
    public function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '', $norepresentative = 0)
425
    {
426
        // phpcs:enable
427
        global $conf, $langs;
428
429
        $langs->load('users');
430
431
        $out = '';
432
        // Enhance with select2
433
        if ($conf->use_javascript_ajax)
434
        {
435
            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
436
437
            $comboenhancement = ajax_combobox($htmlname);
438
            if ($comboenhancement)
439
            {
440
            	$out.=$comboenhancement;
441
            }
442
        }
443
        // Select each sales and print them in a select input
444
        $out.='<select class="flat'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
445
        if ($showempty) $out.='<option value="0">&nbsp;</option>';
446
447
        // Get list of users allowed to be viewed
448
        $sql_usr = "SELECT u.rowid, u.lastname, u.firstname, u.statut, u.login";
449
        $sql_usr.= " FROM ".MAIN_DB_PREFIX."user as u";
450
451
        if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
452
        {
453
        	if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
454
        		$sql_usr.= " WHERE u.entity IS NOT NULL"; // Show all users
455
        	} else {
456
        		$sql_usr.= " WHERE EXISTS (SELECT ug.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug WHERE u.rowid = ug.fk_user AND ug.entity IN (".getEntity('usergroup')."))";
457
        		$sql_usr.= " OR u.entity = 0"; // Show always superadmin
458
        	}
459
        }
460
        else
461
        {
462
        	$sql_usr.= " WHERE u.entity IN (".getEntity('user').")";
463
        }
464
465
        if (empty($user->rights->user->user->lire)) $sql_usr.=" AND u.rowid = ".$user->id;
466
        if (! empty($user->socid)) $sql_usr.=" AND u.fk_soc = ".$user->socid;
467
        // Add existing sales representatives of thirdparty of external user
468
        if (empty($user->rights->user->user->lire) && $user->socid)
469
        {
470
            $sql_usr.=" UNION ";
471
            $sql_usr.= "SELECT u2.rowid, u2.lastname, u2.firstname, u2.statut, u2.login";
472
            $sql_usr.= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc";
473
474
            if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
475
            {
476
            	if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
477
            		$sql_usr.= " WHERE u2.entity IS NOT NULL"; // Show all users
478
            	} else {
479
            		$sql_usr.= " WHERE EXISTS (SELECT ug2.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug2 WHERE u2.rowid = ug2.fk_user AND ug2.entity IN (".getEntity('usergroup')."))";
480
            	}
481
            }
482
            else
483
            {
484
            	$sql_usr.= " WHERE u2.entity IN (".getEntity('user').")";
485
            }
486
487
            $sql_usr.= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->socid;
488
        }
489
	    $sql_usr.= " ORDER BY statut DESC, lastname ASC";  // Do not use 'ORDER BY u.statut' here, not compatible with the UNION.
490
        //print $sql_usr;exit;
491
492
        $resql_usr = $this->db->query($sql_usr);
493
        if ($resql_usr)
494
        {
495
            while ($obj_usr = $this->db->fetch_object($resql_usr))
496
            {
497
                $out.='<option value="'.$obj_usr->rowid.'"';
498
499
                if ($obj_usr->rowid == $selected) $out.=' selected';
500
501
                $out.='>';
502
                $out.=dolGetFirstLastname($obj_usr->firstname, $obj_usr->lastname);
503
                // Complete name with more info
504
                $moreinfo=0;
505
                if (! empty($conf->global->MAIN_SHOW_LOGIN))
506
                {
507
                    $out.=($moreinfo?' - ':' (').$obj_usr->login;
508
                    $moreinfo++;
509
                }
510
                if ($showstatus >= 0)
511
                {
512
					if ($obj_usr->statut == 1 && $showstatus == 1)
513
					{
514
						$out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
515
	                	$moreinfo++;
516
					}
517
					if ($obj_usr->statut == 0)
518
					{
519
						$out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
520
                		$moreinfo++;
521
					}
522
				}
523
				$out.=($moreinfo?')':'');
524
                $out.='</option>';
525
            }
526
            $this->db->free($resql_usr);
527
        }
528
        else
529
        {
530
            dol_print_error($this->db);
531
        }
532
533
        if ($norepresentative)
534
        {
535
        	$langs->load("companies");
536
        	$out.='<option value="-2"'.($selected == -2 ? ' selected':'').'>- '.$langs->trans("NoSalesRepresentativeAffected").' -</option>';
537
        }
538
539
        $out.='</select>';
540
541
        return $out;
542
    }
543
544
    /**
545
     *	Return list of project and tasks
546
     *
547
     *	@param  int		$selectedtask   		Pre-selected task
548
     *  @param  int		$projectid				Project id
549
     * 	@param  string	$htmlname    			Name of html select
550
     * 	@param	int		$modeproject			1 to restrict on projects owned by user
551
     * 	@param	int		$modetask				1 to restrict on tasks associated to user
552
     * 	@param	int		$mode					0=Return list of tasks and their projects, 1=Return projects and tasks if exists
553
     *  @param  int		$useempty       		0=Allow empty values
554
     *  @param	int		$disablechildoftaskid	1=Disable task that are child of the provided task id
555
	 *  @param	string	$filteronprojstatus		Filter on project status ('-1'=no filter, '0,1'=Draft+Validated status)
556
     *  @param	string	$morecss				More css
557
     *  @return	void
558
     */
559
    public function selectProjectTasks($selectedtask = '', $projectid = 0, $htmlname = 'task_parent', $modeproject = 0, $modetask = 0, $mode = 0, $useempty = 0, $disablechildoftaskid = 0, $filteronprojstatus = '', $morecss = '')
560
    {
561
        global $user, $langs;
562
563
        require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
564
565
        //print $modeproject.'-'.$modetask;
566
        $task = new Task($this->db);
567
        $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus);
568
        if ($tasksarray)
0 ignored issues
show
introduced by
$tasksarray is an empty array, thus is always false.
Loading history...
Bug Best Practice introduced by
The expression $tasksarray 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...
569
        {
570
        	print '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
571
            if ($useempty) print '<option value="0">&nbsp;</option>';
572
            $j = 0;
573
            $level = 0;
574
            $this->_pLineSelect($j, 0, $tasksarray, $level, $selectedtask, $projectid, $disablechildoftaskid);
575
            print '</select>';
576
577
            print ajax_combobox($htmlname);
578
        }
579
        else
580
        {
581
            print '<div class="warning">'.$langs->trans("NoProject").'</div>';
582
        }
583
    }
584
585
    /**
586
     * Write lines of a project (all lines of a project if parent = 0)
587
     *
588
     * @param 	int		$inc					Cursor counter
589
     * @param 	int		$parent					Id of parent task we want to see
590
     * @param 	array	$lines					Array of task lines
591
     * @param 	int		$level					Level
592
     * @param 	int		$selectedtask			Id selected task
593
     * @param 	int		$selectedproject		Id selected project
594
     * @param	int		$disablechildoftaskid	1=Disable task that are child of the provided task id
595
     * @return	void
596
     */
597
    private function _pLineSelect(&$inc, $parent, $lines, $level = 0, $selectedtask = 0, $selectedproject = 0, $disablechildoftaskid = 0)
598
    {
599
        global $langs, $user, $conf;
600
601
        $lastprojectid = 0;
602
603
        $numlines = count($lines);
604
        for ($i = 0; $i < $numlines; $i++) {
605
            if ($lines[$i]->fk_parent == $parent) {
606
                $var = !$var;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $var does not seem to be defined for all execution paths leading up to this point.
Loading history...
607
608
                //var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id);		// $lines[$i]->id may be empty if project has no lines
609
610
                // Break on a new project
611
                if ($parent == 0)	// We are on a task at first level
612
                {
613
                    if ($lines[$i]->fk_project != $lastprojectid)	// Break found on project
614
                    {
615
                        if ($i > 0) print '<option value="0" disabled>----------</option>';
616
                        print '<option value="'.$lines[$i]->fk_project.'_0"';
617
                        if ($selectedproject == $lines[$i]->fk_project) print ' selected';
618
                        print '>'; // Project -> Task
619
                        print $langs->trans("Project").' '.$lines[$i]->projectref;
620
                        if (empty($lines[$i]->public))
621
                        {
622
                            print ' ('.$langs->trans("Visibility").': '.$langs->trans("PrivateProject").')';
623
                        }
624
                        else
625
                        {
626
                            print ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')';
627
                        }
628
                        //print '-'.$parent.'-'.$lines[$i]->fk_project.'-'.$lastprojectid;
629
                        print "</option>\n";
630
631
                        $lastprojectid = $lines[$i]->fk_project;
632
                        $inc++;
633
                    }
634
                }
635
636
                $newdisablechildoftaskid = $disablechildoftaskid;
637
638
                // Print task
639
                if (isset($lines[$i]->id))		// We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0
640
                {
641
                	// Check if we must disable entry
642
                	$disabled = 0;
643
                	if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid)))
644
                	{
645
               			$disabled++;
646
               			if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too
647
                	}
648
649
                    print '<option value="'.$lines[$i]->fk_project.'_'.$lines[$i]->id.'"';
650
                    if (($lines[$i]->id == $selectedtask) || ($lines[$i]->fk_project.'_'.$lines[$i]->id == $selectedtask)) print ' selected';
651
                    if ($disabled) print ' disabled';
652
                    print '>';
653
                    print $langs->trans("Project").' '.$lines[$i]->projectref;
654
                    print ' '.$lines[$i]->projectlabel;
655
                    if (empty($lines[$i]->public))
656
                    {
657
                        print ' ('.$langs->trans("Visibility").': '.$langs->trans("PrivateProject").')';
658
                    }
659
                    else
660
                    {
661
                        print ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')';
662
                    }
663
                    if ($lines[$i]->id) print ' > ';
664
                    for ($k = 0; $k < $level; $k++)
665
                    {
666
                        print "&nbsp;&nbsp;&nbsp;";
667
                    }
668
                    print $lines[$i]->ref.' '.$lines[$i]->label."</option>\n";
669
                    $inc++;
670
                }
671
672
                $level++;
673
                if ($lines[$i]->id) $this->_pLineSelect($inc, $lines[$i]->id, $lines, $level, $selectedtask, $selectedproject, $newdisablechildoftaskid);
674
                $level--;
675
            }
676
        }
677
    }
678
679
680
    /**
681
     *  Output a HTML thumb of color or a text if not defined.
682
     *
683
     *  @param	string		$color				String with hex (FFFFFF) or comma RGB ('255,255,255')
684
     *  @param	string		$textifnotdefined	Text to show if color not defined
685
     *  @return	string							HTML code for color thumb
686
     *  @see selectColor()
687
     */
688
    public static function showColor($color, $textifnotdefined = '')
689
    {
690
    	$textcolor = 'FFF';
691
    	include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
692
    	if (colorIsLight($color)) $textcolor = '000';
693
694
    	$color = colorArrayToHex(colorStringToArray($color, array()), '');
695
696
		if ($color) print '<input type="text" class="colorthumb" disabled style="padding: 1px; margin-top: 0; margin-bottom: 0; color: #'.$textcolor.'; background-color: #'.$color.'" value="'.$color.'">';
697
		else print $textifnotdefined;
698
    }
699
700
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
701
    /**
702
     *  Output a HTML code to select a color
703
     *
704
     *  @param	string		$set_color		Pre-selected color
705
     *  @param	string		$prefix			Name of HTML field
706
     *  @param	string		$form_name		Deprecated. Not used.
707
     *  @param	int			$showcolorbox	1=Show color code and color box, 0=Show only color code
708
     *  @param 	array		$arrayofcolors	Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813')
709
     *  @return	void
710
     *  @deprecated Use instead selectColor
711
     *  @see selectColor()
712
     */
713
    public function select_color($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '')
714
    {
715
        // phpcs:enable
716
    	print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors);
717
    }
718
719
    /**
720
     *  Output a HTML code to select a color. Field will return an hexa color like '334455'.
721
     *
722
     *  @param	string		$set_color		Pre-selected color
723
     *  @param	string		$prefix			Name of HTML field
724
     *  @param	string		$form_name		Deprecated. Not used.
725
     *  @param	int			$showcolorbox	1=Show color code and color box, 0=Show only color code
726
     *  @param 	array		$arrayofcolors	Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813')
727
     *  @param	string		$morecss		Add css style into input field
728
     *  @return	string
729
     *  @see showColor()
730
     */
731
    public static function selectColor($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '', $morecss = '')
732
    {
733
        // Deprecation warning
734
        if ($form_name) {
735
            dol_syslog(__METHOD__.": form_name parameter is deprecated", LOG_WARNING);
736
        }
737
738
        global $langs, $conf;
739
740
        $out = '';
741
742
        if (!is_array($arrayofcolors) || count($arrayofcolors) < 1)
743
        {
744
            $langs->load("other");
745
            if (empty($conf->dol_use_jmobile) && !empty($conf->use_javascript_ajax))
746
            {
747
	            $out .= '<link rel="stylesheet" media="screen" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/css/jPicker-1.1.6.css" />';
748
	            $out .= '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/jpicker-1.1.6.js"></script>';
749
	            $out .= '<script type="text/javascript">
750
	             jQuery(document).ready(function(){
751
	                $(\'#colorpicker'.$prefix.'\').jPicker( {
752
	                window: {
753
	                  title: \''.dol_escape_js($langs->trans("SelectAColor")).'\', /* any title for the jPicker window itself - displays "Drag Markers To Pick A Color" if left null */
754
	                  effects:
755
	                    {
756
	                    type: \'show\', /* effect used to show/hide an expandable picker. Acceptable values "slide", "show", "fade" */
757
	                    speed:
758
	                    {
759
	                      show: \'fast\', /* duration of "show" effect. Acceptable values are "fast", "slow", or time in ms */
760
	                      hide: \'fast\' /* duration of "hide" effect. Acceptable values are "fast", "slow", or time in ms */
761
	                    }
762
	                    },
763
	                  position:
764
	                    {
765
	                    x: \'screenCenter\', /* acceptable values "left", "center", "right", "screenCenter", or relative px value */
766
	                    y: \'center\' /* acceptable values "top", "bottom", "center", or relative px value */
767
	                    },
768
	                },
769
	                images: {
770
	                    clientPath: \''.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/images/\',
771
	                    picker: { file: \'../../../../../theme/common/colorpicker.png\', width: 14, height: 14 }
772
	          		},
773
	                localization: // alter these to change the text presented by the picker (e.g. different language)
774
	                  {
775
	                    text:
776
	                    {
777
	                      title: \''.dol_escape_js($langs->trans("SelectAColor")).'\',
778
	                      newColor: \''.dol_escape_js($langs->trans("New")).'\',
779
	                      currentColor: \''.dol_escape_js($langs->trans("Current")).'\',
780
	                      ok: \''.dol_escape_js($langs->trans("Save")).'\',
781
	                      cancel: \''.dol_escape_js($langs->trans("Cancel")).'\'
782
	                    }
783
	                  }
784
			        } ); });
785
	             </script>';
786
            }
787
            $out .= '<input id="colorpicker'.$prefix.'" name="'.$prefix.'" size="6" maxlength="7" class="flat'.($morecss ? ' '.$morecss : '').'" type="text" value="'.dol_escape_htmltag($set_color).'" />';
788
        }
789
        else  // In most cases, this is not used. We used instead function with no specific list of colors
790
        {
791
        	if (empty($conf->dol_use_jmobile) && !empty($conf->use_javascript_ajax))
792
            {
793
	        	$out .= '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.css" type="text/css" media="screen" />';
794
	            $out .= '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.js" type="text/javascript"></script>';
795
	            $out .= '<script type="text/javascript">
796
	             jQuery(document).ready(function(){
797
	                 jQuery(\'#colorpicker'.$prefix.'\').colorpicker({
798
	                     size: 14,
799
	                     label: \'\',
800
	                     hide: true
801
	                 });
802
	             });
803
	             </script>';
804
            }
805
            $out .= '<select id="colorpicker'.$prefix.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$prefix.'">';
806
            //print '<option value="-1">&nbsp;</option>';
807
            foreach ($arrayofcolors as $val)
808
            {
809
                $out .= '<option value="'.$val.'"';
810
                if ($set_color == $val) $out .= ' selected';
811
                $out .= '>'.$val.'</option>';
812
            }
813
            $out .= '</select>';
814
        }
815
816
        return $out;
817
    }
818
819
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
820
    /**
821
     *	Creation d'un icone de couleur
822
     *
823
     *	@param	string	$color		Couleur de l'image
824
     *	@param	string	$module 	Nom du module
825
     *	@param	string	$name		Nom de l'image
826
     *	@param	int		$x 			Largeur de l'image en pixels
827
     *	@param	int		$y      	Hauteur de l'image en pixels
828
     *	@return	void
829
     */
830
    public function CreateColorIcon($color, $module, $name, $x = '12', $y = '12')
831
    {
832
        // phpcs:enable
833
        global $conf;
834
835
        $file = $conf->$module->dir_temp.'/'.$name.'.png';
836
837
        // On cree le repertoire contenant les icones
838
        if (!file_exists($conf->$module->dir_temp))
839
        {
840
            dol_mkdir($conf->$module->dir_temp);
841
        }
842
843
        // On cree l'image en vraies couleurs
844
        $image = imagecreatetruecolor($x, $y);
845
846
        $color = substr($color, 1, 6);
847
848
        $rouge = hexdec(substr($color, 0, 2)); //conversion du canal rouge
849
        $vert  = hexdec(substr($color, 2, 2)); //conversion du canal vert
850
        $bleu  = hexdec(substr($color, 4, 2)); //conversion du canal bleu
851
852
        $couleur = imagecolorallocate($image, $rouge, $vert, $bleu);
853
        //print $rouge.$vert.$bleu;
854
        imagefill($image, 0, 0, $couleur); //on remplit l'image
855
        // On cree la couleur et on l'attribue a une variable pour ne pas la perdre
856
        ImagePng($image, $file); //renvoie une image sous format png
857
        ImageDestroy($image);
858
    }
859
860
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
861
    /**
862
     *    	Return HTML combo list of week
863
     *
864
     *    	@param	string		$selected          Preselected value
865
     *    	@param  string		$htmlname          Nom de la zone select
866
     *    	@param  int			$useempty          Affiche valeur vide dans liste
867
     *    	@return	string
868
     */
869
    public function select_dayofweek($selected = '', $htmlname = 'weekid', $useempty = 0)
870
    {
871
        // phpcs:enable
872
        global $langs;
873
874
        $week = array(
875
            0=>$langs->trans("Day0"),
876
            1=>$langs->trans("Day1"),
877
            2=>$langs->trans("Day2"),
878
            3=>$langs->trans("Day3"),
879
            4=>$langs->trans("Day4"),
880
            5=>$langs->trans("Day5"),
881
            6=>$langs->trans("Day6")
882
        );
883
884
        $select_week = '<select class="flat" name="'.$htmlname.'">';
885
        if ($useempty)
886
        {
887
            $select_week .= '<option value="-1">&nbsp;</option>';
888
        }
889
        foreach ($week as $key => $val)
890
        {
891
            if ($selected == $key)
892
            {
893
                $select_week .= '<option value="'.$key.'" selected>';
894
            }
895
            else
896
            {
897
                $select_week .= '<option value="'.$key.'">';
898
            }
899
            $select_week .= $val;
900
            $select_week .= '</option>';
901
        }
902
        $select_week .= '</select>';
903
        return $select_week;
904
    }
905
906
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
907
    /**
908
     *      Return HTML combo list of month
909
     *
910
     *      @param  string      $selected          	Preselected value
911
     *      @param  string      $htmlname          	Name of HTML select object
912
     *      @param  int         $useempty          	Show empty in list
913
     *      @param  int         $longlabel         	Show long label
914
     *      @param	string		$morecss			More Css
915
     *      @return string
916
     */
917
    public function select_month($selected = '', $htmlname = 'monthid', $useempty = 0, $longlabel = 0, $morecss = 'maxwidth50imp valignmiddle')
918
    {
919
        // phpcs:enable
920
        global $langs;
921
922
        require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
923
924
        if ($longlabel) $montharray = monthArray($langs, 0); // Get array
925
        else $montharray = monthArray($langs, 1);
926
927
        $select_month = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
928
        if ($useempty)
929
        {
930
            $select_month .= '<option value="0">&nbsp;</option>';
931
        }
932
        foreach ($montharray as $key => $val)
933
        {
934
            if ($selected == $key)
935
            {
936
                $select_month .= '<option value="'.$key.'" selected>';
937
            }
938
            else
939
            {
940
                $select_month .= '<option value="'.$key.'">';
941
            }
942
            $select_month .= $val;
943
            $select_month .= '</option>';
944
        }
945
        $select_month .= '</select>';
946
        return $select_month;
947
    }
948
949
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
950
    /**
951
     *	Return HTML combo list of years
952
     *
953
     *  @param  string		$selected       Preselected value (''=current year, -1=none, year otherwise)
954
     *  @param  string		$htmlname       Name of HTML select object
955
     *  @param  int			$useempty       Affiche valeur vide dans liste
956
     *  @param  int			$min_year       Offset of minimum year into list (by default current year -10)
957
     *  @param  int		    $max_year		Offset of maximum year into list (by default current year + 5)
958
     *  @param	int			$offset			Offset
959
     *  @param	int			$invert			Invert
960
     *  @param	string		$option			Option
961
     *  @param	string		$morecss		More CSS
962
     *  @return	string
963
     */
964
    public function select_year($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp')
965
    {
966
        // phpcs:enable
967
        print $this->selectyear($selected, $htmlname, $useempty, $min_year, $max_year, $offset, $invert, $option, $morecss);
968
    }
969
970
    /**
971
     *	Return HTML combo list of years
972
     *
973
     *  @param  string	$selected       Preselected value (''=current year, -1=none, year otherwise)
974
     *  @param  string	$htmlname       Name of HTML select object
975
     *  @param  int	    $useempty       Affiche valeur vide dans liste
976
     *  @param  int	    $min_year		Offset of minimum year into list (by default current year -10)
977
     *  @param  int	    $max_year       Offset of maximum year into list (by default current year + 5)
978
     *  @param	int		$offset			Offset
979
     *  @param	int		$invert			Invert
980
     *  @param	string	$option			Option
981
     *  @param	string	$morecss		More css
982
     *  @return	string
983
     */
984
    public function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp')
985
    {
986
        $out = '';
987
988
        $currentyear = date("Y") + $offset;
989
        $max_year = $currentyear + $max_year;
990
        $min_year = $currentyear - $min_year;
991
        if (empty($selected) && empty($useempty)) $selected = $currentyear;
992
993
        $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$option.' >';
994
        if ($useempty)
995
        {
996
        	$selected_html = '';
997
            if ($selected == '') $selected_html = ' selected';
998
            $out .= '<option value=""'.$selected_html.'>&nbsp;</option>';
999
        }
1000
        if (!$invert)
1001
        {
1002
            for ($y = $max_year; $y >= $min_year; $y--)
1003
            {
1004
                $selected_html = '';
1005
                if ($selected > 0 && $y == $selected) $selected_html = ' selected';
1006
                $out .= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
1007
            }
1008
        }
1009
        else
1010
        {
1011
            for ($y = $min_year; $y <= $max_year; $y++)
1012
            {
1013
                $selected_html = '';
1014
                if ($selected > 0 && $y == $selected) $selected_html = ' selected';
1015
                $out .= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
1016
            }
1017
        }
1018
        $out .= "</select>\n";
1019
1020
        return $out;
1021
    }
1022
1023
1024
    /**
1025
     * 	Get array with HTML tabs with boxes of a particular area including personalized choices of user.
1026
     *  Class 'Form' must be known.
1027
     *
1028
     * 	@param	   User         $user		 Object User
1029
     * 	@param	   String       $areacode    Code of area for pages - 0 = Home page ... See getListOfPagesForBoxes()
1030
	 *	@return    array                     array('selectboxlist'=>, 'boxactivated'=>, 'boxlista'=>, 'boxlistb'=>)
1031
     */
1032
    public static function getBoxesArea($user, $areacode)
1033
    {
1034
        global $conf, $langs, $db;
1035
1036
        include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
1037
1038
        $confuserzone = 'MAIN_BOXES_'.$areacode;
1039
1040
        // $boxactivated will be array of boxes enabled into global setup
1041
        // $boxidactivatedforuser will be array of boxes choosed by user
1042
1043
        $selectboxlist = '';
1044
        $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup)
1045
1046
        $boxidactivatedforuser = array();
1047
        foreach ($boxactivated as $box)
1048
        {
1049
        	if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user
1050
        }
1051
1052
        // Define selectboxlist
1053
        $arrayboxtoactivatelabel = array();
1054
        if (!empty($user->conf->$confuserzone))
1055
        {
1056
        	$boxorder = '';
1057
        	$langs->load("boxes"); // Load label of boxes
1058
        	foreach ($boxactivated as $box)
1059
        	{
1060
        		if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user
1061
        		$label = $langs->transnoentitiesnoconv($box->boxlabel);
1062
        		//if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')';
1063
        		if (preg_match('/graph/', $box->class) && $conf->browser->layout != 'phone')
1064
        		{
1065
        			$label = $label.' <span class="fa fa-bar-chart"></span>';
1066
        		}
1067
        		$arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list
1068
        	}
1069
            foreach ($boxidactivatedforuser as $boxid)
1070
        	{
1071
       			if (empty($boxorder)) $boxorder .= 'A:';
1072
  				$boxorder .= $boxid.',';
1073
        	}
1074
1075
        	//var_dump($boxidactivatedforuser);
1076
1077
        	// Class Form must have been already loaded
1078
        	$selectboxlist .= '<!-- Form with select box list -->'."\n";
1079
			$selectboxlist .= '<form id="addbox" name="addbox" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1080
			$selectboxlist .= '<input type="hidden" name="addbox" value="addbox">';
1081
			$selectboxlist .= '<input type="hidden" name="userid" value="'.$user->id.'">';
1082
			$selectboxlist .= '<input type="hidden" name="areacode" value="'.$areacode.'">';
1083
			$selectboxlist .= '<input type="hidden" name="boxorder" value="'.$boxorder.'">';
1084
			$selectboxlist .= Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1);
1085
            if (empty($conf->use_javascript_ajax)) $selectboxlist .= ' <input type="submit" class="button" value="'.$langs->trans("AddBox").'">';
1086
            $selectboxlist .= '</form>';
1087
            if (!empty($conf->use_javascript_ajax))
1088
            {
1089
            	include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1090
            	$selectboxlist .= ajax_combobox("boxcombo");
1091
            }
1092
        }
1093
1094
        // Javascript code for dynamic actions
1095
        if (!empty($conf->use_javascript_ajax))
1096
        {
1097
	        $selectboxlist .= '<script type="text/javascript" language="javascript">
1098
1099
	        // To update list of activated boxes
1100
	        function updateBoxOrder(closing) {
1101
	        	var left_list = cleanSerialize(jQuery("#boxhalfleft").sortable("serialize"));
1102
	        	var right_list = cleanSerialize(jQuery("#boxhalfright").sortable("serialize"));
1103
	        	var boxorder = \'A:\' + left_list + \'-B:\' + right_list;
1104
	        	if (boxorder==\'A:A-B:B\' && closing == 1)	// There is no more boxes on screen, and we are after a delete of a box so we must hide title
1105
	        	{
1106
	        		jQuery.ajax({
1107
	        			url: \''.DOL_URL_ROOT.'/core/ajax/box.php?closing=0&boxorder=\'+boxorder+\'&zone='.$areacode.'&userid=\'+'.$user->id.',
1108
	        			async: false
1109
	        		});
1110
	        		// We force reload to be sure to get all boxes into list
1111
	        		window.location.search=\'mainmenu='.GETPOST("mainmenu", "aZ09").'&leftmenu='.GETPOST('leftmenu', "aZ09").'&action=delbox\';
1112
	        	}
1113
	        	else
1114
	        	{
1115
	        		jQuery.ajax({
1116
	        			url: \''.DOL_URL_ROOT.'/core/ajax/box.php?closing=\'+closing+\'&boxorder=\'+boxorder+\'&zone='.$areacode.'&userid=\'+'.$user->id.',
1117
	        			async: true
1118
	        		});
1119
	        	}
1120
	        }
1121
1122
	        jQuery(document).ready(function() {
1123
	        	jQuery("#boxcombo").change(function() {
1124
	        	var boxid=jQuery("#boxcombo").val();
1125
	        		if (boxid > 0) {
1126
	            		var left_list = cleanSerialize(jQuery("#boxhalfleft").sortable("serialize"));
1127
	            		var right_list = cleanSerialize(jQuery("#boxhalfright").sortable("serialize"));
1128
	            		var boxorder = \'A:\' + left_list + \'-B:\' + right_list;
1129
	    				jQuery.ajax({
1130
	    					url: \''.DOL_URL_ROOT.'/core/ajax/box.php?boxorder=\'+boxorder+\'&boxid=\'+boxid+\'&zone='.$areacode.'&userid='.$user->id.'\',
1131
	    			        async: false
1132
	    		        });
1133
	        			window.location.search=\'mainmenu='.GETPOST("mainmenu", "aZ09").'&leftmenu='.GETPOST('leftmenu', "aZ09").'&action=addbox&boxid=\'+boxid;
1134
	                }
1135
	        	});';
1136
	        	if (!count($arrayboxtoactivatelabel)) $selectboxlist .= 'jQuery("#boxcombo").hide();';
1137
	        	$selectboxlist .= '
1138
1139
	        	jQuery("#boxhalfleft, #boxhalfright").sortable({
1140
	    	    	handle: \'.boxhandle\',
1141
	    	    	revert: \'invalid\',
1142
	       			items: \'.boxdraggable\',
1143
					containment: \'document\',
1144
	        		connectWith: \'#boxhalfleft, #boxhalfright\',
1145
	        		stop: function(event, ui) {
1146
	        			updateBoxOrder(1);  /* 1 to avoid message after a move */
1147
	        		}
1148
	    		});
1149
1150
	        	jQuery(".boxclose").click(function() {
1151
	        		var self = this;	// because JQuery can modify this
1152
	        		var boxid=self.id.substring(8);
1153
	        		var label=jQuery(\'#boxlabelentry\'+boxid).val();
1154
	        		console.log("We close box "+boxid);
1155
	        		jQuery(\'#boxto_\'+boxid).remove();
1156
	        		if (boxid > 0) jQuery(\'#boxcombo\').append(new Option(label, boxid));
1157
	        		updateBoxOrder(1);  /* 1 to avoid message after a remove */
1158
	        	});
1159
1160
        	});'."\n";
1161
1162
	        $selectboxlist .= '</script>'."\n";
1163
        }
1164
1165
        // Define boxlista and boxlistb
1166
        $nbboxactivated = count($boxidactivatedforuser);
1167
1168
        if ($nbboxactivated)
1169
        {
1170
        	// Load translation files required by the page
1171
            $langs->loadLangs(array("boxes", "projects"));
1172
1173
        	$emptybox = new ModeleBoxes($db);
1174
1175
            $boxlista .= "\n<!-- Box left container -->\n";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $boxlista seems to be never defined.
Loading history...
1176
1177
            // Define $box_max_lines
1178
            $box_max_lines = 5;
1179
            if (!empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines = $conf->global->MAIN_BOXES_MAXLINES;
1180
1181
            $ii = 0;
1182
            foreach ($boxactivated as $key => $box)
1183
            {
1184
            	if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1185
				if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'A'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0
1186
            	if (preg_match('/^A/i', $box->box_order)) // column A
1187
                {
1188
                    $ii++;
1189
                    //print 'box_id '.$boxactivated[$ii]->box_id.' ';
1190
                    //print 'box_order '.$boxactivated[$ii]->box_order.'<br>';
1191
                    // Show box
1192
                    $box->loadBox($box_max_lines);
1193
                    $boxlista .= $box->outputBox();
1194
                }
1195
            }
1196
1197
            if ($conf->browser->layout != 'phone')
1198
            {
1199
            	$emptybox->box_id = 'A';
1200
            	$emptybox->info_box_head = array();
1201
            	$emptybox->info_box_contents = array();
1202
            	$boxlista .= $emptybox->outputBox(array(), array());
1203
            }
1204
            $boxlista .= "<!-- End box left container -->\n";
1205
1206
            $boxlistb .= "\n<!-- Box right container -->\n";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $boxlistb seems to be never defined.
Loading history...
1207
1208
            $ii = 0;
1209
            foreach ($boxactivated as $key => $box)
1210
            {
1211
            	if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1212
            	if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0
1213
            	if (preg_match('/^B/i', $box->box_order)) // colonne B
1214
                {
1215
                    $ii++;
1216
                    //print 'box_id '.$boxactivated[$ii]->box_id.' ';
1217
                    //print 'box_order '.$boxactivated[$ii]->box_order.'<br>';
1218
                    // Show box
1219
                    $box->loadBox($box_max_lines);
1220
                    $boxlistb .= $box->outputBox();
1221
                }
1222
            }
1223
1224
            if ($conf->browser->layout != 'phone')
1225
            {
1226
            	$emptybox->box_id = 'B';
1227
            	$emptybox->info_box_head = array();
1228
            	$emptybox->info_box_contents = array();
1229
            	$boxlistb .= $emptybox->outputBox(array(), array());
1230
            }
1231
1232
            $boxlistb .= "<!-- End box right container -->\n";
1233
        }
1234
1235
        return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb);
1236
    }
1237
1238
1239
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1240
    /**
1241
     *  Return a HTML select list of a dictionary
1242
     *
1243
     *  @param  string	$htmlname          	Name of select zone
1244
     *  @param	string	$dictionarytable	Dictionary table
1245
     *  @param	string	$keyfield			Field for key
1246
     *  @param	string	$labelfield			Label field
1247
     *  @param	string	$selected			Selected value
1248
     *  @param  int		$useempty          	1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
1249
     *  @param  string  $moreattrib         More attributes on HTML select tag
1250
     * 	@return	void
1251
     */
1252
    public function select_dictionary($htmlname, $dictionarytable, $keyfield = 'code', $labelfield = 'label', $selected = '', $useempty = 0, $moreattrib = '')
1253
    {
1254
        // phpcs:enable
1255
        global $langs, $conf;
1256
1257
        $langs->load("admin");
1258
1259
        $sql = "SELECT rowid, ".$keyfield.", ".$labelfield;
1260
        $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable;
1261
        $sql .= " ORDER BY ".$labelfield;
1262
1263
        dol_syslog(get_class($this)."::select_dictionary", LOG_DEBUG);
1264
        $result = $this->db->query($sql);
1265
        if ($result)
1266
        {
1267
            $num = $this->db->num_rows($result);
1268
            $i = 0;
1269
            if ($num)
1270
            {
1271
                print '<select id="select'.$htmlname.'" class="flat selectdictionary" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
1272
                if ($useempty == 1 || ($useempty == 2 && $num > 1))
1273
                {
1274
                    print '<option value="-1">&nbsp;</option>';
1275
                }
1276
1277
                while ($i < $num)
1278
                {
1279
                    $obj = $this->db->fetch_object($result);
1280
                    if ($selected == $obj->rowid || $selected == $obj->$keyfield)
1281
                    {
1282
                        print '<option value="'.$obj->$keyfield.'" selected>';
1283
                    }
1284
                    else
1285
                    {
1286
                        print '<option value="'.$obj->$keyfield.'">';
1287
                    }
1288
                    print $obj->$labelfield;
1289
                    print '</option>';
1290
                    $i++;
1291
                }
1292
                print "</select>";
1293
            } else {
1294
                print $langs->trans("DictionaryEmpty");
1295
            }
1296
        }
1297
        else {
1298
            dol_print_error($this->db);
1299
        }
1300
    }
1301
1302
    /**
1303
	 *	Return an html string with a select combo box to choose yes or no
1304
	 *
1305
	 *	@param	string		$htmlname		Name of html select field
1306
	 *	@param	string		$value			Pre-selected value
1307
	 *	@param	int			$option			0 return automatic/manual, 1 return 1/0
1308
	 *	@param	bool		$disabled		true or false
1309
	 *  @param	int      	$useempty		1=Add empty line
1310
	 *	@return	string						See option
1311
	 */
1312
    public function selectAutoManual($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0)
1313
	{
1314
		global $langs;
1315
1316
		$automatic = "automatic"; $manual = "manual";
1317
		if ($option)
1318
		{
1319
			$automatic = "1";
1320
			$manual = "0";
1321
		}
1322
1323
		$disabled = ($disabled ? ' disabled' : '');
1324
1325
		$resultautomanual = '<select class="flat width100" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
1326
		if ($useempty) $resultautomanual .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
1327
		if (("$value" == 'automatic') || ($value == 1))
1328
		{
1329
			$resultautomanual .= '<option value="'.$automatic.'" selected>'.$langs->trans("Automatic").'</option>'."\n";
1330
			$resultautomanual .= '<option value="'.$manual.'">'.$langs->trans("Manual").'</option>'."\n";
1331
		}
1332
		else
1333
	    {
1334
	   		$selected=(($useempty && $value != '0' && $value != 'manual')?'':' selected');
1335
			$resultautomanual .= '<option value="'.$automatic.'">'.$langs->trans("Automatic").'</option>'."\n";
1336
			$resultautomanual .= '<option value="'.$manual.'"'.$selected.'>'.$langs->trans("Manual").'</option>'."\n";
1337
		}
1338
		$resultautomanual .= '</select>'."\n";
1339
		return $resultautomanual;
1340
	}
1341
}
1342