Completed
Branch develop (5cf21f)
by
unknown
27:49
created

project.lib.php ➔ projectLinesPerAction()   F

Complexity

Conditions 37
Paths > 20000

Size

Total Lines 207
Code Lines 101

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 37
eloc 101
nc 663570
nop 12
dl 0
loc 207
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

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

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

Commonly applied refactorings include:

Many Parameters

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

There are several approaches to avoid long parameter lists:

1
<?php
2
/* Copyright (C) 2006-2015 Laurent Destailleur  <[email protected]>
3
 * Copyright (C) 2010      Regis Houssin        <[email protected]>
4
 * Copyright (C) 2011      Juanjo Menent        <[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
 * or see http://www.gnu.org/
19
 */
20
21
/**
22
 *	    \file       htdocs/core/lib/project.lib.php
23
 *		\brief      Functions used by project module
24
 *      \ingroup    project
25
 */
26
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
27
28
29
/**
30
 * Prepare array with list of tabs
31
 *
32
 * @param   Object	$object		Object related to tabs
33
 * @return  array				Array of tabs to show
34
 */
35
function project_prepare_head($object)
36
{
37
	global $db, $langs, $conf, $user;
38
39
	$h = 0;
40
	$head = array();
41
42
	$head[$h][0] = DOL_URL_ROOT.'/projet/card.php?id='.$object->id;
43
	$head[$h][1] = $langs->trans("Project");
44
	$head[$h][2] = 'project';
45
	$h++;
46
47
	$nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
48
	$head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$object->id;
49
	$head[$h][1] = $langs->trans("ProjectContact");
50
	if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
51
	$head[$h][2] = 'contact';
52
	$h++;
53
54
	if (! empty($conf->fournisseur->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->commande->enabled)
55
	|| ! empty($conf->facture->enabled) || ! empty($conf->contrat->enabled)
56
	|| ! empty($conf->ficheinter->enabled) || ! empty($conf->agenda->enabled) || ! empty($conf->deplacement->enabled))
57
	{
58
		$head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$object->id;
59
		$head[$h][1] = $langs->trans("ProjectOverview");
60
		$head[$h][2] = 'element';
61
		$h++;
62
	}
63
64
	// Show more tabs from modules
65
	// Entries must be declared in modules descriptor with line
66
	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
67
	// $this->tabs = array('entity:-tabname);   												to remove a tab
68
	complete_head_from_modules($conf,$langs,$object,$head,$h,'project');
69
70
71
	if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
72
	{
73
		$nbNote = 0;
74
		if(!empty($object->note_private)) $nbNote++;
75
		if(!empty($object->note_public)) $nbNote++;
76
		$head[$h][0] = DOL_URL_ROOT.'/projet/note.php?id='.$object->id;
77
		$head[$h][1] = $langs->trans('Notes');
78
		if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
79
		$head[$h][2] = 'notes';
80
		$h++;
81
	}
82
83
	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
84
	require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
85
	$upload_dir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($object->ref);
86
	$nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview.*\.png)$'));
87
	$nbLinks=Link::count($db, $object->element, $object->id);
88
	$head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$object->id;
89
	$head[$h][1] = $langs->trans('Documents');
90
	if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
91
	$head[$h][2] = 'document';
92
	$h++;
93
94
	if (empty($conf->global->PROJECT_HIDE_TASKS))
95
	{
96
		// Then tab for sub level of projet, i mean tasks
97
		$head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$object->id;
98
		$head[$h][1] = $langs->trans("Tasks");
99
100
		require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
101
		$taskstatic=new Task($db);
102
		$nbTasks=count($taskstatic->getTasksArray(0, 0, $object->id, 0, 0));
103
		if ($nbTasks > 0) $head[$h][1].= ' <span class="badge">'.($nbTasks).'</span>';
104
		$head[$h][2] = 'tasks';
105
		$h++;
106
107
		$head[$h][0] = DOL_URL_ROOT.'/projet/ganttview.php?id='.$object->id;
108
		$head[$h][1] = $langs->trans("Gantt");
109
		if ($nbTasks > 0) $head[$h][1].= ' <span class="badge">'.($nbTasks).'</span>';
110
		$head[$h][2] = 'gantt';
111
		$h++;
112
	}
113
114
	// Manage discussion
115
	if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT))
116
	{
117
		$nbComments = $object->getNbComments();
118
		$head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$object->id;
119
		$head[$h][1] = $langs->trans("CommentLink");
120
		if ($nbComments > 0) $head[$h][1].= ' <span class="badge">'.$nbComments.'</span>';
121
		$head[$h][2] = 'project_comment';
122
		$h++;
123
	}
124
125
	$head[$h][0] = DOL_URL_ROOT.'/projet/info.php?id='.$object->id;
126
	$head[$h][1].= $langs->trans("Events");
127
	if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) ))
128
	{
129
		$head[$h][1].= '/';
130
		$head[$h][1].= $langs->trans("Agenda");
131
	}
132
	$head[$h][2] = 'agenda';
133
	$h++;
134
135
	complete_head_from_modules($conf,$langs,$object,$head,$h,'project','remove');
136
137
	return $head;
138
}
139
140
141
/**
142
 * Prepare array with list of tabs
143
 *
144
 * @param   Object	$object		Object related to tabs
145
 * @return  array				Array of tabs to show
146
 */
147
function task_prepare_head($object)
148
{
149
	global $db, $langs, $conf, $user;
150
	$h = 0;
151
	$head = array();
152
153
	$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/task.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
154
	$head[$h][1] = $langs->trans("Card");
155
	$head[$h][2] = 'task_task';
156
	$h++;
157
158
	$nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
159
	$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/contact.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
160
	$head[$h][1] = $langs->trans("TaskRessourceLinks");
161
	if ($nbContact > 0) $head[$h][1].= ' <span class="badge">'.$nbContact.'</span>';
162
	$head[$h][2] = 'task_contact';
163
	$h++;
164
165
	// Is there timespent ?
166
	$nbTimeSpent=0;
167
	$sql = "SELECT t.rowid";
168
	$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."user as u";
169
	$sql .= " WHERE t.fk_user = u.rowid AND t.fk_task = pt.rowid";
170
	$sql .= " AND t.fk_task =".$object->id;
171
	$resql = $db->query($sql);
172
	if ($resql)
173
	{
174
		$obj = $db->fetch_object($resql);
175
		if ($obj) $nbTimeSpent=1;
176
	}
177
	else dol_print_error($db);
178
179
	$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
180
	$head[$h][1] = $langs->trans("TimeSpent");
181
	if ($nbTimeSpent > 0) $head[$h][1].= ' <span class="badge">...</span>';
182
	$head[$h][2] = 'task_time';
183
	$h++;
184
185
	// Show more tabs from modules
186
	// Entries must be declared in modules descriptor with line
187
	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
188
	// $this->tabs = array('entity:-tabname);   												to remove a tab
189
	complete_head_from_modules($conf,$langs,$object,$head,$h,'task');
190
191
	if (empty($conf->global->MAIN_DISABLE_NOTES_TAB))
192
	{
193
		$nbNote = 0;
194
		if(!empty($object->note_private)) $nbNote++;
195
		if(!empty($object->note_public)) $nbNote++;
196
		$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/note.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
197
		$head[$h][1] = $langs->trans('Notes');
198
		if ($nbNote > 0) $head[$h][1].= ' <span class="badge">'.$nbNote.'</span>';
199
		$head[$h][2] = 'task_notes';
200
		$h++;
201
	}
202
203
	$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/document.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
204
	$filesdir = $conf->projet->dir_output . "/" . dol_sanitizeFileName($object->project->ref) . '/' .dol_sanitizeFileName($object->ref);
205
	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
206
	include_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
207
	$nbFiles = count(dol_dir_list($filesdir,'files',0,'','(\.meta|_preview.*\.png)$'));
208
	$nbLinks=Link::count($db, $object->element, $object->id);
209
	$head[$h][1] = $langs->trans('Documents');
210
	if (($nbFiles+$nbLinks) > 0) $head[$h][1].= ' <span class="badge">'.($nbFiles+$nbLinks).'</span>';
211
	$head[$h][2] = 'task_document';
212
	$h++;
213
214
	// Manage discussion
215
	if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK))
216
	{
217
		$nbComments = $object->getNbComments();
218
		$head[$h][0] = DOL_URL_ROOT.'/projet/tasks/comment.php?id='.$object->id.(GETPOST('withproject')?'&withproject=1':'');
219
		$head[$h][1] = $langs->trans("CommentLink");
220
		if ($nbComments > 0) $head[$h][1].= ' <span class="badge">'.$nbComments.'</span>';
221
		$head[$h][2] = 'task_comment';
222
		$h++;
223
	}
