Completed
Branch develop (348e00)
by
unknown
24:02
created

FormProjets   D

Complexity

Total Complexity 130

Size/Duplication

Total Lines 599
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 599
rs 4.8717
c 0
b 0
f 0
wmc 130
lcom 1
cbo 3

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
D select_projects() 0 46 10
F select_projects_list() 0 155 40
F selectTasks() 0 143 35
F select_element() 0 98 28
C selectOpportunityStatus() 0 61 16

How to fix   Complexity   

Complex Class

Complex classes like FormProjets often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FormProjets, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* Copyright (c) 2013 Florian Henry  <[email protected]>
3
 * Copyright (C) 2015 Marcos García  <[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
/**
20
 *      \file       htdocs/core/class/html.formprojet.class.php
21
 *      \ingroup    core
22
 *      \brief      Class file for html component project
23
 */
24
25
26
/**
27
 *      Class to manage building of HTML components
28
 */
29
class FormProjets
30
{
31
	var $db;
32
	var $error;
33
34
35
	/**
36
	 *	Constructor
37
	 *
38
	 *  @param		DoliDB		$db      Database handler
39
	 */
40
	function __construct($db)
41
	{
42
		$this->db = $db;
43
		return 1;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
44
	}
45
46
	/**
47
	 *	Output a combo list with projects qualified for a third party / user
48
	 *
49
	 *	@param	int		$socid      	Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
50
	 *	@param  int		$selected   	Id project preselected
51
	 *	@param  string	$htmlname   	Name of HTML field
52
	 *	@param	int		$maxlength		Maximum length of label
53
	 *	@param	int		$option_only	Return only html options lines without the select tag
54
	 *	@param	int		$show_empty		Add an empty line
55
	 *  @param	int		$discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
56
	 *  @param	int		$forcefocus		Force focus on field (works with javascript only)
57
	 *  @param	int		$disabled		Disabled
58
	 *  @param  int     $mode           0 for HTML mode and 1 for JSON mode
59
	 *  @param  string  $filterkey      Key to filter
60
	 *  @param  int     $nooutput       No print output. Return it only.
61
	 *  @param  int     $forceaddid     Force to add project id in list, event if not qualified
62
	 *  @param  string  $morecss        More css
63
	 *	@return string           		Return html content
64
	 */
65
	function select_projects($socid=-1, $selected='', $htmlname='projectid', $maxlength=16, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode = 0, $filterkey = '', $nooutput=0, $forceaddid=0, $morecss='')
66
	{
67
		global $langs,$conf,$form;
68
69
		$out='';
70
		
71
		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT))
72
		{
73
			$placeholder='';
74
75
			if ($selected && empty($selected_input_value))
0 ignored issues
show
Bug introduced by
The variable $selected_input_value seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
76
			{
77
				require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
78
				$project = new Project($this->db);
79
				$project->fetch($selected);
80
				$selected_input_value=$project->ref;
81
			}
82
			$urloption='socid='.$socid.'&htmlname='.$htmlname;
83
			$out.=ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PROJECT_USE_SEARCH_TO_SELECT, 0, array(
84
//				'update' => array(
85
//					'projectid' => 'id'
86
//				)
87
			));
88
89
			$out.='<input type="text" class="minwidth200'.($morecss?' '.$morecss:'').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
0 ignored issues
show
Bug introduced by
The variable $selected_input_value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
90
		}
91
		else
92
		{
93
			$out.=$this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey, 1);
94
			if ($discard_closed) 
95
			{
96
			    if (class_exists('Form'))
97
			    {
98
    			    if (empty($form)) $form=new Form($this->db);
99
                    $out.=$form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden"));
100
			    }
101
			}
102
		}
103
		
104
		if (empty($nooutput)) 
105
		{
106
		    print $out;
107
		    return '';
108
		}
109
		else return $out;
110
	}
