Browse Source

code syntax project

Frédéric FRANCE 4 years ago
parent
commit
a82df7e6ea
39 changed files with 4544 additions and 3730 deletions
  1. 148 133
      htdocs/projet/activity/index.php
  2. 147 146
      htdocs/projet/activity/perday.php
  3. 109 121
      htdocs/projet/activity/permonth.php
  4. 180 183
      htdocs/projet/activity/perweek.php
  5. 152 200
      htdocs/projet/admin/project.php
  6. 9 8
      htdocs/projet/admin/project_extrafields.php
  7. 9 8
      htdocs/projet/admin/project_task_extrafields.php
  8. 12 5
      htdocs/projet/admin/website.php
  9. 24 8
      htdocs/projet/ajax/projects.php
  10. 217 238
      htdocs/projet/card.php
  11. 135 129
      htdocs/projet/class/api_projects.class.php
  12. 171 164
      htdocs/projet/class/api_tasks.class.php
  13. 236 248
      htdocs/projet/class/project.class.php
  14. 53 41
      htdocs/projet/class/projectstats.class.php
  15. 287 248
      htdocs/projet/class/task.class.php
  16. 22 12
      htdocs/projet/class/taskstats.class.php
  17. 18 8
      htdocs/projet/comment.php
  18. 61 51
      htdocs/projet/contact.php
  19. 25 15
      htdocs/projet/document.php
  20. 389 248
      htdocs/projet/element.php
  21. 51 39
      htdocs/projet/event.php
  22. 17 22
      htdocs/projet/ganttchart.inc.php
  23. 53 51
      htdocs/projet/ganttview.php
  24. 34 29
      htdocs/projet/graph_opportunities.inc.php
  25. 68 48
      htdocs/projet/index.php
  26. 36 26
      htdocs/projet/info.php
  27. 37 21
      htdocs/projet/jsgantt_language.js.php
  28. 508 298
      htdocs/projet/list.php
  29. 9 8
      htdocs/projet/note.php
  30. 41 39
      htdocs/projet/stats/index.php
  31. 190 126
      htdocs/projet/tasks.php
  32. 50 44
      htdocs/projet/tasks/comment.php
  33. 83 83
      htdocs/projet/tasks/contact.php
  34. 50 42
      htdocs/projet/tasks/document.php
  35. 479 254
      htdocs/projet/tasks/list.php
  36. 40 37
      htdocs/projet/tasks/note.php
  37. 31 19
      htdocs/projet/tasks/stats/index.php
  38. 100 102
      htdocs/projet/tasks/task.php
  39. 263 228
      htdocs/projet/tasks/time.php

+ 148 - 133
htdocs/projet/activity/index.php

@@ -32,13 +32,19 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
 
 $search_project_user = GETPOST('search_project_user', 'int');
 $mine = GETPOST('mode', 'aZ09') == 'mine' ? 1 : 0;
-if ($search_project_user == $user->id) $mine = 1;
+if ($search_project_user == $user->id) {
+	$mine = 1;
+}
 
 // Security check
 $socid = 0;
-if ($user->socid > 0) $socid = $user->socid;
+if ($user->socid > 0) {
+	$socid = $user->socid;
+}
 //$result = restrictedArea($user, 'projet', $projectid);
-if (!$user->rights->projet->lire) accessforbidden();
+if (!$user->rights->projet->lire) {
+	accessforbidden();
+}
 
 $hookmanager = new HookManager($db);
 
@@ -73,8 +79,11 @@ llxHeader("", $title);
 
 // Title for combo list see all projects
 $titleall = $langs->trans("AllAllowedProjects");
-if (!empty($user->rights->projet->all->lire) && !$socid) $titleall = $langs->trans("AllProjects");
-else $titleall = $langs->trans("AllAllowedProjects").'<br><br>';
+if (!empty($user->rights->projet->all->lire) && !$socid) {
+	$titleall = $langs->trans("AllProjects");
+} else {
+	$titleall = $langs->trans("AllAllowedProjects").'<br><br>';
+}
 
 
 $morehtml = '';