224
225
	complete_head_from_modules($conf,$langs,$object,$head,$h,'task','remove');
226
227
	return $head;
228
}
229
230
/**
231
 * Prepare array with list of tabs
232
 *
233
 * @param	string	$mode		Mode
234
 * @param   string  $fuser      Filter on user
235
 * @return  array				Array of tabs to show
236
 */
237
function project_timesheet_prepare_head($mode, $fuser=null)
238
{
239
	global $langs, $conf, $user;
240
	$h = 0;
241
	$head = array();
242
243
	$h = 0;
244
245
	$param='';
246
	$param.=($mode?'&mode='.$mode:'');
247
	if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) $param.='&search_usertoprocessid='.$fuser->id;
248
249
	if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK))
250
	{
251
		$head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($param?'?'.$param:'');
252
		$head[$h][1] = $langs->trans("InputPerWeek");
253
		$head[$h][2] = 'inputperweek';
254
		$h++;
255
	}
256
257
	if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME))
258
	{
259
		$head[$h][0] = DOL_URL_ROOT."/projet/activity/perday.php".($param?'?'.$param:'');
260
		$head[$h][1] = $langs->trans("InputPerDay");
261
		$head[$h][2] = 'inputperday';
262
		$h++;
263
	}
264
265
	/*if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
266
	{
267
		$head[$h][0] = DOL_URL_ROOT."/projet/activity/perline.php".($param?'?'.$param:'');
268
		$head[$h][1] = $langs->trans("InputDetail");
269
		$head[$h][2] = 'inputperline';
270
		$h++;
271
	}*/
272
273
	complete_head_from_modules($conf,$langs,null,$head,$h,'project_timesheet');
274
275
	complete_head_from_modules($conf,$langs,null,$head,$h,'project_timesheet','remove');
276
277
	return $head;
278
}
279
280
281
/**
282
 * Prepare array with list of tabs
283
 *
284
 * @return  array				Array of tabs to show
285
 */
286
function project_admin_prepare_head()
287
{
288
	global $langs, $conf, $user;
289
	$h = 0;
290
	$head = array();
291
292
	$h = 0;
293
294
	$head[$h][0] = DOL_URL_ROOT."/projet/admin/project.php";
295
	$head[$h][1] = $langs->trans("Projects");
296
	$head[$h][2] = 'project';
297
	$h++;
298
299
	complete_head_from_modules($conf,$langs,null,$head,$h,'project_admin');
300
301
	$head[$h][0] = DOL_URL_ROOT."/projet/admin/project_extrafields.php";
302
	$head[$h][1] = $langs->trans("ExtraFieldsProject");
303
	$head[$h][2] = 'attributes';
304
	$h++;
305
306
	$head[$h][0] = DOL_URL_ROOT.'/projet/admin/project_task_extrafields.php';
307
	$head[$h][1] = $langs->trans("ExtraFieldsProjectTask");
308
	$head[$h][2] = 'attributes_task';
309
	$h++;
310
311
	complete_head_from_modules($conf,$langs,null,$head,$h,'project_admin','remove');
312
313
	return $head;
314
}
315
316
317
/**
318
 * Show task lines with a particular parent
319
 *
320
 * @param	string	   	$inc				Line number (start to 0, then increased by recursive call)
321
 * @param   string		$parent				Id of parent project to show (0 to show all)
322
 * @param   Task[]		$lines				Array of lines
323
 * @param   int			$level				Level (start to 0, then increased/decrease by recursive call), or -1 to show all level in order of $lines without the recursive groupment feature.
324
 * @param 	string		$var				Color
325
 * @param 	int			$showproject		Show project columns
326
 * @param	int			$taskrole			Array of roles of user for each tasks
327
 * @param	int			$projectsListId		List of id of project allowed to user (string separated with comma)
328
 * @param	int			$addordertick		Add a tick to move task
329
 * @param   int         $projectidfortotallink     0 or Id of project to use on total line (link to see all time consumed for project)
330
 * @return	void
331
 */
