Completed
Branch develop (09fbe4)
by
unknown
29:23
created

FormProjets::selectOpportunityStatus()   C

Complexity

Conditions 16
Paths 70

Size

Total Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
nc 70
nop 7
dl 0
loc 67
rs 5.5666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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:

1
<?php
2
/* Copyright (c) 2013 Florian Henry  <[email protected]>
3
 * Copyright (C) 2015 Marcos García  <[email protected]>
4
 * Copyright (C) 2018 Charlene Benke <[email protected]>
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
/**
21
 *      \file       htdocs/core/class/html.formprojet.class.php
22
 *      \ingroup    core
23
 *      \brief      Class file for html component project
24
 */
25
26
27
/**
28
 *      Class to manage building of HTML components
29
 */
30
class FormProjets
31
{
32
	/**
33
     * @var DoliDB Database handler.
34
     */
35
    public $db;
36
37
	/**
38
	 * @var string Error code (or message)
39
	 */
40
	public $error='';
41
42
43
	/**
44
	 *	Constructor
45
	 *
46
	 *  @param		DoliDB		$db      Database handler
47
	 */
48
	function __construct($db)
49
	{
50
		$this->db = $db;
51
	}
52
53
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
54
	/**
55
	 *	Output a combo list with projects qualified for a third party / user
56
	 *
57
	 *	@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)
58
	 *	@param  string	$selected   	Id project preselected ('' or id of project)
59
	 *	@param  string	$htmlname   	Name of HTML field
60
	 *	@param	int		$maxlength		Maximum length of label
61
	 *	@param	int		$option_only	Return only html options lines without the select tag
62
	 *	@param	int		$show_empty		Add an empty line
63
	 *  @param	int		$discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
64
	 *  @param	int		$forcefocus		Force focus on field (works with javascript only)
65
	 *  @param	int		$disabled		Disabled
66
	 *  @param  int     $mode           0 for HTML mode and 1 for JSON mode
67
	 *  @param  string  $filterkey      Key to filter
68
	 *  @param  int     $nooutput       No print output. Return it only.
69
	 *  @param  int     $forceaddid     Force to add project id in list, event if not qualified
70
	 *  @param  string  $morecss        More css
71
	 *	@param  int     $htmlid         Html id to use instead of htmlname
72
	 *	@return string           		Return html content
73
	 */
74
	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='', $htmlid='')
75
	{
76
        // phpcs:enable
77
		global $langs,$conf,$form;
78
79
		$out='';
80
81
		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT))
82
		{
83
			$placeholder='';
84
85
			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...
86
			{
87
				require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
88
				$project = new Project($this->db);
89
				$project->fetch($selected);
90
				$selected_input_value=$project->ref;
91
			}
92
			$urloption='socid='.$socid.'&htmlname='.$htmlname.'&discardclosed='.$discard_closed;
93
			$out.=ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PROJECT_USE_SEARCH_TO_SELECT, 0, array(
94
//				'update' => array(
95
//					'projectid' => 'id'
96
//				)
97
			));
98
99
			$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...
100
		}
101
		else
102
		{
103
			$out.=$this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey, 1, $forceaddid, $htmlid, $morecss);
104
		}
105
		if ($discard_closed)
106
		{
107
			if (class_exists('Form'))
108
			{
109
				if (empty($form)) $form=new Form($this->db);
110
				$out.=$form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden"));
111
			}
112
		}
113
114
		if (empty($nooutput))
115
		{
116
		    print $out;
117
		    return '';
118
		}
119
		else return $out;
120
	}
121
122
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
123
	/**
124
	 * Returns an array with projects qualified for a third party
125
	 *
126
	 * @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)
127
	 * @param  int     $selected   	       Id project preselected
128
	 * @param  string  $htmlname   	       Nom de la zone html
129
	 * @param  int     $maxlength          Maximum length of label
130
	 * @param  int     $option_only	       Return only html options lines without the select tag
131
	 * @param  int     $show_empty		   Add an empty line
132
	 * @param  int     $discard_closed     Discard closed projects (0=Keep,1=hide completely,2=Disable)
133
     * @param  int     $forcefocus		   Force focus on field (works with javascript only)
134
     * @param  int     $disabled           Disabled
135
	 * @param  int     $mode               0 for HTML mode and 1 for array return (to be used by json_encode for example)
136
	 * @param  string  $filterkey          Key to filter
137
	 * @param  int     $nooutput           No print output. Return it only.
138
	 * @param  int     $forceaddid         Force to add project id in list, event if not qualified
139
	 * @param  int     $htmlid             Html id to use instead of htmlname
140
	 * @param  string  $morecss            More CSS
141
	 * @return int         			       Nb of project if OK, <0 if KO
142
	 */