@@ -85,10 +94,14 @@ $morehtml .= '<option name="mine" value="'.$user->id.'"'.(($search_project_user
 $morehtml .= '</SELECT>';
 $morehtml .= '<input type="submit" class="button" name="refresh" value="'.$langs->trans("Refresh").'">';
 
-if ($mine) $tooltiphelp = $langs->trans("MyTasksDesc");
-else {
-	if ($user->rights->projet->all->lire && !$socid) $tooltiphelp = $langs->trans("TasksDesc");
-	else $tooltiphelp = $langs->trans("TasksPublicDesc");
+if ($mine) {
+	$tooltiphelp = $langs->trans("MyTasksDesc");
+} else {
+	if ($user->rights->projet->all->lire && !$socid) {
+		$tooltiphelp = $langs->trans("TasksDesc");
+	} else {
+		$tooltiphelp = $langs->trans("TasksPublicDesc");
+	}
 }
 
 print_barre_liste($form->textwithpicto($title, $tooltiphelp), 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, -1, 'projecttask', 0, $morehtml);
@@ -96,27 +109,27 @@ print_barre_liste($form->textwithpicto($title, $tooltiphelp), 0, $_SERVER["PHP_S
 print '<div class="fichecenter"><div class="fichethirdleft">';
 
 
-if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS))     // This is useless due to the global search combo
-{
+if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) {     // This is useless due to the global search combo
 	// Search project
-	if (!empty($conf->projet->enabled) && $user->rights->projet->lire)
-	{
+	if (!empty($conf->projet->enabled) && $user->rights->projet->lire) {
 		$listofsearchfields['search_task'] = array('text'=>'Task');
 	}
 
-	if (count($listofsearchfields))
-	{
+	if (count($listofsearchfields)) {
 		print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">';
 		print '<input type="hidden" name="token" value="'.newToken().'">';
 		print '<div class="div-table-responsive-no-min">';
 		print '<table class="noborder nohover centpercent">';
 		$i = 0;
-		foreach ($listofsearchfields as $key => $value)
-		{
-			if ($i == 0) print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>';
+		foreach ($listofsearchfields as $key => $value) {
+			if ($i == 0) {
+				print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>';
+			}
 			print '<tr '.$bc[false].'>';
 			print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>';
-			if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>';
+			if ($i == 0) {
+				print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>';
+			}
 			print '</tr>';
 			$i++;
 		}
@@ -149,12 +162,10 @@ $sql .= " AND p.rowid in (".$db->sanitize($projectsListId).")";
 $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public";
 
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$total = 0;
 
-	while ($row = $db->fetch_object($resql))
-	{
+	while ($row = $db->fetch_object($resql)) {
 		print '<tr class="oddeven">';
 		print '<td>';
 		$projectstatic->id = $row->rowid;
@@ -204,12 +215,10 @@ $sql .= " AND p.rowid in (".$db->sanitize($projectsListId).")";
 $sql .= " GROUP BY p.rowid, p.ref, p.title, p.public";
 
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$total = 0;
 
-	while ($row = $db->fetch_object($resql))
-	{
+	while ($row = $db->fetch_object($resql)) {
 		print '<tr class="oddeven">';
 		print '<td>';
 		$projectstatic->id = $row->rowid;
@@ -239,66 +248,65 @@ print '</div>';
 /*
 if ($db->type != 'pgsql')
 {
-    print '<br>';
-
-    // Affichage de la liste des projets de la semaine
-    print '<div class="div-table-responsive-no-min">';
-    print '<table class="noborder centpercent">';
-    print '<tr class="liste_titre">';
-    print '<td>'.$langs->trans("ActivityOnProjectThisWeek").'</td>';
-    print '<td class="right">'.$langs->trans("Time").'</td>';
-    print "</tr>\n";
-
-    $sql = "SELECT p.rowid, p.ref, p.title, p.public, SUM(tt.task_duration) as nb";
-    $sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
-    $sql.= " , ".MAIN_DB_PREFIX."projet_task as t";
-    $sql.= " , ".MAIN_DB_PREFIX."projet_task_time as tt";
-    $sql.= " WHERE t.fk_projet = p.rowid";
-    $sql.= " AND p.entity = ".$conf->entity;
-    $sql.= " AND tt.fk_task = t.rowid";
-    $sql.= " AND tt.fk_user = ".$user->id;
-    $sql.= " AND task_date >= '".$db->idate(dol_get_first_day($year, $month)).'" AND ...";
-    $sql.= " AND p.rowid in (".$db->sanitize($projectsListId).")";
-    $sql.= " GROUP BY p.rowid, p.ref, p.title";
-
-    $resql = $db->query($sql);
-    if ( $resql )
-    {
-    	$total = 0;
-
-    	while ($row = $db->fetch_object($resql))
-    	{
-    		print '<tr class="oddeven">';
-    		print '<td>';
-    		$projectstatic->id=$row->rowid;
-    		$projectstatic->ref=$row->ref;
-    		$projectstatic->title=$row->title;
-    		$projectstatic->public=$row->public;
-    		print $projectstatic->getNomUrl(1, '', 1);
-    		print '</td>';
-    		print '<td class="right">'.convertSecondToTime($row->nb, 'allhourmin').'</td>';
-    		print "</tr>\n";
-    		$total += $row->nb;
-    	}
-
-    	$db->free($resql);
-    }
-    else
-    {
-    	dol_print_error($db);
-    }
-    print '<tr class="liste_total">';
-    print '<td>'.$langs->trans('Total').'</td>';
-    print '<td class="right">'.convertSecondToTime($total, 'allhourmin').'</td>';
-    print "</tr>\n";
-    print "</table></div><br>";
+	print '<br>';
+
+	// Affichage de la liste des projets de la semaine
+	print '<div class="div-table-responsive-no-min">';
+	print '<table class="noborder centpercent">';
+	print '<tr class="liste_titre">';
+	print '<td>'.$langs->trans("ActivityOnProjectThisWeek").'</td>';
+	print '<td class="right">'.$langs->trans("Time").'</td>';
+	print "</tr>\n";
+
+	$sql = "SELECT p.rowid, p.ref, p.title, p.public, SUM(tt.task_duration) as nb";
+	$sql.= " FROM ".MAIN_DB_PREFIX."projet as p";
+	$sql.= " , ".MAIN_DB_PREFIX."projet_task as t";
+	$sql.= " , ".MAIN_DB_PREFIX."projet_task_time as tt";
+	$sql.= " WHERE t.fk_projet = p.rowid";
+	$sql.= " AND p.entity = ".$conf->entity;
+	$sql.= " AND tt.fk_task = t.rowid";
+	$sql.= " AND tt.fk_user = ".$user->id;
+	$sql.= " AND task_date >= '".$db->idate(dol_get_first_day($year, $month)).'" AND ...";
+	$sql.= " AND p.rowid in (".$db->sanitize($projectsListId).")";
+	$sql.= " GROUP BY p.rowid, p.ref, p.title";
+
+	$resql = $db->query($sql);
+	if ( $resql )
+	{
+		$total = 0;
+
+		while ($row = $db->fetch_object($resql))
+		{
+			print '<tr class="oddeven">';
+			print '<td>';
+			$projectstatic->id=$row->rowid;
+			$projectstatic->ref=$row->ref;
+			$projectstatic->title=$row->title;
+			$projectstatic->public=$row->public;
+			print $projectstatic->getNomUrl(1, '', 1);
+			print '</td>';
+			print '<td class="right">'.convertSecondToTime($row->nb, 'allhourmin').'</td>';
+			print "</tr>\n";
+			$total += $row->nb;
+		}
+
+		$db->free($resql);
+	}
+	else
+	{
+		dol_print_error($db);
+	}
+	print '<tr class="liste_total">';
+	print '<td>'.$langs->trans('Total').'</td>';
+	print '<td class="right">'.convertSecondToTime($total, 'allhourmin').'</td>';
+	print "</tr>\n";
+	print "</table></div><br>";
 
 }
 */
 
 /* Affichage de la liste des projets du mois */
-if (!empty($conf->global->PROJECT_TASK_TIME_MONTH))
-{
+if (!empty($conf->global->PROJECT_TASK_TIME_MONTH)) {
 	print '<div class="div-table-responsive-no-min">';
 	print '<table class="noborder centpercent">';
 	print '<tr class="liste_titre">';
@@ -319,10 +327,8 @@ if (!empty($conf->global->PROJECT_TASK_TIME_MONTH))
 	$sql .= " GROUP BY p.rowid, p.ref, p.title, p.public";
 
 	$resql = $db->query($sql);
-	if ($resql)
-	{
-		while ($row = $db->fetch_object($resql))
-		{
+	if ($resql) {
+		while ($row = $db->fetch_object($resql)) {
 			print '<tr class="oddeven">';
 			print '<td>';
 			$projectstatic->id = $row->rowid;
@@ -346,8 +352,7 @@ if (!empty($conf->global->PROJECT_TASK_TIME_MONTH))
 }
 
 /* Affichage de la liste des projets de l'annee */
-if (!empty($conf->global->PROJECT_TASK_TIME_YEAR))
-{
+if (!empty($conf->global->PROJECT_TASK_TIME_YEAR)) {
 	print '<div class="div-table-responsive-no-min">';
 	print '<br><table class="noborder centpercent">';
 	print '<tr class="liste_titre">';
@@ -368,10 +373,8 @@ if (!empty($conf->global->PROJECT_TASK_TIME_YEAR))
 	$sql .= " GROUP BY p.rowid, p.ref, p.title, p.public";
 
 	$resql = $db->query($sql);
-	if ($resql)
-	{
-		while ($row = $db->fetch_object($resql))
-		{
+	if ($resql) {
+		while ($row = $db->fetch_object($resql)) {
 			print '<tr class="oddeven">';
 			print '<td>';
 			$projectstatic->id = $row->rowid;
@@ -395,36 +398,39 @@ if (!empty($conf->global->PROJECT_TASK_TIME_YEAR))
 	print '</div>';
 }
 
-if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SHOW_TASK_LIST_ON_PROJECT_AREA))
-{
+if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SHOW_TASK_LIST_ON_PROJECT_AREA)) {
 	// Get id of types of contacts for projects (This list never contains a lot of elements)
 	$listofprojectcontacttype = array();
 	$sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc";
 	$sql .= " WHERE ctc.element = '".$db->escape($projectstatic->element)."'";
 	$sql .= " AND ctc.source = 'internal'";
 	$resql = $db->query($sql);
-	if ($resql)
-	{
-		while ($obj = $db->fetch_object($resql))
-		{
+	if ($resql) {
+		while ($obj = $db->fetch_object($resql)) {
 			$listofprojectcontacttype[$obj->rowid] = $obj->code;
 		}
-	} else dol_print_error($db);
-	if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0] = '0'; // To avoid sql syntax error if not found
+	} else {
+		dol_print_error($db);
+	}
+	if (count($listofprojectcontacttype) == 0) {
+		$listofprojectcontacttype[0] = '0'; // To avoid sql syntax error if not found
+	}
 	// Get id of types of contacts for tasks (This list never contains a lot of elements)
 	$listoftaskcontacttype = array();
 	$sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc";
 	$sql .= " WHERE ctc.element = '".$db->escape($taskstatic->element)."'";
 	$sql .= " AND ctc.source = 'internal'";
 	$resql = $db->query($sql);
-	if ($resql)
-	{
-		while ($obj = $db->fetch_object($resql))
-		{
+	if ($resql) {
+		while ($obj = $db->fetch_object($resql)) {
 			$listoftaskcontacttype[$obj->rowid] = $obj->code;
 		}
-	} else dol_print_error($db);
-	if (count($listoftaskcontacttype) == 0) $listoftaskcontacttype[0] = '0'; // To avoid sql syntax error if not found
+	} else {
+		dol_print_error($db);
+	}
+	if (count($listoftaskcontacttype) == 0) {
+		$listoftaskcontacttype[0] = '0'; // To avoid sql syntax error if not found
+	}
 
 
 	// Tasks for all resources of all opened projects and time spent for each task/resource
@@ -440,17 +446,19 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH
 	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t on t.fk_projet = p.rowid";
 	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_time as tasktime on tasktime.fk_task = t.rowid";
 	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on tasktime.fk_user = u.rowid";
-	if ($mine)
-	{
+	if ($mine) {
 		$sql .= ", ".MAIN_DB_PREFIX."element_contact as ect";
 	}
 	$sql .= " WHERE p.entity IN (".getEntity('project').")";
-	if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$db->sanitize($projectsListId).")"; // project i have permission on
-	if ($mine)     // this may duplicate record if we are contact twice
-	{
+	if ($mine || empty($user->rights->projet->all->lire)) {
+		$sql .= " AND p.rowid IN (".$db->sanitize($projectsListId).")"; // project i have permission on
+	}
+	if ($mine) {     // this may duplicate record if we are contact twice
 		$sql .= " AND ect.fk_c_type_contact IN (".join(',', array_keys($listoftaskcontacttype)).") AND ect.element_id = t.rowid AND ect.fk_socpeople = ".$user->id;
 	}
-	if ($socid)	$sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
+	if ($socid) {
+		$sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
+	}
 	$sql .= " AND p.fk_statut=1";
 	$sql .= " GROUP BY p.ref, p.title, p.rowid, p.fk_statut, p.fk_opp_status, p.public, t.label, t.rowid, t.planned_workload, t.duration_effective, t.progress, t.dateo, t.datee";
 	$sql .= " ORDER BY t.dateo desc, t.rowid desc, t.datee";
@@ -458,8 +466,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH
 
 	dol_syslog('projet:index.php: affectationpercent', LOG_DEBUG);
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$num = $db->num_rows($resql);
 		$i = 0;
 
@@ -470,7 +477,9 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH
 		print '<tr class="liste_titre">';
 		//print '<th>'.$langs->trans('TaskRessourceLinks').'</th>';
 		print '<th>'.$langs->trans('OpenedProjects').'</th>';
-		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) print '<th>'.$langs->trans('OpportunityStatus').'</th>';
+		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
+			print '<th>'.$langs->trans('OpportunityStatus').'</th>';
+		}
 		print '<th>'.$langs->trans('Task').'</th>';
 		print '<th class="center">'.$langs->trans('DateStart').'</th>';
 		print '<th class="center">'.$langs->trans('DateEnd').'</th>';
@@ -480,8 +489,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH
 		print '<th class="right">'.$langs->trans("ProgressDeclared").'</td>';
 		print '</tr>';
 
-		while ($i < $num && $i < $max)
-		{
+		while ($i < $num && $i < $max) {
 			$obj = $db->fetch_object($resql);
 
 			$projectstatic->id = $obj->projectid;
@@ -499,37 +507,44 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH
 			$taskstatic->datee = $db->jdate($obj->datee);
 
 			$username = '';
-			if ($obj->userid && $userstatic->id != $obj->userid)	// We have a user and it is not last loaded user
-			{
+			if ($obj->userid && $userstatic->id != $obj->userid) {	// We have a user and it is not last loaded user
 				$result = $userstatic->fetch($obj->userid);
-				if (!$result) $userstatic->id = 0;
+				if (!$result) {
+					$userstatic->id = 0;
+				}
+			}
+			if ($userstatic->id) {
+				$username = $userstatic->getNomUrl(0, 0);
 			}
-			if ($userstatic->id) $username = $userstatic->getNomUrl(0, 0);
 
 			print '<tr class="oddeven">';
 			//print '<td>'.$username.'</td>';
 			print '<td>';
 			print $projectstatic->getNomUrl(1, '', 0, '', '<br>');
 			print '</td>';
-			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-			{
+			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 				print '<td>';
 				$code = dol_getIdFromCode($db, $obj->opp_status, 'c_lead_status', 'rowid', 'code');
-				if ($code) print $langs->trans("OppStatus".$code);
+				if ($code) {
+					print $langs->trans("OppStatus".$code);
+				}
 				print '</td>';
 			}
 			print '<td>';
-			if (!empty($obj->taskid))
-			{
+			if (!empty($obj->taskid)) {
 				$tasktmp->id = $obj->taskid;
 				$tasktmp->ref = $obj->ref;
 				$tasktmp->label = $obj->label;
 				print $tasktmp->getNomUrl(1, 'withproject', 'task', 1, '<br>');
-			} else print $langs->trans("NoTasks");
+			} else {
+				print $langs->trans("NoTasks");
+			}
 			print '</td>';
 			print '<td class="center">'.dol_print_date($db->jdate($obj->dateo), 'day').'</td>';
 			print '<td class="center">'.dol_print_date($db->jdate($obj->datee), 'day');
-			if ($taskstatic->hasDelay()) print img_warning($langs->trans("Late"));
+			if ($taskstatic->hasDelay()) {
+				print img_warning($langs->trans("Late"));
+			}
 			print '</td>';
 			print '<td class="right"><a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$obj->taskid.'&withproject=1">';
 			print convertSecondToTime($obj->planned_workload, 'allhourmin');
@@ -538,8 +553,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH
 			print convertSecondToTime($obj->timespent, 'allhourmin');
 			print '</a></td>';
 			print '<td class="right">';
-			if (!empty($obj->taskid))
-			{
+			if (!empty($obj->taskid)) {
 				if (empty($obj->planned_workload) > 0) {
 					$percentcompletion = $langs->trans("WorkloadNotDefined");
 				} else {
@@ -556,10 +570,11 @@ if (empty($conf->global->PROJECT_HIDE_TASKS) && !empty($conf->global->PROJECT_SH
 			$i++;
 		}
 
-		if ($num > $max)
-		{
+		if ($num > $max) {
 			$colspan = 6;
-			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $colspan++;
+			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
+				$colspan++;
+			}
 			print '<tr><td colspan="'.$colspan.'">'.$langs->trans("WarningTooManyDataPleaseUseMoreFilters").'</td></tr>';
 		}
 

+ 147 - 146
htdocs/projet/activity/perday.php

@@ -46,7 +46,9 @@ $taskid = GETPOST('taskid', 'int');
 $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'perdaycard';
 
 $mine = 0;
-if ($mode == 'mine') $mine = 1;
+if ($mode == 'mine') {
+	$mine = 1;
+}
 
 $projectid = isset($_GET["id"]) ? GETPOST("id", "int", 1) : GETPOST("projectid", "int");
 
@@ -84,16 +86,17 @@ $dayofday = GETPOST('addtimeday');
 $yearofday = GETPOST('addtimeyear');
 
 $daytoparse = $now;
-if ($yearofday && $monthofday && $dayofday) $daytoparse = dol_mktime(0, 0, 0, $monthofday, $dayofday, $yearofday); // xxxofday is value of day after submit action 'addtime'
-elseif ($year && $month && $day) $daytoparse = dol_mktime(0, 0, 0, $month, $day, $year); // this are value submited after submit of action 'submitdateselect'
+if ($yearofday && $monthofday && $dayofday) {
+	$daytoparse = dol_mktime(0, 0, 0, $monthofday, $dayofday, $yearofday); // xxxofday is value of day after submit action 'addtime'
+} elseif ($year && $month && $day) {
+	$daytoparse = dol_mktime(0, 0, 0, $month, $day, $year); // this are value submited after submit of action 'submitdateselect'
+}
 
 
-if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id)
-{
+if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) {
 	$usertoprocess = $user;
 	$search_usertoprocessid = $usertoprocess->id;
-} elseif ($search_usertoprocessid > 0)
-{
+} elseif ($search_usertoprocessid > 0) {
 	$usertoprocess = new User($db);
 	$usertoprocess->fetch($search_usertoprocessid);
 	$search_usertoprocessid = $usertoprocess->id;
@@ -124,12 +127,11 @@ $arrayfields['t.progress'] = array('label'=>'ProgressDeclared', 'checked'=>1, 'e
  );
  */
 // Extra fields
-if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
-{
-	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
-	{
-		if (!empty($extrafields->attributes[$object->table_element]['list'][$key]))
+if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
+	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
+		if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
 			$arrayfields["efpt.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs((int) $extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key]));
+		}
 	}
 }
 $arrayfields = dol_sort_array($arrayfields, 'position');
@@ -145,10 +147,11 @@ $search_array_options_task = $extrafields->getOptionalsFromPost($object->table_e
 
 $parameters = array('id' => $id, 'taskid' => $taskid, 'projectid' => $projectid);
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 // Purge criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 	$action = '';
 	$search_categ = '';
 	$search_usertoprocessid = $user->id;
@@ -164,15 +167,12 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
 	// We redefine $usertoprocess
 	$usertoprocess = $user;
 }
-if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha'))
-{
+if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) {
 	$action = '';
 }
 
-if (GETPOST('submitdateselect'))
-{
-	if (GETPOST('remonth', 'int') && GETPOST('reday', 'int') && GETPOST('reyear', 'int'))
-	{
+if (GETPOST('submitdateselect')) {
+	if (GETPOST('remonth', 'int') && GETPOST('reday', 'int') && GETPOST('reyear', 'int')) {
 		$daytoparse = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
 	}
 
@@ -181,46 +181,40 @@ if (GETPOST('submitdateselect'))
 
 include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
-if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') && GETPOST('formfilteraction') != 'listafterchangingselectedfields')
-{
+if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') && GETPOST('formfilteraction') != 'listafterchangingselectedfields') {
 	$action = 'assigntask';
 
-	if ($taskid > 0)
-	{
+	if ($taskid > 0) {
 		$result = $object->fetch($taskid, $ref);
-		if ($result < 0) $error++;
+		if ($result < 0) {
+			$error++;
+		}
 	} else {
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors');
 		$error++;
 	}
-	if (!GETPOST('type'))
-	{
+	if (!GETPOST('type')) {
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors');
 		$error++;
 	}
-	if (!$error)
-	{
+	if (!$error) {
 		$idfortaskuser = $usertoprocess->id;
 		$result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal');
 
-		if ($result >= 0 || $result == -2)	// Contact add ok or already contact of task
-		{
+		if ($result >= 0 || $result == -2) {	// Contact add ok or already contact of task
 			// Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project)
 			$sql = 'SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact';
 			$sql .= ' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'";
 			$resql = $db->query($sql);
-			if ($resql)
-			{
+			if ($resql) {
 				$obj = $db->fetch_object($resql);
-				if (!$obj)	// User is not already linked to project, so we will create link to first type
-				{
+				if (!$obj) {	// User is not already linked to project, so we will create link to first type
 					$project = new Project($db);
 					$project->fetch($object->fk_project);
 					// Get type
 					$listofprojcontact = $project->liste_type_contact('internal');
 
-					if (count($listofprojcontact))
-					{
+					if (count($listofprojcontact)) {
 						$typeforprojectcontact = reset(array_keys($listofprojcontact));
 						$result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal');
 					}
@@ -231,11 +225,9 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')
 		}
 	}
 
-	if ($result < 0)
-	{
+	if ($result < 0) {
 		$error++;
-		if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
-		{
+		if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
 			$langs->load("errors");
 			setEventMessages($langs->trans("ErrorTaskAlreadyAssigned"), null, 'warnings');
 		} else {
@@ -243,8 +235,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')
 		}
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		setEventMessages("TaskAssignedToEnterTime", null);
 		$taskid = 0;
 	}
@@ -252,49 +243,47 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')
 	$action = '';
 }
 
-if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields')
-{
+if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields') {
 	$timespent_duration = array();
 
-	if (is_array($_POST))
-	{
-		foreach ($_POST as $key => $time)
-		{
-			if (intval($time) > 0)
-			{
+	if (is_array($_POST)) {
+		foreach ($_POST as $key => $time) {
+			if (intval($time) > 0) {
 				$matches = array();
 				// Hours or minutes of duration
-				if (preg_match("/([0-9]+)duration(hour|min)/", $key, $matches))
-				{
+				if (preg_match("/([0-9]+)duration(hour|min)/", $key, $matches)) {
 					$id = $matches[1];
-					if ($id > 0)
-					{
+					if ($id > 0) {
 						// We store HOURS in seconds
-						if ($matches[2] == 'hour') $timespent_duration[$id] += $time * 60 * 60;
+						if ($matches[2] == 'hour') {
+							$timespent_duration[$id] += $time * 60 * 60;
+						}
 
 						// We store MINUTES in seconds
-						if ($matches[2] == 'min') $timespent_duration[$id] += $time * 60;
+						if ($matches[2] == 'min') {
+							$timespent_duration[$id] += $time * 60;
+						}
 					}
 				}
 			}
 		}
 	}
 
-	if (count($timespent_duration) > 0)
-	{
-		foreach ($timespent_duration as $key => $val)
-		{
+	if (count($timespent_duration) > 0) {
+		foreach ($timespent_duration as $key => $val) {
 			$object->fetch($key);
 			$taskid = $object->id;
 
-			if (GETPOSTISSET($taskid.'progress')) $object->progress = GETPOST($taskid.'progress', 'int');
-			else unset($object->progress);
+			if (GETPOSTISSET($taskid.'progress')) {
+				$object->progress = GETPOST($taskid.'progress', 'int');
+			} else {
+				unset($object->progress);
+			}
 
 			$object->timespent_duration = $val;
 			$object->timespent_fk_user = $usertoprocess->id;
 			$object->timespent_note = GETPOST($key.'note');
-			if (GETPOST($key."hour", 'int') != '' && GETPOST($key."hour", 'int') >= 0)	// If hour was entered
-			{
+			if (GETPOST($key."hour", 'int') != '' && GETPOST($key."hour", 'int') >= 0) {	// If hour was entered
 				$object->timespent_datehour = dol_mktime(GETPOST($key."hour", 'int'), GETPOST($key."min", 'int'), 0, $monthofday, $dayofday, $yearofday);
 				$object->timespent_withhour = 1;
 			} else {
@@ -302,8 +291,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac
 			}
 			$object->timespent_date = $object->timespent_datehour;
 
-			if ($object->timespent_date > 0)
-			{
+			if ($object->timespent_date > 0) {
 				$result = $object->addTimeSpent($user);
 			} else {
 				setEventMessages("ErrorBadDate", null, 'errors');
@@ -311,16 +299,14 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac
 				break;
 			}
 
-			if ($result < 0)
-			{
+			if ($result < 0) {
 				setEventMessages($object->error, $object->errors, 'errors');
 				$error++;
 				break;
 			}
 		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
 
 			// Redirect to avoid submit twice on back
@@ -328,7 +314,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac
 			exit;
 		}
 	} else {
-   		setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors');
+		setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors');
 	}
 }
 
@@ -362,8 +348,7 @@ $title = $langs->trans("TimeSpent");
 
 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id) ? 2 : 0), 1); // Return all project i have permission on. I want my tasks and some of my task may be on a public projet that is not my project
 
-if ($id)
-{
+if ($id) {
 	$project->fetch($id);
 	$project->fetch_thirdparty();
 }
@@ -371,11 +356,21 @@ if ($id)
 $onlyopenedproject = 1; // or -1
 $morewherefilter = '';
 
-if ($search_project_ref) $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref);
-if ($search_task_ref)    $morewherefilter .= natural_search("t.ref", $search_task_ref);
-if ($search_task_label)  $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label);
-if ($search_thirdparty)  $morewherefilter .= natural_search("s.nom", $search_thirdparty);
-if ($search_declared_progress)  $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1);
+if ($search_project_ref) {
+	$morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref);
+}
+if ($search_task_ref) {
+	$morewherefilter .= natural_search("t.ref", $search_task_ref);
+}
+if ($search_task_label) {
+	$morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label);
+}
+if ($search_thirdparty) {
+	$morewherefilter .= natural_search("s.nom", $search_thirdparty);
+}
+if ($search_declared_progress) {
+	$morewherefilter .= natural_search("t.progress", $search_declared_progress, 1);
+}
 
 $sql = &$morewherefilter;
 
@@ -392,8 +387,7 @@ $extrafieldsobjectkey = 'projet_task';
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
 
 $tasksarray = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid ? $search_usertoprocessid : 0), 0, $extrafields); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later.
-if ($morewherefilter)	// Get all task without any filter, so we can show total of time spent for not visible tasks
-{
+if ($morewherefilter) {	// Get all task without any filter, so we can show total of time spent for not visible tasks
 	$tasksarraywithoutfilter = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all task of opened project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later.
 }
 $projectsrole = $taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id ? $project->id : 0), 0, $onlyopenedproject);
@@ -451,16 +445,18 @@ print dol_get_fiche_head($head, 'inputperday', $langs->trans('TimeSpent'), -1, $
 
 // Show description of content
 print '<div class="hideonsmartphone opacitymedium">';
-if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
-else {
-	if (empty($usertoprocess->id) || $usertoprocess->id < 0)
-	{
-		if ($user->rights->projet->all->lire && !$socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
-		else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+if ($mine || ($usertoprocess->id == $user->id)) {
+	print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+} else {
+	if (empty($usertoprocess->id) || $usertoprocess->id < 0) {
+		if ($user->rights->projet->all->lire && !$socid) {
+			print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+		} else {
+			print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+		}
 	}
 }
-if ($mine || ($usertoprocess->id == $user->id))
-{
+if ($mine || ($usertoprocess->id == $user->id)) {
 	print $langs->trans("OnlyYourTaskAreVisible").'<br>';
 } else {
 	print $langs->trans("AllTaskVisibleButEditIfYouAreAssigned").'<br>';
@@ -474,7 +470,9 @@ print '<div class="floatright right'.($conf->dol_optimize_smallscreen ? ' centpe
 
 print '<div class="colorbacktimesheet float valignmiddle">';
 $titleassigntask = $langs->transnoentities("AssignTaskToMe");
-if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs));
+if ($usertoprocess->id != $user->id) {
+	$titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs));
+}
 print '<div class="taskiddiv inline-block">';
 print img_picto('', 'projecttask');
 $formproject->selectTasks($socid ? $socid : -1, $taskid, 'taskid', 32, 0, '-- '.$langs->trans("ChooseANotYetAssignedTask").' --', 1, 0, 0, '', '', 'all', $usertoprocess);
@@ -503,12 +501,13 @@ $moreforfilter = '';
 $moreforfilter .= '<div class="divsearchfield">';
 $moreforfilter .= '<div class="inline-block hideonsmartphone"></div>';
 $includeonly = 'hierarchyme';
-if (empty($user->rights->user->user->lire)) $includeonly = array($user->id);
+if (empty($user->rights->user->user->lire)) {
+	$includeonly = array($user->id);
+}
 $moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('User'), 'user').$form->select_dolusers($search_usertoprocessid ? $search_usertoprocessid : $usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire ? 0 : 0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200 marginleftonly');
 $moreforfilter .= '</div>';
 
-if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
-{
+if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
 	$moreforfilter .= '<div class="divsearchfield">';
 	$moreforfilter .= '<div class="inline-block"></div>';
 	$moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('Project'), 'project').'<input type="text" size="4" name="search_project_ref" class="marginleftonly" value="'.dol_escape_htmltag($search_project_ref).'">';
@@ -520,8 +519,7 @@ if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
 	$moreforfilter .= '</div>';
 }
 
-if (!empty($moreforfilter))
-{
+if (!empty($moreforfilter)) {
 	print '<div class="liste_titre liste_titre_bydiv centpercent">';
 	print $moreforfilter;
 	$parameters = array();
@@ -535,19 +533,28 @@ $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfi
 
 // This must be after the $selectedfields
 $addcolspan = 0;
-if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++;
-if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++;
-foreach ($arrayfields as $key => $val)
-{
-	if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++;
+if (!empty($arrayfields['t.planned_workload']['checked'])) {
+	$addcolspan++;
+}
+if (!empty($arrayfields['t.progress']['checked'])) {
+	$addcolspan++;
+}
+foreach ($arrayfields as $key => $val) {
+	if ($val['checked'] && substr($key, 0, 5) == 'efpt.') {
+		$addcolspan++;
+	}
 }
 
 print '<div class="div-table-responsive">';
 print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'" id="tablelines3">'."\n";
 
 print '<tr class="liste_titre_filter">';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>';
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
+}
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>';
+}
 print '<td class="liste_titre"><input type="text" size="4" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>';
 // TASK fields
 $search_options_pattern = 'search_task_options_';
@@ -555,12 +562,10 @@ $extrafieldsobjectkey = 'projet_task';
 $extrafieldsobjectprefix = 'efpt.';
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
 print '<td class="liste_titre"></td>';
-if (!empty($arrayfields['t.planned_workload']['checked']))
-{
+if (!empty($arrayfields['t.planned_workload']['checked'])) {
 	print '<td class="liste_titre right"><input type="text" size="4" name="search_declared_progress" value="'.dol_escape_htmltag($search_declared_progress).'"></td>';
 }
-if (!empty($arrayfields['t.progress']['checked']))
-{
+if (!empty($arrayfields['t.progress']['checked'])) {
 	print '<td class="liste_titre"></td>';
 }
 print '<td class="liste_titre"></td>';
@@ -575,19 +580,21 @@ print '</td>';
 print "</tr>\n";
 
 print '<tr class="liste_titre">';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<th>'.$langs->trans("Project").'</th>';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<th>'.$langs->trans("ThirdParty").'</th>';
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<th>'.$langs->trans("Project").'</th>';
+}
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<th>'.$langs->trans("ThirdParty").'</th>';
+}
 print '<th>'.$langs->trans("Task").'</th>';
 // TASK fields
 $extrafieldsobjectkey = 'projet_task';
 $extrafieldsobjectprefix = 'efpt.';
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
-if (!empty($arrayfields['t.planned_workload']['checked']))
-{
+if (!empty($arrayfields['t.planned_workload']['checked'])) {
 	print '<th class="right leftborder plannedworkload maxwidth100">'.$langs->trans("PlannedWorkload").'</th>';
 }
-if (!empty($arrayfields['t.progress']['checked']))
-{
+if (!empty($arrayfields['t.progress']['checked'])) {
 	print '<th class="right maxwidth100">'.$langs->trans("ProgressDeclared").'</th>';
 }
 /*print '<td class="right maxwidth100">'.$langs->trans("TimeSpent").'</td>';
@@ -602,11 +609,9 @@ $restrictviewformytask = ((!isset($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSI
 
 // Get if user is available or not for each day
 $isavailable = array();
-if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS))
-{
+if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) {
 	$tmparray = explode('-', $conf->global->MAIN_DEFAULT_WORKING_DAYS);
-	if (count($tmparray) >= 2)
-	{
+	if (count($tmparray) >= 2) {
 		$numstartworkingday = $tmparray[0];
 		$numendworkingday = $tmparray[1];
 	}
@@ -617,24 +622,29 @@ $isavailablefordayanduser = $holiday->verifDateHolidayForTimestamp($usertoproces
 $isavailable[$daytoparse] = $isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day
 
 $test = num_public_holiday($daytoparse, $daytoparse + 86400, $mysoc->country_code);
-if ($test) $isavailable[$daytoparse] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday');
+if ($test) {
+	$isavailable[$daytoparse] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday');
+}
 
 $tmparray = dol_getdate($daytoparse, true); // detail of current day
 // For monday, must be 0 for monday if MAIN_START_WEEK = 1, must be 1 for monday if MAIN_START_WEEK = 0
 $idw = ($tmparray['wday'] - (empty($conf->global->MAIN_START_WEEK) ? 0 : 1));
 // numstartworkingday and numendworkingday are default start and end date of working days (1 means sunday if MAIN_START_WEEK is 0, 1 means monday if MAIN_START_WEEK is 1)
 $cssweekend = '';
-if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday))	// This is a day is not inside the setup of working days, so we use a week-end css.
-{
+if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) {	// This is a day is not inside the setup of working days, so we use a week-end css.
 	$cssweekend = 'weekend';
 }
 
 $tmpday = dol_time_plus_duree($daytoparse, $idw, 'd');
 
 $cssonholiday = '';
-if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon'])   $cssonholiday .= 'onholidayallday ';
-elseif (!$isavailable[$daytoparse]['morning'])   $cssonholiday .= 'onholidaymorning ';
-elseif (!$isavailable[$daytoparse]['afternoon']) $cssonholiday .= 'onholidayafternoon ';
+if (!$isavailable[$daytoparse]['morning'] && !$isavailable[$daytoparse]['afternoon']) {
+	$cssonholiday .= 'onholidayallday ';
+} elseif (!$isavailable[$daytoparse]['morning']) {
+	$cssonholiday .= 'onholidaymorning ';
+} elseif (!$isavailable[$daytoparse]['afternoon']) {
+	$cssonholiday .= 'onholidayafternoon ';
+}
 
 print '<th class="center'.($cssonholiday ? ' '.$cssonholiday : '').($cssweekend ? ' '.$cssweekend : '').'">'.$langs->trans("Duration").'</th>';
 print '<th class="center">'.$langs->trans("Note").'</th>';
@@ -645,8 +655,7 @@ print "</tr>\n";
 
 $colspan = 4 + (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : 2);
 
-if ($conf->use_javascript_ajax)
-{
+if ($conf->use_javascript_ajax) {
 	print '<tr class="liste_total">';
 	print '<td class="liste_total" colspan="'.($colspan - 1 + $addcolspan).'">';
 	print $langs->trans("Total");
@@ -663,8 +672,7 @@ if ($conf->use_javascript_ajax)
 }
 
 
-if (count($tasksarray) > 0)
-{
+if (count($tasksarray) > 0) {
 	//var_dump($tasksarray);				// contains only selected tasks
 	//var_dump($tasksarraywithoutfilter);	// contains all tasks (if there is a filter, not defined if no filter)
 	//var_dump($tasksrole);
@@ -678,21 +686,17 @@ if (count($tasksarray) > 0)
 
 	// Calculate total for all tasks
 	$listofdistinctprojectid = array(); // List of all distinct projects
-	if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter))
-	{
-		foreach ($tasksarraywithoutfilter as $tmptask)
-		{
+	if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) {
+		foreach ($tasksarraywithoutfilter as $tmptask) {
 			$listofdistinctprojectid[$tmptask->fk_project] = $tmptask->fk_project;
 		}
 	}
 	//var_dump($listofdistinctprojectid);
 	$totalforeachday = array();
-	foreach ($listofdistinctprojectid as $tmpprojectid)
-	{
+	foreach ($listofdistinctprojectid as $tmpprojectid) {
 		$projectstatic->id = $tmpprojectid;
 		$projectstatic->loadTimeSpent($daytoparse, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week
-		for ($idw = 0; $idw < 7; $idw++)
-		{
+		for ($idw = 0; $idw < 7; $idw++) {
 			$tmpday = dol_time_plus_duree($daytoparse, $idw, 'd');
 			$totalforeachday[$tmpday] += $projectstatic->weekWorkLoad[$tmpday];
 		}
@@ -701,18 +705,15 @@ if (count($tasksarray) > 0)
 
 	// Is there a diff between selected/filtered tasks and all tasks ?
 	$isdiff = 0;
-	if (count($totalforeachday))
-	{
+	if (count($totalforeachday)) {
 		$timeonothertasks = ($totalforeachday[$daytoparse] - $totalforvisibletasks[$daytoparse]);
-		if ($timeonothertasks)
-		{
+		if ($timeonothertasks) {
 			$isdiff = 1;
 		}
 	}
 
 	// There is a diff between total shown on screen and total spent by user, so we add a line with all other cumulated time of user
-	if ($isdiff)
-	{
+	if ($isdiff) {
 		print '<tr class="oddeven othertaskwithtime">';
 		print '<td colspan="'.($colspan - 1).'" class="opacitymedium">';
 		print $langs->trans("OtherFilteredTasks");
@@ -723,7 +724,9 @@ if (count($tasksarray) > 0)
 		//if ($timeonothertasks)
 		//{
 			print '<span class="timesheetalreadyrecorded" title="texttoreplace"><input type="text" class="center" size="2" disabled="" id="timespent[-1][0]" name="task[-1][0]" value="';
-			if ($timeonothertasks) print convertSecondToTime($timeonothertasks, 'allhourmin');
+		if ($timeonothertasks) {
+			print convertSecondToTime($timeonothertasks, 'allhourmin');
+		}
 			print '"></span>';
 		//}
 		print '</td>';
@@ -732,8 +735,7 @@ if (count($tasksarray) > 0)
 		print '</tr>';
 	}
 
-	if ($conf->use_javascript_ajax)
-	{
+	if ($conf->use_javascript_ajax) {
 		print '<tr class="liste_total">';
 		print '<td class="liste_total" colspan="'.($colspan - 1 + $addcolspan).'">';
 		print $langs->trans("Total");
@@ -764,8 +766,7 @@ print '</form>';
 
 $modeinput = 'hours';
 
-if ($conf->use_javascript_ajax)
-{
+if ($conf->use_javascript_ajax) {
 	print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n";
 	print '<script type="text/javascript">'."\n";
 	print "jQuery(document).ready(function () {\n";

+ 109 - 121
htdocs/projet/activity/permonth.php

@@ -44,7 +44,9 @@ $id = GETPOST('id', 'int');
 $taskid = GETPOST('taskid', 'int');
 
 $mine = 0;
-if ($mode == 'mine') $mine = 1;
+if ($mode == 'mine') {
+	$mine = 1;
+}
 
 $projectid = isset($_GET["id"]) ? GETPOST("id", "int", 1) : GETPOST("projectid", "int");
 
@@ -91,12 +93,10 @@ $TFirstDays = getFirstDayOfEachWeek($TWeek, $year);
 $TFirstDays[reset($TWeek)] = '01'; //first day of month
 $TLastDays = getLastDayOfEachWeek($TWeek, $year);
 $TLastDays[end($TWeek)] = date("t", strtotime($year.'-'.$month.'-'.$day)); //last day of month
-if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id)
-{
+if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) {
 	$usertoprocess = $user;
 	$search_usertoprocessid = $usertoprocess->id;
-} elseif ($search_usertoprocessid > 0)
-{
+} elseif ($search_usertoprocessid > 0) {
 	$usertoprocess = new User($db);
 	$usertoprocess->fetch($search_usertoprocessid);
 	$search_usertoprocessid = $usertoprocess->id;
@@ -112,11 +112,12 @@ $object = new Task($db);
  */
 $parameters = array('id' => $id, 'taskid' => $taskid, 'projectid' => $projectid, 'TWeek' => $TWeek, 'TFirstDays' => $TFirstDays, 'TLastDays' => $TLastDays);
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
 // Purge criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 	$action = '';
 	$search_categ = '';
 	$search_usertoprocessid = $user->id;
@@ -126,58 +127,50 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
 	$search_thirdparty = '';
 	$search_declared_progress = '';
 }
-if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha'))
-{
+if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) {
 	$action = '';
 }
 
-if (GETPOST('submitdateselect'))
-{
+if (GETPOST('submitdateselect')) {
 	$daytoparse = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
 
 	$action = '';
 }
-if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask'))
-{
+if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')) {
 	$action = 'assigntask';
 
-	if ($taskid > 0)
-	{
+	if ($taskid > 0) {
 		$result = $object->fetch($taskid, $ref);
-		if ($result < 0) $error++;
+		if ($result < 0) {
+			$error++;
+		}
 	} else {
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors');
 		$error++;
 	}
-	if (!GETPOST('type'))
-	{
+	if (!GETPOST('type')) {
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors');
 		$error++;
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		$idfortaskuser = $usertoprocess->id;
 		$result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal');
 
-		if ($result >= 0 || $result == -2)	// Contact add ok or already contact of task
-		{
+		if ($result >= 0 || $result == -2) {	// Contact add ok or already contact of task
 			// Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project)
 			$sql = 'SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact';
 			$sql .= ' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'";
 			$resql = $db->query($sql);
-			if ($resql)
-			{
+			if ($resql) {
 				$obj = $db->fetch_object($resql);
-				if (!$obj)	// User is not already linked to project, so we will create link to first type
-				{
+				if (!$obj) {	// User is not already linked to project, so we will create link to first type
 					$project = new Project($db);
 					$project->fetch($object->fk_project);
 					// Get type
 					$listofprojcontact = $project->liste_type_contact('internal');
 
-					if (count($listofprojcontact))
-					{
+					if (count($listofprojcontact)) {
 						$typeforprojectcontact = reset(array_keys($listofprojcontact));
 						$result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal');
 					}
@@ -188,11 +181,9 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')
 		}
 	}
 
-	if ($result < 0)
-	{
+	if ($result < 0) {
 		$error++;
-		if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
-		{
+		if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
 			$langs->load("errors");
 			setEventMessages($langs->trans("ErrorTaskAlreadyAssigned"), null, 'warnings');
 		} else {
@@ -200,8 +191,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')
 		}
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		setEventMessages("TaskAssignedToEnterTime", null);
 		$taskid = 0;
 	}
@@ -209,29 +199,29 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')
 	$action = '';
 }
 
-if ($action == 'addtime' && $user->rights->projet->lire)
-{
+if ($action == 'addtime' && $user->rights->projet->lire) {
 	$timetoadd = $_POST['task'];
-	if (empty($timetoadd))
-	{
+	if (empty($timetoadd)) {
 		setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors');
 	} else {
-		foreach ($timetoadd as $taskid => $value)     // Loop on each task
-		{
+		foreach ($timetoadd as $taskid => $value) {     // Loop on each task
 			$updateoftaskdone = 0;
-			foreach ($value as $key => $val)          // Loop on each day
-			{
+			foreach ($value as $key => $val) {          // Loop on each day
 				$amountoadd = $timetoadd[$taskid][$key];
-				if (!empty($amountoadd))
-				{
+				if (!empty($amountoadd)) {
 					$tmpduration = explode(':', $amountoadd);
 					$newduration = 0;
-					if (!empty($tmpduration[0])) $newduration += ($tmpduration[0] * 3600);
-					if (!empty($tmpduration[1])) $newduration += ($tmpduration[1] * 60);
-					if (!empty($tmpduration[2])) $newduration += ($tmpduration[2]);
+					if (!empty($tmpduration[0])) {
+						$newduration += ($tmpduration[0] * 3600);
+					}
+					if (!empty($tmpduration[1])) {
+						$newduration += ($tmpduration[1] * 60);
+					}
+					if (!empty($tmpduration[2])) {
+						$newduration += ($tmpduration[2]);
+					}
 
-					if ($newduration > 0)
-					{
+					if ($newduration > 0) {
 						$object->fetch($taskid);
 						$object->progress = GETPOST($taskid.'progress', 'int');
 						$object->timespent_duration = $newduration;
@@ -240,8 +230,7 @@ if ($action == 'addtime' && $user->rights->projet->lire)
 						$object->timespent_datehour = $object->timespent_date;
 
 						$result = $object->addTimeSpent($user);
-						if ($result < 0)
-						{
+						if ($result < 0) {
 							setEventMessages($object->error, $object->errors, 'errors');
 							$error++;
 							break;
@@ -252,16 +241,13 @@ if ($action == 'addtime' && $user->rights->projet->lire)
 				}
 			}
 
-			if (!$updateoftaskdone)  // Check to update progress if no update were done on task.
-			{
+			if (!$updateoftaskdone) {  // Check to update progress if no update were done on task.
 				$object->fetch($taskid);
 				//var_dump($object->progress);var_dump(GETPOST($taskid . 'progress', 'int')); exit;
-				if ($object->progress != GETPOST($taskid.'progress', 'int'))
-				{
+				if ($object->progress != GETPOST($taskid.'progress', 'int')) {
 					$object->progress = GETPOST($taskid.'progress', 'int');
 					$result = $object->update($user);
-					if ($result < 0)
-					{
+					if ($result < 0) {
 						setEventMessages($object->error, $object->errors, 'errors');
 						$error++;
 						break;
@@ -270,8 +256,7 @@ if ($action == 'addtime' && $user->rights->projet->lire)
 			}
 		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
 
 			$param = '';
@@ -313,8 +298,7 @@ $title = $langs->trans("TimeSpent");
 
 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id) ? 2 : 0), 1); // Return all project i have permission on (assigned to me+public). I want my tasks and some of my task may be on a public projet that is not my project
 //var_dump($projectsListId);
-if ($id)
-{
+if ($id) {
 	$project->fetch($id);
 	$project->fetch_thirdparty();
 }
@@ -322,15 +306,24 @@ if ($id)
 $onlyopenedproject = 1; // or -1
 $morewherefilter = '';
 
-if ($search_project_ref) $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref);
-if ($search_task_ref)    $morewherefilter .= natural_search("t.ref", $search_task_ref);
-if ($search_task_label)  $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label);
-if ($search_thirdparty)  $morewherefilter .= natural_search("s.nom", $search_thirdparty);
-if ($search_declared_progress)  $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1);
+if ($search_project_ref) {
+	$morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref);
+}
+if ($search_task_ref) {
+	$morewherefilter .= natural_search("t.ref", $search_task_ref);
+}
+if ($search_task_label) {
+	$morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label);
+}
+if ($search_thirdparty) {
+	$morewherefilter .= natural_search("s.nom", $search_thirdparty);
+}
+if ($search_declared_progress) {
+	$morewherefilter .= natural_search("t.progress", $search_declared_progress, 1);
+}
 
 $tasksarray = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later.
-if ($morewherefilter)	// Get all task without any filter, so we can show total of time spent for not visible tasks
-{
+if ($morewherefilter) {	// Get all task without any filter, so we can show total of time spent for not visible tasks
 	$tasksarraywithoutfilter = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later.
 }
 $projectsrole = $taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id ? $project->id : 0), 0, $onlyopenedproject);
@@ -376,16 +369,18 @@ print dol_get_fiche_head($head, 'inputpermonth', $langs->trans('TimeSpent'), -1,
 
 // Show description of content
 print '<div class="hideonsmartphone opacitymedium">';
-if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
-else {
-	if (empty($usertoprocess->id) || $usertoprocess->id < 0)
-	{
-		if ($user->rights->projet->all->lire && !$socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
-		else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+if ($mine || ($usertoprocess->id == $user->id)) {
+	print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+} else {
+	if (empty($usertoprocess->id) || $usertoprocess->id < 0) {
+		if ($user->rights->projet->all->lire && !$socid) {
+			print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+		} else {
+			print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+		}
 	}
 }
-if ($mine || ($usertoprocess->id == $user->id))
-{
+if ($mine || ($usertoprocess->id == $user->id)) {
 	print $langs->trans("OnlyYourTaskAreVisible").'<br>';
 } else {
 	print $langs->trans("AllTaskVisibleButEditIfYouAreAssigned").'<br>';
@@ -398,7 +393,9 @@ print '<div class="floatright right'.($conf->dol_optimize_smallscreen ? ' centpe
 
 print '<div class="colorbacktimesheet float valignmiddle">';
 $titleassigntask = $langs->transnoentities("AssignTaskToMe");
-if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs));
+if ($usertoprocess->id != $user->id) {
+	$titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs));
+}
 print '<div class="taskiddiv inline-block">';
 print img_picto('', 'projecttask');
 $formproject->selectTasks($socid ? $socid : -1, $taskid, 'taskid', 32, 0, '-- '.$langs->trans("ChooseANotYetAssignedTask").' --', 1);
@@ -428,12 +425,13 @@ if (! empty($conf->categorie->enabled))
 $moreforfilter .= '<div class="divsearchfield">';
 $moreforfilter .= '<div class="inline-block hideonsmartphone"></div>';
 $includeonly = 'hierachyme';
-if (empty($user->rights->user->user->lire)) $includeonly = array($user->id);
+if (empty($user->rights->user->user->lire)) {
+	$includeonly = array($user->id);
+}
 $moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('User'), 'user').$form->select_dolusers($search_usertoprocessid ? $search_usertoprocessid : $usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire ? 0 : 0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200');
 $moreforfilter .= '</div>';
 
-if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
-{
+if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
 	$moreforfilter .= '<div class="divsearchfield">';
 	$moreforfilter .= '<div class="inline-block"></div>';
 	$moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('Project'), 'project').'<input type="text" size="4" name="search_project_ref" class="marginleftonly" value="'.dol_escape_htmltag($search_project_ref).'">';
@@ -445,8 +443,7 @@ if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
 	$moreforfilter .= '</div>';
 }
 
-if (!empty($moreforfilter))
-{
+if (!empty($moreforfilter)) {
 	print '<div class="liste_titre liste_titre_bydiv centpercent">';
 	print $moreforfilter;
 	$parameters = array();
@@ -460,15 +457,18 @@ print '<div class="div-table-responsive">';
 print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'" id="tablelines3">'."\n";
 
 print '<tr class="liste_titre_filter">';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>';
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
+}
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>';
+}
 print '<td class="liste_titre"><input type="text" size="4" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>';
 print '<td class="liste_titre"></td>';
 print '<td class="liste_titre right"><input type="text" size="4" name="search_declared_progress" value="'.dol_escape_htmltag($search_declared_progress).'"></td>';
 print '<td class="liste_titre"></td>';
 print '<td class="liste_titre"></td>';
-foreach ($TWeek as $week_number)
-{
+foreach ($TWeek as $week_number) {
 	print '<td class="liste_titre"></td>';
 }
 // Action column
@@ -479,8 +479,12 @@ print '</td>';
 print "</tr>\n";
 
 print '<tr class="liste_titre">';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td>'.$langs->trans("Project").'</td>';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td>'.$langs->trans("ThirdParty").'</td>';
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<td>'.$langs->trans("Project").'</td>';
+}
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<td>'.$langs->trans("ThirdParty").'</td>';
+}
 print '<td>'.$langs->trans("Task").'</td>';
 print '<td align="right" class="leftborder plannedworkload maxwidth75">'.$langs->trans("PlannedWorkload").'</td>';
 print '<td align="right" class="maxwidth75">'.$langs->trans("ProgressDeclared").'</td>';
@@ -490,8 +494,7 @@ print '<td align="right" class="maxwidth75">'.$langs->trans("ProgressDeclared").
 print '<td align="right" class="maxwidth75">'.$langs->trans("TimeSpent").'<br><span class="opacitymedium">'.$langs->trans("Everybody").'</span></td>';
 print '<td align="right" class="maxwidth75">'.$langs->trans("TimeSpent").($usertoprocess->firstname ? '<br>'.$usertoprocess->getNomUrl(-2).'<span class="opacitymedium paddingleft">'.dol_trunc($usertoprocess->firstname, 10).'</span>' : '').'</td>';
 
-foreach ($TWeek as $week_number)
-{
+foreach ($TWeek as $week_number) {
 	print '<td width="6%" align="center" class="bold hide">'.$langs->trans("Week").' '.$week_number.'<br>('.$TFirstDays[$week_number].'...'.$TLastDays[$week_number].')</td>';
 }
 print '<td></td>';
@@ -507,8 +510,7 @@ $isavailable = array();
 // TODO See code into perweek.php to initialize isavailable array
 
 
-if (count($tasksarray) > 0)
-{
+if (count($tasksarray) > 0) {
 	//var_dump($tasksarray);				// contains only selected tasks
 	//var_dump($tasksarraywithoutfilter);	// contains all tasks (if there is a filter, not defined if no filter)
 	//var_dump($tasksrole);
@@ -522,21 +524,17 @@ if (count($tasksarray) > 0)
 
 	// Calculate total for all tasks
 	$listofdistinctprojectid = array(); // List of all distinct projects
-	if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter))
-	{
-		foreach ($tasksarraywithoutfilter as $tmptask)
-		{
+	if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) {
+		foreach ($tasksarraywithoutfilter as $tmptask) {
 			$listofdistinctprojectid[$tmptask->fk_project] = $tmptask->fk_project;
 		}
 	}
 	//var_dump($listofdistinctprojectid);
 	$totalforeachweek = array();
-	foreach ($listofdistinctprojectid as $tmpprojectid)
-	{
+	foreach ($listofdistinctprojectid as $tmpprojectid) {
 		$projectstatic->id = $tmpprojectid;
 		$projectstatic->loadTimeSpentMonth($firstdaytoshow, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week
-		foreach ($TWeek as $weekNb)
-		{
+		foreach ($TWeek as $weekNb) {
 			$totalforeachweek[$weekNb] += $projectstatic->monthWorkLoad[$weekNb];
 		}
 	}
@@ -546,13 +544,10 @@ if (count($tasksarray) > 0)
 
 	// Is there a diff between selected/filtered tasks and all tasks ?
 	$isdiff = 0;
-	if (count($totalforeachweek))
-	{
-		foreach ($TWeek as $weekNb)
-		{
+	if (count($totalforeachweek)) {
+		foreach ($TWeek as $weekNb) {
 			$timeonothertasks = ($totalforeachweek[$weekNb] - $totalforvisibletasks[$weekNb]);
-			if ($timeonothertasks)
-			{
+			if ($timeonothertasks) {
 				$isdiff = 1;
 				break;
 			}
@@ -560,19 +555,16 @@ if (count($tasksarray) > 0)
 	}
 
 	// There is a diff between total shown on screen and total spent by user, so we add a line with all other cumulated time of user
-	if ($isdiff)
-	{
+	if ($isdiff) {
 		print '<tr class="oddeven othertaskwithtime">';
 		print '<td colspan="'.$colspan.'" class="opacitymedium">';
 		print $langs->trans("OtherFilteredTasks");
 		print '</td>';
-		foreach ($TWeek as $weekNb)
-		{
+		foreach ($TWeek as $weekNb) {
 			print '<td class="center hide">';
 
 			$timeonothertasks = ($totalforeachweek[$weekNb] - $totalforvisibletasks[$weekNb]);
-			if ($timeonothertasks)
-			{
+			if ($timeonothertasks) {
 				print '<span class="timesheetalreadyrecorded" title="texttoreplace"><input type="text" class="center smallpadd" size="2" disabled="" id="timespent[-1]['.$weekNb.']" name="task[-1]['.$weekNb.']" value="';
 				print convertSecondToTime($timeonothertasks, 'allhourmin');
 				print '"></span>';
@@ -583,16 +575,14 @@ if (count($tasksarray) > 0)
 		print '</tr>';
 	}
 
-	if ($conf->use_javascript_ajax)
-	{
+	if ($conf->use_javascript_ajax) {
 		print '<tr class="liste_total">
                 <td class="liste_total" colspan="'.$colspan.'">';
 		print $langs->trans("Total");
 		print '<span class="opacitymediumbycolor">  - '.$langs->trans("ExpectedWorkedHours").': <strong>'.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).'</strong></span>';
 		print '</td>';
 
-		foreach ($TWeek as $weekNb)
-		{
+		foreach ($TWeek as $weekNb) {
 			print '<td class="liste_total hide'.$weekNb.'" align="center"><div class="totalDay'.$weekNb.'">'.convertSecondToTime($totalforvisibletasks[$weekNb], 'allhourmin').'</div></td>';
 		}
 		print '<td class="liste_total center"><div class="totalDayAll">&nbsp;</div></td>
@@ -615,8 +605,7 @@ print '</form>'."\n\n";
 
 $modeinput = 'hours';
 
-if ($conf->use_javascript_ajax)
-{
+if ($conf->use_javascript_ajax) {
 	print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n";
 	print '<script type="text/javascript">'."\n";
 	print "jQuery(document).ready(function () {\n";
@@ -629,8 +618,7 @@ if ($conf->use_javascript_ajax)
 					}
 				});'."\n";
 
-	foreach ($TWeek as $week_number)
-	{
+	foreach ($TWeek as $week_number) {
 		print '    updateTotal('.$week_number.',\''.$modeinput.'\');';
 	}
 	print "\n});\n";

+ 180 - 183
htdocs/projet/activity/perweek.php

@@ -46,7 +46,9 @@ $taskid = GETPOST('taskid', 'int');
 $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'perweekcard';
 
 $mine = 0;
-if ($mode == 'mine') $mine = 1;
+if ($mode == 'mine') {
+	$mine = 1;
+}
 
 $projectid = isset($_GET["id"]) ? GETPOST("id", "int", 1) : GETPOST("projectid", "int");
 
@@ -99,12 +101,10 @@ $next_day   = $next['day'];
 $firstdaytoshow = dol_mktime(0, 0, 0, $first_month, $first_day, $first_year);
 $lastdaytoshow = dol_time_plus_duree($firstdaytoshow, 7, 'd');
 
-if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id)
-{
+if (empty($search_usertoprocessid) || $search_usertoprocessid == $user->id) {
 	$usertoprocess = $user;
 	$search_usertoprocessid = $usertoprocess->id;
-} elseif ($search_usertoprocessid > 0)
-{
+} elseif ($search_usertoprocessid > 0) {
 	$usertoprocess = new User($db);
 	$usertoprocess->fetch($search_usertoprocessid);
 	$search_usertoprocessid = $usertoprocess->id;
@@ -122,28 +122,27 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 
 $arrayfields = array();
 /*$arrayfields=array(
-    // Project
-    'p.opp_amount'=>array('label'=>$langs->trans("OpportunityAmountShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>103),
-    'p.fk_opp_status'=>array('label'=>$langs->trans("OpportunityStatusShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>104),
-    'p.opp_percent'=>array('label'=>$langs->trans("OpportunityProbabilityShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>105),
-    'p.budget_amount'=>array('label'=>$langs->trans("Budget"), 'checked'=>0, 'position'=>110),
-    'p.usage_bill_time'=>array('label'=>$langs->trans("BillTimeShort"), 'checked'=>0, 'position'=>115),
+	// Project
+	'p.opp_amount'=>array('label'=>$langs->trans("OpportunityAmountShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>103),
+	'p.fk_opp_status'=>array('label'=>$langs->trans("OpportunityStatusShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>104),
+	'p.opp_percent'=>array('label'=>$langs->trans("OpportunityProbabilityShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES?1:0), 'position'=>105),
+	'p.budget_amount'=>array('label'=>$langs->trans("Budget"), 'checked'=>0, 'position'=>110),
+	'p.usage_bill_time'=>array('label'=>$langs->trans("BillTimeShort"), 'checked'=>0, 'position'=>115),
 );*/
 $arrayfields['t.planned_workload'] = array('label'=>'PlannedWorkload', 'checked'=>1, 'enabled'=>1, 'position'=>0);
 $arrayfields['t.progress'] = array('label'=>'ProgressDeclared', 'checked'=>1, 'enabled'=>1, 'position'=>0);
 /*foreach($object->fields as $key => $val)
 {
-    // If $val['visible']==0, then we never show the field
-    if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled'], 'position'=>$val['position']);
+	// If $val['visible']==0, then we never show the field
+	if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled'], 'position'=>$val['position']);
 }*/
 // Definition of fields for list
 // Extra fields
-if (is_array($extrafields->attributes['projet_task']['label']) && count($extrafields->attributes['projet_task']['label']) > 0)
-{
-	foreach ($extrafields->attributes['projet_task']['label'] as $key => $val)
-	{
-		if (!empty($extrafields->attributes['projet_task']['list'][$key]))
+if (is_array($extrafields->attributes['projet_task']['label']) && count($extrafields->attributes['projet_task']['label']) > 0) {
+	foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) {
+		if (!empty($extrafields->attributes['projet_task']['list'][$key])) {
 			$arrayfields["efpt.".$key] = array('label'=>$extrafields->attributes['projet_task']['label'][$key], 'checked'=>(($extrafields->attributes['projet_task']['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes['projet_task']['pos'][$key], 'enabled'=>(abs((int) $extrafields->attributes['projet_task']['list'][$key]) != 3 && $extrafields->attributes['projet_task']['perms'][$key]));
+		}
 	}
 }
 $arrayfields = dol_sort_array($arrayfields, 'position');
@@ -160,10 +159,11 @@ $search_array_options_task = $extrafields->getOptionalsFromPost('projet_task', '
 
 $parameters = array('id' => $id, 'taskid' => $taskid, 'projectid' => $projectid);
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 // Purge criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 	$action = '';
 	$search_categ = '';
 	$search_usertoprocessid = $user->id;
@@ -179,13 +179,11 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
 	// We redefine $usertoprocess
 	$usertoprocess = $user;
 }
-if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha'))
-{
+if (GETPOST("button_search_x", 'alpha') || GETPOST("button_search.x", 'alpha') || GETPOST("button_search", 'alpha')) {
 	$action = '';
 }
 
-if (GETPOST('submitdateselect'))
-{
+if (GETPOST('submitdateselect')) {
 	$daytoparse = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
 
 	$action = '';
@@ -193,47 +191,41 @@ if (GETPOST('submitdateselect'))
 
 include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
-if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') && GETPOST('formfilteraction') != 'listafterchangingselectedfields')
-{
+if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') && GETPOST('formfilteraction') != 'listafterchangingselectedfields') {
 	$action = 'assigntask';
 
-	if ($taskid > 0)
-	{
+	if ($taskid > 0) {
 		$result = $object->fetch($taskid, $ref);
-		if ($result < 0) $error++;
+		if ($result < 0) {
+			$error++;
+		}
 	} else {
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), '', 'errors');
 		$error++;
 	}
-	if (!GETPOST('type'))
-	{
+	if (!GETPOST('type')) {
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors');
 		$error++;
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		$idfortaskuser = $usertoprocess->id;
 		$result = $object->add_contact($idfortaskuser, GETPOST("type"), 'internal');
 
-		if ($result >= 0 || $result == -2)	// Contact add ok or already contact of task
-		{
+		if ($result >= 0 || $result == -2) {	// Contact add ok or already contact of task
 			// Test if we are already contact of the project (should be rare but sometimes we can add as task contact without being contact of project, like when admin user has been removed from contact of project)
 			$sql = 'SELECT ec.rowid FROM '.MAIN_DB_PREFIX.'element_contact as ec, '.MAIN_DB_PREFIX.'c_type_contact as tc WHERE tc.rowid = ec.fk_c_type_contact';
 			$sql .= ' AND ec.fk_socpeople = '.$idfortaskuser." AND ec.element_id = '.$object->fk_project.' AND tc.element = 'project' AND source = 'internal'";
 			$resql = $db->query($sql);
-			if ($resql)
-			{
+			if ($resql) {
 				$obj = $db->fetch_object($resql);
-				if (!$obj)	// User is not already linked to project, so we will create link to first type
-				{
+				if (!$obj) {	// User is not already linked to project, so we will create link to first type
 					$project = new Project($db);
 					$project->fetch($object->fk_project);
 					// Get type
 					$listofprojcontact = $project->liste_type_contact('internal');
 
-					if (count($listofprojcontact))
-					{
+					if (count($listofprojcontact)) {
 						$typeforprojectcontact = reset(array_keys($listofprojcontact));
 						$result = $project->add_contact($idfortaskuser, $typeforprojectcontact, 'internal');
 					}
@@ -244,11 +236,9 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')
 		}
 	}
 
-	if ($result < 0)
-	{
+	if ($result < 0) {
 		$error++;
-		if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
-		{
+		if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
 			$langs->load("errors");
 			setEventMessages($langs->trans("ErrorTaskAlreadyAssigned"), null, 'warnings');
 		} else {
@@ -256,8 +246,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')
 		}
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		setEventMessages("TaskAssignedToEnterTime", null);
 		$taskid = 0;
 	}
@@ -265,33 +254,36 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')
 	$action = '';
 }
 
-if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields')
-{
+if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilteraction') != 'listafterchangingselectedfields') {
 	$timetoadd = $_POST['task'];
-	if (empty($timetoadd))
-	{
+	if (empty($timetoadd)) {
 		setEventMessages($langs->trans("ErrorTimeSpentIsEmpty"), null, 'errors');
 	} else {
-		foreach ($timetoadd as $taskid => $value)     // Loop on each task
-		{
+		foreach ($timetoadd as $taskid => $value) {     // Loop on each task
 			$updateoftaskdone = 0;
-			foreach ($value as $key => $val)          // Loop on each day
-			{
+			foreach ($value as $key => $val) {          // Loop on each day
 				$amountoadd = $timetoadd[$taskid][$key];
-				if (!empty($amountoadd))
-				{
+				if (!empty($amountoadd)) {
 					$tmpduration = explode(':', $amountoadd);
 					$newduration = 0;
-					if (!empty($tmpduration[0])) $newduration += ($tmpduration[0] * 3600);
-					if (!empty($tmpduration[1])) $newduration += ($tmpduration[1] * 60);
-					if (!empty($tmpduration[2])) $newduration += ($tmpduration[2]);
+					if (!empty($tmpduration[0])) {
+						$newduration += ($tmpduration[0] * 3600);
+					}
+					if (!empty($tmpduration[1])) {
+						$newduration += ($tmpduration[1] * 60);
+					}
+					if (!empty($tmpduration[2])) {
+						$newduration += ($tmpduration[2]);
+					}
 
-					if ($newduration > 0)
-					{
-			   			$object->fetch($taskid);
+					if ($newduration > 0) {
+						$object->fetch($taskid);
 
-			   			if (GETPOSTISSET($taskid.'progress')) $object->progress = GETPOST($taskid.'progress', 'int');
-			   			else unset($object->progress);
+						if (GETPOSTISSET($taskid.'progress')) {
+							$object->progress = GETPOST($taskid.'progress', 'int');
+						} else {
+							unset($object->progress);
+						}
 
 						$object->timespent_duration = $newduration;
 						$object->timespent_fk_user = $usertoprocess->id;
@@ -300,8 +292,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac
 						$object->timespent_note = $object->description;
 
 						$result = $object->addTimeSpent($user);
-						if ($result < 0)
-						{
+						if ($result < 0) {
 							setEventMessages($object->error, $object->errors, 'errors');
 							$error++;
 							break;
@@ -312,16 +303,13 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac
 				}
 			}
 
-			if (!$updateoftaskdone)  // Check to update progress if no update were done on task.
-			{
+			if (!$updateoftaskdone) {  // Check to update progress if no update were done on task.
 				$object->fetch($taskid);
 				//var_dump($object->progress);var_dump(GETPOST($taskid . 'progress', 'int')); exit;
-				if ($object->progress != GETPOST($taskid.'progress', 'int'))
-				{
+				if ($object->progress != GETPOST($taskid.'progress', 'int')) {
 					$object->progress = GETPOST($taskid.'progress', 'int');
 					$result = $object->update($user);
-					if ($result < 0)
-					{
+					if ($result < 0) {
 						setEventMessages($object->error, $object->errors, 'errors');
 						$error++;
 						break;
@@ -330,8 +318,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac
 			}
 		}
 
-	   	if (!$error)
-	   	{
+		if (!$error) {
 			setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
 
 			$param = '';
@@ -347,18 +334,18 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('formfilterac
 			$param .= ($search_task_label ? '&search_task_label='.urlencode($search_task_label) : '');
 
 			/*$search_array_options=$search_array_options_project;
-            $search_options_pattern='search_options_';
-            include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
-            */
+			$search_options_pattern='search_options_';
+			include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
+			*/
 
 			$search_array_options = $search_array_options_task;
 			$search_options_pattern = 'search_task_options_';
 			include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 
-	   		// Redirect to avoid submit twice on back
-		   	header('Location: '.$_SERVER["PHP_SELF"].'?'.$param);
-		   	exit;
-	   	}
+			// Redirect to avoid submit twice on back
+			header('Location: '.$_SERVER["PHP_SELF"].'?'.$param);
+			exit;
+		}
 	}
 }
 
@@ -381,8 +368,7 @@ $title = $langs->trans("TimeSpent");
 
 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertoprocess, (empty($usertoprocess->id) ? 2 : 0), 1); // Return all project i have permission on (assigned to me+public). I want my tasks and some of my task may be on a public projet that is not my project
 //var_dump($projectsListId);
-if ($id)
-{
+if ($id) {
 	$project->fetch($id);
 	$project->fetch_thirdparty();
 }
@@ -390,11 +376,21 @@ if ($id)
 $onlyopenedproject = 1; // or -1
 $morewherefilter = '';
 
-if ($search_project_ref) $morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref);
-if ($search_task_ref)    $morewherefilter .= natural_search("t.ref", $search_task_ref);
-if ($search_task_label)  $morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label);
-if ($search_thirdparty)  $morewherefilter .= natural_search("s.nom", $search_thirdparty);
-if ($search_declared_progress)  $morewherefilter .= natural_search("t.progress", $search_declared_progress, 1);
+if ($search_project_ref) {
+	$morewherefilter .= natural_search(array("p.ref", "p.title"), $search_project_ref);
+}
+if ($search_task_ref) {
+	$morewherefilter .= natural_search("t.ref", $search_task_ref);
+}
+if ($search_task_label) {
+	$morewherefilter .= natural_search(array("t.ref", "t.label"), $search_task_label);
+}
+if ($search_thirdparty) {
+	$morewherefilter .= natural_search("s.nom", $search_thirdparty);
+}
+if ($search_declared_progress) {
+	$morewherefilter .= natural_search("t.progress", $search_declared_progress, 1);
+}
 
 $sql = &$morewherefilter;
 
@@ -411,8 +407,7 @@ $extrafieldsobjectkey = 'projet_task';
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
 
 $tasksarray = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter, ($search_usertoprocessid ? $search_usertoprocessid : 0), 0, $extrafields); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later.
-if ($morewherefilter)	// Get all task without any filter, so we can show total of time spent for not visible tasks
-{
+if ($morewherefilter) {	// Get all task without any filter, so we can show total of time spent for not visible tasks
 	$tasksarraywithoutfilter = $taskstatic->getTasksArray(0, 0, ($project->id ? $project->id : 0), $socid, 0, '', $onlyopenedproject, '', ($search_usertoprocessid ? $search_usertoprocessid : 0)); // We want to see all tasks of open project i am allowed to see and that match filter, not only my tasks. Later only mine will be editable later.
 }
 $projectsrole = $taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id ? $project->id : 0), 0, $onlyopenedproject);
@@ -468,16 +463,18 @@ print dol_get_fiche_head($head, 'inputperweek', $langs->trans('TimeSpent'), -1,
 
 // Show description of content
 print '<div class="hideonsmartphone opacitymedium">';
-if ($mine || ($usertoprocess->id == $user->id)) print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
-else {
-	if (empty($usertoprocess->id) || $usertoprocess->id < 0)
-	{
-		if ($user->rights->projet->all->lire && !$socid) print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
-		else print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+if ($mine || ($usertoprocess->id == $user->id)) {
+	print $langs->trans("MyTasksDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+} else {
+	if (empty($usertoprocess->id) || $usertoprocess->id < 0) {
+		if ($user->rights->projet->all->lire && !$socid) {
+			print $langs->trans("ProjectsDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+		} else {
+			print $langs->trans("ProjectsPublicTaskDesc").'.'.($onlyopenedproject ? ' '.$langs->trans("OnlyOpenedProject") : '').'<br>';
+		}
 	}
 }
-if ($mine || ($usertoprocess->id == $user->id))
-{
+if ($mine || ($usertoprocess->id == $user->id)) {
 	print $langs->trans("OnlyYourTaskAreVisible").'<br>';
 } else {
 	print $langs->trans("AllTaskVisibleButEditIfYouAreAssigned").'<br>';
@@ -490,7 +487,9 @@ print '<div class="floatright right'.($conf->dol_optimize_smallscreen ? ' centpe
 
 print '<div class="colorbacktimesheet float valignmiddle">';
 $titleassigntask = $langs->transnoentities("AssignTaskToMe");
-if ($usertoprocess->id != $user->id) $titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs));
+if ($usertoprocess->id != $user->id) {
+	$titleassigntask = $langs->transnoentities("AssignTaskToUser", $usertoprocess->getFullName($langs));
+}
 print '<div class="taskiddiv inline-block">';
 print img_picto('', 'projecttask');
 $formproject->selectTasks($socid ? $socid : -1, $taskid, 'taskid', 32, 0, '-- '.$langs->trans("ChooseANotYetAssignedTask").' --', 1, 0, 0, '', '', 'all', $usertoprocess);
@@ -507,18 +506,15 @@ $startday = dol_mktime(12, 0, 0, $startdayarray['first_month'], $startdayarray['
 
 // Get if user is available or not for each day
 $isavailable = array();
-if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS))
-{
+if (!empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)) {
 	$tmparray = explode('-', $conf->global->MAIN_DEFAULT_WORKING_DAYS);
-	if (count($tmparray) >= 2)
-	{
+	if (count($tmparray) >= 2) {
 		$numstartworkingday = $tmparray[0];
 		$numendworkingday = $tmparray[1];
 	}
 }
 
-for ($idw = 0; $idw < 7; $idw++)
-{
+for ($idw = 0; $idw < 7; $idw++) {
 	$dayinloopfromfirstdaytoshow = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); // $firstdaytoshow is a date with hours = 0
 	$dayinloop = dol_time_plus_duree($startday, $idw, 'd');
 
@@ -535,7 +531,9 @@ for ($idw = 0; $idw < 7; $idw++)
 	$isavailable[$dayinloopfromfirstdaytoshow] = $isavailablefordayanduser; // in projectLinesPerWeek later, we are using $firstdaytoshow and dol_time_plus_duree to loop on each day
 
 	$test = num_public_holiday($dayinloopfromfirstdaytoshow, $dayinloopfromfirstdaytoshow + 86400, $mysoc->country_code);
-	if ($test) $isavailable[$dayinloopfromfirstdaytoshow] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday');
+	if ($test) {
+		$isavailable[$dayinloopfromfirstdaytoshow] = array('morning'=>false, 'afternoon'=>false, 'morning_reason'=>'public_holiday', 'afternoon_reason'=>'public_holiday');
+	}
 }
 //var_dump($isavailable);
 
@@ -558,12 +556,13 @@ if (! empty($conf->categorie->enabled))
 $moreforfilter .= '<div class="divsearchfield">';
 $moreforfilter .= '<div class="inline-block hideonsmartphone"></div>';
 $includeonly = 'hierarchyme';
-if (empty($user->rights->user->user->lire)) $includeonly = array($user->id);
+if (empty($user->rights->user->user->lire)) {
+	$includeonly = array($user->id);
+}
 $moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('User'), 'user').$form->select_dolusers($search_usertoprocessid ? $search_usertoprocessid : $usertoprocess->id, 'search_usertoprocessid', $user->rights->user->user->lire ? 0 : 0, null, 0, $includeonly, null, 0, 0, 0, '', 0, '', 'maxwidth200');
 $moreforfilter .= '</div>';
 
-if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
-{
+if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
 	$moreforfilter .= '<div class="divsearchfield">';
 	$moreforfilter .= '<div class="inline-block"></div>';
 	$moreforfilter .= img_picto($langs->trans('Filter').' '.$langs->trans('Project'), 'project').'<input type="text" size="4" name="search_project_ref" class="marginleftonly" value="'.dol_escape_htmltag($search_project_ref).'">';
@@ -575,8 +574,7 @@ if (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
 	$moreforfilter .= '</div>';
 }
 
-if (!empty($moreforfilter))
-{
+if (!empty($moreforfilter)) {
 	print '<div class="liste_titre liste_titre_bydiv centpercent">';
 	print $moreforfilter;
 	$parameters = array();
@@ -592,19 +590,28 @@ $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfi
 
 // This must be after the $selectedfields
 $addcolspan = 0;
-if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++;
-if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++;
-foreach ($arrayfields as $key => $val)
-{
-	if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++;
+if (!empty($arrayfields['t.planned_workload']['checked'])) {
+	$addcolspan++;
+}
+if (!empty($arrayfields['t.progress']['checked'])) {
+	$addcolspan++;
+}
+foreach ($arrayfields as $key => $val) {
+	if ($val['checked'] && substr($key, 0, 5) == 'efpt.') {
+		$addcolspan++;
+	}
 }
 
 print '<div class="div-table-responsive">';
 print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'" id="tablelines3">'."\n";
 
 print '<tr class="liste_titre_filter">';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>';
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<td class="liste_titre"><input type="text" size="4" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
+}
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<td class="liste_titre"><input type="text" size="4" name="search_thirdparty" value="'.dol_escape_htmltag($search_thirdparty).'"></td>';
+}
 print '<td class="liste_titre"><input type="text" size="4" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>';
 // TASK fields
 $search_options_pattern = 'search_task_options_';
@@ -612,17 +619,14 @@ $extrafieldsobjectkey = 'projet_task';
 $extrafieldsobjectprefix = 'efpt.';
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
 print '<td class="liste_titre"></td>';
-if (!empty($arrayfields['t.planned_workload']['checked']))
-{
+if (!empty($arrayfields['t.planned_workload']['checked'])) {
 	print '<td class="liste_titre right"><input type="text" size="4" name="search_declared_progress" value="'.dol_escape_htmltag($search_declared_progress).'"></td>';
 }
-if (!empty($arrayfields['t.progress']['checked']))
-{
+if (!empty($arrayfields['t.progress']['checked'])) {
 	print '<td class="liste_titre"></td>';
 }
 print '<td class="liste_titre"></td>';
-for ($idw = 0; $idw < 7; $idw++)
-{
+for ($idw = 0; $idw < 7; $idw++) {
 	print '<td class="liste_titre"></td>';
 }
 // Action column
@@ -633,19 +637,21 @@ print '</td>';
 print "</tr>\n";
 
 print '<tr class="liste_titre">';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<th>'.$langs->trans("Project").'</th>';
-if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) print '<th>'.$langs->trans("ThirdParty").'</th>';
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<th>'.$langs->trans("Project").'</th>';
+}
+if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) {
+	print '<th>'.$langs->trans("ThirdParty").'</th>';
+}
 print '<th>'.$langs->trans("Task").'</th>';
 // TASK fields
 $extrafieldsobjectkey = 'projet_task';
 $extrafieldsobjectprefix = 'efpt.';
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
-if (!empty($arrayfields['t.planned_workload']['checked']))
-{
+if (!empty($arrayfields['t.planned_workload']['checked'])) {
 	print '<th class="leftborder plannedworkload maxwidth75 right">'.$langs->trans("PlannedWorkload").'</th>';
 }
-if (!empty($arrayfields['t.progress']['checked']))
-{
+if (!empty($arrayfields['t.progress']['checked'])) {
 	print '<th class="maxwidth75 right">'.$langs->trans("ProgressDeclared").'</th>';
 }
 /*print '<td class="maxwidth75 right">'.$langs->trans("TimeSpent").'</td>';
@@ -654,23 +660,25 @@ if (!empty($arrayfields['t.progress']['checked']))
 print '<th class="maxwidth75 right">'.$langs->trans("TimeSpent").'<br><span class="opacitymedium">'.$langs->trans("Everybody").'</span></th>';
 print '<th class="maxwidth75 right">'.$langs->trans("TimeSpent").($usertoprocess->firstname ? '<br>'.$usertoprocess->getNomUrl(-2).'<span class="opacitymedium paddingleft">'.dol_trunc($usertoprocess->firstname, 10).'</span>' : '').'</th>';
 
-for ($idw = 0; $idw < 7; $idw++)
-{
+for ($idw = 0; $idw < 7; $idw++) {
 	$dayinloopfromfirstdaytoshow = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); // $firstdaytoshow is a date with hours = 0
 	$dayinloop = dol_time_plus_duree($startday, $idw, 'd');
 
 	$cssweekend = '';
-	if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday))	// This is a day is not inside the setup of working days, so we use a week-end css.
-	{
+	if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) {	// This is a day is not inside the setup of working days, so we use a week-end css.
 		$cssweekend = 'weekend';
 	}
 
 	$tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd');
 
 	$cssonholiday = '';
-	if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon'])   $cssonholiday .= 'onholidayallday ';
-	elseif (!$isavailable[$tmpday]['morning'])   $cssonholiday .= 'onholidaymorning ';
-	elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon ';
+	if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) {
+		$cssonholiday .= 'onholidayallday ';
+	} elseif (!$isavailable[$tmpday]['morning']) {
+		$cssonholiday .= 'onholidaymorning ';
+	} elseif (!$isavailable[$tmpday]['afternoon']) {
+		$cssonholiday .= 'onholidayafternoon ';
+	}
 
 	print '<th width="6%" align="center" class="bold hide'.$idw.($cssonholiday ? ' '.$cssonholiday : '').($cssweekend ? ' '.$cssweekend : '').'">'.dol_print_date($dayinloopfromfirstdaytoshow, '%a').'<br>'.dol_print_date($dayinloopfromfirstdaytoshow, 'dayreduceformat').'</th>';
 }
@@ -682,28 +690,29 @@ print "</tr>\n";
 
 $colspan = 3 + (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : 2);
 
-if ($conf->use_javascript_ajax)
-{
+if ($conf->use_javascript_ajax) {
 	print '<tr class="liste_total">';
 	print '<td class="liste_total" colspan="'.($colspan + $addcolspan).'">';
 	print $langs->trans("Total");
 	print '<span class="opacitymediumbycolor">  - '.$langs->trans("ExpectedWorkedHours").': <strong>'.price($usertoprocess->weeklyhours, 1, $langs, 0, 0).'</strong></span>';
 	print '</td>';
 
-	for ($idw = 0; $idw < 7; $idw++)
-	{
+	for ($idw = 0; $idw < 7; $idw++) {
 		$cssweekend = '';
-		if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday))	// This is a day is not inside the setup of working days, so we use a week-end css.
-		{
+		if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) {	// This is a day is not inside the setup of working days, so we use a week-end css.
 			$cssweekend = 'weekend';
 		}
 
 		$tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd');
 
 		$cssonholiday = '';
-		if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon'])   $cssonholiday .= 'onholidayallday ';
-		elseif (!$isavailable[$tmpday]['morning'])   $cssonholiday .= 'onholidaymorning ';
-		elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon ';
+		if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) {
+			$cssonholiday .= 'onholidayallday ';
+		} elseif (!$isavailable[$tmpday]['morning']) {
+			$cssonholiday .= 'onholidaymorning ';
+		} elseif (!$isavailable[$tmpday]['afternoon']) {
+			$cssonholiday .= 'onholidayafternoon ';
+		}
 		print '<td class="liste_total hide'.$idw.($cssonholiday ? ' '.$cssonholiday : '').($cssweekend ? ' '.$cssweekend : '').'" align="center"><div class="totalDay'.$idw.'">&nbsp;</div></td>';
 	}
 	print '<td class="liste_total center"><div class="totalDayAll">&nbsp;</div></td>';
@@ -714,8 +723,7 @@ if ($conf->use_javascript_ajax)
 
 // By default, we can edit only tasks we are assigned to
 $restrictviewformytask = ((!isset($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)) ? 2 : $conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED);
-if (count($tasksarray) > 0)
-{
+if (count($tasksarray) > 0) {
 	//var_dump($tasksarray);				// contains only selected tasks
 	//var_dump($tasksarraywithoutfilter);	// contains all tasks (if there is a filter, not defined if no filter)
 	//var_dump($tasksrole);
@@ -729,21 +737,17 @@ if (count($tasksarray) > 0)
 
 	// Calculate total for all tasks
 	$listofdistinctprojectid = array(); // List of all distinct projects
-	if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter))
-	{
-		foreach ($tasksarraywithoutfilter as $tmptask)
-		{
+	if (is_array($tasksarraywithoutfilter) && count($tasksarraywithoutfilter)) {
+		foreach ($tasksarraywithoutfilter as $tmptask) {
 			$listofdistinctprojectid[$tmptask->fk_project] = $tmptask->fk_project;
 		}
 	}
 	//var_dump($listofdistinctprojectid);
 	$totalforeachday = array();
-	foreach ($listofdistinctprojectid as $tmpprojectid)
-	{
+	foreach ($listofdistinctprojectid as $tmpprojectid) {
 		$projectstatic->id = $tmpprojectid;
 		$projectstatic->loadTimeSpent($firstdaytoshow, 0, $usertoprocess->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week
-		for ($idw = 0; $idw < 7; $idw++)
-		{
+		for ($idw = 0; $idw < 7; $idw++) {
 			$tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd');
 			$totalforeachday[$tmpday] += $projectstatic->weekWorkLoad[$tmpday];
 		}
@@ -754,14 +758,11 @@ if (count($tasksarray) > 0)
 
 	// Is there a diff between selected/filtered tasks and all tasks ?
 	$isdiff = 0;
-	if (count($totalforeachday))
-	{
-		for ($idw = 0; $idw < 7; $idw++)
-		{
+	if (count($totalforeachday)) {
+		for ($idw = 0; $idw < 7; $idw++) {
 			$tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd');
 			$timeonothertasks = ($totalforeachday[$tmpday] - $totalforvisibletasks[$tmpday]);
-			if ($timeonothertasks)
-			{
+			if ($timeonothertasks) {
 				$isdiff = 1;
 				break;
 			}
@@ -769,25 +770,21 @@ if (count($tasksarray) > 0)
 	}
 
 	// There is a diff between total shown on screen and total spent by user, so we add a line with all other cumulated time of user
-	if ($isdiff)
-	{
+	if ($isdiff) {
 		print '<tr class="oddeven othertaskwithtime">';
 		print '<td colspan="'.($colspan + $addcolspan).'" class="opacitymedium">';
 		print $langs->trans("OtherFilteredTasks");
 		print '</td>';
-		for ($idw = 0; $idw < 7; $idw++)
-		{
+		for ($idw = 0; $idw < 7; $idw++) {
 			$cssweekend = '';
-			if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday))	// This is a day is not inside the setup of working days, so we use a week-end css.
-			{
+			if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) {	// This is a day is not inside the setup of working days, so we use a week-end css.
 				$cssweekend = 'weekend';
 			}
 
 			print '<td class="center hide'.$idw.' '.($cssweekend ? ' '.$cssweekend : '').'">';
 			$tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd');
 			$timeonothertasks = ($totalforeachday[$tmpday] - $totalforvisibletasks[$tmpday]);
-			if ($timeonothertasks)
-			{
+			if ($timeonothertasks) {
 				print '<span class="timesheetalreadyrecorded" title="texttoreplace"><input type="text" class="center smallpadd" size="2" disabled="" id="timespent[-1]['.$idw.']" name="task[-1]['.$idw.']" value="';
 				print convertSecondToTime($timeonothertasks, 'allhourmin');
 				print '"></span>';
@@ -798,8 +795,7 @@ if (count($tasksarray) > 0)
 		print '</tr>';
 	}
 
-	if ($conf->use_javascript_ajax)
-	{
+	if ($conf->use_javascript_ajax) {
 		print '<tr class="liste_total">
                 <td class="liste_total" colspan="'.($colspan + $addcolspan).'">';
 				print $langs->trans("Total");
@@ -808,17 +804,20 @@ if (count($tasksarray) > 0)
 
 		for ($idw = 0; $idw < 7; $idw++) {
 			$cssweekend = '';
-			if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday))	// This is a day is not inside the setup of working days, so we use a week-end css.
-			{
+			if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) {	// This is a day is not inside the setup of working days, so we use a week-end css.
 				$cssweekend = 'weekend';
 			}
 
 			$tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd');
 
 			$cssonholiday = '';
-			if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon'])   $cssonholiday .= 'onholidayallday ';
-			elseif (!$isavailable[$tmpday]['morning'])   $cssonholiday .= 'onholidaymorning ';
-			elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon ';
+			if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) {
+				$cssonholiday .= 'onholidayallday ';
+			} elseif (!$isavailable[$tmpday]['morning']) {
+				$cssonholiday .= 'onholidaymorning ';
+			} elseif (!$isavailable[$tmpday]['afternoon']) {
+				$cssonholiday .= 'onholidayafternoon ';
+			}
 
 			print '<td class="liste_total hide'.$idw.($cssonholiday ? ' '.$cssonholiday : '').($cssweekend ? ' '.$cssweekend : '').'" align="center"><div class="totalDay'.$idw.'">&nbsp;</div></td>';
 		}
@@ -841,8 +840,7 @@ print '</form>'."\n\n";
 
 $modeinput = 'hours';
 
-if ($conf->use_javascript_ajax)
-{
+if ($conf->use_javascript_ajax) {
 	print "\n<!-- JS CODE TO ENABLE Tooltips on all object with class classfortooltip -->\n";
 	print '<script type="text/javascript">'."\n";
 	print "jQuery(document).ready(function () {\n";
@@ -856,8 +854,7 @@ if ($conf->use_javascript_ajax)
 				});'."\n";
 
 	$idw = 0;
-	while ($idw < 7)
-	{
+	while ($idw < 7) {
 		print '    updateTotal('.$idw.',\''.$modeinput.'\');';
 		$idw++;
 	}

+ 152 - 200
htdocs/projet/admin/project.php

@@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
 // Load translation files required by the page
 $langs->loadLangs(array('admin', 'errors', 'other', 'projects'));
 
-if (!$user->admin) accessforbidden();
+if (!$user->admin) {
+	accessforbidden();
+}
 
 $value = GETPOST('value', 'alpha');
 $action = GETPOST('action', 'aZ09');
@@ -51,40 +53,43 @@ $type = 'project';
 
 include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
 
-if ($action == 'updateMask')
-{
+if ($action == 'updateMask') {
 	$maskconstproject = GETPOST('maskconstproject', 'alpha');
 	$maskproject = GETPOST('maskproject', 'alpha');
 
-	if ($maskconstproject)  $res = dolibarr_set_const($db, $maskconstproject, $maskproject, 'chaine', 0, '', $conf->entity);
+	if ($maskconstproject) {
+		$res = dolibarr_set_const($db, $maskconstproject, $maskproject, 'chaine', 0, '', $conf->entity);
+	}
 
-	if (!($res > 0)) $error++;
+	if (!($res > 0)) {
+		$error++;
+	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
 	} else {
 		setEventMessages($langs->trans("Error"), null, 'errors');
 	}
 }
 
-if ($action == 'updateMaskTask')
-{
+if ($action == 'updateMaskTask') {
 	$maskconstmasktask = GETPOST('maskconsttask', 'alpha');
 	$masktaskt = GETPOST('masktask', 'alpha');
 
-	if ($maskconstmasktask)  $res = dolibarr_set_const($db, $maskconstmasktask, $masktaskt, 'chaine', 0, '', $conf->entity);
+	if ($maskconstmasktask) {
+		$res = dolibarr_set_const($db, $maskconstmasktask, $masktaskt, 'chaine', 0, '', $conf->entity);
+	}
 
-	if (!($res > 0)) $error++;
+	if (!($res > 0)) {
+		$error++;
+	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
 	} else {
 		setEventMessages($langs->trans("Error"), null, 'errors');
 	}
-} elseif ($action == 'specimen')
-{
+} elseif ($action == 'specimen') {
 	$modele = GETPOST('module', 'alpha');
 
 	$project = new Project($db);
@@ -93,25 +98,21 @@ if ($action == 'updateMaskTask')
 	// Search template files
 	$file = ''; $classname = ''; $filefound = 0;
 	$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
-	foreach ($dirmodels as $reldir)
-	{
+	foreach ($dirmodels as $reldir) {
 		$file = dol_buildpath($reldir."core/modules/project/doc/pdf_".$modele.".modules.php", 0);
-		if (file_exists($file))
-		{
+		if (file_exists($file)) {
 			$filefound = 1;
 			$classname = "pdf_".$modele;
 			break;
 		}
 	}
 
-	if ($filefound)
-	{
+	if ($filefound) {
 		require_once $file;
 
 		$module = new $classname($db);
 
-		if ($module->write_file($project, $langs) > 0)
-		{
+		if ($module->write_file($project, $langs) > 0) {
 			header("Location: ".DOL_URL_ROOT."/document.php?modulepart=project&file=SPECIMEN.pdf");
 			return;
 		} else {
@@ -122,8 +123,7 @@ if ($action == 'updateMaskTask')
 		setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors');
 		dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR);
 	}
-} elseif ($action == 'specimentask')
-{
+} elseif ($action == 'specimentask') {
 	$modele = GETPOST('module', 'alpha');
 
 	$project = new Project($db);
@@ -132,25 +132,21 @@ if ($action == 'updateMaskTask')
 	// Search template files
 	$file = ''; $classname = ''; $filefound = 0;
 	$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
-	foreach ($dirmodels as $reldir)
-	{
+	foreach ($dirmodels as $reldir) {
 		$file = dol_buildpath($reldir."core/modules/project/task/doc/pdf_".$modele.".modules.php", 0);
-		if (file_exists($file))
-		{
+		if (file_exists($file)) {
 			$filefound = 1;
 			$classname = "pdf_".$modele;
 			break;
 		}
 	}
 
-	if ($filefound)
-	{
+	if ($filefound) {
 		require_once $file;
 
 		$module = new $classname($db);
 
-		if ($module->write_file($project, $langs) > 0)
-		{
+		if ($module->write_file($project, $langs) > 0) {
 			header("Location: ".DOL_URL_ROOT."/document.php?modulepart=project_task&file=SPECIMEN.pdf");
 			return;
 		} else {
@@ -161,49 +157,37 @@ if ($action == 'updateMaskTask')
 		setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors');
 		dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR);
 	}
-}
-
-// Activate a model
-elseif ($action == 'set')
-{
+} elseif ($action == 'set') {
+	// Activate a model
 	$ret = addDocumentModel($value, $type, $label, $scandir);
-}
-// Activate a model for task
-elseif ($action == 'settask')
-{
+} elseif ($action == 'settask') {
+	// Activate a model for task
 	$ret = addDocumentModel($value, 'project_task', $label, $scandir);
-} elseif ($action == 'del')
-{
+} elseif ($action == 'del') {
 	$ret = delDocumentModel($value, $type);
-	if ($ret > 0)
-	{
-		if ($conf->global->PROJECT_ADDON_PDF == "$value") dolibarr_del_const($db, 'PROJECT_ADDON_PDF', $conf->entity);
+	if ($ret > 0) {
+		if ($conf->global->PROJECT_ADDON_PDF == "$value") {
+			dolibarr_del_const($db, 'PROJECT_ADDON_PDF', $conf->entity);
+		}
 	}
-}
-if ($action == 'deltask')
-{
+} elseif ($action == 'deltask') {
 	$ret = delDocumentModel($value, 'project_task');
-	if ($ret > 0)
-	{
-		if ($conf->global->PROJECT_TASK_ADDON_PDF == "$value") dolibarr_del_const($db, 'PROJECT_TASK_ADDON_PDF', $conf->entity);
+	if ($ret > 0) {
+		if ($conf->global->PROJECT_TASK_ADDON_PDF == "$value") {
+			dolibarr_del_const($db, 'PROJECT_TASK_ADDON_PDF', $conf->entity);
+		}
 	}
-}
-
-// Set default model
-elseif ($action == 'setdoc')
-{
+} elseif ($action == 'setdoc') {
+	// Set default model
 	dolibarr_set_const($db, "PROJECT_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity);
 
 	// On active le modele
 	$ret = delDocumentModel($value, $type);
-	if ($ret > 0)
-	{
+	if ($ret > 0) {
 		$ret = addDocumentModel($value, $type, $label, $scandir);
 	}
-} elseif ($action == 'setdoctask')
-{
-	if (dolibarr_set_const($db, "PROJECT_TASK_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity))
-	{
+} elseif ($action == 'setdoctask') {
+	if (dolibarr_set_const($db, "PROJECT_TASK_ADDON_PDF", $value, 'chaine', 0, '', $conf->entity)) {
 		// La constante qui a ete lue en avant du nouveau set
 		// on passe donc par une variable pour avoir un affichage coherent
 		$conf->global->PROJECT_TASK_ADDON_PDF = $value;
@@ -211,41 +195,32 @@ elseif ($action == 'setdoc')
 
 	// On active le modele
 	$ret = delDocumentModel($value, 'project_task');
-	if ($ret > 0)
-	{
+	if ($ret > 0) {
 		$ret = addDocumentModel($value, 'project_task', $label, $scandir);
 	}
-} elseif ($action == 'setmod')
-{
+} elseif ($action == 'setmod') {
 	// TODO Verifier si module numerotation choisi peut etre active
 	// par appel methode canBeActivated
 
 	dolibarr_set_const($db, "PROJECT_ADDON", $value, 'chaine', 0, '', $conf->entity);
-} elseif ($action == 'setmodtask')
-{
+} elseif ($action == 'setmodtask') {
 	// TODO Verifier si module numerotation choisi peut etre active
 	// par appel methode canBeActivated
 
 	dolibarr_set_const($db, "PROJECT_TASK_ADDON", $value, 'chaine', 0, '', $conf->entity);
-} elseif ($action == 'updateoptions')
-{
-	if (GETPOST('PROJECT_USE_SEARCH_TO_SELECT'))
-	{
+} elseif ($action == 'updateoptions') {
+	if (GETPOST('PROJECT_USE_SEARCH_TO_SELECT')) {
 		$companysearch = GETPOST('activate_PROJECT_USE_SEARCH_TO_SELECT', 'alpha');
-		if (dolibarr_set_const($db, "PROJECT_USE_SEARCH_TO_SELECT", $companysearch, 'chaine', 0, '', $conf->entity))
-		{
+		if (dolibarr_set_const($db, "PROJECT_USE_SEARCH_TO_SELECT", $companysearch, 'chaine', 0, '', $conf->entity)) {
 			$conf->global->PROJECT_USE_SEARCH_TO_SELECT = $companysearch;
 		}
 	}
-	if (GETPOST('PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY'))
-	{
+	if (GETPOST('PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY')) {
 		$projectToSelect = GETPOST('projectToSelect', 'alpha');
 		dolibarr_set_const($db, 'PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY', $projectToSelect, 'chaine', 0, '', $conf->entity); //Allow to disable this configuration if empty value
 	}
-}
-
-// Set boolean (on/off) constants
-elseif (preg_match('/^(set|del)_?([A-Z_]+)$/', $action, $reg)) {
+} elseif (preg_match('/^(set|del)_?([A-Z_]+)$/', $action, $reg)) {
+	// Set boolean (on/off) constants
 	if (!dolibarr_set_const($db, $reg[2], ($reg[1] === 'set' ? '1' : '0'), 'chaine', 0, '', $conf->entity) > 0) {
 		dol_print_error($db);
 	}
@@ -323,19 +298,14 @@ print "</tr>\n";
 
 clearstatcache();
 
-foreach ($dirmodels as $reldir)
-{
+foreach ($dirmodels as $reldir) {
 	$dir = dol_buildpath($reldir."core/modules/project/");
 
-	if (is_dir($dir))
-	{
+	if (is_dir($dir)) {
 		$handle = opendir($dir);
-		if (is_resource($handle))
-		{
-			while (($file = readdir($handle)) !== false)
-			{
-				if (preg_match('/^(mod_.*)\.php$/i', $file, $reg))
-				{
+		if (is_resource($handle)) {
+			while (($file = readdir($handle)) !== false) {
+				if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) {
 					$file = $reg[1];
 					$classname = substr($file, 4);
 
@@ -344,11 +314,14 @@ foreach ($dirmodels as $reldir)
 					$module = new $file;
 
 					// Show modules according to features level
-					if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue;
-					if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue;
+					if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
+						continue;
+					}
+					if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
+						continue;
+					}
 
-					if ($module->isEnabled())
-					{
+					if ($module->isEnabled()) {
 						print '<tr class="oddeven"><td>'.$module->name."</td><td>\n";
 						print $module->info();
 						print '</td>';
@@ -359,13 +332,15 @@ foreach ($dirmodels as $reldir)
 						if (preg_match('/^Error/', $tmp)) {
 							$langs->load("errors");
 							print '<div class="error">'.$langs->trans($tmp).'</div>';
-						} elseif ($tmp == 'NotConfigured') print $langs->trans($tmp);
-						else print $tmp;
+						} elseif ($tmp == 'NotConfigured') {
+							print $langs->trans($tmp);
+						} else {
+							print $tmp;
+						}
 						print '</td>'."\n";
 
 						print '<td class="center">';
-						if ($conf->global->PROJECT_ADDON == 'mod_'.$classname)
-						{
+						if ($conf->global->PROJECT_ADDON == 'mod_'.$classname) {
 							print img_picto($langs->trans("Activated"), 'switch_on');
 						} else {
 							print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setmod&amp;token='.newToken().'&amp;value=mod_'.$classname.'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</a>';
@@ -379,11 +354,9 @@ foreach ($dirmodels as $reldir)
 						$htmltooltip = '';
 						$htmltooltip .= ''.$langs->trans("Version").': <b>'.$module->getVersion().'</b><br>';
 						$nextval = $module->getNextValue($mysoc, $project);
-						if ("$nextval" != $langs->trans("NotAvailable"))	// Keep " on nextval
-						{
+						if ("$nextval" != $langs->trans("NotAvailable")) {	// Keep " on nextval
 							$htmltooltip .= ''.$langs->trans("NextValue").': ';
-							if ($nextval)
-							{
+							if ($nextval) {
 								$htmltooltip .= $nextval.'<br>';
 							} else {
 								$htmltooltip .= $langs->trans($module->error).'<br>';
@@ -406,8 +379,7 @@ foreach ($dirmodels as $reldir)
 print '</table><br>';
 
 
-if (empty($conf->global->PROJECT_HIDE_TASKS))
-{
+if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 	// Task numbering module
 	print load_fiche_titre($langs->trans("TasksNumberingModules"), '', '');
 
@@ -422,19 +394,14 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 
 	clearstatcache();
 
-	foreach ($dirmodels as $reldir)
-	{
+	foreach ($dirmodels as $reldir) {
 		$dir = dol_buildpath($reldir."core/modules/project/task/");
 
-		if (is_dir($dir))
-		{
+		if (is_dir($dir)) {
 			$handle = opendir($dir);
-			if (is_resource($handle))
-			{
-				while (($file = readdir($handle)) !== false)
-				{
-					if (preg_match('/^(mod_.*)\.php$/i', $file, $reg))
-					{
+			if (is_resource($handle)) {
+				while (($file = readdir($handle)) !== false) {
+					if (preg_match('/^(mod_.*)\.php$/i', $file, $reg)) {
 						$file = $reg[1];
 						$classname = substr($file, 4);
 
@@ -443,11 +410,14 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 						$module = new $file;
 
 						// Show modules according to features level
-						if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue;
-						if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue;
+						if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
+							continue;
+						}
+						if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
+							continue;
+						}
 
-						if ($module->isEnabled())
-						{
+						if ($module->isEnabled()) {
 							print '<tr class="oddeven"><td>'.$module->name."</td><td>\n";
 							print $module->info();
 							print '</td>';
@@ -458,13 +428,15 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 							if (preg_match('/^Error/', $tmp)) {
 								$langs->load("errors");
 								print '<div class="error">'.$langs->trans($tmp).'</div>';
-							} elseif ($tmp == 'NotConfigured') print $langs->trans($tmp);
-							else print $tmp;
+							} elseif ($tmp == 'NotConfigured') {
+								print $langs->trans($tmp);
+							} else {
+								print $tmp;
+							}
 							print '</td>'."\n";
 
 							print '<td class="center">';
-							if ($conf->global->PROJECT_TASK_ADDON == 'mod_'.$classname)
-							{
+							if ($conf->global->PROJECT_TASK_ADDON == 'mod_'.$classname) {
 								print img_picto($langs->trans("Activated"), 'switch_on');
 							} else {
 								print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setmodtask&amp;token='.newToken().'&amp;value=mod_'.$classname.'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'switch_off').'</a>';
@@ -478,11 +450,9 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 							$htmltooltip = '';
 							$htmltooltip .= ''.$langs->trans("Version").': <b>'.$module->getVersion().'</b><br>';
 							$nextval = $module->getNextValue($mysoc, $project);
-							if ("$nextval" != $langs->trans("NotAvailable"))	// Keep " on nextval
-							{
+							if ("$nextval" != $langs->trans("NotAvailable")) {	// Keep " on nextval
 								$htmltooltip .= ''.$langs->trans("NextValue").': ';
-								if ($nextval)
-								{
+								if ($nextval) {
 									$htmltooltip .= $nextval.'<br>';
 								} else {
 									$htmltooltip .= $langs->trans($module->error).'<br>';
@@ -522,12 +492,10 @@ $sql .= " WHERE type = '".$db->escape($type)."'";
 $sql .= " AND entity = ".$conf->entity;
 
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$i = 0;
 	$num_rows = $db->num_rows($resql);
-	while ($i < $num_rows)
-	{
+	while ($i < $num_rows) {
 		$array = $db->fetch_array($resql);
 		array_push($def, $array[0]);
 		$i++;
@@ -548,30 +516,22 @@ print "</tr>\n";
 
 clearstatcache();
 
-foreach ($dirmodels as $reldir)
-{
-	foreach (array('', '/doc') as $valdir)
-	{
+foreach ($dirmodels as $reldir) {
+	foreach (array('', '/doc') as $valdir) {
 		$dir = dol_buildpath($reldir."core/modules/project/".$valdir);
 
-		if (is_dir($dir))
-		{
+		if (is_dir($dir)) {
 			$handle = opendir($dir);
-			if (is_resource($handle))
-			{
-				while (($file = readdir($handle)) !== false)
-				{
+			if (is_resource($handle)) {
+				while (($file = readdir($handle)) !== false) {
 					$filelist[] = $file;
 				}
 				closedir($handle);
 				arsort($filelist);
 
-				foreach ($filelist as $file)
-				{
-					if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file))
-					{
-						if (file_exists($dir.'/'.$file))
-						{
+				foreach ($filelist as $file) {
+					if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) {
+						if (file_exists($dir.'/'.$file)) {
 							$name = substr($file, 4, dol_strlen($file) - 16);
 							$classname = substr($file, 0, dol_strlen($file) - 12);
 
@@ -579,21 +539,26 @@ foreach ($dirmodels as $reldir)
 							$module = new $classname($db);
 
 							$modulequalified = 1;
-							if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0;
-							if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0;
+							if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
+								$modulequalified = 0;
+							}
+							if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
+								$modulequalified = 0;
+							}
 
-							if ($modulequalified)
-							{
+							if ($modulequalified) {
 								print '<tr class="oddeven"><td width="100">';
 								print (empty($module->name) ? $name : $module->name);
 								print "</td><td>\n";
-								if (method_exists($module, 'info')) print $module->info($langs);
-								else print $module->description;
+								if (method_exists($module, 'info')) {
+									print $module->info($langs);
+								} else {
+									print $module->description;
+								}
 								print "</td>\n";
 
 								// Active
-								if (in_array($name, $def))
-								{
+								if (in_array($name, $def)) {
 									print "<td class=\"center\">\n";
 									print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'">';
 									print img_picto($langs->trans("Enabled"), 'switch_on');
@@ -607,8 +572,7 @@ foreach ($dirmodels as $reldir)
 
 								// Default
 								print "<td class=\"center\">";
-								if ($conf->global->PROJECT_ADDON_PDF == "$name")
-								{
+								if ($conf->global->PROJECT_ADDON_PDF == "$name") {
 									print img_picto($langs->trans("Default"), 'on');
 								} else {
 									print '<a href="'.$_SERVER["PHP_SELF"].'?action=setdoc&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
@@ -618,8 +582,7 @@ foreach ($dirmodels as $reldir)
 								// Info
 								$htmltooltip = ''.$langs->trans("Name").': '.$module->name;
 								$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
-								if ($module->type == 'pdf')
-								{
+								if ($module->type == 'pdf') {
 									$htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
 								}
 								$htmltooltip .= '<br><br><u>'.$langs->trans("FeaturesSupported").':</u>';
@@ -631,8 +594,7 @@ foreach ($dirmodels as $reldir)
 
 								// Preview
 								print '<td class="center">';
-								if ($module->type == 'pdf')
-								{
+								if ($module->type == 'pdf') {
 									print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'">'.img_object($langs->trans("Preview"), 'bill').'</a>';
 								} else {
 									print img_object($langs->trans("PreviewNotAvailable"), 'generic');
@@ -653,8 +615,7 @@ print '</table><br/>';
 
 
 
-if (empty($conf->global->PROJECT_HIDE_TASKS))
-{
+if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 	/*
 	 * Modeles documents for Task
 	 */
@@ -671,12 +632,10 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 	$sql .= " AND entity = ".$conf->entity;
 
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$i = 0;
 		$num_rows = $db->num_rows($resql);
-		while ($i < $num_rows)
-		{
+		while ($i < $num_rows) {
 			$array = $db->fetch_array($resql);
 			array_push($def, $array[0]);
 			$i++;
@@ -697,30 +656,22 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 
 	clearstatcache();
 
-	foreach ($dirmodels as $reldir)
-	{
-		foreach (array('', '/doc') as $valdir)
-		{
+	foreach ($dirmodels as $reldir) {
+		foreach (array('', '/doc') as $valdir) {
 			$dir = dol_buildpath($reldir."core/modules/project/task/".$valdir);
 
-			if (is_dir($dir))
-			{
+			if (is_dir($dir)) {
 				$handle = opendir($dir);
-				if (is_resource($handle))
-				{
-					while (($file = readdir($handle)) !== false)
-					{
+				if (is_resource($handle)) {
+					while (($file = readdir($handle)) !== false) {
 						$filelist[] = $file;
 					}
 					closedir($handle);
 					arsort($filelist);
 
-					foreach ($filelist as $file)
-					{
-						if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file))
-						{
-							if (file_exists($dir.'/'.$file))
-							{
+					foreach ($filelist as $file) {
+						if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) {
+							if (file_exists($dir.'/'.$file)) {
 								$name = substr($file, 4, dol_strlen($file) - 16);
 								$classname = substr($file, 0, dol_strlen($file) - 12);
 
@@ -728,21 +679,26 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 								$module = new $classname($db);
 
 								$modulequalified = 1;
-								if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0;
-								if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0;
+								if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
+									$modulequalified = 0;
+								}
+								if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
+									$modulequalified = 0;
+								}
 
-								if ($modulequalified)
-								{
+								if ($modulequalified) {
 									print '<tr class="oddeven"><td width="100">';
 									print (empty($module->name) ? $name : $module->name);
 									print "</td><td>\n";
-									if (method_exists($module, 'info')) print $module->info($langs);
-									else print $module->description;
+									if (method_exists($module, 'info')) {
+										print $module->info($langs);
+									} else {
+										print $module->description;
+									}
 									print "</td>\n";
 
 									// Active
-									if (in_array($name, $def))
-									{
+									if (in_array($name, $def)) {
 										print "<td class=\"center\">\n";
 										print '<a href="'.$_SERVER["PHP_SELF"].'?action=deltask&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'">';
 										print img_picto($langs->trans("Enabled"), 'switch_on');
@@ -756,8 +712,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 
 									// Defaut
 									print "<td class=\"center\">";
-									if ($conf->global->PROJECT_TASK_ADDON_PDF == "$name")
-									{
+									if ($conf->global->PROJECT_TASK_ADDON_PDF == "$name") {
 										print img_picto($langs->trans("Default"), 'on');
 									} else {
 										print '<a href="'.$_SERVER["PHP_SELF"].'?action=setdoctask&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
@@ -767,8 +722,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 									// Info
 									$htmltooltip = ''.$langs->trans("Name").': '.$module->name;
 									$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
-									if ($module->type == 'pdf')
-									{
+									if ($module->type == 'pdf') {
 										$htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
 									}
 									$htmltooltip .= '<br><br><u>'.$langs->trans("FeaturesSupported").':</u>';
@@ -780,8 +734,7 @@ if (empty($conf->global->PROJECT_HIDE_TASKS))
 
 									// Preview
 									print '<td class="center">';
-									if ($module->type == 'pdf')
-									{
+									if ($module->type == 'pdf') {
 										print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimentask&module='.$name.'">'.img_object($langs->trans("Preview"), 'bill').'</a>';
 									} else {
 										print img_object($langs->trans("PreviewNotAvailable"), 'generic');
@@ -818,8 +771,7 @@ print '<td width="80">&nbsp;</td></tr>'."\n";
 
 print '<tr class="oddeven">';
 print '<td width="80%">'.$langs->trans("UseSearchToSelectProject").'</td>';
-if (!$conf->use_javascript_ajax)
-{
+if (!$conf->use_javascript_ajax) {
 	print '<td class="nowrap right" colspan="2">';
 	print $langs->trans("NotAvailableWhenAjaxDisabled");
 	print "</td>";

+ 9 - 8
htdocs/projet/admin/project_extrafields.php

@@ -38,13 +38,17 @@ $form = new Form($db);
 // List of supported format
 $tmptype2label = ExtraFields::$type2label;
 $type2label = array('');
-foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val);
+foreach ($tmptype2label as $key => $val) {
+	$type2label[$key] = $langs->transnoentitiesnoconv($val);
+}
 
 $action = GETPOST('action', 'aZ09');
 $attrname = GETPOST('attrname', 'alpha');
 $elementtype = 'projet'; //Must be the $table_element of the class that manage extrafield
 
-if (!$user->admin) accessforbidden();
+if (!$user->admin) {
+	accessforbidden();
+}
 
 
 /*
@@ -77,8 +81,7 @@ print dol_get_fiche_end();
 
 
 // Buttons
-if ($action != 'create' && $action != 'edit')
-{
+if ($action != 'create' && $action != 'edit') {
 	print '<div class="tabsAction">';
 	print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"]."?action=create\">".$langs->trans("NewAttribute").'</a></div>';
 	print "</div>";
@@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit')
 /*                                                                            */
 /* ************************************************************************** */
 
-if ($action == 'create')
-{
+if ($action == 'create') {
 	print "<br>";
 	print load_fiche_titre($langs->trans('NewAttribute'));
 
@@ -104,8 +106,7 @@ if ($action == 'create')
 /* Edition of an optional field                                               */
 /*                                                                            */
 /* ************************************************************************** */
-if ($action == 'edit' && !empty($attrname))
-{
+if ($action == 'edit' && !empty($attrname)) {
 	print "<br>";
 	print load_fiche_titre($langs->trans("FieldEdition", $attrname));
 

+ 9 - 8
htdocs/projet/admin/project_task_extrafields.php

@@ -39,13 +39,17 @@ $form = new Form($db);
 // List of supported format
 $tmptype2label = ExtraFields::$type2label;
 $type2label = array('');
-foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val);
+foreach ($tmptype2label as $key => $val) {
+	$type2label[$key] = $langs->transnoentitiesnoconv($val);
+}
 
 $action = GETPOST('action', 'aZ09');
 $attrname = GETPOST('attrname', 'alpha');
 $elementtype = 'projet_task';
 
-if (!$user->admin) accessforbidden();
+if (!$user->admin) {
+	accessforbidden();
+}
 
 
 /*
@@ -77,8 +81,7 @@ print dol_get_fiche_end();
 
 
 // Buttons
-if ($action != 'create' && $action != 'edit')
-{
+if ($action != 'create' && $action != 'edit') {
 	print '<div class="tabsAction">';
 	print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"]."?action=create\">".$langs->trans("NewAttribute").'</a></div>';
 	print "</div>";
@@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit')
 /*                                                                            */
 /* ************************************************************************** */
 
-if ($action == 'create')
-{
+if ($action == 'create') {
 	print "<br>";
 	print load_fiche_titre($langs->trans('NewAttribute'));
 
@@ -104,8 +106,7 @@ if ($action == 'create')
 /* Edition of an optional field                                               */
 /*                                                                            */
 /* ************************************************************************** */
-if ($action == 'edit' && !empty($attrname))
-{
+if ($action == 'edit' && !empty($attrname)) {
 	print "<br>";
 	print load_fiche_titre($langs->trans("FieldEdition", $attrname));
 

+ 12 - 5
htdocs/projet/admin/website.php

@@ -35,7 +35,9 @@ $langs->loadLangs(array("admin", "members"));
 
 $action = GETPOST('action', 'aZ09');
 
-if (!$user->admin) accessforbidden();
+if (!$user->admin) {
+	accessforbidden();
+}
 
 
 /*
@@ -43,8 +45,11 @@ if (!$user->admin) accessforbidden();
  */
 
 if ($action == 'setPROJECT_ENABLE_PUBLIC') {
-	if (GETPOST('value')) dolibarr_set_const($db, 'PROJECT_ENABLE_PUBLIC', 1, 'chaine', 0, '', $conf->entity);
-	else dolibarr_set_const($db, 'PROJECT_ENABLE_PUBLIC', 0, 'chaine', 0, '', $conf->entity);
+	if (GETPOST('value')) {
+		dolibarr_set_const($db, 'PROJECT_ENABLE_PUBLIC', 1, 'chaine', 0, '', $conf->entity);
+	} else {
+		dolibarr_set_const($db, 'PROJECT_ENABLE_PUBLIC', 0, 'chaine', 0, '', $conf->entity);
+	}
 }
 
 if ($action == 'update') {
@@ -52,9 +57,11 @@ if ($action == 'update') {
 
 	$res = dolibarr_set_const($db, "PROJECT_ENABLE_PUBLIC", $public, 'chaine', 0, '', $conf->entity);
 
-	if (!($res > 0)) $error++;
+	if (!($res > 0)) {
+		$error++;
+	}
 
- 	if (!$error) {
+	if (!$error) {
 		setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
 	} else {
 		setEventMessages($langs->trans("Error"), null, 'errors');

+ 24 - 8
htdocs/projet/ajax/projects.php

@@ -23,13 +23,27 @@
  *       \brief      File to return Ajax response on product list request
  */
 
-if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal
-if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
-if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1');
-if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
-if (!defined('NOREQUIRESOC'))   define('NOREQUIRESOC', '1');
-if (!defined('NOCSRFCHECK'))    define('NOCSRFCHECK', '1');
-if (empty($_GET['keysearch']) && !defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1');
+if (!defined('NOTOKENRENEWAL')) {
+	define('NOTOKENRENEWAL', 1); // Disables token renewal
+}
+if (!defined('NOREQUIREMENU')) {
+	define('NOREQUIREMENU', '1');
+}
+if (!defined('NOREQUIREHTML')) {
+	define('NOREQUIREHTML', '1');
+}
+if (!defined('NOREQUIREAJAX')) {
+	define('NOREQUIREAJAX', '1');
+}
+if (!defined('NOREQUIRESOC')) {
+	define('NOREQUIRESOC', '1');
+}
+if (!defined('NOCSRFCHECK')) {
+	define('NOCSRFCHECK', '1');
+}
+if (empty($_GET['keysearch']) && !defined('NOREQUIREHTML')) {
+	define('NOREQUIREHTML', '1');
+}
 
 require '../../main.inc.php';
 
@@ -49,7 +63,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
 
 top_httphead();
 
-if (empty($htmlname) && !GETPOST('mode', 'aZ09')) return;
+if (empty($htmlname) && !GETPOST('mode', 'aZ09')) {
+	return;
+}
 
 // Mode to get list of projects
 if (!GETPOST('mode', 'aZ09') || GETPOST('mode', 'aZ09') != 'gettasks') {

File diff suppressed because it is too large
+ 217 - 238
htdocs/projet/card.php


+ 135 - 129
htdocs/projet/class/api_projects.class.php

@@ -33,7 +33,7 @@ class Projects extends DolibarrApi
 	/**
 	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
 	 */
-	static $FIELDS = array(
+	public static $FIELDS = array(
 		'ref',
 		'title'
 	);
@@ -110,23 +110,34 @@ class Projects extends DolibarrApi
 
 		// If the internal user must only see his customers, force searching by him
 		$search_sale = 0;
-		if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
+		if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
+			$search_sale = DolibarrApiAccess::$user->id;
+		}
 
 		$sql = "SELECT t.rowid";
-		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
+		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
+			$sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
+		}
 		$sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
 		if ($category > 0) {
 			$sql .= ", ".MAIN_DB_PREFIX."categorie_project as c";
 		}
-		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
+		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
+			$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
+		}
 
 		$sql .= ' WHERE t.entity IN ('.getEntity('project').')';
-		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
-		if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
-		if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
+		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
+			$sql .= " AND t.fk_soc = sc.fk_soc";
+		}
+		if ($socids) {
+			$sql .= " AND t.fk_soc IN (".$socids.")";
+		}
+		if ($search_sale > 0) {
+			$sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
+		}
 		// Insert sale filter
-		if ($search_sale > 0)
-		{
+		if ($search_sale > 0) {
 			$sql .= " AND sc.fk_user = ".$search_sale;
 		}
 		// Select projects of given category
@@ -134,10 +145,8 @@ class Projects extends DolibarrApi
 			$sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_project = t.rowid ";
 		}
 		// Add sql filters
-		if ($sqlfilters)
-		{
-			if (!DolibarrApi::_checkFilters($sqlfilters))
-			{
+		if ($sqlfilters) {
+			if (!DolibarrApi::_checkFilters($sqlfilters)) {
 				throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
 			}
 			$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
@@ -157,8 +166,7 @@ class Projects extends DolibarrApi
 		dol_syslog("API Rest request");
 		$result = $this->db->query($sql);
 
-		if ($result)
-		{
+		if ($result) {
 			$num = $this->db->num_rows($result);
 			$min = min($num, ($limit <= 0 ? $num : $limit));
 			$i = 0;
@@ -197,12 +205,12 @@ class Projects extends DolibarrApi
 			$this->project->$field = $value;
 		}
 		/*if (isset($request_data["lines"])) {
-          $lines = array();
-          foreach ($request_data["lines"] as $line) {
-            array_push($lines, (object) $line);
-          }
-          $this->project->lines = $lines;
-        }*/
+		  $lines = array();
+		  foreach ($request_data["lines"] as $line) {
+			array_push($lines, (object) $line);
+		  }
+		  $this->project->lines = $lines;
+		}*/
 		if ($this->project->create(DolibarrApiAccess::$user) < 0) {
 			throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors));
 		}
@@ -236,14 +244,11 @@ class Projects extends DolibarrApi
 		}
 		$this->project->getLinesArray(DolibarrApiAccess::$user);
 		$result = array();
-		foreach ($this->project->lines as $line)      // $line is a task
-		{
-			if ($includetimespent == 1)
-			{
+		foreach ($this->project->lines as $line) {      // $line is a task
+			if ($includetimespent == 1) {
 				$timespent = $line->getSummaryOfTimeSpent(0);
 			}
-			if ($includetimespent == 1)
-			{
+			if ($includetimespent == 1) {
 				// TODO
 				// Add class for timespent records and loop and fill $line->lines with records of timespent
 			}
@@ -283,8 +288,7 @@ class Projects extends DolibarrApi
 		require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
 		$taskstatic = new Task($this->db);
 		$userp = DolibarrApiAccess::$user;
-		if ($userid > 0)
-		{
+		if ($userid > 0) {
 			$userp = new User($this->db);
 			$userp->fetch($userid);
 		}
@@ -308,56 +312,56 @@ class Projects extends DolibarrApi
 	 * @return int
 	 */
 	/*
-    public function postLine($id, $request_data = null)
-    {
-        if(! DolibarrApiAccess::$user->rights->projet->creer) {
-            throw new RestException(401);
-        }
-
-        $result = $this->project->fetch($id);
-        if( ! $result ) {
-            throw new RestException(404, 'Project not found');
-        }
-
-        if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
-            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
-        }
-        $request_data = (object) $request_data;
-        $updateRes = $this->project->addline(
-                        $request_data->desc,
-                        $request_data->subprice,
-                        $request_data->qty,
-                        $request_data->tva_tx,
-                        $request_data->localtax1_tx,
-                        $request_data->localtax2_tx,
-                        $request_data->fk_product,
-                        $request_data->remise_percent,
-                        $request_data->info_bits,
-                        $request_data->fk_remise_except,
-                        'HT',
-                        0,
-                        $request_data->date_start,
-                        $request_data->date_end,
-                        $request_data->product_type,
-                        $request_data->rang,
-                        $request_data->special_code,
-                        $fk_parent_line,
-                        $request_data->fk_fournprice,
-                        $request_data->pa_ht,
-                        $request_data->label,
-                        $request_data->array_options,
-                        $request_data->fk_unit,
-                        $this->element,
-                        $request_data->id
-        );
-
-        if ($updateRes > 0) {
-            return $updateRes;
-
-        }
-        return false;
-    }
-    */
+	public function postLine($id, $request_data = null)
+	{
+		if(! DolibarrApiAccess::$user->rights->projet->creer) {
+			throw new RestException(401);
+		}
+
+		$result = $this->project->fetch($id);
+		if( ! $result ) {
+			throw new RestException(404, 'Project not found');
+		}
+
+		if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+		}
+		$request_data = (object) $request_data;
+		$updateRes = $this->project->addline(
+						$request_data->desc,
+						$request_data->subprice,
+						$request_data->qty,
+						$request_data->tva_tx,
+						$request_data->localtax1_tx,
+						$request_data->localtax2_tx,
+						$request_data->fk_product,
+						$request_data->remise_percent,
+						$request_data->info_bits,
+						$request_data->fk_remise_except,
+						'HT',
+						0,
+						$request_data->date_start,
+						$request_data->date_end,
+						$request_data->product_type,
+						$request_data->rang,
+						$request_data->special_code,
+						$fk_parent_line,
+						$request_data->fk_fournprice,
+						$request_data->pa_ht,
+						$request_data->label,
+						$request_data->array_options,
+						$request_data->fk_unit,
+						$this->element,
+						$request_data->id
+		);
+
+		if ($updateRes > 0) {
+			return $updateRes;
+
+		}
+		return false;
+	}
+	*/
 
 	/**
 	 * Update a task to given project
@@ -371,52 +375,52 @@ class Projects extends DolibarrApi
 	 * @return object
 	 */
 	/*
-    public function putLine($id, $lineid, $request_data = null)
-    {
-        if(! DolibarrApiAccess::$user->rights->projet->creer) {
-            throw new RestException(401);
-        }
-
-        $result = $this->project->fetch($id);
-        if( ! $result ) {
-            throw new RestException(404, 'Project not found');
-        }
-
-        if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
-            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
-        }
-        $request_data = (object) $request_data;
-        $updateRes = $this->project->updateline(
-                        $lineid,
-                        $request_data->desc,
-                        $request_data->subprice,
-                        $request_data->qty,
-                        $request_data->remise_percent,
-                        $request_data->tva_tx,
-                        $request_data->localtax1_tx,
-                        $request_data->localtax2_tx,
-                        'HT',
-                        $request_data->info_bits,
-                        $request_data->date_start,
-                        $request_data->date_end,
-                        $request_data->product_type,
-                        $request_data->fk_parent_line,
-                        0,
-                        $request_data->fk_fournprice,
-                        $request_data->pa_ht,
-                        $request_data->label,
-                        $request_data->special_code,
-                        $request_data->array_options,
-                        $request_data->fk_unit
-        );
-
-        if ($updateRes > 0) {
-            $result = $this->get($id);
-            unset($result->line);
-            return $this->_cleanObjectDatas($result);
-        }
-        return false;
-    }*/
+	public function putLine($id, $lineid, $request_data = null)
+	{
+		if(! DolibarrApiAccess::$user->rights->projet->creer) {
+			throw new RestException(401);
+		}
+
+		$result = $this->project->fetch($id);
+		if( ! $result ) {
+			throw new RestException(404, 'Project not found');
+		}
+
+		if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+		}
+		$request_data = (object) $request_data;
+		$updateRes = $this->project->updateline(
+						$lineid,
+						$request_data->desc,
+						$request_data->subprice,
+						$request_data->qty,
+						$request_data->remise_percent,
+						$request_data->tva_tx,
+						$request_data->localtax1_tx,
+						$request_data->localtax2_tx,
+						'HT',
+						$request_data->info_bits,
+						$request_data->date_start,
+						$request_data->date_end,
+						$request_data->product_type,
+						$request_data->fk_parent_line,
+						0,
+						$request_data->fk_fournprice,
+						$request_data->pa_ht,
+						$request_data->label,
+						$request_data->special_code,
+						$request_data->array_options,
+						$request_data->fk_unit
+		);
+
+		if ($updateRes > 0) {
+			$result = $this->get($id);
+			unset($result->line);
+			return $this->_cleanObjectDatas($result);
+		}
+		return false;
+	}*/
 
 
 
@@ -443,12 +447,13 @@ class Projects extends DolibarrApi
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
 		}
 		foreach ($request_data as $field => $value) {
-			if ($field == 'id') continue;
+			if ($field == 'id') {
+				continue;
+			}
 			$this->project->$field = $value;
 		}
 
-		if ($this->project->update(DolibarrApiAccess::$user) >= 0)
-		{
+		if ($this->project->update(DolibarrApiAccess::$user) >= 0) {
 			return $this->get($id);
 		} else {
 			throw new RestException(500, $this->project->error);
@@ -600,8 +605,9 @@ class Projects extends DolibarrApi
 	{
 		$object = array();
 		foreach (self::$FIELDS as $field) {
-			if (!isset($data[$field]))
+			if (!isset($data[$field])) {
 				throw new RestException(400, "$field field missing");
+			}
 			$object[$field] = $data[$field];
 		}
 		return $object;

+ 171 - 164
htdocs/projet/class/api_tasks.class.php

@@ -33,7 +33,7 @@ class Tasks extends DolibarrApi
 	/**
 	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
 	 */
-	static $FIELDS = array(
+	public static $FIELDS = array(
 		'ref',
 		'label',
 		'fk_project'
@@ -80,12 +80,10 @@ class Tasks extends DolibarrApi
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
 		}
 
-		if ($includetimespent == 1)
-		{
+		if ($includetimespent == 1) {
 			$timespent = $this->task->getSummaryOfTimeSpent(0);
 		}
-		if ($includetimespent == 1)
-		{
+		if ($includetimespent == 1) {
 			// TODO
 			// Add class for timespent records and loop and fill $line->lines with records of timespent
 		}
@@ -118,28 +116,37 @@ class Tasks extends DolibarrApi
 
 		// If the internal user must only see his customers, force searching by him
 		$search_sale = 0;
-		if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
+		if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
+			$search_sale = DolibarrApiAccess::$user->id;
+		}
 
 		$sql = "SELECT t.rowid";
-		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
+		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
+			$sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
+		}
 		$sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t";
 
-		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
+		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
+			$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
+		}
 
 		$sql .= ' WHERE t.entity IN ('.getEntity('project').')';
-		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
-		if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
-		if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
+		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
+			$sql .= " AND t.fk_soc = sc.fk_soc";
+		}
+		if ($socids) {
+			$sql .= " AND t.fk_soc IN (".$socids.")";
+		}
+		if ($search_sale > 0) {
+			$sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
+		}
 		// Insert sale filter
-		if ($search_sale > 0)
-		{
+		if ($search_sale > 0) {
 			$sql .= " AND sc.fk_user = ".$search_sale;
 		}
 		// Add sql filters
-		if ($sqlfilters)
-		{
-			if (!DolibarrApi::_checkFilters($sqlfilters))
-			{
+		if ($sqlfilters) {
+			if (!DolibarrApi::_checkFilters($sqlfilters)) {
 				throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
 			}
 			$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
@@ -148,8 +155,7 @@ class Tasks extends DolibarrApi
 
 		$sql .= $this->db->order($sortfield, $sortorder);
 		if ($limit) {
-			if ($page < 0)
-			{
+			if ($page < 0) {
 				$page = 0;
 			}
 			$offset = $limit * $page;
@@ -160,13 +166,11 @@ class Tasks extends DolibarrApi
 		dol_syslog("API Rest request");
 		$result = $this->db->query($sql);
 
-		if ($result)
-		{
+		if ($result) {
 			$num = $this->db->num_rows($result);
 			$min = min($num, ($limit <= 0 ? $num : $limit));
 			$i = 0;
-			while ($i < $min)
-			{
+			while ($i < $min) {
 				$obj = $this->db->fetch_object($result);
 				$task_static = new Task($this->db);
 				if ($task_static->fetch($obj->rowid)) {
@@ -201,12 +205,12 @@ class Tasks extends DolibarrApi
 			$this->task->$field = $value;
 		}
 		/*if (isset($request_data["lines"])) {
-          $lines = array();
-          foreach ($request_data["lines"] as $line) {
-            array_push($lines, (object) $line);
-          }
-          $this->project->lines = $lines;
-        }*/
+		  $lines = array();
+		  foreach ($request_data["lines"] as $line) {
+			array_push($lines, (object) $line);
+		  }
+		  $this->project->lines = $lines;
+		}*/
 		if ($this->task->create(DolibarrApiAccess::$user) < 0) {
 			throw new RestException(500, "Error creating task", array_merge(array($this->task->error), $this->task->errors));
 		}
@@ -223,38 +227,38 @@ class Tasks extends DolibarrApi
 	//  * @url	GET {id}/tasks
 	//  */
 	/*
-    public function getLines($id, $includetimespent=0)
-    {
-        if(! DolibarrApiAccess::$user->rights->projet->lire) {
-            throw new RestException(401);
-        }
-
-        $result = $this->project->fetch($id);
-        if( ! $result ) {
-            throw new RestException(404, 'Project not found');
-        }
-
-        if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
-            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
-        }
-        $this->project->getLinesArray(DolibarrApiAccess::$user);
-        $result = array();
-        foreach ($this->project->lines as $line)      // $line is a task
-        {
-            if ($includetimespent == 1)
-            {
-                $timespent = $line->getSummaryOfTimeSpent(0);
-            }
-            if ($includetimespent == 1)
-            {
-                // TODO
-                // Add class for timespent records and loop and fill $line->lines with records of timespent
-            }
-            array_push($result,$this->_cleanObjectDatas($line));
-        }
-        return $result;
-    }
-    */
+	public function getLines($id, $includetimespent=0)
+	{
+		if(! DolibarrApiAccess::$user->rights->projet->lire) {
+			throw new RestException(401);
+		}
+
+		$result = $this->project->fetch($id);
+		if( ! $result ) {
+			throw new RestException(404, 'Project not found');
+		}
+
+		if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+		}
+		$this->project->getLinesArray(DolibarrApiAccess::$user);
+		$result = array();
+		foreach ($this->project->lines as $line)      // $line is a task
+		{
+			if ($includetimespent == 1)
+			{
+				$timespent = $line->getSummaryOfTimeSpent(0);
+			}
+			if ($includetimespent == 1)
+			{
+				// TODO
+				// Add class for timespent records and loop and fill $line->lines with records of timespent
+			}
+			array_push($result,$this->_cleanObjectDatas($line));
+		}
+		return $result;
+	}
+	*/
 
 	/**
 	 * Get roles a user is assigned to a task with
@@ -284,8 +288,7 @@ class Tasks extends DolibarrApi
 		}
 
 		$usert = DolibarrApiAccess::$user;
-		if ($userid > 0)
-		{
+		if ($userid > 0) {
 			$usert = new User($this->db);
 			$usert->fetch($userid);
 		}
@@ -309,56 +312,56 @@ class Tasks extends DolibarrApi
 	//  * @return int
 	//  */
 	/*
-    public function postLine($id, $request_data = null)
-    {
-        if(! DolibarrApiAccess::$user->rights->projet->creer) {
-            throw new RestException(401);
-        }
-
-        $result = $this->project->fetch($id);
-        if( ! $result ) {
-            throw new RestException(404, 'Project not found');
-        }
-
-        if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
-            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
-        }
-        $request_data = (object) $request_data;
-        $updateRes = $this->project->addline(
-                        $request_data->desc,
-                        $request_data->subprice,
-                        $request_data->qty,
-                        $request_data->tva_tx,
-                        $request_data->localtax1_tx,
-                        $request_data->localtax2_tx,
-                        $request_data->fk_product,
-                        $request_data->remise_percent,
-                        $request_data->info_bits,
-                        $request_data->fk_remise_except,
-                        'HT',
-                        0,
-                        $request_data->date_start,
-                        $request_data->date_end,
-                        $request_data->product_type,
-                        $request_data->rang,
-                        $request_data->special_code,
-                        $fk_parent_line,
-                        $request_data->fk_fournprice,
-                        $request_data->pa_ht,
-                        $request_data->label,
-                        $request_data->array_options,
-                        $request_data->fk_unit,
-                        $this->element,
-                        $request_data->id
-        );
-
-        if ($updateRes > 0) {
-            return $updateRes;
-
-        }
-        return false;
-    }
-    */
+	public function postLine($id, $request_data = null)
+	{
+		if(! DolibarrApiAccess::$user->rights->projet->creer) {
+			throw new RestException(401);
+		}
+
+		$result = $this->project->fetch($id);
+		if( ! $result ) {
+			throw new RestException(404, 'Project not found');
+		}
+
+		if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+		}
+		$request_data = (object) $request_data;
+		$updateRes = $this->project->addline(
+						$request_data->desc,
+						$request_data->subprice,
+						$request_data->qty,
+						$request_data->tva_tx,
+						$request_data->localtax1_tx,
+						$request_data->localtax2_tx,
+						$request_data->fk_product,
+						$request_data->remise_percent,
+						$request_data->info_bits,
+						$request_data->fk_remise_except,
+						'HT',
+						0,
+						$request_data->date_start,
+						$request_data->date_end,
+						$request_data->product_type,
+						$request_data->rang,
+						$request_data->special_code,
+						$fk_parent_line,
+						$request_data->fk_fournprice,
+						$request_data->pa_ht,
+						$request_data->label,
+						$request_data->array_options,
+						$request_data->fk_unit,
+						$this->element,
+						$request_data->id
+		);
+
+		if ($updateRes > 0) {
+			return $updateRes;
+
+		}
+		return false;
+	}
+	*/
 
 	// /**
 	//  * Update a task to given project
@@ -372,52 +375,52 @@ class Tasks extends DolibarrApi
 	//  * @return object
 	//  */
 	/*
-    public function putLine($id, $lineid, $request_data = null)
-    {
-        if(! DolibarrApiAccess::$user->rights->projet->creer) {
-            throw new RestException(401);
-        }
-
-        $result = $this->project->fetch($id);
-        if( ! $result ) {
-            throw new RestException(404, 'Project not found');
-        }
-
-        if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
-            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
-        }
-        $request_data = (object) $request_data;
-        $updateRes = $this->project->updateline(
-                        $lineid,
-                        $request_data->desc,
-                        $request_data->subprice,
-                        $request_data->qty,
-                        $request_data->remise_percent,
-                        $request_data->tva_tx,
-                        $request_data->localtax1_tx,
-                        $request_data->localtax2_tx,
-                        'HT',
-                        $request_data->info_bits,
-                        $request_data->date_start,
-                        $request_data->date_end,
-                        $request_data->product_type,
-                        $request_data->fk_parent_line,
-                        0,
-                        $request_data->fk_fournprice,
-                        $request_data->pa_ht,
-                        $request_data->label,
-                        $request_data->special_code,
-                        $request_data->array_options,
-                        $request_data->fk_unit
-        );
-
-        if ($updateRes > 0) {
-            $result = $this->get($id);
-            unset($result->line);
-            return $this->_cleanObjectDatas($result);
-        }
-        return false;
-    }*/
+	public function putLine($id, $lineid, $request_data = null)
+	{
+		if(! DolibarrApiAccess::$user->rights->projet->creer) {
+			throw new RestException(401);
+		}
+
+		$result = $this->project->fetch($id);
+		if( ! $result ) {
+			throw new RestException(404, 'Project not found');
+		}
+
+		if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+		}
+		$request_data = (object) $request_data;
+		$updateRes = $this->project->updateline(
+						$lineid,
+						$request_data->desc,
+						$request_data->subprice,
+						$request_data->qty,
+						$request_data->remise_percent,
+						$request_data->tva_tx,
+						$request_data->localtax1_tx,
+						$request_data->localtax2_tx,
+						'HT',
+						$request_data->info_bits,
+						$request_data->date_start,
+						$request_data->date_end,
+						$request_data->product_type,
+						$request_data->fk_parent_line,
+						0,
+						$request_data->fk_fournprice,
+						$request_data->pa_ht,
+						$request_data->label,
+						$request_data->special_code,
+						$request_data->array_options,
+						$request_data->fk_unit
+		);
+
+		if ($updateRes > 0) {
+			$result = $this->get($id);
+			unset($result->line);
+			return $this->_cleanObjectDatas($result);
+		}
+		return false;
+	}*/
 
 
 	/**
@@ -443,12 +446,13 @@ class Tasks extends DolibarrApi
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
 		}
 		foreach ($request_data as $field => $value) {
-			if ($field == 'id') continue;
+			if ($field == 'id') {
+				continue;
+			}
 			$this->task->$field = $value;
 		}
 
-		if ($this->task->update(DolibarrApiAccess::$user) > 0)
-		{
+		if ($this->task->update(DolibarrApiAccess::$user) > 0) {
 			return $this->get($id);
 		} else {
 			throw new RestException(500, $this->task->error);
@@ -519,7 +523,9 @@ class Tasks extends DolibarrApi
 		}
 
 		$uid = $user_id;
-		if (empty($uid)) $uid = DolibarrApiAccess::$user->id;
+		if (empty($uid)) {
+			$uid = DolibarrApiAccess::$user->id;
+		}
 
 		$newdate = dol_stringtotime($date, 1);
 		$this->task->timespent_date = $newdate;
@@ -607,8 +613,9 @@ class Tasks extends DolibarrApi
 	{
 		$object = array();
 		foreach (self::$FIELDS as $field) {
-			if (!isset($data[$field]))
+			if (!isset($data[$field])) {
 				throw new RestException(400, "$field field missing");
+			}
 			$object[$field] = $data[$field];
 		}
 		return $object;

File diff suppressed because it is too large
+ 236 - 248
htdocs/projet/class/project.class.php


+ 53 - 41
htdocs/projet/class/projectstats.class.php

@@ -85,21 +85,23 @@ class ProjectStats extends Stats
 			$other = 0;
 			while ($i < $num) {
 				$row = $this->db->fetch_row($resql);
-				if ($i < $limit || $num == $limit)
-				{
+				if ($i < $limit || $num == $limit) {
 					$label = (($langs->trans("OppStatus".$row[2]) != "OppStatus".$row[2]) ? $langs->trans("OppStatus".$row[2]) : $row[2]);
 					$result[$i] = array(
 					$label.' ('.price(price2num($row[0], 'MT'), 1, $langs, 1, -1, -1, $conf->currency).')',
 					$row[0]
 					);
-				} else $other += $row[1];
+				} else {
+					$other += $row[1];
+				}
 					$i++;
 			}
-			if ($num > $limit)
+			if ($num > $limit) {
 				$result[$i] = array(
 				$langs->transnoentitiesnoconv("Other"),
 				$other
 				);
+			}
 				$this->db->free($resql);
 		} else {
 			$this->error = "Error ".$this->db->lasterror();
@@ -156,25 +158,34 @@ class ProjectStats extends Stats
 		// Get list of project id allowed to user (in a string list separated by coma)
 		$object = new Project($this->db);
 		$projectsListId = '';
-		if (!$user->rights->projet->all->lire) $projectsListId = $object->getProjectsAuthorizedForUser($user, 0, 1, $user->socid);
+		if (!$user->rights->projet->all->lire) {
+			$projectsListId = $object->getProjectsAuthorizedForUser($user, 0, 1, $user->socid);
+		}
 
 		$sqlwhere[] = ' t.entity IN ('.getEntity('project').')';
 
-		if (!empty($this->userid))
+		if (!empty($this->userid)) {
 			$sqlwhere[] = ' t.fk_user_resp='.$this->userid;
+		}
 
 		// Forced filter on socid is similar to forced filter on project. TODO Use project assignement to allow to not use filter on project
-		if (!empty($this->socid))
+		if (!empty($this->socid)) {
 			$sqlwhere[] = ' t.fk_soc='.$this->socid;
-		if (!empty($this->year) && empty($this->yearmonth))
+		}
+		if (!empty($this->year) && empty($this->yearmonth)) {
 			$sqlwhere[] = " date_format(t.datec,'%Y')='".$this->db->escape($this->year)."'";
-		if (!empty($this->yearmonth))
+		}
+		if (!empty($this->yearmonth)) {
 			$sqlwhere[] = " t.datec BETWEEN '".$this->db->idate(dol_get_first_day($this->yearmonth))."' AND '".$this->db->idate(dol_get_last_day($this->yearmonth))."'";
+		}
 
-		if (!empty($this->status))
+		if (!empty($this->status)) {
 			$sqlwhere[] = " t.fk_opp_status IN (".$this->status.")";
+		}
 
-		if (!$user->rights->projet->all->lire) $sqlwhere[] = " t.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users
+		if (!$user->rights->projet->all->lire) {
+			$sqlwhere[] = " t.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users
+		}
 
 		if (count($sqlwhere) > 0) {
 			$sqlwhere_str = ' WHERE '.implode(' AND ', $sqlwhere);
@@ -254,13 +265,14 @@ class ProjectStats extends Stats
 	{
 		global $conf, $user, $langs;
 
-		if ($startyear > $endyear) return -1;
+		if ($startyear > $endyear) {
+			return -1;
+		}
 
 		$datay = array();
 
 		// Search into cache
-		if (!empty($cachedelay))
-		{
+		if (!empty($cachedelay)) {
 			include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 			include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
 		}
@@ -271,11 +283,9 @@ class ProjectStats extends Stats
 		$nowgmt = dol_now();
 
 		$foundintocache = 0;
-		if ($cachedelay > 0)
-		{
+		if ($cachedelay > 0) {
 			$filedate = dol_filemtime($newpathofdestfile);
-			if ($filedate >= ($nowgmt - $cachedelay))
-			{
+			if ($filedate >= ($nowgmt - $cachedelay)) {
 				$foundintocache = 1;
 
 				$this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
@@ -285,26 +295,22 @@ class ProjectStats extends Stats
 		}
 
 		// Load file into $data
-		if ($foundintocache)    // Cache file found and is not too old
-		{
+		if ($foundintocache) {    // Cache file found and is not too old
 			dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
 			$data = json_decode(file_get_contents($newpathofdestfile), true);
 		} else {
 			$year = $startyear;
-			while ($year <= $endyear)
-			{
+			while ($year <= $endyear) {
 				$datay[$year] = $this->getWeightedAmountByMonth($year, $wonlostfilter);
 				$year++;
 			}
 
 			$data = array();
 			// $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
-			for ($i = 0; $i < 12; $i++)
-			{
+			for ($i = 0; $i < 12; $i++) {
 				$data[$i][] = $datay[$endyear][$i][0]; // set label
 				$year = $startyear;
-				while ($year <= $endyear)
-				{
+				while ($year <= $endyear) {
 					$data[$i][] = $datay[$year][$i][1]; // set yval for x=i
 					$year++;
 				}
@@ -312,18 +318,22 @@ class ProjectStats extends Stats
 		}
 
 		// Save cache file
-		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
-		{
+		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
 			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
-			if (!dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
+			if (!dol_is_dir($conf->user->dir_temp)) {
+				dol_mkdir($conf->user->dir_temp);
+			}
 			$fp = fopen($newpathofdestfile, 'w');
-			if ($fp)
-			{
+			if ($fp) {
 				fwrite($fp, json_encode($data));
 				fclose($fp);
-				if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
+				if (!empty($conf->global->MAIN_UMASK)) {
+					$newmask = $conf->global->MAIN_UMASK;
+				}
 				@chmod($newpathofdestfile, octdec($newmask));
-			} else dol_syslog("Failed to write cache file", LOG_ERR);
+			} else {
+				dol_syslog("Failed to write cache file", LOG_ERR);
+			}
 			$this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
 		}
 
@@ -371,13 +381,14 @@ class ProjectStats extends Stats
 	{
 		global $conf, $user, $langs;
 
-		if ($startyear > $endyear) return -1;
+		if ($startyear > $endyear) {
+			return -1;
+		}
 
 		$datay = array();
 
 		// Search into cache
-		if (!empty($cachedelay))
-		{
+		if (!empty($cachedelay)) {
 			include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 			include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
 		}
@@ -400,8 +411,7 @@ class ProjectStats extends Stats
 		}
 
 		// Load file into $data
-		if ($foundintocache) // Cache file found and is not too old
-		{
+		if ($foundintocache) { // Cache file found and is not too old
 			dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
 			$data = json_decode(file_get_contents($newpathofdestfile), true);
 		} else {
@@ -426,13 +436,15 @@ class ProjectStats extends Stats
 		// Save cache file
 		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == - 1)) {
 			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
-			if (!dol_is_dir($conf->user->dir_temp))
+			if (!dol_is_dir($conf->user->dir_temp)) {
 				dol_mkdir($conf->user->dir_temp);
+			}
 			$fp = fopen($newpathofdestfile, 'w');
 			fwrite($fp, json_encode($data));
 			fclose($fp);
-			if (!empty($conf->global->MAIN_UMASK))
+			if (!empty($conf->global->MAIN_UMASK)) {
 				$newmask = $conf->global->MAIN_UMASK;
+			}
 			@chmod($newpathofdestfile, octdec($newmask));
 
 			$this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
@@ -483,7 +495,7 @@ class ProjectStats extends Stats
 
 		$res = array();
 
-		foreach ($res_total as $key=>$total_row) {
+		foreach ($res_total as $key => $total_row) {
 			//var_dump($total_row);
 			if (!empty($total_row[1])) {
 				$res[$key] = array($total_row[0], (100 * $res_only_wined[$key][1]) / $total_row[1]);

File diff suppressed because it is too large
+ 287 - 248
htdocs/projet/class/task.class.php


+ 22 - 12
htdocs/projet/class/taskstats.class.php

@@ -59,8 +59,9 @@ class TaskStats extends Stats
 		$sql = "SELECT";
 		$sql .= " COUNT(t.rowid), t.priority";
 		$sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t INNER JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = t.fk_projet";
-		if (!$user->rights->societe->client->voir && !$user->soc_id)
+		if (!$user->rights->societe->client->voir && !$user->soc_id) {
 			$sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=".$user->id;
+		}
 		$sql .= $this->buildWhere();
 		//$sql .= " AND t.fk_statut <> 0";     // We want historic also, so all task not draft
 		$sql .= " GROUP BY t.priority";
@@ -76,20 +77,22 @@ class TaskStats extends Stats
 			$other = 0;
 			while ($i < $num) {
 				$row = $this->db->fetch_row($resql);
-				if ($i < $limit || $num == $limit)
-				{
+				if ($i < $limit || $num == $limit) {
 					$result[$i] = array(
 						$row[1],
 						$row[0]
 					);
-				} else $other += $row[1];
+				} else {
+					$other += $row[1];
+				}
 				$i++;
 			}
-			if ($num > $limit)
+			if ($num > $limit) {
 				$result[$i] = array(
 						$langs->transnoentitiesnoconv("Other"),
 						$other
 				);
+			}
 			$this->db->free($resql);
 		} else {
 			$this->error = "Error ".$this->db->lasterror();
@@ -115,8 +118,9 @@ class TaskStats extends Stats
 
 		$sql = "SELECT date_format(t.datec,'%Y') as year, COUNT(t.rowid) as nb";
 		$sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t INNER JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = t.fk_projet";
-		if (!$user->rights->societe->client->voir && !$user->soc_id)
+		if (!$user->rights->societe->client->voir && !$user->soc_id) {
 			$sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=".$user->id;
+		}
 		$sql .= $this->buildWhere();
 		$sql .= " GROUP BY year";
 		$sql .= $this->db->order('year', 'DESC');
@@ -137,18 +141,23 @@ class TaskStats extends Stats
 
 		$sqlwhere[] = ' t.entity IN ('.getEntity('project').')';
 
-		if (!empty($this->userid))
+		if (!empty($this->userid)) {
 			$sqlwhere[] = ' t.fk_user_resp='.$this->userid;
+		}
 		// Forced filter on socid is similar to forced filter on project. TODO Use project assignement to allow to not use filter on project
-		if (!empty($this->socid))
+		if (!empty($this->socid)) {
 			$sqlwhere[] = ' p.fk_soc='.$this->socid; // Link on thirdparty is on project, not on task
-		if (!empty($this->year) && empty($this->yearmonth))
+		}
+		if (!empty($this->year) && empty($this->yearmonth)) {
 			$sqlwhere[] = " date_format(t.datec,'%Y')='".$this->db->escape($this->year)."'";
-		if (!empty($this->yearmonth))
+		}
+		if (!empty($this->yearmonth)) {
 			$sqlwhere[] = " t.datec BETWEEN '".$this->db->idate(dol_get_first_day($this->yearmonth))."' AND '".$this->db->idate(dol_get_last_day($this->yearmonth))."'";
+		}
 
-		if (!empty($this->status))
+		if (!empty($this->status)) {
 			$sqlwhere[] = " t.priority IN (".$this->priority.")";
+		}
 
 		if (count($sqlwhere) > 0) {
 			$sqlwhere_str = ' WHERE '.implode(' AND ', $sqlwhere);
@@ -172,8 +181,9 @@ class TaskStats extends Stats
 
 		$sql = "SELECT date_format(t.datec,'%m') as dm, COUNT(t.rowid) as nb";
 		$sql .= " FROM ".MAIN_DB_PREFIX."projet_task as t INNER JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = t.fk_projet";
-		if (!$user->rights->societe->client->voir && !$user->soc_id)
+		if (!$user->rights->societe->client->voir && !$user->soc_id) {
 			$sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc=t.fk_soc AND sc.fk_user=".$user->id;
+		}
 		$sql .= $this->buildWhere();
 		$sql .= " GROUP BY dm";
 		$sql .= $this->db->order('dm', 'DESC');

+ 18 - 8
htdocs/projet/comment.php

@@ -50,7 +50,9 @@ $planned_workload = ((GETPOST('planned_workloadhour', 'int') != '' || GETPOST('p
 // Security check
 $socid = 0;
 //if ($user->socid > 0) $socid = $user->socid;    // For external user, no check is done on company because readability is managed by public status of project and assignement.
-if (!$user->rights->projet->lire) accessforbidden();
+if (!$user->rights->projet->lire) {
+	accessforbidden();
+}
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 $hookmanager->initHooks(array('projectcard', 'globalcard'));
@@ -62,12 +64,13 @@ $object = new Project($db);
 $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Load object
-if ($id > 0 || !empty($ref))
-{
+if ($id > 0 || !empty($ref)) {
 	$ret = $object->fetch($id, $ref); // If we create project, ref may be defined into POST but record does not yet exists into database
 	if ($ret > 0) {
 		$object->fetch_thirdparty();
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+			$object->fetchComments();
+		}
 		$id = $object->id;
 	}
 }
@@ -122,20 +125,27 @@ print '<table class="border centpercent">';
 
 // Visibility
 print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-if ($object->public) print $langs->trans('SharedProject');
-else print $langs->trans('PrivateProject');
+if ($object->public) {
+	print $langs->trans('SharedProject');
+} else {
+	print $langs->trans('PrivateProject');
+}
 print '</td></tr>';
 
 // Date start - end
 print '<tr><td>'.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").'</td><td>';
 print dol_print_date($object->date_start, 'day');
 $end = dol_print_date($object->date_end, 'day');
-if ($end) print ' - '.$end;
+if ($end) {
+	print ' - '.$end;
+}
 print '</td></tr>';
 
 // Budget
 print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+if (strcmp($object->budget_amount, '')) {
+	print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+}
 print '</td></tr>';
 
 // Other attributes

+ 61 - 51
htdocs/projet/contact.php

@@ -28,7 +28,9 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
-if ($conf->categorie->enabled) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; }
+if ($conf->categorie->enabled) {
+	require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
+}
 
 // Load translation files required by the page
 $langs->loadLangs(array('projects', 'companies'));
@@ -45,7 +47,9 @@ $mine   = GETPOST('mode') == 'mine' ? 1 : 0;
 $object = new Project($db);
 
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
-if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+	$object->fetchComments();
+}
 
 // Security check
 $socid = 0;
@@ -140,8 +144,7 @@ if ($action == 'addcontact') {
 }
 
 // Add new contact
-if ($action == 'addcontact_confirm' && $user->rights->projet->creer)
-{
+if ($action == 'addcontact_confirm' && $user->rights->projet->creer) {
 	$contactid = (GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int'));
 	$typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
 
@@ -154,15 +157,13 @@ if ($action == 'addcontact_confirm' && $user->rights->projet->creer)
 	$result = 0;
 	$result = $object->fetch($id);
 
-	if (!$error && $result > 0 && $id > 0)
-	{
-  		$result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
+	if (!$error && $result > 0 && $id > 0) {
+		$result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
 
-  		if ($result == 0) {
-  			$langs->load("errors");
-  			setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
-  		}
-  		elseif ($result < 0) {
+		if ($result == 0) {
+			$langs->load("errors");
+			setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
+		} elseif ($result < 0) {
 			if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
 				$langs->load("errors");
 				setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
@@ -171,7 +172,7 @@ if ($action == 'addcontact_confirm' && $user->rights->projet->creer)
 			}
 		}
 
-  		$affecttotask=GETPOST('tasksavailable', 'intcomma');
+		$affecttotask=GETPOST('tasksavailable', 'intcomma');
 		if (!empty($affecttotask)) {
 			require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
 			$task_to_affect = explode(',', $affecttotask);
@@ -199,18 +200,15 @@ if ($action == 'addcontact_confirm' && $user->rights->projet->creer)
 		}
 	}
 
-	if ($result >= 0)
-	{
+	if ($result >= 0) {
 		header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 		exit;
 	}
 }
 
 // Change contact's status
-if ($action == 'swapstatut' && $user->rights->projet->creer)
-{
-	if ($object->fetch($id))
-	{
+if ($action == 'swapstatut' && $user->rights->projet->creer) {
+	if ($object->fetch($id)) {
 		$result = $object->swapContactStatus(GETPOST('ligne', 'int'));
 	} else {
 		dol_print_error($db);
@@ -218,13 +216,11 @@ if ($action == 'swapstatut' && $user->rights->projet->creer)
 }
 
 // Delete a contact
-if (($action == 'deleteline' || $action == 'deletecontact') && $user->rights->projet->creer)
-{
+if (($action == 'deleteline' || $action == 'deletecontact') && $user->rights->projet->creer) {
 	$object->fetch($id);
 	$result = $object->delete_contact(GETPOST("lineid"));
 
-	if ($result >= 0)
-	{
+	if ($result >= 0) {
 		header("Location: contact.php?id=".$object->id);
 		exit;
 	} else {
@@ -239,7 +235,9 @@ if (($action == 'deleteline' || $action == 'deletecontact') && $user->rights->pr
  */
 
 $title = $langs->trans("ProjectContact").' - '.$object->ref.' '.$object->name;
-if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("ProjectContact");
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
+	$title = $object->ref.' '.$object->name.' - '.$langs->trans("ProjectContact");
+}
 $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos";
 llxHeader('', $title, $help_url);
 
@@ -254,9 +252,10 @@ $userstatic = new User($db);
 /*                                                                             */
 /* *************************************************************************** */
 
-if ($id > 0 || !empty($ref))
-{
-	if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+if ($id > 0 || !empty($ref)) {
+	if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+		$object->fetchComments();
+	}
 	// To verify role of users
 	//$userAccess = $object->restrictedProjectArea($user,'read');
 	$userWrite = $object->restrictedProjectArea($user, 'write');
@@ -271,8 +270,11 @@ if ($id > 0 || !empty($ref))
 	// Call Hook formConfirm
 	$parameters = array('formConfirm' => $formconfirm);
 	$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-	if (empty($reshook)) $formconfirm .= $hookmanager->resPrint;
-	elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint;
+	if (empty($reshook)) {
+		$formconfirm .= $hookmanager->resPrint;
+	} elseif ($reshook > 0) {
+		$formconfirm = $hookmanager->resPrint;
+	}
 
 	// Print form confirm
 	print $formconfirm;
@@ -285,15 +287,13 @@ if ($id > 0 || !empty($ref))
 	// Title
 	$morehtmlref .= $object->title;
 	// Thirdparty
-	if ($object->thirdparty->id > 0)
-	{
+	if ($object->thirdparty->id > 0) {
 		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project');
 	}
 	$morehtmlref .= '</div>';
 
 	// Define a complementary filter for search of next/prev ref.
-	if (!$user->rights->projet->all->lire)
-	{
+	if (!$user->rights->projet->all->lire) {
 		$objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0);
 		$object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 	}
@@ -312,22 +312,19 @@ if ($id > 0 || !empty($ref))
 	print $langs->trans("Usage");
 	print '</td>';
 	print '<td>';
-	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-	{
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 		print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectFollowOpportunity");
 		print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
 		print '<br>';
 	}
-	if (empty($conf->global->PROJECT_HIDE_TASKS))
-	{
+	if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 		print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectFollowTasks");
 		print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
 		print '<br>';
 	}
-	if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-	{
+	if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) {
 		print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectBillTimeDescription");
 		print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
@@ -337,26 +334,34 @@ if ($id > 0 || !empty($ref))
 
 	// Visibility
 	print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-	if ($object->public) print $langs->trans('SharedProject');
-	else print $langs->trans('PrivateProject');
+	if ($object->public) {
+		print $langs->trans('SharedProject');
+	} else {
+		print $langs->trans('PrivateProject');
+	}
 	print '</td></tr>';
 
-	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && $object->opp_status)
-	{
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && $object->opp_status) {
 		// Opportunity status
 		print '<tr><td>'.$langs->trans("OpportunityStatus").'</td><td>';
 		$code = dol_getIdFromCode($db, $object->opp_status, 'c_lead_status', 'rowid', 'code');
-		if ($code) print $langs->trans("OppStatus".$code);
+		if ($code) {
+			print $langs->trans("OppStatus".$code);
+		}
 		print '</td></tr>';
 
 		// Opportunity percent
 		print '<tr><td>'.$langs->trans("OpportunityProbability").'</td><td>';
-		if (strcmp($object->opp_percent, '')) print price($object->opp_percent, '', $langs, 1, 0).' %';
+		if (strcmp($object->opp_percent, '')) {
+			print price($object->opp_percent, '', $langs, 1, 0).' %';
+		}
 		print '</td></tr>';
 
 		// Opportunity Amount
 		print '<tr><td>'.$langs->trans("OpportunityAmount").'</td><td>';
-		if (strcmp($object->opp_amount, '')) print price($object->opp_amount, '', $langs, 0, 0, 0, $conf->currency);
+		if (strcmp($object->opp_amount, '')) {
+			print price($object->opp_amount, '', $langs, 0, 0, 0, $conf->currency);
+		}
 		print '</td></tr>';
 	}
 
@@ -367,12 +372,16 @@ if ($id > 0 || !empty($ref))
 	$end = dol_print_date($object->date_end, 'day');
 	print ' - ';
 	print ($end ? $end : '?');
-	if ($object->hasDelay()) print img_warning("Late");
+	if ($object->hasDelay()) {
+		print img_warning("Late");
+	}
 	print '</td></tr>';
 
 	// Budget
 	print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-	if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 0, 0, 0, $conf->currency);
+	if (strcmp($object->budget_amount, '')) {
+		print price($object->budget_amount, '', $langs, 0, 0, 0, $conf->currency);
+	}
 	print '</td></tr>';
 
 	// Other attributes
@@ -414,10 +423,11 @@ if ($id > 0 || !empty($ref))
 
 	// Contacts lines (modules that overwrite templates must declare this into descriptor)
 	$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
-	foreach ($dirtpls as $reldir)
-	{
+	foreach ($dirtpls as $reldir) {
 		$res = @include dol_buildpath($reldir.'/contacts.tpl.php');
-		if ($res) break;
+		if ($res) {
+			break;
+		}
 	}
 }
 

+ 25 - 15
htdocs/projet/document.php

@@ -48,7 +48,9 @@ $result = restrictedArea($user, 'projet', $id, 'projet&project');
 $object = new Project($db);
 
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
-if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+	$object->fetchComments();
+}
 
 if ($id > 0 || !empty($ref)) {
 	$upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($object->ref);
@@ -59,16 +61,26 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
 
-if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; }
-if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; }
+if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) {
+	$sortfield = $conf->global->MAIN_DOC_SORT_FIELD;
+}
+if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) {
+	$sortorder = $conf->global->MAIN_DOC_SORT_ORDER;
+}
 
-if (!$sortorder) $sortorder = "ASC";
-if (!$sortfield) $sortfield = "name";
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
+if (!$sortfield) {
+	$sortfield = "name";
+}
 
 
 
@@ -84,15 +96,16 @@ include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
  */
 
 $title = $langs->trans("Project").' - '.$langs->trans("Document").' - '.$object->ref.' '.$object->name;
-if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Document");
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
+	$title = $object->ref.' '.$object->name.' - '.$langs->trans("Document");
+}
 $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos";
 
 llxHeader('', $title, $help_url);
 
 $form = new Form($db);
 
-if ($object->id > 0)
-{
+if ($object->id > 0) {
 	$upload_dir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($object->ref);
 
 	// To verify role of users
@@ -107,8 +120,7 @@ if ($object->id > 0)
 	// Files list constructor
 	$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
 	$totalsize = 0;
-	foreach ($filearray as $key => $file)
-	{
+	foreach ($filearray as $key => $file) {
 		$totalsize += $file['size'];
 	}
 
@@ -121,15 +133,13 @@ if ($object->id > 0)
 	// Title
 	$morehtmlref .= $object->title;
 	// Thirdparty
-	if ($object->thirdparty->id > 0)
-	{
+	if ($object->thirdparty->id > 0) {
 		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project');
 	}
 	$morehtmlref .= '</div>';
 
 	// Define a complementary filter for search of next/prev ref.
-	if (!$user->rights->projet->all->lire)
-	{
+	if (!$user->rights->projet->all->lire) {
 		$objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0);
 		$object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 	}

File diff suppressed because it is too large
+ 389 - 248
htdocs/projet/element.php


+ 51 - 39
htdocs/projet/event.php

@@ -74,8 +74,11 @@ if ($action == 'update' && empty(GETPOST('cancel')) && $permissiontoadd) {
 		$action = 'edit';
 	} else {
 		$db->commit();
-		if (GETPOST('socid', 'int') > 0) $object->fetch_thirdparty(GETPOST('socid', 'int'));
-		else unset($object->thirdparty);
+		if (GETPOST('socid', 'int') > 0) {
+			$object->fetch_thirdparty(GETPOST('socid', 'int'));
+		} else {
+			unset($object->thirdparty);
+		}
 		$action='';
 	}
 }
@@ -87,7 +90,9 @@ if ($action == 'update' && empty(GETPOST('cancel')) && $permissiontoadd) {
  */
 
 $title = $langs->trans("Project").' - '.$langs->trans("ConferenceOrBoothTab").' - '.$object->ref.' '.$object->name;
-if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Note");
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
+	$title = $object->ref.' '.$object->name.' - '.$langs->trans("Note");
+}
 //TODO Make wiki docs
 $help_url = '';
 llxHeader("", $title, $help_url);
@@ -97,8 +102,7 @@ $userstatic = new User($db);
 
 $now = dol_now();
 
-if ($id > 0 || !empty($ref))
-{
+if ($id > 0 || !empty($ref)) {
 	$head = project_prepare_head($object);
 	print dol_get_fiche_head($head, 'eventorganisation', $langs->trans('ConferenceOrBoothTab'), -1);
 
@@ -110,15 +114,13 @@ if ($id > 0 || !empty($ref))
 	// Title
 	$morehtmlref .= $object->title;
 	// Thirdparty
-	if ($object->thirdparty->id > 0)
-	{
+	if ($object->thirdparty->id > 0) {
 		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project');
 	}
 	$morehtmlref .= '</div>';
 
 	// Define a complementary filter for search of next/prev ref.
-	if (!$user->rights->projet->all->lire)
-	{
+	if (!$user->rights->projet->all->lire) {
 		$objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0);
 		$object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 	}
@@ -137,30 +139,26 @@ if ($id > 0 || !empty($ref))
 	print $langs->trans("Usage");
 	print '</td>';
 	print '<td>';
-	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-	{
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 		print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectFollowOpportunity");
 		print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
 		print '<br>';
 	}
-	if (empty($conf->global->PROJECT_HIDE_TASKS))
-	{
+	if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 		print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectFollowTasks");
 		print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
 		print '<br>';
 	}
-	if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-	{
+	if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) {
 		print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectBillTimeDescription");
 		print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
 		print '<br>';
 	}
 
-	if (!empty($conf->eventorganization->enabled))
-	{
+	if (!empty($conf->eventorganization->enabled)) {
 		print '<input type="checkbox" disabled name="usage_organize_event"'.(GETPOSTISSET('usage_organize_event') ? (GETPOST('usage_organize_event', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_organize_event ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("EventOrganizationDescriptionLong");
 		print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext);
@@ -169,21 +167,27 @@ if ($id > 0 || !empty($ref))
 
 	// Visibility
 	print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-	if ($object->public) print $langs->trans('SharedProject');
-	else print $langs->trans('PrivateProject');
+	if ($object->public) {
+		print $langs->trans('SharedProject');
+	} else {
+		print $langs->trans('PrivateProject');
+	}
 	print '</td></tr>';
 
-	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity))
-	{
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity)) {
 		// Opportunity status
 		print '<tr><td>'.$langs->trans("OpportunityStatus").'</td><td>';
 		$code = dol_getIdFromCode($db, $object->opp_status, 'c_lead_status', 'rowid', 'code');
-		if ($code) print $langs->trans("OppStatus".$code);
+		if ($code) {
+			print $langs->trans("OppStatus".$code);
+		}
 		print '</td></tr>';
 
 		// Opportunity percent
 		print '<tr><td>'.$langs->trans("OpportunityProbability").'</td><td>';
-		if (strcmp($object->opp_percent, '')) print price($object->opp_percent, 0, $langs, 1, 0).' %';
+		if (strcmp($object->opp_percent, '')) {
+			print price($object->opp_percent, 0, $langs, 1, 0).' %';
+		}
 		print '</td></tr>';
 
 		// Opportunity Amount
@@ -192,12 +196,16 @@ if ($id > 0 || !empty($ref))
 		{
 		   print price($obj->opp_amount, 1, $langs, 1, 0, -1, $conf->currency);
 		}*/
-		if (strcmp($object->opp_amount, '')) print price($object->opp_amount, 0, $langs, 1, 0, -1, $conf->currency);
+		if (strcmp($object->opp_amount, '')) {
+			print price($object->opp_amount, 0, $langs, 1, 0, -1, $conf->currency);
+		}
 		print '</td></tr>';
 
 		// Opportunity Weighted Amount
 		print '<tr><td>'.$langs->trans('OpportunityWeightedAmount').'</td><td>';
-		if (strcmp($object->opp_amount, '') && strcmp($object->opp_percent, '')) print price($object->opp_amount * $object->opp_percent / 100, 0, $langs, 1, 0, -1, $conf->currency);
+		if (strcmp($object->opp_amount, '') && strcmp($object->opp_percent, '')) {
+			print price($object->opp_amount * $object->opp_percent / 100, 0, $langs, 1, 0, -1, $conf->currency);
+		}
 		print '</td></tr>';
 	}
 
@@ -208,12 +216,16 @@ if ($id > 0 || !empty($ref))
 	$end = dol_print_date($object->date_end, 'day');
 	print ' - ';
 	print ($end ? $end : '?');
-	if ($object->hasDelay()) print img_warning("Late");
+	if ($object->hasDelay()) {
+		print img_warning("Late");
+	}
 	print '</td></tr>';
 
 	// Budget
 	print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-	if (strcmp($object->budget_amount, '')) print price($object->budget_amount, 0, $langs, 1, 0, 0, $conf->currency);
+	if (strcmp($object->budget_amount, '')) {
+		print price($object->budget_amount, 0, $langs, 1, 0, 0, $conf->currency);
+	}
 	print '</td></tr>';
 
 	// Other attributes
@@ -281,12 +293,16 @@ if ($id > 0 || !empty($ref))
 
 		//Price of registration
 		print '<tr><td class="valignmiddle">' . $langs->trans("PriceOfRegistration") . '</td><td>';
-		if (strcmp($object->price_registration, '')) print price($object->price_registration, 0, $langs, 1, 0, 0, $conf->currency);
+		if (strcmp($object->price_registration, '')) {
+			print price($object->price_registration, 0, $langs, 1, 0, 0, $conf->currency);
+		}
 		print "</td></tr>";
 
 		//Price of registration
 		print '<tr><td class="valignmiddle">' . $langs->trans("PriceOfBooth") . '</td><td>';
-		if (strcmp($object->price_booth, '')) print price($object->price_booth, 0, $langs, 1, 0, 0, $conf->currency);
+		if (strcmp($object->price_booth, '')) {
+			print price($object->price_booth, 0, $langs, 1, 0, 0, $conf->currency);
+		}
 		print "</td></tr>";
 	}
 
@@ -309,8 +325,7 @@ if ($id > 0 || !empty($ref))
 
 print dol_get_fiche_end();
 
-if ($action == 'edit' && $permissiontoadd > 0)
-{
+if ($action == 'edit' && $permissiontoadd > 0) {
 	print '<div class="center">';
 	print '<input name="update" class="button" type="submit" value="'.$langs->trans("Save").'">&nbsp; &nbsp; &nbsp;';
 	print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
@@ -321,19 +336,16 @@ if ($action == 'edit' && $permissiontoadd > 0)
 
 
 /*
-     * Actions Buttons
-     */
+	 * Actions Buttons
+	 */
 print '<div class="tabsAction">';
 $parameters = array();
 $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
 // modified by hook
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	// Modify
-	if ($object->statut != Project::STATUS_CLOSED && $action=='')
-	{
-		if ($permissiontoadd > 0)
-		{
+	if ($object->statut != Project::STATUS_CLOSED && $action=='') {
+		if ($permissiontoadd > 0) {
 			print '<a class="butAction" href="event.php?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>';
 		} else {
 			print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotOwnerOfProject").'">'.$langs->trans('Modify').'</a>';

+ 17 - 22
htdocs/projet/ganttchart.inc.php

@@ -116,12 +116,10 @@ if (g.getDivId() != null)
 	$level = 0;
 	$tnums = count($tasks);
 	$old_project_id = 0;
-	for ($tcursor = 0; $tcursor < $tnums; $tcursor++)
-	{
+	for ($tcursor = 0; $tcursor < $tnums; $tcursor++) {
 		$t = $tasks[$tcursor];
 
-		if (empty($old_project_id) || $old_project_id != $t['task_project_id'])
-		{
+		if (empty($old_project_id) || $old_project_id != $t['task_project_id']) {
 			// Break on project, create a fictive task for project id $t['task_project_id']
 			$projecttmp = new Project($db);
 			$projecttmp->fetch($t['task_project_id']);
@@ -140,8 +138,7 @@ if (g.getDivId() != null)
 			$old_project_id = $t['task_project_id'];
 		}
 
-		if ($t["task_parent"] <= 0)
-		{
+		if ($t["task_parent"] <= 0) {
 			constructGanttLine($tasks, $t, $task_dependencies, $level, $t['task_project_id']);
 			findChildGanttLine($tasks, $t["task_id"], $task_dependencies, $level + 1);
 		}
@@ -180,7 +177,9 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje
 
 	$start_date = $task["task_start_date"];
 	$end_date = $task["task_end_date"];
-	if (!$end_date) $end_date = $start_date;
+	if (!$end_date) {
+		$end_date = $start_date;
+	}
 	$start_date = dol_print_date($start_date, $dateformatinput2);
 	$end_date = dol_print_date($end_date, $dateformatinput2);
 	// Resources
@@ -198,8 +197,7 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje
 	}
 	// $depend .= "\"";
 	// Define parent
-	if ($project_id && $level < 0)
-	{
+	if ($project_id && $level < 0) {
 		$parent = '-'.$project_id;
 	} else {
 		$parent = $task["task_parent_alternate_id"];
@@ -208,8 +206,7 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje
 	// Define percent
 	$percent = $task['task_percent_complete'] ? $task['task_percent_complete'] : 0;
 	// Link (more information)
-	if ($task["task_id"] < 0)
-	{
+	if ($task["task_id"] < 0) {
 		//$link=DOL_URL_ROOT.'/projet/tasks.php?withproject=1&id='.abs($task["task_id"]);
 		$link = '';
 	} else {
@@ -221,8 +218,8 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje
 	$name = $task['task_name'];
 
 	/*for($i=0; $i < $level; $i++) {
-        $name=' - '.$name;
-    }*/
+		$name=' - '.$name;
+	}*/
 	// Add line to gantt
 	/*
 	g.AddTaskItem(new JSGantt.TaskItem(1, 'Define Chart API','',          '',          'ggroupblack','', 0, 'Brian', 0,  1,0,1,'','','Some Notes text',g));
@@ -247,7 +244,7 @@ function constructGanttLine($tarr, $task, $task_dependencies, $level = 0, $proje
 	<dt>pCaption</dt><dd>(optional) caption that will be added after task bar if CaptionType set to "Caption"</dd>
 	<dt>pNotes</dt><dd>(optional) Detailed task information that will be displayed in tool tip for this task</dd>
 	<dt>pGantt</dt><dd>(required) javascript JSGantt.GanttChart object from which to take settings.  Defaults to &quot;g&quot; for backwards compatibility</dd>
-    */
+	*/
 
 	//$note="";
 
@@ -289,18 +286,16 @@ function findChildGanttLine($tarr, $parent, $task_dependencies, $level)
 	$n = count($tarr);
 
 	$old_parent_id = 0;
-	for ($x = 0; $x < $n; $x++)
-	{
-		if ($tarr[$x]["task_parent"] == $parent && $tarr[$x]["task_parent"] != $tarr[$x]["task_id"])
-		{
+	for ($x = 0; $x < $n; $x++) {
+		if ($tarr[$x]["task_parent"] == $parent && $tarr[$x]["task_parent"] != $tarr[$x]["task_id"]) {
 			// Create a grouping parent task for the new level
 			/*if (empty($old_parent_id) || $old_parent_id != $tarr[$x]['task_project_id'])
 			{
 				$tmpt = array(
-	        	'task_id'=> -98, 'task_name'=>'Level '.$level, 'task_resources'=>'', 'task_start_date'=>'', 'task_end_date'=>'',
-    	    	'task_is_group'=>1, 'task_css'=>'ggroupblack', 'task_milestone'=> 0, 'task_parent'=>$tarr[$x]["task_parent"], 'task_notes'=>'');
-        		constructGanttLine($tasks, $tmpt, array(), 0, $tarr[$x]['task_project_id']);
-        		$old_parent_id = $tarr[$x]['task_project_id'];
+				'task_id'=> -98, 'task_name'=>'Level '.$level, 'task_resources'=>'', 'task_start_date'=>'', 'task_end_date'=>'',
+				'task_is_group'=>1, 'task_css'=>'ggroupblack', 'task_milestone'=> 0, 'task_parent'=>$tarr[$x]["task_parent"], 'task_notes'=>'');
+				constructGanttLine($tasks, $tmpt, array(), 0, $tarr[$x]['task_project_id']);
+				$old_parent_id = $tarr[$x]['task_project_id'];
 			}*/
 
 			constructGanttLine($tarr, $tarr[$x], $task_dependencies, $level, null);

+ 53 - 51
htdocs/projet/ganttview.php

@@ -43,7 +43,9 @@ $mine = ($mode == 'mine' ? 1 : 0);
 $object = new Project($db);
 
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
-if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+	$object->fetchComments();
+}
 
 // Security check
 $socid = 0;
@@ -74,8 +76,7 @@ $task = new Task($db);
 
 $arrayofcss = array('/includes/jsgantt/jsgantt.css');
 
-if (!empty($conf->use_javascript_ajax))
-{
+if (!empty($conf->use_javascript_ajax)) {
 	$arrayofjs = array(
 	'/includes/jsgantt/jsgantt.js',
 	'/projet/jsgantt_language.js.php?lang='.$langs->defaultlang
@@ -84,12 +85,13 @@ if (!empty($conf->use_javascript_ajax))
 
 //$title=$langs->trans("Gantt").($object->ref?' - '.$object->ref.' '.$object->name:'');
 $title = $langs->trans("Gantt");
-if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = ($object->ref ? $object->ref.' '.$object->name.' - ' : '').$langs->trans("Gantt");
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
+	$title = ($object->ref ? $object->ref.' '.$object->name.' - ' : '').$langs->trans("Gantt");
+}
 $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos";
 llxHeader("", $title, $help_url, '', 0, 0, $arrayofjs, $arrayofcss);
 
-if (($id > 0 && is_numeric($id)) || !empty($ref))
-{
+if (($id > 0 && is_numeric($id)) || !empty($ref)) {
 	// To verify role of users
 	//$userAccess = $object->restrictedProjectArea($user,'read');
 	$userWrite = $object->restrictedProjectArea($user, 'write');
@@ -113,15 +115,13 @@ if (($id > 0 && is_numeric($id)) || !empty($ref))
 	// Title
 	$morehtmlref .= $object->title;
 	// Thirdparty
-	if ($object->thirdparty->id > 0)
-	{
+	if ($object->thirdparty->id > 0) {
 		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project');
 	}
 	$morehtmlref .= '</div>';
 
 	// Define a complementary filter for search of next/prev ref.
-	if (!$user->rights->projet->all->lire)
-	{
+	if (!$user->rights->projet->all->lire) {
 		$objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0);
 		$object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 	}
@@ -140,22 +140,19 @@ if (($id > 0 && is_numeric($id)) || !empty($ref))
 	print $langs->trans("Usage");
 	print '</td>';
 	print '<td>';
-	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-	{
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 		print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectFollowOpportunity");
 		print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
 		print '<br>';
 	}
-	if (empty($conf->global->PROJECT_HIDE_TASKS))
-	{
+	if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 		print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectFollowTasks");
 		print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
 		print '<br>';
 	}
-	if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-	{
+	if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) {
 		print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectBillTimeDescription");
 		print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
@@ -165,8 +162,11 @@ if (($id > 0 && is_numeric($id)) || !empty($ref))
 
 	// Visibility
 	print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-	if ($object->public) print $langs->trans('SharedProject');
-	else print $langs->trans('PrivateProject');
+	if ($object->public) {
+		print $langs->trans('SharedProject');
+	} else {
+		print $langs->trans('PrivateProject');
+	}
 	print '</td></tr>';
 
 	// Date start - end
@@ -176,12 +176,16 @@ if (($id > 0 && is_numeric($id)) || !empty($ref))
 	$end = dol_print_date($object->date_end, 'day');
 	print ' - ';
 	print ($end ? $end : '?');
-	if ($object->hasDelay()) print img_warning("Late");
+	if ($object->hasDelay()) {
+		print img_warning("Late");
+	}
 	print '</td></tr>';
 
 	// Budget
 	print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-	if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+	if (strcmp($object->budget_amount, '')) {
+		print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+	}
 	print '</td></tr>';
 
 	// Other attributes
@@ -252,8 +256,7 @@ $tasksarray = $task->getTasksArray(0, 0, ($object->id ? $object->id : $id), $soc
 //var_dump($tasksrole);
 
 
-if (count($tasksarray) > 0)
-{
+if (count($tasksarray) > 0) {
 	// Show Gant diagram from $taskarray using JSGantt
 
 	$dateformat = $langs->trans("FormatDateShortJQuery"); // Used by include ganttchart.inc.php later
@@ -262,8 +265,7 @@ if (count($tasksarray) > 0)
 	$tasks = array();
 	$task_dependencies = array();
 	$taskcursor = 0;
-	foreach ($tasksarray as $key => $val)	// Task array are sorted by "project, position, date"
-	{
+	foreach ($tasksarray as $key => $val) {	// Task array are sorted by "project, position, date"
 		$task->fetch($val->id, '');
 
 		$idparent = ($val->fk_parent ? $val->fk_parent : '-'.$val->fk_project); // If start with -, id is a project id
@@ -299,34 +301,34 @@ if (count($tasksarray) > 0)
 
 		$idofusers = $task->getListContactId('internal');
 		$idofcontacts = $task->getListContactId('external');
-  		$s = '';
-		if (count($idofusers) > 0)
-		{
+		$s = '';
+		if (count($idofusers) > 0) {
 			$s .= $langs->trans("Internals").': ';
 			$i = 0;
-			foreach ($idofusers as $valid)
-			{
+			foreach ($idofusers as $valid) {
 				$userstatic->fetch($valid);
-				if ($i) $s .= ', ';
+				if ($i) {
+					$s .= ', ';
+				}
 				$s .= $userstatic->login;
 				$i++;
 			}
 		}
 		//if (count($idofusers)>0 && (count($idofcontacts)>0)) $s.=' - ';
-		if (count($idofcontacts) > 0)
-		{
-			if ($s) $s .= ' - ';
+		if (count($idofcontacts) > 0) {
+			if ($s) {
+				$s .= ' - ';
+			}
 			$s .= $langs->trans("Externals").': ';
 			$i = 0;
 			$contactidfound = array();
-			foreach ($idofcontacts as $valid)
-			{
-				if (empty($contactidfound[$valid]))
-				{
+			foreach ($idofcontacts as $valid) {
+				if (empty($contactidfound[$valid])) {
 					$res = $contactstatic->fetch($valid);
-					if ($res > 0)
-					{
-						if ($i) $s .= ', ';
+					if ($res > 0) {
+						if ($i) {
+							$s .= ', ';
+						}
 						$s .= $contactstatic->getFullName($langs);
 						$contactidfound[$valid] = 1;
 						$i++;
@@ -338,30 +340,30 @@ if (count($tasksarray) > 0)
 		/* For JSGanttImproved */
 		//if ($s) $tasks[$taskcursor]['task_resources']=implode(',',$idofusers);
 		$tasks[$taskcursor]['task_resources'] = $s;
-		if ($s) $tasks[$taskcursor]['task_resources'] = '<a href="'.DOL_URL_ROOT.'/projet/tasks/contact.php?id='.$val->id.'&withproject=1" title="'.dol_escape_htmltag($s).'">'.$langs->trans("List").'</a>';
+		if ($s) {
+			$tasks[$taskcursor]['task_resources'] = '<a href="'.DOL_URL_ROOT.'/projet/tasks/contact.php?id='.$val->id.'&withproject=1" title="'.dol_escape_htmltag($s).'">'.$langs->trans("List").'</a>';
+		}
 		//print "xxx".$val->id.$tasks[$taskcursor]['task_resources'];
 		$tasks[$taskcursor]['note'] = $task->note_public;
 		$taskcursor++;
 	}
 
 	// Search parent to set task_parent_alternate_id (requird by ganttchart)
-	foreach ($tasks as $tmpkey => $tmptask)
-	{
-		foreach ($tasks as $tmptask2)
-		{
-			if ($tmptask2['task_id'] == $tmptask['task_parent'])
-			{
+	foreach ($tasks as $tmpkey => $tmptask) {
+		foreach ($tasks as $tmptask2) {
+			if ($tmptask2['task_id'] == $tmptask['task_parent']) {
 				$tasks[$tmpkey]['task_parent_alternate_id'] = $tmptask2['task_alternate_id'];
 				break;
 			}
 		}
-		if (empty($tasks[$tmpkey]['task_parent_alternate_id'])) $tasks[$tmpkey]['task_parent_alternate_id'] = $tasks[$tmpkey]['task_parent'];
+		if (empty($tasks[$tmpkey]['task_parent_alternate_id'])) {
+			$tasks[$tmpkey]['task_parent_alternate_id'] = $tasks[$tmpkey]['task_parent'];
+		}
 	}
 
 	print "\n";
 
- 	if (!empty($conf->use_javascript_ajax))
-	{
+	if (!empty($conf->use_javascript_ajax)) {
 		//var_dump($_SESSION);
 
 		// How the date for data are formated (format used bu jsgantt)
@@ -369,7 +371,7 @@ if (count($tasksarray) > 0)
 		// How the date for data are formated (format used by dol_print_date)
 		$dateformatinput2 = 'standard';
 		//var_dump($dateformatinput);
-  		//var_dump($dateformatinput2);
+		//var_dump($dateformatinput2);
 
 		$moreforfilter = '<div class="liste_titre liste_titre_bydiv centpercent">';
 

+ 34 - 29
htdocs/projet/graph_opportunities.inc.php

@@ -17,19 +17,21 @@
 
 // variable $listofopplabel and $listofoppstatus should be defined
 
-if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-{
+if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 	$sql = "SELECT p.fk_opp_status as opp_status, cls.code, COUNT(p.rowid) as nb, SUM(p.opp_amount) as opp_amount, SUM(p.opp_amount * p.opp_percent) as ponderated_opp_amount";
 	$sql .= " FROM ".MAIN_DB_PREFIX."projet as p LEFT JOIN ".MAIN_DB_PREFIX."c_lead_status as cls ON p.fk_opp_status = cls.rowid";	// If lead status has been removed, we must show it in stats as unknown
 	$sql .= " WHERE p.entity IN (".getEntity('project').")";
 	$sql .= " AND p.fk_statut = 1"; // Opend projects only
-	if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$projectsListId.")";
-	if ($socid)	$sql .= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
+	if ($mine || empty($user->rights->projet->all->lire)) {
+		$sql .= " AND p.rowid IN (".$projectsListId.")";
+	}
+	if ($socid) {
+		$sql .= "  AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
+	}
 	$sql .= " GROUP BY p.fk_opp_status, cls.code";
 	$resql = $db->query($sql);
 
-	if ($resql)
-	{
+	if ($resql) {
 		$num = $db->num_rows($resql);
 		$i = 0;
 
@@ -41,15 +43,15 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 		$valsamount = array();
 		$dataseries = array();
 		// -1=Canceled, 0=Draft, 1=Validated, (2=Accepted/On process not managed for customer orders), 3=Closed (Sent/Received, billed or not)
-		while ($i < $num)
-		{
+		while ($i < $num) {
 			$obj = $db->fetch_object($resql);
-			if ($obj)
-			{
+			if ($obj) {
 				$valsnb[$obj->opp_status] = $obj->nb;
 				$valsamount[$obj->opp_status] = $obj->opp_amount;
 				$totalnb += $obj->nb;
-				if ($obj->opp_status) $totaloppnb += $obj->nb;
+				if ($obj->opp_status) {
+					$totaloppnb += $obj->nb;
+				}
 				if (!in_array($obj->code, array('WON', 'LOST'))) {
 					$totalamount += $obj->opp_amount;
 					$ponderated_opp_amount += $obj->ponderated_opp_amount;
@@ -63,40 +65,43 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 		$ponderated_opp_amount = $ponderated_opp_amount / 100;
 
 		print '<div class="div-table-responsive-no-min">';
-	    print '<table class="noborder nohover centpercent">';
-	    print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("OpportunitiesStatusForOpenedProjects").'</th></tr>'."\n";
+		print '<table class="noborder nohover centpercent">';
+		print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("OpportunitiesStatusForOpenedProjects").'</th></tr>'."\n";
 
-	    $listofstatus = array_keys($listofoppstatus);
+		$listofstatus = array_keys($listofoppstatus);
 		// Complete with values found into database and not into the dictionary
-	    foreach ($valsamount as $key => $val) {
-	    	if (!in_array($key, $listofstatus) && $key) {
-	    		$listofstatus[] = $key;
-	    	}
-	    }
+		foreach ($valsamount as $key => $val) {
+			if (!in_array($key, $listofstatus) && $key) {
+				$listofstatus[] = $key;
+			}
+		}
 
-	    foreach ($listofstatus as $status)
-	    {
-	    	$labelStatus = '';
+		foreach ($listofstatus as $status) {
+			$labelStatus = '';
 
 			$code = dol_getIdFromCode($db, $status, 'c_lead_status', 'rowid', 'code');
-	        if ($code) $labelStatus = $langs->transnoentitiesnoconv("OppStatus".$code);
-	        if (empty($labelStatus)) $labelStatus = $listofopplabel[$status];
-	        if (empty($labelStatus)) $labelStatus = $langs->transnoentitiesnoconv('OldValue', $status);	// When id is id of an entry no more in dictionary for example.
+			if ($code) {
+				$labelStatus = $langs->transnoentitiesnoconv("OppStatus".$code);
+			}
+			if (empty($labelStatus)) {
+				$labelStatus = $listofopplabel[$status];
+			}
+			if (empty($labelStatus)) {
+				$labelStatus = $langs->transnoentitiesnoconv('OldValue', $status);	// When id is id of an entry no more in dictionary for example.
+			}
 
 			//$labelStatus .= ' ('.$langs->trans("Coeff").': '.price2num($listofoppstatus[$status]).')';
 			//$labelStatus .= ' - '.price2num($listofoppstatus[$status]).'%';
 
 			$dataseries[] = array($labelStatus, (isset($valsamount[$status]) ? (float) $valsamount[$status] : 0));
-			if (!$conf->use_javascript_ajax)
-			{
+			if (!$conf->use_javascript_ajax) {
 				print '<tr class="oddeven">';
 				print '<td>'.$labelStatus.'</td>';
 				print '<td class="right"><a href="list.php?statut='.$status.'">'.price((isset($valsamount[$status]) ? (float) $valsamount[$status] : 0), 0, '', 1, -1, -1, $conf->currency).'</a></td>';
 				print "</tr>\n";
 			}
 		}
-		if ($conf->use_javascript_ajax)
-		{
+		if ($conf->use_javascript_ajax) {
 			print '<tr><td class="center nopaddingleftimp nopaddingrightimp" colspan="2">';
 
 			include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';

+ 68 - 48
htdocs/projet/index.php

@@ -42,13 +42,19 @@ $langs->loadLangs(array('projects', 'companies'));
 $action = GETPOST('action', 'aZ09');
 $search_project_user = GETPOST('search_project_user', 'int');
 $mine = GETPOST('mode', 'aZ09') == 'mine' ? 1 : 0;
-if ($mine == 0 && $search_project_user === '') $search_project_user = $user->conf->MAIN_SEARCH_PROJECT_USER_PROJECTSINDEX;
-if ($search_project_user == $user->id) $mine = 1;
+if ($mine == 0 && $search_project_user === '') {
+	$search_project_user = $user->conf->MAIN_SEARCH_PROJECT_USER_PROJECTSINDEX;
+}
+if ($search_project_user == $user->id) {
+	$mine = 1;
+}
 
 // Security check
 $socid = 0;
 //if ($user->socid > 0) $socid = $user->socid;    // For external user, no check is done on company because readability is managed by public status of project and assignement.
-if (!$user->rights->projet->lire) accessforbidden();
+if (!$user->rights->projet->lire) {
+	accessforbidden();
+}
 
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
@@ -62,7 +68,9 @@ $max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT;
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 if (empty($reshook)) {
 	if ($action == 'refresh_search_project_user') {
 		$search_project_user = GETPOST('search_project_user', 'int');
@@ -95,8 +103,11 @@ $title = $langs->trans("ProjectsArea");
 
 // Title for combo list see all projects
 $titleall = $langs->trans("AllAllowedProjects");
-if (!empty($user->rights->projet->all->lire) && !$socid) $titleall = $langs->trans("AllProjects");
-else $titleall = $langs->trans("AllAllowedProjects").'<br><br>';
+if (!empty($user->rights->projet->all->lire) && !$socid) {
+	$titleall = $langs->trans("AllProjects");
+} else {
+	$titleall = $langs->trans("AllAllowedProjects").'<br><br>';
+}
 
 $morehtml = '';
 $morehtml .= '<form name="projectform" method="POST">';
@@ -109,10 +120,14 @@ $morehtml .= '</SELECT>';
 $morehtml .= '<input type="submit" class="button smallpaddingimp" name="refresh" value="'.$langs->trans("Refresh").'">';
 $morehtml .= '</form>';
 
-if ($mine) $tooltiphelp = $langs->trans("MyProjectsDesc");
-else {
-	if (!empty($user->rights->projet->all->lire) && !$socid) $tooltiphelp = $langs->trans("ProjectsDesc");
-	else $tooltiphelp = $langs->trans("ProjectsPublicDesc");
+if ($mine) {
+	$tooltiphelp = $langs->trans("MyProjectsDesc");
+} else {
+	if (!empty($user->rights->projet->all->lire) && !$socid) {
+		$tooltiphelp = $langs->trans("ProjectsDesc");
+	} else {
+		$tooltiphelp = $langs->trans("ProjectsPublicDesc");
+	}
 }
 
 print_barre_liste($form->textwithpicto($title, $tooltiphelp), 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, -1, 'project', 0, $morehtml);
@@ -125,13 +140,11 @@ $sql = "SELECT cls.rowid, cls.code, cls.percent, cls.label";
 $sql .= " FROM ".MAIN_DB_PREFIX."c_lead_status as cls";
 $sql .= " WHERE active=1";
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$num = $db->num_rows($resql);
 	$i = 0;
 
-	while ($i < $num)
-	{
+	while ($i < $num) {
 		$objp = $db->fetch_object($resql);
 		$listofoppstatus[$objp->rowid] = $objp->percent;
 		$listofopplabel[$objp->rowid] = $objp->label;
@@ -161,34 +174,36 @@ if ($resql)
 		}
 		$i++;
 	}
-} else dol_print_error($db);
+} else {
+	dol_print_error($db);
+}
 //var_dump($listofoppcode);
 
 
 print '<div class="fichecenter"><div class="fichethirdleft">';
 
 
-if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS))     // This is useless due to the global search combo
-{
+if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) {     // This is useless due to the global search combo
 	// Search project
-	if (!empty($conf->projet->enabled) && $user->rights->projet->lire)
-	{
+	if (!empty($conf->projet->enabled) && $user->rights->projet->lire) {
 		$listofsearchfields['search_project'] = array('text'=>'Project');
 	}
 
-	if (count($listofsearchfields))
-	{
+	if (count($listofsearchfields)) {
 		print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">';
 		print '<input type="hidden" name="token" value="'.newToken().'">';
 		print '<div class="div-table-responsive-no-min">';
 		print '<table class="noborder nohover centpercent">';
 		$i = 0;
-		foreach ($listofsearchfields as $key => $value)
-		{
-			if ($i == 0) print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>';
+		foreach ($listofsearchfields as $key => $value) {
+			if ($i == 0) {
+				print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>';
+			}
 			print '<tr>';
 			print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>';
-			if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>';
+			if ($i == 0) {
+				print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>';
+			}
 			print '</tr>';
 			$i++;
 		}
@@ -222,14 +237,17 @@ $sql .= ", s.canvas, s.status as thirdpartystatus";
 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
 $sql .= " WHERE p.entity IN (".getEntity('project').")";
-if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$projectsListId.")"; // If we have this test true, it also means projectset is not 2
-if ($socid)	$sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
+if ($mine || empty($user->rights->projet->all->lire)) {
+	$sql .= " AND p.rowid IN (".$projectsListId.")"; // If we have this test true, it also means projectset is not 2
+}
+if ($socid) {
+	$sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
+}
 $sql .= " ORDER BY p.tms DESC";
 $sql .= $db->plimit($max, 0);
 
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	print '<div class="div-table-responsive-no-min">';
 	print '<table class="noborder centpercent">';
 	print '<tr class="liste_titre">';
@@ -238,11 +256,9 @@ if ($resql)
 
 	$num = $db->num_rows($resql);
 
-	if ($num)
-	{
+	if ($num) {
 		$i = 0;
-		while ($i < $num)
-		{
+		while ($i < $num) {
 			$obj = $db->fetch_object($resql);
 
 			print '<tr class="oddeven">';
@@ -290,8 +306,7 @@ if ($resql)
 			print '</td>';
 
 			print '<td class="nowrap">';
-			if ($companystatic->id > 0)
-			{
+			if ($companystatic->id > 0) {
 				print $companystatic->getNomUrl(1, 'company', 16);
 			}
 			print '</td>';
@@ -304,7 +319,9 @@ if ($resql)
 		print '<tr><td colspan="4"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
 	}
 	print "</table></div>";
-} else dol_print_error($db);
+} else {
+	dol_print_error($db);
+}
 
 
 $companystatic = new Societe($db); // We need a clean new object for next loop because current one has some properties set.
@@ -320,15 +337,18 @@ $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid";
 $sql .= " WHERE p.entity IN (".getEntity('project').")";
 $sql .= " AND p.fk_statut = 1";
-if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$projectsListId.")"; // If we have this test true, it also means projectset is not 2
-if ($socid)	$sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
+if ($mine || empty($user->rights->projet->all->lire)) {
+	$sql .= " AND p.rowid IN (".$projectsListId.")"; // If we have this test true, it also means projectset is not 2
+}
+if ($socid) {
+	$sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")";
+}
 $sql .= " GROUP BY s.rowid, s.nom, s.name_alias, s.code_client, s.code_compta, s.client, s.code_fournisseur, s.code_compta_fournisseur, s.fournisseur, s.logo, s.email, s.entity, s.canvas, s.status";
 $sql .= $db->order($sortfield, $sortorder);
 //$sql .= $db->plimit($max + 1, 0);
 
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$num = $db->num_rows($resql);
 	$i = 0;
 	$othernb = 0;
@@ -345,8 +365,7 @@ if ($resql)
 		print "</tr>\n";
 	}
 
-	while ($i < $num)
-	{
+	while ($i < $num) {
 		$obj = $db->fetch_object($resql);
 
 		if ($i >= $max) {
@@ -357,8 +376,7 @@ if ($resql)
 
 		print '<tr class="oddeven">';
 		print '<td class="nowraponall tdoverflowmax100">';
-		if ($obj->socid > 0)
-		{
+		if ($obj->socid > 0) {
 			$companystatic->id = $obj->socid;
 			$companystatic->name = $obj->name;
 			$companystatic->name_alias = $obj->name_alias;
@@ -380,8 +398,11 @@ if ($resql)
 		}
 		print '</td>';
 		print '<td class="right">';
-		if ($obj->socid) print '<a href="'.DOL_URL_ROOT.'/projet/list.php?socid='.$obj->socid.'&search_status=1">'.$obj->nb.'</a>';
-		else print '<a href="'.DOL_URL_ROOT.'/projet/list.php?search_societe='.urlencode('^$').'&search_status=1">'.$obj->nb.'</a>';
+		if ($obj->socid) {
+			print '<a href="'.DOL_URL_ROOT.'/projet/list.php?socid='.$obj->socid.'&search_status=1">'.$obj->nb.'</a>';
+		} else {
+			print '<a href="'.DOL_URL_ROOT.'/projet/list.php?search_societe='.urlencode('^$').'&search_status=1">'.$obj->nb.'</a>';
+		}
 		print '</td>';
 		print "</tr>\n";
 
@@ -408,8 +429,7 @@ if ($resql)
 	dol_print_error($db);
 }
 
-if (empty($conf->global->PROJECT_HIDE_PROJECT_LIST_ON_PROJECT_AREA))
-{
+if (empty($conf->global->PROJECT_HIDE_PROJECT_LIST_ON_PROJECT_AREA)) {
 	// This list can be very long, so we allow to hide it to prefer to use the list page.
 	// Add constant PROJECT_HIDE_PROJECT_LIST_ON_PROJECT_AREA to hide this list
 

+ 36 - 26
htdocs/projet/info.php

@@ -42,16 +42,21 @@ $sortorder = GETPOST("sortorder", 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
 $page = is_numeric($page) ? $page : 0;
 $page = $page == -1 ? 0 : $page;
-if (!$sortfield) $sortfield = "a.datep,a.id";
-if (!$sortorder) $sortorder = "DESC";
+if (!$sortfield) {
+	$sortfield = "a.datep,a.id";
+}
+if (!$sortorder) {
+	$sortorder = "DESC";
+}
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
 
-if (GETPOST('actioncode', 'array'))
-{
+if (GETPOST('actioncode', 'array')) {
 	$actioncode = GETPOST('actioncode', 'array', 3);
-	if (!count($actioncode)) $actioncode = '0';
+	if (!count($actioncode)) {
+		$actioncode = '0';
+	}
 } else {
 	$actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
 }
@@ -63,7 +68,9 @@ $socid = 0;
 //if ($user->socid > 0) $socid = $user->socid;    // For external user, no check is done on company because readability is managed by public status of project and assignement.
 $result = restrictedArea($user, 'projet', $id, 'projet&project');
 
-if (!$user->rights->projet->lire)	accessforbidden();
+if (!$user->rights->projet->lire) {
+	accessforbidden();
+}
 
 
 
@@ -73,11 +80,12 @@ if (!$user->rights->projet->lire)	accessforbidden();
 
 $parameters = array('id'=>$socid);
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
 // Purge search criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
 	$actioncode = '';
 	$search_agenda_label = '';
 }
@@ -91,16 +99,19 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
 $form = new Form($db);
 $object = new Project($db);
 
-if ($id > 0 || !empty($ref))
-{
+if ($id > 0 || !empty($ref)) {
 	$object->fetch($id, $ref);
 	$object->fetch_thirdparty();
-	if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+	if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+		$object->fetchComments();
+	}
 	$object->info($object->id);
 }
 
 $title = $langs->trans("Project").' - '.$object->ref.' '.$object->name;
-if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info");
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
+	$title = $object->ref.' '.$object->name.' - '.$langs->trans("Info");
+}
 $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos";
 llxHeader("", $title, $help_url);
 
@@ -117,15 +128,13 @@ $morehtmlref = '<div class="refidno">';
 // Title
 $morehtmlref .= $object->title;
 // Thirdparty
-if ($object->thirdparty->id > 0)
-{
+if ($object->thirdparty->id > 0) {
 	$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project');
 }
 $morehtmlref .= '</div>';
 
 // Define a complementary filter for search of next/prev ref.
-if (!$user->rights->projet->all->lire)
-{
+if (!$user->rights->projet->all->lire) {
 	$objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0);
 	$object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 }
@@ -149,29 +158,30 @@ print dol_get_fiche_end();
 
 $out = '';
 $permok = $user->rights->agenda->myactions->create;
-if ($permok)
-{
+if ($permok) {
 	$out .= '&projectid='.$object->id;
 }
 
 
 //print '<div class="tabsAction">';
 $morehtmlcenter = '';
-if (!empty($conf->agenda->enabled))
-{
+if (!empty($conf->agenda->enabled)) {
 	$addActionBtnRight = !empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create);
-    $morehtmlcenter .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'&socid='.$object->socid.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id), '', $addActionBtnRight);
+	$morehtmlcenter .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'&socid='.$object->socid.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id), '', $addActionBtnRight);
 }
 
 //print '</div>';
 
-if (!empty($object->id))
-{
+if (!empty($object->id)) {
 	print '<br>';
 
 	$param = '&id='.$object->id;
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.$contextpage;
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.$limit;
+	}
 
 	print_barre_liste($langs->trans("ActionsOnProject"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlcenter, '', 0, 1, 1);
 

+ 37 - 21
htdocs/projet/jsgantt_language.js.php

@@ -20,13 +20,27 @@
  *		\brief      Fichier de javascript de traduction pour JSGantt
  */
 
-if (!defined('NOREQUIRESOC'))    define('NOREQUIRESOC', '1');
-if (!defined('NOCSRFCHECK'))     define('NOCSRFCHECK', 1);
-if (!defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL', 1);
-if (!defined('NOLOGIN'))         define('NOLOGIN', 1);
-if (!defined('NOREQUIREMENU'))   define('NOREQUIREMENU', 1);
-if (!defined('NOREQUIREHTML'))   define('NOREQUIREHTML', 1);
-if (!defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX', '1');
+if (!defined('NOREQUIRESOC')) {
+	define('NOREQUIRESOC', '1');
+}
+if (!defined('NOCSRFCHECK')) {
+	define('NOCSRFCHECK', 1);
+}
+if (!defined('NOTOKENRENEWAL')) {
+	define('NOTOKENRENEWAL', 1);
+}
+if (!defined('NOLOGIN')) {
+	define('NOLOGIN', 1);
+}
+if (!defined('NOREQUIREMENU')) {
+	define('NOREQUIREMENU', 1);
+}
+if (!defined('NOREQUIREHTML')) {
+	define('NOREQUIREHTML', 1);
+}
+if (!defined('NOREQUIREAJAX')) {
+	define('NOREQUIREAJAX', '1');
+}
 
 require_once __DIR__.'/../main.inc.php';
 
@@ -40,20 +54,22 @@ $langs->load("projects");
 var vLangs={'<?php print $langs->getDefaultLang(1); ?>':
 	{
 	'format':'<?php print $langs->transnoentities('Period'); ?>','hour':'"<?php print $langs->transnoentities('Hour'); ?>','day':'<?php print $langs->transnoentities('Day'); ?>',
-    'week':'<?php print $langs->transnoentities('Week'); ?>','month':'<?php print $langs->transnoentities('Month'); ?>','quarter':'<?php print $langs->transnoentities('Quadri'); ?>',
-    'hours':'<?php print $langs->transnoentities('Hours'); ?>','days':'<?php print $langs->transnoentities('Days'); ?>','weeks':'<?php print $langs->transnoentities('Weeks'); ?>',
-    'months':'<?php print $langs->transnoentities('Months'); ?>','quarters':'<?php print $langs->transnoentities('Quadri'); ?>','hr':'Hr','dy':'<?php print $langs->transnoentities('Day'); ?>','wk':'<?php print $langs->transnoentities('Week'); ?>','mth':'<?php print $langs->transnoentities('Month'); ?>','qtr':'<?php print $langs->transnoentities('Quadri'); ?>','hrs':'<?php print $langs->transnoentities('Hours'); ?>',
-    'dys':'<?php print $langs->transnoentities('Days'); ?>','wks':'<?php print $langs->transnoentities('Weeks'); ?>','mths':'<?php print $langs->transnoentities('Months'); ?>','qtrs':'<?php print $langs->transnoentities('Quadri'); ?>','resource':'<?php print dol_escape_js($langs->transnoentities('Resource')); ?>','duration':'<?php print dol_escape_js($langs->transnoentities('Duration')); ?>','comp':'%',
-    'completion':'<?php print $langs->transnoentities('Total'); ?>','startdate':'<?php print $langs->transnoentities('DateStart'); ?>','enddate':'<?php print $langs->transnoentities('DateEnd'); ?>','moreinfo':'<?php print dol_escape_js($langs->transnoentities('ShowTask')); ?>',
-    'notes':'<?php print $langs->transnoentities('NotePublic'); ?>',
-    'january':'<?php print $langs->transnoentities('January'); ?>','february':'<?php print $langs->transnoentities('February'); ?>','march':'<?php print $langs->transnoentities('March'); ?>','april':'<?php print $langs->transnoentities('April'); ?>','maylong':'<?php print $langs->transnoentities('May'); ?>','june':'<?php print $langs->transnoentities('June'); ?>','july':'<?php print $langs->transnoentities('July'); ?>',
-    'august':'<?php print $langs->transnoentities('August'); ?>','september':'<?php print $langs->transnoentities('September'); ?>','october':'<?php print $langs->transnoentities('October'); ?>','november':'<?php print $langs->transnoentities('November'); ?>','december':'<?php print $langs->transnoentities('December'); ?>',
-    'jan':'<?php print $langs->transnoentities('MonthShort01'); ?>','feb':'<?php print $langs->transnoentities('MonthShort02'); ?>','mar':'<?php print $langs->transnoentities('MonthShort03'); ?>','apr':'<?php print $langs->transnoentities('MonthShort04'); ?>','may':'<?php print $langs->transnoentities('MonthShort05'); ?>','jun':'<?php print $langs->transnoentities('MonthShort06'); ?>','jul':'<?php print $langs->transnoentities('MonthShort07'); ?>',
-    'aug':'<?php print $langs->transnoentities('MonthShort08'); ?>','sep':'<?php print $langs->transnoentities('MonthShort09'); ?>','oct':'<?php print $langs->transnoentities('MonthShort10'); ?>','nov':'<?php print $langs->transnoentities('MonthShort11'); ?>','dec':'<?php print $langs->transnoentities('MonthShort12'); ?>',
-    'sunday':'<?php print $langs->transnoentities('Sunday'); ?>','monday':'<?php print $langs->transnoentities('Monday'); ?>','tuesday':'<?php print $langs->transnoentities('Tuesday'); ?>','wednesday':'<?php print $langs->transnoentities('Wednesday'); ?>','thursday':'<?php print $langs->transnoentities('Thursday'); ?>','friday':'<?php print $langs->transnoentities('Friday'); ?>','saturday':'<?php print $langs->transnoentities('Saturday'); ?>',
-    'sun':'<?php print $langs->transnoentities('SundayMin'); ?>','mon':'<?php print $langs->transnoentities('MondayMin'); ?>','tue':'<?php print $langs->transnoentities('TuesdayMin'); ?>','wed':'<?php print $langs->transnoentities('WednesdayMin'); ?>','thu':'<?php print $langs->transnoentities('ThursdayMin'); ?>','fri':'<?php print $langs->transnoentities('FridayMin'); ?>','sat':'<?php print $langs->transnoentities('SaturdayMin'); ?>'
-    }
+	'week':'<?php print $langs->transnoentities('Week'); ?>','month':'<?php print $langs->transnoentities('Month'); ?>','quarter':'<?php print $langs->transnoentities('Quadri'); ?>',
+	'hours':'<?php print $langs->transnoentities('Hours'); ?>','days':'<?php print $langs->transnoentities('Days'); ?>','weeks':'<?php print $langs->transnoentities('Weeks'); ?>',
+	'months':'<?php print $langs->transnoentities('Months'); ?>','quarters':'<?php print $langs->transnoentities('Quadri'); ?>','hr':'Hr','dy':'<?php print $langs->transnoentities('Day'); ?>','wk':'<?php print $langs->transnoentities('Week'); ?>','mth':'<?php print $langs->transnoentities('Month'); ?>','qtr':'<?php print $langs->transnoentities('Quadri'); ?>','hrs':'<?php print $langs->transnoentities('Hours'); ?>',
+	'dys':'<?php print $langs->transnoentities('Days'); ?>','wks':'<?php print $langs->transnoentities('Weeks'); ?>','mths':'<?php print $langs->transnoentities('Months'); ?>','qtrs':'<?php print $langs->transnoentities('Quadri'); ?>','resource':'<?php print dol_escape_js($langs->transnoentities('Resource')); ?>','duration':'<?php print dol_escape_js($langs->transnoentities('Duration')); ?>','comp':'%',
+	'completion':'<?php print $langs->transnoentities('Total'); ?>','startdate':'<?php print $langs->transnoentities('DateStart'); ?>','enddate':'<?php print $langs->transnoentities('DateEnd'); ?>','moreinfo':'<?php print dol_escape_js($langs->transnoentities('ShowTask')); ?>',
+	'notes':'<?php print $langs->transnoentities('NotePublic'); ?>',
+	'january':'<?php print $langs->transnoentities('January'); ?>','february':'<?php print $langs->transnoentities('February'); ?>','march':'<?php print $langs->transnoentities('March'); ?>','april':'<?php print $langs->transnoentities('April'); ?>','maylong':'<?php print $langs->transnoentities('May'); ?>','june':'<?php print $langs->transnoentities('June'); ?>','july':'<?php print $langs->transnoentities('July'); ?>',
+	'august':'<?php print $langs->transnoentities('August'); ?>','september':'<?php print $langs->transnoentities('September'); ?>','october':'<?php print $langs->transnoentities('October'); ?>','november':'<?php print $langs->transnoentities('November'); ?>','december':'<?php print $langs->transnoentities('December'); ?>',
+	'jan':'<?php print $langs->transnoentities('MonthShort01'); ?>','feb':'<?php print $langs->transnoentities('MonthShort02'); ?>','mar':'<?php print $langs->transnoentities('MonthShort03'); ?>','apr':'<?php print $langs->transnoentities('MonthShort04'); ?>','may':'<?php print $langs->transnoentities('MonthShort05'); ?>','jun':'<?php print $langs->transnoentities('MonthShort06'); ?>','jul':'<?php print $langs->transnoentities('MonthShort07'); ?>',
+	'aug':'<?php print $langs->transnoentities('MonthShort08'); ?>','sep':'<?php print $langs->transnoentities('MonthShort09'); ?>','oct':'<?php print $langs->transnoentities('MonthShort10'); ?>','nov':'<?php print $langs->transnoentities('MonthShort11'); ?>','dec':'<?php print $langs->transnoentities('MonthShort12'); ?>',
+	'sunday':'<?php print $langs->transnoentities('Sunday'); ?>','monday':'<?php print $langs->transnoentities('Monday'); ?>','tuesday':'<?php print $langs->transnoentities('Tuesday'); ?>','wednesday':'<?php print $langs->transnoentities('Wednesday'); ?>','thursday':'<?php print $langs->transnoentities('Thursday'); ?>','friday':'<?php print $langs->transnoentities('Friday'); ?>','saturday':'<?php print $langs->transnoentities('Saturday'); ?>',
+	'sun':'<?php print $langs->transnoentities('SundayMin'); ?>','mon':'<?php print $langs->transnoentities('MondayMin'); ?>','tue':'<?php print $langs->transnoentities('TuesdayMin'); ?>','wed':'<?php print $langs->transnoentities('WednesdayMin'); ?>','thu':'<?php print $langs->transnoentities('ThursdayMin'); ?>','fri':'<?php print $langs->transnoentities('FridayMin'); ?>','sat':'<?php print $langs->transnoentities('SaturdayMin'); ?>'
+	}
 };
 var vLang='<?php print $langs->getDefaultLang(1); ?>';
 <?php
-if (is_object($db)) $db->close();
+if (is_object($db)) {
+	$db->close();
+}

File diff suppressed because it is too large
+ 508 - 298
htdocs/projet/list.php


+ 9 - 8
htdocs/projet/note.php

@@ -39,7 +39,9 @@ $mine = $_REQUEST['mode'] == 'mine' ? 1 : 0;
 $object = new Project($db);
 
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
-if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+	$object->fetchComments();
+}
 
 // Security check
 $socid = 0;
@@ -61,7 +63,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include,
  */
 
 $title = $langs->trans("Project").' - '.$langs->trans("Note").' - '.$object->ref.' '.$object->name;
-if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Note");
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
+	$title = $object->ref.' '.$object->name.' - '.$langs->trans("Note");
+}
 $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos";
 llxHeader("", $title, $help_url);
 
@@ -70,8 +74,7 @@ $userstatic = new User($db);
 
 $now = dol_now();
 
-if ($id > 0 || !empty($ref))
-{
+if ($id > 0 || !empty($ref)) {
 	// To verify role of users
 	//$userAccess = $object->restrictedProjectArea($user,'read');
 	$userWrite = $object->restrictedProjectArea($user, 'write');
@@ -90,15 +93,13 @@ if ($id > 0 || !empty($ref))
 	// Title
 	$morehtmlref .= $object->title;
 	// Thirdparty
-	if ($object->thirdparty->id > 0)
-	{
+	if ($object->thirdparty->id > 0) {
 		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project');
 	}
 	$morehtmlref .= '</div>';
 
 	// Define a complementary filter for search of next/prev ref.
-	if (!$user->rights->projet->all->lire)
-	{
+	if (!$user->rights->projet->all->lire) {
 		$objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0);
 		$object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 	}

+ 41 - 39
htdocs/projet/stats/index.php

@@ -28,8 +28,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/projet/class/projectstats.class.php';
 
 // Security check
-if (!$user->rights->projet->lire)
+if (!$user->rights->projet->lire) {
 	accessforbidden();
+}
 
 
 $WIDTH = DolGraph::getDefaultGraphSizeForStats('width');
@@ -38,8 +39,7 @@ $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height');
 $userid = GETPOST('userid', 'int');
 $socid = GETPOST('socid', 'int');
 // Security check
-if ($user->socid > 0)
-{
+if ($user->socid > 0) {
 	$action = '';
 	$socid = $user->socid;
 }
@@ -73,9 +73,15 @@ dol_mkdir($dir);
 
 
 $stats_project = new ProjectStats($db);
-if (!empty($userid) && $userid != -1) $stats_project->userid = $userid;
-if (!empty($socid) && $socid != -1) $stats_project->socid = $socid;
-if (!empty($year)) $stats_project->year = $year;
+if (!empty($userid) && $userid != -1) {
+	$stats_project->userid = $userid;
+}
+if (!empty($socid) && $socid != -1) {
+	$stats_project->socid = $socid;
+}
+if (!empty($year)) {
+	$stats_project->year = $year;
+}
 
 /*
 if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
@@ -149,12 +155,10 @@ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=projectstats&amp;file=proje
 
 $px1 = new DolGraph();
 $mesg = $px1->isGraphKo();
-if (!$mesg)
-{
+if (!$mesg) {
 	$px1->SetData($data);
 	$i = $startyear; $legend = array();
-	while ($i <= $endyear)
-	{
+	while ($i <= $endyear) {
 		$legend[] = $i;
 		$i++;
 	}
@@ -172,8 +176,7 @@ if (!$mesg)
 }
 
 
-if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-{
+if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 	// Build graphic amount of object
 	$data = $stats_project->getAmountByMonthWithPrevYear($endyear, $startyear);
 	//var_dump($data);
@@ -184,11 +187,9 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 
 	$px2 = new DolGraph();
 	$mesg = $px2->isGraphKo();
-	if (!$mesg)
-	{
+	if (!$mesg) {
 		$i = $startyear; $legend = array();
-		while ($i <= $endyear)
-		{
+		while ($i <= $endyear) {
 			$legend[] = $i;
 			$i++;
 		}
@@ -210,8 +211,7 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 	}
 }
 
-if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-{
+if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 	// Build graphic with transformation rate
 	$data = $stats_project->getWeightedAmountByMonthWithPrevYear($endyear, $startyear, 0, 0);
 	//var_dump($data);
@@ -222,12 +222,10 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 
 	$px3 = new DolGraph();
 	$mesg = $px3->isGraphKo();
-	if (!$mesg)
-	{
+	if (!$mesg) {
 		$px3->SetData($data);
 		$i = $startyear; $legend = array();
-		while ($i <= $endyear)
-		{
+		while ($i <= $endyear) {
 			$legend[] = $i;
 			$i++;
 		}
@@ -251,12 +249,16 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 $stats_project->year = 0;
 $data_all_year = $stats_project->getAllByYear();
 
-if (!empty($year)) $stats_project->year = $year;
+if (!empty($year)) {
+	$stats_project->year = $year;
+}
 $arrayyears = array();
 foreach ($data_all_year as $val) {
 	$arrayyears[$val['year']] = $val['year'];
 }
-if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear;
+if (!count($arrayyears)) {
+	$arrayyears[$nowyear] = $nowyear;
+}
 
 
 $h = 0;
@@ -288,8 +290,12 @@ print $form->select_dolusers($userid, 'userid', 1, array(),0,$includeuserlist);
 print '</td></tr>';*/
 // Year
 print '<tr><td>'.$langs->trans("Year").'</td><td>';
-if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year;
-if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear;
+if (!in_array($year, $arrayyears)) {
+	$arrayyears[$year] = $year;
+}
+if (!in_array($nowyear, $arrayyears)) {
+	$arrayyears[$nowyear] = $nowyear;
+}
 arsort($arrayyears);
 print $form->selectarray('year', $arrayyears, $year, 0);
 print '</td></tr>';
@@ -303,8 +309,7 @@ print '<table class="noborder centpercent">';
 print '<tr class="liste_titre" height="24">';
 print '<td class="center">'.$langs->trans("Year").'</td>';
 print '<td class="right">'.$langs->trans("NbOfProjects").'</td>';
-if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-{
+if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 	print '<td class="right">'.$langs->trans("OpportunityAmountShort").'</td>';
 	print '<td class="right">'.$langs->trans("OpportunityAmountAverageShort").'</td>';
 	print '<td class="right">'.$langs->trans("OpportunityAmountWeigthedShort").'</td>';
@@ -312,17 +317,14 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 print '</tr>';
 
 $oldyear = 0;
-foreach ($data_all_year as $val)
-{
+foreach ($data_all_year as $val) {
 	$year = $val['year'];
-	while ($year && $oldyear > $year + 1)
-	{	// If we have empty year
+	while ($year && $oldyear > $year + 1) {	// If we have empty year
 		$oldyear--;
 
 		print '<tr class="oddeven" height="24">';
 		print '<td class="center"><a href="'.$_SERVER["PHP_SELF"].'?year='.$oldyear.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$oldyear.'</a></td>';
-		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-		{
+		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 			print '<td class="right">0</td>';
 			print '<td class="right">0</td>';
 			print '<td class="right">0</td>';
@@ -334,8 +336,7 @@ foreach ($data_all_year as $val)
 	print '<tr class="oddeven" height="24">';
 	print '<td class="center"><a href="'.$_SERVER["PHP_SELF"].'?year='.$year.($socid > 0 ? '&socid='.$socid : '').($userid > 0 ? '&userid='.$userid : '').'">'.$year.'</a></td>';
 	print '<td class="right">'.$val['nb'].'</td>';
-	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-	{
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 		print '<td class="right">'.($val['total'] ?price(price2num($val['total'], 'MT'), 1) : '0').'</td>';
 		print '<td class="right">'.($val['avg'] ?price(price2num($val['avg'], 'MT'), 1) : '0').'</td>';
 		print '<td class="right">'.($val['weighted'] ?price(price2num($val['weighted'], 'MT'), 1) : '0').'</td>';
@@ -350,11 +351,12 @@ print '</div>';
 print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
 
 $stringtoshow .= '<table class="border centpercent"><tr class="pair nohover"><td class="center">';
-if ($mesg) { print $mesg; } else {
+if ($mesg) {
+	print $mesg;
+} else {
 	$stringtoshow .= $px1->show();
 	$stringtoshow .= "<br>\n";
-	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-	{
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 		//$stringtoshow .= $px->show();
 		//$stringtoshow .= "<br>\n";
 		$stringtoshow .= $px2->show();

+ 190 - 126
htdocs/projet/tasks.php

@@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
-if ($conf->categorie->enabled) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; }
+if ($conf->categorie->enabled) {
+	require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
+}
 
 // Load translation files required by the page
 $langs->loadLangs(array('projects', 'users', 'companies'));
@@ -51,7 +53,9 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; }     // If $page is not defined, or '' or -1 or if we click on clear filters
+if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1 or if we click on clear filters
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
@@ -83,10 +87,11 @@ $taskstatic = new Task($db);
 $extrafields = new ExtraFields($db);
 
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
-if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+	$object->fetchComments();
+}
 
-if ($id > 0 || !empty($ref))
-{
+if ($id > 0 || !empty($ref)) {
 	// fetch optionals attributes and labels
 	$extrafields->fetch_name_optionals_label($object->table_element);
 }
@@ -95,8 +100,12 @@ $search_array_options = $extrafields->getOptionalsFromPost($taskstatic->table_el
 
 
 // Default sort order (if not yet defined by previous GETPOST)
-if (!$sortfield) { reset($object->fields); $sortfield="t.".key($object->fields); }   // Set here default search field. By default 1st field in definition. Reset is required to avoid key() to return null.
-if (!$sortorder) $sortorder = "ASC";
+if (!$sortfield) {
+	reset($object->fields); $sortfield="t.".key($object->fields);
+}   // Set here default search field. By default 1st field in definition. Reset is required to avoid key() to return null.
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
 
 
 // Security check
@@ -148,16 +157,16 @@ $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
 
 $parameters = array('id'=>$id);
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	// Selection of new fields
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
 	// Purge search criteria
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-	{
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 		$search_user_id = "";
 		$search_taskref = '';
 		$search_tasklabel = '';
@@ -195,10 +204,14 @@ if (!empty($search_tasklabel)) {
 }
 
 $moresql = dolSqlDateFilter('t.dateo', $search_dtstartday, $search_dtstartmonth, $search_dtstartyear, 1);
-if ($moresql) $morewherefilterarray[] = $moresql;
+if ($moresql) {
+	$morewherefilterarray[] = $moresql;
+}
 
 $moresql = dolSqlDateFilter('t.datee', $search_dtendday, $search_dtendmonth, $search_dtendyear, 1);
-if ($moresql) $morewherefilterarray[] = $moresql;
+if ($moresql) {
+	$morewherefilterarray[] = $moresql;
+}
 
 if (!empty($search_planedworkload)) {
 	$morewherefilterarray[] = natural_search('t.planned_workload', $search_planedworkload, 1, 1);
@@ -223,8 +236,7 @@ if (count($morewherefilterarray) > 0) {
 	$morewherefilter = ' AND '.implode(' AND ', $morewherefilterarray);
 }
 
-if ($action == 'createtask' && $user->rights->projet->creer)
-{
+if ($action == 'createtask' && $user->rights->projet->creer) {
 	$error = 0;
 
 	// If we use user timezone, we must change also view/list to use user timezone everywhere
@@ -233,33 +245,32 @@ if ($action == 'createtask' && $user->rights->projet->creer)
 	$date_start = dol_mktime(GETPOST('dateohour', 'int'), GETPOST('dateomin', 'int'), 0, GETPOST('dateomonth', 'int'), GETPOST('dateoday', 'int'), GETPOST('dateoyear', 'int'));
 	$date_end = dol_mktime(GETPOST('dateehour', 'int'), GETPOST('dateemin', 'int'), 0, GETPOST('dateemonth', 'int'), GETPOST('dateeday', 'int'), GETPOST('dateeyear', 'int'));
 
-	if (!$cancel)
-	{
-		if (empty($taskref))
-		{
+	if (!$cancel) {
+		if (empty($taskref)) {
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors');
 			$action = 'create';
 			$error++;
 		}
-		if (empty($label))
-		{
+		if (empty($label)) {
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors');
 			$action = 'create';
 			$error++;
-		} elseif (empty($_POST['task_parent']))
-		{
+		} elseif (empty($_POST['task_parent'])) {
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ChildOfProjectTask")), null, 'errors');
 			$action = 'create';
 			$error++;
 		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			$tmparray = explode('_', GETPOST('task_parent'));
 			$projectid = $tmparray[0];
-			if (empty($projectid)) $projectid = $id; // If projectid is ''
+			if (empty($projectid)) {
+				$projectid = $id; // If projectid is ''
+			}
 			$task_parent = $tmparray[1];
-			if (empty($task_parent)) $task_parent = 0; // If task_parent is ''
+			if (empty($task_parent)) {
+				$task_parent = 0; // If task_parent is ''
+			}
 
 			$task = new Task($db);
 
@@ -279,12 +290,10 @@ if ($action == 'createtask' && $user->rights->projet->creer)
 
 			$taskid = $task->create($user);
 
-			if ($taskid > 0)
-			{
+			if ($taskid > 0) {
 				$result = $task->add_contact($_POST["userid"], 'TASKEXECUTIVE', 'internal');
 			} else {
-				if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
-				{
+				if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
 					$langs->load("projects");
 					setEventMessages($langs->trans('NewTaskRefSuggested'), '', 'warnings');
 					$duplicate_code_error = true;
@@ -296,26 +305,21 @@ if ($action == 'createtask' && $user->rights->projet->creer)
 			}
 		}
 
-		if (!$error)
-		{
-			if (!empty($backtopage))
-			{
+		if (!$error) {
+			if (!empty($backtopage)) {
 				header("Location: ".$backtopage);
 				exit;
-			} elseif (empty($projectid))
-			{
+			} elseif (empty($projectid)) {
 				header("Location: ".DOL_URL_ROOT.'/projet/tasks/list.php'.(empty($mode) ? '' : '?mode='.$mode));
 				exit;
 			}
 			$id = $projectid;
 		}
 	} else {
-		if (!empty($backtopage))
-		{
+		if (!empty($backtopage)) {
 			header("Location: ".$backtopage);
 			exit;
-		} elseif (empty($id))
-		{
+		} elseif (empty($id)) {
 			// We go back on task list
 			header("Location: ".DOL_URL_ROOT.'/projet/tasks/list.php'.(empty($mode) ? '' : '?mode='.$mode));
 			exit;
@@ -337,14 +341,15 @@ $taskstatic = new Task($db);
 $userstatic = new User($db);
 
 $title = $langs->trans("Project").' - '.$langs->trans("Tasks").' - '.$object->ref.' '.$object->name;
-if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Tasks");
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
+	$title = $object->ref.' '.$object->name.' - '.$langs->trans("Tasks");
+}
 $help_url = "EN:Module_Projects|FR:Module_Projets|ES:M&oacute;dulo_Proyectos";
 
 llxHeader("", $title, $help_url);
 
 
-if ($id > 0 || !empty($ref))
-{
+if ($id > 0 || !empty($ref)) {
 	$object->fetch($id, $ref);
 	$object->fetch_thirdparty();
 	$res = $object->fetch_optionals();
@@ -362,22 +367,54 @@ if ($id > 0 || !empty($ref))
 	print dol_get_fiche_head($head, $tab, $langs->trans("Project"), -1, ($object->public ? 'projectpub' : 'project'));
 
 	$param = '&id='.$object->id;
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($search_user_id)                 		$param .= '&search_user_id='.urlencode($search_user_id);
-	if ($search_taskref)              		$param .= '&search_taskref='.urlencode($search_taskref);
-	if ($search_tasklabel)              		$param .= '&search_tasklabel='.urlencode($search_tasklabel);
-	if ($search_taskdescription)              		$param .= '&search_taskdescription='.urlencode($search_taskdescription);
-	if ($search_dtstartday)              		$param .= '&search_dtstartday='.urlencode($search_dtstartday);
-	if ($search_dtstartmonth)              		$param .= '&search_dtstartmonth='.urlencode($search_dtstartmonth);
-	if ($search_dtstartyear)              		$param .= '&search_dtstartyear='.urlencode($search_dtstartyear);
-	if ($search_dtendday)              		$param .= '&search_dtendday='.urlencode($search_dtendday);
-	if ($search_dtendmonth)              		$param .= '&search_dtendmonth='.urlencode($search_dtendmonth);
-	if ($search_dtendyear)              		$param .= '&search_dtendyear='.urlencode($search_dtendyear);
-	if ($search_planedworkload)              		$param .= '&search_planedworkload='.urlencode($search_planedworkload);
-	if ($search_timespend)              		$param .= '&search_timespend='.urlencode($search_timespend);
-	if ($search_progresscalc)              		$param .= '&search_progresscalc='.urlencode($search_progresscalc);
-	if ($search_progressdeclare)              		$param .= '&search_progressdeclare='.urlencode($search_progressdeclare);
-	if ($optioncss != '')           $param .= '&optioncss='.urlencode($optioncss);
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($search_user_id) {
+		$param .= '&search_user_id='.urlencode($search_user_id);
+	}
+	if ($search_taskref) {
+		$param .= '&search_taskref='.urlencode($search_taskref);
+	}
+	if ($search_tasklabel) {
+		$param .= '&search_tasklabel='.urlencode($search_tasklabel);
+	}
+	if ($search_taskdescription) {
+		$param .= '&search_taskdescription='.urlencode($search_taskdescription);
+	}
+	if ($search_dtstartday) {
+		$param .= '&search_dtstartday='.urlencode($search_dtstartday);
+	}
+	if ($search_dtstartmonth) {
+		$param .= '&search_dtstartmonth='.urlencode($search_dtstartmonth);
+	}
+	if ($search_dtstartyear) {
+		$param .= '&search_dtstartyear='.urlencode($search_dtstartyear);
+	}
+	if ($search_dtendday) {
+		$param .= '&search_dtendday='.urlencode($search_dtendday);
+	}
+	if ($search_dtendmonth) {
+		$param .= '&search_dtendmonth='.urlencode($search_dtendmonth);
+	}
+	if ($search_dtendyear) {
+		$param .= '&search_dtendyear='.urlencode($search_dtendyear);
+	}
+	if ($search_planedworkload) {
+		$param .= '&search_planedworkload='.urlencode($search_planedworkload);
+	}
+	if ($search_timespend) {
+		$param .= '&search_timespend='.urlencode($search_timespend);
+	}
+	if ($search_progresscalc) {
+		$param .= '&search_progresscalc='.urlencode($search_progresscalc);
+	}
+	if ($search_progressdeclare) {
+		$param .= '&search_progressdeclare='.urlencode($search_progressdeclare);
+	}
+	if ($optioncss != '') {
+		$param .= '&optioncss='.urlencode($optioncss);
+	}
 	// Add $param from extra fields
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 
@@ -389,15 +426,13 @@ if ($id > 0 || !empty($ref))
 	// Title
 	$morehtmlref .= $object->title;
 	// Thirdparty
-	if ($object->thirdparty->id > 0)
-	{
+	if ($object->thirdparty->id > 0) {
 		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project');
 	}
 	$morehtmlref .= '</div>';
 
 	// Define a complementary filter for search of next/prev ref.
-	if (!$user->rights->projet->all->lire)
-	{
+	if (!$user->rights->projet->all->lire) {
 		$objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0);
 		$object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 	}
@@ -415,22 +450,19 @@ if ($id > 0 || !empty($ref))
 	print $langs->trans("Usage");
 	print '</td>';
 	print '<td>';
-	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-	{
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 		print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectFollowOpportunity");
 		print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
 		print '<br>';
 	}
-	if (empty($conf->global->PROJECT_HIDE_TASKS))
-	{
+	if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 		print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectFollowTasks");
 		print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
 		print '<br>';
 	}
-	if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-	{
+	if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) {
 		print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> ';
 		$htmltext = $langs->trans("ProjectBillTimeDescription");
 		print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
@@ -440,8 +472,11 @@ if ($id > 0 || !empty($ref))
 
 	// Visibility
 	print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-	if ($object->public) print $langs->trans('SharedProject');
-	else print $langs->trans('PrivateProject');
+	if ($object->public) {
+		print $langs->trans('SharedProject');
+	} else {
+		print $langs->trans('PrivateProject');
+	}
 	print '</td></tr>';
 
 	// Date start - end
@@ -451,12 +486,16 @@ if ($id > 0 || !empty($ref))
 	$end = dol_print_date($object->date_end, 'day');
 	print ' - ';
 	print ($end ? $end : '?');
-	if ($object->hasDelay()) print img_warning("Late");
+	if ($object->hasDelay()) {
+		print img_warning("Late");
+	}
 	print '</td></tr>';
 
 	// Budget
 	print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-	if (strcmp($object->budget_amount, '')) print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+	if (strcmp($object->budget_amount, '')) {
+		print price($object->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+	}
 	print '</td></tr>';
 
 	// Other attributes
@@ -497,9 +536,10 @@ if ($id > 0 || !empty($ref))
 }
 
 
-if ($action == 'create' && $user->rights->projet->creer && (empty($object->thirdparty->id) || $userWrite > 0))
-{
-	if ($id > 0 || !empty($ref)) print '<br>';
+if ($action == 'create' && $user->rights->projet->creer && (empty($object->thirdparty->id) || $userWrite > 0)) {
+	if ($id > 0 || !empty($ref)) {
+		print '<br>';
+	}
 
 	print load_fiche_titre($langs->trans("NewTask"), '', 'projecttask');
 
@@ -521,7 +561,9 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="createtask">';
 	print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
-	if (!empty($object->id)) print '<input type="hidden" name="id" value="'.$object->id.'">';
+	if (!empty($object->id)) {
+		print '<input type="hidden" name="id" value="'.$object->id.'">';
+	}
 
 	print dol_get_fiche_head('');
 
@@ -529,19 +571,19 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 
 	$defaultref = '';
 	$obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
-	if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php"))
-	{
+	if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php")) {
 		require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
 		$modTask = new $obj;
 		$defaultref = $modTask->getNextValue($object->thirdparty, null);
 	}
 
-	if (is_numeric($defaultref) && $defaultref <= 0) $defaultref = '';
+	if (is_numeric($defaultref) && $defaultref <= 0) {
+		$defaultref = '';
+	}
 
 	// Ref
 	print '<tr><td class="titlefieldcreate"><span class="fieldrequired">'.$langs->trans("Ref").'</span></td><td>';
-	if (empty($duplicate_code_error))
-	{
+	if (empty($duplicate_code_error)) {
 		print (GETPOSTISSET("ref") ? GETPOST("ref", 'alpha') : $defaultref);
 	} else {
 		print $defaultref;
@@ -561,8 +603,7 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 
 	print '<tr><td>'.$langs->trans("AffectedTo").'</td><td>';
 	$contactsofproject = (!empty($object->id) ? $object->getListContactId('internal') : '');
-	if (is_array($contactsofproject) && count($contactsofproject))
-	{
+	if (is_array($contactsofproject) && count($contactsofproject)) {
 		print $form->select_dolusers($user->id, 'userid', 0, '', 0, '', $contactsofproject, 0, 0, 0, '', 0, '', 'maxwidth300');
 	} else {
 		print $langs->trans("NoUserAssignedToTheProject");
@@ -600,8 +641,7 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 	$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $taskstatic, $action); // Note that $action and $object may have been modified by hook
 	print $hookmanager->resPrint;
 
-	if (empty($reshook) && !empty($extrafields->attributes[$taskstatic->table_element]['label']))
-	{
+	if (empty($reshook) && !empty($extrafields->attributes[$taskstatic->table_element]['label'])) {
 		print $taskstatic->showOptionals($extrafields, 'edit'); // Do not use $object here that is object of project but use $taskstatic
 	}
 
@@ -639,7 +679,9 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 	$linktocreatetask = dolGetButtonTitle($langs->trans('AddTask'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/projet/tasks.php?action=create'.$param.'&backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.$object->id), '', $linktocreatetaskUserRight, $linktocreatetaskParam);
 
 	print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="list">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
@@ -662,28 +704,27 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 
 	// We load also tasks limited to a particular user
 	$tmpuser = new User($db);
-	if ($search_user_id > 0) $tmpuser->fetch($search_user_id);
+	if ($search_user_id > 0) {
+		$tmpuser->fetch($search_user_id);
+	}
 
 	$tasksrole = ($tmpuser->id > 0 ? $taskstatic->getUserRolesForProjectsOrTasks(0, $tmpuser, $object->id, 0) : '');
 	//var_dump($tasksarray);
 	//var_dump($tasksrole);
 
-	if (!empty($conf->use_javascript_ajax))
-	{
+	if (!empty($conf->use_javascript_ajax)) {
 		include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
 	}
 
 	// Filter on categories
 	$moreforfilter = '';
-	if (count($tasksarray) > 0)
-	{
+	if (count($tasksarray) > 0) {
 		$moreforfilter .= '<div class="divsearchfield">';
 		$moreforfilter .= $langs->trans("TasksAssignedTo").': ';
 		$moreforfilter .= $form->select_dolusers($tmpuser->id > 0 ? $tmpuser->id : '', 'search_user_id', 1);
 		$moreforfilter .= '</div>';
 	}
-	if ($moreforfilter)
-	{
+	if ($moreforfilter) {
 		print '<div class="liste_titre liste_titre_bydiv centpercent">';
 		print $moreforfilter;
 		print '</div>';
@@ -756,8 +797,7 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 	// progress resume not searchable
 	print '<td class="liste_titre right"></td>';
 
-	if ($object->usage_bill_time)
-	{
+	if ($object->usage_bill_time) {
 		if (!empty($arrayfields['t.tobill']['checked'])) {
 			print '<td class="liste_titre right">';
 			print '</td>';
@@ -769,7 +809,9 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 		}
 	}
 
-	if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) print '<td class="liste_titre"></td>';
+	if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) {
+		print '<td class="liste_titre"></td>';
+	}
 
 	$extrafieldsobjectkey = $taskstatic->table_element;
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
@@ -783,22 +825,47 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 
 	print '<tr class="liste_titre nodrag nodrop">';
 	// print '<td>'.$langs->trans("Project").'</td>';
-	if (!empty($arrayfields['t.ref']['checked'])) print_liste_field_titre($arrayfields['t.ref']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, '');
-	if (!empty($arrayfields['t.label']['checked'])) print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, '');
-	if (!empty($arrayfields['t.description']['checked'])) print_liste_field_titre($arrayfields['t.description']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, '');
-	if (!empty($arrayfields['t.dateo']['checked'])) print_liste_field_titre($arrayfields['t.dateo']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center ');
-	if (!empty($arrayfields['t.datee']['checked'])) print_liste_field_titre($arrayfields['t.datee']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center ');
-	if (!empty($arrayfields['t.planned_workload']['checked'])) print_liste_field_titre($arrayfields['t.planned_workload']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1);
-	if (!empty($arrayfields['t.duration_effective']['checked'])) print_liste_field_titre($arrayfields['t.duration_effective']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1);
-	if (!empty($arrayfields['t.progress_calculated']['checked'])) print_liste_field_titre($arrayfields['t.progress_calculated']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1);
-	if (!empty($arrayfields['t.progress']['checked']))  print_liste_field_titre($arrayfields['t.progress']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1);
-	if (!empty($arrayfields['t.progress_summary']['checked'])) print_liste_field_titre($arrayfields['t.progress_summary']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center ', '', 1);
-	if ($object->usage_bill_time)
-	{
-		if (!empty($arrayfields['t.tobill']['checked']))  print_liste_field_titre($arrayfields['t.tobill']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ');
-		if (!empty($arrayfields['t.billed']['checked'])) print_liste_field_titre($arrayfields['t.billed']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ');
-	}
-	if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) print_liste_field_titre("TaskRessourceLinks", $_SERVER["PHP_SELF"], '', '', $param, $sortfield, $sortorder);
+	if (!empty($arrayfields['t.ref']['checked'])) {
+		print_liste_field_titre($arrayfields['t.ref']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, '');
+	}
+	if (!empty($arrayfields['t.label']['checked'])) {
+		print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, '');
+	}
+	if (!empty($arrayfields['t.description']['checked'])) {
+		print_liste_field_titre($arrayfields['t.description']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, '');
+	}
+	if (!empty($arrayfields['t.dateo']['checked'])) {
+		print_liste_field_titre($arrayfields['t.dateo']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center ');
+	}
+	if (!empty($arrayfields['t.datee']['checked'])) {
+		print_liste_field_titre($arrayfields['t.datee']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center ');
+	}
+	if (!empty($arrayfields['t.planned_workload']['checked'])) {
+		print_liste_field_titre($arrayfields['t.planned_workload']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1);
+	}
+	if (!empty($arrayfields['t.duration_effective']['checked'])) {
+		print_liste_field_titre($arrayfields['t.duration_effective']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1);
+	}
+	if (!empty($arrayfields['t.progress_calculated']['checked'])) {
+		print_liste_field_titre($arrayfields['t.progress_calculated']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1);
+	}
+	if (!empty($arrayfields['t.progress']['checked'])) {
+		print_liste_field_titre($arrayfields['t.progress']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', '', 1);
+	}
+	if (!empty($arrayfields['t.progress_summary']['checked'])) {
+		print_liste_field_titre($arrayfields['t.progress_summary']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center ', '', 1);
+	}
+	if ($object->usage_bill_time) {
+		if (!empty($arrayfields['t.tobill']['checked'])) {
+			print_liste_field_titre($arrayfields['t.tobill']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ');
+		}
+		if (!empty($arrayfields['t.billed']['checked'])) {
+			print_liste_field_titre($arrayfields['t.billed']['label'], $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ');
+		}
+	}
+	if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) {
+		print_liste_field_titre("TaskRessourceLinks", $_SERVER["PHP_SELF"], '', '', $param, $sortfield, $sortorder);
+	}
 	// Extra fields
 	$disablesortlink = 1;
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
@@ -809,14 +876,15 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 	print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
 	print "</tr>\n";
 
-	if (count($tasksarray) > 0)
-	{
+	if (count($tasksarray) > 0) {
 		// Show all lines in taskarray (recursive function to go down on tree)
 		$j = 0; $level = 0;
 		$nboftaskshown = projectLinesa($j, 0, $tasksarray, $level, true, 0, $tasksrole, $object->id, 1, $object->id, $filterprogresscalc, ($object->usage_bill_time ? 1 : 0), $arrayfields);
 	} else {
 		$colspan = 10;
-		if ($object->usage_bill_time) $colspan += 2;
+		if ($object->usage_bill_time) {
+			$colspan += 2;
+		}
 		print '<tr class="oddeven nobottom"><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoTasks").'</span></td></tr>';
 	}
 
@@ -828,18 +896,14 @@ if ($action == 'create' && $user->rights->projet->creer && (empty($object->third
 
 	// Test if database is clean. If not we clean it.
 	//print 'mode='.$_REQUEST["mode"].' $nboftaskshown='.$nboftaskshown.' count($tasksarray)='.count($tasksarray).' count($tasksrole)='.count($tasksrole).'<br>';
-	if (!empty($user->rights->projet->all->lire))	// We make test to clean only if user has permission to see all (test may report false positive otherwise)
-	{
-		if ($search_user_id == $user->id)
-		{
-			if ($nboftaskshown < count($tasksrole))
-			{
+	if (!empty($user->rights->projet->all->lire)) {	// We make test to clean only if user has permission to see all (test may report false positive otherwise)
+		if ($search_user_id == $user->id) {
+			if ($nboftaskshown < count($tasksrole)) {
 				include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 				cleanCorruptedTree($db, 'projet_task', 'fk_task_parent');
 			}
 		} else {
-			if ($nboftaskshown < count($tasksarray) && !GETPOST('search_user_id', 'int'))
-			{
+			if ($nboftaskshown < count($tasksarray) && !GETPOST('search_user_id', 'int')) {
 				include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 				cleanCorruptedTree($db, 'projet_task', 'fk_task_parent');
 			}

+ 50 - 44
htdocs/projet/tasks/comment.php

@@ -50,7 +50,9 @@ $planned_workload = ((GETPOST('planned_workloadhour', 'int') != '' || GETPOST('p
 // Security check
 $socid = 0;
 //if ($user->socid > 0) $socid = $user->socid;    // For external user, no check is done on company because readability is managed by public status of project and assignement.
-if (!$user->rights->projet->lire) accessforbidden();
+if (!$user->rights->projet->lire) {
+	accessforbidden();
+}
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 $hookmanager->initHooks(array('projecttaskcommentcard', 'globalcard'));
@@ -66,13 +68,10 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 include DOL_DOCUMENT_ROOT.'/core/actions_comments.inc.php';
 
 // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work
-if (!empty($project_ref) && !empty($withproject))
-{
-	if ($projectstatic->fetch('', $project_ref) > 0)
-	{
+if (!empty($project_ref) && !empty($withproject)) {
+	if ($projectstatic->fetch('', $project_ref) > 0) {
 		$objectsarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0);
-		if (count($objectsarray) > 0)
-		{
+		if (count($objectsarray) > 0) {
 			$id = $objectsarray[0]->id;
 		} else {
 			header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.(empty($mode) ? '' : '&mode='.$mode));
@@ -91,10 +90,8 @@ $form = new Form($db);
 $formother = new FormOther($db);
 $formfile = new FormFile($db);
 
-if ($id > 0 || !empty($ref))
-{
-	if ($object->fetch($id, $ref) > 0)
-	{
+if ($id > 0 || !empty($ref)) {
+	if ($object->fetch($id, $ref) > 0) {
 		$result = $object->fetch_optionals();
 
 		$result = $object->fetchComments();
@@ -103,15 +100,18 @@ if ($id > 0 || !empty($ref))
 		}
 
 		$result = $projectstatic->fetch($object->fk_project);
-		if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty();
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments();
+		if (!empty($projectstatic->socid)) {
+			$projectstatic->fetch_thirdparty();
+		}
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) {
+			$projectstatic->fetchComments();
+		}
 
 		$object->project = clone $projectstatic;
 
 		$userWrite = $projectstatic->restrictedProjectArea($user, 'write');
 
-		if (!empty($withproject))
-		{
+		if (!empty($withproject)) {
 			// Tabs for project
 			$tab = 'tasks';
 			$head = project_prepare_head($projectstatic);
@@ -127,15 +127,13 @@ if ($id > 0 || !empty($ref))
 			// Title
 			$morehtmlref .= $projectstatic->title;
 			// Thirdparty
-			if ($projectstatic->thirdparty->id > 0)
-			{
+			if ($projectstatic->thirdparty->id > 0) {
 				$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project');
 			}
 			$morehtmlref .= '</div>';
 
 			// Define a complementary filter for search of next/prev ref.
-			if (!$user->rights->projet->all->lire)
-			{
+			if (!$user->rights->projet->all->lire) {
 				$objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0);
 				$projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 			}
@@ -153,22 +151,19 @@ if ($id > 0 || !empty($ref))
 			print $langs->trans("Usage");
 			print '</td>';
 			print '<td>';
-			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-			{
+			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 				print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> ';
 				$htmltext = $langs->trans("ProjectFollowOpportunity");
 				print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
 				print '<br>';
 			}
-			if (empty($conf->global->PROJECT_HIDE_TASKS))
-			{
+			if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 				print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> ';
 				$htmltext = $langs->trans("ProjectFollowTasks");
 				print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
 				print '<br>';
 			}
-			if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-			{
+			if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) {
 				print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> ';
 				$htmltext = $langs->trans("ProjectBillTimeDescription");
 				print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
@@ -178,31 +173,39 @@ if ($id > 0 || !empty($ref))
 
 			// Visibility
 			print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-			if ($projectstatic->public) print $langs->trans('SharedProject');
-			else print $langs->trans('PrivateProject');
+			if ($projectstatic->public) {
+				print $langs->trans('SharedProject');
+			} else {
+				print $langs->trans('PrivateProject');
+			}
 			print '</td></tr>';
 
 			// Usage
-			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity))
-			{
+			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity)) {
 				// Opportunity status
 				print '<tr><td>'.$langs->trans("OpportunityStatus").'</td><td>';
 				$code = dol_getIdFromCode($db, $projectstatic->opp_status, 'c_lead_status', 'rowid', 'code');
-				if ($code) print $langs->trans("OppStatus".$code);
+				if ($code) {
+					print $langs->trans("OppStatus".$code);
+				}
 				print '</td></tr>';
 
 				// Opportunity percent
 				print '<tr><td>'.$langs->trans("OpportunityProbability").'</td><td>';
-				if (strcmp($object->opp_percent, '')) print price($projectstatic->opp_percent, 0, $langs, 1, 0).' %';
+				if (strcmp($object->opp_percent, '')) {
+					print price($projectstatic->opp_percent, 0, $langs, 1, 0).' %';
+				}
 				print '</td></tr>';
 
 				// Opportunity Amount
 				print '<tr><td>'.$langs->trans("OpportunityAmount").'</td><td>';
 				/*if ($object->opp_status)
-            	 {
-            	 print price($obj->opp_amount, 1, $langs, 1, 0, -1, $conf->currency);
-            	 }*/
-				if (strcmp($projectstatic->opp_amount, '')) print price($projectstatic->opp_amount, 0, $langs, 1, 0, -1, $conf->currency);
+				 {
+				 print price($obj->opp_amount, 1, $langs, 1, 0, -1, $conf->currency);
+				 }*/
+				if (strcmp($projectstatic->opp_amount, '')) {
+					print price($projectstatic->opp_amount, 0, $langs, 1, 0, -1, $conf->currency);
+				}
 				print '</td></tr>';
 			}
 
@@ -213,12 +216,16 @@ if ($id > 0 || !empty($ref))
 			$end = dol_print_date($projectstatic->date_end, 'day');
 			print ' - ';
 			print ($end ? $end : '?');
-			if ($projectstatic->hasDelay()) print img_warning("Late");
+			if ($projectstatic->hasDelay()) {
+				print img_warning("Late");
+			}
 			print '</td></tr>';
 
 			// Budget
 			print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-			if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+			if (strcmp($projectstatic->budget_amount, '')) {
+				print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+			}
 			print '</td></tr>';
 
 			// Other attributes
@@ -269,22 +276,21 @@ if ($id > 0 || !empty($ref))
 
 		print dol_get_fiche_head($head, 'task_comment', $langs->trans("Task"), -1, 'projecttask');
 
-		if ($action == 'delete')
-		{
+		if ($action == 'delete') {
 			print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$_GET["id"].'&withproject='.$withproject, $langs->trans("DeleteATask"), $langs->trans("ConfirmDeleteATask"), "confirm_delete");
 		}
 
-		if (!GETPOST('withproject') || empty($projectstatic->id))
-		{
+		if (!GETPOST('withproject') || empty($projectstatic->id)) {
 			$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1);
 			$object->next_prev_filter = " fk_projet in (".$projectsListId.")";
-		} else $object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+		} else {
+			$object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+		}
 
 		$morehtmlref = '';
 
 		// Project
-		if (empty($withproject))
-		{
+		if (empty($withproject)) {
 			$morehtmlref .= '<div class="refidno">';
 			$morehtmlref .= $langs->trans("Project").': ';
 			$morehtmlref .= $projectstatic->getNomUrl(1);

+ 83 - 83
htdocs/projet/tasks/contact.php

@@ -44,7 +44,9 @@ $project_ref = GETPOST('project_ref', 'alpha');
 $socid = 0;
 //if ($user->socid > 0) $socid = $user->socid;    // For external user, no check is done on company because readability is managed by public status of project and assignement.
 //$result = restrictedArea($user, 'projet', $id, 'projet_task');
-if (!$user->rights->projet->lire) accessforbidden();
+if (!$user->rights->projet->lire) {
+	accessforbidden();
+}
 
 $object = new Task($db);
 $projectstatic = new Project($db);
@@ -55,8 +57,7 @@ $projectstatic = new Project($db);
  */
 
 // Add new contact
-if ($action == 'addcontact' && $user->rights->projet->creer)
-{
+if ($action == 'addcontact' && $user->rights->projet->creer) {
 	$source  = 'internal';
 	if (GETPOST("addsourceexternal")) {
 		$source  ='external';
@@ -64,8 +65,7 @@ if ($action == 'addcontact' && $user->rights->projet->creer)
 
 	$result = $object->fetch($id, $ref);
 
-	if ($result > 0 && $id > 0)
-	{
+	if ($result > 0 && $id > 0) {
 		if ($source == 'internal') {
 			$idfortaskuser = ((GETPOST("userid") != 0 && GETPOST('userid') != -1) ? GETPOST("userid") : 0); // GETPOST('contactid') may val -1 to mean empty or -2 to means "everybody"
 			$typeid = GETPOST('type');
@@ -73,16 +73,13 @@ if ($action == 'addcontact' && $user->rights->projet->creer)
 			$idfortaskuser = ((GETPOST("contactid") > 0) ? GETPOST("contactid", 'int') : 0); // GETPOST('contactid') may val -1 to mean empty or -2 to means "everybody"
 			$typeid = GETPOST('typecontact');
 		}
-		if ($idfortaskuser == -2)
-		{
+		if ($idfortaskuser == -2) {
 			$result = $projectstatic->fetch($object->fk_project);
-			if ($result <= 0)
-			{
+			if ($result <= 0) {
 				dol_print_error($db, $projectstatic->error, $projectstatic->errors);
 			} else {
 				$contactsofproject = $projectstatic->getListContactId('internal');
-				foreach ($contactsofproject as $key => $val)
-				{
+				foreach ($contactsofproject as $key => $val) {
 					$result = $object->add_contact($val, $typeid, $source);
 				}
 			}
@@ -105,8 +102,7 @@ if ($action == 'addcontact' && $user->rights->projet->creer)
 }
 
 // bascule du statut d'un contact
-if ($action == 'swapstatut' && $user->rights->projet->creer)
-{
+if ($action == 'swapstatut' && $user->rights->projet->creer) {
 	if ($object->fetch($id, $ref)) {
 		$result = $object->swapContactStatus(GETPOST('ligne'));
 	} else {
@@ -115,13 +111,11 @@ if ($action == 'swapstatut' && $user->rights->projet->creer)
 }
 
 // Efface un contact
-if ($action == 'deleteline' && $user->rights->projet->creer)
-{
+if ($action == 'deleteline' && $user->rights->projet->creer) {
 	$object->fetch($id, $ref);
 	$result = $object->delete_contact($_GET["lineid"]);
 
-	if ($result >= 0)
-	{
+	if ($result >= 0) {
 		header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id.($withproject ? '&withproject=1' : ''));
 		exit;
 	} else {
@@ -130,13 +124,10 @@ if ($action == 'deleteline' && $user->rights->projet->creer)
 }
 
 // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work
-if (!empty($project_ref) && !empty($withproject))
-{
-	if ($projectstatic->fetch(0, $project_ref) > 0)
-	{
+if (!empty($project_ref) && !empty($withproject)) {
+	if ($projectstatic->fetch(0, $project_ref) > 0) {
 		$tasksarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0);
-		if (count($tasksarray) > 0)
-		{
+		if (count($tasksarray) > 0) {
 			$id = $tasksarray[0]->id;
 		} else {
 			header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.($withproject ? '&withproject=1' : '').(empty($mode) ? '' : '&mode='.$mode));
@@ -163,23 +154,26 @@ $userstatic = new User($db);
 /*                                                                             */
 /* *************************************************************************** */
 
-if ($id > 0 || !empty($ref))
-{
-	if ($object->fetch($id, $ref) > 0)
-	{
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+if ($id > 0 || !empty($ref)) {
+	if ($object->fetch($id, $ref) > 0) {
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+			$object->fetchComments();
+		}
 		$id = $object->id; // So when doing a search from ref, id is also set correctly.
 
 		$result = $projectstatic->fetch($object->fk_project);
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments();
-		if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty();
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) {
+			$projectstatic->fetchComments();
+		}
+		if (!empty($projectstatic->socid)) {
+			$projectstatic->fetch_thirdparty();
+		}
 
 		$object->project = clone $projectstatic;
 
 		$userWrite = $projectstatic->restrictedProjectArea($user, 'write');
 
-		if ($withproject)
-		{
+		if ($withproject) {
 			// Tabs for project
 			$tab = 'tasks';
 			$head = project_prepare_head($projectstatic);
@@ -195,15 +189,13 @@ if ($id > 0 || !empty($ref))
 			// Title
 			$morehtmlref .= $projectstatic->title;
 			// Thirdparty
-			if ($projectstatic->thirdparty->id > 0)
-			{
+			if ($projectstatic->thirdparty->id > 0) {
 				$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project');
 			}
 			$morehtmlref .= '</div>';
 
 			// Define a complementary filter for search of next/prev ref.
-			if (!$user->rights->projet->all->lire)
-			{
+			if (!$user->rights->projet->all->lire) {
 				$objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0);
 				$projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 			}
@@ -221,22 +213,19 @@ if ($id > 0 || !empty($ref))
 			print $langs->trans("Usage");
 			print '</td>';
 			print '<td>';
-			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-			{
+			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 				print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> ';
 				$htmltext = $langs->trans("ProjectFollowOpportunity");
 				print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
 				print '<br>';
 			}
-			if (empty($conf->global->PROJECT_HIDE_TASKS))
-			{
+			if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 				print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> ';
 				$htmltext = $langs->trans("ProjectFollowTasks");
 				print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
 				print '<br>';
 			}
-			if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-			{
+			if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) {
 				print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> ';
 				$htmltext = $langs->trans("ProjectBillTimeDescription");
 				print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
@@ -246,8 +235,11 @@ if ($id > 0 || !empty($ref))
 
 			// Visibility
 			print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-			if ($projectstatic->public) print $langs->trans('SharedProject');
-			else print $langs->trans('PrivateProject');
+			if ($projectstatic->public) {
+				print $langs->trans('SharedProject');
+			} else {
+				print $langs->trans('PrivateProject');
+			}
 			print '</td></tr>';
 
 			// Date start - end
@@ -257,12 +249,16 @@ if ($id > 0 || !empty($ref))
 			$end = dol_print_date($projectstatic->date_end, 'day');
 			print ' - ';
 			print ($end ? $end : '?');
-			if ($projectstatic->hasDelay()) print img_warning("Late");
+			if ($projectstatic->hasDelay()) {
+				print img_warning("Late");
+			}
 			print '</td></tr>';
 
 			// Budget
 			print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-			if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+			if (strcmp($projectstatic->budget_amount, '')) {
+				print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+			}
 			print '</td></tr>';
 
 			// Other attributes
@@ -315,17 +311,17 @@ if ($id > 0 || !empty($ref))
 		$param = (GETPOST('withproject') ? '&withproject=1' : '');
 		$linkback = GETPOST('withproject') ? '<a href="'.DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.'">'.$langs->trans("BackToList").'</a>' : '';
 
-		if (!GETPOST('withproject') || empty($projectstatic->id))
-		{
+		if (!GETPOST('withproject') || empty($projectstatic->id)) {
 			$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1);
 			$object->next_prev_filter = " fk_projet in (".$projectsListId.")";
-		} else $object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+		} else {
+			$object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+		}
 
 		$morehtmlref = '';
 
 		// Project
-		if (empty($withproject))
-		{
+		if (empty($withproject)) {
 			$result = $projectstatic->fetch($object->fk_project);
 			$morehtmlref .= '<div class="refidno">';
 			$morehtmlref .= $langs->trans("Project").': ';
@@ -354,8 +350,8 @@ if ($id > 0 || !empty($ref))
 		$dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
 		foreach($dirtpls as $reldir)
 		{
-		    $res=@include dol_buildpath($reldir.'/contacts.tpl.php');
-		    if ($res) break;
+			$res=@include dol_buildpath($reldir.'/contacts.tpl.php');
+			if ($res) break;
 		}
 		*/
 
@@ -366,12 +362,13 @@ if ($id > 0 || !empty($ref))
 		print '<input type="hidden" name="token" value="'.newToken().'">';
 		print '<input type="hidden" name="action" value="addcontact">';
 		print '<input type="hidden" name="id" value="'.$id.'">';
-		if ($withproject) print '<input type="hidden" name="withproject" value="'.$withproject.'">';
+		if ($withproject) {
+			print '<input type="hidden" name="withproject" value="'.$withproject.'">';
+		}
 
 		print '<table class="noborder centpercent">';
 
-		if ($action != 'editline' && $user->rights->projet->creer)
-		{
+		if ($action != 'editline' && $user->rights->projet->creer) {
 			print '<tr class="liste_titre">';
 			print '<td>'.$langs->trans("NatureOfContact").'</td>';
 			print '<td>'.$langs->trans("ThirdParty").'</td>';
@@ -393,8 +390,11 @@ if ($id > 0 || !empty($ref))
 
 			print '<td>';
 			// On recupere les id des users deja selectionnes
-			if ($object->project->public) $contactsofproject = ''; // Everybody
-			else $contactsofproject = $projectstatic->getListContactId('internal');
+			if ($object->project->public) {
+				$contactsofproject = ''; // Everybody
+			} else {
+				$contactsofproject = $projectstatic->getListContactId('internal');
+			}
 			print $form->select_dolusers((GETPOSTISSET('userid') ? GETPOST('userid', 'int') : $user->id), 'userid', 0, '', 0, '', $contactsofproject, 0, 0, 0, '', 1, $langs->trans("ResourceNotAssignedToProject"));
 			print '</td>';
 			print '<td>';
@@ -404,8 +404,7 @@ if ($id > 0 || !empty($ref))
 			print '</tr>';
 
 			// Line to add an external contact. Only if project linked to a third party.
-			if ($projectstatic->socid)
-			{
+			if ($projectstatic->socid) {
 				print '<tr class="oddeven">';
 
 				print '<td class="nowrap">';
@@ -427,7 +426,9 @@ if ($id > 0 || !empty($ref))
 				$formcompany->selectTypeContact($object, '', 'typecontact', 'external', 'rowid');
 				print '</td>';
 				print '<td class="right" colspan="3" ><input type="submit" class="button" id="add-customer-contact" name="addsourceexternal" value="'.$langs->trans("Add").'"';
-				if (!$nbofcontacts) print ' disabled';
+				if (!$nbofcontacts) {
+					print ' disabled';
+				}
 				print '></td>';
 				print '</tr>';
 			}
@@ -445,44 +446,42 @@ if ($id > 0 || !empty($ref))
 
 		$companystatic = new Societe($db);
 
-		foreach (array('internal', 'external') as $source)
-		{
+		foreach (array('internal', 'external') as $source) {
 			$tab = $object->liste_contact(-1, $source);
 
 			$num = count($tab);
 
 			$i = 0;
-			while ($i < $num)
-			{
+			while ($i < $num) {
 				print '<tr class="oddeven" valign="top">';
 
 				// Source
 				print '<td class="left">';
-				if ($tab[$i]['source'] == 'internal') print $langs->trans("User");
-				if ($tab[$i]['source'] == 'external') print $langs->trans("ThirdPartyContact");
+				if ($tab[$i]['source'] == 'internal') {
+					print $langs->trans("User");
+				}
+				if ($tab[$i]['source'] == 'external') {
+					print $langs->trans("ThirdPartyContact");
+				}
 				print '</td>';
 
 				// Societe
 				print '<td class="left">';
-				if ($tab[$i]['socid'] > 0)
-				{
+				if ($tab[$i]['socid'] > 0) {
 					$companystatic->fetch($tab[$i]['socid']);
 					print $companystatic->getNomUrl(1);
 				}
-				if ($tab[$i]['socid'] < 0)
-				{
+				if ($tab[$i]['socid'] < 0) {
 					print $conf->global->MAIN_INFO_SOCIETE_NOM;
 				}
-				if (!$tab[$i]['socid'])
-				{
+				if (!$tab[$i]['socid']) {
 					print '&nbsp;';
 				}
 				print '</td>';
 
 				// Contact
 				print '<td>';
-				if ($tab[$i]['source'] == 'internal')
-				{
+				if ($tab[$i]['source'] == 'internal') {
 					$userstatic->id = $tab[$i]['id'];
 					$userstatic->lastname = $tab[$i]['lastname'];
 					$userstatic->firstname = $tab[$i]['firstname'];
@@ -493,8 +492,7 @@ if ($id > 0 || !empty($ref))
 
 					print $userstatic->getNomUrl(-1);
 				}
-				if ($tab[$i]['source'] == 'external')
-				{
+				if ($tab[$i]['source'] == 'external') {
 					$contactstatic->id = $tab[$i]['id'];
 					$contactstatic->lastname = $tab[$i]['lastname'];
 					$contactstatic->firstname = $tab[$i]['firstname'];
@@ -510,15 +508,18 @@ if ($id > 0 || !empty($ref))
 				// Statut
 				print '<td class="center">';
 				// Activation desativation du contact
-				if ($object->statut >= 0) print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=swapstatut&ligne='.$tab[$i]['rowid'].($withproject ? '&withproject=1' : '').'">';
+				if ($object->statut >= 0) {
+					print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=swapstatut&ligne='.$tab[$i]['rowid'].($withproject ? '&withproject=1' : '').'">';
+				}
 				print $contactstatic->LibStatut($tab[$i]['status'], 3);
-				if ($object->statut >= 0) print '</a>';
+				if ($object->statut >= 0) {
+					print '</a>';
+				}
 				print '</td>';
 
 				// Icon update et delete
 				print '<td class="center nowrap">';
-				if ($user->rights->projet->creer)
-				{
+				if ($user->rights->projet->creer) {
 					print '&nbsp;';
 					print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deleteline&token='.newToken().'&lineid='.$tab[$i]['rowid'].($withproject ? '&withproject=1' : '').'">';
 					print img_picto($langs->trans('Unlink'), 'unlink');
@@ -539,8 +540,7 @@ if ($id > 0 || !empty($ref))
 	}
 }
 
-if (is_object($hookmanager))
-{
+if (is_object($hookmanager)) {
 	$hookmanager->initHooks(array('contacttpl'));
 	$parameters = array();
 	$reshook = $hookmanager->executeHooks('formContactTpl', $parameters, $object, $action);

+ 50 - 42
htdocs/projet/tasks/document.php

@@ -48,19 +48,27 @@ $project_ref = GETPOST('project_ref', 'alpha');
 $socid = 0;
 //if ($user->socid > 0) $socid = $user->socid;    // For external user, no check is done on company because readability is managed by public status of project and assignement.
 //$result=restrictedArea($user,'projet',$id,'');
-if (!$user->rights->projet->lire) accessforbidden();
+if (!$user->rights->projet->lire) {
+	accessforbidden();
+}
 
 // Get parameters
 $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortorder) $sortorder = "ASC";
-if (!$sortfield) $sortfield = "name";
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
+if (!$sortfield) {
+	$sortfield = "name";
+}
 
 $object = new Task($db);
 $projectstatic = new Project($db);
@@ -70,13 +78,10 @@ $projectstatic = new Project($db);
  */
 
 // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work
-if (!empty($project_ref) && !empty($withproject))
-{
-	if ($projectstatic->fetch(0, $project_ref) > 0)
-	{
+if (!empty($project_ref) && !empty($withproject)) {
+	if ($projectstatic->fetch(0, $project_ref) > 0) {
 		$tasksarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0);
-		if (count($tasksarray) > 0)
-		{
+		if (count($tasksarray) > 0) {
 			$id = $tasksarray[0]->id;
 			$object->fetch($id);
 		} else {
@@ -86,13 +91,15 @@ if (!empty($project_ref) && !empty($withproject))
 	}
 }
 
-if ($id > 0 || !empty($ref))
-{
-	if ($object->fetch($id, $ref) > 0)
-	{
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+if ($id > 0 || !empty($ref)) {
+	if ($object->fetch($id, $ref) > 0) {
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+			$object->fetchComments();
+		}
 		$projectstatic->fetch($object->fk_project);
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments();
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) {
+			$projectstatic->fetchComments();
+		}
 
 		if (!empty($projectstatic->socid)) {
 			$projectstatic->fetch_thirdparty();
@@ -117,14 +124,12 @@ $form = new Form($db);
 
 llxHeader('', $langs->trans('Task'));
 
-if ($object->id > 0)
-{
+if ($object->id > 0) {
 	$projectstatic->fetch_thirdparty();
 
 	$userWrite = $projectstatic->restrictedProjectArea($user, 'write');
 
-	if (!empty($withproject))
-	{
+	if (!empty($withproject)) {
 		// Tabs for project
 		$tab = 'tasks';
 		$head = project_prepare_head($projectstatic);
@@ -141,15 +146,13 @@ if ($object->id > 0)
 		// Title
 		$morehtmlref .= $projectstatic->title;
 		// Thirdparty
-		if ($projectstatic->thirdparty->id > 0)
-		{
+		if ($projectstatic->thirdparty->id > 0) {
 			$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project');
 		}
 		$morehtmlref .= '</div>';
 
 		// Define a complementary filter for search of next/prev ref.
-		if (!$user->rights->projet->all->lire)
-		{
+		if (!$user->rights->projet->all->lire) {
 			$objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0);
 			$projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 		}
@@ -167,22 +170,19 @@ if ($object->id > 0)
 		print $langs->trans("Usage");
 		print '</td>';
 		print '<td>';
-		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-		{
+		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 			print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> ';
 			$htmltext = $langs->trans("ProjectFollowOpportunity");
 			print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
 			print '<br>';
 		}
-		if (empty($conf->global->PROJECT_HIDE_TASKS))
-		{
+		if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 			print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> ';
 			$htmltext = $langs->trans("ProjectFollowTasks");
 			print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
 			print '<br>';
 		}
-		if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-		{
+		if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) {
 			print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> ';
 			$htmltext = $langs->trans("ProjectBillTimeDescription");
 			print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
@@ -192,8 +192,11 @@ if ($object->id > 0)
 
 		// Visibility
 		print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-		if ($projectstatic->public) print $langs->trans('SharedProject');
-		else print $langs->trans('PrivateProject');
+		if ($projectstatic->public) {
+			print $langs->trans('SharedProject');
+		} else {
+			print $langs->trans('PrivateProject');
+		}
 		print '</td></tr>';
 
 		// Date start - end
@@ -203,12 +206,16 @@ if ($object->id > 0)
 		$end = dol_print_date($projectstatic->date_end, 'day');
 		print ' - ';
 		print ($end ? $end : '?');
-		if ($projectstatic->hasDelay()) print img_warning("Late");
+		if ($projectstatic->hasDelay()) {
+			print img_warning("Late");
+		}
 		print '</td></tr>';
 
 		// Budget
 		print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-		if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+		if (strcmp($projectstatic->budget_amount, '')) {
+			print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+		}
 		print '</td></tr>';
 
 		// Other attributes
@@ -255,25 +262,24 @@ if ($object->id > 0)
 	// Files list constructor
 	$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
 	$totalsize = 0;
-	foreach ($filearray as $key => $file)
-	{
+	foreach ($filearray as $key => $file) {
 		$totalsize += $file['size'];
 	}
 
 	$param = (GETPOST('withproject') ? '&withproject=1' : '');
 	$linkback = GETPOST('withproject') ? '<a href="'.DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.'">'.$langs->trans("BackToList").'</a>' : '';
 
-	if (!GETPOST('withproject') || empty($projectstatic->id))
-	{
+	if (!GETPOST('withproject') || empty($projectstatic->id)) {
 		$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1);
 		$object->next_prev_filter = " fk_projet in (".$projectsListId.")";
-	} else $object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+	} else {
+		$object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+	}
 
 	$morehtmlref = '';
 
 	// Project
-	if (empty($withproject))
-	{
+	if (empty($withproject)) {
 		$morehtmlref .= '<div class="refidno">';
 		$morehtmlref .= $langs->trans("Project").': ';
 		$morehtmlref .= $projectstatic->getNomUrl(1);
@@ -307,7 +313,9 @@ if ($object->id > 0)
 	print '<br>';
 
 	$param = '';
-	if ($withproject) $param .= '&withproject=1';
+	if ($withproject) {
+		$param .= '&withproject=1';
+	}
 	$modulepart = 'project_task';
 	$permission = $user->rights->projet->creer;
 	$permtoedit = $user->rights->projet->creer;

File diff suppressed because it is too large
+ 479 - 254
htdocs/projet/tasks/list.php


+ 40 - 37
htdocs/projet/tasks/note.php

@@ -41,20 +41,26 @@ $project_ref = GETPOST('project_ref', 'alpha');
 // Security check
 $socid = 0;
 //if ($user->socid > 0) $socid = $user->socid;    // For external user, no check is done on company because readability is managed by public status of project and assignement.
-if (!$user->rights->projet->lire) accessforbidden();
+if (!$user->rights->projet->lire) {
+	accessforbidden();
+}
 //$result = restrictedArea($user, 'projet', $id, '', 'task'); // TODO ameliorer la verification
 
 $object = new Task($db);
 $projectstatic = new Project($db);
 
-if ($id > 0 || !empty($ref))
-{
-	if ($object->fetch($id, $ref) > 0)
-	{
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+if ($id > 0 || !empty($ref)) {
+	if ($object->fetch($id, $ref) > 0) {
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+			$object->fetchComments();
+		}
 		$projectstatic->fetch($object->fk_project);
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments();
-		if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty();
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) {
+			$projectstatic->fetchComments();
+		}
+		if (!empty($projectstatic->socid)) {
+			$projectstatic->fetch_thirdparty();
+		}
 
 		$object->project = clone $projectstatic;
 	} else {
@@ -64,13 +70,10 @@ if ($id > 0 || !empty($ref))
 
 
 // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work
-if (!empty($project_ref) && !empty($withproject))
-{
-	if ($projectstatic->fetch(0, $project_ref) > 0)
-	{
+if (!empty($project_ref) && !empty($withproject)) {
+	if ($projectstatic->fetch(0, $project_ref) > 0) {
 		$tasksarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0);
-		if (count($tasksarray) > 0)
-		{
+		if (count($tasksarray) > 0) {
 			$id = $tasksarray[0]->id;
 			$object->fetch($id);
 		} else {
@@ -100,12 +103,10 @@ $userstatic = new User($db);
 
 $now = dol_now();
 
-if ($object->id > 0)
-{
+if ($object->id > 0) {
 	$userWrite = $projectstatic->restrictedProjectArea($user, 'write');
 
-	if (!empty($withproject))
-	{
+	if (!empty($withproject)) {
 		// Tabs for project
 		$tab = 'tasks';
 		$head = project_prepare_head($projectstatic);
@@ -120,15 +121,13 @@ if ($object->id > 0)
 		// Title
 		$morehtmlref .= $projectstatic->title;
 		// Thirdparty
-		if ($projectstatic->thirdparty->id > 0)
-		{
+		if ($projectstatic->thirdparty->id > 0) {
 			$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project');
 		}
 		$morehtmlref .= '</div>';
 
 		// Define a complementary filter for search of next/prev ref.
-		if (!$user->rights->projet->all->lire)
-		{
+		if (!$user->rights->projet->all->lire) {
 			$objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0);
 			$projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 		}
@@ -146,22 +145,19 @@ if ($object->id > 0)
 		print $langs->trans("Usage");
 		print '</td>';
 		print '<td>';
-		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-		{
+		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 			print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> ';
 			$htmltext = $langs->trans("ProjectFollowOpportunity");
 			print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
 			print '<br>';
 		}
-		if (empty($conf->global->PROJECT_HIDE_TASKS))
-		{
+		if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 			print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> ';
 			$htmltext = $langs->trans("ProjectFollowTasks");
 			print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
 			print '<br>';
 		}
-		if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-		{
+		if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) {
 			print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> ';
 			$htmltext = $langs->trans("ProjectBillTimeDescription");
 			print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
@@ -171,8 +167,11 @@ if ($object->id > 0)
 
 		// Visibility
 		print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-		if ($projectstatic->public) print $langs->trans('SharedProject');
-		else print $langs->trans('PrivateProject');
+		if ($projectstatic->public) {
+			print $langs->trans('SharedProject');
+		} else {
+			print $langs->trans('PrivateProject');
+		}
 		print '</td></tr>';
 
 		// Date start - end
@@ -182,12 +181,16 @@ if ($object->id > 0)
 		$end = dol_print_date($projectstatic->date_end, 'day');
 		print ' - ';
 		print ($end ? $end : '?');
-		if ($projectstatic->hasDelay()) print img_warning("Late");
+		if ($projectstatic->hasDelay()) {
+			print img_warning("Late");
+		}
 		print '</td></tr>';
 
 		// Budget
 		print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-		if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+		if (strcmp($projectstatic->budget_amount, '')) {
+			print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+		}
 		print '</td></tr>';
 
 		// Other attributes
@@ -235,17 +238,17 @@ if ($object->id > 0)
 	$param = (GETPOST('withproject') ? '&withproject=1' : '');
 	$linkback = GETPOST('withproject') ? '<a href="'.DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.'">'.$langs->trans("BackToList").'</a>' : '';
 
-	if (!GETPOST('withproject') || empty($projectstatic->id))
-	{
+	if (!GETPOST('withproject') || empty($projectstatic->id)) {
 		$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1);
 		$object->next_prev_filter = " fk_projet in (".$projectsListId.")";
-	} else $object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+	} else {
+		$object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+	}
 
 	$morehtmlref = '';
 
 	// Project
-	if (empty($withproject))
-	{
+	if (empty($withproject)) {
 		$morehtmlref .= '<div class="refidno">';
 		$morehtmlref .= $langs->trans("Project").': ';
 		$morehtmlref .= $projectstatic->getNomUrl(1);

+ 31 - 19
htdocs/projet/tasks/stats/index.php

@@ -28,8 +28,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/projet/class/taskstats.class.php';
 
 // Security check
-if (!$user->rights->projet->lire)
+if (!$user->rights->projet->lire) {
 	accessforbidden();
+}
 
 
 $WIDTH = DolGraph::getDefaultGraphSizeForStats('width');
@@ -38,8 +39,7 @@ $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height');
 $userid = GETPOST('userid', 'int');
 $socid = GETPOST('socid', 'int');
 // Security check
-if ($user->socid > 0)
-{
+if ($user->socid > 0) {
 	$action = '';
 	$socid = $user->socid;
 }
@@ -73,9 +73,15 @@ dol_mkdir($dir);
 
 
 $stats_tasks = new TaskStats($db);
-if (!empty($userid) && $userid != -1) $stats_tasks->userid = $userid;
-if (!empty($socid) && $socid != -1) $stats_tasks->socid = $socid;
-if (!empty($year)) $stats_tasks->year = $year;
+if (!empty($userid) && $userid != -1) {
+	$stats_tasks->userid = $userid;
+}
+if (!empty($socid) && $socid != -1) {
+	$stats_tasks->socid = $socid;
+}
+if (!empty($year)) {
+	$stats_tasks->year = $year;
+}
 
 
 
@@ -89,12 +95,10 @@ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=taskstats&amp;file=tasknbpr
 
 $px1 = new DolGraph();
 $mesg = $px1->isGraphKo();
-if (!$mesg)
-{
+if (!$mesg) {
 	$px1->SetData($data);
 	$i = $startyear; $legend = array();
-	while ($i <= $endyear)
-	{
+	while ($i <= $endyear) {
 		$legend[] = $i;
 		$i++;
 	}
@@ -116,12 +120,16 @@ if (!$mesg)
 $stats_tasks->year = 0;
 $data_all_year = $stats_tasks->getAllByYear();
 
-if (!empty($year)) $stats_tasks->year = $year;
+if (!empty($year)) {
+	$stats_tasks->year = $year;
+}
 $arrayyears = array();
 foreach ($data_all_year as $val) {
 	$arrayyears[$val['year']] = $val['year'];
 }
-if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear;
+if (!count($arrayyears)) {
+	$arrayyears[$nowyear] = $nowyear;
+}
 
 
 $h = 0;
@@ -154,8 +162,12 @@ print $form->select_dolusers($userid, 'userid', 1, array(),0,$includeuserlist);
 print '</td></tr>';*/
 // Year
 print '<tr><td>'.$langs->trans("Year").'</td><td>';
-if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year;
-if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear;
+if (!in_array($year, $arrayyears)) {
+	$arrayyears[$year] = $year;
+}
+if (!in_array($nowyear, $arrayyears)) {
+	$arrayyears[$nowyear] = $nowyear;
+}
 arsort($arrayyears);
 print $form->selectarray('year', $arrayyears, $year, 0);
 print '</td></tr>';
@@ -173,11 +185,9 @@ print '<td class="right">'.$langs->trans("NbOfTasks").'</td>';
 print '</tr>';
 
 $oldyear = 0;
-foreach ($data_all_year as $val)
-{
+foreach ($data_all_year as $val) {
 	$year = $val['year'];
-	while ($year && $oldyear > $year + 1)
-	{	// If we have empty year
+	while ($year && $oldyear > $year + 1) {	// If we have empty year
 		$oldyear--;
 
 		print '<tr class="oddeven" height="24">';
@@ -199,7 +209,9 @@ print '</div>';
 print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
 
 $stringtoshow .= '<table class="border centpercent"><tr class="pair nohover"><td class="center">';
-if ($mesg) { print $mesg; } else {
+if ($mesg) {
+	print $mesg;
+} else {
 	$stringtoshow .= $px1->show();
 	$stringtoshow .= "<br>\n";
 }

+ 100 - 102
htdocs/projet/tasks/task.php

@@ -49,7 +49,9 @@ $planned_workload = ((GETPOST('planned_workloadhour', 'int') != '' || GETPOST('p
 // Security check
 $socid = 0;
 //if ($user->socid > 0) $socid = $user->socid;    // For external user, no check is done on company because readability is managed by public status of project and assignement.
-if (!$user->rights->projet->lire) accessforbidden();
+if (!$user->rights->projet->lire) {
+	accessforbidden();
+}
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 $hookmanager->initHooks(array('projecttaskcard', 'globalcard'));
@@ -63,34 +65,34 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 
 $parameters = array('id'=>$id);
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
 /*
  * Actions
  */
 
-if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer)
-{
+if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer) {
 	$error = 0;
 
-	if (empty($taskref))
-	{
+	if (empty($taskref)) {
 		$error++;
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors');
 	}
-	if (empty($_POST["label"]))
-	{
+	if (empty($_POST["label"])) {
 		$error++;
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors');
 	}
-	if (!$error)
-	{
+	if (!$error) {
 		$object->fetch($id, $ref);
 		$object->oldcopy = clone $object;
 
 		$tmparray = explode('_', $_POST['task_parent']);
 		$task_parent = $tmparray[1];
-		if (empty($task_parent)) $task_parent = 0; // If task_parent is ''
+		if (empty($task_parent)) {
+			$task_parent = 0; // If task_parent is ''
+		}
 
 		$object->ref = $taskref ? $taskref : GETPOST("ref", 'alpha', 2);
 		$object->label = GETPOST("label", "alphanohtml");
@@ -103,13 +105,13 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer)
 
 		// Fill array 'array_options' with data from add form
 		$ret = $extrafields->setOptionalsFromPost(null, $object);
-		if ($ret < 0) $error++;
+		if ($ret < 0) {
+			$error++;
+		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			$result = $object->update($user);
-			if ($result < 0)
-			{
+			if ($result < 0) {
 				setEventMessages($object->error, $object->errors, 'errors');
 			}
 		}
@@ -118,15 +120,12 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer)
 	}
 }
 
-if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->supprimer)
-{
-	if ($object->fetch($id, $ref) >= 0)
-	{
+if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->supprimer) {
+	if ($object->fetch($id, $ref) >= 0) {
 		$result = $projectstatic->fetch($object->fk_project);
 		$projectstatic->fetch_thirdparty();
 
-		if ($object->delete($user) > 0)
-		{
+		if ($object->delete($user) > 0) {
 			header('Location: '.DOL_URL_ROOT.'/projet/tasks.php?restore_lastsearch_values=1&id='.$projectstatic->id.($withproject ? '&withproject=1' : ''));
 			exit;
 		} else {
@@ -137,13 +136,10 @@ if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->s
 }
 
 // Retrieve First Task ID of Project if withprojet is on to allow project prev next to work
-if (!empty($project_ref) && !empty($withproject))
-{
-	if ($projectstatic->fetch('', $project_ref) > 0)
-	{
+if (!empty($project_ref) && !empty($withproject)) {
+	if ($projectstatic->fetch('', $project_ref) > 0) {
 		$tasksarray = $object->getTasksArray(0, 0, $projectstatic->id, $socid, 0);
-		if (count($tasksarray) > 0)
-		{
+		if (count($tasksarray) > 0) {
 			$id = $tasksarray[0]->id;
 		} else {
 			header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.(empty($mode) ? '' : '&mode='.$mode));
@@ -152,41 +148,41 @@ if (!empty($project_ref) && !empty($withproject))
 }
 
 // Build doc
-if ($action == 'builddoc' && $user->rights->projet->creer)
-{
+if ($action == 'builddoc' && $user->rights->projet->creer) {
 	$object->fetch($id, $ref);
 
 	// Save last template used to generate document
-	if (GETPOST('model')) $object->setDocModel($user, GETPOST('model', 'alpha'));
+	if (GETPOST('model')) {
+		$object->setDocModel($user, GETPOST('model', 'alpha'));
+	}
 
 	$outputlangs = $langs;
-	if (GETPOST('lang_id', 'aZ09'))
-	{
+	if (GETPOST('lang_id', 'aZ09')) {
 		$outputlangs = new Translate("", $conf);
 		$outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09'));
 	}
 	$result = $object->generateDocument($object->model_pdf, $outputlangs);
-	if ($result <= 0)
-	{
+	if ($result <= 0) {
 		setEventMessages($object->error, $object->errors, 'errors');
 		$action = '';
 	}
 }
 
 // Delete file in doc form
-if ($action == 'remove_file' && $user->rights->projet->creer)
-{
+if ($action == 'remove_file' && $user->rights->projet->creer) {
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 
-	if ($object->fetch($id, $ref) >= 0)
-	{
+	if ($object->fetch($id, $ref) >= 0) {
 		$langs->load("other");
 		$upload_dir = $conf->projet->dir_output;
 		$file = $upload_dir.'/'.dol_sanitizeFileName(GETPOST('file'));
 
 		$ret = dol_delete_file($file);
-		if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
-		else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
+		if ($ret) {
+			setEventMessages($langs->trans("FileWasRemoved", GETPOST('urlfile')), null, 'mesgs');
+		} else {
+			setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), null, 'errors');
+		}
 	}
 }
 
@@ -201,23 +197,26 @@ $form = new Form($db);
 $formother = new FormOther($db);
 $formfile = new FormFile($db);
 
-if ($id > 0 || !empty($ref))
-{
-	if ($object->fetch($id, $ref) > 0)
-	{
+if ($id > 0 || !empty($ref)) {
+	if ($object->fetch($id, $ref) > 0) {
 		$res = $object->fetch_optionals();
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) $object->fetchComments();
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK) && method_exists($object, 'fetchComments') && empty($object->comments)) {
+			$object->fetchComments();
+		}
 
 		$result = $projectstatic->fetch($object->fk_project);
-		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) $projectstatic->fetchComments();
-		if (!empty($projectstatic->socid)) $projectstatic->fetch_thirdparty();
+		if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT) && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) {
+			$projectstatic->fetchComments();
+		}
+		if (!empty($projectstatic->socid)) {
+			$projectstatic->fetch_thirdparty();
+		}
 
 		$object->project = clone $projectstatic;
 
 		//$userWrite = $projectstatic->restrictedProjectArea($user, 'write');
 
-		if (!empty($withproject))
-		{
+		if (!empty($withproject)) {
 			// Tabs for project
 			$tab = 'tasks';
 			$head = project_prepare_head($projectstatic);
@@ -233,15 +232,13 @@ if ($id > 0 || !empty($ref))
 			// Title
 			$morehtmlref .= $projectstatic->title;
 			// Thirdparty
-			if ($projectstatic->thirdparty->id > 0)
-			{
+			if ($projectstatic->thirdparty->id > 0) {
 				$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project');
 			}
 			$morehtmlref .= '</div>';
 
 			// Define a complementary filter for search of next/prev ref.
-			if (!$user->rights->projet->all->lire)
-			{
+			if (!$user->rights->projet->all->lire) {
 				$objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0);
 				$projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
 			}
@@ -259,22 +256,19 @@ if ($id > 0 || !empty($ref))
 			print $langs->trans("Usage");
 			print '</td>';
 			print '<td>';
-			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-			{
+			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) {
 				print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> ';
 				$htmltext = $langs->trans("ProjectFollowOpportunity");
 				print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
 				print '<br>';
 			}
-			if (empty($conf->global->PROJECT_HIDE_TASKS))
-			{
+			if (empty($conf->global->PROJECT_HIDE_TASKS)) {
 				print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> ';
 				$htmltext = $langs->trans("ProjectFollowTasks");
 				print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
 				print '<br>';
 			}
-			if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-			{
+			if (!empty($conf->global->PROJECT_BILL_TIME_SPENT)) {
 				print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> ';
 				$htmltext = $langs->trans("ProjectBillTimeDescription");
 				print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
@@ -284,8 +278,11 @@ if ($id > 0 || !empty($ref))
 
 			// Visibility
 			print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-			if ($projectstatic->public) print $langs->trans('SharedProject');
-			else print $langs->trans('PrivateProject');
+			if ($projectstatic->public) {
+				print $langs->trans('SharedProject');
+			} else {
+				print $langs->trans('PrivateProject');
+			}
 			print '</td></tr>';
 
 			// Date start - end
@@ -295,12 +292,16 @@ if ($id > 0 || !empty($ref))
 			$end = dol_print_date($projectstatic->date_end, 'day');
 			print ' - ';
 			print ($end ? $end : '?');
-			if ($projectstatic->hasDelay()) print img_warning("Late");
+			if ($projectstatic->hasDelay()) {
+				print img_warning("Late");
+			}
 			print '</td></tr>';
 
 			// Budget
 			print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-			if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+			if (strcmp($projectstatic->budget_amount, '')) {
+				print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+			}
 			print '</td></tr>';
 
 			// Other attributes
@@ -372,8 +373,7 @@ if ($id > 0 || !empty($ref))
 
 		$head = task_prepare_head($object);
 
-		if ($action == 'edit' && $user->rights->projet->creer)
-		{
+		if ($action == 'edit' && $user->rights->projet->creer) {
 			print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
 			print '<input type="hidden" name="token" value="'.newToken().'">';
 			print '<input type="hidden" name="action" value="update">';
@@ -393,16 +393,18 @@ if ($id > 0 || !empty($ref))
 			print '<td><input class="minwidth500" name="label" value="'.$object->label.'"></td></tr>';
 
 			// Project
-			if (empty($withproject))
-			{
+			if (empty($withproject)) {
 				print '<tr><td>'.$langs->trans("Project").'</td><td colspan="3">';
 				print $projectstatic->getNomUrl(1);
 				print '</td></tr>';
 
 				// Third party
 				print '<td>'.$langs->trans("ThirdParty").'</td><td colspan="3">';
-				if ($projectstatic->societe->id) print $projectstatic->societe->getNomUrl(1);
-				else print '&nbsp;';
+				if ($projectstatic->societe->id) {
+					print $projectstatic->societe->getNomUrl(1);
+				} else {
+					print '&nbsp;';
+				}
 				print '</td></tr>';
 			}
 
@@ -441,8 +443,7 @@ if ($id > 0 || !empty($ref))
 			$parameters = array();
 			$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
 			print $hookmanager->resPrint;
-			if (empty($reshook))
-			{
+			if (empty($reshook)) {
 				print $object->showOptionals($extrafields, 'edit');
 			}
 
@@ -465,22 +466,21 @@ if ($id > 0 || !empty($ref))
 
 			print dol_get_fiche_head($head, 'task_task', $langs->trans("Task"), -1, 'projecttask', 0, '', 'reposition');
 
-			if ($action == 'delete')
-			{
+			if ($action == 'delete') {
 				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$_GET["id"].'&withproject='.$withproject, $langs->trans("DeleteATask"), $langs->trans("ConfirmDeleteATask"), "confirm_delete");
 			}
 
-			if (!GETPOST('withproject') || empty($projectstatic->id))
-			{
+			if (!GETPOST('withproject') || empty($projectstatic->id)) {
 				$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1);
 				$object->next_prev_filter = " fk_projet in (".$projectsListId.")";
-			} else $object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+			} else {
+				$object->next_prev_filter = " fk_projet = ".$projectstatic->id;
+			}
 
 			$morehtmlref = '';
 
 			// Project
-			if (empty($withproject))
-			{
+			if (empty($withproject)) {
 				$morehtmlref .= '<div class="refidno">';
 				$morehtmlref .= $langs->trans("Project").': ';
 				$morehtmlref .= $projectstatic->getNomUrl(1);
@@ -504,8 +504,7 @@ if ($id > 0 || !empty($ref))
 
 			// Task parent
 			print '<tr><td>'.$langs->trans("ChildOfTask").'</td><td>';
-			if ($object->fk_task_parent > 0)
-			{
+			if ($object->fk_task_parent > 0) {
 				$tasktmp = new Task($db);
 				$tasktmp->fetch($object->fk_task_parent);
 				print $tasktmp->getNomUrl(1);
@@ -519,13 +518,14 @@ if ($id > 0 || !empty($ref))
 			$end = dol_print_date($object->date_end, 'dayhour');
 			print ' - ';
 			print ($end ? $end : '?');
-			if ($object->hasDelay()) print img_warning("Late");
+			if ($object->hasDelay()) {
+				print img_warning("Late");
+			}
 			print '</td></tr>';
 
 			// Planned workload
 			print '<tr><td>'.$langs->trans("PlannedWorkload").'</td><td colspan="3">';
-			if ($object->planned_workload != '')
-			{
+			if ($object->planned_workload != '') {
 				print convertSecondToTime($object->planned_workload, 'allhourmin');
 			}
 			print '</td></tr>';
@@ -545,20 +545,23 @@ if ($id > 0 || !empty($ref))
 
 			// Progress declared
 			print '<tr><td class="titlefield">'.$langs->trans("ProgressDeclared").'</td><td colspan="3">';
-			if ($object->progress != '')
-			{
+			if ($object->progress != '') {
 				print $object->progress.' %';
 			}
 			print '</td></tr>';
 
 			// Progress calculated
 			print '<tr><td>'.$langs->trans("ProgressCalculated").'</td><td colspan="3">';
-			if ($object->planned_workload != '')
-			{
+			if ($object->planned_workload != '') {
 				$tmparray = $object->getSummaryOfTimeSpent();
-				if ($tmparray['total_duration'] > 0 && !empty($object->planned_workload)) print round($tmparray['total_duration'] / $object->planned_workload * 100, 2).' %';
-				else print '0 %';
-			} else print '<span class="opacitymedium">'.$langs->trans("WorkloadNotDefined").'</span>';
+				if ($tmparray['total_duration'] > 0 && !empty($object->planned_workload)) {
+					print round($tmparray['total_duration'] / $object->planned_workload * 100, 2).' %';
+				} else {
+					print '0 %';
+				}
+			} else {
+				print '<span class="opacitymedium">'.$langs->trans("WorkloadNotDefined").'</span>';
+			}
 			print '</td></tr>';
 
 			// Other attributes
@@ -578,32 +581,27 @@ if ($id > 0 || !empty($ref))
 		}
 
 
-		if ($action != 'edit')
-		{
+		if ($action != 'edit') {
 			/*
 			 * Actions
- 			 */
+			  */
 
 			print '<div class="tabsAction">';
 
 			$parameters = array();
 			$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
 			// modified by hook
-			if (empty($reshook))
-			{
+			if (empty($reshook)) {
 				// Modify
-				if ($user->rights->projet->creer)
-				{
+				if ($user->rights->projet->creer) {
 					print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=edit&amp;withproject='.$withproject.'">'.$langs->trans('Modify').'</a>';
 				} else {
 					print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('Modify').'</a>';
 				}
 
 				// Delete
-				if ($user->rights->projet->supprimer)
-				{
-					if (!$object->hasChildren() && !$object->hasTimeSpent())
-					{
+				if ($user->rights->projet->supprimer) {
+					if (!$object->hasChildren() && !$object->hasTimeSpent()) {
 						print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'&amp;withproject='.$withproject.'">'.$langs->trans('Delete').'</a>';
 					} else {
 						print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("TaskHasChild").'">'.$langs->trans('Delete').'</a>';

File diff suppressed because it is too large
+ 263 - 228
htdocs/projet/tasks/time.php


Some files were not shown because too many files changed in this diff