332
function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$taskrole, $projectsListId='', $addordertick=0, $projectidfortotallink=0)
333
{
334
	global $user, $bc, $langs;
335
	global $projectstatic, $taskstatic;
336
337
	$lastprojectid=0;
338
339
	$projectsArrayId=explode(',',$projectsListId);
340
341
	$numlines=count($lines);
342
343
	// We declare counter as global because we want to edit them into recursive call
344
	global $total_projectlinesa_spent,$total_projectlinesa_planned,$total_projectlinesa_spent_if_planned;
345
	if ($level == 0)
346
	{
347
		$total_projectlinesa_spent=0;
348
		$total_projectlinesa_planned=0;
349
		$total_projectlinesa_spent_if_planned=0;
350
	}
351
352
	for ($i = 0 ; $i < $numlines ; $i++)
353
	{
354
		if ($parent == 0 && $level >= 0) $level = 0;              // if $level = -1, we dont' use sublevel recursion, we show all lines
355
356
		// Process line
357
		// print "i:".$i."-".$lines[$i]->fk_project.'<br>';
358
359
		if ($lines[$i]->fk_parent == $parent || $level < 0)       // if $level = -1, we dont' use sublevel recursion, we show all lines
360
		{
361
			// Show task line.
362
			$showline=1;
363
			$showlineingray=0;
364
365
			// If there is filters to use
366
			if (is_array($taskrole))
367
			{
368
				// If task not legitimate to show, search if a legitimate task exists later in tree
369
				if (! isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent)
370
				{
371
					// So search if task has a subtask legitimate to show
372
					$foundtaskforuserdeeper=0;
373
					searchTaskInChild($foundtaskforuserdeeper,$lines[$i]->id,$lines,$taskrole);
374
					//print '$foundtaskforuserpeeper='.$foundtaskforuserdeeper.'<br>';
375
					if ($foundtaskforuserdeeper > 0)
376
					{
377
						$showlineingray=1;		// We will show line but in gray
378
					}
379
					else
380
					{
381
						$showline=0;			// No reason to show line
382
					}
383
				}
384
			}
385
			else
386
			{
387
				// Caller did not ask to filter on tasks of a specific user (this probably means he want also tasks of all users, into public project
388
				// or into all other projects if user has permission to).
389
				if (empty($user->rights->projet->all->lire))
390
				{
391
					// User is not allowed on this project and project is not public, so we hide line
392
					if (! in_array($lines[$i]->fk_project, $projectsArrayId))
393
					{
394
						// Note that having a user assigned to a task into a project user has no permission on, should not be possible
395
						// because assignement on task can be done only on contact of project.
396
						// If assignement was done and after, was removed from contact of project, then we can hide the line.
397
						$showline=0;
398
					}
399
				}
400
			}
401
402
			if ($showline)
403
			{
404
				// Break on a new project
405
				if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
406
				{
407
					$var = !$var;
408
					$lastprojectid=$lines[$i]->fk_project;
409
				}
410
411
				print '<tr '.$bc[$var].' id="row-'.$lines[$i]->id.'">'."\n";
412
413
				if ($showproject)
414
				{
415
					// Project ref
416
					print "<td>";
417
					//if ($showlineingray) print '<i>';
418
					$projectstatic->id=$lines[$i]->fk_project;
419
					$projectstatic->ref=$lines[$i]->projectref;
420
					$projectstatic->public=$lines[$i]->public;
421
					$projectstatic->title=$lines[$i]->projectlabel;
422
					if ($lines[$i]->public || in_array($lines[$i]->fk_project,$projectsArrayId) || ! empty($user->rights->projet->all->lire)) print $projectstatic->getNomUrl(1);
423
					else print $projectstatic->getNomUrl(1,'nolink');
424
					//if ($showlineingray) print '</i>';
425
					print "</td>";
426
427
					// Project status
428
					print '<td>';
429
					$projectstatic->statut=$lines[$i]->projectstatus;
430
					print $projectstatic->getLibStatut(2);
431
					print "</td>";
432
				}
433
434
				// Ref of task
435
				print '<td>';
436
				if ($showlineingray)
437
				{
438
					print '<i>'.img_object('','projecttask').' '.$lines[$i]->ref.'</i>';
439
				}
440
				else
441
				{
442
					$taskstatic->id=$lines[$i]->id;
443
					$taskstatic->ref=$lines[$i]->ref;
444
					$taskstatic->label=($taskrole[$lines[$i]->id]?$langs->trans("YourRole").': '.$taskrole[$lines[$i]->id]:'');
445
					print $taskstatic->getNomUrl(1,'withproject');
446
				}
447
				print '</td>';
448
449
				// Title of task
450
				print "<td>";
451
				if ($showlineingray) print '<i>';
452
				//else print '<a href="'.DOL_URL_ROOT.'/projet/tasks/task.php?id='.$lines[$i]->id.'&withproject=1">';
453
				for ($k = 0 ; $k < $level ; $k++)
454
				{
455
					print "&nbsp; &nbsp; &nbsp;";
456
				}
457
				print $lines[$i]->label;
458
				if ($showlineingray) print '</i>';
459
				//else print '</a>';
460
				print "</td>\n";
461
462
				// Date start
463
				print '<td align="center">';
464
				print dol_print_date($lines[$i]->date_start,'dayhour');
465
				print '</td>';
466
467
				// Date end
468
				print '<td align="center">';
469
				$taskstatic->projectstatus = $lines[$i]->projectstatus;
470
				$taskstatic->progress = $lines[$i]->progress;
471
				$taskstatic->fk_statut = $lines[$i]->status;
472
				$taskstatic->datee = $lines[$i]->date_end;
473
				print dol_print_date($lines[$i]->date_end,'dayhour');
474
				if ($taskstatic->hasDelay()) print img_warning($langs->trans("Late"));
475
				print '</td>';
476
477
				$plannedworkloadoutputformat='allhourmin';
478
				$timespentoutputformat='allhourmin';
479
				if (! empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat=$conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT;
0 ignored issues
show
Bug introduced by
The variable $conf does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
480
				if (! empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat=$conf->global->PROJECT_TIME_SPENT_FORMAT;
481
482
				// Planned Workload (in working hours)
483
				print '<td align="right">';
484
				$fullhour=convertSecondToTime($lines[$i]->planned_workload,$plannedworkloadoutputformat);
485
				$workingdelay=convertSecondToTime($lines[$i]->planned_workload,'all',86400,7);	// TODO Replace 86400 and 7 to take account working hours per day and working day per weeks
486
				if ($lines[$i]->planned_workload != '')
487
				{
488
					print $fullhour;
489
					// TODO Add delay taking account of working hours per day and working day per week
490
					//if ($workingdelay != $fullhour) print '<br>('.$workingdelay.')';
491
				}
492
				//else print '--:--';
493
				print '</td>';
494
495
				// Time spent
496
				print '<td align="right">';
497
				if ($showlineingray) print '<i>';
498
				else print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$lines[$i]->id.($showproject?'':'&withproject=1').'">';
499
				if ($lines[$i]->duration) print convertSecondToTime($lines[$i]->duration,$timespentoutputformat);
500
				else print '--:--';
501
				if ($showlineingray) print '</i>';
502
				else print '</a>';
503
				print '</td>';
504
505
				// Progress calculated (Note: ->duration is time spent)
506
				print '<td align="right">';
507
				if ($lines[$i]->planned_workload || $lines[$i]->duration)
508
				{
509
					if ($lines[$i]->planned_workload) print round(100 * $lines[$i]->duration / $lines[$i]->planned_workload,2).' %';
510
					else print '<span class="opacitymedium">'.$langs->trans('WorkloadNotDefined').'</span>';
511
				}
512
				print '</td>';
513
514
				// Progress declared
515
				print '<td align="right">';
516
				if ($lines[$i]->progress != '')
517
				{
518
					print $lines[$i]->progress.' %';
519
				}
520
				print '</td>';
521
522
				// Tick to drag and drop
523
				if ($addordertick)
524
				{
525
					print '<td align="center" class="tdlineupdown hideonsmartphone">&nbsp;</td>';
526
				}
527
528
				print "</tr>\n";
529
530
				if (! $showlineingray) $inc++;
531
532
				if ($level >= 0)    // Call sublevels
533
				{
534
					$level++;
535
					if ($lines[$i]->id) projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick);
536
					$level--;
537
				}
538
539
				$total_projectlinesa_spent += $lines[$i]->duration;
540
				$total_projectlinesa_planned += $lines[$i]->planned_workload;
541
				if ($lines[$i]->planned_workload) $total_projectlinesa_spent_if_planned += $lines[$i]->duration;
542
			}
543
		}
544
		else
545
		{
546
			//$level--;
547
		}
548
	}
549
550
	if (($total_projectlinesa_planned > 0 || $total_projectlinesa_spent > 0) && $level <= 0)
551
	{
552
		print '<tr class="liste_total nodrag nodrop">';
553
		print '<td class="liste_total">'.$langs->trans("Total").'</td>';
554
		if ($showproject) print '<td></td><td></td>';
555
		print '<td></td>';
556
		print '<td></td>';
557
		print '<td></td>';
558
		print '<td align="right" class="nowrap liste_total">';
559
		print convertSecondToTime($total_projectlinesa_planned, 'allhourmin');
560
		print '</td>';
561
		print '<td align="right" class="nowrap liste_total">';
562
		if ($projectidfortotallink > 0) print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?projectid='.$projectidfortotallink.($showproject?'':'&withproject=1').'">';
563
		print convertSecondToTime($total_projectlinesa_spent, 'allhourmin');
564
		if ($projectidfortotallink > 0) print '</a>';
565
		print '</td>';
566
		print '<td align="right" class="nowrap liste_total">';
567
		if ($total_projectlinesa_planned) print round(100 * $total_projectlinesa_spent / $total_projectlinesa_planned,2).' %';
568
		print '</td>';
569
		print '<td></td>';
570
		if ($addordertick) print '<td class="hideonsmartphone"></td>';
571
		print '</tr>';
572
	}
573
574
	return $inc;
575
}
576
577
578
/**
579
 * Output a task line into a pertime intput mode
580
 *
581
 * @param	string	   	$inc					Line number (start to 0, then increased by recursive call)
582
 * @param   string		$parent					Id of parent task to show (0 to show all)
583
 * @param	User|null	$fuser					Restrict list to user if defined
584
 * @param   Task[]		$lines					Array of lines
585
 * @param   int			$level					Level (start to 0, then increased/decrease by recursive call)
586
 * @param   string		$projectsrole			Array of roles user has on project
587
 * @param   string		$tasksrole				Array of roles user has on task
588
 * @param	string		$mine					Show only task lines I am assigned to
589
 * @param   int			$restricteditformytask	0=No restriction, 1=Enable add time only if task is a task i am affected to
590
 * @param	int			$preselectedday			Preselected day
591
 * @param   array       $isavailable			Array with data that say if user is available for several days for morning and afternoon
592
 * @param	int			$oldprojectforbreak		Old project id of last project break
593
 * @return  array								Array with time spent for $fuser for each day of week on tasks in $lines and substasks
594
 */
595
function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask, $preselectedday, &$isavailable, $oldprojectforbreak=0)
596
{
597
	global $conf, $db, $user, $bc, $langs;
598
	global $form, $formother, $projectstatic, $taskstatic, $thirdpartystatic;
599
600
	$lastprojectid=0;
601
	$totalforeachline=array();
602
	$workloadforid=array();
603
	$lineswithoutlevel0=array();
604
605
	$numlines=count($lines);
606
607
	// Create a smaller array with sublevels only to be used later. This increase dramatically performances.
608
	if ($parent == 0) // Always and only if at first level
609
	{
610
		for ($i = 0 ; $i < $numlines ; $i++)
611
		{
612
			if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[]=$lines[$i];
613
		}
614
	}
615
616
	if (empty($oldprojectforbreak))
617
	{
618
		$oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:-1);	// 0 to start break , -1 no break
619
	}
620
621
	//dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0));
622
	for ($i = 0 ; $i < $numlines ; $i++)