143
	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, $htmlid='', $morecss='maxwidth500')
144
	{
145
        // phpcs:enable
146
		global $user,$conf,$langs;
147
148
		require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
149
150
		if (empty($htmlid)) $htmlid = $htmlname;
151
152
		$out='';
153
		$outarray=array();
154
155
		$hideunselectables = false;
156
		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
157
158
		$projectsListId = false;
159
		if (empty($user->rights->projet->all->lire))
160
		{
161
			$projectstatic=new Project($this->db);
162
			$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1);
163
		}
164
165
		// Search all projects
166
		$sql = 'SELECT p.rowid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public, s.nom as name, s.name_alias';
167
		$sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p LEFT JOIN '.MAIN_DB_PREFIX .'societe as s ON s.rowid = p.fk_soc';
168
		$sql.= " WHERE p.entity IN (".getEntity('project').")";
169
		if ($projectsListId !== false) $sql.= " AND p.rowid IN (".$projectsListId.")";
170
		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
171
		if ($socid > 0)
172
		{
173
		    if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
174
		    else if ($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')    // PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
175
		    {
176
		        $sql.= " AND (p.fk_soc IN (".$socid.", ".$conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") OR p.fk_soc IS NULL)";
177
		    }
178
		}
179
		if (!empty($filterkey)) $sql .= natural_search(array('p.title', 'p.ref'), $filterkey);
180
		$sql.= " ORDER BY p.ref ASC";
181
182
		$resql=$this->db->query($sql);
183
		if ($resql)
184
		{
185
			// Use select2 selector
186
			if (! empty($conf->use_javascript_ajax))
187
			{
188
				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
189
	           	$comboenhancement = ajax_combobox($htmlid, array(), 0, $forcefocus);
190
            	$out.=$comboenhancement;
191
            	$morecss.=' minwidth100';
192
			}
193
194
			if (empty($option_only)) {
195
				$out.= '<select class="flat'.($morecss?' '.$morecss:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlid.'" name="'.$htmlname.'">';
196
			}
197
			if (!empty($show_empty)) {
198
				$out.= '<option value="0">&nbsp;</option>';
199
			}
200
			$num = $this->db->num_rows($resql);
201
			$i = 0;
202
			if ($num)
203
			{
204
				while ($i < $num)
205
				{
206
					$obj = $this->db->fetch_object($resql);
207
					// 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.
208
					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
209
					{
210
						// Do nothing
211
					}
212
					else
213
					{
214
						if ($discard_closed == 1 && $obj->fk_statut == 2 && $obj->rowid != $selected) // We discard closed except if selected
215
						{
216
							$i++;
217
							continue;
218
						}
219
220
						$labeltoshow=dol_trunc($obj->ref,18);
221
						//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
222
						//else $labeltoshow.=' ('.$langs->trans("Private").')';
223
						$labeltoshow.=', '.dol_trunc($obj->title, $maxlength);
224
						if ($obj->name)
225
						{
226
						    $labeltoshow.=' - '.$obj->name;
227
						    if ($obj->name_alias) $labeltoshow.=' ('.$obj->name_alias.')';
228
						}
229
230
						$disabled=0;
231
						if ($obj->fk_statut == 0)
232
						{
233
							$disabled=1;
234
							$labeltoshow.=' - '.$langs->trans("Draft");
235
						}
236
						else if ($obj->fk_statut == 2)
237
						{
238
							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...
239
							$labeltoshow.=' - '.$langs->trans("Closed");
240
						}
241
						else if ( empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
242
						{
243
							$disabled=1;
244
							$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
245
						}
246
247
						if (!empty($selected) && $selected == $obj->rowid)
248
						{
249
							$out.= '<option value="'.$obj->rowid.'" selected';
250
							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
251
							$out.= '>'.$labeltoshow.'</option>';
252
						}
253
						else
254
						{
255
							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
256
							{
257
								$resultat='';
258
							}
259
							else
260
							{
261
								$resultat='<option value="'.$obj->rowid.'"';
262
								if ($disabled) $resultat.=' disabled';
263
								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
264
								//else $labeltoshow.=' ('.$langs->trans("Private").')';
265
								$resultat.='>';
266
								$resultat.=$labeltoshow;
267
								$resultat.='</option>';
268
							}
269
							$out.= $resultat;
270
271
							$outarray[] = array(
272
								'key' => (int) $obj->rowid,
273
								'value' => $obj->ref,
274
								'ref' => $obj->ref,
275
								'label' => $labeltoshow,
276
								'disabled' => (bool) $disabled
277
							);
278
						}
279
					}
280
					$i++;
281
				}
282
			}
283
284
			$this->db->free($resql);
285
286
			if (!$mode) {
287
				if (empty($option_only)) $out.= '</select>';
288
				if (empty($nooutput))
289
				{
290
				    print $out;
291
				    return '';
292
				}
293
				else return $out;
294
			} else {
295
				return $outarray;
296
			}
297
		}
298
		else
299
		{
300
			dol_print_error($this->db);
301
			return -1;
302
		}
303
	}
304
305
	/**
306
	 *	Output a combo list with tasks qualified for a third party
307
	 *
308
	 *	@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)
309
	 *	@param  int		$selected   	Id task preselected
310
	 *	@param  string	$htmlname   	Name of HTML select
311
	 *	@param	int		$maxlength		Maximum length of label
312
	 *	@param	int		$option_only	Return only html options lines without the select tag
313
	 *	@param	string	$show_empty		Add an empty line ('1' or string to show for empty line)
314
	 *  @param	int		$discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
315
     *  @param	int		$forcefocus		Force focus on field (works with javascript only)
316
     *  @param	int		$disabled		Disabled
317
	 *  @param	string	$morecss        More css added to the select component
318
	 *  @param	string	$projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
319
	 *  @param	string	$showproject	'all' = Show project info, ''=Hide project info
320
	 *	@return int         			Nbr of project if OK, <0 if KO
321
	 */
322
	function selectTasks($socid=-1, $selected='', $htmlname='taskid', $maxlength=24, $option_only=0, $show_empty='1', $discard_closed=0, $forcefocus=0, $disabled=0, $morecss='maxwidth500', $projectsListId='', $showproject='all')
323
	{
324
		global $user,$conf,$langs;
325
326
		require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
327
328
		$out='';
329
330
		$hideunselectables = false;
331
		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
332
333
		if (empty($projectsListId))
334
		{
335
			if (empty($user->rights->projet->all->lire))
336
			{
337
				$projectstatic=new Project($this->db);
338
				$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1);
339
			}
340
		}
341
342
		// Search all projects
343
		$sql = 'SELECT t.rowid, t.ref as tref, t.label as tlabel, p.ref, p.title, p.fk_soc, p.fk_statut, p.public,';
344
		$sql.= ' s.nom as name';
345
		$sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p';
346
		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc';
347
		$sql.= ', '.MAIN_DB_PREFIX.'projet_task as t';
348
		$sql.= " WHERE p.entity IN (".getEntity('project').")";
349
		$sql.= " AND t.fk_projet = p.rowid";
350
		if ($projectsListId) $sql.= " AND p.rowid IN (".$projectsListId.")";
351
		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
352
		if ($socid > 0)  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
353
		$sql.= " ORDER BY p.ref, t.ref ASC";
354
355
		$resql=$this->db->query($sql);
356
		if ($resql)
357
		{
358
			// Use select2 selector
359
			if (! empty($conf->use_javascript_ajax))
360
			{
361
				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
362
	           	$comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
363
            	$out.=$comboenhancement;
364
            	$morecss='minwidth200 maxwidth500';
365
			}
366
367
			if (empty($option_only)) {
368
				$out.= '<select class="valignmiddle flat'.($morecss?' '.$morecss:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlname.'" name="'.$htmlname.'">';
369
			}
370
			if (! empty($show_empty)) {
371
				$out.= '<option value="0" class="optiongrey">';
372
				if (! is_numeric($show_empty)) $out.=$show_empty;
373
				else $out.='&nbsp;';
374
				$out.= '</option>';
375
			}
376
			$num = $this->db->num_rows($resql);
377
			$i = 0;
378
			if ($num)
379
			{
380
				while ($i < $num)
381
				{
382
					$obj = $this->db->fetch_object($resql);
383
					// 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.
384
					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($user->rights->societe->lire))
385
					{
386
						// Do nothing
387
					}
388
					else
389
					{
390
						if ($discard_closed == 1 && $obj->fk_statut == 2)
391
						{
392
							$i++;
393
							continue;
394
						}
395
396
						$labeltoshow = '';
397
398
						if ($showproject == 'all')
399
						{
400
							$labeltoshow.=dol_trunc($obj->ref,18);     // Project ref
401
							//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
402
							//else $labeltoshow.=' ('.$langs->trans("Private").')';
403
							$labeltoshow.=' '.dol_trunc($obj->title,$maxlength);
404
405
							if ($obj->name) $labeltoshow.=' ('.$obj->name.')';
406
407
							$disabled=0;
408
							if ($obj->fk_statut == 0)
409
							{
410
								$disabled=1;
411
								$labeltoshow.=' - '.$langs->trans("Draft");
412
							}
413
							else if ($obj->fk_statut == 2)
414
							{
415
								if ($discard_closed == 2) $disabled=1;
416
								$labeltoshow.=' - '.$langs->trans("Closed");
417
							}
418
							else if ($socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
419
							{
420
								$disabled=1;
421
								$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
422
							}
423
							$labeltoshow.=' - ';
424
						}
425
426
						// Label for task
427
						$labeltoshow.=$obj->tref.' '.dol_trunc($obj->tlabel,$maxlength);
428
429
						if (!empty($selected) && $selected == $obj->rowid)
430
						{
431
							$out.= '<option value="'.$obj->rowid.'" selected';
432
							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
433
							$out.= '>'.$labeltoshow.'</option>';
434
						}
435
						else
436
						{
437
							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
438
							{
439
								$resultat='';
440
							}
441
							else
442
							{
443
								$resultat='<option value="'.$obj->rowid.'"';
444
								if ($disabled) $resultat.=' disabled';
445
								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
446
								//else $labeltoshow.=' ('.$langs->trans("Private").')';
447
								$resultat.='>';
448
								$resultat.=$labeltoshow;
449
								$resultat.='</option>';
450
							}
451
							$out.= $resultat;
452
						}
453
					}
454
					$i++;
455
				}
456
			}
457
			if (empty($option_only)) {
458
				$out.= '</select>';
459
			}
460
461
			print $out;
462
463
			$this->db->free($resql);
464
			return $num;
465
		}
466
		else
467
		{
468
			dol_print_error($this->db);
469
			return -1;
470
		}
471
	}
472
473
474
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
475
	/**
476
	 *    Build a HTML select list of element of same thirdparty to suggest to link them to project
477
	 *
478
	 *    @param	string		$table_element		Table of the element to update
479
	 *    @param	string		$socid				If of thirdparty to use as filter or 'id1,id2,...'
480
	 *    @param	string		$morecss			More CSS
481
	 *    @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
482
	 *    @param	string		$projectkey			Equivalent key  to fk_projet for actual table_element
483
	 *    @return	int|string						The HTML select list of element or '' if nothing or -1 if KO
484
	 */
485
	function select_element($table_element, $socid=0, $morecss='', $limitonstatus=-2,$projectkey="fk_projet")
486
	{
487
        // phpcs:enable
488
		global $conf, $langs;
489
490
		if ($table_element == 'projet_task') return '';		// Special cas of element we never link to a project (already always done)
491
492
		$linkedtothirdparty=false;
493
		if (! in_array($table_element, array('don','expensereport_det','expensereport','loan','stock_mouvement','chargesociales'))) $linkedtothirdparty=true;
494
495
		$sqlfilter='';
496
497
		//print $table_element;
498
		switch ($table_element)
499
		{
500
			case "loan":
501
				$sql = "SELECT t.rowid, t.label as ref";
502
				break;
503
			case "facture":
504
				$sql = "SELECT t.rowid, t.facnumber as ref";
505
				break;
506
			case "facture_fourn":
507
				$sql = "SELECT t.rowid, t.ref, t.ref_supplier";
508
				break;
509
			case "commande_fourn":
510
			case "commande_fournisseur":
511
			    $sql = "SELECT t.rowid, t.ref, t.ref_supplier";
512
				break;
513
			case "facture_rec":
514
				$sql = "SELECT t.rowid, t.titre as ref";
515
				break;
516
			case "actioncomm":
517
				$sql = "SELECT t.id as rowid, t.label as ref";
518
				$projectkey="fk_project";
519
				break;
520
			case "expensereport":
521
				return '';
522
			case "expensereport_det":
523
				/*$sql = "SELECT rowid, '' as ref";	// table is llx_expensereport_det
524
				$projectkey="fk_projet";
525
				break;*/
526
				return '';
527
			case "commande":
528
		    case "contrat":
529
			case "fichinter":
530
			    $sql = "SELECT t.rowid, t.ref";
531
			    break;
532
			case 'stock_mouvement':
533
				$sql = 'SELECT t.rowid, t.label as ref';
534
				$projectkey='fk_origin';
535
				break;
536
			case "payment_various":
537
				$sql = "SELECT t.rowid, t.num_payment as ref";
538
				break;
539
			case "chargesociales":
540
			default:
541
				$sql = "SELECT t.rowid, t.ref";
542
				break;
543
		}
544
		if ($linkedtothirdparty) $sql.=", s.nom as name";
545
		$sql.= " FROM ".MAIN_DB_PREFIX.$table_element." as t";
546
		if ($linkedtothirdparty) $sql.=", ".MAIN_DB_PREFIX."societe as s";
547
		$sql.= " WHERE ".$projectkey." is null";
548
		if (! empty($socid) && $linkedtothirdparty)
549
		{
550
		    if (is_numeric($socid)) $sql.= " AND t.fk_soc=".$socid;
551
		    else $sql.= " AND t.fk_soc IN (".$socid.")";
552
		}
553
		if (! in_array($table_element, array('expensereport_det','stock_mouvement'))) $sql.= ' AND t.entity IN ('.getEntity('project').')';
554
		if ($linkedtothirdparty) $sql.=" AND s.rowid = t.fk_soc";
555
		if ($sqlfilter) $sql.= " AND ".$sqlfilter;
556
		$sql.= " ORDER BY ref DESC";
557
558
		dol_syslog(get_class($this).'::select_element', LOG_DEBUG);
559
		$resql=$this->db->query($sql);
560
		if ($resql)
561
		{
562
			$num = $this->db->num_rows($resql);
563
			$i = 0;
564
			if ($num > 0)
565
			{
566
				$sellist = '<select class="flat elementselect css'.$table_element.($morecss?' '.$morecss:'').'" name="elementselect">';
567
				$sellist .='<option value="-1"></option>';
568
				while ($i < $num)
569
				{
570
					$obj = $this->db->fetch_object($resql);
571
					$ref=$obj->ref?$obj->ref:$obj->rowid;
572
					if (! empty($obj->ref_supplier)) $ref.=' ('.$obj->ref_supplier.')';
573
					if (! empty($obj->name)) $ref.=' - '.$obj->name;
574
					$sellist .='<option value="'.$obj->rowid.'">'.$ref.'</option>';
575
					$i++;
576
				}
577
				$sellist .='</select>';
578
			}
579
			/*else
580
			{
581
				$sellist = '<select class="flat" name="elementselect">';
582
				$sellist.= '<option value="0" disabled>'.$langs->trans("None").'</option>';
583
				$sellist.= '</select>';
584
			}*/
585
			$this->db->free($resql);
586
587
			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...
588
		}
589
		else
590
		{
591
			dol_print_error($this->db);
592
			$this->error=$this->db->lasterror();
593
			$this->errors[]=$this->db->lasterror();
594
			dol_syslog(get_class($this) . "::select_element " . $this->error, LOG_ERR);
595
			return -1;
596
		}
597
	}
598
599
600
	/**
601
	 *    Build a HTML select list of element of same thirdparty to suggest to link them to project
602
	 *
603
	 *    @param   string      $htmlname           HTML name
604
	 *    @param   string      $preselected        Preselected (int or 'all' or 'none')
605
	 *    @param   int         $showempty          Add an empty line
606
	 *    @param   int         $useshortlabel      Use short label
607
	 *    @param   int         $showallnone        Add choice "All" and "None"
608
	 *    @param   int         $showpercent        Show default probability for status
609
	 *    @param   string      $morecss            Add more css
610
	 *    @return  int|string                      The HTML select list of element or '' if nothing or -1 if KO
611
	 */
612
	function selectOpportunityStatus($htmlname, $preselected='-1', $showempty=1, $useshortlabel=0, $showallnone=0, $showpercent=0, $morecss='')
613
	{
614
		global $conf, $langs;
615
616
		$sql = "SELECT rowid, code, label, percent";
617
		$sql.= " FROM ".MAIN_DB_PREFIX.'c_lead_status';
618
		$sql.= " WHERE active = 1";
619
		$sql.= " ORDER BY position";
620
621
		$resql=$this->db->query($sql);
622
		if ($resql)
623
		{
624
			$num = $this->db->num_rows($resql);
625
			$i = 0;
626
			if ($num > 0)
627
			{
628
				$sellist = '<select class="flat oppstatus'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
629
				if ($showempty) {
630
                    // Without &nbsp, strange move of screen when switching value
631
                    $sellist.= '<option value="-1">&nbsp;</option>';
632
                }
633
				if ($showallnone) {
634
                    $sellist.= '<option value="all"'.($preselected == 'all'?' selected="selected"':'').'>-- '.$langs->trans("OnlyOpportunitiesShort").' --</option>';
635
				    $sellist.= '<option value="openedopp"'.($preselected == 'openedopp'?' selected="selected"':'').'>-- '.$langs->trans("OpenedOpportunitiesShort").' --</option>';
636
				    $sellist.= '<option value="notopenedopp"'.($preselected == 'notopenedopp'?' selected="selected"':'').'>-- '.$langs->trans("NotOpenedOpportunitiesShort").' --</option>';
637
				    $sellist.= '<option value="none"'.($preselected == 'none'?' selected="selected"':'').'>-- '.$langs->trans("NotAnOpportunityShort").' --</option>';
638
                }
639
				while ($i < $num)
640
				{
641
					$obj = $this->db->fetch_object($resql);
642
643
					$sellist .='<option value="'.$obj->rowid.'" defaultpercent="'.$obj->percent.'" elemcode="'.$obj->code.'"';
644
					if ($obj->rowid == $preselected) $sellist .= ' selected="selected"';
645
					$sellist .= '>';
646
					if ($useshortlabel)
647
					{
648
						$finallabel = ($langs->transnoentitiesnoconv("OppStatusShort".$obj->code) != "OppStatusShort".$obj->code ? $langs->transnoentitiesnoconv("OppStatusShort".$obj->code) : $obj->label);
649
					}
650
					else
651
					{
652
						$finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label);
653
						if ($showpercent) $finallabel.= ' ('.$obj->percent.'%)';
654
					}
655
					$sellist .= $finallabel;
656
					$sellist .='</option>';
657
					$i++;
658
				}
659
				$sellist .='</select>';
660
			}
661
			/*else
662
			{
663
				$sellist = '<select class="flat" name="elementselect">';
664
				$sellist.= '<option value="0" disabled>'.$langs->trans("None").'</option>';
665
				$sellist.= '</select>';
666
			}*/
667
			$this->db->free($resql);
668
669
			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...
670
		}
671
		else
672
		{
673
			$this->error=$this->db->lasterror();
674
			$this->errors[]=$this->db->lasterror();
675
			dol_syslog(get_class($this) . "::selectOpportunityStatus " . $this->error, LOG_ERR);
676
			return -1;
677
		}
678
	}
679
}
680