111
112
	/**
113
	 * Returns an array with projects qualified for a third party
114
	 *
115
	 * @param  int     $socid      	       Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
116
	 * @param  int     $selected   	       Id project preselected
117
	 * @param  string  $htmlname   	       Nom de la zone html
118
	 * @param  int     $maxlength          Maximum length of label
119
	 * @param  int     $option_only	       Return only html options lines without the select tag
120
	 * @param  int     $show_empty		   Add an empty line
121
	 * @param  int     $discard_closed     Discard closed projects (0=Keep,1=hide completely,2=Disable)
122
     * @param  int     $forcefocus		   Force focus on field (works with javascript only)
123
     * @param  int     $disabled           Disabled
124
	 * @param  int     $mode               0 for HTML mode and 1 for array return (to be used by json_encode for example)
125
	 * @param  string  $filterkey          Key to filter
126
	 * @param  int     $nooutput           No print output. Return it only.
127
	 * @param  int     $forceaddid         Force to add project id in list, event if not qualified
128
	 * @return int         			       Nb of project if OK, <0 if KO
129
	 */
130
	function select_projects_list($socid=-1, $selected='', $htmlname='projectid', $maxlength=24, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode=0, $filterkey = '', $nooutput=0, $forceaddid=0)
131
	{
132
		global $user,$conf,$langs;
133
134
		require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
135
136
		$out='';
137
        $outarray=array();
138
        
139
		$hideunselectables = false;
140
		if (! empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
141
142
		$projectsListId = false;
143
		if (empty($user->rights->projet->all->lire))
144
		{
145
			$projectstatic=new Project($this->db);
146
			$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1);
147
		}
148
149
150
		// Search all projects
151
		$sql = 'SELECT p.rowid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public';
152
		$sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p';
153
		$sql.= " WHERE p.entity IN (".getEntity('project', 1).")";
154
		if ($projectsListId !== false) $sql.= " AND p.rowid IN (".$projectsListId.")";
155
		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
156
		if ($socid > 0 && empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
157
		if (!empty($filterkey)) {
158
			$sql .= " AND p.title LIKE '%".$this->db->escape($filterkey)."%'";
159
			$sql .= " OR p.ref LIKE '%".$this->db->escape($filterkey)."%'";
160
		}
161
		$sql.= " ORDER BY p.ref ASC";
162
163
		dol_syslog(__METHOD__, LOG_DEBUG);
164
		$resql=$this->db->query($sql);
165
		if ($resql)
166
		{
167
			$minmax='maxwidth500';
168
169
			// Use select2 selector
170
			$nodatarole='';
171
			if (! empty($conf->use_javascript_ajax))
172
			{
173
				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
174
	           	$comboenhancement = ajax_combobox($htmlname, array(), 0, $forcefocus);
175
            	$out.=$comboenhancement;
176
            	$nodatarole=($comboenhancement?' data-role="none"':'');
177
            	$minmax='minwidth100 maxwidth300';
178
			}
179
180
			if (empty($option_only)) {
181
				$out.= '<select class="flat'.($minmax?' '.$minmax:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlname.'" name="'.$htmlname.'"'.$nodatarole.'>';
182
			}
183
			if (!empty($show_empty)) {
184
				$out.= '<option value="0">&nbsp;</option>';
185
			}
186
			$num = $this->db->num_rows($resql);
187
			$i = 0;
188
			if ($num)
189
			{
190
				while ($i < $num)
191
				{
192
					$obj = $this->db->fetch_object($resql);
193
					// If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
194
					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
195
					{
196
						// Do nothing
197
					}
198
					else
199
					{
200
						if ($discard_closed == 1 && $obj->fk_statut == 2 && $obj->rowid != $selected) // We discard closed except if selected
201
						{
202
							$i++;
203
							continue;
204
						}
205
206
						$labeltoshow=dol_trunc($obj->ref,18);
207
						//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
208
						//else $labeltoshow.=' ('.$langs->trans("Private").')';
209
						$labeltoshow.=' '.dol_trunc($obj->title,$maxlength);
210
211
						$disabled=0;
212
						if ($obj->fk_statut == 0)
213
						{
214
							$disabled=1;
215
							$labeltoshow.=' - '.$langs->trans("Draft");
216
						}
217
						else if ($obj->fk_statut == 2)
218
						{
219
							if ($discard_close == 2) $disabled=1;
0 ignored issues
show
Bug introduced by
The variable $discard_close does not exist. Did you mean $discard_closed?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
220
							$labeltoshow.=' - '.$langs->trans("Closed");
221
						}
222
						else if ( empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
223
						{
224
							$disabled=1;
225
							$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
226
						}
227
228
						if (!empty($selected) && $selected == $obj->rowid)
229
						{
230
							$out.= '<option value="'.$obj->rowid.'" selected';
231
							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
232
							$out.= '>'.$labeltoshow.'</option>';
233
						}
234
						else
235
						{
236
							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
237
							{
238
								$resultat='';
239
							}
240
							else
241
							{
242
								$resultat='<option value="'.$obj->rowid.'"';
243
								if ($disabled) $resultat.=' disabled';
244
								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
245
								//else $labeltoshow.=' ('.$langs->trans("Private").')';
246
								$resultat.='>';
247
								$resultat.=$labeltoshow;
248
								$resultat.='</option>';
249
							}
250
							$out.= $resultat;
251
252
							$outarray[] = array(
253
								'key' => (int) $obj->rowid,
254
								'value' => $obj->ref,
255
								'ref' => $obj->ref,
256
								'label' => $labeltoshow,
257
								'disabled' => (bool) $disabled
258
							);
259
						}
260
					}
261
					$i++;
262
				}
263
			}
264
265
			$this->db->free($resql);
266
267
			if (!$mode) {
268
				if (empty($option_only)) $out.= '</select>';
269
				if (empty($nooutput)) 
270
				{
271
				    print $out;
272
				    return '';
273
				}
274
				else return $out;
275
			} else {
276
				return $outarray;
277
			}
278
		}
279
		else
280
		{
281
			dol_print_error($this->db);
282
			return -1;
283
		}
284
	}
285
286
	/**
287
	 *	Output a combo list with projects qualified for a third party
288
	 *
289
	 *	@param	int		$socid      	Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
290
	 *	@param  int		$selected   	Id task preselected
291
	 *	@param  string	$htmlname   	Name of HTML select
292
	 *	@param	int		$maxlength		Maximum length of label
293
	 *	@param	int		$option_only	Return only html options lines without the select tag
294
	 *	@param	int		$show_empty		Add an empty line
295
	 *  @param	int		$discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
296
     *  @param	int		$forcefocus		Force focus on field (works with javascript only)
297
     *  @param	int		$disabled		Disabled
298
	 *	@return int         			Nbr of project if OK, <0 if KO
299
	 */
300
	function selectTasks($socid=-1, $selected='', $htmlname='taskid', $maxlength=24, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0)
301
	{
302
		global $user,$conf,$langs;
303
304
		require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
305
306
		$out='';
307
308
		$hideunselectables = false;
309
		if (! empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
310
311
		$projectsListId = false;
312
		if (empty($user->rights->projet->all->lire))
313
		{
314
			$projectstatic=new Project($this->db);
315
			$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1);
316
		}
317
318
		// Search all projects
319
		$sql = 'SELECT t.rowid, t.ref as tref, t.label as tlabel, p.ref, p.title, p.fk_soc, p.fk_statut, p.public,';
320
		$sql.= ' s.nom as name';
321
		$sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p';
322
		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc';
323
		$sql.= ', '.MAIN_DB_PREFIX.'projet_task as t';
324
		$sql.= " WHERE p.entity = ".$conf->entity;
325
		$sql.= " AND t.fk_projet = p.rowid";
326
		if ($projectsListId !== false) $sql.= " AND p.rowid IN (".$projectsListId.")";
327
		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
328
		if ($socid > 0)  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
329
		$sql.= " ORDER BY p.ref, t.ref ASC";
330
331
		dol_syslog(__METHOD__, LOG_DEBUG);
332
		$resql=$this->db->query($sql);
333
		if ($resql)
334
		{
335
			$minmax='maxwidth500';
336
337
			// Use select2 selector
338
			$nodatarole='';
339
			if (! empty($conf->use_javascript_ajax))
340
			{
341
				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
342
	           	$comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
343
            	$out.=$comboenhancement;
344
            	$nodatarole=($comboenhancement?' data-role="none"':'');
345
            	$minmax='minwidth200 maxwidth500';
346
			}
347
348
			if (empty($option_only)) {
349
				$out.= '<select class="flat'.($minmax?' '.$minmax:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlname.'" name="'.$htmlname.'"'.$nodatarole.'>';
350
			}
351
			if (!empty($show_empty)) {
352
				$out.= '<option value="0">&nbsp;</option>';
353
			}
354
			$num = $this->db->num_rows($resql);
355
			$i = 0;
356
			if ($num)
357
			{
358
				while ($i < $num)
359
				{
360
					$obj = $this->db->fetch_object($resql);
361
					// If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
362
					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
363
					{
364
						// Do nothing
365
					}
366
					else
367
					{
368
						if ($discard_closed == 1 && $obj->fk_statut == 2)
369
						{
370
							$i++;
371
							continue;
372
						}
373
374
						$labeltoshow=dol_trunc($obj->ref,18);
375
						//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
376
						//else $labeltoshow.=' ('.$langs->trans("Private").')';
377
						$labeltoshow.=' '.dol_trunc($obj->title,$maxlength);
378
379
						if ($obj->name) $labeltoshow.=' ('.$obj->name.')';
380
381
						$disabled=0;
382
						if ($obj->fk_statut == 0)
383
						{
384
							$disabled=1;
385
							$labeltoshow.=' - '.$langs->trans("Draft");
386
						}
387
						else if ($obj->fk_statut == 2)
388
						{
389
							if ($discard_closed == 2) $disabled=1;
390
							$labeltoshow.=' - '.$langs->trans("Closed");
391
						}
392
						else if ($socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
393
						{
394
							$disabled=1;
395
							$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
396
						}
397
						// Label for task
398
						$labeltoshow.=' - '.$obj->tref.' '.dol_trunc($obj->tlabel,$maxlength);
399
400
						if (!empty($selected) && $selected == $obj->rowid)
401
						{
402
							$out.= '<option value="'.$obj->rowid.'" selected';
403
							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
404
							$out.= '>'.$labeltoshow.'</option>';
405
						}
406
						else
407
						{
408
							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
409
							{
410
								$resultat='';
411
							}
412
							else
413
							{
414
								$resultat='<option value="'.$obj->rowid.'"';
415
								if ($disabled) $resultat.=' disabled';
416
								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
417
								//else $labeltoshow.=' ('.$langs->trans("Private").')';
418
								$resultat.='>';
419
								$resultat.=$labeltoshow;
420
								$resultat.='</option>';
421
							}
422
							$out.= $resultat;
423
						}
424
					}
425
					$i++;
426
				}
427
			}
428
			if (empty($option_only)) {
429
				$out.= '</select>';
430
			}
431
432
			print $out;
433
434
			$this->db->free($resql);
435
			return $num;
436
		}
437
		else
438
		{
439
			dol_print_error($this->db);
440
			return -1;
441
		}
442
	}
443
444
445
	/**
446
	 *    Build a HTML select list of element of same thirdparty to suggest to link them to project
447
	 *
448
	 *    @param	string		$table_element		Table of the element to update
449
	 *    @param	int			$socid				If of thirdparty to use as filter
450
	 *    @param	string		$morecss			More CSS
451
	 *    @param    int         $limitonstatus      Add filters to limit length of list to opened status (for example to avoid ERR_RESPONSE_HEADERS_TOO_BIG on project/element.php page). TODO To implement
452
	 *    @return	int|string						The HTML select list of element or '' if nothing or -1 if KO
453
	 */
454
	function select_element($table_element, $socid=0, $morecss='', $limitonstatus=-2)
455
	{
456
		global $conf, $langs;
457
458
		if ($table_element == 'projet_task') return '';		// Special cas of element we never link to a project (already always done)
459
460
		$linkedtothirdparty=false;
461
		if (! in_array($table_element, array('don','expensereport_det','expensereport'))) $linkedtothirdparty=true;
462
463
		$sqlfilter='';
464
		$projectkey="fk_projet";
465
		//print $table_element;
466
		switch ($table_element)
467
		{
468
			case "facture":
469
				$sql = "SELECT t.rowid, t.facnumber as ref";
470
				break;
471
			case "facture_fourn":
472
				$sql = "SELECT t.rowid, t.ref, t.ref_supplier";
473
				break;
474
			case "commande_fourn":
475
			case "commande_fournisseur":
476
			    $sql = "SELECT t.rowid, t.ref, t.ref_supplier";
477
				break;
478
			case "facture_rec":
479
				$sql = "SELECT t.rowid, t.titre as ref";
480
				break;
481
			case "actioncomm":
482
				$sql = "SELECT t.id as rowid, t.label as ref";
483
				$projectkey="fk_project";
484
				break;
485
			case "expensereport":
486
				return '';
487
			case "expensereport_det":
488
				/*$sql = "SELECT rowid, '' as ref";	// table is llx_expensereport_det
489
				$projectkey="fk_projet";
490
				break;*/
491
				return '';
492
			case "commande":
493
		    case "contrat":
494
			case "fichinter":
495
			    $sql = "SELECT t.rowid, t.ref";
496
			    break;
497
			default:
498
				$sql = "SELECT t.rowid, t.ref";
499
				break;
500
		}
501
		if ($linkedtothirdparty) $sql.=", s.nom as name";
502
		$sql.= " FROM ".MAIN_DB_PREFIX.$table_element." as t";
503
		if ($linkedtothirdparty) $sql.=", ".MAIN_DB_PREFIX."societe as s";
504
		$sql.= " WHERE ".$projectkey." is null";
505
		if (! empty($socid) && $linkedtothirdparty) $sql.= " AND t.fk_soc=".$socid;
506
		if (! in_array($table_element, array('expensereport_det'))) $sql.= ' AND t.entity IN ('.getEntity('project',1).')';
507
		if ($linkedtothirdparty) $sql.=" AND s.rowid = t.fk_soc";
508
		if ($sqlfilter) $sql.= " AND ".$sqlfilter;
509
		$sql.= " ORDER BY ref DESC";
510
511
		dol_syslog(get_class($this).'::select_element', LOG_DEBUG);
512
513
		$resql=$this->db->query($sql);
514
		if ($resql)
515
		{
516
			$num = $this->db->num_rows($resql);
517
			$i = 0;
518
			if ($num > 0)
519
			{
520
				$sellist = '<select class="flat elementselect css'.$table_element.($morecss?' '.$morecss:'').'" name="elementselect">';
521
				$sellist .='<option value="-1"></option>';
522
				while ($i < $num)
523
				{
524
					$obj = $this->db->fetch_object($resql);
525
					$ref=$obj->ref?$obj->ref:$obj->rowid;
526
					if (! empty($obj->ref_supplier)) $ref.=' ('.$obj->ref_supplier.')';
527
					if (! empty($obj->name)) $ref.=' - '.$obj->name;
528
					$sellist .='<option value="'.$obj->rowid.'">'.$ref.'</option>';
529
					$i++;
530
				}
531
				$sellist .='</select>';
532
			}
533
			/*else
534
			{
535
				$sellist = '<select class="flat" name="elementselect">';
536
				$sellist.= '<option value="0" disabled>'.$langs->trans("None").'</option>';
537
				$sellist.= '</select>';
538
			}*/
539
			$this->db->free($resql);
540
541
			return $sellist;
0 ignored issues
show
Bug introduced by
The variable $sellist does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
542
		}
543
		else
544
		{
545
			dol_print_error($this->db);
546
			$this->error=$this->db->lasterror();
547
			$this->errors[]=$this->db->lasterror();
548
			dol_syslog(get_class($this) . "::select_element " . $this->error, LOG_ERR);
549
			return -1;
550
		}
551
	}
552
553
554
	/**
555
	 *    Build a HTML select list of element of same thirdparty to suggest to link them to project
556
	 *
557
	 *    @param   string      $htmlname           HTML name
558
	 *    @param   string      $preselected        Preselected (int or 'all' or 'none')
559
	 *    @param   int         $showempty          Add an empty line
560
	 *    @param   int         $useshortlabel      Use short label
561
	 *    @param   int         $showallnone        Add choice "All" and "None"
562
	 *    @param   int         $showpercent        Show default probability for status
563
	 *    @return  int|string                      The HTML select list of element or '' if nothing or -1 if KO
564
	 */
565
	function selectOpportunityStatus($htmlname, $preselected='-1', $showempty=1, $useshortlabel=0, $showallnone=0, $showpercent=0)
566
	{
567
		global $conf, $langs;
568
569
		$sql = "SELECT rowid, code, label, percent";
570
		$sql.= " FROM ".MAIN_DB_PREFIX.'c_lead_status';
571
		$sql.= " WHERE active = 1";
572
		$sql.= " ORDER BY position";
573
574
		$resql=$this->db->query($sql);
575
		if ($resql)
576
		{
577
			$num = $this->db->num_rows($resql);
578
			$i = 0;
579
			if ($num > 0)
580
			{
581
				$sellist = '<select class="flat oppstatus" id="'.$htmlname.'" name="'.$htmlname.'">';
582
				if ($showempty) $sellist.= '<option value="-1"></option>';
583
				if ($showallnone) $sellist.= '<option value="all"'.($preselected == 'all'?' selected="selected"':'').'>--'.$langs->trans("OnlyOpportunitiesShort").'--</option>';
584
				if ($showallnone) $sellist.= '<option value="openedopp"'.($preselected == 'openedopp'?' selected="selected"':'').'>--'.$langs->trans("OpenedOpportunitiesShort").'--</option>';
585
				if ($showallnone) $sellist.= '<option value="none"'.($preselected == 'none'?' selected="selected"':'').'>--'.$langs->trans("NotAnOpportunityShort").'--</option>';
586
				while ($i < $num)
587
				{
588
					$obj = $this->db->fetch_object($resql);
589
590
					$sellist .='<option value="'.$obj->rowid.'" defaultpercent="'.$obj->percent.'" elemcode="'.$obj->code.'"';
591
					if ($obj->rowid == $preselected) $sellist .= ' selected="selected"';
592
					$sellist .= '>';
593
					if ($useshortlabel)
594
					{
595
						$finallabel = ($langs->transnoentitiesnoconv("OppStatusShort".$obj->code) != "OppStatusShort".$obj->code ? $langs->transnoentitiesnoconv("OppStatusShort".$obj->code) : $obj->label);
596
					}
597
					else
598
					{
599
						$finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label);
600
						if ($showpercent) $finallabel.= ' ('.$obj->percent.'%)';
601
					}
602
					$sellist .= $finallabel;
603
					$sellist .='</option>';
604
					$i++;
605
				}
606
				$sellist .='</select>';
607
			}
608
			/*else
609
			{
610
				$sellist = '<select class="flat" name="elementselect">';
611
				$sellist.= '<option value="0" disabled>'.$langs->trans("None").'</option>';
612
				$sellist.= '</select>';
613
			}*/
614
			$this->db->free($resql);
615
616
			return $sellist;
0 ignored issues
show
Bug introduced by
The variable $sellist does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
617
		}
618
		else
619
		{
620
			$this->error=$this->db->lasterror();
621
			$this->errors[]=$this->db->lasterror();
622
			dol_syslog(get_class($this) . "::selectOpportunityStatus " . $this->error, LOG_ERR);
623
			return -1;
624
		}
625
	}
626
627
}
628