623
	{
624
		if ($parent == 0) $level = 0;
625
626
		//if ($lines[$i]->fk_task_parent == $parent)
627
		//{
628
			// If we want all or we have a role on task, we show it
629
			if (empty($mine) || ! empty($tasksrole[$lines[$i]->id]))
630
			{
631
				//dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project);
632
633
				// Break on a new project
634
				if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
635
				{
636
					$lastprojectid=$lines[$i]->fk_project;
637
					if ($preselectedday)
638
					{
639
						$projectstatic->id = $lines[$i]->fk_project;
640
					}
641
				}
642
643
				if (empty($workloadforid[$projectstatic->id]))
644
				{
645
					if ($preselectedday)
646
					{
647
						$projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id);	// Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week
648
						$workloadforid[$projectstatic->id]=1;
649
					}
650
				}
651
652
				$projectstatic->id=$lines[$i]->fk_project;
653
				$projectstatic->ref=$lines[$i]->project_ref;
654
				$projectstatic->title=$lines[$i]->project_label;
655
				$projectstatic->public=$lines[$i]->public;
656
657
				$taskstatic->id=$lines[$i]->task_id;
658
				$taskstatic->ref=($lines[$i]->task_ref?$lines[$i]->task_ref:$lines[$i]->task_id);
659
				$taskstatic->label=$lines[$i]->task_label;
660
				$taskstatic->date_start=$lines[$i]->date_start;
661
				$taskstatic->date_end=$lines[$i]->date_end;
662
663
				$thirdpartystatic->id=$lines[$i]->socid;
664
				$thirdpartystatic->name=$lines[$i]->thirdparty_name;
665
				$thirdpartystatic->email=$lines[$i]->thirdparty_email;
666
667
				if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id))
668
				{
669
					print '<tr class="oddeven trforbreak">'."\n";
670
					print '<td colspan="11">';
671
					print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
672
					if ($projectstatic->title)
673
					{
674
						print ' - ';
675
						print $projectstatic->title;
676
					}
677
					print '</td>';
678
					print '</tr>';
679
				}
680
681
				if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id;
682
683
				print '<tr class="oddeven">'."\n";
684
685
				// User
686
				/*
687
				 print '<td class="nowrap">';
688
				 print $fuser->getNomUrl(1, 'withproject', 'time');
689
				 print '</td>';
690
				 */
691
692
				// Project
693
				print "<td>";
694
				if ($oldprojectforbreak == -1)
695
				{
696
					print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
697
					print '<br>'.$projectstatic->title;
698
				}
699
				print "</td>";
700
701
				// Thirdparty
702
				print '<td class="tdoverflowmax100">';
703
				if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10);
704
				print '</td>';
705
706
				// Ref
707
				print '<td>';
708
				print '<!-- Task id = '.$lines[$i]->id.' -->';
709
				for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
710
				print $taskstatic->getNomUrl(1, 'withproject', 'time');
711
				// Label task
712
				print '<br>';
713
				for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
714
				print $taskstatic->label;
715
				//print "<br>";
716
				//for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
717
				//print get_date_range($lines[$i]->date_start,$lines[$i]->date_end,'',$langs,0);
718
				print "</td>\n";
719
720
				// Date
721
				print '<td align="center">';
722
				print dol_print_date($lines[$i]->timespent_datehour,'day');
723
				print '</td>';
724
725
				$disabledproject=1;$disabledtask=1;
726
				//print "x".$lines[$i]->fk_project;
727
				//var_dump($lines[$i]);
728
				//var_dump($projectsrole[$lines[$i]->fk_project]);
729
				// If at least one role for project
730
				if ($lines[$i]->public || ! empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
731
				{
732
					$disabledproject=0;
733
					$disabledtask=0;
734
				}
735
				// If $restricteditformytask is on and I have no role on task, i disable edit
736
				if ($restricteditformytask && empty($tasksrole[$lines[$i]->id]))
737
				{
738
					$disabledtask=1;
739
				}
740
741
				// Hour
742
				print '<td class="nowrap" align="center">';
743
				print dol_print_date($lines[$i]->timespent_datehour,'hour');
744
				print '</td>';
745
746
				$cssonholiday='';
747
				if (! $isavailable[$preselectedday]['morning'] && ! $isavailable[$preselectedday]['afternoon'])   $cssonholiday.='onholidayallday ';
748
				elseif (! $isavailable[$preselectedday]['morning'])   $cssonholiday.='onholidaymorning ';
749
				elseif (! $isavailable[$preselectedday]['afternoon']) $cssonholiday.='onholidayafternoon ';
750
751
				// Duration
752
				print '<td align="center" class="duration'.($cssonholiday?' '.$cssonholiday:'').'">';
753
754
				$dayWorkLoad = $lines[$i]->timespent_duration;
755
				$totalforeachline[$preselectedday]+=$lines[$i]->timespent_duration;
756
757
				$alreadyspent='';
758
				if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($lines[$i]->timespent_duration,'allhourmin');
759
760
				print convertSecondToTime($lines[$i]->timespent_duration,'allhourmin');
761
762
				$modeinput='hours';
763
764
				print '<script type="text/javascript">';
765
				print "jQuery(document).ready(function () {\n";
766
				print " 	jQuery('.inputhour, .inputminute').bind('keyup', function(e) { updateTotal(0, '".$modeinput."') });";
767
				print "})\n";
768
				print '</script>';
769
770
				print '</td>';
771
772
				// Note
773
				print '<td align="center">';
774
				print '<textarea name="'.$lines[$i]->id.'note" rows="'.ROWS_2.'" id="'.$lines[$i]->id.'note"'.($disabledtask?' disabled="disabled"':'').'>';
775
				print $lines[$i]->timespent_note;
776
				print '</textarea>';
777
				print '</td>';
778
779
				// Warning
780
				print '<td align="right">';
781
				/*if ((! $lines[$i]->public) && $disabledproject) print $form->textwithpicto('',$langs->trans("UserIsNotContactOfProject"));
782
				else if ($disabledtask)
783
				{
784
					$titleassigntask = $langs->trans("AssignTaskToMe");
785
					if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...');
786
787
					print $form->textwithpicto('',$langs->trans("TaskIsNotAssignedToUser", $titleassigntask));
788
				}*/
789
				print '</td>';
790
791
				print "</tr>\n";
792
			}
793
		//}
794
		//else
795
		//{
796
			//$level--;
797
		//}
798
	}
799
800
	return $totalforeachline;
801
}
802
803
804
/**
805
 * Output a task line into a pertime intput mode
806
 *
807
 * @param	string	   	$inc					Line number (start to 0, then increased by recursive call)
808
 * @param   string		$parent					Id of parent task to show (0 to show all)
809
 * @param	User|null	$fuser					Restrict list to user if defined
810
 * @param   Task[]		$lines					Array of lines
811
 * @param   int			$level					Level (start to 0, then increased/decrease by recursive call)
812
 * @param   string		$projectsrole			Array of roles user has on project
813
 * @param   string		$tasksrole				Array of roles user has on task
814
 * @param	string		$mine					Show only task lines I am assigned to
815
 * @param   int			$restricteditformytask	0=No restriction, 1=Enable add time only if task is a task i am affected to
816
 * @param	int			$preselectedday			Preselected day
817
 * @param   array       $isavailable			Array with data that say if user is available for several days for morning and afternoon
818
 * @param	int			$oldprojectforbreak		Old project id of last project break
819
 * @return  array								Array with time spent for $fuser for each day of week on tasks in $lines and substasks
820
 */
821
function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask, $preselectedday, &$isavailable, $oldprojectforbreak=0)
822
{
823
	global $conf, $db, $user, $bc, $langs;
824
	global $form, $formother, $projectstatic, $taskstatic, $thirdpartystatic;
825
826
	$lastprojectid=0;
827
	$totalforeachday=array();
828
	$workloadforid=array();
829
	$lineswithoutlevel0=array();
830
831
	$numlines=count($lines);
832
833
	// Create a smaller array with sublevels only to be used later. This increase dramatically performances.
834
	if ($parent == 0) // Always and only if at first level
835
	{
836
		for ($i = 0 ; $i < $numlines ; $i++)
837
		{
838
			if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[]=$lines[$i];
839
		}
840
	}
841
842
	if (empty($oldprojectforbreak))
843
	{
844
		$oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:-1);	// 0 to start break , -1 no break
845
	}
846
847
	//dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0));
848
	for ($i = 0 ; $i < $numlines ; $i++)
849
	{
850
		if ($parent == 0) $level = 0;
851
852
		if ($lines[$i]->fk_task_parent == $parent)
853
		{
854
			// If we want all or we have a role on task, we show it
855
			if (empty($mine) || ! empty($tasksrole[$lines[$i]->id]))
856
			{
857
				//dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project);
858
859
				// Break on a new project
860
				if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
861
				{
862
					$lastprojectid=$lines[$i]->fk_project;
863
					if ($preselectedday)
864
					{
865
						$projectstatic->id = $lines[$i]->fk_project;
866
					}
867
				}
868
869
				if (empty($workloadforid[$projectstatic->id]))
870
				{
871
					if ($preselectedday)
872
					{
873
						$projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id);	// Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week
874
		   				$workloadforid[$projectstatic->id]=1;
875
					}
876
				}
877
878
				$projectstatic->id=$lines[$i]->fk_project;
879
				$projectstatic->ref=$lines[$i]->projectref;
880
				$projectstatic->title=$lines[$i]->projectlabel;
881
				$projectstatic->public=$lines[$i]->public;
882
883
				$taskstatic->id=$lines[$i]->id;
884
				$taskstatic->ref=($lines[$i]->ref?$lines[$i]->ref:$lines[$i]->id);
885
				$taskstatic->label=$lines[$i]->label;
886
				$taskstatic->date_start=$lines[$i]->date_start;
887
				$taskstatic->date_end=$lines[$i]->date_end;
888
889
				$thirdpartystatic->id=$lines[$i]->socid;
890
				$thirdpartystatic->name=$lines[$i]->thirdparty_name;
891
				$thirdpartystatic->email=$lines[$i]->thirdparty_email;
892
893
				if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id))
894
				{
895
					print '<tr class="oddeven trforbreak">'."\n";
896
					print '<td colspan="11">';
897
					print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
898
					if ($projectstatic->title)
899
					{
900
						print ' - ';
901
						print $projectstatic->title;
902
					}
903
					print '</td>';
904
					print '</tr>';
905
				}
906
907
				if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id;
908
909
				print '<tr class="oddeven">'."\n";
910
911
				// User
912
				/*
913
				print '<td class="nowrap">';
914
				print $fuser->getNomUrl(1, 'withproject', 'time');
915
				print '</td>';
916
				*/
917
918
				// Project
919
				print "<td>";
920
				if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
921
				print "</td>";
922
923
				// Thirdparty
924
				print '<td class="tdoverflowmax100">';
925
				if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10);
926
				print '</td>';
927
928
				// Ref
929
				print '<td>';
930
				print '<!-- Task id = '.$lines[$i]->id.' -->';
931
				for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
932
				print $taskstatic->getNomUrl(1, 'withproject', 'time');
933
				// Label task
934
				print '<br>';
935
				for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
936
				print $taskstatic->label;
937
				//print "<br>";
938
				//for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
939
				//print get_date_range($lines[$i]->date_start,$lines[$i]->date_end,'',$langs,0);
940
				print "</td>\n";
941
942
				// Planned Workload
943
				print '<td align="right">';
944
				if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload,'allhourmin');
945
				else print '--:--';
946
				print '</td>';
947
948
				// Progress declared %
949
				print '<td align="right">';
950
				print $formother->select_percent($lines[$i]->progress, $lines[$i]->id . 'progress');
951
				print '</td>';
952
953
				// Time spent by everybody
954
				print '<td align="right">';
955
				// $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user
956
				if ($lines[$i]->duration)
957
				{
958
					print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$lines[$i]->id.'">';
959
					print convertSecondToTime($lines[$i]->duration,'allhourmin');
960
					print '</a>';
961
				}
962
				else print '--:--';
963
				print "</td>\n";
964
965
				// Time spent by user
966
				print '<td align="right">';
967
				$tmptimespent=$taskstatic->getSummaryOfTimeSpent($fuser->id);
968
				if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'],'allhourmin');
969
				else print '--:--';
970
				print "</td>\n";
971
972
				$disabledproject=1;$disabledtask=1;
973
				//print "x".$lines[$i]->fk_project;
974
				//var_dump($lines[$i]);
975
				//var_dump($projectsrole[$lines[$i]->fk_project]);
976
				// If at least one role for project
977
				if ($lines[$i]->public || ! empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
978
				{
979
					$disabledproject=0;
980
					$disabledtask=0;
981
				}
982
				// If $restricteditformytask is on and I have no role on task, i disable edit
983
				if ($restricteditformytask && empty($tasksrole[$lines[$i]->id]))
984
				{
985
					$disabledtask=1;
986
				}
987
988
				// Form to add new time
989
				print '<td class="nowrap" align="center">';
990
				$tableCell=$form->select_date($preselectedday,$lines[$i]->id,1,1,2,"addtime",0,0,1,$disabledtask);
991
				print $tableCell;
992
				print '</td>';
993
994
				$cssonholiday='';
995
				if (! $isavailable[$preselectedday]['morning'] && ! $isavailable[$preselectedday]['afternoon'])   $cssonholiday.='onholidayallday ';
996
				elseif (! $isavailable[$preselectedday]['morning'])   $cssonholiday.='onholidaymorning ';
997
				elseif (! $isavailable[$preselectedday]['afternoon']) $cssonholiday.='onholidayafternoon ';
998
999
				// Duration
1000
				print '<td align="center" class="duration'.($cssonholiday?' '.$cssonholiday:'').'">';
1001
1002
				$dayWorkLoad = $projectstatic->weekWorkLoadPerTask[$preselectedday][$lines[$i]->id];
1003
				$totalforeachday[$preselectedday]+=$dayWorkLoad;
1004
1005
				$alreadyspent='';
1006
				if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($dayWorkLoad,'allhourmin');
1007
1008
				$idw = 0;
1009
1010
				$tableCell='';
1011
				$tableCell.='<span class="timesheetalreadyrecorded" title="texttoreplace"><input type="text" class="center" size="2" disabled id="timespent['.$inc.']['.$idw.']" name="task['.$lines[$i]->id.']['.$idw.']" value="'.$alreadyspent.'"></span>';
1012
				$tableCell.='<span class="hideonsmartphone"> + </span>';
1013
				//$tableCell.='&nbsp;&nbsp;&nbsp;';
1014
				$tableCell.=$form->select_duration($lines[$i]->id.'duration','',$disabledtask,'text',0,1);
1015
				//$tableCell.='&nbsp;<input type="submit" class="button"'.($disabledtask?' disabled':'').' value="'.$langs->trans("Add").'">';
1016
				print $tableCell;
1017
1018
				$modeinput='hours';
1019
1020
				print '<script type="text/javascript">';
1021
				print "jQuery(document).ready(function () {\n";
1022
				print " 	jQuery('.inputhour, .inputminute').bind('keyup', function(e) { updateTotal(0, '".$modeinput."') });";
1023
				print "})\n";
1024
				print '</script>';
1025
1026
				print '</td>';
1027
1028
				// Note
1029
				print '<td align="center">';
1030
				print '<textarea name="'.$lines[$i]->id.'note" rows="'.ROWS_2.'" id="'.$lines[$i]->id.'note"'.($disabledtask?' disabled="disabled"':'').'>';
1031
				print '</textarea>';
1032
				print '</td>';
1033
1034
				// Warning
1035
				print '<td align="right">';
1036
   				if ((! $lines[$i]->public) && $disabledproject) print $form->textwithpicto('',$langs->trans("UserIsNotContactOfProject"));
1037
   				else if ($disabledtask)
1038
   				{
1039
   					$titleassigntask = $langs->trans("AssignTaskToMe");
1040
   					if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...');
1041
1042
   					print $form->textwithpicto('',$langs->trans("TaskIsNotAssignedToUser", $titleassigntask));
1043
   				}
1044
				print '</td>';
1045
1046
				print "</tr>\n";
1047
			}
1048
1049
			$inc++;
1050
			$level++;
1051
			if ($lines[$i]->id > 0)
1052
			{
1053
				//var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level);
1054
				//var_dump($totalforeachday);
1055
				$ret = projectLinesPerDay($inc, $lines[$i]->id, $fuser, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable, $oldprojectforbreak);
1056
				//var_dump('ret with parent='.$lines[$i]->id.' level='.$level);
1057
				//var_dump($ret);
1058
				foreach($ret as $key => $val)
1059
				{
1060
					$totalforeachday[$key]+=$val;
1061
				}
1062
				//var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks');
1063
				//var_dump($totalforeachday);
1064
			}
1065
			$level--;
1066
		}
1067
		else
1068
		{
1069
			//$level--;
1070
		}
1071
	}
1072
1073
	return $totalforeachday;
1074
}
1075
1076
1077
/**
1078
 * Output a task line into a perday intput mode
1079
 *
1080
 * @param	string	   	$inc					Line output identificator (start to 0, then increased by recursive call)
1081
 * @param	int			$firstdaytoshow			First day to show
1082
 * @param	User|null	$fuser					Restrict list to user if defined
1083
 * @param   string		$parent					Id of parent task to show (0 to show all)
1084
 * @param   Task[]		$lines					Array of lines (list of tasks but we will show only if we have a specific role on task)
1085
 * @param   int			$level					Level (start to 0, then increased/decrease by recursive call)
1086
 * @param   string		$projectsrole			Array of roles user has on project
1087
 * @param   string		$tasksrole				Array of roles user has on task
1088
 * @param	string		$mine					Show only task lines I am assigned to
1089
 * @param   int			$restricteditformytask	0=No restriction, 1=Enable add time only if task is a task i am affected to
1090
 * @param   array       $isavailable			Array with data that say if user is available for several days for morning and afternoon
1091
 * @param	int			$oldprojectforbreak		Old project id of last project break
1092
 * @return  array								Array with time spent for $fuser for each day of week on tasks in $lines and substasks
1093
 */
1094
function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask, &$isavailable, $oldprojectforbreak=0)
1095
{
1096
	global $conf, $db, $user, $bc, $langs;
1097
	global $form, $formother, $projectstatic, $taskstatic, $thirdpartystatic;
1098
1099
	$numlines=count($lines);
1100
1101
	$lastprojectid=0;
1102
	$workloadforid=array();
1103
	$totalforeachday=array();
1104
	$lineswithoutlevel0=array();
1105
1106
	// Create a smaller array with sublevels only to be used later. This increase dramatically performances.
1107
	if ($parent == 0) // Always and only if at first level
1108
	{
1109
		for ($i = 0 ; $i < $numlines ; $i++)
1110
		{
1111
		   if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[]=$lines[$i];
1112
		}
1113
	}
1114
1115
	//dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0));
1116
1117
	if (empty($oldprojectforbreak))
1118
	{
1119
		$oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:-1);	// 0 = start break, -1 = never break
1120
	}
1121
1122
	for ($i = 0 ; $i < $numlines ; $i++)
1123
	{
1124
		if ($parent == 0) $level = 0;
1125
1126
		if ($lines[$i]->fk_task_parent == $parent)
1127
		{
1128
			// If we want all or we have a role on task, we show it
1129
			if (empty($mine) || ! empty($tasksrole[$lines[$i]->id]))
1130
			{
1131
				//dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project);
1132
1133
				// Break on a new project
1134
				if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
1135
				{
1136
					$lastprojectid=$lines[$i]->fk_project;
1137
					$projectstatic->id = $lines[$i]->fk_project;
1138
				}
1139
1140
				//var_dump('--- '.$level.' '.$firstdaytoshow.' '.$fuser->id.' '.$projectstatic->id.' '.$workloadforid[$projectstatic->id]);
1141
				//var_dump($projectstatic->weekWorkLoadPerTask);
1142
				if (empty($workloadforid[$projectstatic->id]))
1143
				{
1144
					$projectstatic->loadTimeSpent($firstdaytoshow, 0, $fuser->id);	// Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week
1145
					$workloadforid[$projectstatic->id]=1;
1146
				}
1147
				//var_dump($projectstatic->weekWorkLoadPerTask);
1148
				//var_dump('--- '.$projectstatic->id.' '.$workloadforid[$projectstatic->id]);
1149
1150
				$projectstatic->id=$lines[$i]->fk_project;
1151
				$projectstatic->ref=$lines[$i]->projectref;
1152
				$projectstatic->title=$lines[$i]->projectlabel;
1153
				$projectstatic->public=$lines[$i]->public;
1154
				$projectstatic->thirdparty_name=$lines[$i]->thirdparty_name;
1155
1156
				$taskstatic->id=$lines[$i]->id;
1157
				$taskstatic->ref=($lines[$i]->ref?$lines[$i]->ref:$lines[$i]->id);
1158
				$taskstatic->label=$lines[$i]->label;
1159
				$taskstatic->date_start=$lines[$i]->date_start;
1160
				$taskstatic->date_end=$lines[$i]->date_end;
1161
1162
				$thirdpartystatic->id=$lines[$i]->thirdparty_id;
1163
				$thirdpartystatic->name=$lines[$i]->thirdparty_name;
1164
				$thirdpartystatic->email=$lines[$i]->thirdparty_email;
1165
1166
				if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id))
1167
				{
1168
					print '<tr class="oddeven trforbreak">'."\n";
1169
					print '<td colspan="15">';
1170
					print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
1171
					if ($projectstatic->title)
1172
					{
1173
						print ' - ';
1174
						print $projectstatic->title;
1175
					}
1176
					print '</td>';
1177
					print '</tr>';
1178
				}
1179
1180
				if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id;
1181
1182
				print '<tr class="oddeven">'."\n";
1183
1184
				// User
1185
				/*
1186
				print '<td class="nowrap">';
1187
				print $fuser->getNomUrl(1, 'withproject', 'time');
1188
				print '</td>';
1189
				*/
1190
1191
				// Project
1192
				print '<td class="nowrap">';
1193
				if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1,'',0,$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
1194
				print "</td>";
1195
1196
				// Thirdparty
1197
				print '<td class="tdoverflowmax100">';
1198
				if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project');
1199
				print '</td>';
1200
1201
				// Ref
1202
				print '<td class="nowrap">';
1203
				print '<!-- Task id = '.$lines[$i]->id.' -->';
1204
				for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
1205
				print $taskstatic->getNomUrl(1, 'withproject', 'time');
1206
				// Label task
1207
				print '<br>';
1208
				for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
1209
				//print $taskstatic->getNomUrl(0, 'withproject', 'time');
1210
				print $taskstatic->label;
1211
				//print "<br>";
1212
				//for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
1213
				//print get_date_range($lines[$i]->date_start,$lines[$i]->date_end,'',$langs,0);
1214
				print "</td>\n";
1215
1216
				// Planned Workload
1217
				print '<td align="right">';
1218
				if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload,'allhourmin');
1219
				else print '--:--';
1220
				print '</td>';
1221
1222
				// Progress declared %
1223
				print '<td align="right">';
1224
				print $formother->select_percent($lines[$i]->progress, $lines[$i]->id . 'progress');
1225
				print '</td>';
1226
1227
				// Time spent by everybody
1228
				print '<td align="right">';
1229
				// $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user
1230
				if ($lines[$i]->duration)
1231
				{
1232
					print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$lines[$i]->id.'">';
1233
					print convertSecondToTime($lines[$i]->duration,'allhourmin');
1234
					print '</a>';
1235
				}
1236
				else print '--:--';
1237
				print "</td>\n";
1238
1239
				// Time spent by user
1240
				print '<td align="right">';
1241
				$tmptimespent=$taskstatic->getSummaryOfTimeSpent($fuser->id);
1242
				if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'],'allhourmin');
1243
				else print '--:--';
1244
				print "</td>\n";
1245
1246
				$disabledproject=1;$disabledtask=1;
1247
				//print "x".$lines[$i]->fk_project;
1248
				//var_dump($lines[$i]);
1249
				//var_dump($projectsrole[$lines[$i]->fk_project]);
1250
				// If at least one role for project
1251
				if ($lines[$i]->public || ! empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
1252
				{
1253
					$disabledproject=0;
1254
					$disabledtask=0;
1255
				}
1256
				// If $restricteditformytask is on and I have no role on task, i disable edit
1257
				if ($restricteditformytask && empty($tasksrole[$lines[$i]->id]))
1258
				{
1259
					$disabledtask=1;
1260
				}
1261
1262
				//var_dump($projectstatic->weekWorkLoadPerTask);
1263
1264
				// Fields to show current time
1265
				$tableCell=''; $modeinput='hours';
1266
				for ($idw = 0; $idw < 7; $idw++)
1267
				{
1268
					$tmpday=dol_time_plus_duree($firstdaytoshow, $idw, 'd');
1269
1270
					$cssonholiday='';
1271
					if (! $isavailable[$tmpday]['morning'] && ! $isavailable[$tmpday]['afternoon'])   $cssonholiday.='onholidayallday ';
1272
					elseif (! $isavailable[$tmpday]['morning'])   $cssonholiday.='onholidaymorning ';
1273
					elseif (! $isavailable[$tmpday]['afternoon']) $cssonholiday.='onholidayafternoon ';
1274
1275
					$tmparray=dol_getdate($tmpday);
1276
					$dayWorkLoad = $projectstatic->weekWorkLoadPerTask[$tmpday][$lines[$i]->id];
1277
					$totalforeachday[$tmpday]+=$dayWorkLoad;
1278
1279
					$alreadyspent='';
1280
					if ($dayWorkLoad > 0) $alreadyspent=convertSecondToTime($dayWorkLoad,'allhourmin');
1281
					$alttitle=$langs->trans("AddHereTimeSpentForDay",$tmparray['day'],$tmparray['mon']);
1282
1283
					$tableCell ='<td align="center" class="hide'.$idw.($cssonholiday?' '.$cssonholiday:'').'">';
1284
					if ($alreadyspent)
1285
					{
1286
						$tableCell.='<span class="timesheetalreadyrecorded" title="texttoreplace"><input type="text" class="center smallpadd" size="2" disabled id="timespent['.$inc.']['.$idw.']" name="task['.$lines[$i]->id.']['.$idw.']" value="'.$alreadyspent.'"></span>';
1287
						//$placeholder=' placeholder="00:00"';
1288
						$placeholder='';
1289
					 	//$tableCell.='+';
1290
					}
1291
				  	$tableCell.='<input type="text" alt="'.($disabledtask?'':$alttitle).'" title="'.($disabledtask?'':$alttitle).'" '.($disabledtask?'disabled':$placeholder).' class="center smallpadd" size="2" id="timeadded['.$inc.']['.$idw.']" name="task['.$lines[$i]->id.']['.$idw.']" value="" cols="2"  maxlength="5"';
0 ignored issues
show
Bug introduced by
The variable $placeholder 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...
1292
					$tableCell.=' onkeypress="return regexEvent(this,event,\'timeChar\')"';
1293
				   	$tableCell.=' onkeyup="updateTotal('.$idw.',\''.$modeinput.'\')"';
1294
				   	$tableCell.=' onblur="regexEvent(this,event,\''.$modeinput.'\'); updateTotal('.$idw.',\''.$modeinput.'\')" />';
1295
				   	$tableCell.='</td>';
1296
					print $tableCell;
1297
				}
1298
1299
				// Warning
1300
				print '<td align="right">';
1301
   				if ((! $lines[$i]->public) && $disabledproject) print $form->textwithpicto('',$langs->trans("UserIsNotContactOfProject"));
1302
   				else if ($disabledtask)
1303
   				{
1304
   					$titleassigntask = $langs->trans("AssignTaskToMe");
1305
   					if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...');
1306
1307
   					print $form->textwithpicto('',$langs->trans("TaskIsNotAssignedToUser", $titleassigntask));
1308
   				}
1309
				print '</td>';
1310
1311
				print "</tr>\n";
1312
			}
1313
1314
			// Call to show task with a lower level (task under the current task)
1315
			$inc++;
1316
			$level++;
1317
			if ($lines[$i]->id > 0)
1318
			{
1319
				//var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level);
1320
				//var_dump($totalforeachday);
1321
				$ret = projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable, $oldprojectforbreak);
1322
				//var_dump('ret with parent='.$lines[$i]->id.' level='.$level);
1323
				//var_dump($ret);
1324
				foreach($ret as $key => $val)
1325
				{
1326
					$totalforeachday[$key]+=$val;
1327
				}
1328
				//var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks');
1329
				//var_dump($totalforeachday);
1330
			}
1331
			$level--;
1332
		}
1333
		else
1334
		{
1335
			//$level--;
1336
		}
1337
	}
1338
1339
	return $totalforeachday;
1340
}
1341
1342
1343
/**
1344
 * Search in task lines with a particular parent if there is a task for a particular user (in taskrole)
1345
 *
1346
 * @param 	string	$inc				Counter that count number of lines legitimate to show (for return)
1347
 * @param 	int		$parent				Id of parent task to start
1348
 * @param 	array	$lines				Array of all tasks
1349
 * @param	string	$taskrole			Array of task filtered on a particular user
1350
 * @return	int							1 if there is
1351
 */
1352
function searchTaskInChild(&$inc, $parent, &$lines, &$taskrole)
1353
{
1354
	//print 'Search in line with parent id = '.$parent.'<br>';
1355
	$numlines=count($lines);
1356
	for ($i = 0 ; $i < $numlines ; $i++)
1357
	{
1358
		// Process line $lines[$i]
1359
		if ($lines[$i]->fk_parent == $parent && $lines[$i]->id != $lines[$i]->fk_parent)
1360
		{
1361
			// If task is legitimate to show, no more need to search deeper
1362
			if (isset($taskrole[$lines[$i]->id]))
1363
			{
1364
				//print 'Found a legitimate task id='.$lines[$i]->id.'<br>';
1365
				$inc++;
1366
				return $inc;
1367
			}
1368
1369
			searchTaskInChild($inc, $lines[$i]->id, $lines, $taskrole);
1370
			//print 'Found inc='.$inc.'<br>';
1371
1372
			if ($inc > 0) return $inc;
1373
		}
1374
	}
1375
1376
	return $inc;
1377
}
1378
1379
/**
1380
 * Return HTML table with list of projects and number of opened tasks
1381
 *
1382
 * @param	DoliDB	$db					Database handler
1383
 * @param	Form	$form				Object form
1384
 * @param   int		$socid				Id thirdparty
1385
 * @param   int		$projectsListId     Id of project I have permission on
1386
 * @param   int		$mytasks            Limited to task I am contact to
1387
 * @param	int		$statut				-1=No filter on statut, 0 or 1 = Filter on status
1388
 * @param	array	$listofoppstatus	List of opportunity status
1389
 * @param   array   $hiddenfields       List of info to not show ('projectlabel', 'declaredprogress', '...', )
1390
 * @return	void
1391
 */
1392
function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks=0, $statut=-1, $listofoppstatus=array(),$hiddenfields=array())
1393
{
1394
	global $langs,$conf,$user,$bc;
1395
1396
	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1397
1398
	$projectstatic=new Project($db);
1399
	$thirdpartystatic=new Societe($db);
1400
1401
	$sortfield='';
1402
	$sortorder='';
1403
	$project_year_filter=0;
1404
1405
	$title=$langs->trans("Projects");
1406
	if (strcmp($statut, '') && $statut >= 0) $title=$langs->trans("Projects").' '.$langs->trans($projectstatic->statuts_long[$statut]);
1407
1408
	$arrayidtypeofcontact=array();
1409
1410
	print '<div class="div-table-responsive-no-min">';
1411
	print '<table class="noborder" width="100%">';
1412
1413
	$sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
0 ignored issues
show
Bug introduced by
The variable $sql does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1414
	if ($mytasks)
1415
	{
1416
		$sql.= ", ".MAIN_DB_PREFIX."projet_task as t";
1417
		$sql.= ", ".MAIN_DB_PREFIX."element_contact as ec";
1418
		$sql.= ", ".MAIN_DB_PREFIX."c_type_contact as ctc";
1419
	}
1420
	else
1421
	{
1422
		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t ON p.rowid = t.fk_projet";
1423
	}
1424
	$sql.= " WHERE p.entity = ".$conf->entity;
1425
	$sql.= " AND p.rowid IN (".$projectsListId.")";
1426
	if ($socid) $sql.= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
1427
	if ($mytasks)
1428
	{
1429
		$sql.= " AND p.rowid = t.fk_projet";
1430
		$sql.= " AND ec.element_id = t.rowid";
1431
		$sql.= " AND ec.fk_socpeople = ".$user->id;
1432
		$sql.= " AND ec.fk_c_type_contact = ctc.rowid";   // Replace the 2 lines with ec.fk_c_type_contact in $arrayidtypeofcontact
1433
		$sql.= " AND ctc.element = 'project_task'";
1434
	}
1435
	if ($statut >= 0)
1436
	{
1437
		$sql.= " AND p.fk_statut = ".$statut;
1438
	}
1439
	if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE))
1440
	{
1441
		$project_year_filter = GETPOST("project_year_filter");
1442
		//Check if empty or invalid year. Wildcard ignores the sql check
1443
		if ($project_year_filter != "*")
1444
		{
1445
			if (empty($project_year_filter) || !ctype_digit($project_year_filter))
1446
			{
1447
				$project_year_filter = date("Y");
1448
			}
1449
			$sql.= " AND (p.dateo IS NULL OR p.dateo <= ".$db->idate(dol_get_last_day($project_year_filter,12,false)).")";
1450
			$sql.= " AND (p.datee IS NULL OR p.datee >= ".$db->idate(dol_get_first_day($project_year_filter,1,false)).")";
1451
		}
1452
	}
1453
1454
	// Get id of project we must show tasks
1455
	$arrayidofprojects=array();
1456
	$sql1 = "SELECT p.rowid as projectid";
1457
	$sql1.= $sql;
1458
	$resql = $db->query($sql1);
1459
	if ($resql)
1460
	{
1461
		$i=0;
1462
		$num = $db->num_rows($resql);
1463
		while ($i < $num)
1464
		{
1465
			$objp = $db->fetch_object($resql);
1466
			$arrayidofprojects[$objp->projectid]=$objp->projectid;
1467
			$i++;
1468
		}
1469
	}
1470
	else dol_print_error($db);
1471
	if (empty($arrayidofprojects)) $arrayidofprojects[0]=-1;
1472
1473
	// Get list of project with calculation on tasks
1474
	$sql2 = "SELECT p.rowid as projectid, p.ref, p.title, p.fk_soc, s.nom as socname, p.fk_user_creat, p.public, p.fk_statut as status, p.fk_opp_status as opp_status, p.opp_amount,";
1475
	$sql2.= " p.dateo, p.datee,";
1476
	$sql2.= " COUNT(t.rowid) as nb, SUM(t.planned_workload) as planned_workload, SUM(t.planned_workload * t.progress / 100) as declared_progess_workload";
1477
	$sql2.= " FROM ".MAIN_DB_PREFIX."projet as p";
1478
	$sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc";
1479
	$sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t ON p.rowid = t.fk_projet";
1480
	$sql2.= " WHERE p.rowid IN (".join(',',$arrayidofprojects).")";
1481
	$sql2.= " GROUP BY p.rowid, p.ref, p.title, p.fk_soc, s.nom, p.fk_user_creat, p.public, p.fk_statut, p.fk_opp_status, p.opp_amount, p.dateo, p.datee";
1482
	$sql2.= " ORDER BY p.title, p.ref";
1483
1484
	$resql = $db->query($sql2);
1485
	if ($resql)
1486
	{
1487
	   $total_task = 0;
1488
		$total_opp_amount = 0;
1489
		$ponderated_opp_amount = 0;
1490
1491
		$num = $db->num_rows($resql);
1492
		$i = 0;
1493
1494
		print '<tr class="liste_titre">';
1495
		print_liste_field_titre($title.' <span class="badge">'.$num.'</span>',$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder);
1496
		print_liste_field_titre("ThirdParty",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder);
1497
		if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
1498
		{
1499
			print_liste_field_titre("OpportunityAmount","","","","",'align="right"',$sortfield,$sortorder);
1500
			print_liste_field_titre("OpportunityStatus","","","","",'align="right"',$sortfield,$sortorder);
1501
		}
1502
		if (empty($conf->global->PROJECT_HIDE_TASKS))
1503
		{
1504
			print_liste_field_titre("Tasks","","","","",'align="right"',$sortfield,$sortorder);
1505
			if (! in_array('plannedworkload', $hiddenfields))  print_liste_field_titre("PlannedWorkload","","","","",'align="right"',$sortfield,$sortorder);
1506
			if (! in_array('declaredprogress', $hiddenfields)) print_liste_field_titre("ProgressDeclared","","","","",'align="right"',$sortfield,$sortorder);
1507
		}
1508
		print_liste_field_titre("Status","","","","",'align="right"',$sortfield,$sortorder);
1509
		print "</tr>\n";
1510
1511
		while ($i < $num)
1512
		{
1513
			$objp = $db->fetch_object($resql);
1514
1515
			$projectstatic->id = $objp->projectid;
1516
			$projectstatic->user_author_id = $objp->fk_user_creat;
1517
			$projectstatic->public = $objp->public;
1518
1519
			// Check is user has read permission on project
1520
			$userAccess = $projectstatic->restrictedProjectArea($user);
1521
			if ($userAccess >= 0)
1522
			{
1523
				$projectstatic->ref=$objp->ref;
1524
				$projectstatic->statut = $objp->status;
1525
				$projectstatic->title = $objp->title;
1526
				$projectstatic->datee = $db->jdate($objp->datee);
1527
				$projectstatic->dateo = $db->jdate($objp->dateo);
1528
1529
1530
				print '<tr class="oddeven">';
1531
				print '<td>';
1532
				print $projectstatic->getNomUrl(1);
1533
				if (! in_array('projectlabel', $hiddenfields)) print '<br>'.dol_trunc($objp->title,24);
1534
				print '</td>';
1535
				print '<td>';
1536
				if ($objp->fk_soc > 0)
1537
				{
1538
					$thirdpartystatic->id=$objp->fk_soc;
1539
					$thirdpartystatic->ref=$objp->socname;
1540
					$thirdpartystatic->name=$objp->socname;
1541
					print $thirdpartystatic->getNomUrl(1);
1542
				}
1543
				print '</td>';
1544
				if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
1545
				{
1546
					print '<td align="right">';
1547
					if ($objp->opp_amount) print price($objp->opp_amount, 0, '', 1, -1, -1, $conf->currency);
1548
					print '</td>';
1549
					print '<td align="right">';
1550
					$code = dol_getIdFromCode($db, $objp->opp_status, 'c_lead_status', 'rowid', 'code');
1551
					if ($code) print $langs->trans("OppStatus".$code);
1552
					print '</td>';
1553
				}
1554
				if (empty($conf->global->PROJECT_HIDE_TASKS))
1555
				{
1556
					print '<td align="right">'.$objp->nb.'</td>';
1557
1558
					$plannedworkload=$objp->planned_workload;
1559
					$total_plannedworkload+=$plannedworkload;
0 ignored issues
show
Bug introduced by
The variable $total_plannedworkload 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...
1560
					if (! in_array('plannedworkload', $hiddenfields))
1561
					{
1562
						print '<td align="right">'.($plannedworkload?convertSecondToTime($plannedworkload):'').'</td>';
1563
					}
1564
					if (! in_array('declaredprogress', $hiddenfields))
1565
					{
1566
						$declaredprogressworkload=$objp->declared_progess_workload;
1567
						$total_declaredprogressworkload+=$declaredprogressworkload;
0 ignored issues
show
Bug introduced by
The variable $total_declaredprogressworkload 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...
1568
						print '<td align="right">';
1569
						//print $objp->planned_workload.'-'.$objp->declared_progess_workload."<br>";
1570
						print ($plannedworkload?round(100*$declaredprogressworkload/$plannedworkload,0).'%':'');
1571
						print '</td>';
1572
					}
1573
				}
1574
1575
				print '<td align="right">'.$projectstatic->getLibStatut(3).'</td>';
1576
				print "</tr>\n";
1577
1578
				$total_task = $total_task + $objp->nb;
1579
				$total_opp_amount = $total_opp_amount + $objp->opp_amount;
1580
				$ponderated_opp_amount = $ponderated_opp_amount + price2num($listofoppstatus[$objp->opp_status] * $objp->opp_amount / 100);
1581
			}
1582
1583
			$i++;
1584
		}
1585
1586
		print '<tr class="liste_total">';
1587
		print '<td colspan="2">'.$langs->trans("Total")."</td>";
1588
		if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
1589
		{
1590
			print '<td class="liste_total" align="right">'.price($total_opp_amount, 0, '', 1, -1, -1, $conf->currency).'</td>';
1591
			print '<td class="liste_total" align="right">'.$form->textwithpicto(price($ponderated_opp_amount, 0, '', 1, -1, -1, $conf->currency), $langs->trans("OpportunityPonderatedAmountDesc"), 1).'</td>';
1592
		}
1593
		if (empty($conf->global->PROJECT_HIDE_TASKS))
1594
		{
1595
			print '<td class="liste_total" align="right">'.$total_task.'</td>';
1596
			if (! in_array('plannedworkload', $hiddenfields))  print '<td class="liste_total" align="right">'.($total_plannedworkload?convertSecondToTime($total_plannedworkload):'').'</td>';
1597
			if (! in_array('declaredprogress', $hiddenfields)) print '<td class="liste_total" align="right">'.($total_plannedworkload?round(100*$total_declaredprogressworkload/$total_plannedworkload,0).'%':'').'</td>';
1598
		}
1599
		print '<td class="liste_total"></td>';
1600
		print '</tr>';
1601
1602
		$db->free($resql);
1603
	}
1604
	else
1605
	{
1606
		dol_print_error($db);
1607
	}
1608
1609
	print "</table>";
1610
	print '</div>';
1611
1612
	if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE))
1613
	{
1614
		//Add the year filter input
1615
		print '<form method="get" action="'.$_SERVER["PHP_SELF"].'">';
1616
		print '<table width="100%">';
1617
		print '<tr>';
1618
		print '<td>'.$langs->trans("Year").'</td>';
1619
		print '<td style="text-align:right"><input type="text" size="4" class="flat" name="project_year_filter" value="'.$project_year_filter.'"/>';
1620
		print "</tr>\n";
1621
		print '</table></form>';
1622
	}
1623
}
1624
1625