
########## admin/notification.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/admin/notification.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/admin/notification.php	2025-04-28 08:31:10.888719000 +0000
@@ -390,6 +390,8 @@
 }
 */
 
+
+
 print '</form>';
 
 

########## admin/tools/export_files.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/admin/tools/export_files.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/admin/tools/export_files.php	2025-02-27 08:48:33.629319000 +0000
@@ -165,7 +165,6 @@
 		}
 	}
 
-	global $errormsg;
 	$ret = dol_compress_dir($fulldirtocompress, $outputdir."/".$file, $compression, $excludefiles, $rootdirinzip);
 	if ($ret < 0) {
 		if ($ret == -2) {

########## bookmarks/bookmarks.lib.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/bookmarks/bookmarks.lib.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/bookmarks/bookmarks.lib.php	2025-02-27 08:48:33.404780000 +0000
@@ -91,8 +91,8 @@
 	$newbtn = '';
 	if ($user->hasRight('bookmark', 'creer')) {
 		if (!preg_match('/bookmarks\/card.php/', $_SERVER['PHP_SELF'])) {
-			//$urltoadd=DOL_URL_ROOT.'/bookmarks/card.php?action=create&amp;url='.urlencode($url);	// With &amp; the GETPOST('url') will fail.
-			$urltoadd = DOL_URL_ROOT.'/bookmarks/card.php?action=create&url='.urlencode($url);
+			//$urltoadd=DOL_URL_ROOT.'/bookmarks/card.php?action=create&amp;urlsource='.urlencode($url).'&amp;url='.urlencode($url);
+			$urltoadd = DOL_URL_ROOT.'/bookmarks/card.php?action=create&amp;url='.urlencode($url);
 			$newbtn .= '<a class="top-menu-dropdown-link" title="'.$langs->trans('AddThisPageToBookmarks').'" href="'.dol_escape_htmltag($urltoadd).'" >';
 			$newbtn .= img_picto('', 'add', '', 0, 0, 0, '', 'pictofixedwidth paddingright').dol_escape_htmltag($langs->trans('AddThisPageToBookmarks')).'</a>';
 		}

########## categories/class/categorie.class.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/categories/class/categorie.class.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/categories/class/categorie.class.php	2025-02-27 08:48:35.233597000 +0000
@@ -1523,15 +1523,15 @@
 				}
 
 				if ($url == '') {
-					$link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.((int) $cat->id).'&type='.urlencode($cat->type).'" class="'.($i < count($way) ? 'small ': '').$forced_color.'">';
+					$link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$cat->id.'&type='.$cat->type.'" class="'.($i < count($way) ? 'small ': '').$forced_color.'">';
 					$linkend = '</a>';
 					$w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
 				} elseif ($url == 'none') {
-					$link = '<span class="'.($i < count($way) ? 'small ': '').$forced_color.'">';
+					$link = '<span class="'.$forced_color.'">';
 					$linkend = '</span>';
 					$w[] = $link.(($addpicto && $i == 1) ? img_object('', 'category', 'class="paddingright"') : '').$cat->label.$linkend;
 				} else {
-					$w[] = '<a class="'.($i < count($way) ? 'small ': '').$forced_color.'" href="'.DOL_URL_ROOT.'/'.$url.'?catid='.((int) $cat->id).'">'.($addpicto ? img_object('', 'category') : '').$cat->label.'</a>';
+					$w[] = '<a class="'.$forced_color.'" href="'.DOL_URL_ROOT.'/'.$url.'?catid='.$cat->id.'">'.($addpicto ? img_object('', 'category') : '').$cat->label.'</a>';
 				}
 			}
 			$newcategwithpath = preg_replace('/colortoreplace/', $forced_color, implode('<span class="inline-block valignmiddle paddingleft paddingright '.$forced_color.'">'.$sep.'</span>', $w));

########## comm/action/card.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/comm/action/card.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/comm/action/card.php	2025-05-26 12:57:19.098506000 +0000
@@ -33,21 +33,22 @@
 
 // Load Dolibarr environment
 require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
-require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
-require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncommreminder.class.php';
-require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
-require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
-require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
-require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
-require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/lib/agenda.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
+require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
+require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncommreminder.class.php';
+require_once DOL_DOCUMENT_ROOT . '/comm/action/class/cactioncomm.class.php';
+require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
+require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+require_once DOL_DOCUMENT_ROOT . '/projet/class/task.class.php';
+require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
+
 
 
 /**
@@ -173,6 +174,23 @@
  * Actions
  */
 
+
+
+$reminders = [];
+$sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "actioncomm_reminder WHERE fk_actioncomm = " . ((int) $object->id);
+$resql = $db->query($sql);
+if ($resql) {
+	while ($objRemnider = $db->fetch_object($resql)) {
+		$reminder = new ActionCommReminder($db);
+		if ($reminder->fetch($objRemnider->rowid) > 0) {
+			$reminders[] = $reminder;
+		}
+	}
+}
+
+
+
+
 $listUserAssignedUpdated = false;
 $listResourceAssignedUpdated = false;
 $assignedtouser = array();
@@ -296,7 +314,7 @@
 			}
 			$result = $object->createFromClone($user, GETPOSTINT('socid'));
 			if ($result > 0) {
-				header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
+				header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result);
 				exit();
 			} else {
 				setEventMessages($object->error, $object->errors, 'errors');
@@ -306,15 +324,103 @@
 	}
 }
 
+//MODIF JOSE
+
+// if (GETPOST('ajax', 'int') == 1 && GETPOST('action') == 'addreminder') {
+// 	header('Content-Type: application/json');
+
+// 	$reminder = new ActionCommReminder($db);
+// 	$reminder->fk_actioncomm = GETPOST('id', 'int');
+// 	$reminder->offsetvalue = GETPOST('offsetvalue', 'int');
+// 	$reminder->offsetunit = GETPOST('offsetunit', 'aZ09');
+// 	$reminder->typeremind = GETPOST('selectremindertype', 'aZ09');
+// 	$reminder->fk_email_template = GETPOST('actioncomm_send', 'int');
+// 	$reminder->fk_user = $user->id;
+// 	$reminder->entity = $conf->entity;
+// 	$reminder->status = 0;
+
+// 	if ($reminder->create($user) > 0) {
+// 		echo json_encode([
+// 			'success' => 1,
+// 			'id' => $reminder->id,
+// 			'type' => $reminder->typeremind,
+// 			'delay' => $reminder->offsetvalue . ' ' . $reminder->offsetunit
+// 		]);
+// 	} else {
+// 		http_response_code(500);
+// 		echo json_encode(['error' => $reminder->error]);
+// 	}
+// 	exit;
+// }
+
+
+if ($action == 'addreminder') {
+	$reminder = new ActionCommReminder($db);
+	$reminder->fk_actioncomm = $id;
+	$reminder->typeremind = GETPOST('typeremind', 'alpha');
+	$reminder->offsetvalue = GETPOST('offsetvalue', 'int');
+	$reminder->offsetunit = GETPOST('offsetunit', 'alpha');
+	$reminder->fk_user = $user->id;
+	$reminder->entity = $conf->entity;
+	$reminder->status = 0;
+
+	if ($reminder->create($user) < 0) {
+		setEventMessages($reminder->error, $reminder->errors, 'errors');
+	} else {
+		header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $object->id);
+		exit;
+	}
+}
+
+if ($action == 'massdeletereminder' && !empty($_POST['reminderids'])) {
+	require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncommreminder.class.php';
+	foreach ($_POST['reminderids'] as $idToDelete) {
+		$reminder = new ActionCommReminder($db);
+		if ($reminder->fetch((int) $idToDelete) > 0) {
+			$reminder->delete($user);
+		}
+	}
+	header("Location: " . dol_buildpath('/comm/action/card.php', 1) . '?id=' . (int) $reminder->fk_actioncomm);
+	exit;
+}
+
+
+
+
+if ($action == 'updatereminder') {
+	var_dump($object->id);
+	$reminderid = GETPOST('reminderid', 'int');
+	$reminder = new ActionCommReminder($db);
+	if ($reminder->fetch($reminderid) > 0) {
+		$reminder->offsetvalue = GETPOST('offsetvalue', 'int');
+		$reminder->offsetunit = GETPOST('offsetunit', 'aZ09');
+		$reminder->typeremind = GETPOST('selectremindertype', 'aZ09');
+		$reminder->fk_email_template = GETPOST('actioncomm_send', 'int');
+		$res = $reminder->update($user);
+		if ($res > 0) {
+			print '<meta http-equiv="refresh" content="1;url=' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '">';
+			exit;
+		} else {
+			setEventMessages($reminder->error, $reminder->errors, 'errors');
+		}
+	}
+}
+
+
+
+
+//END MODIF
+
+
 // Add event
 if (empty($reshook) && $action == 'add' && $usercancreate) {
 	$error = 0;
 
 	if (empty($backtopage)) {
 		if ($socid > 0) {
-			$backtopage = DOL_URL_ROOT.'/societe/agenda.php?socid='.$socid;
+			$backtopage = DOL_URL_ROOT . '/societe/agenda.php?socid=' . $socid;
 		} else {
-			$backtopage = DOL_URL_ROOT.'/comm/action/index.php';
+			$backtopage = DOL_URL_ROOT . '/comm/action/index.php';
 		}
 	}
 
@@ -323,7 +429,7 @@
 	}
 
 	if ($cancel) {
-		header("Location: ".$backtopage);
+		header("Location: " . $backtopage);
 		exit;
 	}
 
@@ -399,8 +505,8 @@
 			if (GETPOST('actioncode', 'aZ09') == 'AC_RDV' && $contact->getFullName($langs)) {
 				$object->label = $langs->transnoentitiesnoconv("TaskRDVWith", $contact->getFullName($langs));
 			} else {
-				if ($langs->trans("Action".$object->type_code) != "Action".$object->type_code) {
-					$object->label = $langs->transnoentitiesnoconv("Action".$object->type_code)."\n";
+				if ($langs->trans("Action" . $object->type_code) != "Action" . $object->type_code) {
+					$object->label = $langs->transnoentitiesnoconv("Action" . $object->type_code) . "\n";
 				} else {
 					$cactioncomm->fetch($object->type_code);
 					$object->label = $cactioncomm->label;
@@ -512,9 +618,9 @@
 		$selectedrecurrulefreq = 'no';
 		$selectedrecurrulebymonthday = '';
 		$selectedrecurrulebyday = '';
-		$object->recurrule = GETPOSTISSET('recurrulefreq') ? "FREQ=".GETPOST('recurrulefreq', 'alpha') : "";
-		$object->recurrule .= (GETPOST('recurrulefreq', 'alpha') == 'MONTHLY' && GETPOSTISSET('BYMONTHDAY')) ? "_BYMONTHDAY".GETPOST('BYMONTHDAY', 'alpha') : "";
-		$object->recurrule .= (GETPOST('recurrulefreq', 'alpha') == 'WEEKLY' && GETPOSTISSET('BYDAY')) ? "_BYDAY".GETPOST('BYDAY', 'alpha') : "";
+		$object->recurrule = GETPOSTISSET('recurrulefreq') ? "FREQ=" . GETPOST('recurrulefreq', 'alpha') : "";
+		$object->recurrule .= (GETPOST('recurrulefreq', 'alpha') == 'MONTHLY' && GETPOSTISSET('BYMONTHDAY')) ? "_BYMONTHDAY" . GETPOST('BYMONTHDAY', 'alpha') : "";
+		$object->recurrule .= (GETPOST('recurrulefreq', 'alpha') == 'WEEKLY' && GETPOSTISSET('BYDAY')) ? "_BYDAY" . GETPOST('BYDAY', 'alpha') : "";
 
 		$reg1 = array();
 		$reg2 = array();
@@ -551,7 +657,7 @@
 				if (is_array($listofresourceid) && count($listofresourceid)) {
 					foreach ($listofresourceid as $resource_id => $val) {
 						$resource_type = 'dolresource';
-						$busy = 1;//GETPOSTINT('busy');
+						$busy = 1; //GETPOSTINT('busy');
 
 						// Resources association
 						if (getDolGlobalString('RESOURCE_USED_IN_EVENT_CHECK')) {
@@ -665,7 +771,7 @@
 				 $moreparam .= ($moreparam ? '&' : '').'search_status=-1';
 				 $moreparam .= ($moreparam ? '&' : '').'search_filtert='.$object->userownerid;
 				 */
-				$moreparam .= ($moreparam ? '&' : '').'disabledefaultvalues=1';
+				$moreparam .= ($moreparam ? '&' : '') . 'disabledefaultvalues=1';
 
 				if ($error) {
 					$db->rollback();
@@ -705,12 +811,12 @@
 			if ($selectedrecurrulefreq == 'WEEKLY' && !empty($selectedrecurrulebyday)) {
 				$firstdatearray = dol_get_first_day_week(GETPOSTINT("apday"), GETPOSTINT("apmonth"), GETPOSTINT("apyear"));
 				$datep = dol_mktime($fulldayevent ? 0 : GETPOSTINT("aphour"), $fulldayevent ? 0 : GETPOSTINT("apmin"), $fulldayevent ? 0 : GETPOSTINT("apsec"), $firstdatearray['month'], $firstdatearray['first_day'], $firstdatearray['year'], $tzforfullday ? $tzforfullday : 'tzuserrel');
-				$datep = dol_time_plus_duree($datep, $selectedrecurrulebyday + 6, 'd');//We begin the week after
+				$datep = dol_time_plus_duree($datep, $selectedrecurrulebyday + 6, 'd'); //We begin the week after
 				$dayoffset = 7;
 				$monthoffset = 0;
 			} elseif ($selectedrecurrulefreq == 'MONTHLY' && !empty($selectedrecurrulebymonthday)) {
 				$firstday = $selectedrecurrulebymonthday;
-				$firstmonth = GETPOST("apday") > $selectedrecurrulebymonthday ? GETPOSTINT("apmonth") + 1 : GETPOSTINT("apmonth");//We begin the week after
+				$firstmonth = GETPOST("apday") > $selectedrecurrulebymonthday ? GETPOSTINT("apmonth") + 1 : GETPOSTINT("apmonth"); //We begin the week after
 				$datep = dol_mktime($fulldayevent ? 0 : GETPOSTINT("aphour"), $fulldayevent ? 0 : GETPOSTINT("apmin"), $fulldayevent ? 0 : GETPOSTINT("apsec"), $firstmonth, $firstday, GETPOSTINT("apyear"), $tzforfullday ? $tzforfullday : 'tzuserrel');
 				$dayoffset = 0;
 				$monthoffset = 1;
@@ -785,7 +891,7 @@
 						 $moreparam .= ($moreparam ? '&' : '').'search_status=-1';
 						 $moreparam .= ($moreparam ? '&' : '').'search_filtert='.$object->userownerid;
 						 */
-						$moreparam .= ($moreparam ? '&' : '').'disabledefaultvalues=1';
+						$moreparam .= ($moreparam ? '&' : '') . 'disabledefaultvalues=1';
 
 						if ($error) {
 							$db->rollback();
@@ -821,12 +927,12 @@
 			}
 		}
 		if (!empty($backtopage) && !$error) {
-			dol_syslog("Back to ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : ''));
-			header("Location: ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : ''));
+			dol_syslog("Back to " . $backtopage . ($moreparam ? (preg_match('/\?/', $backtopage) ? '&' . $moreparam : '?' . $moreparam) : ''));
+			header("Location: " . $backtopage . ($moreparam ? (preg_match('/\?/', $backtopage) ? '&' . $moreparam : '?' . $moreparam) : ''));
 		} elseif ($idaction) {
-			header("Location: ".DOL_URL_ROOT.'/comm/action/card.php?id='.$idaction.($moreparam ? '&'.$moreparam : ''));
+			header("Location: " . DOL_URL_ROOT . '/comm/action/card.php?id=' . $idaction . ($moreparam ? '&' . $moreparam : ''));
 		} else {
-			header("Location: ".DOL_URL_ROOT.'/comm/action/index.php'.($moreparam ? '?'.$moreparam : ''));
+			header("Location: " . DOL_URL_ROOT . '/comm/action/index.php' . ($moreparam ? '?' . $moreparam : ''));
 		}
 		exit;
 	}
@@ -994,30 +1100,30 @@
 				$eventDateEnd = $object->datef;
 
 				$sql  = "SELECT er.rowid, r.ref as r_ref, ac.id as ac_id, ac.label as ac_label";
-				$sql .= " FROM ".MAIN_DB_PREFIX."element_resources as er";
-				$sql .= " INNER JOIN ".MAIN_DB_PREFIX."resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'";
-				$sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm as ac ON ac.id = er.element_id AND er.element_type = '".$db->escape($object->element)."'";
-				$sql .= " WHERE ac.id <> ".((int) $object->id);
+				$sql .= " FROM " . MAIN_DB_PREFIX . "element_resources as er";
+				$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'";
+				$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "actioncomm as ac ON ac.id = er.element_id AND er.element_type = '" . $db->escape($object->element) . "'";
+				$sql .= " WHERE ac.id <> " . ((int) $object->id);
 				$sql .= " AND er.resource_id IN (";
-				$sql .= " SELECT resource_id FROM ".MAIN_DB_PREFIX."element_resources";
-				$sql .= " WHERE element_id = ".((int) $object->id);
-				$sql .= " AND element_type = '".$db->escape($object->element)."'";
+				$sql .= " SELECT resource_id FROM " . MAIN_DB_PREFIX . "element_resources";
+				$sql .= " WHERE element_id = " . ((int) $object->id);
+				$sql .= " AND element_type = '" . $db->escape($object->element) . "'";
 				$sql .= " AND busy = 1";
 				$sql .= ")";
 				$sql .= " AND er.busy = 1";
 				$sql .= " AND (";
 
 				// event date start between ac.datep and ac.datep2 (if datep2 is null we consider there is no end)
-				$sql .= " (ac.datep <= '".$db->idate($eventDateStart)."' AND (ac.datep2 IS NULL OR ac.datep2 >= '".$db->idate($eventDateStart)."'))";
+				$sql .= " (ac.datep <= '" . $db->idate($eventDateStart) . "' AND (ac.datep2 IS NULL OR ac.datep2 >= '" . $db->idate($eventDateStart) . "'))";
 				// event date end between ac.datep and ac.datep2
 				if (!empty($eventDateEnd)) {
-					$sql .= " OR (ac.datep <= '".$db->idate($eventDateEnd)."' AND (ac.datep2 >= '".$db->idate($eventDateEnd)."'))";
+					$sql .= " OR (ac.datep <= '" . $db->idate($eventDateEnd) . "' AND (ac.datep2 >= '" . $db->idate($eventDateEnd) . "'))";
 				}
 				// event date start before ac.datep and event date end after ac.datep2
 				$sql .= " OR (";
-				$sql .= "ac.datep >= '".$db->idate($eventDateStart)."'";
+				$sql .= "ac.datep >= '" . $db->idate($eventDateStart) . "'";
 				if (!empty($eventDateEnd)) {
-					$sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '".$db->idate($eventDateEnd)."')";
+					$sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '" . $db->idate($eventDateEnd) . "')";
 				}
 				$sql .= ")";
 
@@ -1031,9 +1137,9 @@
 					if ($db->num_rows($resql) > 0) {
 						// Resource already in use
 						$error++;
-						$object->error = $langs->trans('ErrorResourcesAlreadyInUse').' : ';
+						$object->error = $langs->trans('ErrorResourcesAlreadyInUse') . ' : ';
 						while ($obj = $db->fetch_object($resql)) {
-							$object->error .= '<br> - '.$langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label.' ['.$obj->ac_id.']');
+							$object->error .= '<br> - ' . $langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label . ' [' . $obj->ac_id . ']');
 						}
 						$object->errors[] = $object->error;
 					}
@@ -1090,8 +1196,8 @@
 
 						// We update the event, so we recreate the notification event.
 						// First we delete all reminders for the user and the type of reminding (all offset dates).
-						$sqldelete = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
-						$sqldelete .= " WHERE fk_user = ".((int) $actionCommReminder->fk_user)." AND fk_actioncomm = ".((int) $object->id)." AND typeremind = '".$db->escape($remindertype)."'";
+						$sqldelete = "DELETE FROM " . MAIN_DB_PREFIX . "actioncomm_reminder";
+						$sqldelete .= " WHERE fk_user = " . ((int) $actionCommReminder->fk_user) . " AND fk_actioncomm = " . ((int) $object->id) . " AND typeremind = '" . $db->escape($remindertype) . "'";
 						$resqldelete = $db->query($sqldelete);
 
 						$res = $actionCommReminder->create($user);
@@ -1127,7 +1233,7 @@
 	if (!$error) {
 		if (!empty($backtopage)) {
 			unset($_SESSION['assignedtouser']);
-			header("Location: ".$backtopage);
+			header("Location: " . $backtopage);
 			exit;
 		}
 	}
@@ -1140,8 +1246,10 @@
 	$object->fetch_userassigned();
 	$object->oldcopy = dol_clone($object, 2);
 
-	if ($user->hasRight('agenda', 'myactions', 'delete')
-		|| $user->hasRight('agenda', 'allactions', 'delete')) {
+	if (
+		$user->hasRight('agenda', 'myactions', 'delete')
+		|| $user->hasRight('agenda', 'allactions', 'delete')
+	) {
 		$result = $object->delete($user);
 
 		if ($result >= 0) {
@@ -1165,7 +1273,7 @@
 
 	$newdate = GETPOST('newdate', 'alpha');
 	if (empty($newdate) || strpos($newdate, 'dayevent_') != 0) {
-		header("Location: ".$backtopage, true, 307);
+		header("Location: " . $backtopage, true, 307);
 		exit;
 	}
 
@@ -1185,30 +1293,30 @@
 				$eventDateEnd = $object->datef;
 
 				$sql  = "SELECT er.rowid, r.ref as r_ref, ac.id as ac_id, ac.label as ac_label";
-				$sql .= " FROM ".MAIN_DB_PREFIX."element_resources as er";
-				$sql .= " INNER JOIN ".MAIN_DB_PREFIX."resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'";
-				$sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm as ac ON ac.id = er.element_id AND er.element_type = '".$db->escape($object->element)."'";
-				$sql .= " WHERE ac.id <> ".((int) $object->id);
+				$sql .= " FROM " . MAIN_DB_PREFIX . "element_resources as er";
+				$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'";
+				$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "actioncomm as ac ON ac.id = er.element_id AND er.element_type = '" . $db->escape($object->element) . "'";
+				$sql .= " WHERE ac.id <> " . ((int) $object->id);
 				$sql .= " AND er.resource_id IN (";
-				$sql .= " SELECT resource_id FROM ".MAIN_DB_PREFIX."element_resources";
-				$sql .= " WHERE element_id = ".((int) $object->id);
-				$sql .= " AND element_type = '".$db->escape($object->element)."'";
+				$sql .= " SELECT resource_id FROM " . MAIN_DB_PREFIX . "element_resources";
+				$sql .= " WHERE element_id = " . ((int) $object->id);
+				$sql .= " AND element_type = '" . $db->escape($object->element) . "'";
 				$sql .= " AND busy = 1";
 				$sql .= ")";
 				$sql .= " AND er.busy = 1";
 				$sql .= " AND (";
 
 				// event date start between ac.datep and ac.datep2 (if datep2 is null we consider there is no end)
-				$sql .= " (ac.datep <= '".$db->idate($eventDateStart)."' AND (ac.datep2 IS NULL OR ac.datep2 >= '".$db->idate($eventDateStart)."'))";
+				$sql .= " (ac.datep <= '" . $db->idate($eventDateStart) . "' AND (ac.datep2 IS NULL OR ac.datep2 >= '" . $db->idate($eventDateStart) . "'))";
 				// event date end between ac.datep and ac.datep2
 				if (!empty($eventDateEnd)) {
-					$sql .= " OR (ac.datep <= '".$db->idate($eventDateEnd)."' AND (ac.datep2 >= '".$db->idate($eventDateEnd)."'))";
+					$sql .= " OR (ac.datep <= '" . $db->idate($eventDateEnd) . "' AND (ac.datep2 >= '" . $db->idate($eventDateEnd) . "'))";
 				}
 				// event date start before ac.datep and event date end after ac.datep2
 				$sql .= " OR (";
-				$sql .= "ac.datep >= '".$db->idate($eventDateStart)."'";
+				$sql .= "ac.datep >= '" . $db->idate($eventDateStart) . "'";
 				if (!empty($eventDateEnd)) {
-					$sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '".$db->idate($eventDateEnd)."')";
+					$sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '" . $db->idate($eventDateEnd) . "')";
 				}
 				$sql .= ")";
 
@@ -1222,9 +1330,9 @@
 					if ($db->num_rows($resql) > 0) {
 						// Resource already in use
 						$error++;
-						$object->error = $langs->trans('ErrorResourcesAlreadyInUse').' : ';
+						$object->error = $langs->trans('ErrorResourcesAlreadyInUse') . ' : ';
 						while ($obj = $db->fetch_object($resql)) {
-							$object->error .= '<br> - '.$langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label.' ['.$obj->ac_id.']');
+							$object->error .= '<br> - ' . $langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label . ' [' . $obj->ac_id . ']');
 						}
 						$object->errors[] = $object->error;
 					}
@@ -1250,7 +1358,7 @@
 		}
 	}
 	if (!empty($backtopage)) {
-		header("Location: ".$backtopage, true, 307);
+		header("Location: " . $backtopage, true, 307);
 		exit;
 	} else {
 		$action = '';
@@ -1258,10 +1366,10 @@
 }
 
 // Actions to delete doc
-$upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref);
+$upload_dir = $conf->agenda->dir_output . '/' . dol_sanitizeFileName($object->ref);
 $permissiontoadd = ($user->hasRight('agenda', 'allactions', 'create') || (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'read')));
 if (empty($reshook)) {
-	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
+	include DOL_DOCUMENT_ROOT . '/core/actions_builddoc.inc.php';
 }
 
 
@@ -1283,6 +1391,49 @@
 $help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda|DE:Modul_Terminplanung';
 llxHeader('', $langs->trans("Agenda"), $help_url);
 
+//MODIF JOSE
+if ($action == 'editreminder') {
+
+	$reminderid = GETPOST('reminderid', 'int');
+	$actionCommReminder = new ActionCommReminder($db);
+	if ($actionCommReminder->fetch($reminderid) <= 0) {
+		setEventMessages($actionCommReminder->error, $actionCommReminder->errors, 'errors');
+	}
+
+
+	print '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '?id=' . $actioncomm->id . '">';
+	print '<input type="hidden" name="action" value="updatereminder">';
+	print '<input type="hidden" name="reminderid" value="' . $actionCommReminder->id . '">';
+	print '<table class="border centpercent">';
+
+	// Reminder Time
+	print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("ReminderTime") . '</td><td colspan="3">';
+	print '<input class="width50" type="number" name="offsetvalue" value="' . $actionCommReminder->offsetvalue . '"> ';
+	print $form->selectTypeDuration('offsetunit', $actionCommReminder->offsetunit, array('y', 'm'));
+	print '</td></tr>';
+
+	// Reminder Type
+	print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("ReminderType") . '</td><td colspan="3">';
+	print $form->selectarray('selectremindertype', $TRemindTypes, $actionCommReminder->typeremind, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
+	print '</td></tr>';
+
+	// Mail model (optional)
+	$hide = '';
+	if ($actionCommReminder->typeremind == 'browser') {
+		$hide = 'style="display:none;"';
+	}
+	if (getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
+		print '<tr ' . $hide . '><td class="titlefieldcreate nowrap">' . $langs->trans("EMailTemplates") . '</td><td colspan="3">';
+		print $form->selectModelMail('actioncommsend', 'actioncomm_send', 1, 1, $actionCommReminder->fk_email_template);
+		print '</td></tr>';
+	}
+
+	print '</table>';
+	print '<div class="center"><input type="submit" class="button" value="' . $langs->trans("Save") . '"></div>';
+	print '</form>';
+}
+
+
 if ($action == 'create') {
 	$contact = new Contact($db);
 
@@ -1297,7 +1448,7 @@
 	dol_set_focus("#label");
 
 	if (!empty($conf->use_javascript_ajax)) {
-		print "\n".'<script type="text/javascript">';
+		print "\n" . '<script type="text/javascript">';
 		print '$(document).ready(function () {
         			function setdatefields()
 	            	{
@@ -1361,19 +1512,19 @@
                     else $("#dateend").removeClass("fieldrequired");
                     setdatefields();
                })';
-		print '</script>'."\n";
+		print '</script>' . "\n";
 	}
 
-	print '<form name="formaction" action="'.$_SERVER['PHP_SELF'].'" method="POST">';
-	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<form name="formaction" action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
+	print '<input type="hidden" name="token" value="' . newToken() . '">';
 	print '<input type="hidden" name="action" value="add">';
 	print '<input type="hidden" name="donotclearsession" value="1">';
 	print '<input type="hidden" name="page_y" value="">';
 	if ($backtopage) {
-		print '<input type="hidden" name="backtopage" value="'.($backtopage != '1' ? $backtopage : '').'">';
+		print '<input type="hidden" name="backtopage" value="' . ($backtopage != '1' ? $backtopage : '') . '">';
 	}
 	if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
-		print '<input type="hidden" name="actioncode" value="'.dol_getIdFromCode($db, 'AC_OTH', 'c_actioncomm').'">';
+		print '<input type="hidden" name="actioncode" value="' . dol_getIdFromCode($db, 'AC_OTH', 'c_actioncomm') . '">';
 	}
 
 	if (GETPOST("actioncode", 'aZ09') == 'AC_RDV') {
@@ -1388,7 +1539,7 @@
 
 	// Type of event
 	if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
-		print '<tr><td class="titlefieldcreate"><span class="fieldrequired">'.$langs->trans("Type").'</span></b></td><td>';
+		print '<tr><td class="titlefieldcreate"><span class="fieldrequired">' . $langs->trans("Type") . '</span></b></td><td>';
 		$default = getDolGlobalString('AGENDA_USE_EVENT_TYPE_DEFAULT', 'AC_RDV');
 		print img_picto($langs->trans("ActionType"), 'square', 'class="fawidth30 inline-block" style="color: #ddd;"');
 		$selectedvalue = GETPOSTISSET("actioncode") ? GETPOST("actioncode", 'aZ09') : ($object->type_code ? $object->type_code : $default);
@@ -1397,11 +1548,11 @@
 	}
 
 	// Title
-	print '<tr><td'.(getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? '' : ' class="fieldrequired titlefieldcreate"').'>'.$langs->trans("Title").'</td><td><input type="text" id="label" name="label" class="soixantepercent" value="'.GETPOST('label').'"></td></tr>';
+	print '<tr><td' . (getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? '' : ' class="fieldrequired titlefieldcreate"') . '>' . $langs->trans("Title") . '</td><td><input type="text" id="label" name="label" class="soixantepercent" value="' . GETPOST('label') . '"></td></tr>';
 
 	// Full day
-	print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td>';
-	print '<td class="valignmiddle height30"><input class="valignmiddle" type="checkbox" id="fullday" name="fullday" '.(GETPOST('fullday') ? ' checked' : '').'><label for="fullday" class="valignmiddle small">'.$langs->trans("EventOnFullDay").'</label>';
+	print '<tr><td><span class="fieldrequired">' . $langs->trans("Date") . '</span></td>';
+	print '<td class="valignmiddle height30"><input class="valignmiddle" type="checkbox" id="fullday" name="fullday" ' . (GETPOST('fullday') ? ' checked' : '') . '><label for="fullday" class="valignmiddle small">' . $langs->trans("EventOnFullDay") . '</label>';
 	print '</td></tr>';
 
 	$datep = ($datep ? $datep : (is_null($object->datep) ? '' : $object->datep));
@@ -1439,14 +1590,14 @@
 		//print ' &nbsp; &nbsp; &nbsp; &nbsp; ';
 		print '<div class="opacitymedium inline-block small">';
 		print img_picto($langs->trans("Recurrence"), 'recurring', 'style="margin-left: 6px" class="paddingright2"');
-		print '<input type="hidden" name="recurid" value="'.(empty($object->recurid) ? '' : $object->recurid).'">';
+		print '<input type="hidden" name="recurid" value="' . (empty($object->recurid) ? '' : $object->recurid) . '">';
 
 		$selectedrecurrulefreq = 'no';
 		$selectedrecurrulebymonthday = '';
 		$selectedrecurrulebyday = '';
-		$object->recurrule = GETPOSTISSET('recurrulefreq') ? "FREQ=".GETPOST('recurrulefreq', 'alpha') : "";
-		$object->recurrule .= GETPOSTISSET('BYMONTHDAY') ? "_BYMONTHDAY".GETPOST('BYMONTHDAY', 'alpha') : "";
-		$object->recurrule .= GETPOSTISSET('BYDAY') ? "_BYDAY".GETPOST('BYDAY', 'alpha') : "";
+		$object->recurrule = GETPOSTISSET('recurrulefreq') ? "FREQ=" . GETPOST('recurrulefreq', 'alpha') : "";
+		$object->recurrule .= GETPOSTISSET('BYMONTHDAY') ? "_BYMONTHDAY" . GETPOST('BYMONTHDAY', 'alpha') : "";
+		$object->recurrule .= GETPOSTISSET('BYDAY') ? "_BYDAY" . GETPOST('BYDAY', 'alpha') : "";
 
 
 		$reg = array();
@@ -1467,16 +1618,16 @@
 
 		// If recurrulefreq is MONTHLY
 		print '<div class="hidden marginrightonly inline-block repeateventBYMONTHDAY">';
-		print $langs->trans("DayOfMonth").': <input type="input" size="2" name="BYMONTHDAY" value="'.$selectedrecurrulebymonthday.'">';
+		print $langs->trans("DayOfMonth") . ': <input type="input" size="2" name="BYMONTHDAY" value="' . $selectedrecurrulebymonthday . '">';
 		print '</div>';
 		// If recurrulefreq is WEEKLY
 		print '<div class="hidden marginrightonly inline-block repeateventBYDAY">';
-		print $langs->trans("DayOfWeek").': <input type="input" size="4" name="BYDAY" value="'.$selectedrecurrulebyday.'">';
+		print $langs->trans("DayOfWeek") . ': <input type="input" size="4" name="BYDAY" value="' . $selectedrecurrulebyday . '">';
 		print '</div>';
 		// limit date
 		$repeateventlimitdate = !empty($repeateventlimitdate) ? $repeateventlimitdate : '';
 		print '<div class="hidden marginrightonly inline-block repeateventlimitdate">';
-		print $langs->trans("Until")." ";
+		print $langs->trans("Until") . " ";
 		print $form->selectDate($repeateventlimitdate, 'limit', 0, 0, 0, "action", 1, 0, 0, '', '', '', '', 1, '', '', 'tzuserrel');
 		print '</div>';
 
@@ -1484,11 +1635,11 @@
 			jQuery(document).ready(function() {
 				function init_repeat()
 				{
-					console.log("recurrule: " + "'.$object->recurrule.'");
-					console.log("reg1: " + "'.$selectedrecurrulefreq.'");
-					console.log("reg2: " + "'.$selectedrecurrulebymonthday.'");
-					console.log("reg3: " + "'.$selectedrecurrulebyday.'");
-					console.log("selectedrulefreq: " + "'.$selectedrecurrulefreq.'");
+					console.log("recurrule: " + "' . $object->recurrule . '");
+					console.log("reg1: " + "' . $selectedrecurrulefreq . '");
+					console.log("reg2: " + "' . $selectedrecurrulebymonthday . '");
+					console.log("reg3: " + "' . $selectedrecurrulebyday . '");
+					console.log("selectedrulefreq: " + "' . $selectedrecurrulefreq . '");
 					if (jQuery("#recurrulefreq").val() == \'MONTHLY\')
 					{
 						jQuery(".repeateventBYMONTHDAY").css("display", "inline-block");		/* use this instead of show because we want inline-block and not block */
@@ -1521,7 +1672,7 @@
 	print '<tr><td class="">&nbsp;</td><td></td></tr>';
 
 	// Assigned to user
-	print '<tr><td class="tdtop nowrap"><span class="fieldrequired">'.$langs->trans("ActionAffectedTo").'</span></td><td>';
+	print '<tr><td class="tdtop nowrap"><span class="fieldrequired">' . $langs->trans("ActionAffectedTo") . '</span></td><td>';
 	$listofuserid = array();
 	$listofcontactid = array();
 	$listofotherid = array();
@@ -1553,20 +1704,20 @@
 
 	// Location
 	if (!getDolGlobalString('AGENDA_DISABLE_LOCATION')) {
-		print '<tr><td>'.$langs->trans("Location").'</td><td><input type="text" name="location" class="minwidth300 maxwidth150onsmartphone" value="'.(GETPOST('location') ? GETPOST('location') : $object->location).'"></td></tr>';
+		print '<tr><td>' . $langs->trans("Location") . '</td><td><input type="text" name="location" class="minwidth300 maxwidth150onsmartphone" value="' . (GETPOST('location') ? GETPOST('location') : $object->location) . '"></td></tr>';
 	}
 
 	if (isModEnabled('category')) {
 		// Categories
-		print '<tr><td>'.$langs->trans("Categories").'</td><td>';
+		print '<tr><td>' . $langs->trans("Categories") . '</td><td>';
 		$cate_arbo = $form->select_all_categories(Categorie::TYPE_ACTIONCOMM, '', 'parent', 64, 0, 3);
-		print img_picto('', 'category').$form->multiselectarray('categories', $cate_arbo, GETPOST('categories', 'array'), 0, 0, 'minwidth300 quatrevingtpercent widthcentpercentminusx', 0, 0);
+		print img_picto('', 'category') . $form->multiselectarray('categories', $cate_arbo, GETPOST('categories', 'array'), 0, 0, 'minwidth300 quatrevingtpercent widthcentpercentminusx', 0, 0);
 		print "</td></tr>";
 	}
 
 	if (isModEnabled('resource')) {
 		// Categories
-		print '<tr><td class="tdtop nowrap">'.$langs->trans("Resource").'</td><td>';
+		print '<tr><td class="tdtop nowrap">' . $langs->trans("Resource") . '</td><td>';
 
 		$listofresourceid = array();
 		if (empty($donotclearsession)) {
@@ -1594,7 +1745,7 @@
 	}
 
 	// Status
-	print '<tr><td>'.$langs->trans("Status").' / '.$langs->trans("Percentage").'</td>';
+	print '<tr><td>' . $langs->trans("Status") . ' / ' . $langs->trans("Percentage") . '</td>';
 	print '<td>';
 	$percent = $complete !== '' ? $complete : -1;
 	if (GETPOSTISSET('status')) {
@@ -1621,26 +1772,26 @@
 
 	if (isModEnabled("societe")) {
 		// Related company
-		print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ActionOnCompany").'</td><td>';
+		print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("ActionOnCompany") . '</td><td>';
 		if (GETPOSTINT('socid') > 0) {
 			$societe = new Societe($db);
 			$societe->fetch(GETPOSTINT('socid'));
 			print $societe->getNomUrl(1);
-			print '<input type="hidden" id="socid" name="socid" value="'.GETPOSTINT('socid').'">';
+			print '<input type="hidden" id="socid" name="socid" value="' . GETPOSTINT('socid') . '">';
 		} else {
 			$events = array();
-			$events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1&token='.currentToken(), 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
+			$events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1&token=' . currentToken(), 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
 			//For external user force the company to user company
 			if (!empty($user->socid)) {
-				print img_picto('', 'company', 'class="paddingrightonly"').$form->select_company($user->socid, 'socid', '', 1, 1, 0, $events, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
+				print img_picto('', 'company', 'class="paddingrightonly"') . $form->select_company($user->socid, 'socid', '', 1, 1, 0, $events, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
 			} else {
-				print img_picto('', 'company', 'class="paddingrightonly"').$form->select_company('', 'socid', '', $langs->trans('SelectThirdParty'), 1, 0, $events, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
+				print img_picto('', 'company', 'class="paddingrightonly"') . $form->select_company('', 'socid', '', $langs->trans('SelectThirdParty'), 1, 0, $events, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
 			}
 		}
 		print '</td></tr>';
 
 		// Related contact
-		print '<tr><td class="nowrap">'.$langs->trans("ActionOnContact").'</td><td>';
+		print '<tr><td class="nowrap">' . $langs->trans("ActionOnContact") . '</td><td>';
 		$preselectedids = GETPOST('socpeopleassigned', 'array:int');
 		if (GETPOSTINT('contactid')) {
 			$preselectedids[GETPOSTINT('contactid')] = GETPOSTINT('contactid');
@@ -1680,20 +1831,20 @@
 
 		$projectid = GETPOSTINT('projectid');
 
-		print '<tr><td class="titlefieldcreate">'.$langs->trans("Project").'</td><td id="project-input-container">';
+		print '<tr><td class="titlefieldcreate">' . $langs->trans("Project") . '</td><td id="project-input-container">';
 		print img_picto('', 'project', 'class="pictofixedwidth"');
 		print $formproject->select_projects(($object->socid > 0 ? $object->socid : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx maxwidth500');
 
-		print '&nbsp;<a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.(empty($societe->id) ? '' : $societe->id).'&action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'">';
-		print '<span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddProject").'"></span></a>';
+		print '&nbsp;<a href="' . DOL_URL_ROOT . '/projet/card.php?socid=' . (empty($societe->id) ? '' : $societe->id) . '&action=create&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?action=create') . '">';
+		print '<span class="fa fa-plus-circle valignmiddle paddingleft" title="' . $langs->trans("AddProject") . '"></span></a>';
 		$urloption = '?action=create&donotclearsession=1';
-		$url = dol_buildpath('comm/action/card.php', 2).$urloption;
+		$url = dol_buildpath('comm/action/card.php', 2) . $urloption;
 
 		// update task list
-		print "\n".'<script type="text/javascript">';
+		print "\n" . '<script type="text/javascript">';
 		print '$(document).ready(function () {
 	               $("#projectid").change(function () {
-                        var url = "'.DOL_URL_ROOT.'/projet/ajax/projects.php?mode=gettasks&socid="+$("#search_socid").val()+"&projectid="+$("#projectid").val();
+                        var url = "' . DOL_URL_ROOT . '/projet/ajax/projects.php?mode=gettasks&socid="+$("#search_socid").val()+"&projectid="+$("#projectid").val();
 						console.log("Call url to get new list of tasks: "+url);
                         $.get(url, function(data) {
                             console.log(data);
@@ -1701,12 +1852,12 @@
                         })
                   });
                })';
-		print '</script>'."\n";
+		print '</script>' . "\n";
 
 		print '</td></tr>';
 
 		// Task
-		print '<tr><td class="titlefieldcreate">'.$langs->trans("Task").'</td><td id="project-task-input-container" >';
+		print '<tr><td class="titlefieldcreate">' . $langs->trans("Task") . '</td><td id="project-task-input-container" >';
 		print img_picto('', 'projecttask', 'class="paddingrightonly"');
 		$projectsListId = false;
 		if (!empty($projectid)) {
@@ -1721,7 +1872,7 @@
 
 	// Object linked
 	if (!empty($origin) && !empty($originid)) {
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+		include_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
 
 		$hasPermissionOnLinkedObject = 0;
 
@@ -1733,16 +1884,16 @@
 
 		if (! in_array($origin, array('societe', 'project', 'task', 'user'))) {
 			// We do not use link for object that already contains a hard coded field to make links with agenda events
-			print '<tr><td class="titlefieldcreate">'.$langs->trans("LinkedObject").'</td>';
+			print '<tr><td class="titlefieldcreate">' . $langs->trans("LinkedObject") . '</td>';
 			print '<td colspan="3">';
 			if ($hasPermissionOnLinkedObject) {
 				print dolGetElementUrl($originid, $origin, 1);
-				print '<input type="hidden" name="fk_element" value="'.$originid.'">';
-				print '<input type="hidden" name="elementtype" value="'.$origin.'">';
-				print '<input type="hidden" name="originid" value="'.$originid.'">';
-				print '<input type="hidden" name="origin" value="'.$origin.'">';
+				print '<input type="hidden" name="fk_element" value="' . $originid . '">';
+				print '<input type="hidden" name="elementtype" value="' . $origin . '">';
+				print '<input type="hidden" name="originid" value="' . $originid . '">';
+				print '<input type="hidden" name="origin" value="' . $origin . '">';
 			} else {
-				print '<!-- no permission on object to link '.$origin.' id '.$originid.' -->';
+				print '<!-- no permission on object to link ' . $origin . ' id ' . $originid . ' -->';
 			}
 			print '</td></tr>';
 		}
@@ -1750,14 +1901,14 @@
 
 	// Priority
 	if (getDolGlobalString('AGENDA_SUPPORT_PRIORITY_IN_EVENTS')) {
-		print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("Priority").'</td><td colspan="3">';
-		print '<input type="text" name="priority" value="'.(GETPOSTISSET('priority') ? GETPOSTINT('priority') : ($object->priority ? $object->priority : '')).'" size="5">';
+		print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("Priority") . '</td><td colspan="3">';
+		print '<input type="text" name="priority" value="' . (GETPOSTISSET('priority') ? GETPOSTINT('priority') : ($object->priority ? $object->priority : '')) . '" size="5">';
 		print '</td></tr>';
 	}
 
 	// Description
-	print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td>';
-	require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+	print '<tr><td class="tdtop">' . $langs->trans("Description") . '</td><td>';
+	require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
 	$doleditor = new DolEditor('note', (GETPOSTISSET('note') ? GETPOST('note', 'restricthtml') : $object->note_private), '', 120, 'dolibarr_notes', 'In', true, true, isModEnabled('fckeditor'), ROWS_4, '90%');
 	$doleditor->Create();
 	print '</td></tr>';
@@ -1777,31 +1928,60 @@
 		//checkbox create reminder
 		print '<hr>';
 		print '<br>';
-		print '<label for="addreminder">'.img_picto('', 'bell', 'class="pictofixedwidth"').$langs->trans("AddReminder").'</label> <input type="checkbox" id="addreminder" name="addreminder"><br><br>';
+		print '<label for="addreminder">' . img_picto('', 'bell', 'class="pictofixedwidth"') . $langs->trans("AddReminder") . '</label> <input type="checkbox" id="addreminder" name="addreminder"><br><br>';
 
 		print '<div class="reminderparameters" style="display: none;">';
 
 		print '<table class="border centpercent">';
 
 		//Reminder
-		print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ReminderTime").'</td><td colspan="3">';
-		print '<input class="width50" type="number" name="offsetvalue" value="'.(GETPOSTISSET('offsetvalue') ? GETPOSTINT('offsetvalue') : getDolGlobalInt('AGENDA_REMINDER_DEFAULT_OFFSET', 30)).'"> ';
+		print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("ReminderTime") . '</td><td colspan="3">';
+		print '<input class="width50" type="number" name="offsetvalue" value="' . (GETPOSTISSET('offsetvalue') ? GETPOSTINT('offsetvalue') : getDolGlobalInt('AGENDA_REMINDER_DEFAULT_OFFSET', 30)) . '"> ';
 		print $form->selectTypeDuration('offsetunit', 'i', array('y', 'm'));
 		print '</td></tr>';
 
 		//Reminder Type
-		print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ReminderType").'</td><td colspan="3">';
+		print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("ReminderType") . '</td><td colspan="3">';
 		print $form->selectarray('selectremindertype', $TRemindTypes, '', 0, 0, 0, '', 0, 0, 0, '', 'minwidth200 maxwidth500', 1);
 		print '</td></tr>';
 
 		//Mail Model
 		if (getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
-			print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("EMailTemplates").'</td><td colspan="3">';
+			print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("EMailTemplates") . '</td><td colspan="3">';
 			print $form->selectModelMail('actioncommsend', 'actioncomm_send', 1, 1);
 			print '</td></tr>';
 		}
 
 		print '</table>';
+
+		print '<div class="reminder-list" data-has-reminders="' . (count($reminders) > 0 ? '1' : '0') . '" style="' . (count($reminders) == 0 ? 'display:none;' : '') . '">';
+
+		if (count($reminders) > 0) {
+			print '<br>';
+			print '<h3>' . $langs->trans("ExistingReminders") . '</h3>';
+			print '<table class="noborder centpercent">';
+			print '<tr class="liste_titre">';
+			print '<td>' . $langs->trans("ReminderType") . '</td>';
+			print '<td>' . $langs->trans("ReminderDelay") . '</td>';
+			print '<td></td>';
+			print '</tr>';
+
+			foreach ($reminders as $reminder) {
+				print '<tr>';
+				print '<td>' . $reminder->typeremind . '</td>';
+				print '<td>' . $reminder->offsetvalue . ' ' . $reminder->offsetunit . '</td>';
+				print '<td>';
+				print '<a class="button" href="' . $_SERVER["PHP_SELF"] . '?id=' . $actioncomm->id . '&reminderid=' . $reminder->id . '&action=editreminder">' . $langs->trans("Modify") . '</a> ';
+				print '<a class="button" href="' . $_SERVER["PHP_SELF"] . '?id=' . $actioncomm->id . '&reminderid=' . $reminder->id . '&action=deletereminder">' . $langs->trans("Delete") . '</a>';
+				print '</td>';
+				print '</tr>';
+			}
+
+			print '</table>';
+			print '</div>';
+		}
+
+
 		print '</div>';
 
 		$reminderDefaultEventTypes = getDolGlobalString('AGENDA_DEFAULT_REMINDER_EVENT_TYPES', '');
@@ -1809,9 +1989,29 @@
 		$reminderDefaultUnit = getDolGlobalString('AGENDA_DEFAULT_REMINDER_OFFSET_UNIT');
 		$reminderDefaultEmailModel = getDolGlobalInt('AGENDA_DEFAULT_REMINDER_EMAIL_MODEL');
 
-		print "\n".'<script type="text/javascript">';
+		print "\n" . '<script type="text/javascript">';
 		print '$(document).ready(function () {
-				const reminderDefaultEventTypes = \''.dol_escape_js($reminderDefaultEventTypes).'\';
+		
+				const reminderDefaultEventTypes = \'' . dol_escape_js($reminderDefaultEventTypes) . '\';
+
+				   // Gérer la visibilité au clic sur la checkbox
+    $("#addreminder").click(function () {
+        if (this.checked) {
+            $(".reminderparameters").show();
+            $(".reminder-list").show();
+        } else {
+            $(".reminderparameters").hide();
+            if ($(".reminder-list").data("has-reminders") != "1") {
+                $(".reminder-list").hide();
+            }
+        }
+
+        $("#selectremindertype").select2("destroy").select2();
+        $("#select_offsetunittype_duration").select2("destroy").select2();
+        selectremindertype();
+    });
+	
+				
 				$("#actioncode").change(function(){
 					var selected_event_type = $("#actioncode option:selected").val();
 
@@ -1822,7 +2022,7 @@
 						// Set period with default reminder period
 						$("[name=\"offsetvalue\"]").val(\'' . dol_escape_js((string) $reminderDefaultOffset) . '\');
 						$("#select_offsetunittype_duration").select2("destroy");
-						$("#select_offsetunittype_duration").val(\''.dol_escape_js($reminderDefaultUnit).'\');
+						$("#select_offsetunittype_duration").val(\'' . dol_escape_js($reminderDefaultUnit) . '\');
 						$("#select_offsetunittype_duration").select2();
 
 						$("#selectremindertype").select2("destroy");
@@ -1832,45 +2032,32 @@
 						// Set default reminder mail model
 						$("#select_actioncommsendmodel_mail").closest("tr").show();
 						$("#select_actioncommsendmodel_mail").select2("destroy");
-						$("#select_actioncommsendmodel_mail").val(\''.dol_escape_js((string) $reminderDefaultEmailModel).'\');
+						$("#select_actioncommsendmodel_mail").val(\'' . dol_escape_js((string) $reminderDefaultEmailModel) . '\');
 						$("#select_actioncommsendmodel_mail").select2();
 					}
 				});
-		   })';
-		print '</script>'."\n";
-
-		print "\n".'<script type="text/javascript">';
-		print '$(document).ready(function () {
-	            		$("#addreminder").click(function(){
-							console.log("Click on addreminder");
-	            		    if (this.checked) {
-	            		    	$(".reminderparameters").show();
-                            } else {
-                            	$(".reminderparameters").hide();
-                            }
-							$("#selectremindertype").select2("destroy");
-							$("#selectremindertype").select2();
-							$("#select_offsetunittype_duration").select2("destroy");
-							$("#select_offsetunittype_duration").select2();
-							selectremindertype();
-	            		 });
 
-	            		$("#selectremindertype").change(function(){
-							selectremindertype();
-	            		});
+				$("#selectremindertype").change(function () {
+        selectremindertype();
+    });
+
+	  function selectremindertype() {
+        var selected_option = $("#selectremindertype option:selected").val();
+        if (selected_option === "email") {
+            $("#select_actioncommsendmodel_mail").closest("tr").show();
+        } else {
+            $("#select_actioncommsendmodel_mail").closest("tr").hide();
+        }
+    }
+
+    // Au chargement, cacher la liste si nécessaire
+    if (!$("#addreminder").is(":checked") && $(".reminder-list").data("has-reminders") != "1") {
+        $(".reminder-list").hide();
+    }
 
-						function selectremindertype() {
-							console.log("Call selectremindertype");
-	            	        var selected_option = $("#selectremindertype option:selected").val();
-	            		    if(selected_option == "email") {
-	            		        $("#select_actioncommsendmodel_mail").closest("tr").show();
-	            		    } else {
-	            			    $("#select_actioncommsendmodel_mail").closest("tr").hide();
-	            		    }
-						}
 
-                   })';
-		print '</script>'."\n";
+		   })';
+		print '</script>' . "\n";
 	}
 
 	print dol_get_fiche_end();
@@ -1951,14 +2138,14 @@
 
 	// Confirmation suppression action
 	if ($action == 'delete') {
-		print $form->formconfirm("card.php?id=".urlencode((string) ($id)), $langs->trans("DeleteAction"), $langs->trans("ConfirmDeleteAction"), "confirm_delete", '', '', 1);
+		print $form->formconfirm("card.php?id=" . urlencode((string) ($id)), $langs->trans("DeleteAction"), $langs->trans("ConfirmDeleteAction"), "confirm_delete", '', '', 1);
 	}
 
 	if ($action == 'edit') {
 		$caneditdateorowner = ($object->type != 'systemauto');
 
 		if (!empty($conf->use_javascript_ajax)) {
-			print "\n".'<script type="text/javascript">';
+			print "\n" . '<script type="text/javascript">';
 			print '$(document).ready(function () {
 	            		function setdatefields()
 	            		{
@@ -1975,7 +2162,7 @@
 	            			}
 	            		}
 
-						'.($caneditdateorowner ? ' setdatefields();' : '').'
+						' . ($caneditdateorowner ? ' setdatefields();' : '') . '
 
 	            		$("#fullday").change(function() {
 	            			setdatefields();
@@ -2008,20 +2195,20 @@
                         	else $("#dateend").removeClass("fieldrequired");
                     	});
                    })';
-			print '</script>'."\n";
+			print '</script>' . "\n";
 		}
 
-		print '<form name="formaction" action="'.$_SERVER['PHP_SELF'].'" method="POST">';
-		print '<input type="hidden" name="token" value="'.newToken().'">';
+		print '<form name="formaction" action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
+		print '<input type="hidden" name="token" value="' . newToken() . '">';
 		print '<input type="hidden" name="action" value="update">';
-		print '<input type="hidden" name="id" value="'.$id.'">';
-		print '<input type="hidden" name="ref_ext" value="'.$object->ref_ext.'">';
+		print '<input type="hidden" name="id" value="' . $id . '">';
+		print '<input type="hidden" name="ref_ext" value="' . $object->ref_ext . '">';
 		print '<input type="hidden" name="page_y" value="">';
 		if ($backtopage) {
-			print '<input type="hidden" name="backtopage" value="'.($backtopage != '1' ? $backtopage : '').'">';
+			print '<input type="hidden" name="backtopage" value="' . ($backtopage != '1' ? $backtopage : '') . '">';
 		}
 		if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') && ! preg_match('/^TICKET_MSG_PRIVATE/', $object->code)) {
-			print '<input type="hidden" name="actioncode" value="'.$object->type_code.'">';
+			print '<input type="hidden" name="actioncode" value="' . $object->type_code . '">';
 		}
 
 		print dol_get_fiche_head($head, 'card', $langs->trans("Action"), 0, 'action');
@@ -2029,36 +2216,36 @@
 		print '<table class="border tableforfield" width="100%">';
 
 		// Ref
-		print '<tr><td class="titlefieldcreate">'.$langs->trans("Ref").'</td><td colspan="3">'.$object->id.'</td></tr>';
+		print '<tr><td class="titlefieldcreate">' . $langs->trans("Ref") . '</td><td colspan="3">' . $object->id . '</td></tr>';
 
 		// Type of event
 		if (getDolGlobalString('AGENDA_USE_EVENT_TYPE') && $object->elementtype != "ticket") {
-			print '<tr><td class="fieldrequired">'.$langs->trans("Type").'</td><td colspan="3">';
+			print '<tr><td class="fieldrequired">' . $langs->trans("Type") . '</td><td colspan="3">';
 			if ($object->type_code != 'AC_OTH_AUTO') {
 				print img_picto($langs->trans("ActionType"), 'square', 'class="fawidth30 inline-block" style="color: #ddd;"');
 				print $formactions->select_type_actions(GETPOST("actioncode", 'aZ09') ? GETPOST("actioncode", 'aZ09') : $object->type_code, "actioncode", "systemauto", 0, 0, 0, 1);
 			} else {
-				print '<input type="hidden" name="actioncode" value="'.$object->type_code.'">';
+				print '<input type="hidden" name="actioncode" value="' . $object->type_code . '">';
 				print $object->getTypePicto();
-				print $langs->trans("Action".$object->type_code);
+				print $langs->trans("Action" . $object->type_code);
 			}
 			print '</td></tr>';
 		}
 
 		// Private
 		if ($object->elementtype == 'ticket') {
-			print '<tr><td>'.$langs->trans("MarkMessageAsPrivate");
-			print ' '.$form->textwithpicto('', $langs->trans("TicketMessagePrivateHelp"), 1, 'help');
-			print '</td><td colspan="3"><input type="checkbox" id="private" name="private" '.(preg_match('/^TICKET_MSG_PRIVATE/', $object->code) ? ' checked' : '').'></td></tr>';
+			print '<tr><td>' . $langs->trans("MarkMessageAsPrivate");
+			print ' ' . $form->textwithpicto('', $langs->trans("TicketMessagePrivateHelp"), 1, 'help');
+			print '</td><td colspan="3"><input type="checkbox" id="private" name="private" ' . (preg_match('/^TICKET_MSG_PRIVATE/', $object->code) ? ' checked' : '') . '></td></tr>';
 		}
 
 		// Title
-		print '<tr><td'.(!getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? ' class="fieldrequired titlefieldcreate"' : '').'>'.$langs->trans("Title").'</td><td colspan="3"><input type="text" name="label" class="soixantepercent" value="'.$object->label.'"></td></tr>';
+		print '<tr><td' . (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? ' class="fieldrequired titlefieldcreate"' : '') . '>' . $langs->trans("Title") . '</td><td colspan="3"><input type="text" name="label" class="soixantepercent" value="' . $object->label . '"></td></tr>';
 
 		// Full day event
-		print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td colspan="3" class="valignmiddle height30 small">';
-		print '<input '.($caneditdateorowner ? '' : ' disabled').' type="checkbox" id="fullday" name="fullday" '.($object->fulldayevent ? ' checked' : '').'>';
-		print '<label for="fullday">'.$langs->trans("EventOnFullDay").'</label>';
+		print '<tr><td><span class="fieldrequired">' . $langs->trans("Date") . '</span></td><td colspan="3" class="valignmiddle height30 small">';
+		print '<input ' . ($caneditdateorowner ? '' : ' disabled') . ' type="checkbox" id="fullday" name="fullday" ' . ($object->fulldayevent ? ' checked' : '') . '>';
+		print '<label for="fullday">' . $langs->trans("EventOnFullDay") . '</label>';
 
 		// // Recurring event
 		// $userepeatevent = (getDolGlobalInt('MAIN_FEATURES_LEVEL') == 2 ? 1 : 0);
@@ -2144,8 +2331,8 @@
 					'type' => 'user',
 					//'transparency'=>$object->userassigned[$user->id]['transparency'],
 					'transparency' => $object->transparency, // Force transparency on ownerfrom event
-					'answer_status' => (isset($object->userassigned[$object->userownerid]['answer_status']) ? $object->userassigned[$object->userownerid]['answer_status']: null),
-					'mandatory' => (isset($object->userassigned[$object->userownerid]['mandatory']) ? $object->userassigned[$object->userownerid]['mandatory']:null)
+					'answer_status' => (isset($object->userassigned[$object->userownerid]['answer_status']) ? $object->userassigned[$object->userownerid]['answer_status'] : null),
+					'mandatory' => (isset($object->userassigned[$object->userownerid]['mandatory']) ? $object->userassigned[$object->userownerid]['mandatory'] : null)
 				);
 			}
 			if (!empty($object->userassigned)) {	// Now concat assigned users
@@ -2167,7 +2354,7 @@
 		$listofcontactid = $object->socpeopleassigned; // Contact assigned
 		$listofotherid = $object->otherassigned; // Other undefined email (not used yet)
 
-		print '<tr><td class="tdtop nowrap fieldrequired">'.$langs->trans("ActionAssignedTo").'</td><td colspan="3">';
+		print '<tr><td class="tdtop nowrap fieldrequired">' . $langs->trans("ActionAssignedTo") . '</td><td colspan="3">';
 		print '<div class="assignedtouser">';
 		print $form->select_dolusers_forevent(($action == 'create' ? 'add' : 'update'), 'assignedtouser', 1, array(), 0, '', array(), 0, 0, 0, 'u.statut:<>:0', 1, $listofuserid, $listofcontactid, $listofotherid, $caneditdateorowner);
 		print '</div>';
@@ -2181,18 +2368,18 @@
 
 		// Location
 		if (!getDolGlobalString('AGENDA_DISABLE_LOCATION')) {
-			print '<tr><td>'.$langs->trans("Location").'</td><td colspan="3"><input type="text" name="location" class="minwidth300 maxwidth150onsmartphone" value="'.$object->location.'"></td></tr>';
+			print '<tr><td>' . $langs->trans("Location") . '</td><td colspan="3"><input type="text" name="location" class="minwidth300 maxwidth150onsmartphone" value="' . $object->location . '"></td></tr>';
 		}
 
 		// Status
-		print '<tr><td class="nowrap">'.$langs->trans("Status").' / '.$langs->trans("Percentage").'</td><td colspan="3">';
+		print '<tr><td class="nowrap">' . $langs->trans("Status") . ' / ' . $langs->trans("Percentage") . '</td><td colspan="3">';
 		$percent = GETPOSTISSET("percentage") ? GETPOSTINT("percentage") : $object->percentage;
 		$formactions->form_select_status_action('formaction', $percent, 1, 'complete', 0, 0, 'maxwidth200');
 		print '</td></tr>';
 
 		// Tags-Categories
 		if (isModEnabled('category')) {
-			print '<tr><td>'.$langs->trans("Categories").'</td><td colspan="3">';
+			print '<tr><td>' . $langs->trans("Categories") . '</td><td colspan="3">';
 			$cate_arbo = $form->select_all_categories(Categorie::TYPE_ACTIONCOMM, '', 'parent', 64, 0, 3);
 			$c = new Categorie($db);
 			$cats = $c->containing($object->id, Categorie::TYPE_ACTIONCOMM);
@@ -2200,7 +2387,7 @@
 			foreach ($cats as $cat) {
 				$arrayselected[] = $cat->id;
 			}
-			print img_picto('', 'category').$form->multiselectarray('categories', $cate_arbo, $arrayselected, 0, 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
+			print img_picto('', 'category') . $form->multiselectarray('categories', $cate_arbo, $arrayselected, 0, 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
 			print "</td></tr>";
 		}
 
@@ -2214,19 +2401,19 @@
 
 		if (isModEnabled("societe")) {
 			// Related company
-			print '<tr><td class="titlefieldcreate">'.$langs->trans("ActionOnCompany").'</td>';
+			print '<tr><td class="titlefieldcreate">' . $langs->trans("ActionOnCompany") . '</td>';
 			print '<td>';
 			print '<div>';
 			$events = array(); // 'method'=parameter action of url, 'url'=url to call that return new list of contacts
-			$events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1&token='.currentToken(), 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
+			$events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1&token=' . currentToken(), 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
 			// TODO Refresh also list of project if conf PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY not defined with list linked to socid ?
 			// FIXME If we change company, we may get a project that does not match
-			print img_picto('', 'company', 'class="pictofixedwidth"').$form->select_company($object->socid, 'socid', '', 'SelectThirdParty', 1, 0, $events, 0, 'minwidth300');
+			print img_picto('', 'company', 'class="pictofixedwidth"') . $form->select_company($object->socid, 'socid', '', 'SelectThirdParty', 1, 0, $events, 0, 'minwidth300');
 			print '</div>';
 			print '</td></tr>';
 
 			// Related contact
-			print '<tr><td>'.$langs->trans("ActionOnContact").'</td><td>';
+			print '<tr><td>' . $langs->trans("ActionOnContact") . '</td><td>';
 			print '<div class="maxwidth200onsmartphone">';
 
 			print img_picto('', 'contact', 'class="paddingrightonly"');
@@ -2253,56 +2440,56 @@
 		if (isModEnabled('project')) {
 			$langs->load("projects");
 
-			print '<tr><td class="titlefieldcreate">'.$langs->trans("Project").'</td><td>';
+			print '<tr><td class="titlefieldcreate">' . $langs->trans("Project") . '</td><td>';
 			print img_picto('', 'project', 'class="pictofixedwidth"');
 			$numprojet = $formproject->select_projects(($object->socid > 0 ? $object->socid : -1), $object->fk_project, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, 'maxwidth500 widthcentpercentminusxx');
 			if ($numprojet == 0) {
-				print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$object->socid.'&action=create&token='.newToken().'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddProject").'"></span></a>';
+				print ' &nbsp; <a href="' . DOL_URL_ROOT . '/projet/card.php?socid=' . $object->socid . '&action=create&token=' . newToken() . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=edit') . '"><span class="fa fa-plus-circle valignmiddle paddingleft" title="' . $langs->trans("AddProject") . '"></span></a>';
 			}
 			print '</td></tr>';
 		}
 
 		// Priority
 		if (getDolGlobalString('AGENDA_SUPPORT_PRIORITY_IN_EVENTS')) {
-			print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("Priority").'</td><td>';
-			print '<input type="text" name="priority" value="'.($object->priority ? $object->priority : '').'" size="5">';
+			print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("Priority") . '</td><td>';
+			print '<input type="text" name="priority" value="' . ($object->priority ? $object->priority : '') . '" size="5">';
 			print '</td></tr>';
 		}
 
 		// Object linked
 		if (!empty($object->fk_element) && !empty($object->elementtype)) {
-			include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+			include_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
 			print '<tr>';
-			print '<td>'.$langs->trans("LinkedObject").'</td>';
+			print '<td>' . $langs->trans("LinkedObject") . '</td>';
 
 			if ($object->elementtype == 'task' && isModEnabled('project')) {
 				print '<td id="project-task-input-container" >';
 
 				$urloption = '?action=create&donotclearsession=1'; // we use create not edit for more flexibility
-				$url = DOL_URL_ROOT.'/comm/action/card.php'.$urloption;
+				$url = DOL_URL_ROOT . '/comm/action/card.php' . $urloption;
 
 				// update task list
-				print "\n".'<script type="text/javascript" >';
+				print "\n" . '<script type="text/javascript" >';
 				print '$(document).ready(function () {
 	              $("#projectid").change(function () {
-                        var url = "'.$url.'&projectid="+$("#projectid").val();
+                        var url = "' . $url . '&projectid="+$("#projectid").val();
                         $.get(url, function(data) {
                             console.log($( data ).find("#fk_element").html());
                             if (data) $("#fk_element").html( $( data ).find("#taskid").html() ).select2();
                         })
                   });
                 })';
-				print '</script>'."\n";
+				print '</script>' . "\n";
 
 				$formproject->selectTasks((!empty($societe->id) ? $societe->id : -1), $object->fk_element, 'fk_element', 24, 0, 0, 1, 0, 0, 'maxwidth500', $object->fk_project);
-				print '<input type="hidden" name="elementtype" value="'.$object->elementtype.'">';
+				print '<input type="hidden" name="elementtype" value="' . $object->elementtype . '">';
 
 				print '</td>';
 			} else {
 				print '<td>';
 				print dolGetElementUrl($object->fk_element, $object->elementtype, 1);
-				print '<input type="hidden" name="fk_element" value="'.$object->fk_element.'">';
-				print '<input type="hidden" name="elementtype" value="'.$object->elementtype.'">';
+				print '<input type="hidden" name="fk_element" value="' . $object->fk_element . '">';
+				print '<input type="hidden" name="elementtype" value="' . $object->elementtype . '">';
 				print '</td>';
 			}
 
@@ -2310,9 +2497,9 @@
 		}
 
 		// Description
-		print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td>';
+		print '<tr><td class="tdtop">' . $langs->trans("Description") . '</td><td>';
 		// Editeur wysiwyg
-		require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+		require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
 		$doleditor = new DolEditor('note', $object->note_private, '', 120, 'dolibarr_notes', 'In', true, true, isModEnabled('fckeditor'), ROWS_4, '90%');
 		$doleditor->Create();
 		print '</td></tr>';
@@ -2326,6 +2513,12 @@
 		}
 
 		print '</table>';
+		print '<br>';
+
+
+		print $form->buttonsSaveCancel();
+
+		print '</form>';
 
 		// Reminders
 		if (getDolGlobalString('AGENDA_REMINDER_EMAIL') || getDolGlobalString('AGENDA_REMINDER_BROWSER')) {
@@ -2357,22 +2550,22 @@
 			}
 			*/
 
-			print '<label for="addreminder">'.img_picto('', 'bell', 'class="pictofixedwidth"').$langs->trans("AddReminder").'</label> <input type="checkbox" id="addreminder" name="addreminder"'.($checked ? ' '.$checked : '').($disabled ? ' '.$disabled : '').'><br>';
+			print '<label for="addreminder">' . img_picto('', 'bell', 'class="pictofixedwidth"') . $langs->trans("AddReminder") . '</label> <input type="checkbox" id="addreminder" name="addreminder"' . ($checked ? ' ' . $checked : '') . ($disabled ? ' ' . $disabled : '') . '><br>';
 
-			print '<div class="reminderparameters" '.(empty($checked) ? 'style="display: none;"' : '').'>';
+			print '<div class="reminderparameters" ' . (empty($checked) ? 'style="display: none;"' : '') . '>';
 
 			print '<br>';
 
 			print '<table class="border centpercent">';
 
 			// Reminder
-			print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ReminderTime").'</td><td colspan="3">';
-			print '<input type="number" name="offsetvalue" class="width50" value="'.$actionCommReminder->offsetvalue.'"> ';
+			print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("ReminderTime") . '</td><td colspan="3">';
+			print '<input type="number" name="offsetvalue" class="width50" value="' . $actionCommReminder->offsetvalue . '"> ';
 			print $form->selectTypeDuration('offsetunit', $actionCommReminder->offsetunit, array('y', 'm'));
 			print '</td></tr>';
 
 			// Reminder Type
-			print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ReminderType").'</td><td colspan="3">';
+			print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("ReminderType") . '</td><td colspan="3">';
 			print $form->selectarray('selectremindertype', $TRemindTypes, $actionCommReminder->typeremind, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
 			print '</td></tr>';
 
@@ -2383,14 +2576,103 @@
 
 			// Mail Model
 			if (getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
-				print '<tr '.$hide.'><td class="titlefieldcreate nowrap">'.$langs->trans("EMailTemplates").'</td><td colspan="3">';
+				print '<tr ' . $hide . '><td class="titlefieldcreate nowrap">' . $langs->trans("EMailTemplates") . '</td><td colspan="3">';
 				print $form->selectModelMail('actioncommsend', 'actioncomm_send', 1, 1, $actionCommReminder->fk_email_template);
 				print '</td></tr>';
 			}
 
 			print '</table>';
 
-			print "\n".'<script type="text/javascript">';
+			print '<br>';
+
+			print '<div><input type="submit" class="button" value="' . $langs->trans("ReminderAdd") . '"></div>';
+
+			print '<br>';
+
+
+			print '<div class="reminder-list" data-has-reminders="' . (count($reminders) > 0 ? '1' : '0') . '" style="' . (count($reminders) == 0 ? 'display:none;' : '') . '">';
+
+			print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?id=' . (int) $actioncomm->id . '">';
+			print '<input type="hidden" name="action" value="massdeletereminder">';
+			print '<div class="div-table-responsive-no-min">';
+			print '<table class="liste centpercent">';
+			print '<tr class="liste_titre">';
+			print '<td>' . $langs->trans("ReminderType") . '</td>';
+			print '<td>' . $langs->trans("ReminderDelay") . '</td>';
+			print '<td class="right">' . $langs->trans("Edit") . '</td>';
+			print '<td class="center"><input type="checkbox" id="checkallreminders"></td>';
+			print '</tr>';
+
+			foreach ($reminders as $reminder) {
+				print '<tr class="oddeven">';
+				print '<td>' . $reminder->typeremind . '</td>';
+				print '<td>' . $reminder->offsetvalue . ' ' . $reminder->offsetunit . '</td>';
+
+
+				$urlto = dol_buildpath('/comm/action/reminder_edit_popup.php', 1) . '?id=' . $reminder->id;
+
+				print '<td class="right">';
+				print dolButtonToOpenUrlInDialogPopup(
+					'editReminder' . $reminder->id,
+					$langs->trans("Modify"),
+					img_picto($langs->trans("Edit"), 'edit', 'class="p-1"'),
+					$urlto,
+					'',
+					'nohover'
+				);
+				print '<td class="center"><input type="checkbox" class="reminder-checkbox" name="reminderids[]" value="' . $reminder->id . '"></td>';
+
+				print '</td>';
+				print '</tr>';
+			}
+
+
+			print '</table>';
+			print '</div>';
+			print '<div class="tabsAction">';
+			print '<input type="submit" class="butActionDelete" value="' . $langs->trans("DeleteSelected") . '">';
+			print '</div>';
+			print '</form>';
+
+			print '<script>
+$(document).ready(function () {
+    $("#ajax-add-reminder").on("submit", function (e) {
+        e.preventDefault();
+        var form = $(this);
+        var formData = form.serialize() + "&ajax=1&action=addreminder";
+
+        $.ajax({
+            url: window.location.href,
+            method: "POST",
+            data: formData,
+            dataType: "json",
+            success: function (response) {
+                if (response.success) {
+                    $(".reminder-list").show();
+                    $(".reminder-list table").append(
+                        "<tr>" +
+                        "<td>" + response.type + "</td>" +
+                        "<td>" + response.delay + "</td>" +
+                        "<td>" +
+                        "<a class=\'button\' href=\'" + window.location.pathname + "?id=' . (int) $actioncomm->id . '&reminderid=" + response.id + "&action=editreminder\'>" + "' . dol_escape_js($langs->transnoentities("Modify")) . '" + "</a> " +
+                        "<a class=\'button\' href=\'" + window.location.pathname + "?id=' . (int) $actioncomm->id . '&reminderid=" + response.id + "&action=deletereminder\'>" + "' . dol_escape_js($langs->transnoentities("Delete")) . '" + "</a>" +
+                        "</td>" +
+                        "</tr>"
+                    );
+                    form[0].reset();
+                }
+            },
+            error: function (xhr) {
+                alert("Erreur : " + xhr.responseText);
+            }
+        });
+    });
+});
+</script>';
+
+
+
+			print "\n" . '<script type="text/javascript">';
 			print '$(document).ready(function () {
 	            		$("#addreminder").click(function(){
 	            		    if (this.checked) {
@@ -2410,16 +2692,16 @@
 	            		});
 
                    })';
-			print '</script>'."\n";
+			print '</script>' . "\n";
 
 			$reminderDefaultEventTypes = getDolGlobalString('AGENDA_DEFAULT_REMINDER_EVENT_TYPES', '');
 			$reminderDefaultOffset = getDolGlobalString('AGENDA_DEFAULT_REMINDER_OFFSET', 30);
 			$reminderDefaultUnit = getDolGlobalString('AGENDA_DEFAULT_REMINDER_OFFSET_UNIT');
 			$reminderDefaultEmailModel = getDolGlobalString('AGENDA_DEFAULT_REMINDER_EMAIL_MODEL');
 
-			print "\n".'<script type="text/javascript">';
+			print "\n" . '<script type="text/javascript">';
 			print '$(document).ready(function () {
-					const reminderDefaultEventTypes = \''.dol_escape_js($reminderDefaultEventTypes).'\';
+					const reminderDefaultEventTypes = \'' . dol_escape_js($reminderDefaultEventTypes) . '\';
 					$("#actioncode").change(function(){
 						var selected_event_type = $("#actioncode option:selected").val();
 
@@ -2428,9 +2710,9 @@
 							$("#addreminder").prop("checked", true);
 
 							// Set period with default reminder period
-							$("#offsetvalue").val(\''.dol_escape_js($reminderDefaultOffset).'\');
+							$("#offsetvalue").val(\'' . dol_escape_js($reminderDefaultOffset) . '\');
 							$("#select_offsetunittype_duration").select2("destroy");
-							$("#select_offsetunittype_duration").val(\''.dol_escape_js($reminderDefaultUnit).'\');
+							$("#select_offsetunittype_duration").val(\'' . dol_escape_js($reminderDefaultUnit) . '\');
 							$("#select_offsetunittype_duration").select2();
 
 							$("#selectremindertype").select2("destroy");
@@ -2440,20 +2722,16 @@
 							// Set default reminder mail model
 							$("#select_actioncommsendmodel_mail").closest("tr").show();
 							$("#select_actioncommsendmodel_mail").select2("destroy");
-							$("#select_actioncommsendmodel_mail").val(\''.dol_escape_js($reminderDefaultEmailModel).'\');
+							$("#select_actioncommsendmodel_mail").val(\'' . dol_escape_js($reminderDefaultEmailModel) . '\');
 							$("#select_actioncommsendmodel_mail").select2();
 						}
 					});
 			   })';
-			print '</script>'."\n";
+			print '</script>' . "\n";
 			print '</div>';		// End of div for reminderparameters
 		}
 
 		print dol_get_fiche_end();
-
-		print $form->buttonsSaveCancel();
-
-		print '</form>';
 	} else {
 		print dol_get_fiche_head($head, 'card', $langs->trans("Action"), -1, 'action');
 
@@ -2461,7 +2739,7 @@
 
 		// Clone event
 		if ($action == 'clone') {
-			$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.GETPOST('id'), $langs->trans('ToClone'), $langs->trans('ConfirmCloneEvent', $object->label), 'confirm_clone', array(), 'yes', 1);
+			$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . GETPOST('id'), $langs->trans('ToClone'), $langs->trans('ConfirmCloneEvent', $object->label), 'confirm_clone', array(), 'yes', 1);
 		}
 
 		// Call Hook formConfirm
@@ -2478,33 +2756,33 @@
 
 		$linkback = '';
 		// Link to other agenda views
-		$linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&restore_lastsearch_values=1">';
+		$linkback .= '<a href="' . DOL_URL_ROOT . '/comm/action/list.php?mode=show_list&restore_lastsearch_values=1">';
 		$linkback .= img_picto($langs->trans("BackToList"), 'object_calendarlist', 'class="pictoactionview pictofixedwidth"');
-		$linkback .= '<span class="hideonsmartphone">'.$langs->trans("BackToList").'</span>';
+		$linkback .= '<span class="hideonsmartphone">' . $langs->trans("BackToList") . '</span>';
 		$linkback .= '</a>';
 		$linkback .= '</li>';
 		$linkback .= '<li class="noborder litext">';
-		$linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/index.php?mode=show_month&year='.dol_print_date($object->datep, '%Y').'&month='.dol_print_date($object->datep, '%m').'&day='.dol_print_date($object->datep, '%d').'">';
+		$linkback .= '<a href="' . DOL_URL_ROOT . '/comm/action/index.php?mode=show_month&year=' . dol_print_date($object->datep, '%Y') . '&month=' . dol_print_date($object->datep, '%m') . '&day=' . dol_print_date($object->datep, '%d') . '">';
 		$linkback .= img_picto($langs->trans("ViewCal"), 'object_calendar', 'class="pictoactionview pictofixedwidth"');
-		$linkback .= '<span class="hideonsmartphone">'.$langs->trans("ViewCal").'</span>';
+		$linkback .= '<span class="hideonsmartphone">' . $langs->trans("ViewCal") . '</span>';
 		$linkback .= '</a>';
 		$linkback .= '</li>';
 		$linkback .= '<li class="noborder litext">';
-		$linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/index.php?mode=show_week&year='.dol_print_date($object->datep, '%Y').'&month='.dol_print_date($object->datep, '%m').'&day='.dol_print_date($object->datep, '%d').'">';
+		$linkback .= '<a href="' . DOL_URL_ROOT . '/comm/action/index.php?mode=show_week&year=' . dol_print_date($object->datep, '%Y') . '&month=' . dol_print_date($object->datep, '%m') . '&day=' . dol_print_date($object->datep, '%d') . '">';
 		$linkback .= img_picto($langs->trans("ViewWeek"), 'object_calendarweek', 'class="pictoactionview pictofixedwidth"');
-		$linkback .= '<span class="hideonsmartphone">'.$langs->trans("ViewWeek").'</span>';
+		$linkback .= '<span class="hideonsmartphone">' . $langs->trans("ViewWeek") . '</span>';
 		$linkback .= '</a>';
 		$linkback .= '</li>';
 		$linkback .= '<li class="noborder litext">';
-		$linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/index.php?mode=show_day&year='.dol_print_date($object->datep, '%Y').'&month='.dol_print_date($object->datep, '%m').'&day='.dol_print_date($object->datep, '%d').'">';
+		$linkback .= '<a href="' . DOL_URL_ROOT . '/comm/action/index.php?mode=show_day&year=' . dol_print_date($object->datep, '%Y') . '&month=' . dol_print_date($object->datep, '%m') . '&day=' . dol_print_date($object->datep, '%d') . '">';
 		$linkback .= img_picto($langs->trans("ViewDay"), 'object_calendarday', 'class="pictoactionview pictofixedwidth"');
-		$linkback .= '<span class="hideonsmartphone">'.$langs->trans("ViewDay").'</span>';
+		$linkback .= '<span class="hideonsmartphone">' . $langs->trans("ViewDay") . '</span>';
 		$linkback .= '</a>';
 		$linkback .= '</li>';
 		$linkback .= '<li class="noborder litext">';
-		$linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/peruser.php?mode=show_peruser&year='.dol_print_date($object->datep, '%Y').'&month='.dol_print_date($object->datep, '%m').'&day='.dol_print_date($object->datep, '%d').'">';
+		$linkback .= '<a href="' . DOL_URL_ROOT . '/comm/action/peruser.php?mode=show_peruser&year=' . dol_print_date($object->datep, '%Y') . '&month=' . dol_print_date($object->datep, '%m') . '&day=' . dol_print_date($object->datep, '%d') . '">';
 		$linkback .= img_picto($langs->trans("ViewPerUser"), 'object_calendarperuser', 'class="pictoactionview pictofixedwidth"');
-		$linkback .= '<span class="hideonsmartphone">'.$langs->trans("ViewPerUser").'</span>';
+		$linkback .= '<span class="hideonsmartphone">' . $langs->trans("ViewPerUser") . '</span>';
 		$linkback .= '</a>';
 
 		// Add more views from hooks
@@ -2528,16 +2806,16 @@
 			if ($usercancreate) {
 				$morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
 				if ($action != 'classify') {
-					$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
+					$morehtmlref .= '<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> ';
 				}
-				$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
+				$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
 			} else {
 				if (!empty($object->fk_project)) {
 					$proj = new Project($db);
 					$proj->fetch($object->fk_project);
 					$morehtmlref .= $proj->getNomUrl(1);
 					if ($proj->title) {
-						$morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
+						$morehtmlref .= '<span class="opacitymedium"> - ' . dol_escape_htmltag($proj->title) . '</span>';
 					}
 				}
 			}
@@ -2557,11 +2835,11 @@
 
 		// Type
 		if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
-			print '<tr><td class="titlefield">'.$langs->trans("Type").'</td><td>';
-			$labeltype = ($langs->transnoentities("Action".$object->type_code) != "Action".$object->type_code) ? $langs->transnoentities("Action".$object->type_code) : $object->type_label;
+			print '<tr><td class="titlefield">' . $langs->trans("Type") . '</td><td>';
+			$labeltype = ($langs->transnoentities("Action" . $object->type_code) != "Action" . $object->type_code) ? $langs->transnoentities("Action" . $object->type_code) : $object->type_label;
 			$labeltoshow = $labeltype;
 			if ($object->code) {
-				$labeltoshow .= ' ('.$object->code.')';
+				$labeltoshow .= ' (' . $object->code . ')';
 			}
 			print $object->getTypePicto('pictofixedwidth paddingright', $labeltoshow);
 			print $labeltype;
@@ -2569,11 +2847,11 @@
 		}
 
 		// Full day event
-		print '<tr><td class="titlefield">'.$langs->trans("EventOnFullDay").'</td><td>'.yn($object->fulldayevent ? 1 : 0, 3).'</td></tr>';
+		print '<tr><td class="titlefield">' . $langs->trans("EventOnFullDay") . '</td><td>' . yn($object->fulldayevent ? 1 : 0, 3) . '</td></tr>';
 
 		// Event into a series
 		if ($object->recurid) {
-			print '<tr><td class="titlefield">'.$langs->trans("EventIntoASerie").'</td><td>'.dol_escape_htmltag($object->recurid).'</td></tr>';
+			print '<tr><td class="titlefield">' . $langs->trans("EventIntoASerie") . '</td><td>' . dol_escape_htmltag($object->recurid) . '</td></tr>';
 		}
 
 		$rowspan = 4;
@@ -2582,7 +2860,7 @@
 		}
 
 		// Date start
-		print '<tr><td>'.$langs->trans("DateActionStart").'</td><td>';
+		print '<tr><td>' . $langs->trans("DateActionStart") . '</td><td>';
 		// Test a date before the 27 march and one after
 		//print dol_print_date($object->datep, 'dayhour', 'gmt');
 		//print dol_print_date($object->datep, 'dayhour', 'tzuser');
@@ -2600,7 +2878,7 @@
 		print '</tr>';
 
 		// Date end
-		print '<tr><td>'.$langs->trans("DateActionEnd").'</td><td>';
+		print '<tr><td>' . $langs->trans("DateActionEnd") . '</td><td>';
 		if (empty($object->fulldayevent)) {
 			print dol_print_date($object->datef, 'dayhour', 'tzuserrel');
 		} else {
@@ -2614,11 +2892,11 @@
 
 		// Location
 		if (!getDolGlobalString('AGENDA_DISABLE_LOCATION')) {
-			print '<tr><td>'.$langs->trans("Location").'</td><td>'.$object->location.'</td></tr>';
+			print '<tr><td>' . $langs->trans("Location") . '</td><td>' . $object->location . '</td></tr>';
 		}
 
 		// Assigned to user
-		print '<tr><td class="nowrap">'.$langs->trans("ActionAssignedTo").'</td><td>';
+		print '<tr><td class="nowrap">' . $langs->trans("ActionAssignedTo") . '</td><td>';
 		$listofuserid = array();
 		if (empty($donotclearsession)) {
 			if ($object->userownerid > 0) {
@@ -2662,7 +2940,7 @@
 
 		// Categories
 		if (isModEnabled('category')) {
-			print '<tr><td class="valignmiddle">'.$langs->trans("Categories").'</td><td>';
+			print '<tr><td class="valignmiddle">' . $langs->trans("Categories") . '</td><td>';
 			print $form->showCategories($object->id, Categorie::TYPE_ACTIONCOMM, 1);
 			print "</td></tr>";
 		}
@@ -2678,17 +2956,17 @@
 
 		if (isModEnabled("societe")) {
 			// Related company
-			print '<tr><td class="titlefield">'.$langs->trans("ActionOnCompany").'</td>';
-			print '<td>'.(is_object($object->thirdparty) && $object->thirdparty->id ? $object->thirdparty->getNomUrl(1) : ('<span class="opacitymedium">'.$langs->trans("None").'</span>'));
+			print '<tr><td class="titlefield">' . $langs->trans("ActionOnCompany") . '</td>';
+			print '<td>' . (is_object($object->thirdparty) && $object->thirdparty->id ? $object->thirdparty->getNomUrl(1) : ('<span class="opacitymedium">' . $langs->trans("None") . '</span>'));
 			if (is_object($object->thirdparty) && $object->thirdparty->id > 0 && $object->type_code == 'AC_TEL') {
 				if ($object->thirdparty->fetch($object->thirdparty->id)) {
-					print "<br>".dol_print_phone($object->thirdparty->phone);
+					print "<br>" . dol_print_phone($object->thirdparty->phone);
 				}
 			}
 			print '</td></tr>';
 
 			// Related contact
-			print '<tr><td>'.$langs->trans("ActionOnContact").'</td>';
+			print '<tr><td>' . $langs->trans("ActionOnContact") . '</td>';
 			print '<td>';
 
 			if (!empty($object->socpeopleassigned)) {
@@ -2704,14 +2982,14 @@
 						print $contact->getNomUrl(1);
 						if ($object->type_code == 'AC_TEL') {
 							if (!empty($contact->phone_pro)) {
-								print '('.dol_print_phone($contact->phone_pro).')';
+								print '(' . dol_print_phone($contact->phone_pro) . ')';
 							}
 						}
 						print '<div class="paddingright"></div>';
 					}
 				}
 			} else {
-				print '<span class="opacitymedium">'.$langs->trans("None").'</span>';
+				print '<span class="opacitymedium">' . $langs->trans("None") . '</span>';
 			}
 			print '</td></tr>';
 		}
@@ -2726,12 +3004,12 @@
 		// Object linked (if link is for thirdparty, contact, project it is a recording error. We should not have links in link table
 		// for such objects because there is already a dedicated field into table llx_actioncomm.
 		if (!empty($object->fk_element) && !empty($object->elementtype) && !in_array($object->elementtype, array('societe', 'contact', 'project'))) {
-			include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
-			print '<tr><td>'.$langs->trans("LinkedObject").'</td>';
+			include_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
+			print '<tr><td>' . $langs->trans("LinkedObject") . '</td>';
 			$link = dolGetElementUrl($object->fk_element, $object->elementtype, 1);
 			print '<td>';
 			if (empty($link)) {
-				print '<span class="opacitymedium">'.$langs->trans("ObjectDeleted").'</span>';
+				print '<span class="opacitymedium">' . $langs->trans("ObjectDeleted") . '</span>';
 			} else {
 				print $link;
 			}
@@ -2740,25 +3018,25 @@
 
 		//mail information
 		if (!empty($object->email_msgid)) {
-			print '<tr><td>'.$langs->trans('MailTopic').'</td>';
-			print '<td>'.dol_escape_htmltag($object->email_subject).'</td></tr>';
-			print '<tr><td>'.$langs->trans('MailFrom').'</td>';
-			print '<td>'.dol_escape_htmltag($object->email_from).'</td></tr>';
-			print '<tr><td>'.$langs->trans('MailTo').'</td>';
-			print '<td>'.dol_escape_htmltag($object->email_to).'</td></tr>';
+			print '<tr><td>' . $langs->trans('MailTopic') . '</td>';
+			print '<td>' . dol_escape_htmltag($object->email_subject) . '</td></tr>';
+			print '<tr><td>' . $langs->trans('MailFrom') . '</td>';
+			print '<td>' . dol_escape_htmltag($object->email_from) . '</td></tr>';
+			print '<tr><td>' . $langs->trans('MailTo') . '</td>';
+			print '<td>' . dol_escape_htmltag($object->email_to) . '</td></tr>';
 			if (!empty($object->email_tocc)) {
-				print '<tr><td>'.$langs->trans('MailCC').'</td>';
-				print '<td>'.dol_escape_htmltag($object->email_tocc).'</td></tr>';
+				print '<tr><td>' . $langs->trans('MailCC') . '</td>';
+				print '<td>' . dol_escape_htmltag($object->email_tocc) . '</td></tr>';
 			}
 		}
 
 		// Description
-		print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td class="wordbreak sensiblehtmlcontent">';
+		print '<tr><td class="tdtop">' . $langs->trans("Description") . '</td><td class="wordbreak sensiblehtmlcontent">';
 		print dol_string_onlythesehtmltags(dol_htmlentitiesbr($object->note_private));
 		print '</td></tr>';
 
 		// Other attributes
-		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
+		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
 
 		// Reminders
 		if (getDolGlobalString('AGENDA_REMINDER_EMAIL') || getDolGlobalString('AGENDA_REMINDER_BROWSER')) {
@@ -2768,7 +3046,7 @@
 			}
 			$object->loadReminders('', $filteruserid, false);
 
-			print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("Reminders").'</td><td>';
+			print '<tr><td class="titlefieldcreate nowrap">' . $langs->trans("Reminders") . '</td><td>';
 
 			if (count($object->reminders) > 0) {
 				$tmpuserstatic = new User($db);
@@ -2777,9 +3055,9 @@
 					print $TRemindTypes[$actioncommreminder->typeremind]['label'];
 					if ($actioncommreminder->fk_user > 0) {
 						$tmpuserstatic->fetch($actioncommreminder->fk_user);
-						print ' ('.$tmpuserstatic->getNomUrl(0, '', 0, 0, 16).')';
+						print ' (' . $tmpuserstatic->getNomUrl(0, '', 0, 0, 16) . ')';
 					}
-					print ' - '.$actioncommreminder->offsetvalue.' '.$TDurationTypes[$actioncommreminder->offsetunit];
+					print ' - ' . $actioncommreminder->offsetvalue . ' ' . $TDurationTypes[$actioncommreminder->offsetunit];
 
 					if ($actioncommreminder->status == $actioncommreminder::STATUS_TODO) {
 						print ' - <span class="opacitymedium">';
@@ -2811,6 +3089,8 @@
 	}
 
 
+
+
 	/*
 	 * Action bar
 	 */
@@ -2820,29 +3100,50 @@
 	$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
 	if (empty($reshook)) {
 		if ($action != 'edit') {
-			if ($user->hasRight('agenda', 'allactions', 'create') ||
-			   (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))) {
-				print '<div class="inline-block divButAction"><a class="butAction" href="card.php?action=edit&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Modify").'</a></div>';
+			if (
+				$user->hasRight('agenda', 'allactions', 'create') ||
+				(($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))
+			) {
+				print '<div class="inline-block divButAction"><a class="butAction" href="card.php?action=edit&token=' . newToken() . '&id=' . $object->id . '">' . $langs->trans("Modify") . '</a></div>';
 			} else {
-				print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans("Modify").'</a></div>';
+				print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="' . $langs->trans("NotAllowed") . '">' . $langs->trans("Modify") . '</a></div>';
 			}
 
-			if ($user->hasRight('agenda', 'allactions', 'create') ||
-			   (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))) {
-				print '<div class="inline-block divButAction"><a class="butAction" href="card.php?action=clone&object='.$object->element.'&id='.$object->id.'">'.$langs->trans("ToClone").'</a></div>';
+			if (
+				$user->hasRight('agenda', 'allactions', 'create') ||
+				(($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))
+			) {
+				print '<div class="inline-block divButAction"><a class="butAction" href="card.php?action=clone&object=' . $object->element . '&id=' . $object->id . '">' . $langs->trans("ToClone") . '</a></div>';
 			} else {
-				print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans("ToClone").'</a></div>';
+				print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="' . $langs->trans("NotAllowed") . '">' . $langs->trans("ToClone") . '</a></div>';
 			}
 
-			if ($user->hasRight('agenda', 'allactions', 'delete') ||
-			   (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'delete'))) {
-				print '<div class="inline-block divButAction"><a class="butActionDelete" href="card.php?action=delete&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Delete").'</a></div>';
+			if (
+				$user->hasRight('agenda', 'allactions', 'delete') ||
+				(($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'delete'))
+			) {
+				print '<div class="inline-block divButAction"><a class="butActionDelete" href="card.php?action=delete&token=' . newToken() . '&id=' . $object->id . '">' . $langs->trans("Delete") . '</a></div>';
 			} else {
-				print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans("Delete").'</a></div>';
+				print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="' . $langs->trans("NotAllowed") . '">' . $langs->trans("Delete") . '</a></div>';
 			}
 		}
 	}
 
+	$url = dol_buildpath('/custom/reminderevents/reminders_list_event.php', 1) . '?eventid=' . $object->id;
+	print '<td><a class="nowrap" href="' . $url . '">' . "lien list" . ' ' . img_picto($langs->trans("Edit"), 'edit') . '</a></td>';
+
+	// $button = dolButtonToOpenUrlInDialogPopup(
+	// 	'eventReminders',
+	// 	$langs->trans("Reminders"),
+	// 	img_picto('', 'bell') . ' ' . $langs->trans("ShowReminders"),
+	// 	$url,
+	// 	'',
+	// 	'nohover'
+	// );
+
+	// Affiche le bouton dans le bloc des actions
+	print '<div class="inline-block">' . $button . '</div>';
+
 	print '</div>';
 
 	if ($action != 'edit') {
@@ -2854,8 +3155,8 @@
 			 * Generated documents
 			 */
 
-			$filedir = $conf->agenda->multidir_output[$conf->entity].'/'.$object->id;
-			$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
+			$filedir = $conf->agenda->multidir_output[$conf->entity] . '/' . $object->id;
+			$urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
 
 			$genallowed = $user->hasRight('agenda', 'myactions', 'read');
 			$delallowed = $user->hasRight('agenda', 'myactions', 'create');

########## comm/propal/list.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/comm/propal/list.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/comm/propal/list.php	2025-03-17 14:10:29.831059000 +0000
@@ -42,20 +42,20 @@
 
 // Load Dolibarr environment
 require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formpropal.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formpropal.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
 if (isModEnabled('margin')) {
-	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
 }
-require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
-require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php';
+require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
 if (isModEnabled('category')) {
-	require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
-	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcategory.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcategory.class.php';
 }
 
 /**
@@ -196,7 +196,7 @@
 $hookmanager->initHooks(array('propallist'));
 $result = restrictedArea($user, $module, $objectid, $dbtable);
 
-$diroutputmassaction = $conf->propal->multidir_output[$conf->entity].'/temp/massgeneration/'.$user->id;
+$diroutputmassaction = $conf->propal->multidir_output[$conf->entity] . '/temp/massgeneration/' . $user->id;
 
 // Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
 $object = new Propal($db);
@@ -302,7 +302,7 @@
 }
 
 // Extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';
 
 // Permissions
 $permissiontoread = $user->hasRight('propal', 'lire');
@@ -343,7 +343,7 @@
 
 if (empty($reshook)) {
 	// Selection of new fields
-	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+	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
@@ -425,7 +425,7 @@
 	$objectclass = 'Propal';
 	$objectlabel = 'Proposals';
 	$uploaddir = $conf->propal->multidir_output[$conf->entity];
-	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
+	include DOL_DOCUMENT_ROOT . '/core/actions_massactions.inc.php';
 }
 
 if ($action == 'validate' && $permissiontovalidate) {
@@ -468,7 +468,7 @@
 				if ($tmpproposal->status == $tmpproposal::STATUS_VALIDATED) {
 					$tmpproposal->status = $tmpproposal::STATUS_SIGNED;
 					if ($tmpproposal->closeProposal($user, $tmpproposal::STATUS_SIGNED) >= 0) {
-						setEventMessages($tmpproposal->ref." ".$langs->trans('Signed'), null, 'mesgs');
+						setEventMessages($tmpproposal->ref . " " . $langs->trans('Signed'), null, 'mesgs');
 					} else {
 						setEventMessages($tmpproposal->error, $tmpproposal->errors, 'errors');
 						$error++;
@@ -499,13 +499,13 @@
 				if ($tmpproposal->status == $tmpproposal::STATUS_VALIDATED || (getDolGlobalString('PROPAL_SKIP_ACCEPT_REFUSE') && $tmpproposal->statut == $tmpproposal::STATUS_DRAFT)) {
 					$tmpproposal->status = $tmpproposal::STATUS_NOTSIGNED;
 					if ($tmpproposal->closeProposal($user, $tmpproposal::STATUS_NOTSIGNED) > 0) {
-						setEventMessage($tmpproposal->ref." ".$langs->trans('NoSigned'), 'mesgs');
+						setEventMessage($tmpproposal->ref . " " . $langs->trans('NoSigned'), 'mesgs');
 					} else {
 						setEventMessages($tmpproposal->error, $tmpproposal->errors, 'errors');
 						$error++;
 					}
 				} else {
-					setEventMessage($tmpproposal->ref." ".$langs->trans('CantBeNoSign'), 'errors');
+					setEventMessage($tmpproposal->ref . " " . $langs->trans('CantBeNoSign'), 'errors');
 					$error++;
 				}
 			} else {
@@ -596,7 +596,7 @@
 // Add fields from extrafields
 if (!empty($extrafields->attributes[$object->table_element]['label'])) {
 	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
-		$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : '');
+		$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef." . $key . " as options_" . $key : '');
 	}
 }
 // Add fields from hooks
@@ -607,28 +607,28 @@
 
 $sqlfields = $sql; // $sql fields to remove for count total
 
-$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
+$sql .= ' FROM ' . MAIN_DB_PREFIX . 'societe as s';
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as country on (country.rowid = s.fk_pays)";
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_typent as typent on (typent.id = s.fk_typent)";
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_departements as state on (state.rowid = s.fk_departement)";
 
-$sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'propal as p ON p.fk_soc = s.rowid';
+$sql .= ' INNER JOIN ' . MAIN_DB_PREFIX . 'propal as p ON p.fk_soc = s.rowid';
 if (!empty($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
-	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)";
+	$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $object->table_element . "_extrafields as ef on (p.rowid = ef.fk_object)";
 }
 if ($search_all) {
-	$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'propaldet as pd ON p.rowid = pd.fk_propal';
+	$sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'propaldet as pd ON p.rowid = pd.fk_propal';
 }
-$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON p.fk_user_author = u.rowid';
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr ON pr.rowid = p.fk_projet";
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_availability as ava on (ava.rowid = p.fk_availability)";
+$sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'user as u ON p.fk_user_author = u.rowid';
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "projet as pr ON pr.rowid = p.fk_projet";
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_availability as ava on (ava.rowid = p.fk_availability)";
 // Add table from hooks
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
 $sql .= $hookmanager->resPrint;
 
 $sql .= ' WHERE';
-$sql .= ' p.entity IN ('.getEntity('propal').')';
+$sql .= ' p.entity IN (' . getEntity('propal') . ')';
 if ($search_town) {
 	$sql .= natural_search('s.town', $search_town);
 }
@@ -639,10 +639,10 @@
 	$sql .= natural_search("state.nom", $search_state);
 }
 if ($search_country) {
-	$sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')';
+	$sql .= " AND s.fk_pays IN (" . $db->sanitize($db->escape($search_country)) . ')';
 }
 if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) {
-	$sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')';
+	$sql .= " AND s.fk_typent IN (" . $db->sanitize($db->escape($search_type_thirdparty)) . ')';
 }
 if ($search_ref) {
 	$sql .= natural_search('p.ref', $search_ref);
@@ -657,7 +657,7 @@
 	$sql .= natural_search('pr.title', $search_project);
 }
 if ($search_availability) {
-	$sql .= " AND p.fk_availability IN (".$db->sanitize($db->escape($search_availability)).')';
+	$sql .= " AND p.fk_availability IN (" . $db->sanitize($db->escape($search_availability)) . ')';
 }
 $societe_add_ref_in_list = getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST');
 if (empty($arrayfields['s.name_alias']['checked']) && $search_societe) {
@@ -698,7 +698,7 @@
 	$sql .= natural_search("p.fk_warehouse", $search_warehouse, 1);
 }
 if ($search_multicurrency_code != '') {
-	$sql .= " AND p.multicurrency_code = '".$db->escape($search_multicurrency_code)."'";
+	$sql .= " AND p.multicurrency_code = '" . $db->escape($search_multicurrency_code) . "'";
 }
 if ($search_multicurrency_tx != '') {
 	$sql .= natural_search('p.multicurrency_tx', $search_multicurrency_tx, 1);
@@ -716,49 +716,49 @@
 	$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
 }
 if ($search_fk_cond_reglement > 0) {
-	$sql .= " AND p.fk_cond_reglement = ".((int) $search_fk_cond_reglement);
+	$sql .= " AND p.fk_cond_reglement = " . ((int) $search_fk_cond_reglement);
 }
 if ($search_fk_shipping_method > 0) {
-	$sql .= " AND p.fk_shipping_method = ".((int) $search_fk_shipping_method);
+	$sql .= " AND p.fk_shipping_method = " . ((int) $search_fk_shipping_method);
 }
 if ($search_fk_input_reason > 0) {
-	$sql .= " AND p.fk_input_reason = ".((int) $search_fk_input_reason);
+	$sql .= " AND p.fk_input_reason = " . ((int) $search_fk_input_reason);
 }
 if ($search_fk_mode_reglement > 0) {
-	$sql .= " AND p.fk_mode_reglement = ".((int) $search_fk_mode_reglement);
+	$sql .= " AND p.fk_mode_reglement = " . ((int) $search_fk_mode_reglement);
 }
 if ($socid > 0) {
-	$sql .= ' AND s.rowid = '.((int) $socid);
+	$sql .= ' AND s.rowid = ' . ((int) $socid);
 }
 if ($search_status != '' && $search_status != '-1') {
-	$sql .= ' AND p.fk_statut IN ('.$db->sanitize($search_status).')';
+	$sql .= ' AND p.fk_statut IN (' . $db->sanitize($search_status) . ')';
 }
 if ($search_date_start) {
-	$sql .= " AND p.datep >= '".$db->idate($search_date_start)."'";
+	$sql .= " AND p.datep >= '" . $db->idate($search_date_start) . "'";
 }
 if ($search_date_end) {
-	$sql .= " AND p.datep <= '".$db->idate($search_date_end)."'";
+	$sql .= " AND p.datep <= '" . $db->idate($search_date_end) . "'";
 }
 if ($search_date_end_start) {
-	$sql .= " AND p.fin_validite >= '".$db->idate($search_date_end_start)."'";
+	$sql .= " AND p.fin_validite >= '" . $db->idate($search_date_end_start) . "'";
 }
 if ($search_date_end_end) {
-	$sql .= " AND p.fin_validite <= '".$db->idate($search_date_end_end)."'";
+	$sql .= " AND p.fin_validite <= '" . $db->idate($search_date_end_end) . "'";
 }
 if ($search_date_delivery_start) {
-	$sql .= " AND p.date_livraison >= '".$db->idate($search_date_delivery_start)."'";
+	$sql .= " AND p.date_livraison >= '" . $db->idate($search_date_delivery_start) . "'";
 }
 if ($search_date_delivery_end) {
-	$sql .= " AND p.date_livraison <= '".$db->idate($search_date_delivery_end)."'";
+	$sql .= " AND p.date_livraison <= '" . $db->idate($search_date_delivery_end) . "'";
 }
 if ($search_date_signature_start) {
-	$sql .= " AND p.date_signature >= '".$db->idate($search_date_signature_start)."'";
+	$sql .= " AND p.date_signature >= '" . $db->idate($search_date_signature_start) . "'";
 }
 if ($search_date_signature_end) {
-	$sql .= " AND p.date_signature <= '".$db->idate($search_date_signature_end)."'";
+	$sql .= " AND p.date_signature <= '" . $db->idate($search_date_signature_end) . "'";
 }
 if ($search_note_public) {
-	$sql .= " AND p.note_public LIKE '%".$db->escape($db->escapeforlike($search_note_public))."%'";
+	$sql .= " AND p.note_public LIKE '%" . $db->escape($db->escapeforlike($search_note_public)) . "%'";
 }
 if ($search_import_key) {
 	$sql .= natural_search("s.import_key", $search_import_key);
@@ -767,17 +767,17 @@
 if ($search_user > 0) {
 	$sql .= " AND EXISTS (";
 	$sql .= " SELECT ec.fk_c_type_contact, ec.element_id, ec.fk_socpeople";
-	$sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec";
-	$sql .= " INNER JOIN  ".MAIN_DB_PREFIX."c_type_contact as tc";
+	$sql .= " FROM " . MAIN_DB_PREFIX . "element_contact as ec";
+	$sql .= " INNER JOIN  " . MAIN_DB_PREFIX . "c_type_contact as tc";
 	$sql .= " ON ec.fk_c_type_contact = tc.rowid AND tc.element='propal' AND tc.source='internal'";
-	$sql .= " WHERE ec.element_id = p.rowid AND ec.fk_socpeople = ".((int) $search_user).")";
+	$sql .= " WHERE ec.element_id = p.rowid AND ec.fk_socpeople = " . ((int) $search_user) . ")";
 }
 // Search on sale representative
 if ($search_sale && $search_sale != '-1') {
 	if ($search_sale == -2) {
-		$sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
+		$sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc)";
 	} elseif ($search_sale > 0) {
-		$sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
+		$sql .= " AND EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = p.fk_soc AND sc.fk_user = " . ((int) $search_sale) . ")";
 	}
 }
 // Search for tag/category ($searchCategoryCustomerList is an array of ID)
@@ -788,25 +788,25 @@
 	$listofcategoryid = '';
 	foreach ($searchCategoryCustomerList as $searchCategoryCustomer) {
 		if (intval($searchCategoryCustomer) == -2) {
-			$searchCategoryCustomerSqlList[] = "NOT EXISTS (SELECT cs.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as cs WHERE s.rowid = cs.fk_soc)";
+			$searchCategoryCustomerSqlList[] = "NOT EXISTS (SELECT cs.fk_soc FROM " . MAIN_DB_PREFIX . "categorie_societe as cs WHERE s.rowid = cs.fk_soc)";
 		} elseif (intval($searchCategoryCustomer) > 0) {
 			if ($searchCategoryCustomerOperator == 0) {
-				$searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie = ".((int) $searchCategoryCustomer).")";
+				$searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM " . MAIN_DB_PREFIX . "categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie = " . ((int) $searchCategoryCustomer) . ")";
 			} else {
-				$listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryCustomer);
+				$listofcategoryid .= ($listofcategoryid ? ', ' : '') . ((int) $searchCategoryCustomer);
 			}
 		}
 	}
 	if ($listofcategoryid) {
-		$searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie IN (".$db->sanitize($listofcategoryid)."))";
+		$searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM " . MAIN_DB_PREFIX . "categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie IN (" . $db->sanitize($listofcategoryid) . "))";
 	}
 	if ($searchCategoryCustomerOperator == 1) {
 		if (!empty($searchCategoryCustomerSqlList)) {
-			$sql .= " AND (".implode(' OR ', $searchCategoryCustomerSqlList).")";
+			$sql .= " AND (" . implode(' OR ', $searchCategoryCustomerSqlList) . ")";
 		}
 	} else {
 		if (!empty($searchCategoryCustomerSqlList)) {
-			$sql .= " AND (".implode(' AND ', $searchCategoryCustomerSqlList).")";
+			$sql .= " AND (" . implode(' AND ', $searchCategoryCustomerSqlList) . ")";
 		}
 	}
 }
@@ -818,33 +818,33 @@
 	$listofcategoryid = '';
 	foreach ($searchCategoryProductList as $searchCategoryProduct) {
 		if (intval($searchCategoryProduct) == -2) {
-			$searchCategoryProductSqlList[] = "NOT EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."propaldet as pd WHERE pd.fk_propal = p.rowid AND pd.fk_product = ck.fk_product)";
+			$searchCategoryProductSqlList[] = "NOT EXISTS (SELECT ck.fk_product FROM " . MAIN_DB_PREFIX . "categorie_product as ck, " . MAIN_DB_PREFIX . "propaldet as pd WHERE pd.fk_propal = p.rowid AND pd.fk_product = ck.fk_product)";
 		} elseif (intval($searchCategoryProduct) > 0) {
 			if ($searchCategoryProductOperator == 0) {
-				$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."propaldet as pd WHERE pd.fk_propal = p.rowid AND pd.fk_product = ck.fk_product AND ck.fk_categorie = ".((int) $searchCategoryProduct).")";
+				$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM " . MAIN_DB_PREFIX . "categorie_product as ck, " . MAIN_DB_PREFIX . "propaldet as pd WHERE pd.fk_propal = p.rowid AND pd.fk_product = ck.fk_product AND ck.fk_categorie = " . ((int) $searchCategoryProduct) . ")";
 			} else {
-				$listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryProduct);
+				$listofcategoryid .= ($listofcategoryid ? ', ' : '') . ((int) $searchCategoryProduct);
 			}
 		}
 	}
 	if ($listofcategoryid) {
-		$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."propaldet as pd WHERE pd.fk_propal = p.rowid AND pd.fk_product = ck.fk_product AND ck.fk_categorie IN (".$db->sanitize($listofcategoryid)."))";
+		$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM " . MAIN_DB_PREFIX . "categorie_product as ck, " . MAIN_DB_PREFIX . "propaldet as pd WHERE pd.fk_propal = p.rowid AND pd.fk_product = ck.fk_product AND ck.fk_categorie IN (" . $db->sanitize($listofcategoryid) . "))";
 	}
 	if ($searchCategoryProductOperator == 1) {
 		if (!empty($searchCategoryProductSqlList)) {
-			$sql .= " AND (".implode(' OR ', $searchCategoryProductSqlList).")";
+			$sql .= " AND (" . implode(' OR ', $searchCategoryProductSqlList) . ")";
 		}
 	} else {
 		if (!empty($searchCategoryProductSqlList)) {
-			$sql .= " AND (".implode(' AND ', $searchCategoryProductSqlList).")";
+			$sql .= " AND (" . implode(' AND ', $searchCategoryProductSqlList) . ")";
 		}
 	}
 }
 if ($search_option == 'late') {
-	$sql .= " AND p.fin_validite < '".$db->idate(dol_now() - $conf->propal->cloture->warning_delay)."'";
+	$sql .= " AND p.fin_validite < '" . $db->idate(dol_now() - $conf->propal->cloture->warning_delay) . "'";
 }
 // Add where from extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_sql.tpl.php';
 //print $sql;
 
 // Add where from hooks
@@ -855,23 +855,40 @@
 // Add HAVING from hooks
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-$sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 ".$hookmanager->resPrint;
+$sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 " . $hookmanager->resPrint;
 
 // Count total nb of records
 $nbtotalofrecords = '';
 if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
 	/* The fast and low memory method to get and count full list converts the sql into a sql count */
-	$sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
-	$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
+	$parameters = array(
+		'sqlforcount' => $sql,
+		'sqlfields' => $sqlfields,
+		'context' => $parameters['context']
+	);
+
+	$reshook = $hookmanager->executeHooks('beforeCountQuery', $parameters, $object, $action);
+
+	if ($reshook > 0 && !empty($hookmanager->resPrint)) {
+		$sqlforcount = $hookmanager->resPrint;
+	} else {
+		$sqlforcount = preg_replace('/^' . preg_quote($sqlfields, '/') . '/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
+		$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
+	}
+
 	$resql = $db->query($sqlforcount);
 	if ($resql) {
 		$objforcount = $db->fetch_object($resql);
 		$nbtotalofrecords = $objforcount->nbtotalofrecords;
+
+		$_GET['total_ht'] = $objforcount->total_ht ?? 0;
+		$_GET['total_tva'] = $objforcount->total_tva ?? 0;
+		$_GET['total_ttc'] = $objforcount->total_ttc ?? 0;
 	} else {
 		dol_print_error($db);
 	}
 
-	if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller then paging size (filtering), goto and load page 0
+	if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller than paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -897,7 +914,7 @@
 if ($socid > 0) {
 	$soc = new Societe($db);
 	$soc->fetch($socid);
-	$title = $langs->trans('Proposals').' - '.$soc->name;
+	$title = $langs->trans('Proposals') . ' - ' . $soc->name;
 	if (empty($search_societe)) {
 		$search_societe = $soc->name;
 	}
@@ -914,194 +931,194 @@
 
 	$id = $obj->rowid;
 
-	header("Location: ".DOL_URL_ROOT.'/comm/propal/card.php?id='.$id);
+	header("Location: " . DOL_URL_ROOT . '/comm/propal/card.php?id=' . $id);
 	exit;
 }
 
 $help_url = 'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos';
 llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'bodyforlist');
 
-$param = '&search_status='.urlencode($search_status);
+$param = '&search_status=' . urlencode($search_status);
 if (!empty($mode)) {
-	$param .= '&mode='.urlencode($mode);
+	$param .= '&mode=' . urlencode($mode);
 }
 if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
-	$param .= '&contextpage='.urlencode($contextpage);
+	$param .= '&contextpage=' . urlencode($contextpage);
 }
 if ($limit > 0 && $limit != $conf->liste_limit) {
-	$param .= '&limit='.((int) $limit);
+	$param .= '&limit=' . ((int) $limit);
 }
 if ($optioncss != '') {
-	$param .= '&optioncss='.urlencode($optioncss);
+	$param .= '&optioncss=' . urlencode($optioncss);
 }
 if ($socid > 0) {
-	$param .= '&socid='.urlencode((string) ($socid));
+	$param .= '&socid=' . urlencode((string) ($socid));
 }
 if ($search_all) {
-	$param .= '&search_all='.urlencode($search_all);
+	$param .= '&search_all=' . urlencode($search_all);
 }
 if ($search_date_startday) {
-	$param .= '&search_date_startday='.urlencode((string) ($search_date_startday));
+	$param .= '&search_date_startday=' . urlencode((string) ($search_date_startday));
 }
 if ($search_date_startmonth) {
-	$param .= '&search_date_startmonth='.urlencode((string) ($search_date_startmonth));
+	$param .= '&search_date_startmonth=' . urlencode((string) ($search_date_startmonth));
 }
 if ($search_date_startyear) {
-	$param .= '&search_date_startyear='.urlencode((string) ($search_date_startyear));
+	$param .= '&search_date_startyear=' . urlencode((string) ($search_date_startyear));
 }
 if ($search_date_endday) {
-	$param .= '&search_date_endday='.urlencode((string) ($search_date_endday));
+	$param .= '&search_date_endday=' . urlencode((string) ($search_date_endday));
 }
 if ($search_date_endmonth) {
-	$param .= '&search_date_endmonth='.urlencode((string) ($search_date_endmonth));
+	$param .= '&search_date_endmonth=' . urlencode((string) ($search_date_endmonth));
 }
 if ($search_date_endyear) {
-	$param .= '&search_date_endyear='.urlencode((string) ($search_date_endyear));
+	$param .= '&search_date_endyear=' . urlencode((string) ($search_date_endyear));
 }
 if ($search_date_end_startday) {
-	$param .= '&search_date_end_startday='.urlencode((string) ($search_date_end_startday));
+	$param .= '&search_date_end_startday=' . urlencode((string) ($search_date_end_startday));
 }
 if ($search_date_end_startmonth) {
-	$param .= '&search_date_end_startmonth='.urlencode((string) ($search_date_end_startmonth));
+	$param .= '&search_date_end_startmonth=' . urlencode((string) ($search_date_end_startmonth));
 }
 if ($search_date_end_startyear) {
-	$param .= '&search_date_end_startyear='.urlencode((string) ($search_date_end_startyear));
+	$param .= '&search_date_end_startyear=' . urlencode((string) ($search_date_end_startyear));
 }
 if ($search_date_end_endday) {
-	$param .= '&search_date_end_endday='.urlencode((string) ($search_date_end_endday));
+	$param .= '&search_date_end_endday=' . urlencode((string) ($search_date_end_endday));
 }
 if ($search_date_end_endmonth) {
-	$param .= '&search_date_end_endmonth='.urlencode((string) ($search_date_end_endmonth));
+	$param .= '&search_date_end_endmonth=' . urlencode((string) ($search_date_end_endmonth));
 }
 if ($search_date_end_endyear) {
-	$param .= '&search_date_end_endyear='.urlencode((string) ($search_date_end_endyear));
+	$param .= '&search_date_end_endyear=' . urlencode((string) ($search_date_end_endyear));
 }
 if ($search_date_delivery_startday) {
-	$param .= '&search_date_delivery_startday='.urlencode((string) ($search_date_delivery_startday));
+	$param .= '&search_date_delivery_startday=' . urlencode((string) ($search_date_delivery_startday));
 }
 if ($search_date_delivery_startmonth) {
-	$param .= '&search_date_delivery_startmonth='.urlencode((string) ($search_date_delivery_startmonth));
+	$param .= '&search_date_delivery_startmonth=' . urlencode((string) ($search_date_delivery_startmonth));
 }
 if ($search_date_delivery_startyear) {
-	$param .= '&search_date_delivery_startyear='.urlencode((string) ($search_date_delivery_startyear));
+	$param .= '&search_date_delivery_startyear=' . urlencode((string) ($search_date_delivery_startyear));
 }
 if ($search_date_delivery_endday) {
-	$param .= '&search_date_delivery_endday='.urlencode((string) ($search_date_delivery_endday));
+	$param .= '&search_date_delivery_endday=' . urlencode((string) ($search_date_delivery_endday));
 }
 if ($search_date_delivery_endmonth) {
-	$param .= '&search_date_delivery_endmonth='.urlencode((string) ($search_date_delivery_endmonth));
+	$param .= '&search_date_delivery_endmonth=' . urlencode((string) ($search_date_delivery_endmonth));
 }
 if ($search_date_delivery_endyear) {
-	$param .= '&search_date_delivery_endyear='.urlencode((string) ($search_date_delivery_endyear));
+	$param .= '&search_date_delivery_endyear=' . urlencode((string) ($search_date_delivery_endyear));
 }
 if ($search_ref) {
-	$param .= '&search_ref='.urlencode($search_ref);
+	$param .= '&search_ref=' . urlencode($search_ref);
 }
 if ($search_refcustomer) {
-	$param .= '&search_refcustomer='.urlencode($search_refcustomer);
+	$param .= '&search_refcustomer=' . urlencode($search_refcustomer);
 }
 if ($search_refproject) {
-	$param .= '&search_refproject='.urlencode($search_refproject);
+	$param .= '&search_refproject=' . urlencode($search_refproject);
 }
 if ($search_societe) {
-	$param .= '&search_societe='.urlencode($search_societe);
+	$param .= '&search_societe=' . urlencode($search_societe);
 }
 if ($search_societe_alias) {
-	$param .= '&search_societe_alias='.urlencode($search_societe_alias);
+	$param .= '&search_societe_alias=' . urlencode($search_societe_alias);
 }
 if ($search_user > 0) {
-	$param .= '&search_user='.urlencode((string) ($search_user));
+	$param .= '&search_user=' . urlencode((string) ($search_user));
 }
 if ($search_sale > 0) {
-	$param .= '&search_sale='.urlencode((string) $search_sale);
+	$param .= '&search_sale=' . urlencode((string) $search_sale);
 }
 if ($search_montant_ht) {
-	$param .= '&search_montant_ht='.urlencode($search_montant_ht);
+	$param .= '&search_montant_ht=' . urlencode($search_montant_ht);
 }
 if ($search_multicurrency_code != '') {
-	$param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code);
+	$param .= '&search_multicurrency_code=' . urlencode($search_multicurrency_code);
 }
 if ($search_multicurrency_tx != '') {
-	$param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx);
+	$param .= '&search_multicurrency_tx=' . urlencode($search_multicurrency_tx);
 }
 if ($search_multicurrency_montant_ht != '') {
-	$param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht);
+	$param .= '&search_multicurrency_montant_ht=' . urlencode($search_multicurrency_montant_ht);
 }
 if ($search_multicurrency_montant_vat != '') {
-	$param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat);
+	$param .= '&search_multicurrency_montant_vat=' . urlencode($search_multicurrency_montant_vat);
 }
 if ($search_multicurrency_montant_ttc != '') {
-	$param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc);
+	$param .= '&search_multicurrency_montant_ttc=' . urlencode($search_multicurrency_montant_ttc);
 }
 if ($search_login) {
-	$param .= '&search_login='.urlencode($search_login);
+	$param .= '&search_login=' . urlencode($search_login);
 }
 if ($search_town) {
-	$param .= '&search_town='.urlencode($search_town);
+	$param .= '&search_town=' . urlencode($search_town);
 }
 if ($search_zip) {
-	$param .= '&search_zip='.urlencode($search_zip);
+	$param .= '&search_zip=' . urlencode($search_zip);
 }
 if ($search_categ_cus > 0) {
-	$param .= '&search_categ_cus='.urlencode((string) ($search_categ_cus));
+	$param .= '&search_categ_cus=' . urlencode((string) ($search_categ_cus));
 }
 if ($search_product_category != '') {
-	$param .= '&search_product_category='.urlencode((string) ($search_product_category));
+	$param .= '&search_product_category=' . urlencode((string) ($search_product_category));
 }
 if ($search_fk_cond_reglement > 0) {
-	$param .= '&search_fk_cond_reglement='.urlencode((string) ($search_fk_cond_reglement));
+	$param .= '&search_fk_cond_reglement=' . urlencode((string) ($search_fk_cond_reglement));
 }
 if ($search_fk_shipping_method > 0) {
-	$param .= '&search_fk_shipping_method='.urlencode((string) ($search_fk_shipping_method));
+	$param .= '&search_fk_shipping_method=' . urlencode((string) ($search_fk_shipping_method));
 }
 if ($search_fk_input_reason > 0) {
-	$param .= '&search_fk_input_reason='.urlencode((string) ($search_fk_input_reason));
+	$param .= '&search_fk_input_reason=' . urlencode((string) ($search_fk_input_reason));
 }
 if ($search_fk_mode_reglement > 0) {
-	$param .= '&search_fk_mode_reglement='.urlencode((string) ($search_fk_mode_reglement));
+	$param .= '&search_fk_mode_reglement=' . urlencode((string) ($search_fk_mode_reglement));
 }
 if ($search_type_thirdparty > 0) {
-	$param .= '&search_type_thirdparty='.urlencode((string) ($search_type_thirdparty));
+	$param .= '&search_type_thirdparty=' . urlencode((string) ($search_type_thirdparty));
 }
 if ($search_town) {
-	$param .= '&search_town='.urlencode($search_town);
+	$param .= '&search_town=' . urlencode($search_town);
 }
 if ($search_zip) {
-	$param .= '&search_zip='.urlencode($search_zip);
+	$param .= '&search_zip=' . urlencode($search_zip);
 }
 if ($search_state) {
-	$param .= '&search_state='.urlencode($search_state);
+	$param .= '&search_state=' . urlencode($search_state);
 }
 if ($search_town) {
-	$param .= '&search_town='.urlencode($search_town);
+	$param .= '&search_town=' . urlencode($search_town);
 }
 if ($search_country) {
-	$param .= '&search_country='.urlencode((string) ($search_country));
+	$param .= '&search_country=' . urlencode((string) ($search_country));
 }
 if ($search_date_signature_startday) {
-	$param .= '&search_date_signature_startday='.urlencode((string) ($search_date_signature_startday));
+	$param .= '&search_date_signature_startday=' . urlencode((string) ($search_date_signature_startday));
 }
 if ($search_date_signature_startmonth) {
-	$param .= '&search_date_signature_startmonth='.urlencode((string) ($search_date_signature_startmonth));
+	$param .= '&search_date_signature_startmonth=' . urlencode((string) ($search_date_signature_startmonth));
 }
 if ($search_date_signature_startyear) {
-	$param .= '&search_date_signature_startyear='.urlencode((string) ($search_date_signature_startyear));
+	$param .= '&search_date_signature_startyear=' . urlencode((string) ($search_date_signature_startyear));
 }
 if ($search_date_signature_endday) {
-	$param .= '&search_date_signature_endday='.urlencode((string) ($search_date_signature_endday));
+	$param .= '&search_date_signature_endday=' . urlencode((string) ($search_date_signature_endday));
 }
 if ($search_date_signature_endmonth) {
-	$param .= '&search_date_signature_endmonth='.urlencode((string) ($search_date_signature_endmonth));
+	$param .= '&search_date_signature_endmonth=' . urlencode((string) ($search_date_signature_endmonth));
 }
 if ($search_date_signature_endyear) {
-	$param .= '&search_date_signature_endyear='.urlencode((string) ($search_date_signature_endyear));
+	$param .= '&search_date_signature_endyear=' . urlencode((string) ($search_date_signature_endyear));
 }
 if ($search_import_key != '') {
-	$param .= '&search_import_key='.urlencode($search_import_key);
+	$param .= '&search_import_key=' . urlencode($search_import_key);
 }
 
 // Add $param from extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_param.tpl.php';
 // Add $param from hooks
 $parameters = array('param' => &$param);
 $reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
@@ -1109,22 +1126,22 @@
 
 // List of mass actions available
 $arrayofmassactions = array(
-	'generate_doc' => img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
-	'builddoc' => img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
+	'generate_doc' => img_picto('', 'pdf', 'class="pictofixedwidth"') . $langs->trans("ReGeneratePDF"),
+	'builddoc' => img_picto('', 'pdf', 'class="pictofixedwidth"') . $langs->trans("PDFMerge"),
 );
 if ($permissiontosendbymail) {
-	$arrayofmassactions['presend'] = img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail");
+	$arrayofmassactions['presend'] = img_picto('', 'email', 'class="pictofixedwidth"') . $langs->trans("SendByMail");
 }
 if ($permissiontovalidate) {
-	$arrayofmassactions['prevalidate'] = img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate");
+	$arrayofmassactions['prevalidate'] = img_picto('', 'check', 'class="pictofixedwidth"') . $langs->trans("Validate");
 }
 if ($permissiontoclose) {
-	$arrayofmassactions['presign'] = img_picto('', 'propal', 'class="pictofixedwidth"').$langs->trans("Sign");
-	$arrayofmassactions['nopresign'] = img_picto('', 'propal', 'class="pictofixedwidth"').$langs->trans("NoSign");
-	$arrayofmassactions['setbilled'] = img_picto('', 'bill', 'class="pictofixedwidth"').$langs->trans("ClassifyBilled");
+	$arrayofmassactions['presign'] = img_picto('', 'propal', 'class="pictofixedwidth"') . $langs->trans("Sign");
+	$arrayofmassactions['nopresign'] = img_picto('', 'propal', 'class="pictofixedwidth"') . $langs->trans("NoSign");
+	$arrayofmassactions['setbilled'] = img_picto('', 'bill', 'class="pictofixedwidth"') . $langs->trans("ClassifyBilled");
 }
 if ($permissiontodelete) {
-	$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
+	$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"') . $langs->trans("Delete");
 }
 
 if (in_array($massaction, array('presend', 'predelete', 'closed'))) {
@@ -1132,37 +1149,37 @@
 }
 $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
 
-$url = DOL_URL_ROOT.'/comm/propal/card.php?action=create';
+$url = DOL_URL_ROOT . '/comm/propal/card.php?action=create';
 if (!empty($socid)) {
-	$url .= '&socid='.$socid;
+	$url .= '&socid=' . $socid;
 }
 $newcardbutton = '';
-$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition'));
-$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition'));
+$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"] . '?mode=common' . preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition'));
+$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"] . '?mode=kanban' . preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition'));
 $newcardbutton .= dolGetButtonTitleSeparator();
 $newcardbutton .= dolGetButtonTitle($langs->trans('NewPropal'), '', 'fa fa-plus-circle', $url, '', $user->hasRight('propal', 'creer'));
 
 // Fields title search
-print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
+print '<form method="POST" id="searchFormList" action="' . $_SERVER["PHP_SELF"] . '">';
 if ($optioncss != '') {
-	print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	print '<input type="hidden" name="optioncss" value="' . $optioncss . '">';
 }
-print '<input type="hidden" name="token" value="'.newToken().'">';
+print '<input type="hidden" name="token" value="' . newToken() . '">';
 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 print '<input type="hidden" name="action" value="list">';
-print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
-print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
-print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
-print '<input type="hidden" name="socid" value="'.$socid.'">';
-print '<input type="hidden" name="mode"value="'.$mode.'">';
+print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
+print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
+print '<input type="hidden" name="contextpage" value="' . $contextpage . '">';
+print '<input type="hidden" name="socid" value="' . $socid . '">';
+print '<input type="hidden" name="mode"value="' . $mode . '">';
 
 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'propal', 0, $newcardbutton, '', $limit, 0, 0, 1);
 
 $topicmail = "SendPropalRef";
 $modelmail = "propal_send";
 $objecttmp = new Propal($db);
-$trackid = 'pro'.$object->id;
-include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
+$trackid = 'pro' . $object->id;
+include DOL_DOCUMENT_ROOT . '/core/tpl/massactions_pre.tpl.php';
 
 if ($massaction == 'prevalidate') {
 	print $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans("ConfirmMassValidation"), $langs->trans("ConfirmMassValidationQuestion"), "validate", null, '', 0, 200, 500, 1);
@@ -1180,7 +1197,7 @@
 	foreach ($fieldstosearchall as $key => $val) {
 		$fieldstosearchall[$key] = $langs->trans($val);
 	}
-	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).implode(', ', $fieldstosearchall).'</div>';
+	print '<div class="divsearchfieldfilter">' . $langs->trans("FilterOnInto", $search_all) . implode(', ', $fieldstosearchall) . '</div>';
 }
 
 $i = 0;
@@ -1192,37 +1209,37 @@
 	$langs->load("commercial");
 	$moreforfilter .= '<div class="divsearchfield">';
 	$tmptitle = $langs->trans('ThirdPartiesOfSaleRepresentative');
-	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"').$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, $tmptitle, 'maxwidth250 widthcentpercentminusx', 1);
+	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"') . $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, $tmptitle, 'maxwidth250 widthcentpercentminusx', 1);
 	$moreforfilter .= '</div>';
 }
 // If the user can view prospects other than his'
 if ($user->hasRight('user', 'user', 'lire')) {
 	$moreforfilter .= '<div class="divsearchfield">';
 	$tmptitle = $langs->trans('LinkedToSpecificUsers');
-	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"').$form->select_dolusers((empty($search_user) ? -2 : 0), 'search_user', $tmptitle, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth250 widthcentpercentminusx');
+	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"') . $form->select_dolusers((empty($search_user) ? -2 : 0), 'search_user', $tmptitle, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth250 widthcentpercentminusx');
 	$moreforfilter .= '</div>';
 }
 // If the user can view products
 if (isModEnabled('category') && $user->hasRight('categorie', 'read') && ($user->hasRight('product', 'read') || $user->hasRight('service', 'read'))) {
 	$searchCategoryProductOperator = -1;
-	include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
+	include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
 	$tmptitle = $langs->trans('IncludingProductWithTag');
 	$formcategory = new FormCategory($db);
 	$moreforfilter .= $formcategory->getFilterBox(Categorie::TYPE_PRODUCT, array($search_product_category), 'maxwidth300', $searchCategoryProductOperator, 0, 0, $tmptitle);
 }
 if (isModEnabled('category') && $user->hasRight('categorie', 'lire')) {
-	require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
 	$moreforfilter .= '<div class="divsearchfield">';
 	$tmptitle = $langs->trans('CustomersProspectsCategoriesShort');
-	$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"').$formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $tmptitle, (empty($conf->dol_optimize_smallscreen) ? 'maxwidth300 widthcentpercentminusx' : 'maxwidth250 widthcentpercentminusx'));
+	$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"') . $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $tmptitle, (empty($conf->dol_optimize_smallscreen) ? 'maxwidth300 widthcentpercentminusx' : 'maxwidth250 widthcentpercentminusx'));
 	$moreforfilter .= '</div>';
 }
 if (isModEnabled('stock') && getDolGlobalString('WAREHOUSE_ASK_WAREHOUSE_DURING_PROPAL')) {
-	require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
 	$formproduct = new FormProduct($db);
 	$moreforfilter .= '<div class="divsearchfield">';
 	$tmptitle = $langs->trans('Warehouse');
-	$moreforfilter .= img_picto($tmptitle, 'stock', 'class="pictofixedwidth"').$formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', $tmptitle, 0, 0, $tmptitle);
+	$moreforfilter .= img_picto($tmptitle, 'stock', 'class="pictofixedwidth"') . $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', $tmptitle, 0, 0, $tmptitle);
 	$moreforfilter .= '</div>';
 }
 $parameters = array();
@@ -1244,7 +1261,7 @@
 $selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
 
 print '<div class="div-table-responsive">';
-print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
+print '<table class="tagtable nobottomiftotal liste' . ($moreforfilter ? " listwithfilterbefore" : "") . '">' . "\n";
 
 print '<tr class="liste_titre_filter">';
 
@@ -1258,44 +1275,44 @@
 
 if (!empty($arrayfields['p.ref']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth50" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
+	print '<input class="flat maxwidth50" type="text" name="search_ref" value="' . dol_escape_htmltag($search_ref) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['p.ref_client']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth50" type="text" name="search_refcustomer" value="'.dol_escape_htmltag($search_refcustomer).'">';
+	print '<input class="flat maxwidth50" type="text" name="search_refcustomer" value="' . dol_escape_htmltag($search_refcustomer) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['pr.ref']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth50" type="text" name="search_refproject" value="'.dol_escape_htmltag($search_refproject).'">';
+	print '<input class="flat maxwidth50" type="text" name="search_refproject" value="' . dol_escape_htmltag($search_refproject) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['pr.title']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth50" type="text" name="search_project" value="'.dol_escape_htmltag($search_project).'">';
+	print '<input class="flat maxwidth50" type="text" name="search_project" value="' . dol_escape_htmltag($search_project) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['s.nom']['checked'])) {
 	print '<td class="liste_titre" align="left">';
-	print '<input class="flat maxwidth100" type="text" name="search_societe" value="'.dol_escape_htmltag($search_societe).'"'.($socid > 0 ? " disabled" : "").'>';
+	print '<input class="flat maxwidth100" type="text" name="search_societe" value="' . dol_escape_htmltag($search_societe) . '"' . ($socid > 0 ? " disabled" : "") . '>';
 	print '</td>';
 }
 if (!empty($arrayfields['s.name_alias']['checked'])) {
 	print '<td class="liste_titre" align="left">';
-	print '<input class="flat maxwidth100" type="text" name="search_societe_alias" value="'.dol_escape_htmltag($search_societe_alias).'">';
+	print '<input class="flat maxwidth100" type="text" name="search_societe_alias" value="' . dol_escape_htmltag($search_societe_alias) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['s.town']['checked'])) {
-	print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="'.$search_town.'"></td>';
+	print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="' . $search_town . '"></td>';
 }
 if (!empty($arrayfields['s.zip']['checked'])) {
-	print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_zip" value="'.$search_zip.'"></td>';
+	print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_zip" value="' . $search_zip . '"></td>';
 }
 // State
 if (!empty($arrayfields['state.nom']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth50" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
+	print '<input class="flat maxwidth50" type="text" name="search_state" value="' . dol_escape_htmltag($search_state) . '">';
 	print '</td>';
 }
 // Country
@@ -1389,19 +1406,19 @@
 if (!empty($arrayfields['p.total_ht']['checked'])) {
 	// Amount
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">';
+	print '<input class="flat" type="text" size="5" name="search_montant_ht" value="' . dol_escape_htmltag($search_montant_ht) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['p.total_tva']['checked'])) {
 	// Amount
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">';
+	print '<input class="flat" type="text" size="5" name="search_montant_vat" value="' . dol_escape_htmltag($search_montant_vat) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['p.total_ttc']['checked'])) {
 	// Amount
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">';
+	print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="' . dol_escape_htmltag($search_montant_ttc) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) {
@@ -1423,25 +1440,25 @@
 if (!empty($arrayfields['p.multicurrency_tx']['checked'])) {
 	// Currency rate
 	print '<td class="liste_titre">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">';
+	print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="' . dol_escape_htmltag($search_multicurrency_tx) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) {
 	// Amount
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">';
+	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="' . dol_escape_htmltag($search_multicurrency_montant_ht) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['p.multicurrency_total_tva']['checked'])) {
 	// Amount
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="'.dol_escape_htmltag($search_multicurrency_montant_vat).'">';
+	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="' . dol_escape_htmltag($search_multicurrency_montant_vat) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) {
 	// Amount
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">';
+	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="' . dol_escape_htmltag($search_multicurrency_montant_ttc) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) {
@@ -1457,7 +1474,7 @@
 if (!empty($arrayfields['u.login']['checked'])) {
 	// Author
 	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth75" type="text" name="search_login" value="'.dol_escape_htmltag($search_login).'">';
+	print '<input class="flat maxwidth75" type="text" name="search_login" value="' . dol_escape_htmltag($search_login) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['sale_representative']['checked'])) {
@@ -1480,7 +1497,7 @@
 	print '</td>';
 }
 // Extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_input.tpl.php';
 
 // Fields from hook
 $parameters = array('arrayfields' => $arrayfields);
@@ -1504,7 +1521,7 @@
 if (!empty($arrayfields['p.note_public']['checked'])) {
 	// Note public
 	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth75" type="text" name="search_note_public" value="'.dol_escape_htmltag($search_note_public).'">';
+	print '<input class="flat maxwidth75" type="text" name="search_note_public" value="' . dol_escape_htmltag($search_note_public) . '">';
 	print '</td>';
 }
 if (!empty($arrayfields['p.note_private']['checked'])) {
@@ -1515,7 +1532,7 @@
 // Import key
 if (!empty($arrayfields['p.import_key']['checked'])) {
 	print '<td class="liste_titre maxwidthonsmartphone center">';
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_import_key" value="'.dol_escape_htmltag($search_import_key).'">';
+	print '<input class="flat searchstring maxwidth50" type="text" name="search_import_key" value="' . dol_escape_htmltag($search_import_key) . '">';
 	print '</td>';
 }
 // Status
@@ -1701,7 +1718,7 @@
 	$totalarray['nbfield']++;
 }
 // Extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_title.tpl.php';
 // Hook fields
 $parameters = array(
 	'arrayfields' => $arrayfields,
@@ -1747,7 +1764,7 @@
 	print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ');
 	$totalarray['nbfield']++;
 }
-print '</tr>'."\n";
+print '</tr>' . "\n";
 
 // Loop on record
 // --------------------------------------------------------------------
@@ -1755,12 +1772,13 @@
 $now = dol_now();
 
 $with_margin_info = false;
-if (isModEnabled('margin') && (
-	!empty($arrayfields['total_pa']['checked'])
-	|| !empty($arrayfields['total_margin']['checked'])
-	|| !empty($arrayfields['total_margin_rate']['checked'])
-	|| !empty($arrayfields['total_mark_rate']['checked'])
-)
+if (
+	isModEnabled('margin') && (
+		!empty($arrayfields['total_pa']['checked'])
+		|| !empty($arrayfields['total_margin']['checked'])
+		|| !empty($arrayfields['total_margin_rate']['checked'])
+		|| !empty($arrayfields['total_mark_rate']['checked'])
+	)
 ) {
 	$with_margin_info = true;
 }
@@ -1779,7 +1797,7 @@
 		break; // Should not happen
 	}
 	if ($search_option) {
-		$param .= "&search_option=".urlencode($search_option);
+		$param .= "&search_option=" . urlencode($search_option);
 	}
 
 	$objectstatic->id = $obj->rowid;
@@ -1840,7 +1858,7 @@
 
 	if ($mode == 'kanban') {
 		if ($i == 0) {
-			print '<tr class="trkanban"><td colspan="'.$savnbfield.'">';
+			print '<tr class="trkanban"><td colspan="' . $savnbfield . '">';
 			print '<div class="box-flex-container kanban">';
 		}
 		// Output Kanban
@@ -1853,7 +1871,7 @@
 			print '</td></tr>';
 		}
 	} else {
-		print '<tr class="oddeven '.((getDolGlobalInt('MAIN_FINISHED_LINES_OPACITY') == 1 && $obj->status > 1) ? 'opacitymedium' : '').'">';
+		print '<tr class="oddeven ' . ((getDolGlobalInt('MAIN_FINISHED_LINES_OPACITY') == 1 && $obj->status > 1) ? 'opacitymedium' : '') . '">';
 
 		// Action column
 		if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
@@ -1863,7 +1881,7 @@
 				if (in_array($obj->rowid, $arrayofselected)) {
 					$selected = 1;
 				}
-				print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
+				print '<input id="cb' . $obj->rowid . '" class="flat checkforselect" type="checkbox" name="toselect[]" value="' . $obj->rowid . '"' . ($selected ? ' checked="checked"' : '') . '>';
 			}
 			print '</td>';
 			if (!$i) {
@@ -1892,8 +1910,8 @@
 			// Other picto tool
 			print '<td width="16" class="nobordernopadding right">';
 			$filename = dol_sanitizeFileName($obj->ref);
-			$filedir = $conf->propal->multidir_output[$obj->propal_entity].'/'.dol_sanitizeFileName($obj->ref);
-			$urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid;
+			$filedir = $conf->propal->multidir_output[$obj->propal_entity] . '/' . dol_sanitizeFileName($obj->ref);
+			$urlsource = $_SERVER['PHP_SELF'] . '?id=' . $obj->rowid;
 			print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir);
 			print '</td></tr></table>';
 
@@ -1959,7 +1977,7 @@
 
 		// Town
 		if (!empty($arrayfields['s.town']['checked'])) {
-			print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($obj->town).'">';
+			print '<td class="tdoverflowmax100" title="' . dol_escape_htmltag($obj->town) . '">';
 			print dol_escape_htmltag($obj->town);
 			print '</td>';
 			if (!$i) {
@@ -1977,7 +1995,7 @@
 		}
 		// State
 		if (!empty($arrayfields['state.nom']['checked'])) {
-			print "<td>".$obj->state_name."</td>\n";
+			print "<td>" . $obj->state_name . "</td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -1985,7 +2003,7 @@
 		// Country
 		if (!empty($arrayfields['country.code_iso']['checked'])) {
 			$tmparray = getCountry($obj->fk_pays, 'all');
-			print '<td class="center tdoverflowmax100" title="'.dolPrintHTML($tmparray['label']).'">';
+			print '<td class="center tdoverflowmax100" title="' . dolPrintHTML($tmparray['label']) . '">';
 			print $tmparray['label'];
 			print '</td>';
 			if (!$i) {
@@ -2021,7 +2039,7 @@
 		// Date end validity
 		if (!empty($arrayfields['p.fin_validite']['checked'])) {
 			if ($obj->dfv) {
-				print '<td class="center">'.dol_print_date($db->jdate($obj->dfv), 'day');
+				print '<td class="center">' . dol_print_date($db->jdate($obj->dfv), 'day');
 				print '</td>';
 			} else {
 				print '<td>&nbsp;</td>';
@@ -2033,7 +2051,7 @@
 		// Date delivery
 		if (!empty($arrayfields['p.date_livraison']['checked'])) {
 			if ($obj->ddelivery) {
-				print '<td class="center">'.dol_print_date($db->jdate($obj->ddelivery), 'day');
+				print '<td class="center">' . dol_print_date($db->jdate($obj->ddelivery), 'day');
 				print '</td>';
 			} else {
 				print '<td>&nbsp;</td>';
@@ -2045,7 +2063,7 @@
 		// Date Signature
 		if (!empty($arrayfields['p.date_signature']['checked'])) {
 			if ($obj->dsignature) {
-				print '<td class="center">'.dol_print_date($db->jdate($obj->dsignature), 'day');
+				print '<td class="center">' . dol_print_date($db->jdate($obj->dsignature), 'day');
 				print '</td>';
 			} else {
 				print '<td>&nbsp;</td>';
@@ -2078,7 +2096,7 @@
 			if ($obj->fk_input_reason > 0) {
 				$labelInputReason = $form->cache_demand_reason[$obj->fk_input_reason]['label'];
 			}
-			print '<td class="tdoverflowmax125" title="'.dol_escape_htmltag($labelInputReason).'">';
+			print '<td class="tdoverflowmax125" title="' . dol_escape_htmltag($labelInputReason) . '">';
 			print dol_escape_htmltag($labelInputReason);
 			print '</td>';
 			if (!$i) {
@@ -2105,7 +2123,7 @@
 		}
 		// Amount HT
 		if (!empty($arrayfields['p.total_ht']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($obj->total_ht)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($obj->total_ht) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2120,7 +2138,7 @@
 		}
 		// Amount VAT
 		if (!empty($arrayfields['p.total_tva']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($obj->total_tva)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($obj->total_tva) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2135,7 +2153,7 @@
 		}
 		// Amount TTC
 		if (!empty($arrayfields['p.total_ttc']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($obj->total_ttc)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($obj->total_ttc) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2150,7 +2168,7 @@
 		}
 		// Amount invoiced HT
 		if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($totalInvoicedHT)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($totalInvoicedHT) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2165,7 +2183,7 @@
 		}
 		// Amount invoiced TTC
 		if (!empty($arrayfields['p.total_invoiced']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($totalInvoicedTTC)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($totalInvoicedTTC) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2180,7 +2198,7 @@
 		}
 		// Currency
 		if (!empty($arrayfields['p.multicurrency_code']['checked'])) {
-			print '<td class="nowrap">'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."</td>\n";
+			print '<td class="nowrap">' . $obj->multicurrency_code . ' - ' . $langs->trans('Currency' . $obj->multicurrency_code) . "</td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2189,7 +2207,7 @@
 		// Currency rate
 		if (!empty($arrayfields['p.multicurrency_tx']['checked'])) {
 			print '<td class="nowrap">';
-			$form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code);
+			$form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code);
 			print "</td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
@@ -2197,35 +2215,35 @@
 		}
 		// Amount HT
 		if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) {
-			print '<td class="right nowrap"><span class="amount">'.price($obj->multicurrency_total_ht)."</span></td>\n";
+			print '<td class="right nowrap"><span class="amount">' . price($obj->multicurrency_total_ht) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
 		}
 		// Amount VAT
 		if (!empty($arrayfields['p.multicurrency_total_tva']['checked'])) {
-			print '<td class="right nowrap"><span class="amount">'.price($obj->multicurrency_total_tva)."</span></td>\n";
+			print '<td class="right nowrap"><span class="amount">' . price($obj->multicurrency_total_tva) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
 		}
 		// Amount TTC
 		if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) {
-			print '<td class="right nowrap"><span class="amount">'.price($obj->multicurrency_total_ttc)."</span></td>\n";
+			print '<td class="right nowrap"><span class="amount">' . price($obj->multicurrency_total_ttc) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
 		}
 		// Amount invoiced
 		if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($multicurrency_totalInvoicedHT)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($multicurrency_totalInvoicedHT) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
 		}
 		// Amount invoiced
 		if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($multicurrency_totalInvoicedTTC)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($multicurrency_totalInvoicedTTC) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2307,14 +2325,14 @@
 
 		// Total buying or cost price
 		if (!empty($arrayfields['total_pa']['checked'])) {
-			print '<td class="right nowrap">'.price($marginInfo['pa_total']).'</td>';
+			print '<td class="right nowrap">' . price($marginInfo['pa_total']) . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
 		}
 		// Total margin
 		if (!empty($arrayfields['total_margin']['checked'])) {
-			print '<td class="right nowrap">'.price($marginInfo['total_margin']).'</td>';
+			print '<td class="right nowrap">' . price($marginInfo['total_margin']) . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2325,14 +2343,14 @@
 		}
 		// Total margin rate
 		if (!empty($arrayfields['total_margin_rate']['checked'])) {
-			print '<td class="right nowrap">'.(($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], 0, '', 0, 0, 2).'%').'</td>';
+			print '<td class="right nowrap">' . (($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], 0, '', 0, 0, 2) . '%') . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
 		}
 		// Total mark rate
 		if (!empty($arrayfields['total_mark_rate']['checked'])) {
-			print '<td class="right nowrap">'.(($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], 0, '', 0, 0, 2).'%').'</td>';
+			print '<td class="right nowrap">' . (($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], 0, '', 0, 0, 2) . '%') . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2349,7 +2367,7 @@
 		}
 
 		// Extra fields
-		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
+		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_print_fields.tpl.php';
 		// Fields from hook
 		$parameters = array('arrayfields' => $arrayfields, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray);
 		$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
@@ -2402,7 +2420,7 @@
 
 		// Import key
 		if (!empty($arrayfields['p.import_key']['checked'])) {
-			print '<td class="nowrap center">'.dol_escape_htmltag($obj->import_key).'</td>';
+			print '<td class="nowrap center">' . dol_escape_htmltag($obj->import_key) . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2410,7 +2428,7 @@
 
 		// Status
 		if (!empty($arrayfields['p.fk_statut']['checked'])) {
-			print '<td class="nowrap center">'.$objectstatic->getLibStatut(5).'</td>';
+			print '<td class="nowrap center">' . $objectstatic->getLibStatut(5) . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2423,7 +2441,7 @@
 				if (in_array($obj->rowid, $arrayofselected)) {
 					$selected = 1;
 				}
-				print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
+				print '<input id="cb' . $obj->rowid . '" class="flat checkforselect" type="checkbox" name="toselect[]" value="' . $obj->rowid . '"' . ($selected ? ' checked="checked"' : '') . '>';
 			}
 			print '</td>';
 			if (!$i) {
@@ -2432,14 +2450,14 @@
 		}
 
 
-		print '</tr>'."\n";
+		print '</tr>' . "\n";
 	}
 
 	$i++;
 }
 
 // Show total line
-include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/list_print_total.tpl.php';
 
 // If no record found
 if ($num == 0) {
@@ -2449,7 +2467,7 @@
 			$colspan++;
 		}
 	}
-	print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
+	print '<tr><td colspan="' . $colspan . '"><span class="opacitymedium">' . $langs->trans("NoRecordFound") . '</span></td></tr>';
 }
 
 $db->free($resql);
@@ -2458,10 +2476,10 @@
 $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
 print $hookmanager->resPrint;
 
-print '</table>'."\n";
-print '</div>'."\n";
+print '</table>' . "\n";
+print '</div>' . "\n";
 
-print '</form>'."\n";
+print '</form>' . "\n";
 
 if (in_array('builddoc', array_keys($arrayofmassactions)) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
 	$hidegeneratedfilelistifempty = 1;
@@ -2469,11 +2487,11 @@
 		$hidegeneratedfilelistifempty = 0;
 	}
 
-	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
 	$formfile = new FormFile($db);
 
 	// Show list of available documents
-	$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
+	$urlsource = $_SERVER['PHP_SELF'] . '?sortfield=' . $sortfield . '&sortorder=' . $sortorder;
 	$urlsource .= str_replace('&amp;', '&', $param);
 
 	$filedir = $diroutputmassaction;

########## commande/list.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/commande/list.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/commande/list.php	2025-05-02 11:52:46.627672000 +0000
@@ -41,19 +41,19 @@
 
 // Load Dolibarr environment
 require '../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
 if (isModEnabled('margin')) {
-	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
 }
-require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
-require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
-require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
+require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
+require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
 
 /**
  * @var Conf $conf
@@ -151,7 +151,7 @@
 
 $search_import_key  = trim(GETPOST("search_import_key", "alpha"));
 
-$diroutputmassaction = $conf->commande->multidir_output[$conf->entity].'/temp/massgeneration/'.$user->id;
+$diroutputmassaction = $conf->commande->multidir_output[$conf->entity] . '/temp/massgeneration/' . $user->id;
 
 // Load variable for pagination
 $limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
@@ -216,7 +216,7 @@
 	'typent.code' => array('label' => "ThirdPartyType", 'checked' => $checkedtypetiers, 'position' => 55),
 	'c.date_commande' => array('label' => "OrderDateShort", 'checked' => 1, 'position' => 60, 'csslist' => 'nowraponall'),
 	'c.date_delivery' => array('label' => "DateDeliveryPlanned", 'checked' => 1, 'enabled' => !getDolGlobalString('ORDER_DISABLE_DELIVERY_DATE'), 'position' => 65, 'csslist' => 'nowraponall'),
-	'c.fk_shipping_method' => array('label' => "SendingMethod", 'checked' => -1, 'position' => 66 , 'enabled' => isModEnabled("shipping")),
+	'c.fk_shipping_method' => array('label' => "SendingMethod", 'checked' => -1, 'position' => 66, 'enabled' => isModEnabled("shipping")),
 	'c.fk_cond_reglement' => array('label' => "PaymentConditionsShort", 'checked' => -1, 'position' => 67),
 	'c.fk_mode_reglement' => array('label' => "PaymentMode", 'checked' => -1, 'position' => 68),
 	'c.fk_input_reason' => array('label' => "Origin", 'checked' => -1, 'position' => 69),
@@ -239,7 +239,7 @@
 	'c.date_cloture' => array('label' => "DateClosing", 'checked' => 0, 'position' => 130),
 	'c.note_public' => array('label' => 'NotePublic', 'checked' => 0, 'enabled' => (!getDolGlobalInt('MAIN_LIST_HIDE_PUBLIC_NOTES')), 'position' => 135, 'searchall' => 1),
 	'c.note_private' => array('label' => 'NotePrivate', 'checked' => 0, 'enabled' => (!getDolGlobalInt('MAIN_LIST_HIDE_PRIVATE_NOTES')), 'position' => 140),
-	'shippable' => array('label' => "Shippable", 'checked' => 1,'enabled' => (isModEnabled("shipping")), 'position' => 990),
+	'shippable' => array('label' => "Shippable", 'checked' => 1, 'enabled' => (isModEnabled("shipping")), 'position' => 990),
 	'c.facture' => array('label' => "Billed", 'checked' => 1, 'enabled' => (!getDolGlobalString('WORKFLOW_BILL_ON_SHIPMENT')), 'position' => 995),
 	'c.import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 999),
 	'c.fk_statut' => array('label' => "Status", 'checked' => 1, 'position' => 1000)
@@ -254,7 +254,7 @@
 }
 
 // Extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';
 
 $object->fields = dol_sort_array($object->fields, 'position');
 //$arrayfields['anotherfield'] = array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>1, 'enabled'=>1, 'position'=>90, 'csslist'=>'right');
@@ -302,7 +302,7 @@
 
 if (empty($reshook)) {
 	// Selection of new fields
-	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+	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
@@ -354,8 +354,10 @@
 		$toselect = array();
 		$search_array_options = array();
 	}
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
-		|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
+	if (
+		GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
+		|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')
+	) {
 		$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
 	}
 
@@ -380,7 +382,7 @@
 	$triggersendname = 'ORDER_SENTBYMAIL';
 	$year = "";
 	$month = "";
-	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
+	include DOL_DOCUMENT_ROOT . '/core/actions_massactions.inc.php';
 
 	if ($massaction == 'confirm_createbills') {   // Create bills from orders.
 		$orders = GETPOST('toselect', 'array');
@@ -455,7 +457,7 @@
 					$TFactThirdNbLines[$cmd->socid] = 0; //init nblines to have lines ordered by expedition and rang
 				} else {
 					$langs->load("errors");
-					$errors[] = $cmd->ref.' : '.$langs->trans($objecttmp->errors[0]);
+					$errors[] = $cmd->ref . ' : ' . $langs->trans($objecttmp->errors[0]);
 					$error++;
 				}
 			}
@@ -464,7 +466,7 @@
 				$res = $objecttmp->add_object_linked($objecttmp->origin, $id_order);
 
 				if ($res == 0) {
-					$errors[] = $cmd->ref.' : '.$langs->trans($objecttmp->errors[0]);
+					$errors[] = $cmd->ref . ' : ' . $langs->trans($objecttmp->errors[0]);
 					$error++;
 				}
 
@@ -483,7 +485,7 @@
 						$desc = ($lines[$i]->desc ? $lines[$i]->desc : '');
 						// If we build one invoice for several orders, we must put the ref of order on the invoice line
 						if (!empty($createbills_onebythird)) {
-							$desc = dol_concatdesc($desc, $langs->trans("Order").' '.$cmd->ref.' - '.dol_print_date($cmd->date, 'day'));
+							$desc = dol_concatdesc($desc, $langs->trans("Order") . ' ' . $cmd->ref . ' - ' . dol_print_date($cmd->date, 'day'));
 						}
 
 						if ($lines[$i]->subprice < 0 && !getDolGlobalString('INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN')) {
@@ -599,7 +601,7 @@
 			}
 
 			if ($currentIndex <= (getDolGlobalInt("MAXREFONDOC") ? getDolGlobalInt("MAXREFONDOC") : 10)) {
-				$objecttmp->note_public = dol_concatdesc($objecttmp->note_public, $langs->transnoentities($cmd->ref).(empty($cmd->ref_client) ? '' : ' ('.$cmd->ref_client.')'));
+				$objecttmp->note_public = dol_concatdesc($objecttmp->note_public, $langs->transnoentities($cmd->ref) . (empty($cmd->ref_client) ? '' : ' (' . $cmd->ref_client . ')'));
 				$objecttmp->update($user);
 			}
 
@@ -637,7 +639,7 @@
 				// Call action to build doc
 				$savobject = $object;
 				$object = $objecttmp;
-				include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
+				include DOL_DOCUMENT_ROOT . '/core/actions_builddoc.inc.php';
 				$object = $savobject;
 			}
 
@@ -650,16 +652,16 @@
 			if ($nb_bills_created == 1) {
 				if (getDolGlobalInt('MAIN_MASSACTION_CREATEBILLS_REDIRECT_IF_ONE') == 1) {
 					// Redirect to generated invoice if unique
-					header('Location: '.DOL_URL_ROOT.'/compta/facture/card.php?id='.urlencode((string) $lastid));
+					header('Location: ' . DOL_URL_ROOT . '/compta/facture/card.php?id=' . urlencode((string) $lastid));
 					exit;
 				}
 				$texttoshow = $langs->trans('BillXCreated', '{s1}');
-				$texttoshow = str_replace('{s1}', '<a href="'.DOL_URL_ROOT.'/compta/facture/card.php?id='.urlencode((string) ($lastid)).'">'.$lastref.'</a>', $texttoshow);
+				$texttoshow = str_replace('{s1}', '<a href="' . DOL_URL_ROOT . '/compta/facture/card.php?id=' . urlencode((string) ($lastid)) . '">' . $lastref . '</a>', $texttoshow);
 				setEventMessages($texttoshow, null, 'mesgs');
 			} else {
 				if (getDolGlobalInt('MAIN_MASSACTION_CREATEBILLS_REDIRECT_IF_MANY') == 1) {
 					// Redirect to invoice list
-					header("Location: ".DOL_URL_ROOT.'/compta/facture/list.php?mainmenu=billing&leftmenu=customers_bills');
+					header("Location: " . DOL_URL_ROOT . '/compta/facture/list.php?mainmenu=billing&leftmenu=customers_bills');
 					exit;
 				}
 				setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
@@ -668,88 +670,88 @@
 			// Make a redirect to avoid to bill twice if we make a refresh or back
 			$param = '';
 			if (!empty($mode)) {
-				$param .= '&mode='.urlencode($mode);
+				$param .= '&mode=' . urlencode($mode);
 			}
 			if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
-				$param .= '&contextpage='.urlencode($contextpage);
+				$param .= '&contextpage=' . urlencode($contextpage);
 			}
 			if ($limit > 0 && $limit != $conf->liste_limit) {
-				$param .= '&limit='.((int) $limit);
+				$param .= '&limit=' . ((int) $limit);
 			}
 			if ($optioncss != '') {
-				$param .= '&optioncss='.urlencode($optioncss);
+				$param .= '&optioncss=' . urlencode($optioncss);
 			}
 			if ($search_all) {
-				$param .= '&search_all='.urlencode($search_all);
+				$param .= '&search_all=' . urlencode($search_all);
 			}
 			if ($show_files) {
-				$param .= '&show_files='.urlencode((string) ($show_files));
+				$param .= '&show_files=' . urlencode((string) ($show_files));
 			}
 			if ($socid > 0) {
-				$param .= '&socid='.urlencode((string) ($socid));
+				$param .= '&socid=' . urlencode((string) ($socid));
 			}
 			if ($search_status != '') {
-				$param .= '&search_status='.urlencode($search_status);
+				$param .= '&search_status=' . urlencode($search_status);
 			}
 			if ($search_option) {
-				$param .= "&search_option=".urlencode($search_option);
+				$param .= "&search_option=" . urlencode($search_option);
 			}
 			if ($search_orderday) {
-				$param .= '&search_orderday='.urlencode($search_orderday);
+				$param .= '&search_orderday=' . urlencode($search_orderday);
 			}
 			if ($search_ordermonth) {
-				$param .= '&search_ordermonth='.urlencode($search_ordermonth);
+				$param .= '&search_ordermonth=' . urlencode($search_ordermonth);
 			}
 			if ($search_orderyear) {
-				$param .= '&search_orderyear='.urlencode($search_orderyear);
+				$param .= '&search_orderyear=' . urlencode($search_orderyear);
 			}
 			if ($search_deliveryday) {
-				$param .= '&search_deliveryday='.urlencode($search_deliveryday);
+				$param .= '&search_deliveryday=' . urlencode($search_deliveryday);
 			}
 			if ($search_deliverymonth) {
-				$param .= '&search_deliverymonth='.urlencode($search_deliverymonth);
+				$param .= '&search_deliverymonth=' . urlencode($search_deliverymonth);
 			}
 			if ($search_deliveryyear) {
-				$param .= '&search_deliveryyear='.urlencode($search_deliveryyear);
+				$param .= '&search_deliveryyear=' . urlencode($search_deliveryyear);
 			}
 			if ($search_id) {
-				$param .= '&search_id='.urlencode((string) $search_id);
+				$param .= '&search_id=' . urlencode((string) $search_id);
 			}
 			if ($search_ref) {
-				$param .= '&search_ref='.urlencode($search_ref);
+				$param .= '&search_ref=' . urlencode($search_ref);
 			}
 			if ($search_ref_ext) {
-				$param .= '&search_ref_ext='.urlencode($search_ref_ext);
+				$param .= '&search_ref_ext=' . urlencode($search_ref_ext);
 			}
 			if ($search_company) {
-				$param .= '&search_company='.urlencode($search_company);
+				$param .= '&search_company=' . urlencode($search_company);
 			}
 			if ($search_ref_customer) {
-				$param .= '&search_ref_customer='.urlencode($search_ref_customer);
+				$param .= '&search_ref_customer=' . urlencode($search_ref_customer);
 			}
 			if ($search_user > 0) {
-				$param .= '&search_user='.urlencode((string) ($search_user));
+				$param .= '&search_user=' . urlencode((string) ($search_user));
 			}
 			if ($search_sale > 0) {
-				$param .= '&search_sale='.urlencode((string) ($search_sale));
+				$param .= '&search_sale=' . urlencode((string) ($search_sale));
 			}
 			if ($search_total_ht != '') {
-				$param .= '&search_total_ht='.urlencode($search_total_ht);
+				$param .= '&search_total_ht=' . urlencode($search_total_ht);
 			}
 			if ($search_total_vat != '') {
-				$param .= '&search_total_vat='.urlencode($search_total_vat);
+				$param .= '&search_total_vat=' . urlencode($search_total_vat);
 			}
 			if ($search_total_ttc != '') {
-				$param .= '&search_total_ttc='.urlencode($search_total_ttc);
+				$param .= '&search_total_ttc=' . urlencode($search_total_ttc);
 			}
 			if ($search_project_ref >= 0) {
-				$param .= "&search_project_ref=".urlencode($search_project_ref);
+				$param .= "&search_project_ref=" . urlencode($search_project_ref);
 			}
 			if ($search_billed != '') {
-				$param .= '&search_billed='.urlencode($search_billed);
+				$param .= '&search_billed=' . urlencode($search_billed);
 			}
 
-			header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
+			header("Location: " . $_SERVER['PHP_SELF'] . '?' . $param);
 			exit;
 		} else {
 			$db->rollback();
@@ -919,7 +921,7 @@
 // Add fields from extrafields
 if (!empty($extrafields->attributes[$object->table_element]['label'])) {
 	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
-		$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : '');
+		$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef." . $key . " as options_" . $key : '');
 	}
 }
 
@@ -931,35 +933,35 @@
 
 $sqlfields = $sql; // $sql fields to remove for count total
 
-$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s2 ON s2.rowid = s.parent";
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
-$sql .= ', '.MAIN_DB_PREFIX.'commande as c';
+$sql .= ' FROM ' . MAIN_DB_PREFIX . 'societe as s';
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s2 ON s2.rowid = s.parent";
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as country on (country.rowid = s.fk_pays)";
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_typent as typent on (typent.id = s.fk_typent)";
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_departements as state on (state.rowid = s.fk_departement)";
+$sql .= ', ' . MAIN_DB_PREFIX . 'commande as c';
 if (!empty($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
-	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)";
+	$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "commande_extrafields as ef on (c.rowid = ef.fk_object)";
 }
 if ($search_all) {
-	$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid = pd.fk_commande';
+	$sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'commandedet as pd ON c.rowid = pd.fk_commande';
 }
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = c.fk_projet";
-$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON c.fk_user_author = u.rowid';
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "projet as p ON p.rowid = c.fk_projet";
+$sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'user as u ON c.fk_user_author = u.rowid';
 // Add table from hooks
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
 $sql .= $hookmanager->resPrint;
 
 $sql .= ' WHERE c.fk_soc = s.rowid';
-$sql .= ' AND c.entity IN ('.getEntity('commande').')';
+$sql .= ' AND c.entity IN (' . getEntity('commande') . ')';
 if ($socid > 0) {
-	$sql .= ' AND s.rowid = '.((int) $socid);
+	$sql .= ' AND s.rowid = ' . ((int) $socid);
 }
 // Restriction on sale representative
 if (empty($user->socid) && !$permissiontoreadallthirdparty) {
-	$sql .= " AND (EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user = ".((int) $user->id).")";
+	$sql .= " AND (EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user = " . ((int) $user->id) . ")";
 	if (getDolGlobalInt('MAIN_SEE_SUBORDINATES') && $userschilds) {
-		$sql .= " OR EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user IN (".$db->sanitize(implode(',', $userschilds))."))";
+		$sql .= " OR EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user IN (" . $db->sanitize(implode(',', $userschilds)) . "))";
 	}
 	$sql .= ")";
 }
@@ -980,14 +982,14 @@
 	$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
 }
 if ($search_billed != '' && $search_billed >= 0) {
-	$sql .= ' AND c.facture = '.((int) $search_billed);
+	$sql .= ' AND c.facture = ' . ((int) $search_billed);
 }
 if ($search_status != '') {
 	if ($search_status <= 3 && $search_status >= -1) {	// status from -1 to 3 are real status (other are virtual combination)
 		if ($search_status == 1 && !isModEnabled('shipping')) {
 			$sql .= ' AND c.fk_statut IN (1,2)'; // If module expedition disabled, we include order with status "sent" into "validated"
 		} else {
-			$sql .= ' AND c.fk_statut = '.((int) $search_status); // draft, validated, in process or canceled
+			$sql .= ' AND c.fk_statut = ' . ((int) $search_status); // draft, validated, in process or canceled
 		}
 	}
 	if ($search_status == -2) {	// "validated + in progress"
@@ -1001,25 +1003,25 @@
 	}
 }
 if ($search_option == 'late') {
-	$sql .= " AND c.date_commande < '".$db->idate(dol_now() - $conf->commande->client->warning_delay)."'";
+	$sql .= " AND c.date_commande < '" . $db->idate(dol_now() - $conf->commande->client->warning_delay) . "'";
 }
 if ($search_datecloture_start) {
-	$sql .= " AND c.date_cloture >= '".$db->idate($search_datecloture_start)."'";
+	$sql .= " AND c.date_cloture >= '" . $db->idate($search_datecloture_start) . "'";
 }
 if ($search_datecloture_end) {
-	$sql .= " AND c.date_cloture <= '".$db->idate($search_datecloture_end)."'";
+	$sql .= " AND c.date_cloture <= '" . $db->idate($search_datecloture_end) . "'";
 }
 if ($search_dateorder_start) {
-	$sql .= " AND c.date_commande >= '".$db->idate($search_dateorder_start)."'";
+	$sql .= " AND c.date_commande >= '" . $db->idate($search_dateorder_start) . "'";
 }
 if ($search_dateorder_end) {
-	$sql .= " AND c.date_commande <= '".$db->idate($search_dateorder_end)."'";
+	$sql .= " AND c.date_commande <= '" . $db->idate($search_dateorder_end) . "'";
 }
 if ($search_datedelivery_start) {
-	$sql .= " AND c.date_livraison >= '".$db->idate($search_datedelivery_start)."'";
+	$sql .= " AND c.date_livraison >= '" . $db->idate($search_datedelivery_start) . "'";
 }
 if ($search_datedelivery_end) {
-	$sql .= " AND c.date_livraison <= '".$db->idate($search_datedelivery_end)."'";
+	$sql .= " AND c.date_livraison <= '" . $db->idate($search_datedelivery_end) . "'";
 }
 if ($search_town) {
 	$sql .= natural_search('s.town', $search_town);
@@ -1031,10 +1033,10 @@
 	$sql .= natural_search("state.nom", $search_state);
 }
 if ($search_country) {
-	$sql .= " AND s.fk_pays IN (".$db->sanitize($search_country).')';
+	$sql .= " AND s.fk_pays IN (" . $db->sanitize($search_country) . ')';
 }
 if ($search_type_thirdparty && $search_type_thirdparty != '-1') {
-	$sql .= " AND s.fk_typent IN (".$db->sanitize($search_type_thirdparty).')';
+	$sql .= " AND s.fk_typent IN (" . $db->sanitize($search_type_thirdparty) . ')';
 }
 if (empty($arrayfields['s.name_alias']['checked']) && $search_company) {
 	$sql .= natural_search(array("s.nom", "s.name_alias"), $search_company);
@@ -1062,7 +1064,7 @@
 	$sql .= natural_search('c.fk_warehouse', $search_warehouse, 1);
 }
 if ($search_multicurrency_code != '') {
-	$sql .= " AND c.multicurrency_code = '".$db->escape($search_multicurrency_code)."'";
+	$sql .= " AND c.multicurrency_code = '" . $db->escape($search_multicurrency_code) . "'";
 }
 if ($search_multicurrency_tx != '') {
 	$sql .= natural_search('c.multicurrency_tx', $search_multicurrency_tx, 1);
@@ -1086,16 +1088,16 @@
 	$sql .= natural_search("p.title", $search_project);
 }
 if ($search_fk_cond_reglement > 0) {
-	$sql .= " AND c.fk_cond_reglement = ".((int) $search_fk_cond_reglement);
+	$sql .= " AND c.fk_cond_reglement = " . ((int) $search_fk_cond_reglement);
 }
 if ($search_fk_shipping_method > 0) {
-	$sql .= " AND c.fk_shipping_method = ".((int) $search_fk_shipping_method);
+	$sql .= " AND c.fk_shipping_method = " . ((int) $search_fk_shipping_method);
 }
 if ($search_fk_mode_reglement > 0) {
-	$sql .= " AND c.fk_mode_reglement = ".((int) $search_fk_mode_reglement);
+	$sql .= " AND c.fk_mode_reglement = " . ((int) $search_fk_mode_reglement);
 }
 if ($search_fk_input_reason > 0) {
-	$sql .= " AND c.fk_input_reason = ".((int) $search_fk_input_reason);
+	$sql .= " AND c.fk_input_reason = " . ((int) $search_fk_input_reason);
 }
 if ($search_import_key) {
 	$sql .= natural_search("s.import_key", $search_import_key);
@@ -1104,17 +1106,17 @@
 if ($search_user > 0) {
 	$sql .= " AND EXISTS (";
 	$sql .= " SELECT ec.fk_c_type_contact, ec.element_id, ec.fk_socpeople";
-	$sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec";
-	$sql .= " INNER JOIN  ".MAIN_DB_PREFIX."c_type_contact as tc";
+	$sql .= " FROM " . MAIN_DB_PREFIX . "element_contact as ec";
+	$sql .= " INNER JOIN  " . MAIN_DB_PREFIX . "c_type_contact as tc";
 	$sql .= " ON ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal'";
-	$sql .= " WHERE ec.element_id = c.rowid AND ec.fk_socpeople = ".((int) $search_user).")";
+	$sql .= " WHERE ec.element_id = c.rowid AND ec.fk_socpeople = " . ((int) $search_user) . ")";
 }
 // Search on sale representative
 if ($search_sale && $search_sale != '-1') {
 	if ($search_sale == -2) {
-		$sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc)";
+		$sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc)";
 	} elseif ($search_sale > 0) {
-		$sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
+		$sql .= " AND EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user = " . ((int) $search_sale) . ")";
 	}
 }
 // Search for tag/category ($searchCategoryCustomerList is an array of ID)
@@ -1125,25 +1127,25 @@
 	$listofcategoryid = '';
 	foreach ($searchCategoryCustomerList as $searchCategoryCustomer) {
 		if (intval($searchCategoryCustomer) == -2) {
-			$searchCategoryCustomerSqlList[] = "NOT EXISTS (SELECT cs.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as cs WHERE s.rowid = cs.fk_soc)";
+			$searchCategoryCustomerSqlList[] = "NOT EXISTS (SELECT cs.fk_soc FROM " . MAIN_DB_PREFIX . "categorie_societe as cs WHERE s.rowid = cs.fk_soc)";
 		} elseif (intval($searchCategoryCustomer) > 0) {
 			if ($searchCategoryCustomerOperator == 0) {
-				$searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie = ".((int) $searchCategoryCustomer).")";
+				$searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM " . MAIN_DB_PREFIX . "categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie = " . ((int) $searchCategoryCustomer) . ")";
 			} else {
-				$listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryCustomer);
+				$listofcategoryid .= ($listofcategoryid ? ', ' : '') . ((int) $searchCategoryCustomer);
 			}
 		}
 	}
 	if ($listofcategoryid) {
-		$searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie IN (".$db->sanitize($listofcategoryid)."))";
+		$searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM " . MAIN_DB_PREFIX . "categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie IN (" . $db->sanitize($listofcategoryid) . "))";
 	}
 	if ($searchCategoryCustomerOperator == 1) {
 		if (!empty($searchCategoryCustomerSqlList)) {
-			$sql .= " AND (".implode(' OR ', $searchCategoryCustomerSqlList).")";
+			$sql .= " AND (" . implode(' OR ', $searchCategoryCustomerSqlList) . ")";
 		}
 	} else {
 		if (!empty($searchCategoryCustomerSqlList)) {
-			$sql .= " AND (".implode(' AND ', $searchCategoryCustomerSqlList).")";
+			$sql .= " AND (" . implode(' AND ', $searchCategoryCustomerSqlList) . ")";
 		}
 	}
 }
@@ -1155,30 +1157,30 @@
 	$listofcategoryid = '';
 	foreach ($searchCategoryProductList as $searchCategoryProduct) {
 		if (intval($searchCategoryProduct) == -2) {
-			$searchCategoryProductSqlList[] = "NOT EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."commandedet as cd WHERE cd.fk_commande = c.rowid AND cd.fk_product = ck.fk_product)";
+			$searchCategoryProductSqlList[] = "NOT EXISTS (SELECT ck.fk_product FROM " . MAIN_DB_PREFIX . "categorie_product as ck, " . MAIN_DB_PREFIX . "commandedet as cd WHERE cd.fk_commande = c.rowid AND cd.fk_product = ck.fk_product)";
 		} elseif (intval($searchCategoryProduct) > 0) {
 			if ($searchCategoryProductOperator == 0) {
-				$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."commandedet as cd WHERE cd.fk_commande = c.rowid AND cd.fk_product = ck.fk_product AND ck.fk_categorie = ".((int) $searchCategoryProduct).")";
+				$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM " . MAIN_DB_PREFIX . "categorie_product as ck, " . MAIN_DB_PREFIX . "commandedet as cd WHERE cd.fk_commande = c.rowid AND cd.fk_product = ck.fk_product AND ck.fk_categorie = " . ((int) $searchCategoryProduct) . ")";
 			} else {
-				$listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryProduct);
+				$listofcategoryid .= ($listofcategoryid ? ', ' : '') . ((int) $searchCategoryProduct);
 			}
 		}
 	}
 	if ($listofcategoryid) {
-		$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."commandedet as cd WHERE cd.fk_commande = c.rowid AND cd.fk_product = ck.fk_product AND ck.fk_categorie IN (".$db->sanitize($listofcategoryid)."))";
+		$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM " . MAIN_DB_PREFIX . "categorie_product as ck, " . MAIN_DB_PREFIX . "commandedet as cd WHERE cd.fk_commande = c.rowid AND cd.fk_product = ck.fk_product AND ck.fk_categorie IN (" . $db->sanitize($listofcategoryid) . "))";
 	}
 	if ($searchCategoryProductOperator == 1) {
 		if (!empty($searchCategoryProductSqlList)) {
-			$sql .= " AND (".implode(' OR ', $searchCategoryProductSqlList).")";
+			$sql .= " AND (" . implode(' OR ', $searchCategoryProductSqlList) . ")";
 		}
 	} else {
 		if (!empty($searchCategoryProductSqlList)) {
-			$sql .= " AND (".implode(' AND ', $searchCategoryProductSqlList).")";
+			$sql .= " AND (" . implode(' AND ', $searchCategoryProductSqlList) . ")";
 		}
 	}
 }
 // Add where from extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_sql.tpl.php';
 // Add where from hooks
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
@@ -1187,20 +1189,43 @@
 // Add HAVING from hooks
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-$sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 ".$hookmanager->resPrint;
+$sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 " . $hookmanager->resPrint;
 //print $sql;
 
 // Count total nb of records
 $nbtotalofrecords = '';
 if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
 	/* The fast and low memory method to get and count full list converts the sql into a sql count */
-	$sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
-	$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
+	$parameters = array(
+		'sqlforcount' => $sql,
+		'sqlfields' => $sqlfields,
+		'context' => $parameters['context']
+	);
+
+	$reshook = $hookmanager->executeHooks('beforeCountQuery', $parameters, $object, $action);
+
+
+	if ($reshook > 0 && !empty($hookmanager->resPrint)) {
+		$sqlforcount = $hookmanager->resPrint;
+	} else {
+		$sqlforcount = preg_replace('/^' . preg_quote($sqlfields, '/') . '/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
+		$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
+	}
+
 	$resql = $db->query($sqlforcount);
 	if ($resql) {
 		$objforcount = $db->fetch_object($resql);
 		$nbtotalofrecords = $objforcount->nbtotalofrecords;
+
+		$_GET['total_ht'] = $objforcount->total_ht ?? 0;
+		$_GET['total_tva'] = $objforcount->total_tva ?? 0;
+		$_GET['total_ttc'] = $objforcount->total_ttc ?? 0;
+
+		$total_ht1 = GETPOST('total_ht', 'alpha') ?: 0;
+		$total_tva2 = GETPOST('total_tva', 'alpha') ?: 0;
+		$total_ttc3 = GETPOST('total_ttc', 'alpha') ?: 0;
 	} else {
+		error_log("Erreur lors de l'exécution de SQLforcount", 1, "valentin.grimal@pichinov.com");
 		dol_print_error($db);
 	}
 
@@ -1226,7 +1251,7 @@
 if ($socid > 0) {
 	$soc = new Societe($db);
 	$soc->fetch($socid);
-	$title = $langs->trans('CustomersOrders').' - '.$soc->name;
+	$title = $langs->trans('CustomersOrders') . ' - ' . $soc->name;
 	if (empty($search_company)) {
 		$search_company = $soc->name;
 	}
@@ -1234,28 +1259,28 @@
 	$title = $langs->trans('CustomersOrders');
 }
 if (strval($search_status) == '0') {
-	$title .= ' - '.$langs->trans('StatusOrderDraftShort');
+	$title .= ' - ' . $langs->trans('StatusOrderDraftShort');
 }
 if ($search_status == 1) {
-	$title .= ' - '.$langs->trans('StatusOrderValidatedShort');
+	$title .= ' - ' . $langs->trans('StatusOrderValidatedShort');
 }
 if ($search_status == 2) {
-	$title .= ' - '.$langs->trans('StatusOrderSentShort');
+	$title .= ' - ' . $langs->trans('StatusOrderSentShort');
 }
 if ($search_status == 3) {
-	$title .= ' - '.$langs->trans('StatusOrderToBillShort');
+	$title .= ' - ' . $langs->trans('StatusOrderToBillShort');
 }
 if ($search_status == -1) {
-	$title .= ' - '.$langs->trans('StatusOrderCanceledShort');
+	$title .= ' - ' . $langs->trans('StatusOrderCanceledShort');
 }
 if ($search_status == -2) {
-	$title .= ' - '.$langs->trans('StatusOrderToProcessShort');
+	$title .= ' - ' . $langs->trans('StatusOrderToProcessShort');
 }
 if ($search_status == -3) {
-	$title .= ' - '.$langs->trans('StatusOrderValidated').', '.(!isModEnabled('shipping') ? '' : $langs->trans("StatusOrderSent").', ').$langs->trans('StatusOrderToBill');
+	$title .= ' - ' . $langs->trans('StatusOrderValidated') . ', ' . (!isModEnabled('shipping') ? '' : $langs->trans("StatusOrderSent") . ', ') . $langs->trans('StatusOrderToBill');
 }
 if ($search_status == -4) {
-	$title .= ' - '.$langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort");
+	$title .= ' - ' . $langs->trans("StatusOrderValidatedShort") . '+' . $langs->trans("StatusOrderSentShort");
 }
 
 $num = $db->num_rows($resql);
@@ -1265,7 +1290,7 @@
 if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all) {
 	$obj = $db->fetch_object($resql);
 	$id = $obj->rowid;
-	header("Location: ".DOL_URL_ROOT.'/commande/card.php?id='.$id);
+	header("Location: " . DOL_URL_ROOT . '/commande/card.php?id=' . $id);
 	exit;
 }
 
@@ -1278,152 +1303,152 @@
 
 $param = '';
 if (!empty($mode)) {
-	$param .= '&mode='.urlencode($mode);
+	$param .= '&mode=' . urlencode($mode);
 }
 if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
-	$param .= '&contextpage='.urlencode($contextpage);
+	$param .= '&contextpage=' . urlencode($contextpage);
 }
 if ($limit > 0 && $limit != $conf->liste_limit) {
-	$param .= '&limit='.((int) $limit);
+	$param .= '&limit=' . ((int) $limit);
 }
 if ($optioncss != '') {
-	$param .= '&optioncss='.urlencode($optioncss);
+	$param .= '&optioncss=' . urlencode($optioncss);
 }
 if ($show_files) {
-	$param .= '&show_files='.urlencode((string) ($show_files));
+	$param .= '&show_files=' . urlencode((string) ($show_files));
 }
 if ($search_all) {
-	$param .= '&search_all='.urlencode($search_all);
+	$param .= '&search_all=' . urlencode($search_all);
 }
 if ($socid > 0) {
-	$param .= '&socid='.((int) $socid);
+	$param .= '&socid=' . ((int) $socid);
 }
 if ($search_status != '') {
-	$param .= '&search_status='.urlencode($search_status);
+	$param .= '&search_status=' . urlencode($search_status);
 }
 if ($search_option) {
-	$param .= "&search_option=".urlencode($search_option);
+	$param .= "&search_option=" . urlencode($search_option);
 }
 if ($search_datecloture_start) {
-	$param .= '&search_datecloture_startday='.dol_print_date($search_datecloture_start, '%d').'&search_datecloture_startmonth='.dol_print_date($search_datecloture_start, '%m').'&search_datecloture_startyear='.dol_print_date($search_datecloture_start, '%Y');
+	$param .= '&search_datecloture_startday=' . dol_print_date($search_datecloture_start, '%d') . '&search_datecloture_startmonth=' . dol_print_date($search_datecloture_start, '%m') . '&search_datecloture_startyear=' . dol_print_date($search_datecloture_start, '%Y');
 }
 if ($search_datecloture_end) {
-	$param .= '&search_datecloture_endday='.dol_print_date($search_datecloture_end, '%d').'&search_datecloture_endmonth='.dol_print_date($search_datecloture_end, '%m').'&search_datecloture_endyear='.dol_print_date($search_datecloture_end, '%Y');
+	$param .= '&search_datecloture_endday=' . dol_print_date($search_datecloture_end, '%d') . '&search_datecloture_endmonth=' . dol_print_date($search_datecloture_end, '%m') . '&search_datecloture_endyear=' . dol_print_date($search_datecloture_end, '%Y');
 }
 if ($search_dateorder_start) {
-	$param .= '&search_dateorder_start_day='.dol_print_date($search_dateorder_start, '%d').'&search_dateorder_start_month='.dol_print_date($search_dateorder_start, '%m').'&search_dateorder_start_year='.dol_print_date($search_dateorder_start, '%Y');
+	$param .= '&search_dateorder_start_day=' . dol_print_date($search_dateorder_start, '%d') . '&search_dateorder_start_month=' . dol_print_date($search_dateorder_start, '%m') . '&search_dateorder_start_year=' . dol_print_date($search_dateorder_start, '%Y');
 }
 if ($search_dateorder_end) {
-	$param .= '&search_dateorder_end_day='.dol_print_date($search_dateorder_end, '%d').'&search_dateorder_end_month='.dol_print_date($search_dateorder_end, '%m').'&search_dateorder_end_year='.dol_print_date($search_dateorder_end, '%Y');
+	$param .= '&search_dateorder_end_day=' . dol_print_date($search_dateorder_end, '%d') . '&search_dateorder_end_month=' . dol_print_date($search_dateorder_end, '%m') . '&search_dateorder_end_year=' . dol_print_date($search_dateorder_end, '%Y');
 }
 if ($search_datedelivery_start) {
-	$param .= '&search_datedelivery_start_day='.dol_print_date($search_datedelivery_start, '%d').'&search_datedelivery_start_month='.dol_print_date($search_datedelivery_start, '%m').'&search_datedelivery_start_year='.dol_print_date($search_datedelivery_start, '%Y');
+	$param .= '&search_datedelivery_start_day=' . dol_print_date($search_datedelivery_start, '%d') . '&search_datedelivery_start_month=' . dol_print_date($search_datedelivery_start, '%m') . '&search_datedelivery_start_year=' . dol_print_date($search_datedelivery_start, '%Y');
 }
 if ($search_datedelivery_end) {
-	$param .= '&search_datedelivery_end_day='.dol_print_date($search_datedelivery_end, '%d').'&search_datedelivery_end_month='.dol_print_date($search_datedelivery_end, '%m').'&search_datedelivery_end_year='.dol_print_date($search_datedelivery_end, '%Y');
+	$param .= '&search_datedelivery_end_day=' . dol_print_date($search_datedelivery_end, '%d') . '&search_datedelivery_end_month=' . dol_print_date($search_datedelivery_end, '%m') . '&search_datedelivery_end_year=' . dol_print_date($search_datedelivery_end, '%Y');
 }
 if ($search_id) {
-	$param .= '&search_id='.urlencode((string) $search_id);
+	$param .= '&search_id=' . urlencode((string) $search_id);
 }
 if ($search_ref) {
-	$param .= '&search_ref='.urlencode($search_ref);
+	$param .= '&search_ref=' . urlencode($search_ref);
 }
 if ($search_ref_ext) {
-	$param .= '&search_ref_ext='.urlencode($search_ref_ext);
+	$param .= '&search_ref_ext=' . urlencode($search_ref_ext);
 }
 if ($search_company) {
-	$param .= '&search_company='.urlencode($search_company);
+	$param .= '&search_company=' . urlencode($search_company);
 }
 if ($search_company_alias) {
-	$param .= '&search_company_alias='.urlencode($search_company_alias);
+	$param .= '&search_company_alias=' . urlencode($search_company_alias);
 }
 if ($search_parent_name != '') {
-	$param .= '&search_parent_name='.urlencode($search_parent_name);
+	$param .= '&search_parent_name=' . urlencode($search_parent_name);
 }
 if ($search_ref_customer) {
-	$param .= '&search_ref_customer='.urlencode($search_ref_customer);
+	$param .= '&search_ref_customer=' . urlencode($search_ref_customer);
 }
 if ($search_user > 0) {
-	$param .= '&search_user='.urlencode((string) ($search_user));
+	$param .= '&search_user=' . urlencode((string) ($search_user));
 }
 if ($search_sale > 0) {
-	$param .= '&search_sale='.urlencode((string) ($search_sale));
+	$param .= '&search_sale=' . urlencode((string) ($search_sale));
 }
 if ($search_total_ht != '') {
-	$param .= '&search_total_ht='.urlencode($search_total_ht);
+	$param .= '&search_total_ht=' . urlencode($search_total_ht);
 }
 if ($search_total_vat != '') {
-	$param .= '&search_total_vat='.urlencode($search_total_vat);
+	$param .= '&search_total_vat=' . urlencode($search_total_vat);
 }
 if ($search_total_ttc != '') {
-	$param .= '&search_total_ttc='.urlencode($search_total_ttc);
+	$param .= '&search_total_ttc=' . urlencode($search_total_ttc);
 }
 if ($search_warehouse != '') {
-	$param .= '&search_warehouse='.urlencode((string) ($search_warehouse));
+	$param .= '&search_warehouse=' . urlencode((string) ($search_warehouse));
 }
 if ($search_login) {
-	$param .= '&search_login='.urlencode($search_login);
+	$param .= '&search_login=' . urlencode($search_login);
 }
 if ($search_multicurrency_code != '') {
-	$param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code);
+	$param .= '&search_multicurrency_code=' . urlencode($search_multicurrency_code);
 }
 if ($search_multicurrency_tx != '') {
-	$param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx);
+	$param .= '&search_multicurrency_tx=' . urlencode($search_multicurrency_tx);
 }
 if ($search_multicurrency_montant_ht != '') {
-	$param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht);
+	$param .= '&search_multicurrency_montant_ht=' . urlencode($search_multicurrency_montant_ht);
 }
 if ($search_multicurrency_montant_vat != '') {
-	$param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat);
+	$param .= '&search_multicurrency_montant_vat=' . urlencode($search_multicurrency_montant_vat);
 }
 if ($search_multicurrency_montant_ttc != '') {
-	$param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc);
+	$param .= '&search_multicurrency_montant_ttc=' . urlencode($search_multicurrency_montant_ttc);
 }
 if ($search_project_ref >= 0) {
-	$param .= "&search_project_ref=".urlencode($search_project_ref);
+	$param .= "&search_project_ref=" . urlencode($search_project_ref);
 }
 if ($search_town != '') {
-	$param .= '&search_town='.urlencode($search_town);
+	$param .= '&search_town=' . urlencode($search_town);
 }
 if ($search_zip != '') {
-	$param .= '&search_zip='.urlencode($search_zip);
+	$param .= '&search_zip=' . urlencode($search_zip);
 }
 if ($search_state != '') {
-	$param .= '&search_state='.urlencode($search_state);
+	$param .= '&search_state=' . urlencode($search_state);
 }
 if ($search_country != '') {
-	$param .= '&search_country='.urlencode((string) ($search_country));
+	$param .= '&search_country=' . urlencode((string) ($search_country));
 }
 if ($search_type_thirdparty && $search_type_thirdparty != '-1') {
-	$param .= '&search_type_thirdparty='.urlencode((string) ($search_type_thirdparty));
+	$param .= '&search_type_thirdparty=' . urlencode((string) ($search_type_thirdparty));
 }
 if ($search_product_category != '') {
-	$param .= '&search_product_category='.urlencode((string) ($search_product_category));
+	$param .= '&search_product_category=' . urlencode((string) ($search_product_category));
 }
 if (($search_categ_cus > 0) || ($search_categ_cus == -2)) {
-	$param .= '&search_categ_cus='.urlencode((string) ($search_categ_cus));
+	$param .= '&search_categ_cus=' . urlencode((string) ($search_categ_cus));
 }
 if ($search_billed != '') {
-	$param .= '&search_billed='.urlencode($search_billed);
+	$param .= '&search_billed=' . urlencode($search_billed);
 }
 if ($search_fk_cond_reglement > 0) {
-	$param .= '&search_fk_cond_reglement='.urlencode((string) ($search_fk_cond_reglement));
+	$param .= '&search_fk_cond_reglement=' . urlencode((string) ($search_fk_cond_reglement));
 }
 if ($search_fk_shipping_method > 0) {
-	$param .= '&search_fk_shipping_method='.urlencode((string) ($search_fk_shipping_method));
+	$param .= '&search_fk_shipping_method=' . urlencode((string) ($search_fk_shipping_method));
 }
 if ($search_fk_mode_reglement > 0) {
-	$param .= '&search_fk_mode_reglement='.urlencode((string) ($search_fk_mode_reglement));
+	$param .= '&search_fk_mode_reglement=' . urlencode((string) ($search_fk_mode_reglement));
 }
 if ($search_fk_input_reason > 0) {
-	$param .= '&search_fk_input_reason='.urlencode((string) ($search_fk_input_reason));
+	$param .= '&search_fk_input_reason=' . urlencode((string) ($search_fk_input_reason));
 }
 if ($search_import_key != '') {
-	$param .= '&search_import_key='.urlencode($search_import_key);
+	$param .= '&search_import_key=' . urlencode($search_import_key);
 }
 
 // Add $param from extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_param.tpl.php';
 
 // Add $param from hooks
 $parameters = array();
@@ -1432,60 +1457,60 @@
 
 // List of mass actions available
 $arrayofmassactions = array(
-	'generate_doc' => img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
-	'builddoc' => img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
+	'generate_doc' => img_picto('', 'pdf', 'class="pictofixedwidth"') . $langs->trans("ReGeneratePDF"),
+	'builddoc' => img_picto('', 'pdf', 'class="pictofixedwidth"') . $langs->trans("PDFMerge"),
 );
 if ($permissiontovalidate) {
-	$arrayofmassactions['prevalidate'] = img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate");
+	$arrayofmassactions['prevalidate'] = img_picto('', 'check', 'class="pictofixedwidth"') . $langs->trans("Validate");
 }
 if ($permissiontoclose) {
-	$arrayofmassactions['preshipped'] = img_picto('', 'dolly', 'class="pictofixedwidth"').$langs->trans("ClassifyShipped");
+	$arrayofmassactions['preshipped'] = img_picto('', 'dolly', 'class="pictofixedwidth"') . $langs->trans("ClassifyShipped");
 }
 if (isModEnabled('invoice') && $user->hasRight("facture", "creer")) {
-	$arrayofmassactions['createbills'] = img_picto('', 'bill', 'class="pictofixedwidth"').$langs->trans("CreateInvoiceForThisCustomer");
+	$arrayofmassactions['createbills'] = img_picto('', 'bill', 'class="pictofixedwidth"') . $langs->trans("CreateInvoiceForThisCustomer");
 }
 if ($permissiontoclose) {
-	$arrayofmassactions['setbilled'] = img_picto('', 'bill', 'class="pictofixedwidth"').$langs->trans("ClassifyBilled");
+	$arrayofmassactions['setbilled'] = img_picto('', 'bill', 'class="pictofixedwidth"') . $langs->trans("ClassifyBilled");
 }
 if ($permissiontocancel) {
-	$arrayofmassactions['cancelorders'] = img_picto('', 'close_title', 'class="pictofixedwidth"').$langs->trans("CancelOrder");
+	$arrayofmassactions['cancelorders'] = img_picto('', 'close_title', 'class="pictofixedwidth"') . $langs->trans("CancelOrder");
 }
 if (!empty($permissiontodelete)) {
-	$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
+	$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"') . $langs->trans("Delete");
 }
 if ($permissiontosendbymail) {
-	$arrayofmassactions['presend'] = img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail");
+	$arrayofmassactions['presend'] = img_picto('', 'email', 'class="pictofixedwidth"') . $langs->trans("SendByMail");
 }
 if (in_array($massaction, array('presend', 'predelete', 'createbills'))) {
 	$arrayofmassactions = array();
 }
 $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
 
-$url = DOL_URL_ROOT.'/commande/card.php?action=create';
+$url = DOL_URL_ROOT . '/commande/card.php?action=create';
 if (!empty($socid)) {
-	$url .= '&socid='.$socid;
+	$url .= '&socid=' . $socid;
 }
 $newcardbutton = '';
-$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition'));
-$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition'));
+$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"] . '?mode=common' . preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition'));
+$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"] . '?mode=kanban' . preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition'));
 $newcardbutton .= dolGetButtonTitleSeparator();
 $newcardbutton .= dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', $url, '', (int) (($contextpage == 'orderlist' || $contextpage == 'billableorders') && $permissiontoadd));
 
 // Lines of title fields
-print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
+print '<form method="POST" id="searchFormList" action="' . $_SERVER["PHP_SELF"] . '">' . "\n";
 if ($optioncss != '') {
-	print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	print '<input type="hidden" name="optioncss" value="' . $optioncss . '">';
 }
-print '<input type="hidden" name="token" value="'.newToken().'">';
+print '<input type="hidden" name="token" value="' . newToken() . '">';
 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 print '<input type="hidden" name="action" value="list">';
-print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
-print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
-print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
-print '<input type="hidden" name="search_status" value="'.$search_status.'">';
-print '<input type="hidden" name="socid" value="'.$socid.'">';
+print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
+print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
+print '<input type="hidden" name="contextpage" value="' . $contextpage . '">';
+print '<input type="hidden" name="search_status" value="' . $search_status . '">';
+print '<input type="hidden" name="socid" value="' . $socid . '">';
 print '<input type="hidden" name="page_y" value="">';
-print '<input type="hidden" name="mode" value="'.$mode.'">';
+print '<input type="hidden" name="mode" value="' . $mode . '">';
 
 
 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'order', 0, $newcardbutton, '', $limit, 0, 0, 1);
@@ -1493,8 +1518,8 @@
 $topicmail = "SendOrderRef";
 $modelmail = "order_send";
 $objecttmp = new Commande($db);
-$trackid = 'ord'.$object->id;
-include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
+$trackid = 'ord' . $object->id;
+include DOL_DOCUMENT_ROOT . '/core/tpl/massactions_pre.tpl.php';
 
 if ($massaction == 'prevalidate') {
 	print $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans("ConfirmMassValidation"), $langs->trans("ConfirmMassValidationQuestion"), "validate", null, '', 0, 200, 500, 1);
@@ -1531,22 +1556,22 @@
 	if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
 		print $form->selectyesno('validate_invoices', 0, 1, 1);
 		$langs->load("errors");
-		print ' ('.$langs->trans("WarningAutoValNotPossibleWhenStockIsDecreasedOnInvoiceVal").')';
+		print ' (' . $langs->trans("WarningAutoValNotPossibleWhenStockIsDecreasedOnInvoiceVal") . ')';
 	} else {
 		print $form->selectyesno('validate_invoices', 0, 1);
 	}
 	if (!empty($conf->workflow->enabled) && getDolGlobalString('WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER')) {
-		print ' &nbsp; &nbsp; <span class="opacitymedium">'.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").'</span>';
+		print ' &nbsp; &nbsp; <span class="opacitymedium">' . $langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled") . '</span>';
 	} else {
-		print ' &nbsp; &nbsp; <span class="opacitymedium">'.$langs->trans("OptionToSetOrderBilledNotEnabled").'</span>';
+		print ' &nbsp; &nbsp; <span class="opacitymedium">' . $langs->trans("OptionToSetOrderBilledNotEnabled") . '</span>';
 	}
 	print '</td>';
 	print '</tr>';
 	print '</table>';
 
 	print '<div class="center">';
-	print '<input type="submit" class="button" id="createbills" name="createbills" value="'.$langs->trans('CreateInvoiceForThisCustomer').'">  ';
-	print '<input type="submit" class="button button-cancel" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
+	print '<input type="submit" class="button" id="createbills" name="createbills" value="' . $langs->trans('CreateInvoiceForThisCustomer') . '">  ';
+	print '<input type="submit" class="button button-cancel" id="cancel" name="cancel" value="' . $langs->trans("Cancel") . '">';
 	print '</div>';
 	print '<br><br>';
 }
@@ -1555,10 +1580,10 @@
 	$setupstring = '';
 	foreach ($fieldstosearchall as $key => $val) {
 		$fieldstosearchall[$key] = $langs->trans($val);
-		$setupstring .= $key."=".$val.";";
+		$setupstring .= $key . "=" . $val . ";";
 	}
-	print '<!-- Search done like if MYOBJECT_QUICKSEARCH_ON_FIELDS = '.$setupstring.' -->'."\n";
-	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).implode(', ', $fieldstosearchall).'</div>';
+	print '<!-- Search done like if MYOBJECT_QUICKSEARCH_ON_FIELDS = ' . $setupstring . ' -->' . "\n";
+	print '<div class="divsearchfieldfilter">' . $langs->trans("FilterOnInto", $search_all) . implode(', ', $fieldstosearchall) . '</div>';
 }
 
 $moreforfilter = '';
@@ -1568,41 +1593,41 @@
 	$langs->load("commercial");
 	$moreforfilter .= '<div class="divsearchfield">';
 	$tmptitle = $langs->trans('ThirdPartiesOfSaleRepresentative');
-	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"').$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, $tmptitle, 'maxwidth250 widthcentpercentminusx');
+	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"') . $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, $tmptitle, 'maxwidth250 widthcentpercentminusx');
 	$moreforfilter .= '</div>';
 }
 // If the user can view other users
 if ($user->hasRight("user", "user", "lire")) {
 	$moreforfilter .= '<div class="divsearchfield">';
 	$tmptitle = $langs->trans('LinkedToSpecificUsers');
-	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"').$form->select_dolusers($search_user, 'search_user', $tmptitle, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth250 widthcentpercentminusx');
+	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"') . $form->select_dolusers($search_user, 'search_user', $tmptitle, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth250 widthcentpercentminusx');
 	$moreforfilter .= '</div>';
 }
 
 // If the user can view other products/services than his own
 if (isModEnabled('category') && $user->hasRight("categorie", "lire") && ($user->hasRight("produit", "lire") || $user->hasRight("service", "lire"))) {
-	include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
+	include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
 	$moreforfilter .= '<div class="divsearchfield">';
 	$tmptitle = $langs->trans('IncludingProductWithTag');
 	$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', 'parent', 0, array(), 1);
-	$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"').$form->selectarray('search_product_category', $cate_arbo, $search_product_category, $tmptitle, 0, 0, '', 0, 0, 0, 0, 'maxwidth300 widthcentpercentminusx', 1);
+	$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"') . $form->selectarray('search_product_category', $cate_arbo, $search_product_category, $tmptitle, 0, 0, '', 0, 0, 0, 0, 'maxwidth300 widthcentpercentminusx', 1);
 	$moreforfilter .= '</div>';
 }
 // If Categories are enabled & user has rights to see
 if (isModEnabled('category') && $user->hasRight("categorie", "lire")) {
-	require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
 	$moreforfilter .= '<div class="divsearchfield">';
 	$tmptitle = $langs->trans('CustomersProspectsCategoriesShort');
-	$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"').$formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $tmptitle, 'maxwidth300 widthcentpercentminusx');
+	$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"') . $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $tmptitle, 'maxwidth300 widthcentpercentminusx');
 	$moreforfilter .= '</div>';
 }
 // If Stock is enabled
 if (isModEnabled('stock') && getDolGlobalString('WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER')) {
-	require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
 	$formproduct = new FormProduct($db);
 	$moreforfilter .= '<div class="divsearchfield">';
 	$tmptitle = $langs->trans('Warehouse');
-	$moreforfilter .= img_picto($tmptitle, 'stock', 'class="pictofixedwidth"').$formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', 1, 0, 0, $tmptitle, 0, 0, array(), 'maxwidth250 widthcentpercentminusx');
+	$moreforfilter .= img_picto($tmptitle, 'stock', 'class="pictofixedwidth"') . $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', 1, 0, 0, $tmptitle, 0, 0, array(), 'maxwidth250 widthcentpercentminusx');
 	$moreforfilter .= '</div>';
 }
 
@@ -1636,7 +1661,7 @@
 }
 
 print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you don't need reserved height for your table
-print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
+print '<table class="tagtable nobottomiftotal liste' . ($moreforfilter ? " listwithfilterbefore" : "") . '">' . "\n";
 
 // Fields title search
 // --------------------------------------------------------------------
@@ -1652,66 +1677,66 @@
 // Line numbering
 if (!empty($arrayfields['c.rowid']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat" size="6" type="text" name="search_id" value="'.dol_escape_htmltag($search_id).'">';
+	print '<input class="flat" size="6" type="text" name="search_id" value="' . dol_escape_htmltag($search_id) . '">';
 	print '</td>';
 }
 
 // Ref
 if (!empty($arrayfields['c.ref']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat" size="6" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
+	print '<input class="flat" size="6" type="text" name="search_ref" value="' . dol_escape_htmltag($search_ref) . '">';
 	print '</td>';
 }
 // Ref ext
 if (!empty($arrayfields['c.ref_ext']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat" size="6" type="text" name="search_ref_ext" value="'.dol_escape_htmltag($search_ref_ext).'">';
+	print '<input class="flat" size="6" type="text" name="search_ref_ext" value="' . dol_escape_htmltag($search_ref_ext) . '">';
 	print '</td>';
 }
 // Ref customer
 if (!empty($arrayfields['c.ref_client']['checked'])) {
 	print '<td class="liste_titre" align="left">';
-	print '<input class="flat" type="text" size="6" name="search_ref_customer" value="'.dol_escape_htmltag($search_ref_customer).'">';
+	print '<input class="flat" type="text" size="6" name="search_ref_customer" value="' . dol_escape_htmltag($search_ref_customer) . '">';
 	print '</td>';
 }
 // Project ref
 if (!empty($arrayfields['p.ref']['checked'])) {
-	print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
+	print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_project_ref" value="' . dol_escape_htmltag($search_project_ref) . '"></td>';
 }
 // Project title
 if (!empty($arrayfields['p.title']['checked'])) {
-	print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_project" value="'.dol_escape_htmltag($search_project).'"></td>';
+	print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_project" value="' . dol_escape_htmltag($search_project) . '"></td>';
 }
 // Thirpdarty
 if (!empty($arrayfields['s.nom']['checked'])) {
 	print '<td class="liste_titre" align="left">';
-	print '<input class="flat maxwidth100" type="text" name="search_company" value="'.dol_escape_htmltag($search_company).'"'.(!empty($user->socid) ? " disabled" : "").'>';
+	print '<input class="flat maxwidth100" type="text" name="search_company" value="' . dol_escape_htmltag($search_company) . '"' . (!empty($user->socid) ? " disabled" : "") . '>';
 	print '</td>';
 }
 // Alias
 if (!empty($arrayfields['s.name_alias']['checked'])) {
 	print '<td class="liste_titre" align="left">';
-	print '<input class="flat maxwidth100" type="text" name="search_company_alias" value="'.dol_escape_htmltag($search_company_alias).'">';
+	print '<input class="flat maxwidth100" type="text" name="search_company_alias" value="' . dol_escape_htmltag($search_company_alias) . '">';
 	print '</td>';
 }
 // Parent company
 if (!empty($arrayfields['s2.nom']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth100" type="text" name="search_parent_name" value="'.dol_escape_htmltag($search_parent_name).'">';
+	print '<input class="flat maxwidth100" type="text" name="search_parent_name" value="' . dol_escape_htmltag($search_parent_name) . '">';
 	print '</td>';
 }
 // Town
 if (!empty($arrayfields['s.town']['checked'])) {
-	print '<td class="liste_titre"><input class="flat width50" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'"></td>';
+	print '<td class="liste_titre"><input class="flat width50" type="text" name="search_town" value="' . dol_escape_htmltag($search_town) . '"></td>';
 }
 // Zip
 if (!empty($arrayfields['s.zip']['checked'])) {
-	print '<td class="liste_titre"><input class="flat width50" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'"></td>';
+	print '<td class="liste_titre"><input class="flat width50" type="text" name="search_zip" value="' . dol_escape_htmltag($search_zip) . '"></td>';
 }
 // State
 if (!empty($arrayfields['state.nom']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat width50" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
+	print '<input class="flat width50" type="text" name="search_state" value="' . dol_escape_htmltag($search_state) . '">';
 	print '</td>';
 }
 // Country
@@ -1774,19 +1799,19 @@
 // Amount HT / net
 if (!empty($arrayfields['c.total_ht']['checked'])) {
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_total_ht" value="'.dol_escape_htmltag($search_total_ht).'">';
+	print '<input class="flat" type="text" size="4" name="search_total_ht" value="' . dol_escape_htmltag($search_total_ht) . '">';
 	print '</td>';
 }
 // Amount of VAT
 if (!empty($arrayfields['c.total_vat']['checked'])) {
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_total_vat" value="'.dol_escape_htmltag($search_total_vat).'">';
+	print '<input class="flat" type="text" size="4" name="search_total_vat" value="' . dol_escape_htmltag($search_total_vat) . '">';
 	print '</td>';
 }
 // Total Amount (TTC / gross)
 if (!empty($arrayfields['c.total_ttc']['checked'])) {
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="5" name="search_total_ttc" value="'.$search_total_ttc.'">';
+	print '<input class="flat" type="text" size="5" name="search_total_ttc" value="' . $search_total_ttc . '">';
 	print '</td>';
 }
 // Currency
@@ -1798,31 +1823,31 @@
 // Currency rate
 if (!empty($arrayfields['c.multicurrency_tx']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">';
+	print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="' . dol_escape_htmltag($search_multicurrency_tx) . '">';
 	print '</td>';
 }
 // Amount HT/net in foreign currency
 if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) {
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">';
+	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="' . dol_escape_htmltag($search_multicurrency_montant_ht) . '">';
 	print '</td>';
 }
 // VAT in foreign currency
 if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) {
 	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="'.dol_escape_htmltag($search_multicurrency_montant_vat).'">';
+	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="' . dol_escape_htmltag($search_multicurrency_montant_vat) . '">';
 	print '</td>';
 }
 // Amount/Total (TTC / gross) in foreign currency
 if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) {
 	print '<td class="liste_titre right">';
-	print '<input class="flat width75" type="text" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">';
+	print '<input class="flat width75" type="text" name="search_multicurrency_montant_ttc" value="' . dol_escape_htmltag($search_multicurrency_montant_ttc) . '">';
 	print '</td>';
 }
 // Author
 if (!empty($arrayfields['u.login']['checked'])) {
 	print '<td class="liste_titre">';
-	print '<input class="flat width75" type="text" name="search_login" value="'.dol_escape_htmltag($search_login).'">';
+	print '<input class="flat width75" type="text" name="search_login" value="' . dol_escape_htmltag($search_login) . '">';
 	print '</td>';
 }
 // Sales Representative
@@ -1882,7 +1907,7 @@
 	print '<td class="liste_titre maxwidthonsmartphone" align="center">';
 	//print $form->selectyesno('search_shippable', $search_shippable, 1, 0, 1, 1);
 	if (getDolGlobalString('ORDER_SHIPABLE_STATUS_DISABLED_BY_DEFAULT')) {
-		print '<input type="checkbox" name="show_shippable_command" value="1"'.($show_shippable_command ? ' checked' : '').'>';
+		print '<input type="checkbox" name="show_shippable_command" value="1"' . ($show_shippable_command ? ' checked' : '') . '>';
 		print $langs->trans('ShowShippableStatus');
 	} else {
 		$show_shippable_command = 1;
@@ -1891,7 +1916,7 @@
 }
 
 // Extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_input.tpl.php';
 
 // Fields from hook
 $parameters = array('arrayfields' => $arrayfields);
@@ -1908,7 +1933,7 @@
 // Import key
 if (!empty($arrayfields['c.import_key']['checked'])) {
 	print '<td class="liste_titre maxwidthonsmartphone center">';
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_import_key" value="'.dol_escape_htmltag($search_import_key).'">';
+	print '<input class="flat searchstring maxwidth50" type="text" name="search_import_key" value="' . dol_escape_htmltag($search_import_key) . '">';
 	print '</td>';
 }
 
@@ -1919,8 +1944,8 @@
 		Commande::STATUS_DRAFT => $langs->trans("StatusOrderDraftShort"),
 		Commande::STATUS_VALIDATED => $langs->trans("StatusOrderValidated"),
 		Commande::STATUS_SHIPMENTONPROCESS => $langs->trans("StatusOrderSentShort"),
-		-2 => $langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort"),
-		-3 => $langs->trans("StatusOrderValidatedShort").'+'.$langs->trans("StatusOrderSentShort").'+'.$langs->trans("StatusOrderDelivered"),
+		-2 => $langs->trans("StatusOrderValidatedShort") . '+' . $langs->trans("StatusOrderSentShort"),
+		-3 => $langs->trans("StatusOrderValidatedShort") . '+' . $langs->trans("StatusOrderSentShort") . '+' . $langs->trans("StatusOrderDelivered"),
 		Commande::STATUS_CLOSED => $langs->trans("StatusOrderDelivered"),
 		Commande::STATUS_CANCELED => $langs->trans("StatusOrderCanceledShort")
 	);
@@ -1935,7 +1960,7 @@
 	print $searchpicto;
 	print '</td>';
 }
-print '</tr>'."\n";
+print '</tr>' . "\n";
 
 $totalarray = array(
 	'nbfield' => 0,
@@ -2120,7 +2145,7 @@
 	$totalarray['nbfield']++;
 }
 // Extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_title.tpl.php';
 
 // Hook fields
 $parameters = array('arrayfields' => $arrayfields, 'param' => $param, 'sortfield' => $sortfield, 'sortorder' => $sortorder, 'totalarray' => &$totalarray);
@@ -2147,7 +2172,7 @@
 	print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'maxwidthsearch center ');
 	$totalarray['nbfield']++;
 }
-print '</tr>'."\n";
+print '</tr>' . "\n";
 
 $total = 0;
 $subtotal = 0;
@@ -2160,12 +2185,13 @@
 $userstatic = new User($db);
 
 $with_margin_info = false;
-if (isModEnabled('margin') && (
-	!empty($arrayfields['total_pa']['checked'])
-	|| !empty($arrayfields['total_margin']['checked'])
-	|| !empty($arrayfields['total_margin_rate']['checked'])
-	|| !empty($arrayfields['total_mark_rate']['checked'])
-)
+if (
+	isModEnabled('margin') && (
+		!empty($arrayfields['total_pa']['checked'])
+		|| !empty($arrayfields['total_margin']['checked'])
+		|| !empty($arrayfields['total_margin_rate']['checked'])
+		|| !empty($arrayfields['total_mark_rate']['checked'])
+	)
 ) {
 	$with_margin_info = true;
 }
@@ -2238,7 +2264,7 @@
 
 	if ($mode == 'kanban') {
 		if ($i == 0) {
-			print '<tr class="trkanban"><td colspan="'.$savnbfield.'">';
+			print '<tr class="trkanban"><td colspan="' . $savnbfield . '">';
 			print '<div class="box-flex-container kanban">';
 		}
 
@@ -2258,7 +2284,7 @@
 	} else {
 		// Show line of result
 		$j = 0;
-		print '<tr data-rowid="'.$object->id.'" class="oddeven '.((getDolGlobalInt('MAIN_FINISHED_LINES_OPACITY') == 1 && $obj->billed == 1) ? 'opacitymedium' : '').'">';
+		print '<tr data-rowid="' . $object->id . '" class="oddeven ' . ((getDolGlobalInt('MAIN_FINISHED_LINES_OPACITY') == 1 && $obj->billed == 1) ? 'opacitymedium' : '') . '">';
 
 		// Action column
 		if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
@@ -2268,7 +2294,7 @@
 				if (in_array($obj->rowid, $arrayofselected)) {
 					$selected = 1;
 				}
-				print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
+				print '<input id="cb' . $obj->rowid . '" class="flat checkforselect" type="checkbox" name="toselect[]" value="' . $obj->rowid . '"' . ($selected ? ' checked="checked"' : '') . '>';
 			}
 			print '</td>';
 			if (!$i) {
@@ -2278,7 +2304,7 @@
 
 		// Technical ID
 		if (!empty($arrayfields['c.rowid']['checked'])) {
-			print '<td class="center" data-key="id">'.$obj->rowid.'</td>';
+			print '<td class="center" data-key="id">' . $obj->rowid . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2298,8 +2324,8 @@
 			print $generic_commande->getNomUrl(1, $getNomUrlOption, 0, 0, 0, 1, 1);
 
 			$filename = dol_sanitizeFileName($obj->ref);
-			$filedir = $conf->commande->multidir_output[$conf->entity].'/'.dol_sanitizeFileName($obj->ref);
-			$urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->rowid;
+			$filedir = $conf->commande->multidir_output[$conf->entity] . '/' . dol_sanitizeFileName($obj->ref);
+			$urlsource = $_SERVER['PHP_SELF'] . '?id=' . $obj->rowid;
 			print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir);
 
 			print '</td>';
@@ -2310,7 +2336,7 @@
 
 		// Ref customer
 		if (!empty($arrayfields['c.ref_ext']['checked'])) {
-			print '<td class="nowrap tdoverflowmax75" title="'.dol_escape_htmltag($obj->ref_ext).'">';
+			print '<td class="nowrap tdoverflowmax75" title="' . dol_escape_htmltag($obj->ref_ext) . '">';
 			print dol_escape_htmltag($obj->ref_ext);
 			print '</td>';
 			if (!$i) {
@@ -2320,7 +2346,7 @@
 
 		// Ref customer
 		if (!empty($arrayfields['c.ref_client']['checked'])) {
-			print '<td class="nowrap tdoverflowmax150" title="'.dol_escape_htmltag($obj->ref_client).'">';
+			print '<td class="nowrap tdoverflowmax150" title="' . dol_escape_htmltag($obj->ref_client) . '">';
 			print dol_escape_htmltag($obj->ref_client);
 			print '</td>';
 			if (!$i) {
@@ -2365,8 +2391,8 @@
 			if (isModEnabled('invoice') && getDolGlobalString('ORDER_BILLING_ALL_CUSTOMER')) {
 				if ($user->hasRight('facture', 'creer')) {
 					if (($obj->fk_statut > 0 && $obj->fk_statut < 3) || ($obj->fk_statut == 3 && $obj->billed == 0)) {
-						print '&nbsp;<a href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$companystatic->id.'&search_billed=0&autoselectall=1">';
-						print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').'</a>';
+						print '&nbsp;<a href="' . DOL_URL_ROOT . '/commande/list.php?socid=' . $companystatic->id . '&search_billed=0&autoselectall=1">';
+						print img_picto($langs->trans("CreateInvoiceForThisCustomer") . ' : ' . $companystatic->name, 'object_bill', 'hideonsmartphone') . '</a>';
 					}
 				}
 			}
@@ -2378,7 +2404,7 @@
 
 		// Alias name
 		if (!empty($arrayfields['s.name_alias']['checked'])) {
-			print '<td class="nocellnopadd tdoverflowmax100" title="'.dolPrintHTMLForTextArea($obj->alias).'">';
+			print '<td class="nocellnopadd tdoverflowmax100" title="' . dolPrintHTMLForTextArea($obj->alias) . '">';
 			print dolPrintLabel($obj->alias);
 			print '</td>';
 			if (!$i) {
@@ -2409,7 +2435,7 @@
 
 		// Town
 		if (!empty($arrayfields['s.town']['checked'])) {
-			print '<td class="tdoverflowmax100" title="'.dolPrintHTMLForTextArea($obj->town).'">';
+			print '<td class="tdoverflowmax100" title="' . dolPrintHTMLForTextArea($obj->town) . '">';
 			print dolPrintLabel($obj->town);
 			print '</td>';
 			if (!$i) {
@@ -2419,7 +2445,7 @@
 
 		// Zip
 		if (!empty($arrayfields['s.zip']['checked'])) {
-			print '<td class="tdoverflowmax100" title="'.dolPrintHTMLForTextArea($obj->zip).'">';
+			print '<td class="tdoverflowmax100" title="' . dolPrintHTMLForTextArea($obj->zip) . '">';
 			print dolPrintLabel($obj->zip);
 			print '</td>';
 			if (!$i) {
@@ -2429,7 +2455,7 @@
 
 		// State
 		if (!empty($arrayfields['state.nom']['checked'])) {
-			print '<td class="tdoverflowmax100" title="'.dolPrintHTMLForTextArea($obj->state_name).'">'.dolPrintLabel($obj->state_name)."</td>\n";
+			print '<td class="tdoverflowmax100" title="' . dolPrintHTMLForTextArea($obj->state_name) . '">' . dolPrintLabel($obj->state_name) . "</td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2465,7 +2491,7 @@
 			print dol_print_date($db->jdate($obj->date_commande), 'day');
 			// Warning late icon and note
 			if ($generic_commande->hasDelay()) {
-				print img_picto($langs->trans("Late").' : '.$generic_commande->showDelay(), "warning");
+				print img_picto($langs->trans("Late") . ' : ' . $generic_commande->showDelay(), "warning");
 			}
 			print '</td>';
 			if (!$i) {
@@ -2525,7 +2551,7 @@
 
 		// Amount HT/net
 		if (!empty($arrayfields['c.total_ht']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($obj->total_ht)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($obj->total_ht) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2541,7 +2567,7 @@
 
 		// Amount VAT
 		if (!empty($arrayfields['c.total_vat']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($obj->total_tva)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($obj->total_tva) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2557,7 +2583,7 @@
 
 		// Amount TTC / gross
 		if (!empty($arrayfields['c.total_ttc']['checked'])) {
-			print '<td class="nowrap right"><span class="amount">'.price($obj->total_ttc)."</span></td>\n";
+			print '<td class="nowrap right"><span class="amount">' . price($obj->total_ttc) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2573,7 +2599,7 @@
 
 		// Currency
 		if (!empty($arrayfields['c.multicurrency_code']['checked'])) {
-			print '<td class="nowrap">'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."</td>\n";
+			print '<td class="nowrap">' . $obj->multicurrency_code . ' - ' . $langs->trans('Currency' . $obj->multicurrency_code) . "</td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2582,7 +2608,7 @@
 		// Currency rate
 		if (!empty($arrayfields['c.multicurrency_tx']['checked'])) {
 			print '<td class="nowrap">';
-			$form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code);
+			$form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code);
 			print "</td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
@@ -2591,21 +2617,21 @@
 
 		// Amount HT/net in foreign currency
 		if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) {
-			print '<td class="right nowrap"><span class="amount">'.price($obj->multicurrency_total_ht)."</span></td>\n";
+			print '<td class="right nowrap"><span class="amount">' . price($obj->multicurrency_total_ht) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
 		}
 		// Amount VAT in foreign currency
 		if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) {
-			print '<td class="right nowrap"><span class="amount">'.price($obj->multicurrency_total_vat)."</span></td>\n";
+			print '<td class="right nowrap"><span class="amount">' . price($obj->multicurrency_total_vat) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
 		}
 		// Amount TTC / gross in foreign currency
 		if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) {
-			print '<td class="right nowrap"><span class="amount">'.price($obj->multicurrency_total_ttc)."</span></td>\n";
+			print '<td class="right nowrap"><span class="amount">' . price($obj->multicurrency_total_ttc) . "</span></td>\n";
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2688,7 +2714,7 @@
 
 		// Total buying or cost price
 		if (!empty($arrayfields['total_pa']['checked'])) {
-			print '<td class="right nowrap">'.price($marginInfo['pa_total']).'</td>';
+			print '<td class="right nowrap">' . price($marginInfo['pa_total']) . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2696,7 +2722,7 @@
 
 		// Total margin
 		if (!empty($arrayfields['total_margin']['checked'])) {
-			print '<td class="right nowrap">'.price($marginInfo['total_margin']).'</td>';
+			print '<td class="right nowrap">' . price($marginInfo['total_margin']) . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2713,7 +2739,7 @@
 
 		// Total margin rate
 		if (!empty($arrayfields['total_margin_rate']['checked'])) {
-			print '<td class="right nowrap">'.(($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], 0, '', 0, 0, 2).'%').'</td>';
+			print '<td class="right nowrap">' . (($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], 0, '', 0, 0, 2) . '%') . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2721,7 +2747,7 @@
 
 		// Total mark rate
 		if (!empty($arrayfields['total_mark_rate']['checked'])) {
-			print '<td class="right nowrap">'.(($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], 0, '', 0, 0, 2).'%').'</td>';
+			print '<td class="right nowrap">' . (($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], 0, '', 0, 0, 2) . '%') . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2824,10 +2850,10 @@
 								$notshippable++;
 							}
 							if (!getDolGlobalString('SHIPPABLE_ORDER_ICON_IN_LIST')) {  // Default code. Default should be this case.
-								$text_info .= $reliquat.' x '.$orderLine->product_ref.'&nbsp;'.dol_trunc($orderLine->product_label, 20);
-								$text_info .= ' - '.$langs->trans("Stock").': <span class="'.($generic_product->stock_reel > 0 ? 'ok' : 'error').'">'.$generic_product->stock_reel.'</span>';
-								$text_info .= ' - '.$langs->trans("VirtualStock").': <span class="'.($generic_product->stock_theorique > 0 ? 'ok' : 'error').'">'.$generic_product->stock_theorique.'</span>';
-								$text_info .= ($reliquat != $orderLine->qty ? ' <span class="opacitymedium">('.$langs->trans("QtyInOtherShipments").' '.($orderLine->qty - $reliquat).')</span>' : '');
+								$text_info .= $reliquat . ' x ' . $orderLine->product_ref . '&nbsp;' . dol_trunc($orderLine->product_label, 20);
+								$text_info .= ' - ' . $langs->trans("Stock") . ': <span class="' . ($generic_product->stock_reel > 0 ? 'ok' : 'error') . '">' . $generic_product->stock_reel . '</span>';
+								$text_info .= ' - ' . $langs->trans("VirtualStock") . ': <span class="' . ($generic_product->stock_theorique > 0 ? 'ok' : 'error') . '">' . $generic_product->stock_theorique . '</span>';
+								$text_info .= ($reliquat != $orderLine->qty ? ' <span class="opacitymedium">(' . $langs->trans("QtyInOtherShipments") . ' ' . ($orderLine->qty - $reliquat) . ')</span>' : '');
 								$text_info .= '<br>';
 							} else {  // BUGGED CODE.
 								// DOES NOT TAKE INTO ACCOUNT MANUFACTURING. THIS CODE SHOULD BE USELESS. PREVIOUS CODE SEEMS COMPLETE.
@@ -2858,31 +2884,31 @@
 										$stock_order_supplier = $generic_product->stats_commande_fournisseur['qty'];
 									}
 								}
-								$text_info .= $reliquat.' x '.$orderLine->ref.'&nbsp;'.dol_trunc($orderLine->product_label, 20);
-								$text_stock_reel = $generic_product->stock_reel.'/'.$stock_order;
+								$text_info .= $reliquat . ' x ' . $orderLine->ref . '&nbsp;' . dol_trunc($orderLine->product_label, 20);
+								$text_stock_reel = $generic_product->stock_reel . '/' . $stock_order;
 								if ($stock_order > $generic_product->stock_reel && !($generic_product->stock_reel < $orderLine->qty)) {
 									$warning++;
-									$text_warning .= '<span class="warning">'.$langs->trans('Available').'&nbsp;:&nbsp;'.$text_stock_reel.'</span>';
+									$text_warning .= '<span class="warning">' . $langs->trans('Available') . '&nbsp;:&nbsp;' . $text_stock_reel . '</span>';
 								}
 								if ($reliquat > $generic_product->stock_reel) {
-									$text_info .= '<span class="warning">'.$langs->trans('Available').'&nbsp;:&nbsp;'.$text_stock_reel.'</span>';
+									$text_info .= '<span class="warning">' . $langs->trans('Available') . '&nbsp;:&nbsp;' . $text_stock_reel . '</span>';
 								} else {
-									$text_info .= '<span class="ok">'.$langs->trans('Available').'&nbsp;:&nbsp;'.$text_stock_reel.'</span>';
+									$text_info .= '<span class="ok">' . $langs->trans('Available') . '&nbsp;:&nbsp;' . $text_stock_reel . '</span>';
 								}
 								if (isModEnabled("supplier_order")) {
-									$text_info .= '&nbsp;'.$langs->trans('SupplierOrder').'&nbsp;:&nbsp;'.$stock_order_supplier;
+									$text_info .= '&nbsp;' . $langs->trans('SupplierOrder') . '&nbsp;:&nbsp;' . $stock_order_supplier;
 								}
-								$text_info .= ($reliquat != $orderLine->qty ? ' <span class="opacitymedium">('.$langs->trans("QtyInOtherShipments").' '.($orderLine->qty - $reliquat).')</span>' : '');
+								$text_info .= ($reliquat != $orderLine->qty ? ' <span class="opacitymedium">(' . $langs->trans("QtyInOtherShipments") . ' ' . ($orderLine->qty - $reliquat) . ')</span>' : '');
 								$text_info .= '<br>';
 							}
 						}
 					}
 					if ($notshippable == 0) {
 						$text_icon = img_picto('', 'dolly', '', 0, 0, 0, '', 'green paddingleft');
-						$text_info = $text_icon.' '.$langs->trans('Shippable').'<br>'.$text_info;
+						$text_info = $text_icon . ' ' . $langs->trans('Shippable') . '<br>' . $text_info;
 					} else {
 						$text_icon = img_picto('', 'dolly', '', 0, 0, 0, '', 'error paddingleft');
-						$text_info = $text_icon.' '.$langs->trans('NonShippable').'<br>'.$text_info;
+						$text_info = $text_icon . ' ' . $langs->trans('NonShippable') . '<br>' . $text_info;
 					}
 				}
 
@@ -2890,7 +2916,7 @@
 					print $form->textwithtooltip('', $text_info, 2, 1, $text_icon, '', 2);
 				}
 				if ($warning) {     // Always false in default mode
-					print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders').'<br>'.$text_warning, 2, 1, img_picto('', 'error'), '', 2);
+					print $form->textwithtooltip('', $langs->trans('NotEnoughForAllOrders') . '<br>' . $text_warning, 2, 1, img_picto('', 'error'), '', 2);
 				}
 			}
 			print '</td>';
@@ -2900,7 +2926,7 @@
 		}
 
 		// Extra fields
-		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
+		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_print_fields.tpl.php';
 		// Fields from hook
 		$parameters = array('arrayfields' => $arrayfields, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray);
 		$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
@@ -2920,7 +2946,7 @@
 
 		// Import key
 		if (!empty($arrayfields['c.import_key']['checked'])) {
-			print '<td class="nowrap center">'.dol_escape_htmltag($obj->import_key).'</td>';
+			print '<td class="nowrap center">' . dol_escape_htmltag($obj->import_key) . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2928,7 +2954,7 @@
 
 		// Status
 		if (!empty($arrayfields['c.fk_statut']['checked'])) {
-			print '<td class="nowrap center">'.$generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1).'</td>';
+			print '<td class="nowrap center">' . $generic_commande->LibStatut($obj->fk_statut, $obj->billed, 5, 1) . '</td>';
 			if (!$i) {
 				$totalarray['nbfield']++;
 			}
@@ -2942,7 +2968,7 @@
 				if (in_array($obj->rowid, $arrayofselected)) {
 					$selected = 1;
 				}
-				print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
+				print '<input id="cb' . $obj->rowid . '" class="flat checkforselect" type="checkbox" name="toselect[]" value="' . $obj->rowid . '"' . ($selected ? ' checked="checked"' : '') . '>';
 			}
 			print '</td>';
 			if (!$i) {
@@ -2959,7 +2985,7 @@
 }
 
 // Show total line
-include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/list_print_total.tpl.php';
 
 // If no record found
 if ($num == 0) {
@@ -2969,7 +2995,7 @@
 			$colspan++;
 		}
 	}
-	print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
+	print '<tr><td colspan="' . $colspan . '"><span class="opacitymedium">' . $langs->trans("NoRecordFound") . '</span></td></tr>';
 }
 
 $db->free($resql);
@@ -2978,10 +3004,10 @@
 $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
 print $hookmanager->resPrint;
 
-print '</table>'."\n";
-print '</div>'."\n";
+print '</table>' . "\n";
+print '</div>' . "\n";
 
-print '</form>'."\n";
+print '</form>' . "\n";
 
 if (in_array('builddoc', array_keys($arrayofmassactions)) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
 	$hidegeneratedfilelistifempty = 1;
@@ -2990,7 +3016,7 @@
 	}
 
 	// Show list of available documents
-	$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
+	$urlsource = $_SERVER['PHP_SELF'] . '?sortfield=' . $sortfield . '&sortorder=' . $sortorder;
 	$urlsource .= str_replace('&amp;', '&', $param);
 
 	$filedir = $diroutputmassaction;

########## compta/facture/list.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/compta/facture/list.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/compta/facture/list.php	2025-03-18 13:08:35.867382000 +0000
@@ -1,5 +1,5 @@
-<?php
-/* Copyright (C) 2002-2006	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
+l<?php
+	/* Copyright (C) 2002-2006	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
  * Copyright (C) 2004		Eric Seigne				<eric.seigne@ryxeo.com>
  * Copyright (C) 2004-2016	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2005		Marc Barilley / Ocebo	<marc@ocebo.com>
@@ -36,2838 +36,2825 @@
  * along with this program. If not, see <https://www.gnu.org/licenses/>.
  */
 
-/**
- *	\file       htdocs/compta/facture/list.php
- *	\ingroup    invoice
- *	\brief      List of customer invoices
- */
-
-// Load Dolibarr environment
-require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
-if (isModEnabled('margin')) {
-	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
-}
-require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
-if (isModEnabled('order')) {
-	require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
-}
-
-/**
- * @var Conf $conf
- * @var DoliDB $db
- * @var HookManager $hookmanager
- * @var Societe $mysoc
- * @var Translate $langs
- * @var User $user
- */
-
-// Load translation files required by the page
-$langs->loadLangs(array('bills', 'companies', 'products', 'categories'));
-
-$search_all = trim(GETPOST('search_all', 'alphanohtml'));
-
-$id = (GETPOSTINT('id') ? GETPOSTINT('id') : GETPOSTINT('facid')); // For backward compatibility
-$ref = GETPOST('ref', 'alpha');
-$socid = GETPOSTINT('socid');
-
-$action = GETPOST('action', 'aZ09');
-$massaction = GETPOST('massaction', 'alpha');
-$show_files = GETPOSTINT('show_files');
-$confirm = GETPOST('confirm', 'alpha');
-$toselect = GETPOST('toselect', 'array');
-$optioncss = GETPOST('optioncss', 'alpha');
-$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'invoicelist';
-$mode = GETPOST('mode', 'aZ'); // The output mode ('list', 'kanban', 'hierarchy', 'calendar', ...)
-
-if ($contextpage == 'poslist') {
-	$optioncss = 'print';
-}
-
-$userid = GETPOSTINT('userid');
-$search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
-$search_refcustomer = GETPOST('search_refcustomer', 'alpha');
-$search_type = GETPOST('search_type', 'intcomma');
-$search_subtype = GETPOST('search_subtype', 'intcomma');
-$search_project_ref = GETPOST('search_project_ref', 'alpha');
-$search_project = GETPOST('search_project', 'alpha');
-$search_company = GETPOST('search_company', 'alpha');
-$search_company_alias = GETPOST('search_company_alias', 'alpha');
-$search_parent_name = trim(GETPOST('search_parent_name', 'alphanohtml'));
-$search_montant_ht = GETPOST('search_montant_ht', 'alpha');
-$search_montant_vat = GETPOST('search_montant_vat', 'alpha');
-$search_montant_localtax1 = GETPOST('search_montant_localtax1', 'alpha');
-$search_montant_localtax2 = GETPOST('search_montant_localtax2', 'alpha');
-$search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
-$search_login = GETPOST('search_login', 'alpha');
-$search_multicurrency_code = GETPOST('search_multicurrency_code', 'alpha');
-$search_multicurrency_tx = GETPOST('search_multicurrency_tx', 'alpha');
-$search_multicurrency_montant_ht = GETPOST('search_multicurrency_montant_ht', 'alpha');
-$search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', 'alpha');
-$search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha');
-$search_status = GETPOST('search_status', 'intcomma');
-$search_paymentmode = GETPOST('search_paymentmode', 'intcomma');
-$search_paymentterms = GETPOST('search_paymentterms', 'intcomma');
-$search_module_source = GETPOST('search_module_source', 'alpha');
-$search_pos_source = GETPOST('search_pos_source', 'alpha');
-$search_town = GETPOST('search_town', 'alpha');
-$search_zip = GETPOST('search_zip', 'alpha');
-$search_state = GETPOST("search_state");
-$search_country = GETPOST("search_country", 'aZ09');
-$search_customer_code = GETPOST("search_customer_code", 'alphanohtml');
-$search_type_thirdparty = GETPOST("search_type_thirdparty", 'intcomma');
-$search_user = GETPOST('search_user', 'intcomma');
-$search_sale = GETPOST('search_sale', 'intcomma');
-$search_date_startday = GETPOSTINT('search_date_startday');
-$search_date_startmonth = GETPOSTINT('search_date_startmonth');
-$search_date_startyear = GETPOSTINT('search_date_startyear');
-$search_date_endday = GETPOSTINT('search_date_endday');
-$search_date_endmonth = GETPOSTINT('search_date_endmonth');
-$search_date_endyear = GETPOSTINT('search_date_endyear');
-$search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear); // Use tzserver
-$search_date_end = dol_mktime(23, 59, 59, $search_date_endmonth, $search_date_endday, $search_date_endyear);
-$search_date_valid_startday = GETPOSTINT('search_date_valid_startday');
-$search_date_valid_startmonth = GETPOSTINT('search_date_valid_startmonth');
-$search_date_valid_startyear = GETPOSTINT('search_date_valid_startyear');
-$search_date_valid_endday = GETPOSTINT('search_date_valid_endday');
-$search_date_valid_endmonth = GETPOSTINT('search_date_valid_endmonth');
-$search_date_valid_endyear = GETPOSTINT('search_date_valid_endyear');
-$search_date_valid_start = dol_mktime(0, 0, 0, $search_date_valid_startmonth, $search_date_valid_startday, $search_date_valid_startyear); // Use tzserver
-$search_date_valid_end = dol_mktime(23, 59, 59, $search_date_valid_endmonth, $search_date_valid_endday, $search_date_valid_endyear);
-$search_datelimit_startday = GETPOSTINT('search_datelimit_startday');
-$search_datelimit_startmonth = GETPOSTINT('search_datelimit_startmonth');
-$search_datelimit_startyear = GETPOSTINT('search_datelimit_startyear');
-$search_datelimit_endday = GETPOSTINT('search_datelimit_endday');
-$search_datelimit_endmonth = GETPOSTINT('search_datelimit_endmonth');
-$search_datelimit_endyear = GETPOSTINT('search_datelimit_endyear');
-$search_datelimit_start = dol_mktime(0, 0, 0, $search_datelimit_startmonth, $search_datelimit_startday, $search_datelimit_startyear);
-$search_datelimit_end = dol_mktime(23, 59, 59, $search_datelimit_endmonth, $search_datelimit_endday, $search_datelimit_endyear);
-$search_categ_cus = GETPOST("search_categ_cus", 'intcomma');
-$search_product_category = GETPOST('search_product_category', 'intcomma');
-$search_fac_rec_source_title = GETPOST("search_fac_rec_source_title", 'alpha');
-$search_fk_fac_rec_source = GETPOST('search_fk_fac_rec_source', 'int');
-$search_import_key  = trim(GETPOST("search_import_key", "alpha"));
-
-$search_option = GETPOST('search_option');
-if ($search_option == 'late') {
-	$search_status = '1';
-}
-
-$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
-$sortfield = GETPOST('sortfield', 'aZ09comma');
-$sortorder = GETPOST('sortorder', 'aZ09comma');
-$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
-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;
-if (!$sortorder && getDolGlobalString('INVOICE_DEFAULT_UNPAYED_SORT_ORDER') && $search_status == '1') {
-	$sortorder = getDolGlobalString('INVOICE_DEFAULT_UNPAYED_SORT_ORDER');
-}
-if (!$sortorder) {
-	$sortorder = 'DESC';
-}
-if (!$sortfield) {
-	$sortfield = 'f.datef';
-}
-$pageprev = $page - 1;
-$pagenext = $page + 1;
-
-$diroutputmassaction = $conf->facture->dir_output.'/temp/massgeneration/'.$user->id;
-
-$now = dol_now();
-$error = 0;
+	/**
+	 *	\file       htdocs/compta/facture/list.php
+	 *	\ingroup    invoice
+	 *	\brief      List of customer invoices
+	 */
+
+	// Load Dolibarr environment
+	require '../../main.inc.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
+	if (isModEnabled('margin')) {
+		require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
+	}
+	require_once DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php';
+	require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture-rec.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
+	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+	if (isModEnabled('order')) {
+		require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
+	}
+
+	/**
+	 * @var Conf $conf
+	 * @var DoliDB $db
+	 * @var HookManager $hookmanager
+	 * @var Societe $mysoc
+	 * @var Translate $langs
+	 * @var User $user
+	 */
+
+	// Load translation files required by the page
+	$langs->loadLangs(array('bills', 'companies', 'products', 'categories'));
+
+	$search_all = trim(GETPOST('search_all', 'alphanohtml'));
+
+	$id = (GETPOSTINT('id') ? GETPOSTINT('id') : GETPOSTINT('facid')); // For backward compatibility
+	$ref = GETPOST('ref', 'alpha');
+	$socid = GETPOSTINT('socid');
+
+	$action = GETPOST('action', 'aZ09');
+	$massaction = GETPOST('massaction', 'alpha');
+	$show_files = GETPOSTINT('show_files');
+	$confirm = GETPOST('confirm', 'alpha');
+	$toselect = GETPOST('toselect', 'array');
+	$optioncss = GETPOST('optioncss', 'alpha');
+	$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'invoicelist';
+	$mode = GETPOST('mode', 'aZ'); // The output mode ('list', 'kanban', 'hierarchy', 'calendar', ...)
+
+	if ($contextpage == 'poslist') {
+		$optioncss = 'print';
+	}
+
+	$userid = GETPOSTINT('userid');
+	$search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
+	$search_refcustomer = GETPOST('search_refcustomer', 'alpha');
+	$search_type = GETPOST('search_type', 'intcomma');
+	$search_subtype = GETPOST('search_subtype', 'intcomma');
+	$search_project_ref = GETPOST('search_project_ref', 'alpha');
+	$search_project = GETPOST('search_project', 'alpha');
+	$search_company = GETPOST('search_company', 'alpha');
+	$search_company_alias = GETPOST('search_company_alias', 'alpha');
+	$search_parent_name = trim(GETPOST('search_parent_name', 'alphanohtml'));
+	$search_montant_ht = GETPOST('search_montant_ht', 'alpha');
+	$search_montant_vat = GETPOST('search_montant_vat', 'alpha');
+	$search_montant_localtax1 = GETPOST('search_montant_localtax1', 'alpha');
+	$search_montant_localtax2 = GETPOST('search_montant_localtax2', 'alpha');
+	$search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
+	$search_login = GETPOST('search_login', 'alpha');
+	$search_multicurrency_code = GETPOST('search_multicurrency_code', 'alpha');
+	$search_multicurrency_tx = GETPOST('search_multicurrency_tx', 'alpha');
+	$search_multicurrency_montant_ht = GETPOST('search_multicurrency_montant_ht', 'alpha');
+	$search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', 'alpha');
+	$search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha');
+	$search_status = GETPOST('search_status', 'intcomma');
+	$search_paymentmode = GETPOST('search_paymentmode', 'intcomma');
+	$search_paymentterms = GETPOST('search_paymentterms', 'intcomma');
+	$search_module_source = GETPOST('search_module_source', 'alpha');
+	$search_pos_source = GETPOST('search_pos_source', 'alpha');
+	$search_town = GETPOST('search_town', 'alpha');
+	$search_zip = GETPOST('search_zip', 'alpha');
+	$search_state = GETPOST("search_state");
+	$search_country = GETPOST("search_country", 'aZ09');
+	$search_customer_code = GETPOST("search_customer_code", 'alphanohtml');
+	$search_type_thirdparty = GETPOST("search_type_thirdparty", 'intcomma');
+	$search_user = GETPOST('search_user', 'intcomma');
+	$search_sale = GETPOST('search_sale', 'intcomma');
+	$search_date_startday = GETPOSTINT('search_date_startday');
+	$search_date_startmonth = GETPOSTINT('search_date_startmonth');
+	$search_date_startyear = GETPOSTINT('search_date_startyear');
+	$search_date_endday = GETPOSTINT('search_date_endday');
+	$search_date_endmonth = GETPOSTINT('search_date_endmonth');
+	$search_date_endyear = GETPOSTINT('search_date_endyear');
+	$search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear); // Use tzserver
+	$search_date_end = dol_mktime(23, 59, 59, $search_date_endmonth, $search_date_endday, $search_date_endyear);
+	$search_date_valid_startday = GETPOSTINT('search_date_valid_startday');
+	$search_date_valid_startmonth = GETPOSTINT('search_date_valid_startmonth');
+	$search_date_valid_startyear = GETPOSTINT('search_date_valid_startyear');
+	$search_date_valid_endday = GETPOSTINT('search_date_valid_endday');
+	$search_date_valid_endmonth = GETPOSTINT('search_date_valid_endmonth');
+	$search_date_valid_endyear = GETPOSTINT('search_date_valid_endyear');
+	$search_date_valid_start = dol_mktime(0, 0, 0, $search_date_valid_startmonth, $search_date_valid_startday, $search_date_valid_startyear); // Use tzserver
+	$search_date_valid_end = dol_mktime(23, 59, 59, $search_date_valid_endmonth, $search_date_valid_endday, $search_date_valid_endyear);
+	$search_datelimit_startday = GETPOSTINT('search_datelimit_startday');
+	$search_datelimit_startmonth = GETPOSTINT('search_datelimit_startmonth');
+	$search_datelimit_startyear = GETPOSTINT('search_datelimit_startyear');
+	$search_datelimit_endday = GETPOSTINT('search_datelimit_endday');
+	$search_datelimit_endmonth = GETPOSTINT('search_datelimit_endmonth');
+	$search_datelimit_endyear = GETPOSTINT('search_datelimit_endyear');
+	$search_datelimit_start = dol_mktime(0, 0, 0, $search_datelimit_startmonth, $search_datelimit_startday, $search_datelimit_startyear);
+	$search_datelimit_end = dol_mktime(23, 59, 59, $search_datelimit_endmonth, $search_datelimit_endday, $search_datelimit_endyear);
+	$search_categ_cus = GETPOST("search_categ_cus", 'intcomma');
+	$search_product_category = GETPOST('search_product_category', 'intcomma');
+	$search_fac_rec_source_title = GETPOST("search_fac_rec_source_title", 'alpha');
+	$search_fk_fac_rec_source = GETPOST('search_fk_fac_rec_source', 'int');
+	$search_import_key  = trim(GETPOST("search_import_key", "alpha"));
+
+	$search_option = GETPOST('search_option');
+	if ($search_option == 'late') {
+		$search_status = '1';
+	}
+
+	$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
+	$sortfield = GETPOST('sortfield', 'aZ09comma');
+	$sortorder = GETPOST('sortorder', 'aZ09comma');
+	$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
+	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;
+	if (!$sortorder && getDolGlobalString('INVOICE_DEFAULT_UNPAYED_SORT_ORDER') && $search_status == '1') {
+		$sortorder = getDolGlobalString('INVOICE_DEFAULT_UNPAYED_SORT_ORDER');
+	}
+	if (!$sortorder) {
+		$sortorder = 'DESC';
+	}
+	if (!$sortfield) {
+		$sortfield = 'f.datef';
+	}
+	$pageprev = $page - 1;
+	$pagenext = $page + 1;
+
+	$diroutputmassaction = $conf->facture->dir_output . '/temp/massgeneration/' . $user->id;
+
+	$now = dol_now();
+	$error = 0;
+
+	// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
+	$object = new Facture($db);
+	$hookmanager->initHooks(array($contextpage));
+	$extrafields = new ExtraFields($db);
+
+	// Fetch optionals attributes and labels
+	$extrafields->fetch_name_optionals_label($object->table_element);
+
+	$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+
+	// List of fields to search into when doing a "search in all"
+	$fieldstosearchall = array(
+		'f.ref' => 'Ref',
+		'f.ref_client' => 'RefCustomer',
+		'f.note_public' => 'NotePublic',
+		's.nom' => "ThirdParty",
+		's.code_client' => "CustomerCodeShort",
+		's.name_alias' => "AliasNameShort",
+		's.zip' => "Zip",
+		's.town' => "Town",
+		'pd.description' => 'Description',
+	);
+	if (empty($user->socid)) {
+		$fieldstosearchall["f.note_private"] = "NotePrivate";
+	}
 
-// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
-$object = new Facture($db);
-$hookmanager->initHooks(array($contextpage));
-$extrafields = new ExtraFields($db);
-
-// Fetch optionals attributes and labels
-$extrafields->fetch_name_optionals_label($object->table_element);
-
-$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
-
-// List of fields to search into when doing a "search in all"
-$fieldstosearchall = array(
-	'f.ref' => 'Ref',
-	'f.ref_client' => 'RefCustomer',
-	'f.note_public' => 'NotePublic',
-	's.nom' => "ThirdParty",
-	's.code_client' => "CustomerCodeShort",
-	's.name_alias' => "AliasNameShort",
-	's.zip' => "Zip",
-	's.town' => "Town",
-	'pd.description' => 'Description',
-);
-if (empty($user->socid)) {
-	$fieldstosearchall["f.note_private"] = "NotePrivate";
-}
+	$checkedtypetiers = 0;
+	$arrayfields = array(
+		'f.ref' => array('label' => "Ref", 'checked' => 1, 'position' => 5),
+		'f.ref_client' => array('label' => "RefCustomer", 'checked' => -1, 'position' => 10),
+		'f.type' => array('label' => "Type", 'checked' => 0, 'position' => 15),
+		'f.subtype' => array('label' => "InvoiceSubtype", 'checked' => 0, 'position' => 17),
+		'f.datef' => array('label' => "DateInvoice", 'checked' => 1, 'position' => 20),
+		'f.date_valid' => array('label' => "DateValidation", 'checked' => 0, 'position' => 22),
+		'f.date_lim_reglement' => array('label' => "DateDue", 'checked' => 1, 'position' => 25),
+		'f.date_closing' => array('label' => "DateClosing", 'checked' => 0, 'position' => 30),
+		'p.ref' => array('label' => "ProjectRef", 'langs' => 'projects', 'checked' => 1, 'enabled' => (!isModEnabled('project') ? 0 : 1), 'position' => 40),
+		'p.title' => array('label' => "ProjectLabel", 'checked' => 0, 'enabled' => (!isModEnabled('project') ? 0 : 1), 'position' => 41),
+		's.nom' => array('label' => "ThirdParty", 'checked' => 1, 'position' => 50),
+		's.name_alias' => array('label' => "AliasNameShort", 'checked' => -1, 'position' => 51),
+		's.code_client' => array('label' => "CustomerCodeShort", 'checked' => -1, 'position' => 52),
+		's2.nom' => array('label' => 'ParentCompany', 'position' => 32, 'checked' => 0),
+		's.town' => array('label' => "Town", 'checked' => -1, 'position' => 55),
+		's.zip' => array('label' => "Zip", 'checked' => -1, 'position' => 60),
+		'state.nom' => array('label' => "StateShort", 'checked' => 0, 'position' => 65),
+		'country.code_iso' => array('label' => "Country", 'checked' => 0, 'position' => 70),
+		'typent.code' => array('label' => "ThirdPartyType", 'checked' => $checkedtypetiers, 'position' => 75),
+		'f.fk_mode_reglement' => array('label' => "PaymentMode", 'checked' => 1, 'position' => 80),
+		'f.fk_cond_reglement' => array('label' => "PaymentConditionsShort", 'checked' => 1, 'position' => 85),
+		'f.module_source' => array('label' => "POSModule", 'langs' => 'cashdesk', 'checked' => ($contextpage == 'poslist' ? 1 : 0), 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'position' => 90),
+		'f.pos_source' => array('label' => "POSTerminal", 'langs' => 'cashdesk', 'checked' => ($contextpage == 'poslist' ? 1 : 0), 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'position' => 91),
+		'f.total_ht' => array('label' => "AmountHT", 'checked' => 1, 'position' => 95),
+		'f.total_tva' => array('label' => "AmountVAT", 'checked' => 0, 'position' => 100),
+		'f.total_localtax1' => array('label' => $langs->transcountry("AmountLT1", $mysoc->country_code), 'checked' => 0, 'enabled' => ($mysoc->localtax1_assuj == "1"), 'position' => 110),
+		'f.total_localtax2' => array('label' => $langs->transcountry("AmountLT2", $mysoc->country_code), 'checked' => 0, 'enabled' => ($mysoc->localtax2_assuj == "1"), 'position' => 120),
+		'f.total_ttc' => array('label' => "AmountTTC", 'checked' => 0, 'position' => 130),
+		'dynamount_payed' => array('label' => "AlreadyPaid", 'checked' => 0, 'position' => 140),
+		'rtp' => array('label' => "RemainderToPay", 'checked' => 0, 'position' => 150), // Not enabled by default because slow
+		'f.multicurrency_code' => array('label' => 'Currency', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 280),
+		'f.multicurrency_tx' => array('label' => 'CurrencyRate', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 285),
+		'f.multicurrency_total_ht' => array('label' => 'MulticurrencyAmountHT', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 290),
+		'f.multicurrency_total_vat' => array('label' => 'MulticurrencyAmountVAT', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 291),
+		'f.multicurrency_total_ttc' => array('label' => 'MulticurrencyAmountTTC', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 292),
+		'multicurrency_dynamount_payed' => array('label' => 'MulticurrencyAlreadyPaid', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 295),
+		'multicurrency_rtp' => array('label' => 'MulticurrencyRemainderToPay', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 296), // Not enabled by default because slow
+		'total_pa' => array('label' => ((getDolGlobalString('MARGIN_TYPE') == '1') ? 'BuyingPrice' : 'CostPrice'), 'checked' => 0, 'position' => 300, 'enabled' => (!isModEnabled('margin') || !$user->hasRight('margins', 'liretous') ? 0 : 1)),
+		'total_margin' => array('label' => 'Margin', 'checked' => 0, 'position' => 301, 'enabled' => (!isModEnabled('margin') || !$user->hasRight('margins', 'liretous') ? 0 : 1)),
+		'total_margin_rate' => array('label' => 'MarginRate', 'checked' => 0, 'position' => 302, 'enabled' => (!isModEnabled('margin') || !$user->hasRight('margins', 'liretous') || !getDolGlobalString('DISPLAY_MARGIN_RATES') ? 0 : 1)),
+		'total_mark_rate' => array('label' => 'MarkRate', 'checked' => 0, 'position' => 303, 'enabled' => (!isModEnabled('margin') || !$user->hasRight('margins', 'liretous') || !getDolGlobalString('DISPLAY_MARK_RATES') ? 0 : 1)),
+		'f.datec' => array('label' => "DateCreation", 'checked' => 0, 'position' => 500),
+		'f.tms' => array('type' => 'timestamp', 'label' => 'DateModificationShort', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 502),
+		'u.login' => array('label' => "UserAuthor", 'checked' => 1, 'visible' => -1, 'position' => 504),
+		'sale_representative' => array('label' => "SaleRepresentativesOfThirdParty", 'checked' => 0, 'position' => 506),
+		//'f.fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>506),
+		//'f.fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-1, 'notnull'=>-1, 'position'=>508),
+		//'f.fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>510),
+		//'f.fk_user_closing' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
+		'f.note_public' => array('label' => 'NotePublic', 'checked' => 0, 'position' => 520, 'enabled' => (!getDolGlobalInt('MAIN_LIST_HIDE_PUBLIC_NOTES'))),
+		'f.note_private' => array('label' => 'NotePrivate', 'checked' => 0, 'position' => 521, 'enabled' => (!getDolGlobalInt('MAIN_LIST_HIDE_PRIVATE_NOTES'))),
+		'f.fk_fac_rec_source' => array('label' => 'GeneratedFromTemplate', 'checked' => 0, 'position' => 530, 'enabled' => '1'),
+		'f.import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 999),
+		'f.fk_statut' => array('label' => "Status", 'checked' => 1, 'position' => 1000),
+	);
 
-$checkedtypetiers = 0;
-$arrayfields = array(
-	'f.ref' => array('label' => "Ref", 'checked' => 1, 'position' => 5),
-	'f.ref_client' => array('label' => "RefCustomer", 'checked' => -1, 'position' => 10),
-	'f.type' => array('label' => "Type", 'checked' => 0, 'position' => 15),
-	'f.subtype' => array('label' => "InvoiceSubtype", 'checked' => 0, 'position' => 17),
-	'f.datef' => array('label' => "DateInvoice", 'checked' => 1, 'position' => 20),
-	'f.date_valid' => array('label' => "DateValidation", 'checked' => 0, 'position' => 22),
-	'f.date_lim_reglement' => array('label' => "DateDue", 'checked' => 1, 'position' => 25),
-	'f.date_closing' => array('label' => "DateClosing", 'checked' => 0, 'position' => 30),
-	'p.ref' => array('label' => "ProjectRef", 'langs' => 'projects', 'checked' => 1, 'enabled' => (!isModEnabled('project') ? 0 : 1), 'position' => 40),
-	'p.title' => array('label' => "ProjectLabel", 'checked' => 0, 'enabled' => (!isModEnabled('project') ? 0 : 1), 'position' => 41),
-	's.nom' => array('label' => "ThirdParty", 'checked' => 1, 'position' => 50),
-	's.name_alias' => array('label' => "AliasNameShort", 'checked' => -1, 'position' => 51),
-	's.code_client' => array('label' => "CustomerCodeShort", 'checked' => -1, 'position' => 52),
-	's2.nom' => array('label' => 'ParentCompany', 'position' => 32, 'checked' => 0),
-	's.town' => array('label' => "Town", 'checked' => -1, 'position' => 55),
-	's.zip' => array('label' => "Zip", 'checked' => -1, 'position' => 60),
-	'state.nom' => array('label' => "StateShort", 'checked' => 0, 'position' => 65),
-	'country.code_iso' => array('label' => "Country", 'checked' => 0, 'position' => 70),
-	'typent.code' => array('label' => "ThirdPartyType", 'checked' => $checkedtypetiers, 'position' => 75),
-	'f.fk_mode_reglement' => array('label' => "PaymentMode", 'checked' => 1, 'position' => 80),
-	'f.fk_cond_reglement' => array('label' => "PaymentConditionsShort", 'checked' => 1, 'position' => 85),
-	'f.module_source' => array('label' => "POSModule", 'langs' => 'cashdesk', 'checked' => ($contextpage == 'poslist' ? 1 : 0), 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'position' => 90),
-	'f.pos_source' => array('label' => "POSTerminal", 'langs' => 'cashdesk', 'checked' => ($contextpage == 'poslist' ? 1 : 0), 'enabled' => "(isModEnabled('cashdesk') || isModEnabled('takepos') || getDolGlobalInt('INVOICE_SHOW_POS'))", 'position' => 91),
-	'f.total_ht' => array('label' => "AmountHT", 'checked' => 1, 'position' => 95),
-	'f.total_tva' => array('label' => "AmountVAT", 'checked' => 0, 'position' => 100),
-	'f.total_localtax1' => array('label' => $langs->transcountry("AmountLT1", $mysoc->country_code), 'checked' => 0, 'enabled' => ($mysoc->localtax1_assuj == "1"), 'position' => 110),
-	'f.total_localtax2' => array('label' => $langs->transcountry("AmountLT2", $mysoc->country_code), 'checked' => 0, 'enabled' => ($mysoc->localtax2_assuj == "1"), 'position' => 120),
-	'f.total_ttc' => array('label' => "AmountTTC", 'checked' => 0, 'position' => 130),
-	'dynamount_payed' => array('label' => "AlreadyPaid", 'checked' => 0, 'position' => 140),
-	'rtp' => array('label' => "RemainderToPay", 'checked' => 0, 'position' => 150), // Not enabled by default because slow
-	'f.multicurrency_code' => array('label' => 'Currency', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 280),
-	'f.multicurrency_tx' => array('label' => 'CurrencyRate', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 285),
-	'f.multicurrency_total_ht' => array('label' => 'MulticurrencyAmountHT', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 290),
-	'f.multicurrency_total_vat' => array('label' => 'MulticurrencyAmountVAT', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 291),
-	'f.multicurrency_total_ttc' => array('label' => 'MulticurrencyAmountTTC', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 292),
-	'multicurrency_dynamount_payed' => array('label' => 'MulticurrencyAlreadyPaid', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 295),
-	'multicurrency_rtp' => array('label' => 'MulticurrencyRemainderToPay', 'checked' => 0, 'enabled' => (!isModEnabled('multicurrency') ? 0 : 1), 'position' => 296), // Not enabled by default because slow
-	'total_pa' => array('label' => ((getDolGlobalString('MARGIN_TYPE') == '1') ? 'BuyingPrice' : 'CostPrice'), 'checked' => 0, 'position' => 300, 'enabled' => (!isModEnabled('margin') || !$user->hasRight('margins', 'liretous') ? 0 : 1)),
-	'total_margin' => array('label' => 'Margin', 'checked' => 0, 'position' => 301, 'enabled' => (!isModEnabled('margin') || !$user->hasRight('margins', 'liretous') ? 0 : 1)),
-	'total_margin_rate' => array('label' => 'MarginRate', 'checked' => 0, 'position' => 302, 'enabled' => (!isModEnabled('margin') || !$user->hasRight('margins', 'liretous') || !getDolGlobalString('DISPLAY_MARGIN_RATES') ? 0 : 1)),
-	'total_mark_rate' => array('label' => 'MarkRate', 'checked' => 0, 'position' => 303, 'enabled' => (!isModEnabled('margin') || !$user->hasRight('margins', 'liretous') || !getDolGlobalString('DISPLAY_MARK_RATES') ? 0 : 1)),
-	'f.datec' => array('label' => "DateCreation", 'checked' => 0, 'position' => 500),
-	'f.tms' => array('type' => 'timestamp', 'label' => 'DateModificationShort', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 502),
-	'u.login' => array('label' => "UserAuthor", 'checked' => 1, 'visible' => -1, 'position' => 504),
-	'sale_representative' => array('label' => "SaleRepresentativesOfThirdParty", 'checked' => 0, 'position' => 506),
-	//'f.fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>506),
-	//'f.fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-1, 'notnull'=>-1, 'position'=>508),
-	//'f.fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>510),
-	//'f.fk_user_closing' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
-	'f.note_public' => array('label' => 'NotePublic', 'checked' => 0, 'position' => 520, 'enabled' => (!getDolGlobalInt('MAIN_LIST_HIDE_PUBLIC_NOTES'))),
-	'f.note_private' => array('label' => 'NotePrivate', 'checked' => 0, 'position' => 521, 'enabled' => (!getDolGlobalInt('MAIN_LIST_HIDE_PRIVATE_NOTES'))),
-	'f.fk_fac_rec_source' => array('label' => 'GeneratedFromTemplate', 'checked' => 0, 'position' => 530, 'enabled' => '1'),
-	'f.import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 999),
-	'f.fk_statut' => array('label' => "Status", 'checked' => 1, 'position' => 1000),
-);
+	if (getDolGlobalString("INVOICE_USE_SITUATION") && getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
+		$arrayfields['f.retained_warranty'] = array('label' => $langs->trans("RetainedWarranty"), 'checked' => 0, 'position' => 86);
+	}
 
-if (getDolGlobalString("INVOICE_USE_SITUATION") && getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
-	$arrayfields['f.retained_warranty'] = array('label' => $langs->trans("RetainedWarranty"), 'checked' => 0, 'position' => 86);
-}
+	$subtypearray = $object->getArrayOfInvoiceSubtypes(0);
+	if (empty($subtypearray)) {
+		unset($arrayfields['f.subtype']);
+	}
 
-$subtypearray = $object->getArrayOfInvoiceSubtypes(0);
-if (empty($subtypearray)) {
-	unset($arrayfields['f.subtype']);
-}
+	// Overwrite $arrayfields from columns into ->fields (transition before removal of $arrayoffields)
+	foreach ($object->fields as $key => $val) {
+		// If $val['visible']==0, then we never show the field
 
-// Overwrite $arrayfields from columns into ->fields (transition before removal of $arrayoffields)
-foreach ($object->fields as $key => $val) {
-	// If $val['visible']==0, then we never show the field
-
-	if (!empty($val['visible'])) {
-		$visible = (int) dol_eval((string) $val['visible'], 1, 1, '1');
-		$newkey = '';
-		if (array_key_exists($key, $arrayfields)) {
-			$newkey = $key;
-		} elseif (array_key_exists('f.'.$key, $arrayfields)) {
-			$newkey = 'f.'.$key;
-		} elseif (array_key_exists('s.'.$key, $arrayfields)) {
-			$newkey = 's.'.$key;
-		}
-		if ($newkey) {
-			$arrayfields[$newkey] = array(
-				'label' => $val['label'],
-				'checked' => (($visible < 0) ? 0 : 1),
-				'enabled' => (abs($visible) != 3 && (bool) dol_eval($val['enabled'], 1)),
-				'position' => $val['position'],
-				'help' => empty($val['help']) ? '' : $val['help'],
-			);
+		if (!empty($val['visible'])) {
+			$visible = (int) dol_eval((string) $val['visible'], 1, 1, '1');
+			$newkey = '';
+			if (array_key_exists($key, $arrayfields)) {
+				$newkey = $key;
+			} elseif (array_key_exists('f.' . $key, $arrayfields)) {
+				$newkey = 'f.' . $key;
+			} elseif (array_key_exists('s.' . $key, $arrayfields)) {
+				$newkey = 's.' . $key;
+			}
+			if ($newkey) {
+				$arrayfields[$newkey] = array(
+					'label' => $val['label'],
+					'checked' => (($visible < 0) ? 0 : 1),
+					'enabled' => (abs($visible) != 3 && (bool) dol_eval($val['enabled'], 1)),
+					'position' => $val['position'],
+					'help' => empty($val['help']) ? '' : $val['help'],
+				);
+			}
 		}
 	}
-}
-// Extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
+	// Extra fields
+	include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';
 
 
-$object->fields = dol_sort_array($object->fields, 'position');
-$arrayfields = dol_sort_array($arrayfields, 'position');
-'@phan-var-force array<string,array{label:string,checked?:int<0,1>,position?:int,help?:string}> $arrayfields';  // dol_sort_array looses type for Phan
+	$object->fields = dol_sort_array($object->fields, 'position');
+	$arrayfields = dol_sort_array($arrayfields, 'position');
+	'@phan-var-force array<string,array{label:string,checked?:int<0,1>,position?:int,help?:string}> $arrayfields';  // dol_sort_array looses type for Phan
 
-// Check only if it's an internal user, external users are already filtered by $socid
-if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
-	$search_sale = $user->id;
-}
+	// Check only if it's an internal user, external users are already filtered by $socid
+	if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
+		$search_sale = $user->id;
+	}
 
-// Security check
-$fieldid = (!empty($ref) ? 'ref' : 'rowid');
-if (!empty($user->socid)) {
-	$socid = $user->socid;
-}
-if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
-	$search_sale = $user->id;
-}
+	// Security check
+	$fieldid = (!empty($ref) ? 'ref' : 'rowid');
+	if (!empty($user->socid)) {
+		$socid = $user->socid;
+	}
+	if (empty($user->socid) && !$user->hasRight('societe', 'client', 'voir')) {
+		$search_sale = $user->id;
+	}
 
-$result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid);
+	$result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid);
 
 
-/*
+	/*
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) {
-	$action = 'list';
-	$massaction = '';
-}
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
-	$massaction = '';
-}
-
-$parameters = array('socid' => $socid, 'arrayfields' => &$arrayfields);
-$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');
-}
-
-include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
-
-// Do we click on purge search criteria ?
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha')) { // All tests are required to be compatible with all browsers
-	$search_user = '';
-	$search_sale = '';
-	$search_product_category = '';
-	$search_ref = '';
-	$search_refcustomer = '';
-	$search_type = '';
-	$search_subtype = '';
-	$search_project_ref = '';
-	$search_project = '';
-	$search_company = '';
-	$search_company_alias = '';
-	$search_parent_name = '';
-	$search_montant_ht = '';
-	$search_montant_vat = '';
-	$search_montant_localtax1 = '';
-	$search_montant_localtax2 = '';
-	$search_montant_ttc = '';
-	$search_login = '';
-	$search_multicurrency_code = '';
-	$search_multicurrency_tx = '';
-	$search_multicurrency_montant_ht = '';
-	$search_multicurrency_montant_vat = '';
-	$search_multicurrency_montant_ttc = '';
-	$search_status = '';
-	$search_paymentmode = '';
-	$search_paymentterms = '';
-	$search_module_source = '';
-	$search_pos_source = '';
-	$search_town = '';
-	$search_zip = "";
-	$search_state = "";
-	$search_country = '';
-	$search_type_thirdparty = '';
-	$search_customer_code = '';
-	$search_date_startday = '';
-	$search_date_startmonth = '';
-	$search_date_startyear = '';
-	$search_date_endday = '';
-	$search_date_endmonth = '';
-	$search_date_endyear = '';
-	$search_date_start = '';
-	$search_date_end = '';
-	$search_date_valid_startday = '';
-	$search_date_valid_startmonth = '';
-	$search_date_valid_startyear = '';
-	$search_date_valid_endday = '';
-	$search_date_valid_endmonth = '';
-	$search_date_valid_endyear = '';
-	$search_date_valid_start = '';
-	$search_date_valid_end = '';
-	$search_datelimit_startday = '';
-	$search_datelimit_startmonth = '';
-	$search_datelimit_startyear = '';
-	$search_datelimit_endday = '';
-	$search_datelimit_endmonth = '';
-	$search_datelimit_endyear = '';
-	$search_datelimit_start = '';
-	$search_datelimit_end = '';
-	$search_fac_rec_source_title = '';
-	$search_option = '';
-	$search_import_key = '';
-	$search_categ_cus = 0;
-
-	$search_all = '';
-	$toselect = array();
-	$search_array_options = array();
-}
+	if (GETPOST('cancel', 'alpha')) {
+		$action = 'list';
+		$massaction = '';
+	}
+	if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+		$massaction = '';
+	}
+
+	$parameters = array('socid' => $socid, 'arrayfields' => &$arrayfields);
+	$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');
+	}
+
+	include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php';
+
+	// Do we click on purge search criteria ?
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha')) { // All tests are required to be compatible with all browsers
+		$search_user = '';
+		$search_sale = '';
+		$search_product_category = '';
+		$search_ref = '';
+		$search_refcustomer = '';
+		$search_type = '';
+		$search_subtype = '';
+		$search_project_ref = '';
+		$search_project = '';
+		$search_company = '';
+		$search_company_alias = '';
+		$search_parent_name = '';
+		$search_montant_ht = '';
+		$search_montant_vat = '';
+		$search_montant_localtax1 = '';
+		$search_montant_localtax2 = '';
+		$search_montant_ttc = '';
+		$search_login = '';
+		$search_multicurrency_code = '';
+		$search_multicurrency_tx = '';
+		$search_multicurrency_montant_ht = '';
+		$search_multicurrency_montant_vat = '';
+		$search_multicurrency_montant_ttc = '';
+		$search_status = '';
+		$search_paymentmode = '';
+		$search_paymentterms = '';
+		$search_module_source = '';
+		$search_pos_source = '';
+		$search_town = '';
+		$search_zip = "";
+		$search_state = "";
+		$search_country = '';
+		$search_type_thirdparty = '';
+		$search_customer_code = '';
+		$search_date_startday = '';
+		$search_date_startmonth = '';
+		$search_date_startyear = '';
+		$search_date_endday = '';
+		$search_date_endmonth = '';
+		$search_date_endyear = '';
+		$search_date_start = '';
+		$search_date_end = '';
+		$search_date_valid_startday = '';
+		$search_date_valid_startmonth = '';
+		$search_date_valid_startyear = '';
+		$search_date_valid_endday = '';
+		$search_date_valid_endmonth = '';
+		$search_date_valid_endyear = '';
+		$search_date_valid_start = '';
+		$search_date_valid_end = '';
+		$search_datelimit_startday = '';
+		$search_datelimit_startmonth = '';
+		$search_datelimit_startyear = '';
+		$search_datelimit_endday = '';
+		$search_datelimit_endmonth = '';
+		$search_datelimit_endyear = '';
+		$search_datelimit_start = '';
+		$search_datelimit_end = '';
+		$search_fac_rec_source_title = '';
+		$search_option = '';
+		$search_import_key = '';
+		$search_categ_cus = 0;
+
+		$search_all = '';
+		$toselect = array();
+		$search_array_options = array();
+	}
+
+	if (empty($reshook)) {
+		$objectclass = 'Facture';
+		$objectlabel = 'Invoices';
+		$permissiontoread = $user->hasRight("facture", "lire");
+		$permissiontoadd = $user->hasRight("facture", "creer");
+		$permissiontodelete = $user->hasRight("facture", "supprimer");
+		$uploaddir = $conf->facture->dir_output;
+		include DOL_DOCUMENT_ROOT . '/core/actions_massactions.inc.php';
+	}
 
-if (empty($reshook)) {
-	$objectclass = 'Facture';
-	$objectlabel = 'Invoices';
-	$permissiontoread = $user->hasRight("facture", "lire");
-	$permissiontoadd = $user->hasRight("facture", "creer");
-	$permissiontodelete = $user->hasRight("facture", "supprimer");
-	$uploaddir = $conf->facture->dir_output;
-	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
-}
+	if ($action == 'makepayment_confirm' && $user->hasRight('facture', 'paiement')) {
+		require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
+		$arrayofselected = is_array($toselect) ? $toselect : array();
+		if (!empty($arrayofselected)) {
+			$bankid = GETPOSTINT('bankid');
+			$paiementid = GETPOSTINT('paiementid');
+			$paiementdate = dol_mktime(12, 0, 0, GETPOSTINT('datepaimentmonth'), GETPOSTINT('datepaimentday'), GETPOSTINT('datepaimentyear'));
+			if (empty($paiementdate)) {
+				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
+				$error++;
+				$action = 'makepayment';
+			}
+
+			if (!$error) {
+				foreach ($arrayofselected as $toselectid) {
+					$errorpayment = 0;
+					$facture = new Facture($db);
+					$result = $facture->fetch($toselectid);
 
-if ($action == 'makepayment_confirm' && $user->hasRight('facture', 'paiement')) {
-	require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
-	$arrayofselected = is_array($toselect) ? $toselect : array();
-	if (!empty($arrayofselected)) {
-		$bankid = GETPOSTINT('bankid');
-		$paiementid = GETPOSTINT('paiementid');
-		$paiementdate = dol_mktime(12, 0, 0, GETPOSTINT('datepaimentmonth'), GETPOSTINT('datepaimentday'), GETPOSTINT('datepaimentyear'));
-		if (empty($paiementdate)) {
-			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
-			$error++;
-			$action = 'makepayment';
-		}
+					$db->begin();
 
-		if (!$error) {
-			foreach ($arrayofselected as $toselectid) {
-				$errorpayment = 0;
-				$facture = new Facture($db);
-				$result = $facture->fetch($toselectid);
-
-				$db->begin();
-
-				if ($result < 0) {
-					setEventMessage($facture->error, 'errors');
-					$errorpayment++;
-				} else {
-					if ($facture->type != Facture::TYPE_CREDIT_NOTE && $facture->status == Facture::STATUS_VALIDATED && $facture->paye == 0) {
-						$paiementAmount = $facture->getSommePaiement();
-						$totalcreditnotes = $facture->getSumCreditNotesUsed();
-						$totaldeposits = $facture->getSumDepositsUsed();
-
-						$totalallpayments = $paiementAmount + $totalcreditnotes + $totaldeposits;
-						$remaintopay = price2num($facture->total_ttc - $totalallpayments);
-
-						// hook to finalize the remaining amount, considering e.g. cash discount agreements
-						$parameters = array('remaintopay' => $remaintopay);
-						$reshook = $hookmanager->executeHooks('finalizeAmountOfInvoice', $parameters, $facture, $action); // Note that $action and $object may have been modified by some hooks
-						if ($reshook > 0) {
-							if (!empty($remain = $hookmanager->resArray['remaintopay'])) {
-								$remaintopay = $remain;
+					if ($result < 0) {
+						setEventMessage($facture->error, 'errors');
+						$errorpayment++;
+					} else {
+						if ($facture->type != Facture::TYPE_CREDIT_NOTE && $facture->status == Facture::STATUS_VALIDATED && $facture->paye == 0) {
+							$paiementAmount = $facture->getSommePaiement();
+							$totalcreditnotes = $facture->getSumCreditNotesUsed();
+							$totaldeposits = $facture->getSumDepositsUsed();
+
+							$totalallpayments = $paiementAmount + $totalcreditnotes + $totaldeposits;
+							$remaintopay = price2num($facture->total_ttc - $totalallpayments);
+
+							// hook to finalize the remaining amount, considering e.g. cash discount agreements
+							$parameters = array('remaintopay' => $remaintopay);
+							$reshook = $hookmanager->executeHooks('finalizeAmountOfInvoice', $parameters, $facture, $action); // Note that $action and $object may have been modified by some hooks
+							if ($reshook > 0) {
+								if (!empty($remain = $hookmanager->resArray['remaintopay'])) {
+									$remaintopay = $remain;
+								}
+							} elseif ($reshook < 0) {
+								$error++;
+								setEventMessages($facture->ref . ' ' . $langs->trans("ProcessingError"), $hookmanager->errors, 'errors');
 							}
-						} elseif ($reshook < 0) {
-							$error++;
-							setEventMessages($facture->ref.' '.$langs->trans("ProcessingError"), $hookmanager->errors, 'errors');
-						}
 
-						if ($remaintopay != 0) {
-							$resultBank = $facture->setBankAccount($bankid);
-							if ($resultBank < 0) {
-								setEventMessages($facture->error, null, 'errors');
-								$errorpayment++;
-							} else {
-								$paiement = new Paiement($db);
-								$paiement->datepaye = $paiementdate;
-								$paiement->amounts[$facture->id] = $remaintopay; // Array with all payments dispatching with invoice id
-								$paiement->multicurrency_amounts[$facture->id] = $remaintopay;
-								$paiement->paiementid = $paiementid;
-								$paiement_id = $paiement->create($user, 1, $facture->thirdparty);
-								if ($paiement_id < 0) {
-									$langs->load("errors");
-									setEventMessages($facture->ref.' '.$langs->trans($paiement->error), $paiement->errors, 'errors');
+							if ($remaintopay != 0) {
+								$resultBank = $facture->setBankAccount($bankid);
+								if ($resultBank < 0) {
+									setEventMessages($facture->error, null, 'errors');
 									$errorpayment++;
 								} else {
-									$result = $paiement->addPaymentToBank($user, 'payment', '', $bankid, '', '');
-									if ($result < 0) {
+									$paiement = new Paiement($db);
+									$paiement->datepaye = $paiementdate;
+									$paiement->amounts[$facture->id] = $remaintopay; // Array with all payments dispatching with invoice id
+									$paiement->multicurrency_amounts[$facture->id] = $remaintopay;
+									$paiement->paiementid = $paiementid;
+									$paiement_id = $paiement->create($user, 1, $facture->thirdparty);
+									if ($paiement_id < 0) {
 										$langs->load("errors");
-										setEventMessages($facture->ref.' '.$langs->trans($paiement->error), $paiement->errors, 'errors');
+										setEventMessages($facture->ref . ' ' . $langs->trans($paiement->error), $paiement->errors, 'errors');
 										$errorpayment++;
+									} else {
+										$result = $paiement->addPaymentToBank($user, 'payment', '', $bankid, '', '');
+										if ($result < 0) {
+											$langs->load("errors");
+											setEventMessages($facture->ref . ' ' . $langs->trans($paiement->error), $paiement->errors, 'errors');
+											$errorpayment++;
+										}
 									}
 								}
+							} else {
+								setEventMessage($langs->trans('NoPaymentAvailable', $facture->ref), 'warnings');
+								$errorpayment++;
 							}
 						} else {
-							setEventMessage($langs->trans('NoPaymentAvailable', $facture->ref), 'warnings');
+							setEventMessage($langs->trans('BulkPaymentNotPossibleForInvoice', $facture->ref), 'warnings');
 							$errorpayment++;
 						}
-					} else {
-						setEventMessage($langs->trans('BulkPaymentNotPossibleForInvoice', $facture->ref), 'warnings');
-						$errorpayment++;
 					}
-				}
 
-				if (empty($errorpayment)) {
-					setEventMessage($langs->trans('PaymentRegisteredAndInvoiceSetToPaid', $facture->ref));
-					$db->commit();
-				} else {
-					$db->rollback();
+					if (empty($errorpayment)) {
+						setEventMessage($langs->trans('PaymentRegisteredAndInvoiceSetToPaid', $facture->ref));
+						$db->commit();
+					} else {
+						$db->rollback();
+					}
 				}
 			}
 		}
-	}
-} elseif ($massaction == 'withdrawrequest') {
-	$langs->load("withdrawals");
+	} elseif ($massaction == 'withdrawrequest') {
+		$langs->load("withdrawals");
 
-	if (!$user->hasRight('prelevement', 'bons', 'creer')) {
-		$error++;
-		setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
-	} else {
-		//Checking error
-		$error = 0;
+		if (!$user->hasRight('prelevement', 'bons', 'creer')) {
+			$error++;
+			setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
+		} else {
+			//Checking error
+			$error = 0;
 
-		$arrayofselected = is_array($toselect) ? $toselect : array();
-		$listofbills = array();
-		foreach ($arrayofselected as $toselectid) {
-			$objecttmp = new Facture($db);
-			$result = $objecttmp->fetch($toselectid);
-			if ($result > 0) {
-				$totalpaid = $objecttmp->getSommePaiement();
-				$totalcreditnotes = $objecttmp->getSumCreditNotesUsed();
-				$totaldeposits = $objecttmp->getSumDepositsUsed();
-				$objecttmp->resteapayer = price2num($objecttmp->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
-
-				// hook to finalize the remaining amount, considering e.g. cash discount agreements
-				$parameters = array('remaintopay' => $objecttmp->resteapayer);
-				$reshook = $hookmanager->executeHooks('finalizeAmountOfInvoice', $parameters, $objecttmp, $action); // Note that $action and $object may have been modified by some hooks
-				if ($reshook > 0) {
-					if (!empty($remaintopay = $hookmanager->resArray['remaintopay'])) {
-						$objecttmp->resteapayer = $remaintopay;
-					}
-				} elseif ($reshook < 0) {
-					$error++;
-					setEventMessages($objecttmp->ref.' '.$langs->trans("ProcessingError"), $hookmanager->errors, 'errors');
-				}
-
-				if ($objecttmp->statut == Facture::STATUS_DRAFT) {
-					$error++;
-					setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors');
-				} elseif ($objecttmp->paye || $objecttmp->resteapayer == 0) {
-					$error++;
-					setEventMessages($objecttmp->ref.' '.$langs->trans("AlreadyPaid"), $objecttmp->errors, 'errors');
-				} elseif ($objecttmp->resteapayer < 0) {
-					$error++;
-					setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors');
-				}
-
-				$rsql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande";
-				$rsql .= " , pfd.date_traite as date_traite";
-				$rsql .= " , pfd.amount";
-				$rsql .= " , u.rowid as user_id, u.lastname, u.firstname, u.login";
-				$rsql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pfd";
-				$rsql .= " , ".MAIN_DB_PREFIX."user as u";
-				$rsql .= " WHERE fk_facture = ".((int) $objecttmp->id);
-				$rsql .= " AND pfd.fk_user_demande = u.rowid";
-				$rsql .= " AND pfd.traite = 0";
-				$rsql .= " ORDER BY pfd.date_demande DESC";
-
-				$result_sql = $db->query($rsql);
-				if ($result_sql) {
-					$numprlv = $db->num_rows($result_sql);
-				} else {
-					$numprlv = 0;
-				}
+			$arrayofselected = is_array($toselect) ? $toselect : array();
+			$listofbills = array();
+			foreach ($arrayofselected as $toselectid) {
+				$objecttmp = new Facture($db);
+				$result = $objecttmp->fetch($toselectid);
+				if ($result > 0) {
+					$totalpaid = $objecttmp->getSommePaiement();
+					$totalcreditnotes = $objecttmp->getSumCreditNotesUsed();
+					$totaldeposits = $objecttmp->getSumDepositsUsed();
+					$objecttmp->resteapayer = price2num($objecttmp->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
+
+					// hook to finalize the remaining amount, considering e.g. cash discount agreements
+					$parameters = array('remaintopay' => $objecttmp->resteapayer);
+					$reshook = $hookmanager->executeHooks('finalizeAmountOfInvoice', $parameters, $objecttmp, $action); // Note that $action and $object may have been modified by some hooks
+					if ($reshook > 0) {
+						if (!empty($remaintopay = $hookmanager->resArray['remaintopay'])) {
+							$objecttmp->resteapayer = $remaintopay;
+						}
+					} elseif ($reshook < 0) {
+						$error++;
+						setEventMessages($objecttmp->ref . ' ' . $langs->trans("ProcessingError"), $hookmanager->errors, 'errors');
+					}
 
-				if ($numprlv > 0) {
-					$error++;
-					setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'warnings');
-				} elseif (!empty($objecttmp->mode_reglement_code) && $objecttmp->mode_reglement_code != 'PRE') {
-					$langs->load("errors");
-					$error++;
-					setEventMessages($objecttmp->ref.' '.$langs->trans("ErrorThisPaymentModeIsNotDirectDebit"), $objecttmp->errors, 'errors');
-				} else {
-					$listofbills[] = $objecttmp; // $listofbills will only contains invoices with good payment method and no request already done
+					if ($objecttmp->statut == Facture::STATUS_DRAFT) {
+						$error++;
+						setEventMessages($objecttmp->ref . ' ' . $langs->trans("Draft"), $objecttmp->errors, 'errors');
+					} elseif ($objecttmp->paye || $objecttmp->resteapayer == 0) {
+						$error++;
+						setEventMessages($objecttmp->ref . ' ' . $langs->trans("AlreadyPaid"), $objecttmp->errors, 'errors');
+					} elseif ($objecttmp->resteapayer < 0) {
+						$error++;
+						setEventMessages($objecttmp->ref . ' ' . $langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors');
+					}
+
+					$rsql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande";
+					$rsql .= " , pfd.date_traite as date_traite";
+					$rsql .= " , pfd.amount";
+					$rsql .= " , u.rowid as user_id, u.lastname, u.firstname, u.login";
+					$rsql .= " FROM " . MAIN_DB_PREFIX . "prelevement_demande as pfd";
+					$rsql .= " , " . MAIN_DB_PREFIX . "user as u";
+					$rsql .= " WHERE fk_facture = " . ((int) $objecttmp->id);
+					$rsql .= " AND pfd.fk_user_demande = u.rowid";
+					$rsql .= " AND pfd.traite = 0";
+					$rsql .= " ORDER BY pfd.date_demande DESC";
+
+					$result_sql = $db->query($rsql);
+					if ($result_sql) {
+						$numprlv = $db->num_rows($result_sql);
+					} else {
+						$numprlv = 0;
+					}
+
+					if ($numprlv > 0) {
+						$error++;
+						setEventMessages($objecttmp->ref . ' ' . $langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'warnings');
+					} elseif (!empty($objecttmp->mode_reglement_code) && $objecttmp->mode_reglement_code != 'PRE') {
+						$langs->load("errors");
+						$error++;
+						setEventMessages($objecttmp->ref . ' ' . $langs->trans("ErrorThisPaymentModeIsNotDirectDebit"), $objecttmp->errors, 'errors');
+					} else {
+						$listofbills[] = $objecttmp; // $listofbills will only contains invoices with good payment method and no request already done
+					}
 				}
 			}
-		}
 
-		//Massive withdraw request for request with no errors
-		if (!empty($listofbills)) {
-			$nbwithdrawrequestok = 0;
-			foreach ($listofbills as $aBill) {
-				$db->begin();
-				$result = $aBill->demande_prelevement($user, $aBill->resteapayer, 'direct-debit', 'facture');
-				if ($result > 0) {
-					$db->commit();
-					$nbwithdrawrequestok++;
-				} else {
-					$db->rollback();
-					setEventMessages($aBill->error, $aBill->errors, 'errors');
+			//Massive withdraw request for request with no errors
+			if (!empty($listofbills)) {
+				$nbwithdrawrequestok = 0;
+				foreach ($listofbills as $aBill) {
+					$db->begin();
+					$result = $aBill->demande_prelevement($user, $aBill->resteapayer, 'direct-debit', 'facture');
+					if ($result > 0) {
+						$db->commit();
+						$nbwithdrawrequestok++;
+					} else {
+						$db->rollback();
+						setEventMessages($aBill->error, $aBill->errors, 'errors');
+					}
+				}
+				if ($nbwithdrawrequestok > 0) {
+					setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs');
 				}
-			}
-			if ($nbwithdrawrequestok > 0) {
-				setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs');
 			}
 		}
 	}
-}
 
 
 
-/*
+	/*
  * View
  */
 
-$form = new Form($db);
-$formother = new FormOther($db);
-$formfile = new FormFile($db);
-$formmargin = null;
-if (isModEnabled('margin')) {
-	$formmargin = new FormMargin($db);
-}
-$bankaccountstatic = new Account($db);
-$facturestatic = new Facture($db);
-$formcompany = new FormCompany($db);
-$companystatic = new Societe($db);
-$companyparent = new Societe($db);
-
-$company_url_list = array();
-
-if ($socid > 0) {
-	$soc = new Societe($db);
-	$soc->fetch($socid);
-	if (empty($search_company)) {
-		$search_company = $soc->name;
+	$form = new Form($db);
+	$formother = new FormOther($db);
+	$formfile = new FormFile($db);
+	$formmargin = null;
+	if (isModEnabled('margin')) {
+		$formmargin = new FormMargin($db);
+	}
+	$bankaccountstatic = new Account($db);
+	$facturestatic = new Facture($db);
+	$formcompany = new FormCompany($db);
+	$companystatic = new Societe($db);
+	$companyparent = new Societe($db);
+
+	$company_url_list = array();
+
+	if ($socid > 0) {
+		$soc = new Societe($db);
+		$soc->fetch($socid);
+		if (empty($search_company)) {
+			$search_company = $soc->name;
+		}
+	} else {
+		$soc = null;
 	}
-} else {
-	$soc = null;
-}
 
-$title = $langs->trans('BillsCustomers').' '.(($socid > 0 && $soc !== null) ? ' - '.$soc->name : '');
-$help_url = 'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes';
+	$title = $langs->trans('BillsCustomers') . ' ' . (($socid > 0 && $soc !== null) ? ' - ' . $soc->name : '');
+	$help_url = 'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes';
 
-$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
-$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
+	$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
+	$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
 
-// Build and execute select
-// --------------------------------------------------------------------
-$sql = 'SELECT';
-if ($search_all) {
-	$sql = 'SELECT DISTINCT';
-}
-$sql .= ' f.rowid as id, f.ref, f.ref_client, f.fk_soc, f.type, f.subtype, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.fk_cond_reglement, f.total_ht, f.total_tva, f.total_ttc,';
-$sql .= ' f.localtax1 as total_localtax1, f.localtax2 as total_localtax2,';
-$sql .= ' f.fk_user_author,';
-$sql .= ' f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva as multicurrency_total_vat, f.multicurrency_total_ttc,';
-$sql .= ' f.datef, f.date_valid, f.date_lim_reglement as datelimite, f.module_source, f.pos_source,';
-$sql .= ' f.paye as paye, f.fk_statut, f.import_key, f.close_code,';
-$sql .= ' f.datec as date_creation, f.tms as date_modification, f.date_closing as date_closing,';
-$sql .= ' f.retained_warranty, f.retained_warranty_date_limit, f.situation_final, f.situation_cycle_ref, f.situation_counter,';
-$sql .= ' s.rowid as socid, s.nom as name, s.name_alias as alias, s.email, s.phone, s.fax, s.address, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta as code_compta_client, s.code_compta_fournisseur,';
-$sql .= " s.parent as fk_parent,";
-$sql .= " s2.nom as name2,";
-$sql .= ' typent.code as typent_code,';
-$sql .= ' state.code_departement as state_code, state.nom as state_name,';
-$sql .= ' country.code as country_code,';
-$sql .= ' f.fk_fac_rec_source,';
-$sql .= ' p.rowid as project_id, p.ref as project_ref, p.title as project_label,';
-$sql .= ' u.login, u.lastname, u.firstname, u.email as user_email, u.statut as user_statut, u.entity, u.photo, u.office_phone, u.office_fax, u.user_mobile, u.job, u.gender';
-// We need dynamount_payed to be able to sort on status (value is surely wrong because we can count several lines several times due to other left join or link with contacts. But what we need is just 0 or > 0).
-// A Better solution to be able to sort on already paid or remain to pay is to store amount_payed in a denormalized field.
-// We disable this. It create a bug when searching with search_all and sorting on status. Also it create performance troubles.
-/*
+	// Build and execute select
+	// --------------------------------------------------------------------
+	$sql = 'SELECT';
+	if ($search_all) {
+		$sql = 'SELECT DISTINCT';
+	}
+	$sql .= ' f.rowid as id, f.ref, f.ref_client, f.fk_soc, f.type, f.subtype, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.fk_cond_reglement, f.total_ht, f.total_tva, f.total_ttc,';
+	$sql .= ' f.localtax1 as total_localtax1, f.localtax2 as total_localtax2,';
+	$sql .= ' f.fk_user_author,';
+	$sql .= ' f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva as multicurrency_total_vat, f.multicurrency_total_ttc,';
+	$sql .= ' f.datef, f.date_valid, f.date_lim_reglement as datelimite, f.module_source, f.pos_source,';
+	$sql .= ' f.paye as paye, f.fk_statut, f.import_key, f.close_code,';
+	$sql .= ' f.datec as date_creation, f.tms as date_modification, f.date_closing as date_closing,';
+	$sql .= ' f.retained_warranty, f.retained_warranty_date_limit, f.situation_final, f.situation_cycle_ref, f.situation_counter,';
+	$sql .= ' s.rowid as socid, s.nom as name, s.name_alias as alias, s.email, s.phone, s.fax, s.address, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta as code_compta_client, s.code_compta_fournisseur,';
+	$sql .= " s.parent as fk_parent,";
+	$sql .= " s2.nom as name2,";
+	$sql .= ' typent.code as typent_code,';
+	$sql .= ' state.code_departement as state_code, state.nom as state_name,';
+	$sql .= ' country.code as country_code,';
+	$sql .= ' f.fk_fac_rec_source,';
+	$sql .= ' p.rowid as project_id, p.ref as project_ref, p.title as project_label,';
+	$sql .= ' u.login, u.lastname, u.firstname, u.email as user_email, u.statut as user_statut, u.entity, u.photo, u.office_phone, u.office_fax, u.user_mobile, u.job, u.gender';
+	// We need dynamount_payed to be able to sort on status (value is surely wrong because we can count several lines several times due to other left join or link with contacts. But what we need is just 0 or > 0).
+	// A Better solution to be able to sort on already paid or remain to pay is to store amount_payed in a denormalized field.
+	// We disable this. It create a bug when searching with search_all and sorting on status. Also it create performance troubles.
+	/*
 if (!$search_all) {
 	$sql .= ', SUM(pf.amount) as dynamount_payed, SUM(pf.multicurrency_amount) as multicurrency_dynamount_payed';
 }
 */
-// Add fields from extrafields
-if (!empty($extrafields->attributes[$object->table_element]['label'])) {
-	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
-		$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : '');
+	// Add fields from extrafields
+	if (!empty($extrafields->attributes[$object->table_element]['label'])) {
+		foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
+			$sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef." . $key . " as options_" . $key : '');
+		}
+	}
+	// Add fields from hooks
+	$parameters = array();
+	$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	$sql .= $hookmanager->resPrint;
+	$sql = preg_replace('/,\s*$/', '', $sql);
+
+	$sqlfields = $sql; // $sql fields to remove for count total
+
+	$sql .= ' FROM ' . MAIN_DB_PREFIX . 'societe as s';
+	$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s2 ON s2.rowid = s.parent";
+	$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as country on (country.rowid = s.fk_pays)";
+	$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_typent as typent on (typent.id = s.fk_typent)";
+	$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_departements as state on (state.rowid = s.fk_departement)";
+	$sql .= ', ' . MAIN_DB_PREFIX . 'facture as f';
+	if ($sortfield == "f.datef") {
+		$sql .= $db->hintindex('idx_facture_datef');
+	}
+	if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
+		$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $object->table_element . "_extrafields as ef on (f.rowid = ef.fk_object)";
+	}
+	if ($search_all) {
+		$sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'facturedet as pd ON f.rowid = pd.fk_facture';
+	}
+	if (!empty($search_fac_rec_source_title)) {
+		$sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'facture_rec as facrec ON f.fk_fac_rec_source = facrec.rowid';
+	}
+	$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "projet as p ON p.rowid = f.fk_projet";
+	$sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'user AS u ON f.fk_user_author = u.rowid';
+	// Add table from hooks
+	$parameters = array();
+	$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
+	$sql .= $hookmanager->resPrint;
+
+	$sql .= ' WHERE f.fk_soc = s.rowid';
+	$sql .= ' AND f.entity IN (' . getEntity('invoice') . ')';
+	if ($socid > 0) {
+		$sql .= ' AND s.rowid = ' . ((int) $socid);
+	}
+	if ($userid) {
+		if ($userid == -1) {
+			$sql .= ' AND f.fk_user_author IS NULL';
+		} else {
+			$sql .= ' AND f.fk_user_author = ' . ((int) $userid);
+		}
 	}
-}
-// Add fields from hooks
-$parameters = array();
-$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-$sql .= $hookmanager->resPrint;
-$sql = preg_replace('/,\s*$/', '', $sql);
-
-$sqlfields = $sql; // $sql fields to remove for count total
-
-$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s2 ON s2.rowid = s.parent";
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)";
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)";
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)";
-$sql .= ', '.MAIN_DB_PREFIX.'facture as f';
-if ($sortfield == "f.datef") {
-	$sql .= $db->hintindex('idx_facture_datef');
-}
-if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
-	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)";
-}
-if ($search_all) {
-	$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as pd ON f.rowid = pd.fk_facture';
-}
-if (!empty($search_fac_rec_source_title)) {
-	$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_rec as facrec ON f.fk_fac_rec_source = facrec.rowid';
-}
-$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = f.fk_projet";
-$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user AS u ON f.fk_user_author = u.rowid';
-// Add table from hooks
-$parameters = array();
-$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
-$sql .= $hookmanager->resPrint;
-
-$sql .= ' WHERE f.fk_soc = s.rowid';
-$sql .= ' AND f.entity IN ('.getEntity('invoice').')';
-if ($socid > 0) {
-	$sql .= ' AND s.rowid = '.((int) $socid);
-}
-if ($userid) {
-	if ($userid == -1) {
-		$sql .= ' AND f.fk_user_author IS NULL';
-	} else {
-		$sql .= ' AND f.fk_user_author = '.((int) $userid);
+	if ($search_ref) {
+		$sql .= natural_search('f.ref', $search_ref);
 	}
-}
-if ($search_ref) {
-	$sql .= natural_search('f.ref', $search_ref);
-}
-if ($search_refcustomer) {
-	$sql .= natural_search('f.ref_client', $search_refcustomer);
-}
-if ($search_type != '' && $search_type != '-1') {
-	$sql .= " AND f.type IN (".$db->sanitize($db->escape($search_type)).")";
-}
-if ($search_subtype != '' && $search_subtype != '-1') {
-	$sql .= " AND f.subtype IN (".$db->sanitize($db->escape($search_subtype)).")";
-}
-if ($search_project_ref) {
-	$sql .= natural_search('p.ref', $search_project_ref);
-}
-if ($search_project) {
-	$sql .= natural_search('p.title', $search_project);
-}
-if (empty($arrayfields['s.name_alias']['checked']) && $search_company) {
-	$sql .= natural_search(array("s.nom", "s.name_alias"), $search_company);
-} else {
-	if ($search_company) {
-		$sql .= natural_search('s.nom', $search_company);
+	if ($search_refcustomer) {
+		$sql .= natural_search('f.ref_client', $search_refcustomer);
 	}
-	if ($search_company_alias) {
-		$sql .= natural_search('s.name_alias', $search_company_alias);
+	if ($search_type != '' && $search_type != '-1') {
+		$sql .= " AND f.type IN (" . $db->sanitize($db->escape($search_type)) . ")";
 	}
-}
-if ($search_parent_name) {
-	$sql .= natural_search('s2.nom', $search_parent_name);
-}
-if ($search_customer_code) {
-	$sql .= natural_search('s.code_client', $search_customer_code);
-}
-if ($search_town) {
-	$sql .= natural_search('s.town', $search_town);
-}
-if ($search_zip) {
-	$sql .= natural_search("s.zip", $search_zip);
-}
-if ($search_state) {
-	$sql .= natural_search("state.nom", $search_state);
-}
-if (strlen(trim($search_country))) {
-	$arrayofcode = getCountriesInEEC();
-	$country_code_in_EEC = $country_code_in_EEC_without_me = '';
-	foreach ($arrayofcode as $key => $value) {
-		$country_code_in_EEC .= ($country_code_in_EEC ? "," : "")."'".$value."'";
-		if ($value != $mysoc->country_code) {
-			$country_code_in_EEC_without_me .= ($country_code_in_EEC_without_me ? "," : "")."'".$value."'";
-		}
-	}
-	if ($search_country == 'special_allnotme') {
-		$sql .= " AND country.code <> '".$db->escape($mysoc->country_code)."'";
-	} elseif ($search_country == 'special_eec') {
-		$sql .= " AND country.code IN (".$db->sanitize($country_code_in_EEC, 1).")";
-	} elseif ($search_country == 'special_eecnotme') {
-		$sql .= " AND country.code IN (".$db->sanitize($country_code_in_EEC_without_me, 1).")";
-	} elseif ($search_country == 'special_noteec') {
-		$sql .= " AND country.code NOT IN (".$db->sanitize($country_code_in_EEC, 1).")";
-	} else {
-		$sql .= natural_search("country.code", $search_country);
+	if ($search_subtype != '' && $search_subtype != '-1') {
+		$sql .= " AND f.subtype IN (" . $db->sanitize($db->escape($search_subtype)) . ")";
 	}
-}
-if ($search_type_thirdparty != '' && $search_type_thirdparty != '-1') {
-	$sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')';
-}
-if ($search_montant_ht != '') {
-	$sql .= natural_search('f.total_ht', $search_montant_ht, 1);
-}
-if ($search_montant_vat != '') {
-	$sql .= natural_search('f.total_tva', $search_montant_vat, 1);
-}
-if ($search_montant_localtax1 != '') {
-	$sql .= natural_search('f.localtax1', $search_montant_localtax1, 1);
-}
-if ($search_montant_localtax2 != '') {
-	$sql .= natural_search('f.localtax2', $search_montant_localtax2, 1);
-}
-if ($search_montant_ttc != '') {
-	$sql .= natural_search('f.total_ttc', $search_montant_ttc, 1);
-}
-if ($search_multicurrency_code != '') {
-	$sql .= " AND f.multicurrency_code = '".$db->escape($search_multicurrency_code)."'";
-}
-if ($search_multicurrency_tx != '') {
-	$sql .= natural_search('f.multicurrency_tx', $search_multicurrency_tx, 1);
-}
-if ($search_multicurrency_montant_ht != '') {
-	$sql .= natural_search('f.multicurrency_total_ht', $search_multicurrency_montant_ht, 1);
-}
-if ($search_multicurrency_montant_vat != '') {
-	$sql .= natural_search('f.multicurrency_total_tva', $search_multicurrency_montant_vat, 1);
-}
-if ($search_multicurrency_montant_ttc != '') {
-	$sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1);
-}
-if ($search_login) {
-	$sql .= natural_search(array('u.login', 'u.firstname', 'u.lastname'), $search_login);
-}
-if ($search_status != '-1' && $search_status != '') {
-	if (is_numeric($search_status) && $search_status >= 0) {
-		if ($search_status == '0') {
-			$sql .= " AND f.fk_statut = 0"; // draft
+	if ($search_project_ref) {
+		$sql .= natural_search('p.ref', $search_project_ref);
+	}
+	if ($search_project) {
+		$sql .= natural_search('p.title', $search_project);
+	}
+	if (empty($arrayfields['s.name_alias']['checked']) && $search_company) {
+		$sql .= natural_search(array("s.nom", "s.name_alias"), $search_company);
+	} else {
+		if ($search_company) {
+			$sql .= natural_search('s.nom', $search_company);
 		}
-		if ($search_status == '1') {
-			$sql .= " AND f.fk_statut = 1"; // unpayed
+		if ($search_company_alias) {
+			$sql .= natural_search('s.name_alias', $search_company_alias);
 		}
-		if ($search_status == '2') {
-			$sql .= " AND f.fk_statut = 2"; // paid     Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means paid too but should not happen. If yes, reopen and reclassify billed)
+	}
+	if ($search_parent_name) {
+		$sql .= natural_search('s2.nom', $search_parent_name);
+	}
+	if ($search_customer_code) {
+		$sql .= natural_search('s.code_client', $search_customer_code);
+	}
+	if ($search_town) {
+		$sql .= natural_search('s.town', $search_town);
+	}
+	if ($search_zip) {
+		$sql .= natural_search("s.zip", $search_zip);
+	}
+	if ($search_state) {
+		$sql .= natural_search("state.nom", $search_state);
+	}
+	if (strlen(trim($search_country))) {
+		$arrayofcode = getCountriesInEEC();
+		$country_code_in_EEC = $country_code_in_EEC_without_me = '';
+		foreach ($arrayofcode as $key => $value) {
+			$country_code_in_EEC .= ($country_code_in_EEC ? "," : "") . "'" . $value . "'";
+			if ($value != $mysoc->country_code) {
+				$country_code_in_EEC_without_me .= ($country_code_in_EEC_without_me ? "," : "") . "'" . $value . "'";
+			}
 		}
-		if ($search_status == '3') {
-			$sql .= " AND f.fk_statut = 3"; // abandoned
+		if ($search_country == 'special_allnotme') {
+			$sql .= " AND country.code <> '" . $db->escape($mysoc->country_code) . "'";
+		} elseif ($search_country == 'special_eec') {
+			$sql .= " AND country.code IN (" . $db->sanitize($country_code_in_EEC, 1) . ")";
+		} elseif ($search_country == 'special_eecnotme') {
+			$sql .= " AND country.code IN (" . $db->sanitize($country_code_in_EEC_without_me, 1) . ")";
+		} elseif ($search_country == 'special_noteec') {
+			$sql .= " AND country.code NOT IN (" . $db->sanitize($country_code_in_EEC, 1) . ")";
+		} else {
+			$sql .= natural_search("country.code", $search_country);
+		}
+	}
+	if ($search_type_thirdparty != '' && $search_type_thirdparty != '-1') {
+		$sql .= " AND s.fk_typent IN (" . $db->sanitize($db->escape($search_type_thirdparty)) . ')';
+	}
+	if ($search_montant_ht != '') {
+		$sql .= natural_search('f.total_ht', $search_montant_ht, 1);
+	}
+	if ($search_montant_vat != '') {
+		$sql .= natural_search('f.total_tva', $search_montant_vat, 1);
+	}
+	if ($search_montant_localtax1 != '') {
+		$sql .= natural_search('f.localtax1', $search_montant_localtax1, 1);
+	}
+	if ($search_montant_localtax2 != '') {
+		$sql .= natural_search('f.localtax2', $search_montant_localtax2, 1);
+	}
+	if ($search_montant_ttc != '') {
+		$sql .= natural_search('f.total_ttc', $search_montant_ttc, 1);
+	}
+	if ($search_multicurrency_code != '') {
+		$sql .= " AND f.multicurrency_code = '" . $db->escape($search_multicurrency_code) . "'";
+	}
+	if ($search_multicurrency_tx != '') {
+		$sql .= natural_search('f.multicurrency_tx', $search_multicurrency_tx, 1);
+	}
+	if ($search_multicurrency_montant_ht != '') {
+		$sql .= natural_search('f.multicurrency_total_ht', $search_multicurrency_montant_ht, 1);
+	}
+	if ($search_multicurrency_montant_vat != '') {
+		$sql .= natural_search('f.multicurrency_total_tva', $search_multicurrency_montant_vat, 1);
+	}
+	if ($search_multicurrency_montant_ttc != '') {
+		$sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1);
+	}
+	if ($search_login) {
+		$sql .= natural_search(array('u.login', 'u.firstname', 'u.lastname'), $search_login);
+	}
+	if ($search_status != '-1' && $search_status != '') {
+		if (is_numeric($search_status) && $search_status >= 0) {
+			if ($search_status == '0') {
+				$sql .= " AND f.fk_statut = 0"; // draft
+			}
+			if ($search_status == '1') {
+				$sql .= " AND f.fk_statut = 1"; // unpayed
+			}
+			if ($search_status == '2') {
+				$sql .= " AND f.fk_statut = 2"; // paid     Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means paid too but should not happen. If yes, reopen and reclassify billed)
+			}
+			if ($search_status == '3') {
+				$sql .= " AND f.fk_statut = 3"; // abandoned
+			}
+		} else {
+			$sql .= " AND f.fk_statut IN (" . $db->sanitize($db->escape($search_status)) . ")"; // When search_status is '1,2' for example
 		}
-	} else {
-		$sql .= " AND f.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; // When search_status is '1,2' for example
 	}
-}
 
-if ($search_paymentmode > 0) {
-	$sql .= " AND f.fk_mode_reglement = ".((int) $search_paymentmode);
-}
-if ($search_paymentterms > 0) {
-	$sql .= " AND f.fk_cond_reglement = ".((int) $search_paymentterms);
-}
-if ($search_module_source) {
-	$sql .= natural_search("f.module_source", $search_module_source);
-}
-if ($search_pos_source) {
-	$sql .= natural_search("f.pos_source", $search_pos_source);
-}
-if ($search_date_start) {
-	$sql .= " AND f.datef >= '".$db->idate($search_date_start)."'";
-}
-if ($search_date_end) {
-	$sql .= " AND f.datef <= '".$db->idate($search_date_end)."'";
-}
-if ($search_date_valid_start) {
-	$sql .= " AND f.date_valid >= '".$db->idate($search_date_valid_start)."'";
-}
-if ($search_date_valid_end) {
-	$sql .= " AND f.date_valid <= '".$db->idate($search_date_valid_end)."'";
-}
-if ($search_datelimit_start) {
-	$sql .= " AND f.date_lim_reglement >= '".$db->idate($search_datelimit_start)."'";
-}
-if ($search_datelimit_end) {
-	$sql .= " AND f.date_lim_reglement <= '".$db->idate($search_datelimit_end)."'";
-}
-if ($search_option == 'late') {
-	$sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->client->warning_delay)."'";
-}
-/*if ($search_sale > 0) {
+	if ($search_paymentmode > 0) {
+		$sql .= " AND f.fk_mode_reglement = " . ((int) $search_paymentmode);
+	}
+	if ($search_paymentterms > 0) {
+		$sql .= " AND f.fk_cond_reglement = " . ((int) $search_paymentterms);
+	}
+	if ($search_module_source) {
+		$sql .= natural_search("f.module_source", $search_module_source);
+	}
+	if ($search_pos_source) {
+		$sql .= natural_search("f.pos_source", $search_pos_source);
+	}
+	if ($search_date_start) {
+		$sql .= " AND f.datef >= '" . $db->idate($search_date_start) . "'";
+	}
+	if ($search_date_end) {
+		$sql .= " AND f.datef <= '" . $db->idate($search_date_end) . "'";
+	}
+	if ($search_date_valid_start) {
+		$sql .= " AND f.date_valid >= '" . $db->idate($search_date_valid_start) . "'";
+	}
+	if ($search_date_valid_end) {
+		$sql .= " AND f.date_valid <= '" . $db->idate($search_date_valid_end) . "'";
+	}
+	if ($search_datelimit_start) {
+		$sql .= " AND f.date_lim_reglement >= '" . $db->idate($search_datelimit_start) . "'";
+	}
+	if ($search_datelimit_end) {
+		$sql .= " AND f.date_lim_reglement <= '" . $db->idate($search_datelimit_end) . "'";
+	}
+	if ($search_option == 'late') {
+		$sql .= " AND f.date_lim_reglement < '" . $db->idate(dol_now() - $conf->facture->client->warning_delay) . "'";
+	}
+	/*if ($search_sale > 0) {
 	$sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $search_sale);
 }*/
-if (!empty($search_fac_rec_source_title)) {
-	$sql .= natural_search('facrec.titre', $search_fac_rec_source_title);
-}
-if ($search_fk_fac_rec_source) {
-	$sql .= ' AND f.fk_fac_rec_source = ' . (int) $search_fk_fac_rec_source;
-}
-if ($search_import_key) {
-	$sql .= natural_search("s.import_key", $search_import_key);
-}
-// Search on user
-if ($search_user > 0) {
-	$sql .= " AND EXISTS (";
-	$sql .= " SELECT ec.fk_c_type_contact, ec.element_id, ec.fk_socpeople";
-	$sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec";
-	$sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_contact as tc";
-	$sql .= " ON ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal'";
-	$sql .= " WHERE ec.element_id = f.rowid AND ec.fk_socpeople = ".((int) $search_user).")";
-}
-// Search on sale representative
-if ($search_sale && $search_sale != '-1') {
-	if ($search_sale == -2) {
-		$sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
-	} elseif ($search_sale > 0) {
-		$sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
+	if (!empty($search_fac_rec_source_title)) {
+		$sql .= natural_search('facrec.titre', $search_fac_rec_source_title);
 	}
-}
-// Search for tag/category ($searchCategoryProductList is an array of ID)
-$searchCategoryProductList = $search_product_category ? array($search_product_category) : array();
-$searchCategoryProductOperator = 0;
-if (!empty($searchCategoryProductList)) {
-	$searchCategoryProductSqlList = array();
-	$listofcategoryid = '';
-	foreach ($searchCategoryProductList as $searchCategoryProduct) {
-		if (intval($searchCategoryProduct) == -2) {
-			$searchCategoryProductSqlList[] = "NOT EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."facturedet as fd WHERE fd.fk_facture = f.rowid AND fd.fk_product = ck.fk_product)";
-		} elseif (intval($searchCategoryProduct) > 0) {
-			if ($searchCategoryProductOperator == 0) {
-				$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."facturedet as fd WHERE fd.fk_facture = f.rowid AND fd.fk_product = ck.fk_product AND ck.fk_categorie = ".((int) $searchCategoryProduct).")";
-			} else {
-				$listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryProduct);
-			}
-		}
+	if ($search_fk_fac_rec_source) {
+		$sql .= ' AND f.fk_fac_rec_source = ' . (int) $search_fk_fac_rec_source;
 	}
-	if ($listofcategoryid) {
-		$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM ".MAIN_DB_PREFIX."categorie_product as ck, ".MAIN_DB_PREFIX."facturedet as fd WHERE fd.fk_facture = f.rowid AND fd.fk_product = ck.fk_product AND ck.fk_categorie IN (".$db->sanitize($listofcategoryid)."))";
+	if ($search_import_key) {
+		$sql .= natural_search("s.import_key", $search_import_key);
 	}
-	if ($searchCategoryProductOperator == 1) {
-		if (!empty($searchCategoryProductSqlList)) {
-			$sql .= " AND (".implode(' OR ', $searchCategoryProductSqlList).")";
+	// Search on user
+	if ($search_user > 0) {
+		$sql .= " AND EXISTS (";
+		$sql .= " SELECT ec.fk_c_type_contact, ec.element_id, ec.fk_socpeople";
+		$sql .= " FROM " . MAIN_DB_PREFIX . "element_contact as ec";
+		$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "c_type_contact as tc";
+		$sql .= " ON ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal'";
+		$sql .= " WHERE ec.element_id = f.rowid AND ec.fk_socpeople = " . ((int) $search_user) . ")";
+	}
+	// Search on sale representative
+	if ($search_sale && $search_sale != '-1') {
+		if ($search_sale == -2) {
+			$sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc)";
+		} elseif ($search_sale > 0) {
+			$sql .= " AND EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = f.fk_soc AND sc.fk_user = " . ((int) $search_sale) . ")";
+		}
+	}
+	// Search for tag/category ($searchCategoryProductList is an array of ID)
+	$searchCategoryProductList = $search_product_category ? array($search_product_category) : array();
+	$searchCategoryProductOperator = 0;
+	if (!empty($searchCategoryProductList)) {
+		$searchCategoryProductSqlList = array();
+		$listofcategoryid = '';
+		foreach ($searchCategoryProductList as $searchCategoryProduct) {
+			if (intval($searchCategoryProduct) == -2) {
+				$searchCategoryProductSqlList[] = "NOT EXISTS (SELECT ck.fk_product FROM " . MAIN_DB_PREFIX . "categorie_product as ck, " . MAIN_DB_PREFIX . "facturedet as fd WHERE fd.fk_facture = f.rowid AND fd.fk_product = ck.fk_product)";
+			} elseif (intval($searchCategoryProduct) > 0) {
+				if ($searchCategoryProductOperator == 0) {
+					$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM " . MAIN_DB_PREFIX . "categorie_product as ck, " . MAIN_DB_PREFIX . "facturedet as fd WHERE fd.fk_facture = f.rowid AND fd.fk_product = ck.fk_product AND ck.fk_categorie = " . ((int) $searchCategoryProduct) . ")";
+				} else {
+					$listofcategoryid .= ($listofcategoryid ? ', ' : '') . ((int) $searchCategoryProduct);
+				}
+			}
 		}
-	} else {
-		if (!empty($searchCategoryProductSqlList)) {
-			$sql .= " AND (".implode(' AND ', $searchCategoryProductSqlList).")";
+		if ($listofcategoryid) {
+			$searchCategoryProductSqlList[] = " EXISTS (SELECT ck.fk_product FROM " . MAIN_DB_PREFIX . "categorie_product as ck, " . MAIN_DB_PREFIX . "facturedet as fd WHERE fd.fk_facture = f.rowid AND fd.fk_product = ck.fk_product AND ck.fk_categorie IN (" . $db->sanitize($listofcategoryid) . "))";
 		}
-	}
-}
-$searchCategoryCustomerList = $search_categ_cus ? array($search_categ_cus) : array();
-$searchCategoryCustomerOperator = 0;
-// Search for tag/category ($searchCategoryCustomerList is an array of ID)
-if (!empty($searchCategoryCustomerList)) {
-	$searchCategoryCustomerSqlList = array();
-	$listofcategoryid = '';
-	foreach ($searchCategoryCustomerList as $searchCategoryCustomer) {
-		if (intval($searchCategoryCustomer) == -2) {
-			$searchCategoryCustomerSqlList[] = "NOT EXISTS (SELECT ck.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as ck WHERE s.rowid = ck.fk_soc)";
-		} elseif (intval($searchCategoryCustomer) > 0) {
-			if ($searchCategoryCustomerOperator == 0) {
-				$searchCategoryCustomerSqlList[] = " EXISTS (SELECT ck.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as ck WHERE s.rowid = ck.fk_soc AND ck.fk_categorie = ".((int) $searchCategoryCustomer).")";
-			} else {
-				$listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryCustomer);
+		if ($searchCategoryProductOperator == 1) {
+			if (!empty($searchCategoryProductSqlList)) {
+				$sql .= " AND (" . implode(' OR ', $searchCategoryProductSqlList) . ")";
+			}
+		} else {
+			if (!empty($searchCategoryProductSqlList)) {
+				$sql .= " AND (" . implode(' AND ', $searchCategoryProductSqlList) . ")";
 			}
 		}
 	}
-	if ($listofcategoryid) {
-		$searchCategoryCustomerSqlList[] = " EXISTS (SELECT ck.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as ck WHERE s.rowid = ck.fk_soc AND ck.fk_categorie IN (".$db->sanitize($listofcategoryid)."))";
-	}
-	if ($searchCategoryCustomerOperator == 1) {
-		if (!empty($searchCategoryCustomerSqlList)) {
-			$sql .= " AND (".implode(' OR ', $searchCategoryCustomerSqlList).")";
+	$searchCategoryCustomerList = $search_categ_cus ? array($search_categ_cus) : array();
+	$searchCategoryCustomerOperator = 0;
+	// Search for tag/category ($searchCategoryCustomerList is an array of ID)
+	if (!empty($searchCategoryCustomerList)) {
+		$searchCategoryCustomerSqlList = array();
+		$listofcategoryid = '';
+		foreach ($searchCategoryCustomerList as $searchCategoryCustomer) {
+			if (intval($searchCategoryCustomer) == -2) {
+				$searchCategoryCustomerSqlList[] = "NOT EXISTS (SELECT ck.fk_soc FROM " . MAIN_DB_PREFIX . "categorie_societe as ck WHERE s.rowid = ck.fk_soc)";
+			} elseif (intval($searchCategoryCustomer) > 0) {
+				if ($searchCategoryCustomerOperator == 0) {
+					$searchCategoryCustomerSqlList[] = " EXISTS (SELECT ck.fk_soc FROM " . MAIN_DB_PREFIX . "categorie_societe as ck WHERE s.rowid = ck.fk_soc AND ck.fk_categorie = " . ((int) $searchCategoryCustomer) . ")";
+				} else {
+					$listofcategoryid .= ($listofcategoryid ? ', ' : '') . ((int) $searchCategoryCustomer);
+				}
+			}
 		}
-	} else {
-		if (!empty($searchCategoryCustomerSqlList)) {
-			$sql .= " AND (".implode(' AND ', $searchCategoryCustomerSqlList).")";
+		if ($listofcategoryid) {
+			$searchCategoryCustomerSqlList[] = " EXISTS (SELECT ck.fk_soc FROM " . MAIN_DB_PREFIX . "categorie_societe as ck WHERE s.rowid = ck.fk_soc AND ck.fk_categorie IN (" . $db->sanitize($listofcategoryid) . "))";
+		}
+		if ($searchCategoryCustomerOperator == 1) {
+			if (!empty($searchCategoryCustomerSqlList)) {
+				$sql .= " AND (" . implode(' OR ', $searchCategoryCustomerSqlList) . ")";
+			}
+		} else {
+			if (!empty($searchCategoryCustomerSqlList)) {
+				$sql .= " AND (" . implode(' AND ', $searchCategoryCustomerSqlList) . ")";
+			}
 		}
 	}
-}
-// Add where from extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
-// Add where from hooks
-$parameters = array();
-$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-$sql .= $hookmanager->resPrint;
-
-if ($search_all) {
-	$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
-}
+	// Add where from extra fields
+	include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_sql.tpl.php';
+	// Add where from hooks
+	$parameters = array();
+	$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	$sql .= $hookmanager->resPrint;
+
+	if ($search_all) {
+		$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
+	}
+
+	// Add HAVING from hooks
+	$parameters = array();
+	$reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	$sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 " . $hookmanager->resPrint;
+
+	// Count total nb of records
+	$nbtotalofrecords = '';
+	if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
+		/* The fast and low memory method to get and count full list converts the sql into a sql count */
+		$parameters = array(
+			'sqlforcount' => $sql,
+			'sqlfields' => $sqlfields,
+			'context' => $parameters['context']
+		);
+		$reshook = $hookmanager->executeHooks('beforeCountQuery', $parameters, $object, $action);
+		if ($reshook > 0 && !empty($hookmanager->resPrint)) {
+			$sqlforcount = $hookmanager->resPrint;
+		} else {
+			$sqlforcount = preg_replace('/^' . preg_quote($sqlfields, '/') . '/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
+			$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
+		}
 
-// Add HAVING from hooks
-$parameters = array();
-$reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-$sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 ".$hookmanager->resPrint;
-
-// Count total nb of records
-$nbtotalofrecords = '';
-if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
-	/* The fast and low memory method to get and count full list converts the sql into a sql count */
-	$sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
-	$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
-
-	$resql = $db->query($sqlforcount);
-	if ($resql) {
-		$objforcount = $db->fetch_object($resql);
-		$nbtotalofrecords = $objforcount->nbtotalofrecords;
-	} else {
-		dol_print_error($db);
-	}
+		$resql = $db->query($sqlforcount);
+		if ($resql) {
+			$objforcount = $db->fetch_object($resql);
+			$nbtotalofrecords = $objforcount->nbtotalofrecords;
+
+			$_GET['total_ht'] = $objforcount->total_ht ?? 0;
+			$_GET['total_tva'] = $objforcount->total_tva ?? 0;
+			$_GET['total_ttc'] = $objforcount->total_ttc ?? 0;
+		} else {
+			dol_print_error($db);
+		}
 
-	if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller then paging size (filtering), goto and load page 0
-		$page = 0;
-		$offset = 0;
+		if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller than paging size (filtering), goto and load page 0
+			$page = 0;
+			$offset = 0;
+		}
+		$db->free($resql);
 	}
-	$db->free($resql);
-}
 
-// Complete request and execute it with limit
-$sql .= $db->order($sortfield, $sortorder);
-if ($limit) {
-	$sql .= $db->plimit($limit + 1, $offset);
-}
-
-$resql = $db->query($sql);
-if (!$resql) {
-	dol_print_error($db);
-	exit;
-}
 
-$num = $db->num_rows($resql);
+	// Complete request and execute it with limit
+	$sql .= $db->order($sortfield, $sortorder);
+	if ($limit) {
+		$sql .= $db->plimit($limit + 1, $offset);
+	}
 
-$arrayofselected = is_array($toselect) ? $toselect : array();
+	$resql = $db->query($sql);
+	if (!$resql) {
+		dol_print_error($db);
+		exit;
+	}
 
-if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all) {
-	$obj = $db->fetch_object($resql);
-	$id = $obj->id;
+	$num = $db->num_rows($resql);
 
-	header("Location: ".DOL_URL_ROOT.'/compta/facture/card.php?id='.$id);
-	exit;
-}
+	$arrayofselected = is_array($toselect) ? $toselect : array();
 
-// Output page
-// --------------------------------------------------------------------
+	if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all) {
+		$obj = $db->fetch_object($resql);
+		$id = $obj->id;
 
-llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'bodyforlist');
+		header("Location: " . DOL_URL_ROOT . '/compta/facture/card.php?id=' . $id);
+		exit;
+	}
 
-if ($search_fk_fac_rec_source) {
-	$object = new FactureRec($db);
-	$object->fetch((int) $search_fk_fac_rec_source);
+	// Output page
+	// --------------------------------------------------------------------
 
-	$head = invoice_rec_prepare_head($object);
+	llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'bodyforlist');
 
-	print dol_get_fiche_head($head, 'generated', $langs->trans('InvoicesGeneratedFromRec'), -1, 'bill'); // Add a div
-}
+	if ($search_fk_fac_rec_source) {
+		$object = new FactureRec($db);
+		$object->fetch((int) $search_fk_fac_rec_source);
 
+		$head = invoice_rec_prepare_head($object);
 
-$param = '&socid='.urlencode((string) ($socid));
-if (!empty($mode)) {
-	$param .= '&mode='.urlencode($mode);
-}
-if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
-	$param .= '&contextpage='.urlencode($contextpage);
-}
-if ($limit > 0 && $limit != $conf->liste_limit) {
-	$param .= '&limit='.((int) $limit);
-}
-if ($optioncss != '') {
-	$param .= '&optioncss='.urlencode($optioncss);
-}
-if ($show_files) {
-	$param .= '&show_files='.urlencode((string) ($show_files));
-}
-if ($search_all) {
-	$param .= '&search_all='.urlencode($search_all);
-}
-if ($search_date_startday) {
-	$param .= '&search_date_startday='.urlencode((string) ($search_date_startday));
-}
-if ($search_date_startmonth) {
-	$param .= '&search_date_startmonth='.urlencode((string) ($search_date_startmonth));
-}
-if ($search_date_startyear) {
-	$param .= '&search_date_startyear='.urlencode((string) ($search_date_startyear));
-}
-if ($search_date_endday) {
-	$param .= '&search_date_endday='.urlencode((string) ($search_date_endday));
-}
-if ($search_date_endmonth) {
-	$param .= '&search_date_endmonth='.urlencode((string) ($search_date_endmonth));
-}
-if ($search_date_endyear) {
-	$param .= '&search_date_endyear='.urlencode((string) ($search_date_endyear));
-}
-if ($search_date_valid_startday) {
-	$param .= '&search_date_valid_startday='.urlencode((string) ($search_date_valid_startday));
-}
-if ($search_date_valid_startmonth) {
-	$param .= '&search_date_valid_startmonth='.urlencode((string) ($search_date_valid_startmonth));
-}
-if ($search_date_valid_startyear) {
-	$param .= '&search_date_valid_startyear='.urlencode((string) ($search_date_valid_startyear));
-}
-if ($search_date_valid_endday) {
-	$param .= '&search_date_valid_endday='.urlencode((string) ($search_date_valid_endday));
-}
-if ($search_date_valid_endmonth) {
-	$param .= '&search_date_valid_endmonth='.urlencode((string) ($search_date_valid_endmonth));
-}
-if ($search_date_valid_endyear) {
-	$param .= '&search_date_valid_endyear='.urlencode((string) ($search_date_valid_endyear));
-}
-if ($search_datelimit_startday) {
-	$param .= '&search_datelimit_startday='.urlencode((string) ($search_datelimit_startday));
-}
-if ($search_datelimit_startmonth) {
-	$param .= '&search_datelimit_startmonth='.urlencode((string) ($search_datelimit_startmonth));
-}
-if ($search_datelimit_startyear) {
-	$param .= '&search_datelimit_startyear='.urlencode((string) ($search_datelimit_startyear));
-}
-if ($search_datelimit_endday) {
-	$param .= '&search_datelimit_endday='.urlencode((string) ($search_datelimit_endday));
-}
-if ($search_datelimit_endmonth) {
-	$param .= '&search_datelimit_endmonth='.urlencode((string) ($search_datelimit_endmonth));
-}
-if ($search_datelimit_endyear) {
-	$param .= '&search_datelimit_endyear='.urlencode((string) ($search_datelimit_endyear));
-}
-if ($search_ref) {
-	$param .= '&search_ref='.urlencode($search_ref);
-}
-if ($search_refcustomer) {
-	$param .= '&search_refcustomer='.urlencode($search_refcustomer);
-}
-if ($search_project_ref) {
-	$param .= '&search_project_ref='.urlencode($search_project_ref);
-}
-if ($search_project) {
-	$param .= '&search_project='.urlencode($search_project);
-}
-if ($search_type != '') {
-	$param .= '&search_type='.urlencode($search_type);
-}
-if ($search_subtype != '') {
-	$param .= '&search_subtype='.urlencode($search_subtype);
-}
-if ($search_company) {
-	$param .= '&search_company='.urlencode($search_company);
-}
-if ($search_company_alias) {
-	$param .= '&search_company_alias='.urlencode($search_company_alias);
-}
-if ($search_parent_name != '') {
-	$param .= '&search_parent_name='.urlencode($search_parent_name);
-}
-if ($search_town) {
-	$param .= '&search_town='.urlencode($search_town);
-}
-if ($search_zip) {
-	$param .= '&search_zip='.urlencode($search_zip);
-}
-if ($search_country) {
-	$param .= "&search_country=".urlencode($search_country);
-}
-if ($search_type_thirdparty != '') {
-	$param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty);
-}
-if ($search_customer_code) {
-	$param .= '&search_customer_code='.urlencode($search_customer_code);
-}
-if ($search_sale > 0) {
-	$param .= '&search_sale='.urlencode((string) $search_sale);
-}
-if ($search_user > 0) {
-	$param .= '&search_user='.urlencode((string) $search_user);
-}
-if ($search_login) {
-	$param .= '&search_login='.urlencode($search_login);
-}
-if ($search_product_category > 0) {
-	$param .= '&search_product_category='.urlencode((string) $search_product_category);
-}
-if ($search_montant_ht != '') {
-	$param .= '&search_montant_ht='.urlencode($search_montant_ht);
-}
-if ($search_montant_vat != '') {
-	$param .= '&search_montant_vat='.urlencode($search_montant_vat);
-}
-if ($search_montant_localtax1 != '') {
-	$param .= '&search_montant_localtax1='.urlencode($search_montant_localtax1);
-}
-if ($search_montant_localtax2 != '') {
-	$param .= '&search_montant_localtax2='.urlencode($search_montant_localtax2);
-}
-if ($search_montant_ttc != '') {
-	$param .= '&search_montant_ttc='.urlencode($search_montant_ttc);
-}
-if ($search_multicurrency_code != '') {
-	$param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code);
-}
-if ($search_multicurrency_tx != '') {
-	$param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx);
-}
-if ($search_multicurrency_montant_ht != '') {
-	$param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht);
-}
-if ($search_multicurrency_montant_vat != '') {
-	$param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat);
-}
-if ($search_multicurrency_montant_ttc != '') {
-	$param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc);
-}
-if ($search_status != '') {
-	$param .= '&search_status='.urlencode($search_status);
-}
-if ($search_paymentmode > 0) {
-	$param .= '&search_paymentmode='.urlencode((string) ($search_paymentmode));
-}
-if ($search_paymentterms > 0) {
-	$param .= '&search_paymentterms='.urlencode((string) ($search_paymentterms));
-}
-if ($search_module_source) {
-	$param .= '&search_module_source='.urlencode($search_module_source);
-}
-if ($search_pos_source) {
-	$param .= '&search_pos_source='.urlencode($search_pos_source);
-}
-if ($search_option) {
-	$param .= "&search_option=".urlencode($search_option);
-}
-if ($search_categ_cus > 0) {
-	$param .= '&search_categ_cus='.urlencode((string) ($search_categ_cus));
-}
-if (!empty($search_fac_rec_source_title)) {
-	$param .= '&search_fac_rec_source_title='.urlencode($search_fac_rec_source_title);
-}
-if ($search_fk_fac_rec_source) {
-	$param .= '&search_fk_fac_rec_source=' . (int) $search_fk_fac_rec_source;
-}
-if ($search_import_key != '') {
-	$param .= '&search_import_key='.urlencode($search_import_key);
-}
+		print dol_get_fiche_head($head, 'generated', $langs->trans('InvoicesGeneratedFromRec'), -1, 'bill'); // Add a div
+	}
 
-// Add $param from extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
-// Add $param from hooks
-$parameters = array('param' => &$param);
-$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-$param .= $hookmanager->resPrint;
-
-$arrayofmassactions = array(
-	'validate' => img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate"),
-	'generate_doc' => img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
-	'builddoc' => img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
-	'presend' => img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"),
-);
 
-if ($user->hasRight('facture', 'paiement')) {
-	$arrayofmassactions['makepayment'] = img_picto('', 'payment', 'class="pictofixedwidth"').$langs->trans("MakePaymentAndClassifyPayed");
-}
-if (isModEnabled('prelevement') && $user->hasRight('prelevement', 'bons', 'creer')) {
-	$langs->load("withdrawals");
-	$arrayofmassactions['withdrawrequest'] = img_picto('', 'payment', 'class="pictofixedwidth"').$langs->trans("MakeWithdrawRequest");
-}
-if ($user->hasRight('facture', 'supprimer')) {
-	if (getDolGlobalString('INVOICE_CAN_REMOVE_DRAFT_ONLY')) {
-		$arrayofmassactions['predeletedraft'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Deletedraft");
-	} elseif (getDolGlobalString('INVOICE_CAN_ALWAYS_BE_REMOVED')) {	// mass deletion never possible on invoices on such situation
-		$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
+	$param = '&socid=' . urlencode((string) ($socid));
+	if (!empty($mode)) {
+		$param .= '&mode=' . urlencode($mode);
+	}
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage=' . urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit=' . ((int) $limit);
+	}
+	if ($optioncss != '') {
+		$param .= '&optioncss=' . urlencode($optioncss);
+	}
+	if ($show_files) {
+		$param .= '&show_files=' . urlencode((string) ($show_files));
+	}
+	if ($search_all) {
+		$param .= '&search_all=' . urlencode($search_all);
+	}
+	if ($search_date_startday) {
+		$param .= '&search_date_startday=' . urlencode((string) ($search_date_startday));
+	}
+	if ($search_date_startmonth) {
+		$param .= '&search_date_startmonth=' . urlencode((string) ($search_date_startmonth));
+	}
+	if ($search_date_startyear) {
+		$param .= '&search_date_startyear=' . urlencode((string) ($search_date_startyear));
+	}
+	if ($search_date_endday) {
+		$param .= '&search_date_endday=' . urlencode((string) ($search_date_endday));
+	}
+	if ($search_date_endmonth) {
+		$param .= '&search_date_endmonth=' . urlencode((string) ($search_date_endmonth));
+	}
+	if ($search_date_endyear) {
+		$param .= '&search_date_endyear=' . urlencode((string) ($search_date_endyear));
+	}
+	if ($search_date_valid_startday) {
+		$param .= '&search_date_valid_startday=' . urlencode((string) ($search_date_valid_startday));
+	}
+	if ($search_date_valid_startmonth) {
+		$param .= '&search_date_valid_startmonth=' . urlencode((string) ($search_date_valid_startmonth));
+	}
+	if ($search_date_valid_startyear) {
+		$param .= '&search_date_valid_startyear=' . urlencode((string) ($search_date_valid_startyear));
+	}
+	if ($search_date_valid_endday) {
+		$param .= '&search_date_valid_endday=' . urlencode((string) ($search_date_valid_endday));
+	}
+	if ($search_date_valid_endmonth) {
+		$param .= '&search_date_valid_endmonth=' . urlencode((string) ($search_date_valid_endmonth));
+	}
+	if ($search_date_valid_endyear) {
+		$param .= '&search_date_valid_endyear=' . urlencode((string) ($search_date_valid_endyear));
+	}
+	if ($search_datelimit_startday) {
+		$param .= '&search_datelimit_startday=' . urlencode((string) ($search_datelimit_startday));
+	}
+	if ($search_datelimit_startmonth) {
+		$param .= '&search_datelimit_startmonth=' . urlencode((string) ($search_datelimit_startmonth));
+	}
+	if ($search_datelimit_startyear) {
+		$param .= '&search_datelimit_startyear=' . urlencode((string) ($search_datelimit_startyear));
+	}
+	if ($search_datelimit_endday) {
+		$param .= '&search_datelimit_endday=' . urlencode((string) ($search_datelimit_endday));
+	}
+	if ($search_datelimit_endmonth) {
+		$param .= '&search_datelimit_endmonth=' . urlencode((string) ($search_datelimit_endmonth));
+	}
+	if ($search_datelimit_endyear) {
+		$param .= '&search_datelimit_endyear=' . urlencode((string) ($search_datelimit_endyear));
+	}
+	if ($search_ref) {
+		$param .= '&search_ref=' . urlencode($search_ref);
+	}
+	if ($search_refcustomer) {
+		$param .= '&search_refcustomer=' . urlencode($search_refcustomer);
+	}
+	if ($search_project_ref) {
+		$param .= '&search_project_ref=' . urlencode($search_project_ref);
+	}
+	if ($search_project) {
+		$param .= '&search_project=' . urlencode($search_project);
+	}
+	if ($search_type != '') {
+		$param .= '&search_type=' . urlencode($search_type);
+	}
+	if ($search_subtype != '') {
+		$param .= '&search_subtype=' . urlencode($search_subtype);
+	}
+	if ($search_company) {
+		$param .= '&search_company=' . urlencode($search_company);
+	}
+	if ($search_company_alias) {
+		$param .= '&search_company_alias=' . urlencode($search_company_alias);
+	}
+	if ($search_parent_name != '') {
+		$param .= '&search_parent_name=' . urlencode($search_parent_name);
+	}
+	if ($search_town) {
+		$param .= '&search_town=' . urlencode($search_town);
+	}
+	if ($search_zip) {
+		$param .= '&search_zip=' . urlencode($search_zip);
+	}
+	if ($search_country) {
+		$param .= "&search_country=" . urlencode($search_country);
+	}
+	if ($search_type_thirdparty != '') {
+		$param .= '&search_type_thirdparty=' . urlencode($search_type_thirdparty);
+	}
+	if ($search_customer_code) {
+		$param .= '&search_customer_code=' . urlencode($search_customer_code);
+	}
+	if ($search_sale > 0) {
+		$param .= '&search_sale=' . urlencode((string) $search_sale);
+	}
+	if ($search_user > 0) {
+		$param .= '&search_user=' . urlencode((string) $search_user);
+	}
+	if ($search_login) {
+		$param .= '&search_login=' . urlencode($search_login);
+	}
+	if ($search_product_category > 0) {
+		$param .= '&search_product_category=' . urlencode((string) $search_product_category);
+	}
+	if ($search_montant_ht != '') {
+		$param .= '&search_montant_ht=' . urlencode($search_montant_ht);
+	}
+	if ($search_montant_vat != '') {
+		$param .= '&search_montant_vat=' . urlencode($search_montant_vat);
+	}
+	if ($search_montant_localtax1 != '') {
+		$param .= '&search_montant_localtax1=' . urlencode($search_montant_localtax1);
+	}
+	if ($search_montant_localtax2 != '') {
+		$param .= '&search_montant_localtax2=' . urlencode($search_montant_localtax2);
+	}
+	if ($search_montant_ttc != '') {
+		$param .= '&search_montant_ttc=' . urlencode($search_montant_ttc);
+	}
+	if ($search_multicurrency_code != '') {
+		$param .= '&search_multicurrency_code=' . urlencode($search_multicurrency_code);
+	}
+	if ($search_multicurrency_tx != '') {
+		$param .= '&search_multicurrency_tx=' . urlencode($search_multicurrency_tx);
+	}
+	if ($search_multicurrency_montant_ht != '') {
+		$param .= '&search_multicurrency_montant_ht=' . urlencode($search_multicurrency_montant_ht);
+	}
+	if ($search_multicurrency_montant_vat != '') {
+		$param .= '&search_multicurrency_montant_vat=' . urlencode($search_multicurrency_montant_vat);
+	}
+	if ($search_multicurrency_montant_ttc != '') {
+		$param .= '&search_multicurrency_montant_ttc=' . urlencode($search_multicurrency_montant_ttc);
+	}
+	if ($search_status != '') {
+		$param .= '&search_status=' . urlencode($search_status);
+	}
+	if ($search_paymentmode > 0) {
+		$param .= '&search_paymentmode=' . urlencode((string) ($search_paymentmode));
+	}
+	if ($search_paymentterms > 0) {
+		$param .= '&search_paymentterms=' . urlencode((string) ($search_paymentterms));
+	}
+	if ($search_module_source) {
+		$param .= '&search_module_source=' . urlencode($search_module_source);
+	}
+	if ($search_pos_source) {
+		$param .= '&search_pos_source=' . urlencode($search_pos_source);
+	}
+	if ($search_option) {
+		$param .= "&search_option=" . urlencode($search_option);
+	}
+	if ($search_categ_cus > 0) {
+		$param .= '&search_categ_cus=' . urlencode((string) ($search_categ_cus));
+	}
+	if (!empty($search_fac_rec_source_title)) {
+		$param .= '&search_fac_rec_source_title=' . urlencode($search_fac_rec_source_title);
+	}
+	if ($search_fk_fac_rec_source) {
+		$param .= '&search_fk_fac_rec_source=' . (int) $search_fk_fac_rec_source;
+	}
+	if ($search_import_key != '') {
+		$param .= '&search_import_key=' . urlencode($search_import_key);
 	}
-}
-if (in_array($massaction, array('presend', 'predelete', 'makepayment'))) {
-	$arrayofmassactions = array();
-}
-$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
 
-// Show the new button only when this page is not opend from the Extended POS
-$newcardbutton = '';
-if ($contextpage != 'poslist') {
-	$url = DOL_URL_ROOT.'/compta/facture/card.php?action=create';
-	if (!empty($object->socid)) {
-		$url .= '&socid='.urlencode((string) $object->socid);
-	}
-	if (!empty($object->id)) {
-		$url .= '&fac_rec='.urlencode((string) $object->id);
-	}
-	$newcardbutton  = '';
-	$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition'));
-	$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition'));
-	$newcardbutton .= dolGetButtonTitleSeparator();
-	$newcardbutton .= dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', $url, '', $user->hasRight("facture", "creer"));
-}
+	// Add $param from extra fields
+	include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_param.tpl.php';
+	// Add $param from hooks
+	$parameters = array('param' => &$param);
+	$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	$param .= $hookmanager->resPrint;
 
-$i = 0;
-print '<form method="POST" id="searchFormList" name="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
-if ($optioncss != '') {
-	print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
-}
-print '<input type="hidden" name="token" value="'.newToken().'">';
-print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
-if (!in_array($massaction, array('makepayment'))) {
-	print '<input type="hidden" name="action" value="list">';
-}
-print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
-print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
-print '<input type="hidden" name="search_status" value="'.$search_status.'">';
-print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
-print '<input type="hidden" name="socid" value="'.$socid.'">';
-print '<input type="hidden" name="mode" value="'.$mode.'">';
-
-print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'bill', 0, $newcardbutton, '', $limit, 0, 0, 1);
-
-$topicmail = "SendBillRef";
-$modelmail = "facture_send";
-$objecttmp = new Facture($db);
-$trackid = 'inv'.$object->id;
-include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
-
-if ($massaction == 'makepayment') {
-	$formconfirm = '';
-	$formquestion = array(
-		// 'text' => $langs->trans("ConfirmClone"),
-		// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
-		// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
-		array('type' => 'date', 'name' => 'datepaiment', 'label' => $langs->trans("Date"), 'datenow' => 1),
-		array('type' => 'other', 'name' => 'paiementid', 'label' => $langs->trans("PaymentMode"), 'value' => $form->select_types_paiements(GETPOST('search_paymentmode'), 'paiementid', '', 0, 0, 1, 0, 1, '', 1)),
-		array('type' => 'other', 'name' => 'bankid', 'label' => $langs->trans("BankAccount"), 'value' => $form->select_comptes('', 'bankid', 0, '', 0, '', 0, '', 1)),
-		//array('type' => 'other', 'name' => 'invoicesid', 'label' => '', 'value'=>'<input type="hidden" id="invoicesid" name="invoicesid" value="'.implode('#',GETPOST('toselect','array')).'">'),
+	$arrayofmassactions = array(
+		'validate' => img_picto('', 'check', 'class="pictofixedwidth"') . $langs->trans("Validate"),
+		'generate_doc' => img_picto('', 'pdf', 'class="pictofixedwidth"') . $langs->trans("ReGeneratePDF"),
+		'builddoc' => img_picto('', 'pdf', 'class="pictofixedwidth"') . $langs->trans("PDFMerge"),
+		'presend' => img_picto('', 'email', 'class="pictofixedwidth"') . $langs->trans("SendByMail"),
 	);
-	$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans('MakePaymentAndClassifyPayed'), $langs->trans('EnterPaymentReceivedFromCustomer'), 'makepayment_confirm', $formquestion, 1, 0, 200, 500, 1);
-	print $formconfirm;
-}
 
-if ($search_all) {
-	foreach ($fieldstosearchall as $key => $val) {
-		$fieldstosearchall[$key] = $langs->trans($val);
+	if ($user->hasRight('facture', 'paiement')) {
+		$arrayofmassactions['makepayment'] = img_picto('', 'payment', 'class="pictofixedwidth"') . $langs->trans("MakePaymentAndClassifyPayed");
+	}
+	if (isModEnabled('prelevement') && $user->hasRight('prelevement', 'bons', 'creer')) {
+		$langs->load("withdrawals");
+		$arrayofmassactions['withdrawrequest'] = img_picto('', 'payment', 'class="pictofixedwidth"') . $langs->trans("MakeWithdrawRequest");
+	}
+	if ($user->hasRight('facture', 'supprimer')) {
+		if (getDolGlobalString('INVOICE_CAN_REMOVE_DRAFT_ONLY')) {
+			$arrayofmassactions['predeletedraft'] = img_picto('', 'delete', 'class="pictofixedwidth"') . $langs->trans("Deletedraft");
+		} elseif (getDolGlobalString('INVOICE_CAN_ALWAYS_BE_REMOVED')) {	// mass deletion never possible on invoices on such situation
+			$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"') . $langs->trans("Delete");
+		}
+	}
+	if (in_array($massaction, array('presend', 'predelete', 'makepayment'))) {
+		$arrayofmassactions = array();
+	}
+	$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
+
+	// Show the new button only when this page is not opend from the Extended POS
+	$newcardbutton = '';
+	if ($contextpage != 'poslist') {
+		$url = DOL_URL_ROOT . '/compta/facture/card.php?action=create';
+		if (!empty($object->socid)) {
+			$url .= '&socid=' . urlencode((string) $object->socid);
+		}
+		if (!empty($object->id)) {
+			$url .= '&fac_rec=' . urlencode((string) $object->id);
+		}
+		$newcardbutton  = '';
+		$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"] . '?mode=common' . preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition'));
+		$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"] . '?mode=kanban' . preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition'));
+		$newcardbutton .= dolGetButtonTitleSeparator();
+		$newcardbutton .= dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', $url, '', $user->hasRight("facture", "creer"));
 	}
-	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).implode(', ', $fieldstosearchall).'</div>';
-}
 
-// If the user can view prospects other than his'
-$moreforfilter = '';
-if ($user->hasRight("user", "user", "lire")) {
-	$langs->load("commercial");
-	$moreforfilter .= '<div class="divsearchfield">';
-	$tmptitle = $langs->trans('ThirdPartiesOfSaleRepresentative');
-	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"').$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, $tmptitle, 'maxwidth200');
-	$moreforfilter .= '</div>';
-}
-// If the user can view prospects other than his'
-if ($user->hasRight("user", "user", "lire")) {
-	$moreforfilter .= '<div class="divsearchfield">';
-	$tmptitle = $langs->trans('LinkedToSpecificUsers');
-	$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"').$form->select_dolusers($search_user, 'search_user', $tmptitle, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200');
-	$moreforfilter .= '</div>';
-}
-// Filter on product tags
-if (isModEnabled('category') && $user->hasRight("categorie", "lire") && ($user->hasRight("produit", "lire") || $user->hasRight("service", "lire"))) {
-	include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
-	$moreforfilter .= '<div class="divsearchfield">';
-	$tmptitle = $langs->trans('IncludingProductWithTag');
-	$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', 'parent', 0, 0, 1);
-	$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"').$form->selectarray('search_product_category', $cate_arbo, $search_product_category, $tmptitle, 0, 0, '', 0, 0, 0, 0, 'maxwidth300 widthcentpercentminusx', 1);
-	$moreforfilter .= '</div>';
-}
-if (isModEnabled('category') && $user->hasRight("categorie", "lire")) {
-	require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
+	$i = 0;
+	print '<form method="POST" id="searchFormList" name="searchFormList" action="' . $_SERVER["PHP_SELF"] . '">' . "\n";
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="' . $optioncss . '">';
+	}
+	print '<input type="hidden" name="token" value="' . newToken() . '">';
+	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
+	if (!in_array($massaction, array('makepayment'))) {
+		print '<input type="hidden" name="action" value="list">';
+	}
+	print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
+	print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
+	print '<input type="hidden" name="search_status" value="' . $search_status . '">';
+	print '<input type="hidden" name="contextpage" value="' . $contextpage . '">';
+	print '<input type="hidden" name="socid" value="' . $socid . '">';
+	print '<input type="hidden" name="mode" value="' . $mode . '">';
+
+	print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'bill', 0, $newcardbutton, '', $limit, 0, 0, 1);
+
+	$topicmail = "SendBillRef";
+	$modelmail = "facture_send";
+	$objecttmp = new Facture($db);
+	$trackid = 'inv' . $object->id;
+	include DOL_DOCUMENT_ROOT . '/core/tpl/massactions_pre.tpl.php';
+
+	if ($massaction == 'makepayment') {
+		$formconfirm = '';
+		$formquestion = array(
+			// 'text' => $langs->trans("ConfirmClone"),
+			// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
+			// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
+			array('type' => 'date', 'name' => 'datepaiment', 'label' => $langs->trans("Date"), 'datenow' => 1),
+			array('type' => 'other', 'name' => 'paiementid', 'label' => $langs->trans("PaymentMode"), 'value' => $form->select_types_paiements(GETPOST('search_paymentmode'), 'paiementid', '', 0, 0, 1, 0, 1, '', 1)),
+			array('type' => 'other', 'name' => 'bankid', 'label' => $langs->trans("BankAccount"), 'value' => $form->select_comptes('', 'bankid', 0, '', 0, '', 0, '', 1)),
+			//array('type' => 'other', 'name' => 'invoicesid', 'label' => '', 'value'=>'<input type="hidden" id="invoicesid" name="invoicesid" value="'.implode('#',GETPOST('toselect','array')).'">'),
+		);
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans('MakePaymentAndClassifyPayed'), $langs->trans('EnterPaymentReceivedFromCustomer'), 'makepayment_confirm', $formquestion, 1, 0, 200, 500, 1);
+		print $formconfirm;
+	}
+
+	if ($search_all) {
+		foreach ($fieldstosearchall as $key => $val) {
+			$fieldstosearchall[$key] = $langs->trans($val);
+		}
+		print '<div class="divsearchfieldfilter">' . $langs->trans("FilterOnInto", $search_all) . implode(', ', $fieldstosearchall) . '</div>';
+	}
+
+	// If the user can view prospects other than his'
+	$moreforfilter = '';
+	if ($user->hasRight("user", "user", "lire")) {
+		$langs->load("commercial");
+		$moreforfilter .= '<div class="divsearchfield">';
+		$tmptitle = $langs->trans('ThirdPartiesOfSaleRepresentative');
+		$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"') . $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, $tmptitle, 'maxwidth200');
+		$moreforfilter .= '</div>';
+	}
+	// If the user can view prospects other than his'
+	if ($user->hasRight("user", "user", "lire")) {
+		$moreforfilter .= '<div class="divsearchfield">';
+		$tmptitle = $langs->trans('LinkedToSpecificUsers');
+		$moreforfilter .= img_picto($tmptitle, 'user', 'class="pictofixedwidth"') . $form->select_dolusers($search_user, 'search_user', $tmptitle, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200');
+		$moreforfilter .= '</div>';
+	}
+	// Filter on product tags
+	if (isModEnabled('category') && $user->hasRight("categorie", "lire") && ($user->hasRight("produit", "lire") || $user->hasRight("service", "lire"))) {
+		include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
+		$moreforfilter .= '<div class="divsearchfield">';
+		$tmptitle = $langs->trans('IncludingProductWithTag');
+		$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', 'parent', 0, 0, 1);
+		$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"') . $form->selectarray('search_product_category', $cate_arbo, $search_product_category, $tmptitle, 0, 0, '', 0, 0, 0, 0, 'maxwidth300 widthcentpercentminusx', 1);
+		$moreforfilter .= '</div>';
+	}
+	if (isModEnabled('category') && $user->hasRight("categorie", "lire")) {
+		require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
+		$moreforfilter .= '<div class="divsearchfield">';
+		$tmptitle = $langs->trans('CustomersProspectsCategoriesShort');
+		$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"') . $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $tmptitle);
+		$moreforfilter .= '</div>';
+	}
+	// alert on due date
 	$moreforfilter .= '<div class="divsearchfield">';
-	$tmptitle = $langs->trans('CustomersProspectsCategoriesShort');
-	$moreforfilter .= img_picto($tmptitle, 'category', 'class="pictofixedwidth"').$formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1, $tmptitle);
+	$moreforfilter .= '<label for="search_option">' . $langs->trans('Alert') . ' </label><input type="checkbox" name="search_option" id="search_option" value="late"' . ($search_option == 'late' ? ' checked' : '') . '>';
 	$moreforfilter .= '</div>';
-}
-// alert on due date
-$moreforfilter .= '<div class="divsearchfield">';
-$moreforfilter .= '<label for="search_option">'.$langs->trans('Alert').' </label><input type="checkbox" name="search_option" id="search_option" value="late"'.($search_option == 'late' ? ' checked' : '').'>';
-$moreforfilter .= '</div>';
-
-$parameters = array();
-$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-if (empty($reshook)) {
-	$moreforfilter .= $hookmanager->resPrint;
-} else {
-	$moreforfilter = $hookmanager->resPrint;
-}
-
-if (!empty($moreforfilter)) {
-	print '<div class="liste_titre liste_titre_bydiv centpercent">';
-	print $moreforfilter;
-	print '</div>';
-}
 
-$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
-$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')); // This also change content of $arrayfields
-
-// Show the massaction checkboxes only when this page is not opend from the Extended POS
-if ($massactionbutton && $contextpage != 'poslist') {
-	$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
-}
-
-print '<div class="div-table-responsive">';
-print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
-
-// Fields title search
-// --------------------------------------------------------------------
-print '<tr class="liste_titre_filter">';
-
-// Action column
-if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
-	print '<td class="liste_titre center maxwidthsearch actioncolumn">';
-	$searchpicto = $form->showFilterButtons('left');
-	print $searchpicto;
-	print '</td>';
-}
-
-if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER_IN_LIST')) {
-	print '<td class="liste_titre">';
-	print '</td>';
-}
-// Ref
-if (!empty($arrayfields['f.ref']['checked'])) {
-	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth50imp" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'">';
-	print '</td>';
-}
-// Ref customer
-if (!empty($arrayfields['f.ref_client']['checked'])) {
-	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth50imp" type="text" name="search_refcustomer" value="'.dol_escape_htmltag($search_refcustomer).'">';
-	print '</td>';
-}
-// Type
-if (!empty($arrayfields['f.type']['checked'])) {
-	print '<td class="liste_titre maxwidthonsmartphone">';
-	$listtype = array(
-		Facture::TYPE_STANDARD => $langs->trans("InvoiceStandard"),
-		Facture::TYPE_DEPOSIT => $langs->trans("InvoiceDeposit"),
-		Facture::TYPE_CREDIT_NOTE => $langs->trans("InvoiceAvoir"),
-		Facture::TYPE_REPLACEMENT => $langs->trans("InvoiceReplacement"),
-	);
-	if (getDolGlobalString('INVOICE_USE_SITUATION')) {
-		$listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation");
+	$parameters = array();
+	$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	if (empty($reshook)) {
+		$moreforfilter .= $hookmanager->resPrint;
+	} else {
+		$moreforfilter = $hookmanager->resPrint;
 	}
-	//$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma");     // A proformat invoice is not an invoice but must be an order.
-	// @phan-suppress-next-line PhanPluginSuspiciousParamOrder
-	print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth75');
-	print '</td>';
-}
-// Invoice Subtype
-if (!empty($arrayfields['f.subtype']['checked'])) {
-	print '<td class="liste_titre maxwidthonsmartphone" align="center">';
-	print $form->selectarray('search_subtype', $subtypearray, $search_subtype, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100');
-	print '</td>';
-}
-// Date invoice
-if (!empty($arrayfields['f.datef']['checked'])) {
-	print '<td class="liste_titre center">';
-	print '<div class="nowrapfordate">';
-	print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
-	print '</div>';
-	print '<div class="nowrapfordate">';
-	print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
-	print '</div>';
-	print '</td>';
-}
-// Date valid
-if (!empty($arrayfields['f.date_valid']['checked'])) {
-	print '<td class="liste_titre center">';
-	print '<div class="nowrapfordate">';
-	print $form->selectDate($search_date_valid_start ? $search_date_valid_start : -1, 'search_date_valid_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
-	print '</div>';
-	print '<div class="nowrapfordate">';
-	print $form->selectDate($search_date_valid_end ? $search_date_valid_end : -1, 'search_date_valid_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
-	print '</div>';
-	print '</td>';
-}
-// Date due
-if (!empty($arrayfields['f.date_lim_reglement']['checked'])) {
-	print '<td class="liste_titre center">';
-	print '<div class="nowrapfordate">';
-	print $form->selectDate($search_datelimit_start ? $search_datelimit_start : -1, 'search_datelimit_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
-	print '</div>';
-	print '<div class="nowrapfordate">';
-	print $form->selectDate($search_datelimit_end ? $search_datelimit_end : -1, 'search_datelimit_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
-	print '</div>';
-	print '</td>';
-}
-// Project ref
-if (!empty($arrayfields['p.ref']['checked'])) {
-	print '<td class="liste_titre"><input class="flat maxwidth50imp" type="text" name="search_project_ref" value="'.dol_escape_htmltag($search_project_ref).'"></td>';
-}
-// Project label
-if (!empty($arrayfields['p.title']['checked'])) {
-	print '<td class="liste_titre"><input class="flat maxwidth50imp" type="text" name="search_project" value="'.dol_escape_htmltag($search_project).'"></td>';
-}
-// Thirdparty
-if (!empty($arrayfields['s.nom']['checked'])) {
-	print '<td class="liste_titre"><input class="flat maxwidth75imp" type="text" name="search_company" value="'.dol_escape_htmltag($search_company).'"'.($socid > 0 ? " disabled" : "").'></td>';
-}
-// Alias
-if (!empty($arrayfields['s.name_alias']['checked'])) {
-	print '<td class="liste_titre"><input class="flat maxwidth75imp" type="text" name="search_company_alias" value="'.dol_escape_htmltag($search_company_alias).'"></td>';
-}
-// Parent company
-if (!empty($arrayfields['s2.nom']['checked'])) {
-	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth100" type="text" name="search_parent_name" value="'.dol_escape_htmltag($search_parent_name).'">';
-	print '</td>';
-}
-// Customer Code
-if (!empty($arrayfields['s.code_client']['checked'])) {
-	print '<td class="liste_titre"><input class="flat maxwidth75imp" type="text" name="search_customer_code" value="'.dol_escape_htmltag($search_customer_code).'"></td>';
-}
-// Town
-if (!empty($arrayfields['s.town']['checked'])) {
-	print '<td class="liste_titre"><input class="flat maxwidth75imp" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'"></td>';
-}
-// Zip
-if (!empty($arrayfields['s.zip']['checked'])) {
-	print '<td class="liste_titre"><input class="flat maxwidth50imp" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'"></td>';
-}
-// State
-if (!empty($arrayfields['state.nom']['checked'])) {
-	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth50imp" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">';
-	print '</td>';
-}
-// Country
-if (!empty($arrayfields['country.code_iso']['checked'])) {
-	print '<td class="liste_titre center">';
-	print $form->select_country($search_country, 'search_country', '', 0, 'minwidth150imp maxwidth150', 'code2', 1, 0, 1, array(), 1);
-	print '</td>';
-}
-// Company type
-if (!empty($arrayfields['typent.code']['checked'])) {
-	print '<td class="liste_titre maxwidthonsmartphone center">';
-	print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (!getDolGlobalString('SOCIETE_SORT_ON_TYPEENT') ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100', 1);
-	print '</td>';
-}
-// Payment mode
-if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) {
-	print '<td class="liste_titre">';
-	print $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 0, 1, 'minwidth100 maxwidth100', 1);
-	print '</td>';
-}
-// Payment terms
-if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) {
-	print '<td class="liste_titre left">';
-	print $form->getSelectConditionsPaiements($search_paymentterms, 'search_paymentterms', -1, 1, 1, 'minwidth100 maxwidth100');
-	print '</td>';
-}
-// Module source
-if (!empty($arrayfields['f.module_source']['checked'])) {
-	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth75" type="text" name="search_module_source" value="'.dol_escape_htmltag($search_module_source).'">';
-	print '</td>';
-}
-// POS Terminal
-if (!empty($arrayfields['f.pos_source']['checked'])) {
-	print '<td class="liste_titre">';
-	print '<input class="flat maxwidth50" type="text" name="search_pos_source" value="'.dol_escape_htmltag($search_pos_source).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.total_ht']['checked'])) {
-	// Amount without tax
-	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.total_tva']['checked'])) {
-	// Amount vat
-	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.total_localtax1']['checked'])) {
-	// Localtax1
-	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_montant_localtax1" value="'.dol_escape_htmltag($search_montant_localtax1).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.total_localtax2']['checked'])) {
-	// Localtax2
-	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_montant_localtax2" value="'.dol_escape_htmltag($search_montant_localtax2).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.total_ttc']['checked'])) {
-	// Amount inc tax
-	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['u.login']['checked'])) {
-	// Author
-	print '<td class="liste_titre" align="center">';
-	print '<input class="flat" size="4" type="text" name="search_login" value="'.dol_escape_htmltag($search_login).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['sale_representative']['checked'])) {
-	print '<td class="liste_titre"></td>';
-}
-if (!empty($arrayfields['f.retained_warranty']['checked'])) {
-	print '<td class="liste_titre" align="right">';
-	print '</td>';
-}
-if (!empty($arrayfields['dynamount_payed']['checked'])) {
-	print '<td class="liste_titre right">';
-	print '</td>';
-}
-if (!empty($arrayfields['rtp']['checked'])) {
-	print '<td class="liste_titre">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.multicurrency_code']['checked'])) {
-	// Currency
-	print '<td class="liste_titre">';
-	print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1);
-	print '</td>';
-}
-if (!empty($arrayfields['f.multicurrency_tx']['checked'])) {
-	// Currency rate
-	print '<td class="liste_titre">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) {
-	// Amount
-	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) {
-	// Amount
-	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="'.dol_escape_htmltag($search_multicurrency_montant_vat).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) {
-	// Amount
-	print '<td class="liste_titre right">';
-	print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">';
-	print '</td>';
-}
-if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) {
-	print '<td class="liste_titre">';
-	print '</td>';
-}
-if (!empty($arrayfields['multicurrency_rtp']['checked'])) {
-	print '<td class="liste_titre right">';
-	print '</td>';
-}
-if (!empty($arrayfields['total_pa']['checked'])) {
-	print '<td class="liste_titre right">';
-	print '</td>';
-}
-if (!empty($arrayfields['total_margin']['checked'])) {
-	print '<td class="liste_titre right">';
-	print '</td>';
-}
-if (!empty($arrayfields['total_margin_rate']['checked'])) {
-	print '<td class="liste_titre right">';
-	print '</td>';
-}
-if (!empty($arrayfields['total_mark_rate']['checked'])) {
-	print '<td class="liste_titre right">';
-	print '</td>';
-}
-
-// Extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
 
-// Fields from hook
-$parameters = array('arrayfields' => $arrayfields);
-$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-print $hookmanager->resPrint;
-// Date creation
-if (!empty($arrayfields['f.datec']['checked'])) {
-	print '<td class="liste_titre">';
-	print '</td>';
-}
-// Date modification
-if (!empty($arrayfields['f.tms']['checked'])) {
-	print '<td class="liste_titre">';
-	print '</td>';
-}
-// Date closing
-if (!empty($arrayfields['f.date_closing']['checked'])) {
-	print '<td class="liste_titre">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.note_public']['checked'])) {
-	// Note public
-	print '<td class="liste_titre">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.note_private']['checked'])) {
-	// Note private
-	print '<td class="liste_titre">';
-	print '</td>';
-}
-if (!empty($arrayfields['f.fk_fac_rec_source']['checked'])) {
-	// Template Invoice
-	print '<td class="liste_titre maxwidthonsmartphone right">';
-	print '<input class="flat maxwidth50imp" type="text" name="search_fac_rec_source_title" id="search_fac_rec_source_title" value="'.dol_escape_htmltag($search_fac_rec_source_title).'">';
-	print '</td>';
-}
-// Import key
-if (!empty($arrayfields['f.import_key']['checked'])) {
-	print '<td class="liste_titre maxwidthonsmartphone center">';
-	print '<input class="flat searchstring maxwidth50" type="text" name="search_import_key" value="'.dol_escape_htmltag($search_import_key).'">';
-	print '</td>';
-}
-// Status
-if (!empty($arrayfields['f.fk_statut']['checked'])) {
-	print '<td class="liste_titre center parentonrightofpage">';
-	$liststatus = array('0' => $langs->trans("BillShortStatusDraft"), '0,1' => $langs->trans("BillShortStatusDraft").'+'.$langs->trans("BillShortStatusNotPaid"), '1' => $langs->trans("BillShortStatusNotPaid"), '1,2' => $langs->trans("BillShortStatusNotPaid").'+'.$langs->trans("BillShortStatusPaid"), '2' => $langs->trans("BillShortStatusPaid"), '3' => $langs->trans("BillShortStatusCanceled"));
-	// @phan-suppress-next-line PhanPluginSuspiciousParamOrder
-	print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', 'search_status width100 onrightofpage', 1);
-	print '</td>';
-}
-// Action column
-if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
-	print '<td class="liste_titre center maxwidthsearch actioncolumn">';
-	$searchpicto = $form->showFilterButtons();
-	print $searchpicto;
-	print '</td>';
-}
-print "</tr>\n";
-
-$totalarray = array();
-$totalarray['nbfield'] = 0;
-
-// Fields title label
-// --------------------------------------------------------------------
-print '<tr class="liste_titre">';
-if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
-	print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ');
-	$totalarray['nbfield']++;
-}
-if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER_IN_LIST')) {
-	print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.ref']['checked'])) {
-	print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.ref_client']['checked'])) {
-	print_liste_field_titre($arrayfields['f.ref_client']['label'], $_SERVER["PHP_SELF"], 'f.ref_client', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.type']['checked'])) {
-	print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.subtype']['checked'])) {
-	print_liste_field_titre($arrayfields['f.subtype']['label'], $_SERVER["PHP_SELF"], 'f.subtype', '', $param, '', $sortfield, $sortorder);
-}
-if (!empty($arrayfields['f.datef']['checked'])) {
-	print_liste_field_titre($arrayfields['f.datef']['label'], $_SERVER['PHP_SELF'], 'f.datef', '', $param, '', $sortfield, $sortorder, 'center ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.date_valid']['checked'])) {
-	print_liste_field_titre($arrayfields['f.date_valid']['label'], $_SERVER['PHP_SELF'], 'f.date_valid', '', $param, '', $sortfield, $sortorder, 'center ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.date_lim_reglement']['checked'])) {
-	print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, '', $sortfield, $sortorder, 'center ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['p.ref']['checked'])) {
-	$langs->load("projects");
-	print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['p.title']['checked'])) {
-	print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER['PHP_SELF'], "p.title", '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['s.nom']['checked'])) {
-	print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['s.name_alias']['checked'])) {
-	// False positive @phan-suppress-next-line PhanTypeInvalidDimOffset
-	print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER['PHP_SELF'], 's.name_alias', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['s2.nom']['checked'])) {
-	print_liste_field_titre($arrayfields['s2.nom']['label'], $_SERVER['PHP_SELF'], 's2.nom', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['s.code_client']['checked'])) {
-	print_liste_field_titre($arrayfields['s.code_client']['label'], $_SERVER['PHP_SELF'], 's.code_client', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['s.town']['checked'])) {
-	print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['s.zip']['checked'])) {
-	print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['state.nom']['checked'])) {
-	print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['country.code_iso']['checked'])) {
-	print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['typent.code']['checked'])) {
-	print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) {
-	print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) {
-	print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.module_source']['checked'])) {
-	print_liste_field_titre($arrayfields['f.module_source']['label'], $_SERVER["PHP_SELF"], "f.module_source", "", $param, "", $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.pos_source']['checked'])) {
-	print_liste_field_titre($arrayfields['f.pos_source']['label'], $_SERVER["PHP_SELF"], "f.pos_source", "", $param, "", $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.total_ht']['checked'])) {
-	print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total_ht', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.total_tva']['checked'])) {
-	print_liste_field_titre($arrayfields['f.total_tva']['label'], $_SERVER['PHP_SELF'], 'f.total_tva', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.total_localtax1']['checked'])) {
-	print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.total_localtax2']['checked'])) {
-	print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.total_ttc']['checked'])) {
-	print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['u.login']['checked'])) {
-	print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, '', $sortfield, $sortorder, 'center ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['sale_representative']['checked'])) {
-	print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", "$param", '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.retained_warranty']['checked'])) {
-	print_liste_field_titre($arrayfields['f.retained_warranty']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['dynamount_payed']['checked'])) {
-	print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['rtp']['checked'])) {
-	print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.multicurrency_code']['checked'])) {
-	print_liste_field_titre($arrayfields['f.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_code', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.multicurrency_tx']['checked'])) {
-	print_liste_field_titre($arrayfields['f.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_tx', '', $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) {
-	print_liste_field_titre($arrayfields['f.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ht', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) {
-	print_liste_field_titre($arrayfields['f.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_tva', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) {
-	print_liste_field_titre($arrayfields['f.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ttc', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) {
-	print_liste_field_titre($arrayfields['multicurrency_dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['multicurrency_rtp']['checked'])) {
-	print_liste_field_titre($arrayfields['multicurrency_rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['total_pa']['checked'])) {
-	print_liste_field_titre($arrayfields['total_pa']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['total_margin']['checked'])) {
-	print_liste_field_titre($arrayfields['total_margin']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['total_margin_rate']['checked'])) {
-	print_liste_field_titre($arrayfields['total_margin_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['total_mark_rate']['checked'])) {
-	print_liste_field_titre($arrayfields['total_mark_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
-	$totalarray['nbfield']++;
-}
-// Extra fields
-include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
-// Hook fields
-$parameters = array('arrayfields' => $arrayfields, 'param' => $param, 'sortfield' => $sortfield, 'sortorder' => $sortorder, 'totalarray' => $totalarray);
-$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-print $hookmanager->resPrint;
-if (!empty($arrayfields['f.datec']['checked'])) {
-	print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'nowraponall center ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.tms']['checked'])) {
-	print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'nowraponall center ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.date_closing']['checked'])) {
-	print_liste_field_titre($arrayfields['f.date_closing']['label'], $_SERVER["PHP_SELF"], "f.date_closing", "", $param, '', $sortfield, $sortorder, 'nowraponall center ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.note_public']['checked'])) {
-	print_liste_field_titre($arrayfields['f.note_public']['label'], $_SERVER["PHP_SELF"], "f.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.note_private']['checked'])) {
-	print_liste_field_titre($arrayfields['f.note_private']['label'], $_SERVER["PHP_SELF"], "f.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-	$totalarray['nbfield']++;
-}
-if (!empty($arrayfields['f.fk_fac_rec_source']['checked'])) {
-	print_liste_field_titre($arrayfields['f.fk_fac_rec_source']['label'], $_SERVER["PHP_SELF"], "facrec.titre", "", $param, '', $sortfield, $sortorder);
-	$totalarray['nbfield']++;
-}
-// Import key
-if (!empty($arrayfields['f.import_key']['checked'])) {
-	print_liste_field_titre($arrayfields['f.import_key']['label'], $_SERVER["PHP_SELF"], "f.import_key", "", $param, '', $sortfield, $sortorder, 'center ');
-	$totalarray['nbfield']++;
-}
-// Status
-if (!empty($arrayfields['f.fk_statut']['checked'])) {
-	print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "f.fk_statut,f.paye,f.type", "", $param, '', $sortfield, $sortorder, 'center ');
-	$totalarray['nbfield']++;
-}
-if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
-	print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch center ');
-	$totalarray['nbfield']++;
-}
-
-print "</tr>\n";
+	if (!empty($moreforfilter)) {
+		print '<div class="liste_titre liste_titre_bydiv centpercent">';
+		print $moreforfilter;
+		print '</div>';
+	}
+
+	$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
+	$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')); // This also change content of $arrayfields
+
+	// Show the massaction checkboxes only when this page is not opend from the Extended POS
+	if ($massactionbutton && $contextpage != 'poslist') {
+		$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
+	}
+
+	print '<div class="div-table-responsive">';
+	print '<table class="tagtable nobottomiftotal liste' . ($moreforfilter ? " listwithfilterbefore" : "") . '">' . "\n";
+
+	// Fields title search
+	// --------------------------------------------------------------------
+	print '<tr class="liste_titre_filter">';
+
+	// Action column
+	if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+		print '<td class="liste_titre center maxwidthsearch actioncolumn">';
+		$searchpicto = $form->showFilterButtons('left');
+		print $searchpicto;
+		print '</td>';
+	}
+
+	if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER_IN_LIST')) {
+		print '<td class="liste_titre">';
+		print '</td>';
+	}
+	// Ref
+	if (!empty($arrayfields['f.ref']['checked'])) {
+		print '<td class="liste_titre">';
+		print '<input class="flat maxwidth50imp" type="text" name="search_ref" value="' . dol_escape_htmltag($search_ref) . '">';
+		print '</td>';
+	}
+	// Ref customer
+	if (!empty($arrayfields['f.ref_client']['checked'])) {
+		print '<td class="liste_titre">';
+		print '<input class="flat maxwidth50imp" type="text" name="search_refcustomer" value="' . dol_escape_htmltag($search_refcustomer) . '">';
+		print '</td>';
+	}
+	// Type
+	if (!empty($arrayfields['f.type']['checked'])) {
+		print '<td class="liste_titre maxwidthonsmartphone">';
+		$listtype = array(
+			Facture::TYPE_STANDARD => $langs->trans("InvoiceStandard"),
+			Facture::TYPE_DEPOSIT => $langs->trans("InvoiceDeposit"),
+			Facture::TYPE_CREDIT_NOTE => $langs->trans("InvoiceAvoir"),
+			Facture::TYPE_REPLACEMENT => $langs->trans("InvoiceReplacement"),
+		);
+		if (getDolGlobalString('INVOICE_USE_SITUATION')) {
+			$listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation");
+		}
+		//$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma");     // A proformat invoice is not an invoice but must be an order.
+		// @phan-suppress-next-line PhanPluginSuspiciousParamOrder
+		print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth75');
+		print '</td>';
+	}
+	// Invoice Subtype
+	if (!empty($arrayfields['f.subtype']['checked'])) {
+		print '<td class="liste_titre maxwidthonsmartphone" align="center">';
+		print $form->selectarray('search_subtype', $subtypearray, $search_subtype, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100');
+		print '</td>';
+	}
+	// Date invoice
+	if (!empty($arrayfields['f.datef']['checked'])) {
+		print '<td class="liste_titre center">';
+		print '<div class="nowrapfordate">';
+		print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
+		print '</div>';
+		print '<div class="nowrapfordate">';
+		print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
+		print '</div>';
+		print '</td>';
+	}
+	// Date valid
+	if (!empty($arrayfields['f.date_valid']['checked'])) {
+		print '<td class="liste_titre center">';
+		print '<div class="nowrapfordate">';
+		print $form->selectDate($search_date_valid_start ? $search_date_valid_start : -1, 'search_date_valid_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
+		print '</div>';
+		print '<div class="nowrapfordate">';
+		print $form->selectDate($search_date_valid_end ? $search_date_valid_end : -1, 'search_date_valid_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
+		print '</div>';
+		print '</td>';
+	}
+	// Date due
+	if (!empty($arrayfields['f.date_lim_reglement']['checked'])) {
+		print '<td class="liste_titre center">';
+		print '<div class="nowrapfordate">';
+		print $form->selectDate($search_datelimit_start ? $search_datelimit_start : -1, 'search_datelimit_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
+		print '</div>';
+		print '<div class="nowrapfordate">';
+		print $form->selectDate($search_datelimit_end ? $search_datelimit_end : -1, 'search_datelimit_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
+		print '</div>';
+		print '</td>';
+	}
+	// Project ref
+	if (!empty($arrayfields['p.ref']['checked'])) {
+		print '<td class="liste_titre"><input class="flat maxwidth50imp" type="text" name="search_project_ref" value="' . dol_escape_htmltag($search_project_ref) . '"></td>';
+	}
+	// Project label
+	if (!empty($arrayfields['p.title']['checked'])) {
+		print '<td class="liste_titre"><input class="flat maxwidth50imp" type="text" name="search_project" value="' . dol_escape_htmltag($search_project) . '"></td>';
+	}
+	// Thirdparty
+	if (!empty($arrayfields['s.nom']['checked'])) {
+		print '<td class="liste_titre"><input class="flat maxwidth75imp" type="text" name="search_company" value="' . dol_escape_htmltag($search_company) . '"' . ($socid > 0 ? " disabled" : "") . '></td>';
+	}
+	// Alias
+	if (!empty($arrayfields['s.name_alias']['checked'])) {
+		print '<td class="liste_titre"><input class="flat maxwidth75imp" type="text" name="search_company_alias" value="' . dol_escape_htmltag($search_company_alias) . '"></td>';
+	}
+	// Parent company
+	if (!empty($arrayfields['s2.nom']['checked'])) {
+		print '<td class="liste_titre">';
+		print '<input class="flat maxwidth100" type="text" name="search_parent_name" value="' . dol_escape_htmltag($search_parent_name) . '">';
+		print '</td>';
+	}
+	// Customer Code
+	if (!empty($arrayfields['s.code_client']['checked'])) {
+		print '<td class="liste_titre"><input class="flat maxwidth75imp" type="text" name="search_customer_code" value="' . dol_escape_htmltag($search_customer_code) . '"></td>';
+	}
+	// Town
+	if (!empty($arrayfields['s.town']['checked'])) {
+		print '<td class="liste_titre"><input class="flat maxwidth75imp" type="text" name="search_town" value="' . dol_escape_htmltag($search_town) . '"></td>';
+	}
+	// Zip
+	if (!empty($arrayfields['s.zip']['checked'])) {
+		print '<td class="liste_titre"><input class="flat maxwidth50imp" type="text" name="search_zip" value="' . dol_escape_htmltag($search_zip) . '"></td>';
+	}
+	// State
+	if (!empty($arrayfields['state.nom']['checked'])) {
+		print '<td class="liste_titre">';
+		print '<input class="flat maxwidth50imp" type="text" name="search_state" value="' . dol_escape_htmltag($search_state) . '">';
+		print '</td>';
+	}
+	// Country
+	if (!empty($arrayfields['country.code_iso']['checked'])) {
+		print '<td class="liste_titre center">';
+		print $form->select_country($search_country, 'search_country', '', 0, 'minwidth150imp maxwidth150', 'code2', 1, 0, 1, array(), 1);
+		print '</td>';
+	}
+	// Company type
+	if (!empty($arrayfields['typent.code']['checked'])) {
+		print '<td class="liste_titre maxwidthonsmartphone center">';
+		print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (!getDolGlobalString('SOCIETE_SORT_ON_TYPEENT') ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100', 1);
+		print '</td>';
+	}
+	// Payment mode
+	if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) {
+		print '<td class="liste_titre">';
+		print $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 0, 1, 'minwidth100 maxwidth100', 1);
+		print '</td>';
+	}
+	// Payment terms
+	if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) {
+		print '<td class="liste_titre left">';
+		print $form->getSelectConditionsPaiements($search_paymentterms, 'search_paymentterms', -1, 1, 1, 'minwidth100 maxwidth100');
+		print '</td>';
+	}
+	// Module source
+	if (!empty($arrayfields['f.module_source']['checked'])) {
+		print '<td class="liste_titre">';
+		print '<input class="flat maxwidth75" type="text" name="search_module_source" value="' . dol_escape_htmltag($search_module_source) . '">';
+		print '</td>';
+	}
+	// POS Terminal
+	if (!empty($arrayfields['f.pos_source']['checked'])) {
+		print '<td class="liste_titre">';
+		print '<input class="flat maxwidth50" type="text" name="search_pos_source" value="' . dol_escape_htmltag($search_pos_source) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.total_ht']['checked'])) {
+		// Amount without tax
+		print '<td class="liste_titre right">';
+		print '<input class="flat" type="text" size="4" name="search_montant_ht" value="' . dol_escape_htmltag($search_montant_ht) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.total_tva']['checked'])) {
+		// Amount vat
+		print '<td class="liste_titre right">';
+		print '<input class="flat" type="text" size="4" name="search_montant_vat" value="' . dol_escape_htmltag($search_montant_vat) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.total_localtax1']['checked'])) {
+		// Localtax1
+		print '<td class="liste_titre right">';
+		print '<input class="flat" type="text" size="4" name="search_montant_localtax1" value="' . dol_escape_htmltag($search_montant_localtax1) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.total_localtax2']['checked'])) {
+		// Localtax2
+		print '<td class="liste_titre right">';
+		print '<input class="flat" type="text" size="4" name="search_montant_localtax2" value="' . dol_escape_htmltag($search_montant_localtax2) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.total_ttc']['checked'])) {
+		// Amount inc tax
+		print '<td class="liste_titre right">';
+		print '<input class="flat" type="text" size="4" name="search_montant_ttc" value="' . dol_escape_htmltag($search_montant_ttc) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['u.login']['checked'])) {
+		// Author
+		print '<td class="liste_titre" align="center">';
+		print '<input class="flat" size="4" type="text" name="search_login" value="' . dol_escape_htmltag($search_login) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['sale_representative']['checked'])) {
+		print '<td class="liste_titre"></td>';
+	}
+	if (!empty($arrayfields['f.retained_warranty']['checked'])) {
+		print '<td class="liste_titre" align="right">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['dynamount_payed']['checked'])) {
+		print '<td class="liste_titre right">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['rtp']['checked'])) {
+		print '<td class="liste_titre">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.multicurrency_code']['checked'])) {
+		// Currency
+		print '<td class="liste_titre">';
+		print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1);
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.multicurrency_tx']['checked'])) {
+		// Currency rate
+		print '<td class="liste_titre">';
+		print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="' . dol_escape_htmltag($search_multicurrency_tx) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) {
+		// Amount
+		print '<td class="liste_titre right">';
+		print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="' . dol_escape_htmltag($search_multicurrency_montant_ht) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) {
+		// Amount
+		print '<td class="liste_titre right">';
+		print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="' . dol_escape_htmltag($search_multicurrency_montant_vat) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) {
+		// Amount
+		print '<td class="liste_titre right">';
+		print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="' . dol_escape_htmltag($search_multicurrency_montant_ttc) . '">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) {
+		print '<td class="liste_titre">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['multicurrency_rtp']['checked'])) {
+		print '<td class="liste_titre right">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['total_pa']['checked'])) {
+		print '<td class="liste_titre right">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['total_margin']['checked'])) {
+		print '<td class="liste_titre right">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['total_margin_rate']['checked'])) {
+		print '<td class="liste_titre right">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['total_mark_rate']['checked'])) {
+		print '<td class="liste_titre right">';
+		print '</td>';
+	}
+
+	// Extra fields
+	include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_input.tpl.php';
+
+	// Fields from hook
+	$parameters = array('arrayfields' => $arrayfields);
+	$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	print $hookmanager->resPrint;
+	// Date creation
+	if (!empty($arrayfields['f.datec']['checked'])) {
+		print '<td class="liste_titre">';
+		print '</td>';
+	}
+	// Date modification
+	if (!empty($arrayfields['f.tms']['checked'])) {
+		print '<td class="liste_titre">';
+		print '</td>';
+	}
+	// Date closing
+	if (!empty($arrayfields['f.date_closing']['checked'])) {
+		print '<td class="liste_titre">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.note_public']['checked'])) {
+		// Note public
+		print '<td class="liste_titre">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.note_private']['checked'])) {
+		// Note private
+		print '<td class="liste_titre">';
+		print '</td>';
+	}
+	if (!empty($arrayfields['f.fk_fac_rec_source']['checked'])) {
+		// Template Invoice
+		print '<td class="liste_titre maxwidthonsmartphone right">';
+		print '<input class="flat maxwidth50imp" type="text" name="search_fac_rec_source_title" id="search_fac_rec_source_title" value="' . dol_escape_htmltag($search_fac_rec_source_title) . '">';
+		print '</td>';
+	}
+	// Import key
+	if (!empty($arrayfields['f.import_key']['checked'])) {
+		print '<td class="liste_titre maxwidthonsmartphone center">';
+		print '<input class="flat searchstring maxwidth50" type="text" name="search_import_key" value="' . dol_escape_htmltag($search_import_key) . '">';
+		print '</td>';
+	}
+	// Status
+	if (!empty($arrayfields['f.fk_statut']['checked'])) {
+		print '<td class="liste_titre center parentonrightofpage">';
+		$liststatus = array('0' => $langs->trans("BillShortStatusDraft"), '0,1' => $langs->trans("BillShortStatusDraft") . '+' . $langs->trans("BillShortStatusNotPaid"), '1' => $langs->trans("BillShortStatusNotPaid"), '1,2' => $langs->trans("BillShortStatusNotPaid") . '+' . $langs->trans("BillShortStatusPaid"), '2' => $langs->trans("BillShortStatusPaid"), '3' => $langs->trans("BillShortStatusCanceled"));
+		// @phan-suppress-next-line PhanPluginSuspiciousParamOrder
+		print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', 'search_status width100 onrightofpage', 1);
+		print '</td>';
+	}
+	// Action column
+	if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+		print '<td class="liste_titre center maxwidthsearch actioncolumn">';
+		$searchpicto = $form->showFilterButtons();
+		print $searchpicto;
+		print '</td>';
+	}
+	print "</tr>\n";
 
-$projectstatic = new Project($db);
-$discount = new DiscountAbsolute($db);
-$userstatic = new User($db);
-
-// Loop on record
-// --------------------------------------------------------------------
-if ($num > 0) {
-	$i = 0;
-	$savnbfield = $totalarray['nbfield'];
 	$totalarray = array();
 	$totalarray['nbfield'] = 0;
-	$totalarray['val'] = array();
-	$totalarray['val']['f.total_ht'] = 0;
-	$totalarray['val']['f.total_tva'] = 0;
-	$totalarray['val']['f.total_localtax1'] = 0;
-	$totalarray['val']['f.total_localtax1'] = 0;
-	$totalarray['val']['f.total_ttc'] = 0;
-	$totalarray['val']['dynamount_payed'] = 0;
-	$totalarray['val']['rtp'] = 0;
-
-	$typenArray = $formcompany->typent_array(1);
-
-	$with_margin_info = false;
-	if (isModEnabled('margin') && (
-		!empty($arrayfields['total_pa']['checked'])
-		|| !empty($arrayfields['total_margin']['checked'])
-		|| !empty($arrayfields['total_margin_rate']['checked'])
-		|| !empty($arrayfields['total_mark_rate']['checked'])
-	)
-	) {
-		$with_margin_info = true;
-	}
-	$total_ht = 0;
-	$total_margin = 0;
-
-	$imaxinloop = ($limit ? min($num, $limit) : $num);
-	while ($i < $imaxinloop) {
-		$obj = $db->fetch_object($resql);
-
-		$datelimit = $db->jdate($obj->datelimite);
 
-		$facturestatic->id = $obj->id;
-		$facturestatic->ref = $obj->ref;
-		$facturestatic->ref_client = $obj->ref_client;		// deprecated
-		$facturestatic->ref_customer = $obj->ref_client;
-		$facturestatic->type = $obj->type;
-		$facturestatic->subtype = $obj->subtype;
-		$facturestatic->total_ht = $obj->total_ht;
-		$facturestatic->total_tva = $obj->total_tva;
-		$facturestatic->total_ttc = $obj->total_ttc;
-		$facturestatic->multicurrency_code = $obj->multicurrency_code;
-		$facturestatic->multicurrency_tx = $obj->multicurrency_tx;
-		$facturestatic->multicurrency_total_ht = $obj->multicurrency_total_ht;
-		$facturestatic->multicurrency_total_tva = $obj->multicurrency_total_vat;
-		$facturestatic->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
-		$facturestatic->statut = $obj->fk_statut;	// deprecated
-		$facturestatic->status = $obj->fk_statut;
-		$facturestatic->close_code = $obj->close_code;
-		$facturestatic->total_ttc = $obj->total_ttc;
-		$facturestatic->paye = $obj->paye;
-		$facturestatic->socid = $obj->fk_soc;
-
-		$facturestatic->date = $db->jdate($obj->datef);
-		$facturestatic->date_validation = $db->jdate($obj->date_valid);
-		$facturestatic->date_lim_reglement = $db->jdate($obj->datelimite);
-
-		$facturestatic->note_public = $obj->note_public;
-		$facturestatic->note_private = $obj->note_private;
-
-		if (getDolGlobalString('INVOICE_USE_SITUATION') && getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
-			$facturestatic->retained_warranty = $obj->retained_warranty;
-			$facturestatic->retained_warranty_date_limit = $obj->retained_warranty_date_limit;
-			$facturestatic->situation_final = $obj->retained_warranty_date_limit;
-			$facturestatic->situation_final = $obj->retained_warranty_date_limit;
-			$facturestatic->situation_cycle_ref = $obj->situation_cycle_ref;
-			$facturestatic->situation_counter = $obj->situation_counter;
-		}
-
-		$companystatic->id = $obj->socid;
-		$companystatic->name = $obj->name;
-		$companystatic->name_alias = $obj->alias;
-		$companystatic->client = $obj->client;
-		$companystatic->fournisseur = $obj->fournisseur;
-		$companystatic->code_client = $obj->code_client;
-		$companystatic->code_compta_client = $obj->code_compta_client;
-		$companystatic->code_fournisseur = $obj->code_fournisseur;
-		$companystatic->code_compta_fournisseur = $obj->code_compta_fournisseur;
-		$companystatic->email = $obj->email;
-		$companystatic->phone = $obj->phone;
-		$companystatic->fax = $obj->fax;
-		$companystatic->address = $obj->address;
-		$companystatic->zip = $obj->zip;
-		$companystatic->town = $obj->town;
-		$companystatic->country_code = $obj->country_code;
-
-		$projectstatic->id = $obj->project_id;
-		$projectstatic->ref = $obj->project_ref;
-		$projectstatic->title = $obj->project_label;
-
-		$paiement = $facturestatic->getSommePaiement();
-		$totalcreditnotes = $facturestatic->getSumCreditNotesUsed();
-		$totaldeposits = $facturestatic->getSumDepositsUsed();
-		$totalallpayments = $paiement + $totalcreditnotes + $totaldeposits;
-		$remaintopay = $obj->total_ttc - $totalallpayments;
-
-		$multicurrency_paiement = $facturestatic->getSommePaiement(1);
-		$multicurrency_totalcreditnotes = $facturestatic->getSumCreditNotesUsed(1);
-		$multicurrency_totaldeposits = $facturestatic->getSumDepositsUsed(1);
-
-		$totalallpayments = $paiement + $totalcreditnotes + $totaldeposits;
-		$remaintopay = price2num($facturestatic->total_ttc - $totalallpayments);
-
-		$multicurrency_totalpay = $multicurrency_paiement + $multicurrency_totalcreditnotes + $multicurrency_totaldeposits;
-		$multicurrency_remaintopay = price2num($facturestatic->multicurrency_total_ttc - $multicurrency_totalpay);
-
-		if ($facturestatic->status == Facture::STATUS_CLOSED && $facturestatic->close_code == 'discount_vat') {		// If invoice closed with discount for anticipated payment
-			$remaintopay = 0;
-			$multicurrency_remaintopay = 0;
-		}
-		if ($facturestatic->type == Facture::TYPE_CREDIT_NOTE && $obj->paye == 1) {		// If credit note closed, we take into account the amount not yet consumed
-			$remaincreditnote = $discount->getAvailableDiscounts($companystatic, null, 'rc.fk_facture_source='.$facturestatic->id);
-			$remaintopay = -$remaincreditnote;
-			$totalallpayments = price2num($facturestatic->total_ttc - $remaintopay);
-			$multicurrency_remaincreditnote = $discount->getAvailableDiscounts($companystatic, null, 'rc.fk_facture_source='.$facturestatic->id, 0, 0, 1);
-			$multicurrency_remaintopay = -$multicurrency_remaincreditnote;
-			$multicurrency_totalpay = price2num($facturestatic->multicurrency_total_ttc - $multicurrency_remaintopay);
-		}
-
-		$facturestatic->alreadypaid = $paiement;
-		$facturestatic->totalpaid = $paiement;
-		$facturestatic->totalcreditnotes = $totalcreditnotes;
-		$facturestatic->totaldeposits = $totaldeposits;
-
-		$marginInfo = array();
-		if ($with_margin_info) {
-			$facturestatic->fetch_lines();
-			$marginInfo = $formmargin->getMarginInfosArray($facturestatic);
-			$total_ht += $obj->total_ht;
-			$total_margin += $marginInfo['total_margin'];
-		}
-
-		$object = $facturestatic;
-
-		if ($mode == 'kanban') {
-			if ($i == 0) {
-				print '<tr class="trkanban"><td colspan="'.$savnbfield.'">';
-				print '<div class="box-flex-container kanban">';
-			}
-			// Output Kanban
-			if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
-				$selected = 0;
-				if (in_array($object->id, $arrayofselected)) {
-					$selected = 1;
-				}
-			}
-
-			$arraydata = array('alreadypaid' => $paiement, 'thirdparty' => $companystatic->getNomUrl(1, '', 12), 'userauthor' => $userstatic->getNomUrl(1), 'selected' => in_array($object->id, $arrayofselected));
-			print $facturestatic->getKanbanView('', $arraydata);
-			if ($i == ($imaxinloop - 1)) {
-				print '</div>';
-				print '</td></tr>';
-			}
-		} else {
-			// Show line of result
-			$j = 0;
-			print '<tr data-rowid="'.$object->id.'" class="oddeven"';
-			if ($contextpage == 'poslist') {
-				print ' onclick="parent.$(\'#poslines\').load(\'invoice.php?action=history&placeid='.$obj->id.'\', function() {parent.$.colorbox.close();';
-				if (strpos($obj->ref, 'PROV') !== false) {
-					//If is a draft invoice, load var to be able to add products
-					$place = str_replace(")", "", str_replace("(PROV-POS".$_SESSION["takeposterminal"]."-", "", $obj->ref));
-					print 'parent.place=\''.dol_escape_js($place).'\'';
-				}
-				print '});"';
-			}
-			print '>';
-
-			// Action column
-			if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
-				print '<td class="nowrap center">';
-				if (($massactionbutton || $massaction) && $contextpage != 'poslist') {   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
+	// Fields title label
+	// --------------------------------------------------------------------
+	print '<tr class="liste_titre">';
+	if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+		print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ');
+		$totalarray['nbfield']++;
+	}
+	if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER_IN_LIST')) {
+		print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.ref']['checked'])) {
+		print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.ref_client']['checked'])) {
+		print_liste_field_titre($arrayfields['f.ref_client']['label'], $_SERVER["PHP_SELF"], 'f.ref_client', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.type']['checked'])) {
+		print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.subtype']['checked'])) {
+		print_liste_field_titre($arrayfields['f.subtype']['label'], $_SERVER["PHP_SELF"], 'f.subtype', '', $param, '', $sortfield, $sortorder);
+	}
+	if (!empty($arrayfields['f.datef']['checked'])) {
+		print_liste_field_titre($arrayfields['f.datef']['label'], $_SERVER['PHP_SELF'], 'f.datef', '', $param, '', $sortfield, $sortorder, 'center ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.date_valid']['checked'])) {
+		print_liste_field_titre($arrayfields['f.date_valid']['label'], $_SERVER['PHP_SELF'], 'f.date_valid', '', $param, '', $sortfield, $sortorder, 'center ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.date_lim_reglement']['checked'])) {
+		print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, '', $sortfield, $sortorder, 'center ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['p.ref']['checked'])) {
+		$langs->load("projects");
+		print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['p.title']['checked'])) {
+		print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER['PHP_SELF'], "p.title", '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['s.nom']['checked'])) {
+		print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['s.name_alias']['checked'])) {
+		// False positive @phan-suppress-next-line PhanTypeInvalidDimOffset
+		print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER['PHP_SELF'], 's.name_alias', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['s2.nom']['checked'])) {
+		print_liste_field_titre($arrayfields['s2.nom']['label'], $_SERVER['PHP_SELF'], 's2.nom', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['s.code_client']['checked'])) {
+		print_liste_field_titre($arrayfields['s.code_client']['label'], $_SERVER['PHP_SELF'], 's.code_client', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['s.town']['checked'])) {
+		print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['s.zip']['checked'])) {
+		print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['state.nom']['checked'])) {
+		print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['country.code_iso']['checked'])) {
+		print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['typent.code']['checked'])) {
+		print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) {
+		print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) {
+		print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.module_source']['checked'])) {
+		print_liste_field_titre($arrayfields['f.module_source']['label'], $_SERVER["PHP_SELF"], "f.module_source", "", $param, "", $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.pos_source']['checked'])) {
+		print_liste_field_titre($arrayfields['f.pos_source']['label'], $_SERVER["PHP_SELF"], "f.pos_source", "", $param, "", $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.total_ht']['checked'])) {
+		print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total_ht', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.total_tva']['checked'])) {
+		print_liste_field_titre($arrayfields['f.total_tva']['label'], $_SERVER['PHP_SELF'], 'f.total_tva', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.total_localtax1']['checked'])) {
+		print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.total_localtax2']['checked'])) {
+		print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.total_ttc']['checked'])) {
+		print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['u.login']['checked'])) {
+		print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, '', $sortfield, $sortorder, 'center ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['sale_representative']['checked'])) {
+		print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", "$param", '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.retained_warranty']['checked'])) {
+		print_liste_field_titre($arrayfields['f.retained_warranty']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['dynamount_payed']['checked'])) {
+		print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['rtp']['checked'])) {
+		print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.multicurrency_code']['checked'])) {
+		print_liste_field_titre($arrayfields['f.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_code', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.multicurrency_tx']['checked'])) {
+		print_liste_field_titre($arrayfields['f.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_tx', '', $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) {
+		print_liste_field_titre($arrayfields['f.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ht', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) {
+		print_liste_field_titre($arrayfields['f.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_tva', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) {
+		print_liste_field_titre($arrayfields['f.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ttc', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) {
+		print_liste_field_titre($arrayfields['multicurrency_dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['multicurrency_rtp']['checked'])) {
+		print_liste_field_titre($arrayfields['multicurrency_rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['total_pa']['checked'])) {
+		print_liste_field_titre($arrayfields['total_pa']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['total_margin']['checked'])) {
+		print_liste_field_titre($arrayfields['total_margin']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['total_margin_rate']['checked'])) {
+		print_liste_field_titre($arrayfields['total_margin_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['total_mark_rate']['checked'])) {
+		print_liste_field_titre($arrayfields['total_mark_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
+		$totalarray['nbfield']++;
+	}
+	// Extra fields
+	include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_search_title.tpl.php';
+	// Hook fields
+	$parameters = array('arrayfields' => $arrayfields, 'param' => $param, 'sortfield' => $sortfield, 'sortorder' => $sortorder, 'totalarray' => $totalarray);
+	$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	print $hookmanager->resPrint;
+	if (!empty($arrayfields['f.datec']['checked'])) {
+		print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'nowraponall center ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.tms']['checked'])) {
+		print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'nowraponall center ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.date_closing']['checked'])) {
+		print_liste_field_titre($arrayfields['f.date_closing']['label'], $_SERVER["PHP_SELF"], "f.date_closing", "", $param, '', $sortfield, $sortorder, 'nowraponall center ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.note_public']['checked'])) {
+		print_liste_field_titre($arrayfields['f.note_public']['label'], $_SERVER["PHP_SELF"], "f.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.note_private']['checked'])) {
+		print_liste_field_titre($arrayfields['f.note_private']['label'], $_SERVER["PHP_SELF"], "f.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+		$totalarray['nbfield']++;
+	}
+	if (!empty($arrayfields['f.fk_fac_rec_source']['checked'])) {
+		print_liste_field_titre($arrayfields['f.fk_fac_rec_source']['label'], $_SERVER["PHP_SELF"], "facrec.titre", "", $param, '', $sortfield, $sortorder);
+		$totalarray['nbfield']++;
+	}
+	// Import key
+	if (!empty($arrayfields['f.import_key']['checked'])) {
+		print_liste_field_titre($arrayfields['f.import_key']['label'], $_SERVER["PHP_SELF"], "f.import_key", "", $param, '', $sortfield, $sortorder, 'center ');
+		$totalarray['nbfield']++;
+	}
+	// Status
+	if (!empty($arrayfields['f.fk_statut']['checked'])) {
+		print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "f.fk_statut,f.paye,f.type", "", $param, '', $sortfield, $sortorder, 'center ');
+		$totalarray['nbfield']++;
+	}
+	if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+		print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch center ');
+		$totalarray['nbfield']++;
+	}
+
+	print "</tr>\n";
+
+	$projectstatic = new Project($db);
+	$discount = new DiscountAbsolute($db);
+	$userstatic = new User($db);
+
+	// Loop on record
+	// --------------------------------------------------------------------
+	if ($num > 0) {
+		$i = 0;
+		$savnbfield = $totalarray['nbfield'];
+		$totalarray = array();
+		$totalarray['nbfield'] = 0;
+		$totalarray['val'] = array();
+		$totalarray['val']['f.total_ht'] = 0;
+		$totalarray['val']['f.total_tva'] = 0;
+		$totalarray['val']['f.total_localtax1'] = 0;
+		$totalarray['val']['f.total_localtax1'] = 0;
+		$totalarray['val']['f.total_ttc'] = 0;
+		$totalarray['val']['dynamount_payed'] = 0;
+		$totalarray['val']['rtp'] = 0;
+
+		$typenArray = $formcompany->typent_array(1);
+
+		$with_margin_info = false;
+		if (
+			isModEnabled('margin') && (
+				!empty($arrayfields['total_pa']['checked'])
+				|| !empty($arrayfields['total_margin']['checked'])
+				|| !empty($arrayfields['total_margin_rate']['checked'])
+				|| !empty($arrayfields['total_mark_rate']['checked'])
+			)
+		) {
+			$with_margin_info = true;
+		}
+		$total_ht = 0;
+		$total_margin = 0;
+
+		$imaxinloop = ($limit ? min($num, $limit) : $num);
+		while ($i < $imaxinloop) {
+			$obj = $db->fetch_object($resql);
+
+			$datelimit = $db->jdate($obj->datelimite);
+
+			$facturestatic->id = $obj->id;
+			$facturestatic->ref = $obj->ref;
+			$facturestatic->ref_client = $obj->ref_client;		// deprecated
+			$facturestatic->ref_customer = $obj->ref_client;
+			$facturestatic->type = $obj->type;
+			$facturestatic->subtype = $obj->subtype;
+			$facturestatic->total_ht = $obj->total_ht;
+			$facturestatic->total_tva = $obj->total_tva;
+			$facturestatic->total_ttc = $obj->total_ttc;
+			$facturestatic->multicurrency_code = $obj->multicurrency_code;
+			$facturestatic->multicurrency_tx = $obj->multicurrency_tx;
+			$facturestatic->multicurrency_total_ht = $obj->multicurrency_total_ht;
+			$facturestatic->multicurrency_total_tva = $obj->multicurrency_total_vat;
+			$facturestatic->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
+			$facturestatic->statut = $obj->fk_statut;	// deprecated
+			$facturestatic->status = $obj->fk_statut;
+			$facturestatic->close_code = $obj->close_code;
+			$facturestatic->total_ttc = $obj->total_ttc;
+			$facturestatic->paye = $obj->paye;
+			$facturestatic->socid = $obj->fk_soc;
+
+			$facturestatic->date = $db->jdate($obj->datef);
+			$facturestatic->date_validation = $db->jdate($obj->date_valid);
+			$facturestatic->date_lim_reglement = $db->jdate($obj->datelimite);
+
+			$facturestatic->note_public = $obj->note_public;
+			$facturestatic->note_private = $obj->note_private;
+
+			if (getDolGlobalString('INVOICE_USE_SITUATION') && getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
+				$facturestatic->retained_warranty = $obj->retained_warranty;
+				$facturestatic->retained_warranty_date_limit = $obj->retained_warranty_date_limit;
+				$facturestatic->situation_final = $obj->retained_warranty_date_limit;
+				$facturestatic->situation_final = $obj->retained_warranty_date_limit;
+				$facturestatic->situation_cycle_ref = $obj->situation_cycle_ref;
+				$facturestatic->situation_counter = $obj->situation_counter;
+			}
+
+			$companystatic->id = $obj->socid;
+			$companystatic->name = $obj->name;
+			$companystatic->name_alias = $obj->alias;
+			$companystatic->client = $obj->client;
+			$companystatic->fournisseur = $obj->fournisseur;
+			$companystatic->code_client = $obj->code_client;
+			$companystatic->code_compta_client = $obj->code_compta_client;
+			$companystatic->code_fournisseur = $obj->code_fournisseur;
+			$companystatic->code_compta_fournisseur = $obj->code_compta_fournisseur;
+			$companystatic->email = $obj->email;
+			$companystatic->phone = $obj->phone;
+			$companystatic->fax = $obj->fax;
+			$companystatic->address = $obj->address;
+			$companystatic->zip = $obj->zip;
+			$companystatic->town = $obj->town;
+			$companystatic->country_code = $obj->country_code;
+
+			$projectstatic->id = $obj->project_id;
+			$projectstatic->ref = $obj->project_ref;
+			$projectstatic->title = $obj->project_label;
+
+			$paiement = $facturestatic->getSommePaiement();
+			$totalcreditnotes = $facturestatic->getSumCreditNotesUsed();
+			$totaldeposits = $facturestatic->getSumDepositsUsed();
+			$totalallpayments = $paiement + $totalcreditnotes + $totaldeposits;
+			$remaintopay = $obj->total_ttc - $totalallpayments;
+
+			$multicurrency_paiement = $facturestatic->getSommePaiement(1);
+			$multicurrency_totalcreditnotes = $facturestatic->getSumCreditNotesUsed(1);
+			$multicurrency_totaldeposits = $facturestatic->getSumDepositsUsed(1);
+
+			$totalallpayments = $paiement + $totalcreditnotes + $totaldeposits;
+			$remaintopay = price2num($facturestatic->total_ttc - $totalallpayments);
+
+			$multicurrency_totalpay = $multicurrency_paiement + $multicurrency_totalcreditnotes + $multicurrency_totaldeposits;
+			$multicurrency_remaintopay = price2num($facturestatic->multicurrency_total_ttc - $multicurrency_totalpay);
+
+			if ($facturestatic->status == Facture::STATUS_CLOSED && $facturestatic->close_code == 'discount_vat') {		// If invoice closed with discount for anticipated payment
+				$remaintopay = 0;
+				$multicurrency_remaintopay = 0;
+			}
+			if ($facturestatic->type == Facture::TYPE_CREDIT_NOTE && $obj->paye == 1) {		// If credit note closed, we take into account the amount not yet consumed
+				$remaincreditnote = $discount->getAvailableDiscounts($companystatic, null, 'rc.fk_facture_source=' . $facturestatic->id);
+				$remaintopay = -$remaincreditnote;
+				$totalallpayments = price2num($facturestatic->total_ttc - $remaintopay);
+				$multicurrency_remaincreditnote = $discount->getAvailableDiscounts($companystatic, null, 'rc.fk_facture_source=' . $facturestatic->id, 0, 0, 1);
+				$multicurrency_remaintopay = -$multicurrency_remaincreditnote;
+				$multicurrency_totalpay = price2num($facturestatic->multicurrency_total_ttc - $multicurrency_remaintopay);
+			}
+
+			$facturestatic->alreadypaid = $paiement;
+			$facturestatic->totalpaid = $paiement;
+			$facturestatic->totalcreditnotes = $totalcreditnotes;
+			$facturestatic->totaldeposits = $totaldeposits;
+
+			$marginInfo = array();
+			if ($with_margin_info) {
+				$facturestatic->fetch_lines();
+				$marginInfo = $formmargin->getMarginInfosArray($facturestatic);
+				$total_ht += $obj->total_ht;
+				$total_margin += $marginInfo['total_margin'];
+			}
+
+			$object = $facturestatic;
+
+			if ($mode == 'kanban') {
+				if ($i == 0) {
+					print '<tr class="trkanban"><td colspan="' . $savnbfield . '">';
+					print '<div class="box-flex-container kanban">';
+				}
+				// Output Kanban
+				if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
 					$selected = 0;
-					if (in_array($obj->id, $arrayofselected)) {
+					if (in_array($object->id, $arrayofselected)) {
 						$selected = 1;
 					}
-					print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected ? ' checked="checked"' : '').'>';
-				}
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
 				}
-			}
 
-			// No
-			if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER_IN_LIST')) {
-				print '<td>'.(($offset * $limit) + $i).'</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				$arraydata = array('alreadypaid' => $paiement, 'thirdparty' => $companystatic->getNomUrl(1, '', 12), 'userauthor' => $userstatic->getNomUrl(1), 'selected' => in_array($object->id, $arrayofselected));
+				print $facturestatic->getKanbanView('', $arraydata);
+				if ($i == ($imaxinloop - 1)) {
+					print '</div>';
+					print '</td></tr>';
 				}
-			}
-
-			// Ref
-			if (!empty($arrayfields['f.ref']['checked'])) {
-				print '<td class="nowraponall">';
-
-				print '<table class="nobordernopadding"><tr class="nocellnopadd">';
-
-				print '<td class="nobordernopadding nowraponall">';
+			} else {
+				// Show line of result
+				$j = 0;
+				print '<tr data-rowid="' . $object->id . '" class="oddeven"';
 				if ($contextpage == 'poslist') {
-					print dol_escape_htmltag($obj->ref);
-				} else {
-					print $facturestatic->getNomUrl(1, '', 200, 0, '', 0, 1);
+					print ' onclick="parent.$(\'#poslines\').load(\'invoice.php?action=history&placeid=' . $obj->id . '\', function() {parent.$.colorbox.close();';
+					if (strpos($obj->ref, 'PROV') !== false) {
+						//If is a draft invoice, load var to be able to add products
+						$place = str_replace(")", "", str_replace("(PROV-POS" . $_SESSION["takeposterminal"] . "-", "", $obj->ref));
+						print 'parent.place=\'' . dol_escape_js($place) . '\'';
+					}
+					print '});"';
 				}
+				print '>';
 
-				$filename = dol_sanitizeFileName($obj->ref);
-				$filepath = $conf->invoice->multidir_output[$obj->entity] ?? $conf->invoice->dir_output;
-				$filedir = $filepath.'/'.$filename;
-
-				$urlsource = $_SERVER['PHP_SELF'].'?id='.$obj->id;
-				print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir);
-				print '</td>';
-				print '</tr>';
-				print '</table>';
-
-				print "</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Action column
+				if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+					print '<td class="nowrap center">';
+					if (($massactionbutton || $massaction) && $contextpage != 'poslist') {   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
+						$selected = 0;
+						if (in_array($obj->id, $arrayofselected)) {
+							$selected = 1;
+						}
+						print '<input id="cb' . $obj->id . '" class="flat checkforselect" type="checkbox" name="toselect[]" value="' . $obj->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
+					}
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Customer ref
-			if (!empty($arrayfields['f.ref_client']['checked'])) {
-				print '<td class="nowrap tdoverflowmax200">';
-				print dol_escape_htmltag($obj->ref_client);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// No
+				if (getDolGlobalString('MAIN_VIEW_LINE_NUMBER_IN_LIST')) {
+					print '<td>' . (($offset * $limit) + $i) . '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Type
-			if (!empty($arrayfields['f.type']['checked'])) {
-				print '<td class="nowraponall tdoverflowmax100" title="'.$facturestatic->getLibType().'">';
-				print $facturestatic->getLibType(2);
-				print "</td>";
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-			}
+				// Ref
+				if (!empty($arrayfields['f.ref']['checked'])) {
+					print '<td class="nowraponall">';
+
+					print '<table class="nobordernopadding"><tr class="nocellnopadd">';
+
+					print '<td class="nobordernopadding nowraponall">';
+					if ($contextpage == 'poslist') {
+						print dol_escape_htmltag($obj->ref);
+					} else {
+						print $facturestatic->getNomUrl(1, '', 200, 0, '', 0, 1);
+					}
 
-			// Invoice Subtype
-			if (!empty($arrayfields['f.subtype']['checked'])) {
-				$labeltoshow = '';
-				if ($facturestatic->subtype > 0) {
-					$labeltoshow = $facturestatic->getSubtypeLabel('facture');
-				}
-				print '<td class="nowraponall tdoverflowmax300" title="'.$labeltoshow.'">';
-				print $labeltoshow;
-				print "</td>";
-				if (!$i) {
-					$totalarray['nbfield']++;
+					$filename = dol_sanitizeFileName($obj->ref);
+					$filepath = $conf->invoice->multidir_output[$obj->entity] ?? $conf->invoice->dir_output;
+					$filedir = $filepath . '/' . $filename;
+
+					$urlsource = $_SERVER['PHP_SELF'] . '?id=' . $obj->id;
+					print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir);
+					print '</td>';
+					print '</tr>';
+					print '</table>';
+
+					print "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Date
-			if (!empty($arrayfields['f.datef']['checked'])) {
-				print '<td align="center" class="nowraponall">';
-				print dol_print_date($db->jdate($obj->datef), 'day');
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Customer ref
+				if (!empty($arrayfields['f.ref_client']['checked'])) {
+					print '<td class="nowrap tdoverflowmax200">';
+					print dol_escape_htmltag($obj->ref_client);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Date
-			if (!empty($arrayfields['f.date_valid']['checked'])) {
-				print '<td align="center" class="nowraponall">';
-				print dol_print_date($db->jdate($obj->date_valid), 'day');
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Type
+				if (!empty($arrayfields['f.type']['checked'])) {
+					print '<td class="nowraponall tdoverflowmax100" title="' . $facturestatic->getLibType() . '">';
+					print $facturestatic->getLibType(2);
+					print "</td>";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Date limit
-			if (!empty($arrayfields['f.date_lim_reglement']['checked'])) {
-				print '<td align="center" class="nowraponall">'.dol_print_date($datelimit, 'day');
-				if ($facturestatic->hasDelay()) {
-					print img_warning($langs->trans('Alert').' - '.$langs->trans('Late'));
-				}
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Invoice Subtype
+				if (!empty($arrayfields['f.subtype']['checked'])) {
+					$labeltoshow = '';
+					if ($facturestatic->subtype > 0) {
+						$labeltoshow = $facturestatic->getSubtypeLabel('facture');
+					}
+					print '<td class="nowraponall tdoverflowmax300" title="' . $labeltoshow . '">';
+					print $labeltoshow;
+					print "</td>";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Project ref
-			if (!empty($arrayfields['p.ref']['checked'])) {
-				print '<td class="nocellnopadd nowraponall">';
-				if ($obj->project_id > 0) {
-					print $projectstatic->getNomUrl(1);
-				}
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Date
+				if (!empty($arrayfields['f.datef']['checked'])) {
+					print '<td align="center" class="nowraponall">';
+					print dol_print_date($db->jdate($obj->datef), 'day');
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Project title
-			if (!empty($arrayfields['p.title']['checked'])) {
-				print '<td class="nowraponall">';
-				if ($obj->project_id > 0) {
-					print dol_escape_htmltag($projectstatic->title);
-				}
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Date
+				if (!empty($arrayfields['f.date_valid']['checked'])) {
+					print '<td align="center" class="nowraponall">';
+					print dol_print_date($db->jdate($obj->date_valid), 'day');
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Third party
-			if (!empty($arrayfields['s.nom']['checked'])) {
-				print '<td class="tdoverflowmax150">';
-				if ($contextpage == 'poslist') {
-					print dol_escape_htmltag($companystatic->name);
-				} else {
-					print $companystatic->getNomUrl(1, 'customer', 0, 0, -1, empty($arrayfields['s.name_alias']['checked']) ? 0 : 1);
+				// Date limit
+				if (!empty($arrayfields['f.date_lim_reglement']['checked'])) {
+					print '<td align="center" class="nowraponall">' . dol_print_date($datelimit, 'day');
+					if ($facturestatic->hasDelay()) {
+						print img_warning($langs->trans('Alert') . ' - ' . $langs->trans('Late'));
+					}
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-			}
-			// Alias
-			if (!empty($arrayfields['s.name_alias']['checked'])) {
-				print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($companystatic->name_alias).'">';
-				print dol_escape_htmltag($companystatic->name_alias);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-			}
-			// Parent company
-			if (!empty($arrayfields['s2.nom']['checked'])) {
-				print '<td class="tdoverflowmax200">';
-				if ($obj->fk_parent > 0) {
-					if (!isset($company_url_list[$obj->fk_parent])) {
-						$companyparent = new Societe($db);
-						$res = $companyparent->fetch($obj->fk_parent);
-						if ($res > 0) {
-							$company_url_list[$obj->fk_parent] = $companyparent->getNomUrl(1);
-						}
+
+				// Project ref
+				if (!empty($arrayfields['p.ref']['checked'])) {
+					print '<td class="nocellnopadd nowraponall">';
+					if ($obj->project_id > 0) {
+						print $projectstatic->getNomUrl(1);
 					}
-					if (isset($company_url_list[$obj->fk_parent])) {
-						print $company_url_list[$obj->fk_parent];
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
 					}
 				}
-				print "</td>";
-				if (!$i) {
-					$totalarray['nbfield']++;
+
+				// Project title
+				if (!empty($arrayfields['p.title']['checked'])) {
+					print '<td class="nowraponall">';
+					if ($obj->project_id > 0) {
+						print dol_escape_htmltag($projectstatic->title);
+					}
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Customer Code
-			if (!empty($arrayfields['s.code_client']['checked'])) {
-				print '<td class="tdoverflowmax150" title="'.dol_escape_htmltag($companystatic->code_client).'">';
-				print dol_escape_htmltag($companystatic->code_client);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+
+				// Third party
+				if (!empty($arrayfields['s.nom']['checked'])) {
+					print '<td class="tdoverflowmax150">';
+					if ($contextpage == 'poslist') {
+						print dol_escape_htmltag($companystatic->name);
+					} else {
+						print $companystatic->getNomUrl(1, 'customer', 0, 0, -1, empty($arrayfields['s.name_alias']['checked']) ? 0 : 1);
+					}
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Town
-			if (!empty($arrayfields['s.town']['checked'])) {
-				print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($obj->town).'">';
-				print dol_escape_htmltag($obj->town);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Alias
+				if (!empty($arrayfields['s.name_alias']['checked'])) {
+					print '<td class="tdoverflowmax150" title="' . dol_escape_htmltag($companystatic->name_alias) . '">';
+					print dol_escape_htmltag($companystatic->name_alias);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Zip
-			if (!empty($arrayfields['s.zip']['checked'])) {
-				print '<td class="nowraponall">';
-				print dol_escape_htmltag($obj->zip);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Parent company
+				if (!empty($arrayfields['s2.nom']['checked'])) {
+					print '<td class="tdoverflowmax200">';
+					if ($obj->fk_parent > 0) {
+						if (!isset($company_url_list[$obj->fk_parent])) {
+							$companyparent = new Societe($db);
+							$res = $companyparent->fetch($obj->fk_parent);
+							if ($res > 0) {
+								$company_url_list[$obj->fk_parent] = $companyparent->getNomUrl(1);
+							}
+						}
+						if (isset($company_url_list[$obj->fk_parent])) {
+							print $company_url_list[$obj->fk_parent];
+						}
+					}
+					print "</td>";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// State
-			if (!empty($arrayfields['state.nom']['checked'])) {
-				print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($obj->state_name).'">'.dol_escape_htmltag($obj->state_name)."</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Customer Code
+				if (!empty($arrayfields['s.code_client']['checked'])) {
+					print '<td class="tdoverflowmax150" title="' . dol_escape_htmltag($companystatic->code_client) . '">';
+					print dol_escape_htmltag($companystatic->code_client);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Country
-			if (!empty($arrayfields['country.code_iso']['checked'])) {
-				$tmparray = getCountry($obj->fk_pays, 'all');
-				print '<td class="center tdoverflowmax100" title="'.dol_escape_htmltag($tmparray['label']).'">';
-				print dol_escape_htmltag($tmparray['label']);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Town
+				if (!empty($arrayfields['s.town']['checked'])) {
+					print '<td class="tdoverflowmax100" title="' . dol_escape_htmltag($obj->town) . '">';
+					print dol_escape_htmltag($obj->town);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Type ent
-			if (!empty($arrayfields['typent.code']['checked'])) {
-				if (!is_array($typenArray) || count($typenArray) == 0) {
-					$typenArray = $formcompany->typent_array(1);
+				// Zip
+				if (!empty($arrayfields['s.zip']['checked'])) {
+					print '<td class="nowraponall">';
+					print dol_escape_htmltag($obj->zip);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-				print '<td class="center tdoverflowmax100" title="'.dolPrintHTML($typenArray[$obj->typent_code]).'">';
-				if (!empty($obj->typent_code)) {
-					print $typenArray[$obj->typent_code];
+				// State
+				if (!empty($arrayfields['state.nom']['checked'])) {
+					print '<td class="tdoverflowmax100" title="' . dol_escape_htmltag($obj->state_name) . '">' . dol_escape_htmltag($obj->state_name) . "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Country
+				if (!empty($arrayfields['country.code_iso']['checked'])) {
+					$tmparray = getCountry($obj->fk_pays, 'all');
+					print '<td class="center tdoverflowmax100" title="' . dol_escape_htmltag($tmparray['label']) . '">';
+					print dol_escape_htmltag($tmparray['label']);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Staff
-			if (!empty($arrayfields['staff.code']['checked'])) {
-				if (!is_array($conf->cache['staff']) || count($conf->cache['staff']) == 0) {
-					$conf->cache['staff'] = $formcompany->effectif_array(1);
+				// Type ent
+				if (!empty($arrayfields['typent.code']['checked'])) {
+					if (!is_array($typenArray) || count($typenArray) == 0) {
+						$typenArray = $formcompany->typent_array(1);
+					}
+					print '<td class="center tdoverflowmax100" title="' . dolPrintHTML($typenArray[$obj->typent_code]) . '">';
+					if (!empty($obj->typent_code)) {
+						print $typenArray[$obj->typent_code];
+					}
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-				print '<td class="center tdoverflowmax100" title="'.dolPrintHTML($conf->cache['staff'][$obj->staff_code]).'">';
-				print $conf->cache['staff'][$obj->staff_code];
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Staff
+				if (!empty($arrayfields['staff.code']['checked'])) {
+					if (!is_array($conf->cache['staff']) || count($conf->cache['staff']) == 0) {
+						$conf->cache['staff'] = $formcompany->effectif_array(1);
+					}
+					print '<td class="center tdoverflowmax100" title="' . dolPrintHTML($conf->cache['staff'][$obj->staff_code]) . '">';
+					print $conf->cache['staff'][$obj->staff_code];
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Payment mode
-			if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) {
-				$s = $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1, 0, '', 1);
-				print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($s).'">';
-				print $s;
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Payment mode
+				if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) {
+					$s = $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1, 0, '', 1);
+					print '<td class="tdoverflowmax100" title="' . dol_escape_htmltag($s) . '">';
+					print $s;
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Payment terms
-			if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) {
-				$s = $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none', 0, '', -1, -1, 1);
-				print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($s).'">';
-				print $s;
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Payment terms
+				if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) {
+					$s = $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none', 0, '', -1, -1, 1);
+					print '<td class="tdoverflowmax100" title="' . dol_escape_htmltag($s) . '">';
+					print $s;
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Module Source
-			if (!empty($arrayfields['f.module_source']['checked'])) {
-				print '<td>';
-				print dol_escape_htmltag($obj->module_source);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Module Source
+				if (!empty($arrayfields['f.module_source']['checked'])) {
+					print '<td>';
+					print dol_escape_htmltag($obj->module_source);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// POS Terminal
-			if (!empty($arrayfields['f.pos_source']['checked'])) {
-				print '<td>';
-				print dol_escape_htmltag($obj->pos_source);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// POS Terminal
+				if (!empty($arrayfields['f.pos_source']['checked'])) {
+					print '<td>';
+					print dol_escape_htmltag($obj->pos_source);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Amount HT
-			if (!empty($arrayfields['f.total_ht']['checked'])) {
-				print '<td class="right nowraponall amount">'.price($obj->total_ht)."</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-				if (!$i) {
-					$totalarray['pos'][$totalarray['nbfield']] = 'f.total_ht';
-				}
-				$totalarray['val']['f.total_ht'] += $obj->total_ht;
-			}
-			// Amount VAT
-			if (!empty($arrayfields['f.total_tva']['checked'])) {
-				print '<td class="right nowraponall amount">'.price($obj->total_tva)."</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-				if (!$i) {
-					$totalarray['pos'][$totalarray['nbfield']] = 'f.total_tva';
-				}
-				$totalarray['val']['f.total_tva'] += $obj->total_tva;
-			}
-			// Amount LocalTax1
-			if (!empty($arrayfields['f.total_localtax1']['checked'])) {
-				print '<td class="right nowraponall amount">'.price($obj->total_localtax1)."</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-				if (!$i) {
-					$totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax1';
+				// Amount HT
+				if (!empty($arrayfields['f.total_ht']['checked'])) {
+					print '<td class="right nowraponall amount">' . price($obj->total_ht) . "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
+					if (!$i) {
+						$totalarray['pos'][$totalarray['nbfield']] = 'f.total_ht';
+					}
+					$totalarray['val']['f.total_ht'] += $obj->total_ht;
 				}
-				$totalarray['val']['f.total_localtax1'] += $obj->total_localtax1;
-			}
-			// Amount LocalTax2
-			if (!empty($arrayfields['f.total_localtax2']['checked'])) {
-				print '<td class="right nowraponall amount">'.price($obj->total_localtax2)."</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Amount VAT
+				if (!empty($arrayfields['f.total_tva']['checked'])) {
+					print '<td class="right nowraponall amount">' . price($obj->total_tva) . "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
+					if (!$i) {
+						$totalarray['pos'][$totalarray['nbfield']] = 'f.total_tva';
+					}
+					$totalarray['val']['f.total_tva'] += $obj->total_tva;
 				}
-				if (!$i) {
-					$totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax2';
+				// Amount LocalTax1
+				if (!empty($arrayfields['f.total_localtax1']['checked'])) {
+					print '<td class="right nowraponall amount">' . price($obj->total_localtax1) . "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
+					if (!$i) {
+						$totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax1';
+					}
+					$totalarray['val']['f.total_localtax1'] += $obj->total_localtax1;
 				}
-				$totalarray['val']['f.total_localtax2'] += $obj->total_localtax2;
-			}
-			// Amount TTC
-			if (!empty($arrayfields['f.total_ttc']['checked'])) {
-				print '<td class="right nowraponall amount">'.price($obj->total_ttc)."</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Amount LocalTax2
+				if (!empty($arrayfields['f.total_localtax2']['checked'])) {
+					print '<td class="right nowraponall amount">' . price($obj->total_localtax2) . "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
+					if (!$i) {
+						$totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax2';
+					}
+					$totalarray['val']['f.total_localtax2'] += $obj->total_localtax2;
 				}
-				if (!$i) {
-					$totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc';
+				// Amount TTC
+				if (!empty($arrayfields['f.total_ttc']['checked'])) {
+					print '<td class="right nowraponall amount">' . price($obj->total_ttc) . "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
+					if (!$i) {
+						$totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc';
+					}
+					$totalarray['val']['f.total_ttc'] += $obj->total_ttc;
 				}
-				$totalarray['val']['f.total_ttc'] += $obj->total_ttc;
-			}
-
-			$userstatic->id = $obj->fk_user_author;
-			$userstatic->login = $obj->login;
-			$userstatic->lastname = $obj->lastname;
-			$userstatic->firstname = $obj->firstname;
-			$userstatic->email = $obj->user_email;
-			$userstatic->status = $obj->user_statut;
-			$userstatic->entity = $obj->entity;
-			$userstatic->photo = $obj->photo;
-			$userstatic->office_phone = $obj->office_phone;
-			$userstatic->office_fax = $obj->office_fax;
-			$userstatic->user_mobile = $obj->user_mobile;
-			$userstatic->job = $obj->job;
-			$userstatic->gender = $obj->gender;
 
-			// Author
-			if (!empty($arrayfields['u.login']['checked'])) {
-				print '<td class="tdoverflowmax125">';
-				if ($userstatic->id) {
-					print $userstatic->getNomUrl(-1);
-				} else {
-					print '&nbsp;';
-				}
-				print "</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				$userstatic->id = $obj->fk_user_author;
+				$userstatic->login = $obj->login;
+				$userstatic->lastname = $obj->lastname;
+				$userstatic->firstname = $obj->firstname;
+				$userstatic->email = $obj->user_email;
+				$userstatic->status = $obj->user_statut;
+				$userstatic->entity = $obj->entity;
+				$userstatic->photo = $obj->photo;
+				$userstatic->office_phone = $obj->office_phone;
+				$userstatic->office_fax = $obj->office_fax;
+				$userstatic->user_mobile = $obj->user_mobile;
+				$userstatic->job = $obj->job;
+				$userstatic->gender = $obj->gender;
+
+				// Author
+				if (!empty($arrayfields['u.login']['checked'])) {
+					print '<td class="tdoverflowmax125">';
+					if ($userstatic->id) {
+						print $userstatic->getNomUrl(-1);
+					} else {
+						print '&nbsp;';
+					}
+					print "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			if (!empty($arrayfields['sale_representative']['checked'])) {
-				// Sales representatives
-				print '<td>';
-				if ($obj->socid > 0) {
-					$listsalesrepresentatives = $companystatic->getSalesRepresentatives($user);
-					if ($listsalesrepresentatives < 0) {
-						dol_print_error($db);
-					}
-					$nbofsalesrepresentative = count($listsalesrepresentatives);
-					if ($nbofsalesrepresentative > 6) {
-						// We print only number
-						print $nbofsalesrepresentative;
-					} elseif ($nbofsalesrepresentative > 0) {
-						$j = 0;
-						foreach ($listsalesrepresentatives as $val) {
-							$userstatic->id = $val['id'];
-							$userstatic->lastname = $val['lastname'];
-							$userstatic->firstname = $val['firstname'];
-							$userstatic->email = $val['email'];
-							$userstatic->status = $val['statut'];
-							$userstatic->entity = $val['entity'];
-							$userstatic->photo = $val['photo'];
-							$userstatic->login = $val['login'];
-							$userstatic->office_phone = $val['office_phone'];
-							$userstatic->office_fax = $val['office_fax'];
-							$userstatic->user_mobile = $val['user_mobile'];
-							$userstatic->job = $val['job'];
-							$userstatic->gender = $val['gender'];
-							//print '<div class="float">':
-							print ($nbofsalesrepresentative < 2) ? $userstatic->getNomUrl(-1, '', 0, 0, 12) : $userstatic->getNomUrl(-2);
-							$j++;
-							if ($j < $nbofsalesrepresentative) {
-								print ' ';
+				if (!empty($arrayfields['sale_representative']['checked'])) {
+					// Sales representatives
+					print '<td>';
+					if ($obj->socid > 0) {
+						$listsalesrepresentatives = $companystatic->getSalesRepresentatives($user);
+						if ($listsalesrepresentatives < 0) {
+							dol_print_error($db);
+						}
+						$nbofsalesrepresentative = count($listsalesrepresentatives);
+						if ($nbofsalesrepresentative > 6) {
+							// We print only number
+							print $nbofsalesrepresentative;
+						} elseif ($nbofsalesrepresentative > 0) {
+							$j = 0;
+							foreach ($listsalesrepresentatives as $val) {
+								$userstatic->id = $val['id'];
+								$userstatic->lastname = $val['lastname'];
+								$userstatic->firstname = $val['firstname'];
+								$userstatic->email = $val['email'];
+								$userstatic->status = $val['statut'];
+								$userstatic->entity = $val['entity'];
+								$userstatic->photo = $val['photo'];
+								$userstatic->login = $val['login'];
+								$userstatic->office_phone = $val['office_phone'];
+								$userstatic->office_fax = $val['office_fax'];
+								$userstatic->user_mobile = $val['user_mobile'];
+								$userstatic->job = $val['job'];
+								$userstatic->gender = $val['gender'];
+								//print '<div class="float">':
+								print ($nbofsalesrepresentative < 2) ? $userstatic->getNomUrl(-1, '', 0, 0, 12) : $userstatic->getNomUrl(-2);
+								$j++;
+								if ($j < $nbofsalesrepresentative) {
+									print ' ';
+								}
+								//print '</div>';
 							}
-							//print '</div>';
 						}
+						//else print $langs->trans("NoSalesRepresentativeAffected");
+					}
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
 					}
-					//else print $langs->trans("NoSalesRepresentativeAffected");
-				}
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
 				}
-			}
 
-			if (!empty($arrayfields['f.retained_warranty']['checked'])) {
-				print '<td align="right">'.(!empty($obj->retained_warranty) ? price($obj->retained_warranty).'%' : '&nbsp;').'</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				if (!empty($arrayfields['f.retained_warranty']['checked'])) {
+					print '<td align="right">' . (!empty($obj->retained_warranty) ? price($obj->retained_warranty) . '%' : '&nbsp;') . '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			if (!empty($arrayfields['dynamount_payed']['checked'])) {
-				print '<td class="right nowraponall amount">'.(!empty($totalallpayments) ? price($totalallpayments, 0, $langs) : '&nbsp;').'</td>'; // TODO Use a denormalized field
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-				if (!$i) {
-					$totalarray['pos'][$totalarray['nbfield']] = 'dynamount_payed';
+				if (!empty($arrayfields['dynamount_payed']['checked'])) {
+					print '<td class="right nowraponall amount">' . (!empty($totalallpayments) ? price($totalallpayments, 0, $langs) : '&nbsp;') . '</td>'; // TODO Use a denormalized field
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
+					if (!$i) {
+						$totalarray['pos'][$totalarray['nbfield']] = 'dynamount_payed';
+					}
+					$totalarray['val']['dynamount_payed'] += $totalallpayments;
 				}
-				$totalarray['val']['dynamount_payed'] += $totalallpayments;
-			}
 
-			// Pending amount
-			if (!empty($arrayfields['rtp']['checked'])) {
-				print '<td class="right nowraponall amount">';
-				print(!empty($remaintopay) ? price($remaintopay, 0, $langs) : '&nbsp;');
-				print '</td>'; // TODO Use a denormalized field
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-				if (!$i) {
-					$totalarray['pos'][$totalarray['nbfield']] = 'rtp';
+				// Pending amount
+				if (!empty($arrayfields['rtp']['checked'])) {
+					print '<td class="right nowraponall amount">';
+					print(!empty($remaintopay) ? price($remaintopay, 0, $langs) : '&nbsp;');
+					print '</td>'; // TODO Use a denormalized field
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
+					if (!$i) {
+						$totalarray['pos'][$totalarray['nbfield']] = 'rtp';
+					}
+					$totalarray['val']['rtp'] += $remaintopay;
 				}
-				$totalarray['val']['rtp'] += $remaintopay;
-			}
 
 
-			// Currency
-			if (!empty($arrayfields['f.multicurrency_code']['checked'])) {
-				print '<td class="nowraponall tdoverflowmax125" title="'.dol_escape_htmltag($obj->multicurrency_code.' - '.$langs->transnoentitiesnoconv('Currency'.$obj->multicurrency_code)).'">';
-				if (!getDolGlobalString('MAIN_SHOW_ONLY_CODE_MULTICURRENCY')) {
-					print $langs->transnoentitiesnoconv('Currency'.$obj->multicurrency_code);
-				} else {
-					print dol_escape_htmltag($obj->multicurrency_code);
-				}
-				print "</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Currency
+				if (!empty($arrayfields['f.multicurrency_code']['checked'])) {
+					print '<td class="nowraponall tdoverflowmax125" title="' . dol_escape_htmltag($obj->multicurrency_code . ' - ' . $langs->transnoentitiesnoconv('Currency' . $obj->multicurrency_code)) . '">';
+					if (!getDolGlobalString('MAIN_SHOW_ONLY_CODE_MULTICURRENCY')) {
+						print $langs->transnoentitiesnoconv('Currency' . $obj->multicurrency_code);
+					} else {
+						print dol_escape_htmltag($obj->multicurrency_code);
+					}
+					print "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Currency rate
-			if (!empty($arrayfields['f.multicurrency_tx']['checked'])) {
-				print '<td class="nowraponall">';
-				$form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code);
-				print "</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Currency rate
+				if (!empty($arrayfields['f.multicurrency_tx']['checked'])) {
+					print '<td class="nowraponall">';
+					$form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code);
+					print "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Amount HT
-			if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) {
-				print '<td class="right nowraponall amount">'.price($obj->multicurrency_total_ht)."</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Amount HT
+				if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) {
+					print '<td class="right nowraponall amount">' . price($obj->multicurrency_total_ht) . "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Amount VAT
-			if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) {
-				print '<td class="right nowraponall amount">'.price($obj->multicurrency_total_vat)."</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Amount VAT
+				if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) {
+					print '<td class="right nowraponall amount">' . price($obj->multicurrency_total_vat) . "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Amount TTC
-			if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) {
-				print '<td class="right nowraponall amount">'.price($obj->multicurrency_total_ttc)."</td>\n";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Amount TTC
+				if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) {
+					print '<td class="right nowraponall amount">' . price($obj->multicurrency_total_ttc) . "</td>\n";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Dyn amount
-			if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) {
-				print '<td class="right nowraponall amount">'.(!empty($multicurrency_totalpay) ? price($multicurrency_totalpay, 0, $langs) : '&nbsp;').'</td>'; // TODO Use a denormalized field
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Dyn amount
+				if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) {
+					print '<td class="right nowraponall amount">' . (!empty($multicurrency_totalpay) ? price($multicurrency_totalpay, 0, $langs) : '&nbsp;') . '</td>'; // TODO Use a denormalized field
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Pending amount
-			if (!empty($arrayfields['multicurrency_rtp']['checked'])) {
-				print '<td class="right nowraponall amount">';
-				print(!empty($multicurrency_remaintopay) ? price($multicurrency_remaintopay, 0, $langs) : '&nbsp;');
-				print '</td>'; // TODO Use a denormalized field ?
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Pending amount
+				if (!empty($arrayfields['multicurrency_rtp']['checked'])) {
+					print '<td class="right nowraponall amount">';
+					print(!empty($multicurrency_remaintopay) ? price($multicurrency_remaintopay, 0, $langs) : '&nbsp;');
+					print '</td>'; // TODO Use a denormalized field ?
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Total buying or cost price
-			if (!empty($arrayfields['total_pa']['checked'])) {
-				print '<td class="right nowrap">'.price($marginInfo['pa_total'], 0, $langs, 1, -1, 'MT').'</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-					$totalarray['pos'][$totalarray['nbfield']] = 'total_pa';
+				// Total buying or cost price
+				if (!empty($arrayfields['total_pa']['checked'])) {
+					print '<td class="right nowrap">' . price($marginInfo['pa_total'], 0, $langs, 1, -1, 'MT') . '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+						$totalarray['pos'][$totalarray['nbfield']] = 'total_pa';
+					}
+					if (empty($totalarray['val']['total_pa'])) {
+						$totalarray['val']['total_pa'] = 0;
+					}
+					$totalarray['val']['total_pa'] += $marginInfo['pa_total'];
 				}
-				if (empty($totalarray['val']['total_pa'])) {
-					$totalarray['val']['total_pa'] = 0;
+				// Total margin
+				if (!empty($arrayfields['total_margin']['checked'])) {
+					print '<td class="right nowrap">' . price($marginInfo['total_margin'], 0, $langs, 1, -1, 'MT') . '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+						$totalarray['pos'][$totalarray['nbfield']] = 'total_margin';
+					}
+					if (empty($totalarray['val']['total_margin'])) {
+						$totalarray['val']['total_margin'] = 0;
+					}
+					$totalarray['val']['total_margin'] += $marginInfo['total_margin'];
 				}
-				$totalarray['val']['total_pa'] += $marginInfo['pa_total'];
-			}
-			// Total margin
-			if (!empty($arrayfields['total_margin']['checked'])) {
-				print '<td class="right nowrap">'.price($marginInfo['total_margin'], 0, $langs, 1, -1, 'MT').'</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-					$totalarray['pos'][$totalarray['nbfield']] = 'total_margin';
+				// Total margin rate
+				if (!empty($arrayfields['total_margin_rate']['checked'])) {
+					print '<td class="right nowrap">' . (($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], 0, '', 0, 0, 2) . '%') . '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-				if (empty($totalarray['val']['total_margin'])) {
-					$totalarray['val']['total_margin'] = 0;
+				// Total mark rate
+				if (!empty($arrayfields['total_mark_rate']['checked'])) {
+					print '<td class="right nowrap">' . (($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], 0, '', 0, 0, 2) . '%') . '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+						$totalarray['pos'][$totalarray['nbfield']] = 'total_mark_rate';
+					}
+					if ($i >= $imaxinloop - 1) {
+						if (!empty($total_ht)) {
+							$totalarray['val']['total_mark_rate'] = price2num($total_margin * 100 / $total_ht, 'MT');
+						} else {
+							$totalarray['val']['total_mark_rate'] = '';
+						}
+					}
 				}
-				$totalarray['val']['total_margin'] += $marginInfo['total_margin'];
-			}
-			// Total margin rate
-			if (!empty($arrayfields['total_margin_rate']['checked'])) {
-				print '<td class="right nowrap">'.(($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], 0, '', 0, 0, 2).'%').'</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+
+				// Extra fields
+				include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_print_fields.tpl.php';
+				// Fields from hook
+				$parameters = array('arrayfields' => $arrayfields, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray);
+				$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+				print $hookmanager->resPrint;
+				// Date creation
+				if (!empty($arrayfields['f.datec']['checked'])) {
+					print '<td class="nowraponall center">';
+					print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
-			// Total mark rate
-			if (!empty($arrayfields['total_mark_rate']['checked'])) {
-				print '<td class="right nowrap">'.(($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], 0, '', 0, 0, 2).'%').'</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-					$totalarray['pos'][$totalarray['nbfield']] = 'total_mark_rate';
+				// Date modification
+				if (!empty($arrayfields['f.tms']['checked'])) {
+					print '<td class="nowraponall center">';
+					print dol_print_date($db->jdate($obj->date_modification), 'dayhour', 'tzuser');
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-				if ($i >= $imaxinloop - 1) {
-					if (!empty($total_ht)) {
-						$totalarray['val']['total_mark_rate'] = price2num($total_margin * 100 / $total_ht, 'MT');
-					} else {
-						$totalarray['val']['total_mark_rate'] = '';
+				// Date closing
+				if (!empty($arrayfields['f.date_closing']['checked'])) {
+					print '<td class="nowraponall center">';
+					print dol_print_date($db->jdate($obj->date_closing), 'dayhour', 'tzuser');
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
 					}
 				}
-			}
-
-			// Extra fields
-			include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
-			// Fields from hook
-			$parameters = array('arrayfields' => $arrayfields, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray);
-			$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-			print $hookmanager->resPrint;
-			// Date creation
-			if (!empty($arrayfields['f.datec']['checked'])) {
-				print '<td class="nowraponall center">';
-				print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-			}
-			// Date modification
-			if (!empty($arrayfields['f.tms']['checked'])) {
-				print '<td class="nowraponall center">';
-				print dol_print_date($db->jdate($obj->date_modification), 'dayhour', 'tzuser');
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-			}
-			// Date closing
-			if (!empty($arrayfields['f.date_closing']['checked'])) {
-				print '<td class="nowraponall center">';
-				print dol_print_date($db->jdate($obj->date_closing), 'dayhour', 'tzuser');
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-			}
-			// Note public
-			if (!empty($arrayfields['f.note_public']['checked'])) {
-				print '<td class="sensiblehtmlcontent center">';
-				print dolPrintHTML($obj->note_public);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-			}
-			// Note private
-			if (!empty($arrayfields['f.note_private']['checked'])) {
-				print '<td class="center">';
-				print dolPrintHTML($obj->note_private);
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
-				}
-			}
-			// Template Invoice
-			if (!empty($arrayfields['f.fk_fac_rec_source']['checked'])) {
-				print '<td class="center">';
-				if (!empty($obj->fk_fac_rec_source)) {
-					$facrec = new FactureRec($db);
-					$result = $facrec->fetch($obj->fk_fac_rec_source);
-					if ($result < 0) {
-						setEventMessages($facrec->error, $facrec->errors, 'errors');
-					} else {
-						print $facrec->getNomUrl();
+				// Note public
+				if (!empty($arrayfields['f.note_public']['checked'])) {
+					print '<td class="sensiblehtmlcontent center">';
+					print dolPrintHTML($obj->note_public);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
 					}
 				}
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Note private
+				if (!empty($arrayfields['f.note_private']['checked'])) {
+					print '<td class="center">';
+					print dolPrintHTML($obj->note_private);
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
+				}
+				// Template Invoice
+				if (!empty($arrayfields['f.fk_fac_rec_source']['checked'])) {
+					print '<td class="center">';
+					if (!empty($obj->fk_fac_rec_source)) {
+						$facrec = new FactureRec($db);
+						$result = $facrec->fetch($obj->fk_fac_rec_source);
+						if ($result < 0) {
+							setEventMessages($facrec->error, $facrec->errors, 'errors');
+						} else {
+							print $facrec->getNomUrl();
+						}
+					}
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Import key
-			if (!empty($arrayfields['f.import_key']['checked'])) {
-				print '<td class="nowrap center">'.dol_escape_htmltag($obj->import_key).'</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Import key
+				if (!empty($arrayfields['f.import_key']['checked'])) {
+					print '<td class="nowrap center">' . dol_escape_htmltag($obj->import_key) . '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Status
-			if (!empty($arrayfields['f.fk_statut']['checked'])) {
-				print '<td class="nowrap center">';
-				print $facturestatic->getLibStatut(5, $totalallpayments);
-				print "</td>";
-				if (!$i) {
-					$totalarray['nbfield']++;
+				// Status
+				if (!empty($arrayfields['f.fk_statut']['checked'])) {
+					print '<td class="nowrap center">';
+					print $facturestatic->getLibStatut(5, $totalallpayments);
+					print "</td>";
+					if (!$i) {
+						$totalarray['nbfield']++;
+					}
 				}
-			}
 
-			// Action column (Show the massaction button only when this page is not opend from the Extended POS)
+				// Action column (Show the massaction button only when this page is not opend from the Extended POS)
 
-			if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
-				print '<td class="nowrap center">';
-				if (($massactionbutton || $massaction) && $contextpage != 'poslist') {   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
-					$selected = 0;
-					if (in_array($obj->id, $arrayofselected)) {
-						$selected = 1;
+				if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
+					print '<td class="nowrap center">';
+					if (($massactionbutton || $massaction) && $contextpage != 'poslist') {   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
+						$selected = 0;
+						if (in_array($obj->id, $arrayofselected)) {
+							$selected = 1;
+						}
+						print '<input id="cb' . $obj->id . '" class="flat checkforselect" type="checkbox" name="toselect[]" value="' . $obj->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
+					}
+					print '</td>';
+					if (!$i) {
+						$totalarray['nbfield']++;
 					}
-					print '<input id="cb'.$obj->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->id.'"'.($selected ? ' checked="checked"' : '').'>';
-				}
-				print '</td>';
-				if (!$i) {
-					$totalarray['nbfield']++;
 				}
+
+				print '</tr>' . "\n";
 			}
 
-			print '</tr>'."\n";
+			$i++;
 		}
 
-		$i++;
-	}
-
-	// Use correct digits number for totals
-	$totalarray['val']['total_pa'] = (isset($totalarray['val']['total_pa']) ? price2num($totalarray['val']['total_pa'], 'MT') : null);
-	$totalarray['val']['total_margin'] = (isset($totalarray['val']['total_margin']) ? price2num($totalarray['val']['total_margin'], 'MT') : null);
+		// Use correct digits number for totals
+		$totalarray['val']['total_pa'] = (isset($totalarray['val']['total_pa']) ? price2num($totalarray['val']['total_pa'], 'MT') : null);
+		$totalarray['val']['total_margin'] = (isset($totalarray['val']['total_margin']) ? price2num($totalarray['val']['total_margin'], 'MT') : null);
 
-	// Show total line
-	include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
-}
-
-// If no record found
-if ($num == 0) {
-	$colspan = 1;
-	foreach ($arrayfields as $key => $val) {
-		if (!empty($val['checked'])) {
-			$colspan++;
-		}
+		// Show total line
+		include DOL_DOCUMENT_ROOT . '/core/tpl/list_print_total.tpl.php';
 	}
-	print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
-}
-
-$db->free($resql);
-
-$parameters = array('arrayfields' => $arrayfields, 'sql' => $sql);
-$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-print $hookmanager->resPrint;
 
-print '</table>'."\n";
-print '</div>'."\n";
-
-print '</form>'."\n";
-
-// Show the file area only when this page is not opend from the Extended POS
-if ($contextpage != 'poslist') {
-	$hidegeneratedfilelistifempty = 1;
-	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
-		$hidegeneratedfilelistifempty = 0;
+	// If no record found
+	if ($num == 0) {
+		$colspan = 1;
+		foreach ($arrayfields as $key => $val) {
+			if (!empty($val['checked'])) {
+				$colspan++;
+			}
+		}
+		print '<tr><td colspan="' . $colspan . '"><span class="opacitymedium">' . $langs->trans("NoRecordFound") . '</span></td></tr>';
 	}
 
-	// Show list of available documents
-	$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
-	$urlsource .= str_replace('&amp;', '&', $param);
-
-	$filedir = $diroutputmassaction;
-	$genallowed = $user->hasRight("facture", "lire");
-	$delallowed = $user->hasRight("facture", "creer");
-	$title = '';
-
-	print $formfile->showdocuments('massfilesarea_invoices', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
-}
+	$db->free($resql);
 
-// End of page
-llxFooter();
-$db->close();
+	$parameters = array('arrayfields' => $arrayfields, 'sql' => $sql);
+	$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook

########## core/class/commoninvoice.class.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/class/commoninvoice.class.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/class/commoninvoice.class.php	2025-02-27 08:48:34.285680000 +0000
@@ -286,12 +286,7 @@
 		$alreadypaid += $this->getSumDepositsUsed($multicurrency);
 		$alreadypaid += $this->getSumCreditNotesUsed($multicurrency);
 
-		if ((int) $multicurrency > 0) {
-			$totalamount = $this->multicurrency_total_ttc;
-		} else {
-			$totalamount = $this->total_ttc;
-		}
-		$remaintopay = price2num($totalamount - $alreadypaid, 'MT');
+		$remaintopay = price2num($this->total_ttc - $alreadypaid, 'MT');
 		if ($this->status == self::STATUS_CLOSED && $this->close_code == 'discount_vat') {		// If invoice closed with discount for anticipated payment
 			$remaintopay = 0.0;
 		}

########## core/class/html.form.class.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/class/html.form.class.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/class/html.form.class.php	2025-02-27 08:48:34.251759000 +0000
@@ -6912,7 +6912,7 @@
 	 *                                              Else, default proposed VAT==0. End of rule.
 	 *  @param	bool		$options_only			Return HTML options lines only (for ajax treatment)
 	 *  @param  int<-1,1>	$mode					0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key
-	 *  @param  int<0,2>	$type_vat				0=All types, 1=VAT rate for sales, 2=VAT rate for purchases
+	 *  @param  int<0,2>	$type_vat				0=All type, 1=VAT rate sale, 2=VAT rate purchase
 	 *  @return	string
 	 */
 	public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = null, $societe_acheteuse = null, $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0, $type_vat = 0)
@@ -7008,14 +7008,12 @@
 		$num = count($arrayofvatrates);
 
 		if ($num > 0) {
-			// Define the rate to pre-select (if defaulttx not forced so is -1 or '')
+			// Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
 			if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
-				// Define a default thirdparty to use if the seller or buyer is not defined
 				$tmpthirdparty = new Societe($this->db);
-				$tmpthirdparty->country_code = $mysoc->country_code;
 
-				$defaulttx = get_default_tva(is_object($societe_vendeuse) ? $societe_vendeuse : $tmpthirdparty, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
-				$defaultnpr = get_default_npr(is_object($societe_vendeuse) ? $societe_vendeuse : $tmpthirdparty, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
+				$defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
+				$defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
 
 				if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
 					$defaultcode = $reg[1];
@@ -9546,7 +9544,7 @@
 	 *
 	 * @param int 		$id 		Id of object
 	 * @param string 	$type 		Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
-	 * @param int<0,1>	$rendermode 0=Default, use multiselect (deprecated). 1=Emulate multiselect (recommended)
+	 * @param int<0,1>	$rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
 	 * @param int<0,1> 	$nolink 	1=Do not add html links
 	 * @return string               String with categories
 	 */

########## core/class/html.formfile.class.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/class/html.formfile.class.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/class/html.formfile.class.php	2025-02-27 08:48:34.346596000 +0000
@@ -969,7 +969,10 @@
 
 					$out .= '<tr class="oddeven'.((!$genallowed && $i == 1) ? ' trfirstline' : '').'">';
 
-					$documenturl = getDolGlobalString('DOL_URL_ROOT_DOCUMENT_PHP', DOL_URL_ROOT.'/document.php'); // DOL_URL_ROOT_DOCUMENT_PHP can be used to set another wrapper
+					$documenturl = DOL_URL_ROOT.'/document.php';
+					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) {
+						$documenturl = getDolGlobalString('DOL_URL_ROOT_DOCUMENT_PHP'); // To use another wrapper
+					}
 
 					// Show file name with link to download
 					$imgpreview = $this->showPreview($file, $modulepart, $relativepath, 0, $param);

########## core/class/html.formsetup.class.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/class/html.formsetup.class.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/class/html.formsetup.class.php	2025-02-27 08:48:34.297178000 +0000
@@ -706,10 +706,10 @@
 	{
 		global $conf;
 		if (isset($conf->global->{$this->confKey})) {
-			$this->fieldValue = getDolGlobalString($this->confKey, null);
+			$this->fieldValue = getDolGlobalString($this->confKey);
 			return true;
 		} else {
-			$this->fieldValue = null;
+			$this->fieldValue = '';
 			return false;
 		}
 	}

########## core/lib/files.lib.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/lib/files.lib.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/lib/files.lib.php	2025-02-27 08:48:34.005874000 +0000
@@ -1983,7 +1983,7 @@
 				// Move file from temp directory to final directory. A .noexe may also be appended on file name.
 				$resupload = dol_move_uploaded_file($TFile['tmp_name'][$i], $destfull, $allowoverwrite, 0, $TFile['error'][$i], 0, $varfiles, $upload_dir);
 
-				if (is_numeric($resupload) && $resupload > 0) {   // $resupload can be 'ErrorFileAlreadyExists', 'ErrorFileIsInfectedWithAVirus...'
+				if (is_numeric($resupload) && $resupload > 0) {   // $resupload can be 'ErrorFileAlreadyExists'
 					include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
 
 					$tmparraysize = getDefaultImageSizes();
@@ -2047,7 +2047,7 @@
 						if (preg_match('/File is a PDF with javascript inside/', $resupload)) {
 							setEventMessages($langs->trans("ErrorFileIsAnInfectedPDFWithJSInside"), null, 'errors');
 						} else {
-							setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus").'<br>'.dolGetFirstLineOfText($resupload), null, 'errors');
+							setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
 						}
 					} else { // Known error
 						setEventMessages($langs->trans($resupload), null, 'errors');

########## core/lib/functions.lib.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/lib/functions.lib.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/lib/functions.lib.php	2025-02-27 08:48:33.970350000 +0000
@@ -12566,7 +12566,7 @@
 	// TODO: add hook
 
 	// escape all attribute
-	$attr = array_map('dolPrintHtmlForAttribute', $attr);
+	$attr = array_map('dol_escape_htmltag', $attr);
 
 	$TCompiledAttr = array();
 	foreach ($attr as $key => $value) {

########## core/lib/pdf.lib.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/lib/pdf.lib.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/lib/pdf.lib.php	2025-02-27 08:48:33.975878000 +0000
@@ -328,8 +328,7 @@
 }
 
 /**
- * Function to try to calculate height of a HTML Content.
- * WARNING: Do not use this function inside a TCPDF transaction.
+ * Function to try to calculate height of a HTML Content
  *
  * @param 	TCPDF     $pdf				PDF initialized object
  * @param 	string    $htmlcontent		HTML Content
@@ -340,9 +339,6 @@
 {
 	// store current object
 	$pdf->startTransaction();
-	// To avoid pagebreak effect or strange behavior of writeHTMLCell when we are out of page, we imagine we are at the begin of page to test the height of the text
-	// Another solution would be to do the test on another PDF instance with samefont, width...
-	$pdf->setY(0);
 	// store starting values
 	$start_y = $pdf->GetY();
 	//var_dump($start_y);
@@ -1216,7 +1212,7 @@
 	$pdf->SetDrawColor(224, 224, 224);
 	// Option for footer text color
 	if (getDolGlobalString('PDF_FOOTER_TEXT_COLOR')) {
-		list($r, $g, $b) = sscanf(getDolGlobalString('PDF_FOOTER_TEXT_COLOR'), '%d, %d, %d');
+		list($r, $g, $b) = sscanf($conf->global->PDF_FOOTER_TEXT_COLOR, '%d, %d, %d');
 		$pdf->SetTextColor($r, $g, $b);
 	}
 
@@ -1235,7 +1231,7 @@
 			$freetextheight = $pdf->getStringHeight($width, $line);
 		} else {
 			$freetextheight = pdfGetHeightForHtmlContent($pdf, dol_htmlentitiesbr($line, 1, 'UTF-8', 0)); // New method (works for HTML content)
-			//print '<br>'.$freetextheight;
+			//print '<br>'.$freetextheight;exit;
 		}
 	}
 
@@ -1457,8 +1453,6 @@
 		}
 		$parameters = array('pdf' => $pdf, 'i' => $i, 'outputlangs' => $outputlangs, 'w' => $w, 'h' => $h, 'posx' => $posx, 'posy' => $posy, 'hideref' => $hideref, 'hidedesc' => $hidedesc, 'issupplierline' => $issupplierline, 'special_code' => $special_code);
 		$action = '';
-		// WARNING: A hook must not close/open the PDF transaction. Doing this generates a lot of trouble.
-		// Test to know if content added by the hooks is already done by the main caller of pdf_writelinedesc
 		$reshook = $hookmanager->executeHooks('pdf_writelinedesc', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
 
 		if (!empty($hookmanager->resPrint)) {

########## core/lib/website.lib.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/lib/website.lib.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/lib/website.lib.php	2025-02-27 08:48:34.038607000 +0000
@@ -286,12 +286,12 @@
 	global $db, $langs, $conf, $user;
 	global $dolibarr_main_url_root, $dolibarr_main_data_root;
 	global $website;
-	global $includehtmlcontentopened;	// $includehtmlcontentopened is the level of includes (start at 0 for main page, 1 for first level include, ...)
+	global $includehtmlcontentopened;
 	'@phan-var-force Website $website';
 
 	$nbrep = 0;
 
-	dol_syslog("dolWebsiteOutput start - contenttype=".$contenttype." containerid=".$containerid.(defined('USEDOLIBARREDITOR') ? ' USEDOLIBARREDITOR=1' : '').(defined('USEDOLIBARRSERVER') ? ' USEDOLIBARRSERVER=1' : '').' includehtmlcontentopened='.$includehtmlcontentopened);
+	dol_syslog("dolWebsiteOutput start - contenttype=".$contenttype." containerid=".$containerid." USEDOLIBARREDITOR=".(defined('USEDOLIBARREDITOR') ? '1' : '')." USEDOLIBARRSERVER=".(defined('USEDOLIBARRSERVER') ? '1' : '').' includehtmlcontentopened='.$includehtmlcontentopened);
 
 	//print $containerid.' '.$content;
 
@@ -558,7 +558,7 @@
 			unset($tmpwebsitepage);
 		}
 		if ($result > 0) {
-			$currenturi = $_SERVER["REQUEST_URI"];	// Example: /public/website/index.php?website=mywebsite.com&pageref=mywebsite-home&cache=3600
+			$currenturi = $_SERVER["REQUEST_URI"];	// Example: /public/website/index.php?website=mywebsite.com&pageref=mywebsite-home&nocache=1708177483
 			$regtmp = array();
 			if (preg_match('/&pageref=([^&]+)/', $currenturi, $regtmp)) {
 				if ($regtmp[0] == $containerref) {
@@ -1573,15 +1573,9 @@
 					dol_mkdir(dirname($filetosave));
 
 					$fp = fopen($filetosave, "w");
-					if ($fp) {
-						fwrite($fp, $tmpgeturl['content']);
-						fclose($fp);
-						dolChmod($filetosave);
-					} else {
-						$error++;
-						setEventMessages('Error failed to open file '.$filetosave.' for writing', null, 'errors');
-						$action = 'create';
-					}
+					fwrite($fp, $tmpgeturl['content']);
+					fclose($fp);
+					dolChmod($filetosave);
 				}
 			}
 		}

########## core/lib/website2.lib.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/lib/website2.lib.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/lib/website2.lib.php	2025-02-27 08:48:33.946616000 +0000
@@ -183,9 +183,6 @@
 		$tplcontent .= "} // Not already loaded\n";
 		$tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
 		$tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
-		if (in_array($objectpage->type_container, array('page', 'blogpost', 'service'))) {
-			$tplcontent .= 'dol_syslog("--- Prepare content of page '.((int) $objectpage->id).' - '.$objectpage->pageurl.'");'."\n";
-		}
 		$tplcontent .= "ob_start();\n";
 		$tplcontent .= "// END PHP ?>\n";
 		if (getDolGlobalString('WEBSITE_FORCE_DOCTYPE_HTML5')) {
@@ -373,9 +370,6 @@
 		$tplcontent .= "} // Not already loaded\n";
 		$tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
 		$tplcontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
-		if (in_array($objectpage->type_container, array('page', 'blogpost', 'service'))) {
-			$tplcontent .= 'dol_syslog("--- Prepare content of page '.((int) $objectpage->id).' - '.$objectpage->pageurl.'");'."\n";
-		}
 		$tplcontent .= "// END PHP ?>\n";
 
 		$tplcontent .= $objectpage->content;

########## core/modules/facture/doc/pdf_crabe.modules.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/modules/facture/doc/pdf_crabe.modules.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/modules/facture/doc/pdf_crabe.modules.php	2025-02-27 08:48:34.781830000 +0000
@@ -831,7 +831,7 @@
 						} else {
 							$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code);
 						}
-						$this->_pagefoot($pdf, $object, $outputlangs, 1, $this->getHeightForQRInvoice($pagenb, $object, $outputlangs));
+						$this->_pagefoot($pdf, $object, $outputlangs, 1, $this->getHeightForQRInvoice($pagenb, $object, $langs));
 						$pagenb++;
 						$pdf->setPage($pagenb);
 						$pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it.
@@ -849,7 +849,7 @@
 						} else {
 							$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code);
 						}
-						$this->_pagefoot($pdf, $object, $outputlangs, 1, $this->getHeightForQRInvoice($pagenb, $object, $outputlangs));
+						$this->_pagefoot($pdf, $object, $outputlangs, 1, $this->getHeightForQRInvoice($pagenb, $object, $langs));
 						// New page
 						$pdf->AddPage();
 						if (!empty($tplidx)) {
@@ -1359,7 +1359,6 @@
 
 					$langs->loadLangs(array('payment', 'paybox', 'stripe'));
 					$servicename = $langs->transnoentities('Online');
-
 					$paiement_url = getOnlinePaymentUrl(0, 'invoice', $object->ref, 0, '', 0);
 					$linktopay = $langs->trans("ToOfferALinkForOnlinePayment", $servicename).' <a href="'.$paiement_url.'">'.$outputlangs->transnoentities("ClickHere").'</a>';
 

########## core/modules/facture/doc/pdf_sponge.modules.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/modules/facture/doc/pdf_sponge.modules.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/modules/facture/doc/pdf_sponge.modules.php	2025-02-27 08:48:34.784401000 +0000
@@ -343,7 +343,7 @@
 				$this->heightforfreetext = getDolGlobalInt('MAIN_PDF_FREETEXT_HEIGHT', 5); // Height reserved to output the free text on last page
 				$this->heightforfooter = $this->marge_basse + (!getDolGlobalString('MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS') ? 12 : 22); // Height reserved to output the footer (value include bottom margin)
 
-				$heightforqrinvoice = 0;
+				$heightforqrinvoice = $heightforqrinvoice_firstpage = 0;
 				if (getDolGlobalString('INVOICE_ADD_SWISS_QR_CODE') == 'bottom') {
 					if ($this->getHeightForQRInvoice(1, $object, $langs) > 0) {
 						// Shrink infotot to a base 30

########## core/modules/member/mod_member_simple.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/modules/member/mod_member_simple.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/modules/member/mod_member_simple.php	2025-02-27 08:48:34.734852000 +0000
@@ -92,7 +92,6 @@
 		$sql = "SELECT MAX(CAST(ref AS SIGNED)) as max";
 		$sql .= " FROM ".MAIN_DB_PREFIX."adherent";
 		$sql .= " WHERE entity = ".$conf->entity;
-
 		$resql = $db->query($sql);
 		if ($resql) {
 			$row = $db->fetch_row($resql);
@@ -126,7 +125,6 @@
 		$sql = "SELECT MAX(CAST(ref AS SIGNED)) as max";
 		$sql .= " FROM ".MAIN_DB_PREFIX."adherent";
 		$sql .= " WHERE entity = ".(int) $conf->entity;
-		$sql .= " AND ref <> '(PROV)'";
 
 		$resql = $db->query($sql);
 		if ($resql) {

########## core/modules/supplier_order/doc/pdf_cornas.modules.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/modules/supplier_order/doc/pdf_cornas.modules.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/modules/supplier_order/doc/pdf_cornas.modules.php	2025-02-27 08:48:34.571270000 +0000
@@ -794,9 +794,9 @@
 
 				// Show square
 				if ($pagenb == $pageposbeforeprintlines) {
-					$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code);
+					$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis);
 				} else {
-					$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code);
+					$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code, $outputlangsbis);
 				}
 				$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
 

########## core/triggers/interface_50_modTicket_TicketEmail.class.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/core/triggers/interface_50_modTicket_TicketEmail.class.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/core/triggers/interface_50_modTicket_TicketEmail.class.php	2025-02-27 08:48:34.055151000 +0000
@@ -1,10 +1,10 @@
 <?php
-/* Copyright (C) 2014-2016  Jean-François Ferry	<hello@librethic.io>
+/*
+ * Copyright (C) 2014-2016  Jean-François Ferry	<hello@librethic.io>
+ * 				 2016       Christophe Battarel <christophe@altairis.fr>
  * Copyright (C) 2023		Benjamin Falière	<benjamin.faliere@altairis.fr>
- * Copyright (C) 2025       Frédéric France     <frederic.france@free.fr>
- * Copyright (C) 2024		MDW	                <mdeweerd@users.noreply.github.com>
- * Copyright (C) 2016       Christophe Battarel <christophe@altairis.fr>
- * Copyright (C) 2023-2025	Benjamin Falière	<benjamin@faliere.com>
+ * Copyright (C) 2024		MDW							<mdeweerd@users.noreply.github.com>
+ * Copyright (C) 2025       Frédéric France         <frederic.france@free.fr>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -472,13 +472,10 @@
 		}
 		$message_customer .= '<p>'.$langs->trans('Message').' : <br><br>'.$message.'</p><br>';
 
-		if (getDolGlobalInt('TICKET_ENABLE_PUBLIC_INTERFACE')) {
-			$url_public_ticket = getDolGlobalString('TICKET_URL_PUBLIC_INTERFACE', dol_buildpath('/public/ticket/', 2)).'view.php?track_id='.((int) $object->track_id);
-			$message_customer .= '<p>'.$langs->trans($see_ticket).' : <a href="'.$url_public_ticket.'">'.$url_public_ticket.'</a></p>';
-			$message_customer .= '<p>'.$langs->trans('TicketEmailPleaseDoNotReplyToThisEmail').'</p>';
-		} else {
-			$message_customer .= '<p>'.$langs->trans('TicketEmailPleaseDoNotReplyToThisEmailNoInterface').'</p>';
-		}
+		$url_public_ticket = getDolGlobalString('TICKET_URL_PUBLIC_INTERFACE', dol_buildpath('/public/ticket/', 2)).'view.php?track_id='.$object->track_id;
+
+		$message_customer .= '<p>'.$langs->trans($see_ticket).' : <a href="'.$url_public_ticket.'">'.$url_public_ticket.'</a></p>';
+		$message_customer .= '<p>'.$langs->trans('TicketEmailPleaseDoNotReplyToThisEmail').'</p>';
 
 		$from = (getDolGlobalString('MAIN_INFO_SOCIETE_NOM') ? getDolGlobalString('MAIN_INFO_SOCIETE_NOM') . ' ' : '').'<' . getDolGlobalString('TICKET_NOTIFICATION_EMAIL_FROM').'>';
 

########## debugbar/class/TraceableDB.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/debugbar/class/TraceableDB.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/debugbar/class/TraceableDB.php	2025-02-27 08:48:40.706741000 +0000
@@ -86,19 +86,6 @@
 		return $this->db->ifsql($test, $resok, $resko);
 	}
 
-	/**
-	 *	format a sql regexp
-	 *
-	 *	@param	string	$subject        field name to test
-	 *	@param	string  $pattern        sql pattern to match
-	 *	@param	int		$sqlstring      0=the string being tested is a hard coded string, 1=the string is a field
-	 *	@return	string          		sql string
-	 */
-	public function regexpsql($subject, $pattern, $sqlstring = 0): string
-	{
-		return $this->db->regexpsql($subject, $pattern, $sqlstring = 0);
-	}
-
 	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
 	 * Return datas as an array

########## ecm/class/ecmfiles.class.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/ecm/class/ecmfiles.class.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/ecm/class/ecmfiles.class.php	2025-02-27 08:48:40.712253000 +0000
@@ -1009,9 +1009,9 @@
 
 		if ($option) {
 			if ($option == 'facture_fournisseur') {
-				$tmppath = preg_replace('/^(\d+\/)?fournisseur\/facture\//', '', $this->filepath);
+				$tmppath = preg_replace('/^fournisseur\/facture\//', '', $this->filepath);
 			} elseif ($option == 'commande_fournisseur') {
-				$tmppath = preg_replace('/^(\d+\/)?fournisseur\/commande\//', '', $this->filepath);
+				$tmppath = preg_replace('/^fournisseur\/commande\//', '', $this->filepath);
 			} else {
 				if ((int) $this->entity > 1) {
 					// Remove the part "entityid/commande/" into "entityid/commande/REFXXX" to get only the ref

########## expensereport/card.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/expensereport/card.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/expensereport/card.php	2025-02-27 08:48:35.513528000 +0000
@@ -473,15 +473,10 @@
 						setEventMessages($mesg, null, 'mesgs');
 					} else {
 						$langs->load("other");
-						if (!empty($mailfile->error) || !empty($mailfile->errors)) {
+						if ($mailfile->error) {
 							$mesg = '';
-							$mesg .= $langs->transnoentities('ErrorFailedToSendMail', dol_escape_htmltag($emailFrom), dol_escape_htmltag($emailTo));
-							if (!empty($mailfile->error)) {
-								$mesg .= '<br>' . $mailfile->error;
-							}
-							if (!empty($mailfile->errors) && is_array($mailfile->errors)) {
-								$mesg .= '<br>' . implode('<br>', $mailfile->errors);
-							}
+							$mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+							$mesg .= '<br>'.$mailfile->error;
 							setEventMessages($mesg, null, 'errors');
 						} else {
 							setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
@@ -2610,12 +2605,12 @@
 
 				// Select VAT
 				print '<td class="right inputvat">';
-				$defaultvat = '';
+				$defaultvat = -1;
 				if (getDolGlobalString('EXPENSEREPORT_NO_DEFAULT_VAT')) {
 					// If option to have no default VAT on expense report is on, we force MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
 					$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS = 'none';
 				}
-				print $form->load_tva('vatrate', (!empty($vatrate) ? $vatrate : $defaultvat), null, null, 0, 0, '', false, 1);
+				print $form->load_tva('vatrate', (!empty($vatrate) ? $vatrate : $defaultvat), $mysoc, '', 0, 0, '', false, 1);
 				print '</td>';
 
 				// Unit price net

########## fourn/facture/list.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/fourn/facture/list.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/fourn/facture/list.php	2025-05-02 15:10:17.929129000 +0000
@@ -783,19 +783,36 @@
 $nbtotalofrecords = '';
 if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
 	/* The fast and low memory method to get and count full list converts the sql into a sql count */
-	$sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
-	$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
-	$sqlforcount = preg_replace('/LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_facturefourn = f.rowid/', '', $sqlforcount);
+	$parameters = array(
+		'sqlforcount' => $sql,
+		'sqlfields' => $sqlfields,
+		'context' => $parameters['context']
+	);
+
+	//MODIF JOSE
+	$reshook = $hookmanager->executeHooks('beforeCountQuery', $parameters, $object, $action);
+
+	if ($reshook > 0 && !empty($hookmanager->resPrint)) {
+		$sqlforcount = $hookmanager->resPrint;
+	} else {
+		$sqlforcount = preg_replace('/^' . preg_quote($sqlfields, '/') . '/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
+		$sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
+	}
 
 	$resql = $db->query($sqlforcount);
 	if ($resql) {
 		$objforcount = $db->fetch_object($resql);
 		$nbtotalofrecords = $objforcount->nbtotalofrecords;
+
+		$_GET['total_ht'] = $objforcount->total_ht ?? 0;
+		$_GET['total_tva'] = $objforcount->total_tva ?? 0;
+		$_GET['total_ttc'] = $objforcount->total_ttc ?? 0;
+
 	} else {
 		dol_print_error($db);
 	}
 
-	if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller than the paging size (filtering), goto and load page 0
+	if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller than paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}

########## main.inc.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/main.inc.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/main.inc.php	2025-06-13 08:13:25.133163000 +0000
@@ -41,6 +41,11 @@
 
 //@ini_set('memory_limit', '128M');	// This may be useless if memory is hard limited by your PHP
 
+ini_set('display_errors', 1);
+ini_set('display_startup_errors', 1);
+error_reporting(E_ALL);
+
+
 // For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined.
 $micro_start_time = 0;
 if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) {
@@ -108,7 +113,7 @@
 		}
 	}
 
-	return '&#'.$matches[1]; // Value will be unchanged because regex was /&#(  )/
+	return '&#' . $matches[1]; // Value will be unchanged because regex was /&#(  )/
 }
 
 /**
@@ -278,25 +283,25 @@
 				$ip = (empty($_SERVER['REMOTE_ADDR']) ? 'unknown' : $_SERVER['REMOTE_ADDR']);
 
 				if ($stopcode) {
-					$errormessage = 'Access refused to '.htmlentities($ip, ENT_COMPAT, 'UTF-8').' by SQL or Script injection protection in main.inc.php:analyseVarsForSqlAndScriptsInjection type='.htmlentities((string) $type, ENT_COMPAT, 'UTF-8');
+					$errormessage = 'Access refused to ' . htmlentities($ip, ENT_COMPAT, 'UTF-8') . ' by SQL or Script injection protection in main.inc.php:analyseVarsForSqlAndScriptsInjection type=' . htmlentities((string) $type, ENT_COMPAT, 'UTF-8');
 					//$errormessage .= ' paramkey='.htmlentities($key, ENT_COMPAT, 'UTF-8');	// Disabled to avoid text injection
 
-					$errormessage2 = 'page='.htmlentities((empty($_SERVER["REQUEST_URI"]) ? '' : $_SERVER["REQUEST_URI"]), ENT_COMPAT, 'UTF-8');
-					$errormessage2 .= ' paramtype='.htmlentities((string) $type, ENT_COMPAT, 'UTF-8');
-					$errormessage2 .= ' paramkey='.htmlentities($key, ENT_COMPAT, 'UTF-8');
-					$errormessage2 .= ' paramvalue='.htmlentities($value, ENT_COMPAT, 'UTF-8');
+					$errormessage2 = 'page=' . htmlentities((empty($_SERVER["REQUEST_URI"]) ? '' : $_SERVER["REQUEST_URI"]), ENT_COMPAT, 'UTF-8');
+					$errormessage2 .= ' paramtype=' . htmlentities((string) $type, ENT_COMPAT, 'UTF-8');
+					$errormessage2 .= ' paramkey=' . htmlentities($key, ENT_COMPAT, 'UTF-8');
+					$errormessage2 .= ' paramvalue=' . htmlentities($value, ENT_COMPAT, 'UTF-8');
 
 					print $errormessage;
 					print "<br>\n";
 					print 'Try to go back, fix data of your form and resubmit it. You can contact also your technical support.';
 
-					print "\n".'<!--'."\n";
+					print "\n" . '<!--' . "\n";
 					print $errormessage2;
-					print "\n".'-->';
+					print "\n" . '-->';
 
 					// Add entry into the PHP server error log
 					if (function_exists('error_log')) {
-						error_log($errormessage.' '.substr($errormessage2, 2000));
+						error_log($errormessage . ' ' . substr($errormessage2, 2000));
 					}
 
 					// Note: No addition into security audit table is done because we don't want to execute code in such a case.
@@ -304,7 +309,7 @@
 
 
 					if (class_exists('PHPUnit\Framework\TestSuite')) {
-						$message = $errormessage.' '.substr($errormessage2, 2000);
+						$message = $errormessage . ' ' . substr($errormessage2, 2000);
 						throw new Exception("Security injection exception: $message");
 					}
 					exit;
@@ -354,7 +359,7 @@
 
 // This is to make Dolibarr working with Plesk
 if (!empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs') {
-	set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs');
+	set_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');
 }
 
 // Include the conf.php and functions.lib.php and security.lib.php. This defined the constants like DOL_DOCUMENT_ROOT, DOL_DATA_ROOT, DOL_URL_ROOT...
@@ -376,7 +381,7 @@
 	$tmplist = explode(',', $tmpautoset[1]);
 	$cookiearrayvalue = array();
 	foreach ($tmplist as $tmpkey) {
-		$postkey = $tmpautoset[0].'_'.$tmpkey;
+		$postkey = $tmpautoset[0] . '_' . $tmpkey;
 		//var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.GETPOST($postkey);
 		if (GETPOST($postkey)) {
 			$cookiearrayvalue[$tmpkey] = GETPOST($postkey);
@@ -407,15 +412,15 @@
 // Set the handler of session
 // if (ini_get('session.save_handler') == 'user')
 if (!empty($php_session_save_handler) && $php_session_save_handler == 'db') {
-	require_once 'core/lib/phpsessionin'.$php_session_save_handler.'.lib.php';
+	require_once 'core/lib/phpsessionin' . $php_session_save_handler . '.lib.php';
 }
 
 // Init session. Name of session is specific to Dolibarr instance.
 // Must be done after the include of filefunc.inc.php so global variables of conf file are defined (like $dolibarr_main_instance_unique_id or $dolibarr_main_force_https).
 // Note: the function dol_getprefix() is defined into functions.lib.php but may have been defined to return a different key to manage another area to protect.
 $prefix = dol_getprefix('');
-$sessionname = 'DOLSESSID_'.$prefix;
-$sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix;
+$sessionname = 'DOLSESSID_' . $prefix;
+$sessiontimeout = 'DOLSESSTIMEOUT_' . $prefix;
 if (!empty($_COOKIE[$sessiontimeout])) {
 	ini_set('session.gc_maxlifetime', $_COOKIE[$sessiontimeout]);
 }
@@ -465,14 +470,14 @@
 	}
 	if (!$ok) {
 		if (session_id() && isset($_SESSION["dol_login"]) && !in_array($_SESSION["dol_login"], explode(';', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')))) {
-			print 'Sorry, your application is offline.'."\n";
-			print 'You are logged with user "'.$_SESSION["dol_login"].'" and only administrator users (' . str_replace(';', ', ', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')).') is allowed to connect for the moment.'."\n";
-			$nexturl = DOL_URL_ROOT.'/user/logout.php?token='.newToken();
-			print 'Please try later or <a href="'.$nexturl.'">click here to disconnect and change login user</a>...'."\n";
+			print 'Sorry, your application is offline.' . "\n";
+			print 'You are logged with user "' . $_SESSION["dol_login"] . '" and only administrator users (' . str_replace(';', ', ', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')) . ') is allowed to connect for the moment.' . "\n";
+			$nexturl = DOL_URL_ROOT . '/user/logout.php?token=' . newToken();
+			print 'Please try later or <a href="' . $nexturl . '">click here to disconnect and change login user</a>...' . "\n";
 		} else {
-			print 'Sorry, your application is offline. Only administrator users (' . str_replace(';', ', ', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')).') is allowed to connect for the moment.'."\n";
-			$nexturl = DOL_URL_ROOT.'/';
-			print 'Please try later or <a href="'.$nexturl.'">click here to change login user</a>...'."\n";
+			print 'Sorry, your application is offline. Only administrator users (' . str_replace(';', ', ', getDolGlobalString('MAIN_ONLY_LOGIN_ALLOWED')) . ') is allowed to connect for the moment.' . "\n";
+			$nexturl = DOL_URL_ROOT . '/';
+			print 'Please try later or <a href="' . $nexturl . '">click here to change login user</a>...' . "\n";
 		}
 		exit;
 	}
@@ -485,7 +490,7 @@
 // Load debugbar
 if (isModEnabled('debugbar') && !GETPOST('dol_use_jmobile') && empty($_SESSION['dol_use_jmobile'])) {
 	global $debugbar;
-	include_once DOL_DOCUMENT_ROOT.'/debugbar/class/DebugBar.php';
+	include_once DOL_DOCUMENT_ROOT . '/debugbar/class/DebugBar.php';
 	$debugbar = new DolibarrDebugBar();
 	$renderer = $debugbar->getJavascriptRenderer();
 	if (!getDolGlobalString('MAIN_HTML_HEADER')) {
@@ -515,7 +520,7 @@
 // If theme is forced
 if (GETPOST('theme', 'aZ09')) {
 	$conf->theme = GETPOST('theme', 'aZ09');
-	$conf->css = "/theme/".$conf->theme."/style.css.php";
+	$conf->css = "/theme/" . $conf->theme . "/style.css.php";
 }
 
 // Set global MAIN_OPTIMIZEFORTEXTBROWSER (must be before login part)
@@ -535,17 +540,17 @@
 		} else {
 			// If HTTPS is not defined in DOL_MAIN_URL_ROOT,
 			// Check HTTPS environment variable (Apache/mod_ssl only)
-			$newurl = preg_replace('/^http:/i', 'https:', DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
+			$newurl = preg_replace('/^http:/i', 'https:', DOL_MAIN_URL_ROOT) . $_SERVER["REQUEST_URI"];
 		}
 	} else {
 		// Check HTTPS environment variable (Apache/mod_ssl only)
-		$newurl = $conf->file->main_force_https.$_SERVER["REQUEST_URI"];
+		$newurl = $conf->file->main_force_https . $_SERVER["REQUEST_URI"];
 	}
 	// Start redirect
 	if ($newurl) {
 		header_remove(); // Clean header already set to be sure to remove any header like "Set-Cookie: DOLSESSID_..." from non HTTPS answers
-		dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
-		header("Location: ".$newurl);
+		dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to " . $newurl);
+		header("Location: " . $newurl);
 		exit;
 	} else {
 		dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
@@ -563,23 +568,23 @@
 		}
 	}
 	if (!$found) {
-		print 'Access refused by IP protection. Your detected IP is '.$_SERVER['REMOTE_ADDR'];
+		print 'Access refused by IP protection. Your detected IP is ' . $_SERVER['REMOTE_ADDR'];
 		exit;
 	}
 }
 
 // Loading of additional presentation includes
 if (!defined('NOREQUIREHTML')) {
-	require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2)
+	require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2)
 }
 if (!defined('NOREQUIREAJAX')) {
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; // Need 22ko memory
+	require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; // Need 22ko memory
 }
 
 // If install or upgrade process not done or not completely finished, we call the install page.
 if (getDolGlobalString('MAIN_NOT_INSTALLED') || getDolGlobalString('MAIN_NOT_UPGRADED')) {
 	dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
-	header("Location: ".DOL_URL_ROOT."/install/index.php");
+	header("Location: " . DOL_URL_ROOT . "/install/index.php");
 	exit;
 }
 // If an upgrade process is required, we call the install page.
@@ -592,18 +597,18 @@
 }
 if ($checkifupgraderequired) {
 	$versiontocompare = getDolGlobalString('MAIN_VERSION_LAST_UPGRADE', getDolGlobalString('MAIN_VERSION_LAST_INSTALL'));
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
+	require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
 	$dolibarrversionlastupgrade = preg_split('/[.-]/', $versiontocompare);
 	$dolibarrversionprogram = preg_split('/[.-]/', DOL_VERSION);
 	$rescomp = versioncompare($dolibarrversionprogram, $dolibarrversionlastupgrade);
 	if ($rescomp > 0) {   // Programs have a version higher than database.
 		if (!getDolGlobalString('MAIN_NO_UPGRADE_REDIRECT_ON_LEVEL_3_CHANGE') || $rescomp < 3) {
 			// We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
-			dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install/upgrade page.", LOG_WARNING);
+			dol_syslog("main.inc: database version " . $versiontocompare . " is lower than programs version " . DOL_VERSION . ". Redirect to install/upgrade page.", LOG_WARNING);
 			if (php_sapi_name() === "cli") {
-				print "main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Try to run upgrade process.\n";
+				print "main.inc: database version " . $versiontocompare . " is lower than programs version " . DOL_VERSION . ". Try to run upgrade process.\n";
 			} else {
-				header("Location: ".DOL_URL_ROOT."/install/index.php");
+				header("Location: " . DOL_URL_ROOT . "/install/index.php");
 			}
 			exit;
 		}
@@ -625,7 +630,7 @@
 			// Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
 			$token = dol_hash(uniqid((string) mt_rand(), false), 'md5'); // Generates a hash of a random number. We don't need a secured hash, just a changing random value.
 			$_SESSION['newtoken'] = $token;
-			dol_syslog("NEW TOKEN generated by : ".$_SERVER['PHP_SELF'], LOG_DEBUG);
+			dol_syslog("NEW TOKEN generated by : " . $_SERVER['PHP_SELF'], LOG_DEBUG);
 		}
 	}
 }
@@ -647,8 +652,12 @@
 		// Few GET actions coded with a &token into url are also processed as sensitive.
 		$arrayofactiontoforcetokencheck = array(
 			'activate',
-			'doprev', 'donext', 'dvprev', 'dvnext',
-			'freezone', 'install',
+			'doprev',
+			'donext',
+			'dvprev',
+			'dvnext',
+			'freezone',
+			'install',
 			'reopen'
 		);
 		if (in_array($tmpaction, $arrayofactiontoforcetokencheck)) {
@@ -672,17 +681,17 @@
 		if (!GETPOST('token', 'alpha') || GETPOST('token', 'alpha') == 'notrequired') {
 			top_httphead();
 			if (GETPOSTINT('uploadform')) {
-				dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." refused. File size too large or not provided.");
+				dol_syslog("--- Access to " . (empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"] . ' ') . $_SERVER["PHP_SELF"] . " refused. File size too large or not provided.");
 				$langs->loadLangs(array("errors", "install"));
-				print $langs->trans("ErrorFileSizeTooLarge").' ';
+				print $langs->trans("ErrorFileSizeTooLarge") . ' ';
 				print $langs->trans("ErrorGoBackAndCorrectParameters");
 			} else {
 				http_response_code(403);
 				if (defined('CSRFCHECK_WITH_TOKEN')) {
-					dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." refused by CSRF protection (CSRFCHECK_WITH_TOKEN protection) in main.inc.php. Token not provided.", LOG_WARNING);
+					dol_syslog("--- Access to " . (empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"] . ' ') . $_SERVER["PHP_SELF"] . " refused by CSRF protection (CSRFCHECK_WITH_TOKEN protection) in main.inc.php. Token not provided.", LOG_WARNING);
 					print "Access to a page that needs a token (constant CSRFCHECK_WITH_TOKEN is defined) is refused by CSRF protection in main.inc.php. Token not provided.\n";
 				} else {
-					dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." refused by CSRF protection (POST method or GET with a sensible value for 'action' parameter) in main.inc.php. Token not provided.", LOG_WARNING);
+					dol_syslog("--- Access to " . (empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"] . ' ') . $_SERVER["PHP_SELF"] . " refused by CSRF protection (POST method or GET with a sensible value for 'action' parameter) in main.inc.php. Token not provided.", LOG_WARNING);
 					print "Access to this page this way (POST method or GET with a sensible value for 'action' parameter) is refused by CSRF protection in main.inc.php. Token not provided.\n";
 					print "If you access your server behind a proxy using url rewriting and the parameter is provided by caller, you might check that all HTTP header are propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file or MAIN_SECURITY_CSRF_WITH_TOKEN to 0";
 					if (getDolGlobalString('MAIN_SECURITY_CSRF_WITH_TOKEN')) {
@@ -698,7 +707,7 @@
 	$sessiontokenforthisurl = (empty($_SESSION['token']) ? '' : $_SESSION['token']);
 	// TODO Get the sessiontokenforthisurl into an array of session token (one array per base URL so we can use the CSRF per page and we keep ability for several tabs per url in a browser)
 	if (GETPOSTISSET('token') && GETPOST('token') != 'notrequired' && GETPOST('token', 'alpha') != $sessiontokenforthisurl) {
-		dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." refused by CSRF protection (invalid token), so we disable POST and some GET parameters - referrer=".(empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']).", action=".GETPOST('action', 'aZ09').", _GET|POST['token']=".GETPOST('token', 'alpha'), LOG_WARNING);
+		dol_syslog("--- Access to " . (empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"] . ' ') . $_SERVER["PHP_SELF"] . " refused by CSRF protection (invalid token), so we disable POST and some GET parameters - referrer=" . (empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']) . ", action=" . GETPOST('action', 'aZ09') . ", _GET|POST['token']=" . GETPOST('token', 'alpha'), LOG_WARNING);
 		//dol_syslog("_SESSION['token']=".$sessiontokenforthisurl, LOG_DEBUG);
 		// Do not output anything on standard output because this create problems when using the BACK button on browsers. So we just set a message into session.
 		if (!defined('NOTOKENRENEWAL')) {
@@ -811,7 +820,7 @@
 
 	if (!isset($_SESSION["dol_login"])) {
 		// It is not already authenticated and it requests the login / password
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
+		include_once DOL_DOCUMENT_ROOT . '/core/lib/security2.lib.php';
 
 		$dol_dst_observed = GETPOSTINT("dst_observed", 3);
 		$dol_dst_first = GETPOSTINT("dst_first", 3);
@@ -825,17 +834,17 @@
 		$dol_use_jmobile = GETPOSTINT('dol_use_jmobile', 3); // 0=default, 1=to say we use app from a webview app, 2=to say we use app from a webview app and keep ajax
 
 		// If in demo mode, we check we go to home page through the public/demo/index.php page
-		if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php') {  // We ask index page
+		if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT . '/index.php') {  // We ask index page
 			if (empty($_SERVER['HTTP_REFERER']) || !preg_match('/public/', $_SERVER['HTTP_REFERER'])) {
-				dol_syslog("Call index page from another url than demo page (call is done from page ".(empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']).")");
+				dol_syslog("Call index page from another url than demo page (call is done from page " . (empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']) . ")");
 				$url = '';
-				$url .= ($url ? '&' : '').($dol_hide_topmenu ? 'dol_hide_topmenu='.$dol_hide_topmenu : '');
-				$url .= ($url ? '&' : '').($dol_hide_leftmenu ? 'dol_hide_leftmenu='.$dol_hide_leftmenu : '');
-				$url .= ($url ? '&' : '').($dol_optimize_smallscreen ? 'dol_optimize_smallscreen='.$dol_optimize_smallscreen : '');
-				$url .= ($url ? '&' : '').($dol_no_mouse_hover ? 'dol_no_mouse_hover='.$dol_no_mouse_hover : '');
-				$url .= ($url ? '&' : '').($dol_use_jmobile ? 'dol_use_jmobile='.$dol_use_jmobile : '');
-				$url = DOL_URL_ROOT.'/public/demo/index.php'.($url ? '?'.$url : '');
-				header("Location: ".$url);
+				$url .= ($url ? '&' : '') . ($dol_hide_topmenu ? 'dol_hide_topmenu=' . $dol_hide_topmenu : '');
+				$url .= ($url ? '&' : '') . ($dol_hide_leftmenu ? 'dol_hide_leftmenu=' . $dol_hide_leftmenu : '');
+				$url .= ($url ? '&' : '') . ($dol_optimize_smallscreen ? 'dol_optimize_smallscreen=' . $dol_optimize_smallscreen : '');
+				$url .= ($url ? '&' : '') . ($dol_no_mouse_hover ? 'dol_no_mouse_hover=' . $dol_no_mouse_hover : '');
+				$url .= ($url ? '&' : '') . ($dol_use_jmobile ? 'dol_use_jmobile=' . $dol_use_jmobile : '');
+				$url = DOL_URL_ROOT . '/public/demo/index.php' . ($url ? '?' . $url : '');
+				header("Location: " . $url);
 				exit;
 			}
 		}
@@ -855,14 +864,14 @@
 			$ok = false;
 
 			// Use the captcha handler to validate
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
+			require_once DOL_DOCUMENT_ROOT . '/core/lib/security2.lib.php';
 			$captcha = getDolGlobalString('MAIN_SECURITY_ENABLECAPTCHA_HANDLER', 'standard');
 
 			// List of directories where we can find captcha handlers
 			$dirModCaptcha = array_merge(array('main' => '/core/modules/security/captcha/'), isset($conf->modules_parts['captcha']) && is_array($conf->modules_parts['captcha']) ? $conf->modules_parts['captcha'] : array());
 			$fullpathclassfile = '';
 			foreach ($dirModCaptcha as $dir) {
-				$fullpathclassfile = dol_buildpath($dir."modCaptcha".ucfirst($captcha).'.class.php', 0, 2);
+				$fullpathclassfile = dol_buildpath($dir . "modCaptcha" . ucfirst($captcha) . '.class.php', 0, 2);
 				if ($fullpathclassfile) {
 					break;
 				}
@@ -874,7 +883,7 @@
 				$captchaobj = null;
 
 				// Charging the numbering class
-				$classname = "modCaptcha".ucfirst($captcha);
+				$classname = "modCaptcha" . ucfirst($captcha);
 				if (class_exists($classname)) {
 					/** @var ModeleCaptcha $captchaobj */
 					$captchaobj = new $classname($db, $conf, $langs, $user);
@@ -883,17 +892,17 @@
 					if (is_object($captchaobj) && method_exists($captchaobj, 'validateCodeAfterLoginSubmit')) {
 						$ok = $captchaobj->validateCodeAfterLoginSubmit(); // @phan-suppress-current-line PhanUndeclaredMethod
 					} else {
-						$_SESSION["dol_loginmesg"] =  'Error, the captcha handler '.get_class($captchaobj).' does not have any method validateCodeAfterLoginSubmit()';
+						$_SESSION["dol_loginmesg"] =  'Error, the captcha handler ' . get_class($captchaobj) . ' does not have any method validateCodeAfterLoginSubmit()';
 						$test = false;
 						$error++;
 					}
 				} else {
-					$_SESSION["dol_loginmesg"] =  'Error, the captcha handler class '.$classname.' was not found after the include';
+					$_SESSION["dol_loginmesg"] =  'Error, the captcha handler class ' . $classname . ' was not found after the include';
 					$test = false;
 					$error++;
 				}
 			} else {
-				$_SESSION["dol_loginmesg"] = 'Error, the captcha handler '.$captcha.' has no class file found modCaptcha'.ucfirst($captcha);
+				$_SESSION["dol_loginmesg"] = 'Error, the captcha handler ' . $captcha . ' has no class file found modCaptcha' . ucfirst($captcha);
 				$test = false;
 				$error++;
 			}
@@ -904,11 +913,11 @@
 				// Load translation files required by page
 				$langs->loadLangs(array('main', 'errors'));
 
-				$_SESSION["dol_loginmesg"] = (empty($_SESSION["dol_loginmesg"]) ? "" : $_SESSION["dol_loginmesg"]."<br>\n").$langs->transnoentitiesnoconv("ErrorBadValueForCode");
+				$_SESSION["dol_loginmesg"] = (empty($_SESSION["dol_loginmesg"]) ? "" : $_SESSION["dol_loginmesg"] . "<br>\n") . $langs->transnoentitiesnoconv("ErrorBadValueForCode");
 				$test = false;
 
 				// Call trigger for the "security events" log
-				$user->context['audit'] = 'ErrorBadValueForCode - login='.GETPOST("username", "alpha", 2);
+				$user->context['audit'] = 'ErrorBadValueForCode - login=' . GETPOST("username", "alpha", 2);
 
 				// Call trigger
 				$result = $user->call_trigger('USER_LOGIN_FAILED', $user);
@@ -961,7 +970,7 @@
 		}
 
 		if (!is_object($langs)) { // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
-			include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
+			include_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
 			$langs = new Translate("", $conf);
 			$langcode = (GETPOST('lang', 'aZ09', 1) ? GETPOST('lang', 'aZ09', 1) : getDolGlobalString('MAIN_LANG_DEFAULT', 'auto'));
 			if (defined('MAIN_LANG_DEFAULT')) {
@@ -978,15 +987,15 @@
 			// $authmode is an array for example: array('0'=>'dolibarr', '1'=>'googleoauth');
 			$oauthmodetotestarray = array('google');
 			foreach ($oauthmodetotestarray as $oauthmodetotest) {
-				if (in_array($oauthmodetotest.'oauth', $authmode)) {	// This is an authmode that is currently qualified. Do we have to remove it ?
+				if (in_array($oauthmodetotest . 'oauth', $authmode)) {	// This is an authmode that is currently qualified. Do we have to remove it ?
 					// If we click on the link to use OAuth authentication or if we goes after callback return, we do nothing
 					// TODO Use: if (GETPOST('beforeoauthloginredirect') == $oauthmodetotest || GETPOST('afteroauthloginreturn') == $oauthmodetotest) {
 					if (GETPOST('beforeoauthloginredirect') == $oauthmodetotest || GETPOST('afteroauthloginreturn')) {
 						continue;
 					}
-					dol_syslog("User did not click on link for OAuth, or is not on the OAuth return, so we disable check using ".$oauthmodetotest);
+					dol_syslog("User did not click on link for OAuth, or is not on the OAuth return, so we disable check using " . $oauthmodetotest);
 					foreach ($authmode as $tmpkey => $tmpval) {
-						if ($tmpval == $oauthmodetotest.'oauth') {
+						if ($tmpval == $oauthmodetotest . 'oauth') {
 							unset($authmode[$tmpkey]);
 							break;
 						}
@@ -1012,7 +1021,7 @@
 				$dol_dst_first = empty($_POST["dst_first"]) ? (empty($_SESSION["dst_first"]) ? '' : $_SESSION["dst_first"]) : $_POST["dst_first"];
 				$dol_dst_second = empty($_POST["dst_second"]) ? (empty($_SESSION["dst_second"]) ? '' : $_SESSION["dst_second"]) : $_POST["dst_second"];
 				if ($dol_dst_first && $dol_dst_second) {
-					include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+					include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
 					$datenow = dol_now();
 					$datefirst = dol_stringtotime($dol_dst_first);
 					$datesecond = dol_stringtotime($dol_dst_second);
@@ -1037,7 +1046,7 @@
 				}
 
 				// Call trigger for the "security events" log
-				$user->context['audit'] = $langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username", "alpha", 2);
+				$user->context['audit'] = $langs->trans("ErrorBadLoginPassword") . ' - login=' . GETPOST("username", "alpha", 2);
 
 				// Call trigger
 				$result = $user->call_trigger('USER_LOGIN_FAILED', $user);
@@ -1062,7 +1071,7 @@
 		// End test login / passwords
 		if (!$login || (in_array('ldap', $authmode) && empty($passwordtotest))) {	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connection is a success.
 			// No data to test login, so we show the login page.
-			dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"]." - action=".GETPOST('action', 'aZ09')." - actionlogin=".GETPOST('actionlogin', 'aZ09')." - showing the login form and exit", LOG_NOTICE);
+			dol_syslog("--- Access to " . (empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"] . ' ') . $_SERVER["PHP_SELF"] . " - action=" . GETPOST('action', 'aZ09') . " - actionlogin=" . GETPOST('actionlogin', 'aZ09') . " - showing the login form and exit", LOG_NOTICE);
 			if (defined('NOREDIRECTBYMAINTOLOGIN')) {
 				// When used with NOREDIRECTBYMAINTOLOGIN set, the http header must already be set when including the main.
 				// See example with selectsearchbox.php. This case is reserved for the selectesearchbox.php so we can
@@ -1094,7 +1103,7 @@
 
 				$_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorCantLoadUserFromDolibarrDatabase", $login);
 
-				$user->context['audit'] = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
+				$user->context['audit'] = 'ErrorCantLoadUserFromDolibarrDatabase - login=' . $login;
 			} elseif ($resultFetchUser < 0) {
 				$_SESSION["dol_loginmesg"] = $user->error;
 
@@ -1105,7 +1114,7 @@
 
 				$_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorLoginDateValidity");
 
-				$user->context['audit'] = $langs->trans("ErrorLoginDateValidity").' - login='.$login;
+				$user->context['audit'] = $langs->trans("ErrorLoginDateValidity") . ' - login=' . $login;
 			}
 
 			// Call trigger
@@ -1127,15 +1136,15 @@
 
 			$paramsurl = array();
 			if (GETPOSTINT('textbrowser')) {
-				$paramsurl[] = 'textbrowser='.GETPOSTINT('textbrowser');
+				$paramsurl[] = 'textbrowser=' . GETPOSTINT('textbrowser');
 			}
 			if (GETPOSTINT('nojs')) {
-				$paramsurl[] = 'nojs='.GETPOSTINT('nojs');
+				$paramsurl[] = 'nojs=' . GETPOSTINT('nojs');
 			}
 			if (GETPOST('lang', 'aZ09')) {
-				$paramsurl[] = 'lang='.GETPOST('lang', 'aZ09');
+				$paramsurl[] = 'lang=' . GETPOST('lang', 'aZ09');
 			}
-			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
+			header('Location: ' . DOL_URL_ROOT . '/index.php' . (count($paramsurl) ? '?' . implode('&', $paramsurl) : ''));
 			exit;
 		} else {
 			// User is loaded, we may need to change language for him according to its choice
@@ -1147,28 +1156,30 @@
 		// We are already into an authenticated session
 		$login = $_SESSION["dol_login"];
 		$entity = isset($_SESSION["dol_entity"]) ? $_SESSION["dol_entity"] : 0;
-		dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
+		dol_syslog("- This is an already logged session. _SESSION['dol_login']=" . $login . " _SESSION['dol_entity']=" . $entity, LOG_DEBUG);
 
 		$resultFetchUser = $user->fetch(0, $login, '', 1, ($entity > 0 ? $entity : -1));
 
 		//var_dump(dol_print_date($user->flagdelsessionsbefore, 'dayhour', 'gmt')." ".dol_print_date($_SESSION["dol_logindate"], 'dayhour', 'gmt'));
 
-		if ($resultFetchUser <= 0
+		if (
+			$resultFetchUser <= 0
 			|| ($user->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $user->flagdelsessionsbefore > $_SESSION["dol_logindate"])
 			|| ($user->status != $user::STATUS_ENABLED)
-			|| ($user->isNotIntoValidityDateRange())) {
+			|| ($user->isNotIntoValidityDateRange())
+		) {
 			if ($resultFetchUser <= 0) {
 				// Account has been removed after login
-				dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
+				dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=" . $login, LOG_WARNING);
 			} elseif ($user->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $user->flagdelsessionsbefore > $_SESSION["dol_logindate"]) {
 				// Session is no more valid
-				dol_syslog("The user has a date for session invalidation = ".$user->flagdelsessionsbefore." and a session date = ".$_SESSION["dol_logindate"].". We must invalidate its sessions.");
+				dol_syslog("The user has a date for session invalidation = " . $user->flagdelsessionsbefore . " and a session date = " . $_SESSION["dol_logindate"] . ". We must invalidate its sessions.");
 			} elseif ($user->status != $user::STATUS_ENABLED) {
 				// User is not enabled
 				dol_syslog("The user login is disabled");
 			} else {
 				// User validity dates are no more valid
-				dol_syslog("The user login has a validity between [".$user->datestartvalidity." and ".$user->dateendvalidity."], current date is ".dol_now());
+				dol_syslog("The user login has a validity between [" . $user->datestartvalidity . " and " . $user->dateendvalidity . "], current date is " . dol_now());
 			}
 			session_destroy();
 			session_set_cookie_params(0, '/', null, !empty($dolibarr_main_force_https), true); // Add tag secure and httponly on session cookie
@@ -1180,7 +1191,7 @@
 
 				$_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorCantLoadUserFromDolibarrDatabase", $login);
 
-				$user->context['audit'] = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
+				$user->context['audit'] = 'ErrorCantLoadUserFromDolibarrDatabase - login=' . $login;
 			} elseif ($resultFetchUser < 0) {
 				$_SESSION["dol_loginmesg"] = $user->error;
 
@@ -1190,7 +1201,7 @@
 
 				$_SESSION["dol_loginmesg"] = $langs->transnoentitiesnoconv("ErrorSessionInvalidatedAfterPasswordChange");
 
-				$user->context['audit'] = 'ErrorUserSessionWasInvalidated - login='.$login;
+				$user->context['audit'] = 'ErrorUserSessionWasInvalidated - login=' . $login;
 			}
 
 			// Call trigger
@@ -1211,16 +1222,16 @@
 
 			$paramsurl = array();
 			if (GETPOSTINT('textbrowser')) {
-				$paramsurl[] = 'textbrowser='.GETPOSTINT('textbrowser');
+				$paramsurl[] = 'textbrowser=' . GETPOSTINT('textbrowser');
 			}
 			if (GETPOSTINT('nojs')) {
-				$paramsurl[] = 'nojs='.GETPOSTINT('nojs');
+				$paramsurl[] = 'nojs=' . GETPOSTINT('nojs');
 			}
 			if (GETPOST('lang', 'aZ09')) {
-				$paramsurl[] = 'lang='.GETPOST('lang', 'aZ09');
+				$paramsurl[] = 'lang=' . GETPOST('lang', 'aZ09');
 			}
 
-			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
+			header('Location: ' . DOL_URL_ROOT . '/index.php' . (count($paramsurl) ? '?' . implode('&', $paramsurl) : ''));
 			exit;
 		} else {
 			// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
@@ -1232,32 +1243,32 @@
 				$relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server
 				// Clean $relativepathstring
 				if (constant('DOL_URL_ROOT')) {
-					$relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
+					$relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
 				}
 				$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
 				$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
 				//var_dump($relativepathstring);
 
 				// We click on a link that leave a page we have to save search criteria, contextpage, limit and page and mode. We save them from tmp to no tmp
-				if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring])) {
-					$_SESSION['lastsearch_values_'.$relativepathstring] = $_SESSION['lastsearch_values_tmp_'.$relativepathstring];
-					unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
-				}
-				if (!empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring])) {
-					$_SESSION['lastsearch_contextpage_'.$relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
-					unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
-				}
-				if (!empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit) {
-					$_SESSION['lastsearch_limit_'.$relativepathstring] = $_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
-					unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
-				}
-				if (!empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 0) {
-					$_SESSION['lastsearch_page_'.$relativepathstring] = $_SESSION['lastsearch_page_tmp_'.$relativepathstring];
-					unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
-				}
-				if (!empty($_SESSION['lastsearch_mode_tmp_'.$relativepathstring])) {
-					$_SESSION['lastsearch_mode_'.$relativepathstring] = $_SESSION['lastsearch_mode_tmp_'.$relativepathstring];
-					unset($_SESSION['lastsearch_mode_tmp_'.$relativepathstring]);
+				if (!empty($_SESSION['lastsearch_values_tmp_' . $relativepathstring])) {
+					$_SESSION['lastsearch_values_' . $relativepathstring] = $_SESSION['lastsearch_values_tmp_' . $relativepathstring];
+					unset($_SESSION['lastsearch_values_tmp_' . $relativepathstring]);
+				}
+				if (!empty($_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring])) {
+					$_SESSION['lastsearch_contextpage_' . $relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring];
+					unset($_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring]);
+				}
+				if (!empty($_SESSION['lastsearch_limit_tmp_' . $relativepathstring]) && $_SESSION['lastsearch_limit_tmp_' . $relativepathstring] != $conf->liste_limit) {
+					$_SESSION['lastsearch_limit_' . $relativepathstring] = $_SESSION['lastsearch_limit_tmp_' . $relativepathstring];
+					unset($_SESSION['lastsearch_limit_tmp_' . $relativepathstring]);
+				}
+				if (!empty($_SESSION['lastsearch_page_tmp_' . $relativepathstring]) && $_SESSION['lastsearch_page_tmp_' . $relativepathstring] > 0) {
+					$_SESSION['lastsearch_page_' . $relativepathstring] = $_SESSION['lastsearch_page_tmp_' . $relativepathstring];
+					unset($_SESSION['lastsearch_page_tmp_' . $relativepathstring]);
+				}
+				if (!empty($_SESSION['lastsearch_mode_tmp_' . $relativepathstring])) {
+					$_SESSION['lastsearch_mode_' . $relativepathstring] = $_SESSION['lastsearch_mode_tmp_' . $relativepathstring];
+					unset($_SESSION['lastsearch_mode_tmp_' . $relativepathstring]);
 				}
 			}
 			if (!empty($_GET['save_pageforbacktolist']) && !empty($_SERVER["HTTP_REFERER"])) {    // We must use $_GET here
@@ -1319,14 +1330,14 @@
 			$_SESSION['dol_use_jmobile'] = $dol_use_jmobile;
 		}
 
-		dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
+		dol_syslog("This is a new started user session. _SESSION['dol_login']=" . $_SESSION["dol_login"] . " Session id=" . session_id());
 
 		$db->begin();
 
 		$user->update_last_login_date();
 
-		$loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
-		$loginfo .= ' - authmode='.$dol_authmode.' - entity='.$conf->entity;
+		$loginfo = 'TZ=' . $_SESSION["dol_tz"] . ';TZString=' . $_SESSION["dol_tz_string"] . ';Screen=' . $_SESSION["dol_screenwidth"] . 'x' . $_SESSION["dol_screenheight"];
+		$loginfo .= ' - authmode=' . $dol_authmode . ' - entity=' . $conf->entity;
 
 		// Call triggers for the "security events" log
 		$user->context['audit'] = $loginfo;
@@ -1362,7 +1373,7 @@
 		if (!empty($landingpage)) {    // Example: /index.php
 			$newpath = dol_buildpath($landingpage, 1);
 			if ($_SERVER["PHP_SELF"] != $newpath) {   // not already on landing page (avoid infinite loop)
-				header('Location: '.$newpath);
+				header('Location: ' . $newpath);
 				exit;
 			}
 		}
@@ -1428,7 +1439,7 @@
 	// Replace conf->css by personalized value if theme not forced
 	if (!getDolGlobalString('MAIN_FORCETHEME') && getDolUserString('MAIN_THEME')) {
 		$conf->theme = getDolUserString('MAIN_THEME');
-		$conf->css = "/theme/".$conf->theme."/style.css.php";
+		$conf->css = "/theme/" . $conf->theme . "/style.css.php";
 	}
 } else {
 	// We may have NOLOGIN set, but NOREQUIREUSER not
@@ -1441,7 +1452,7 @@
 // Case forcing style from url
 if (GETPOST('theme', 'aZ09')) {
 	$conf->theme = GETPOST('theme', 'aZ09', 1);
-	$conf->css = "/theme/".$conf->theme."/style.css.php";
+	$conf->css = "/theme/" . $conf->theme . "/style.css.php";
 }
 
 // Set javascript option
@@ -1489,9 +1500,9 @@
 
 // If on smartphone or optimized for small screen
 if ((!empty($conf->browser->layout) && $conf->browser->layout == 'phone')
-			|| (!empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
-			|| (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400
-				|| getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER'))
+	|| (!empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
+	|| (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400
+		|| getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER'))
 ) {
 	$conf->dol_optimize_smallscreen = 1;
 
@@ -1502,7 +1513,7 @@
 // Replace themes bugged with jmobile with eldy
 if (!empty($conf->dol_use_jmobile) && in_array($conf->theme, array('bureau2crea', 'cameleo', 'amarok'))) {
 	$conf->theme = 'eldy';
-	$conf->css = "/theme/".$conf->theme."/style.css.php";
+	$conf->css = "/theme/" . $conf->theme . "/style.css.php";
 }
 
 if (!defined('NOREQUIRETRAN')) {
@@ -1537,7 +1548,7 @@
 	$user->loadRights();
 }
 
-dol_syslog("--- Access to ".(empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"].' ').$_SERVER["PHP_SELF"].' - action='.GETPOST('action', 'aZ09').', massaction='.GETPOST('massaction', 'aZ09').(defined('NOTOKENRENEWAL') ? ' NOTOKENRENEWAL='.constant('NOTOKENRENEWAL') : ''), LOG_NOTICE);
+dol_syslog("--- Access to " . (empty($_SERVER["REQUEST_METHOD"]) ? '' : $_SERVER["REQUEST_METHOD"] . ' ') . $_SERVER["PHP_SELF"] . ' - action=' . GETPOST('action', 'aZ09') . ', massaction=' . GETPOST('massaction', 'aZ09') . (defined('NOTOKENRENEWAL') ? ' NOTOKENRENEWAL=' . constant('NOTOKENRENEWAL') : ''), LOG_NOTICE);
 //Another call for easy debug
 //dol_syslog("Access to ".$_SERVER["PHP_SELF"].' '.$_SERVER["HTTP_REFERER"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST));
 
@@ -1606,15 +1617,15 @@
 		$menufound = 0;
 		$dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']);
 		foreach ($dirmenus as $dirmenu) {
-			$menufound = dol_include_once($dirmenu."standard/".$file_menu);
+			$menufound = dol_include_once($dirmenu . "standard/" . $file_menu);
 			if (class_exists('MenuManager')) {
 				break;
 			}
 		}
 		if (!class_exists('MenuManager')) {	// If failed to include, we try with standard eldy_menu.php
-			dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
+			dol_syslog("You define a menu manager '" . $file_menu . "' that can not be loaded.", LOG_WARNING);
 			$file_menu = 'eldy_menu.php';
-			include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
+			include_once DOL_DOCUMENT_ROOT . "/core/menus/standard/" . $file_menu;
 		}
 	}
 	// @phan-suppress-next-line PhanRedefinedClassReference
@@ -1661,19 +1672,19 @@
 		global $conf, $hookmanager;
 
 		$parameters = array(
-			'head' => & $head,
-			'title' => & $title,
-			'help_url' => & $help_url,
-			'target' => & $target,
-			'disablejs' => & $disablejs,
-			'disablehead' => & $disablehead,
-			'arrayofjs' => & $arrayofjs,
-			'arrayofcss' => & $arrayofcss,
-			'morequerystring' => & $morequerystring,
-			'morecssonbody' => & $morecssonbody,
-			'replacemainareaby' => & $replacemainareaby,
-			'disablenofollow' => & $disablenofollow,
-			'disablenoindex' => & $disablenoindex
+			'head' => &$head,
+			'title' => &$title,
+			'help_url' => &$help_url,
+			'target' => &$target,
+			'disablejs' => &$disablejs,
+			'disablehead' => &$disablehead,
+			'arrayofjs' => &$arrayofjs,
+			'arrayofcss' => &$arrayofcss,
+			'morequerystring' => &$morequerystring,
+			'morecssonbody' => &$morecssonbody,
+			'replacemainareaby' => &$replacemainareaby,
+			'disablenofollow' => &$disablenofollow,
+			'disablenoindex' => &$disablenoindex
 
 		);
 		$reshook = $hookmanager->executeHooks('llxHeader', $parameters);
@@ -1685,7 +1696,7 @@
 		// html header
 		top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, $disablenofollow, $disablenoindex);
 
-		$tmpcsstouse = 'sidebar-collapse'.($morecssonbody ? ' '.$morecssonbody : '');
+		$tmpcsstouse = 'sidebar-collapse' . ($morecssonbody ? ' ' . $morecssonbody : '');
 		// If theme MD and classic layer, we open the menulayer by default.
 		if ($conf->theme == 'md' && !in_array($conf->browser->layout, array('phone', 'tablet')) && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
 			global $mainmenu;
@@ -1695,10 +1706,10 @@
 		}
 
 		if (getDolGlobalString('MAIN_OPTIMIZEFORCOLORBLIND')) {
-			$tmpcsstouse .= ' colorblind-'.strip_tags(getDolGlobalString('MAIN_OPTIMIZEFORCOLORBLIND'));
+			$tmpcsstouse .= ' colorblind-' . strip_tags(getDolGlobalString('MAIN_OPTIMIZEFORCOLORBLIND'));
 		}
 
-		print '<body id="mainbody" class="'.$tmpcsstouse.'">'."\n";
+		print '<body id="mainbody" class="' . $tmpcsstouse . '">' . "\n";
 
 		// top menu and left menu area
 		if ((empty($conf->dol_hide_topmenu) || GETPOSTINT('dol_invisible_topmenu')) && !GETPOST('dol_openinpopup', 'aZ09')) {
@@ -1732,9 +1743,9 @@
 	global $db, $conf, $hookmanager;
 
 	if ($contenttype == 'text/html') {
-		header("Content-Type: text/html; charset=".$conf->file->character_set_client);
+		header("Content-Type: text/html; charset=" . $conf->file->character_set_client);
 	} else {
-		header("Content-Type: ".$contenttype);
+		header("Content-Type: " . $contenttype);
 	}
 
 	// Security options
@@ -1752,7 +1763,7 @@
 	if (getDolGlobalString('MAIN_SECURITY_FORCE_ACCESS_CONTROL_ALLOW_ORIGIN')) {
 		$tmpurl = constant('DOL_MAIN_URL_ROOT');
 		$tmpurl = preg_replace('/^(https?:\/\/[^\/]+)\/.*$/', '\1', $tmpurl);
-		header('Access-Control-Allow-Origin: '.$tmpurl);
+		header('Access-Control-Allow-Origin: ' . $tmpurl);
 		header('Vary: Origin');
 	}
 
@@ -1776,7 +1787,7 @@
 		$contentsecuritypolicy = getDolGlobalString('MAIN_SECURITY_FORCECSPRO');
 
 		if (!is_object($hookmanager)) {
-			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
+			include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
 			$hookmanager = new HookManager($db);
 		}
 		$hookmanager->initHooks(array("main"));
@@ -1790,10 +1801,10 @@
 		}
 
 		if (!empty($contentsecuritypolicy)) {
-			header("Content-Security-Policy-Report-Only: ".$contentsecuritypolicy);
+			header("Content-Security-Policy-Report-Only: " . $contentsecuritypolicy);
 		}
 	} else {
-		header("Content-Security-Policy: ".constant('MAIN_SECURITY_FORCECSPRO'));
+		header("Content-Security-Policy: " . constant('MAIN_SECURITY_FORCECSPRO'));
 	}
 
 	// Content-Security-Policy
@@ -1813,7 +1824,7 @@
 		$contentsecuritypolicy = getDolGlobalString('MAIN_SECURITY_FORCECSP');
 
 		if (!is_object($hookmanager)) {
-			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
+			include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
 			$hookmanager = new HookManager($db);
 		}
 		$hookmanager->initHooks(array("main"));
@@ -1827,10 +1838,10 @@
 		}
 
 		if (!empty($contentsecuritypolicy)) {
-			header("Content-Security-Policy: ".$contentsecuritypolicy);
+			header("Content-Security-Policy: " . $contentsecuritypolicy);
 		}
 	} else {
-		header("Content-Security-Policy: ".constant('MAIN_SECURITY_FORCECSP'));
+		header("Content-Security-Policy: " . constant('MAIN_SECURITY_FORCECSP'));
 	}
 
 	// Referrer-Policy
@@ -1840,7 +1851,7 @@
 	if (!defined('MAIN_SECURITY_FORCERP')) {
 		$referrerpolicy = getDolGlobalString('MAIN_SECURITY_FORCERP', "same-origin");
 
-		header("Referrer-Policy: ".$referrerpolicy);
+		header("Referrer-Policy: " . $referrerpolicy);
 	}
 
 	if ($forcenocache) {
@@ -1876,52 +1887,52 @@
 		$conf->css = '/theme/eldy/style.css.php'; // If not defined, eldy by default
 	}
 
-	print '<!doctype html>'."\n";
+	print '<!doctype html>' . "\n";
 
-	print '<html lang="'.substr($langs->defaultlang, 0, 2).'">'."\n";
+	print '<html lang="' . substr($langs->defaultlang, 0, 2) . '">' . "\n";
 
 	//print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
 	if (empty($disablehead)) {
 		if (!is_object($hookmanager)) {
-			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
+			include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
 			$hookmanager = new HookManager($db);
 		}
 		$hookmanager->initHooks(array("main"));
 
-		$ext = 'layout='.(empty($conf->browser->layout) ? '' : $conf->browser->layout).'&amp;version='.urlencode(DOL_VERSION);
+		$ext = 'layout=' . (empty($conf->browser->layout) ? '' : $conf->browser->layout) . '&amp;version=' . urlencode(DOL_VERSION);
 
 		print "<head>\n";
 
 		if (GETPOST('dol_basehref', 'alpha')) {
-			print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref', 'alpha')).'">'."\n";
+			print '<base href="' . dol_escape_htmltag(GETPOST('dol_basehref', 'alpha')) . '">' . "\n";
 		}
 
 		// Displays meta
-		print '<meta charset="utf-8">'."\n";
-		print '<meta name="robots" content="'.($disablenoindex ? 'index' : 'noindex').($disablenofollow ? ',follow' : ',nofollow').'">'."\n"; // Do not index
-		print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n"; // Scale for mobile device
-		print '<meta name="author" content="Dolibarr Development Team">'."\n";
-		print '<meta name="anti-csrf-newtoken" content="'.newToken().'">'."\n";
-		print '<meta name="anti-csrf-currenttoken" content="'.currentToken().'">'."\n";
+		print '<meta charset="utf-8">' . "\n";
+		print '<meta name="robots" content="' . ($disablenoindex ? 'index' : 'noindex') . ($disablenofollow ? ',follow' : ',nofollow') . '">' . "\n"; // Do not index
+		print '<meta name="viewport" content="width=device-width, initial-scale=1.0">' . "\n"; // Scale for mobile device
+		print '<meta name="author" content="Dolibarr Development Team">' . "\n";
+		print '<meta name="anti-csrf-newtoken" content="' . newToken() . '">' . "\n";
+		print '<meta name="anti-csrf-currenttoken" content="' . currentToken() . '">' . "\n";
 		if (getDolGlobalInt('MAIN_FEATURES_LEVEL')) {
-			print '<meta name="MAIN_FEATURES_LEVEL" content="'.getDolGlobalInt('MAIN_FEATURES_LEVEL').'">'."\n";
+			print '<meta name="MAIN_FEATURES_LEVEL" content="' . getDolGlobalInt('MAIN_FEATURES_LEVEL') . '">' . "\n";
 		}
 		// Favicon
-		$favicon = DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png';
-		$appletouchicon = DOL_URL_ROOT.'/theme/apple-touch-icon.png';
+		$favicon = DOL_URL_ROOT . '/theme/dolibarr_256x256_color.png';
+		$appletouchicon = DOL_URL_ROOT . '/theme/apple-touch-icon.png';
 		if (!empty($mysoc->logo_squarred_mini)) {
-			$favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini);
+			$favicon = DOL_URL_ROOT . '/viewimage.php?cache=1&modulepart=mycompany&file=' . urlencode('logos/thumbs/' . $mysoc->logo_squarred_mini);
 		}
 		if (getDolGlobalString('MAIN_FAVICON_URL')) {
 			$favicon = getDolGlobalString('MAIN_FAVICON_URL');
 		}
 		if (empty($conf->dol_use_jmobile)) {
-			print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n"; // Not required into an Android webview
-			print '<link rel="apple-touch-icon" href="'.$appletouchicon.'"/>'."\n";
+			print '<link rel="shortcut icon" type="image/x-icon" href="' . $favicon . '"/>' . "\n"; // Not required into an Android webview
+			print '<link rel="apple-touch-icon" href="' . $appletouchicon . '"/>' . "\n";
 		}
 
 		// Mobile appli like icon
-		$manifest = DOL_URL_ROOT.'/theme/'.$conf->theme.'/manifest.json.php';
+		$manifest = DOL_URL_ROOT . '/theme/' . $conf->theme . '/manifest.json.php';
 		$parameters = array('manifest' => $manifest);
 		$resHook = $hookmanager->executeHooks('hookSetManifest', $parameters); // Note that $action and $object may have been modified by some hooks
 		if ($resHook > 0) {
@@ -1930,17 +1941,17 @@
 			$manifest .= $hookmanager->resPrint; // Concat to actual manifest declaration
 		}
 		if (!empty($manifest)) {
-			print '<link rel="manifest" href="'.$manifest.'" />'."\n";
+			print '<link rel="manifest" href="' . $manifest . '" />' . "\n";
 		}
 
 		if (getDolGlobalString('THEME_ELDY_TOPMENU_BACK1')) {
 			// TODO: use auto theme color switch
-			print '<meta name="theme-color" content="rgb(' . getDolGlobalString('THEME_ELDY_TOPMENU_BACK1').')">'."\n";
+			print '<meta name="theme-color" content="rgb(' . getDolGlobalString('THEME_ELDY_TOPMENU_BACK1') . ')">' . "\n";
 		}
 
 		// Auto refresh page
 		if (GETPOSTINT('autorefresh') > 0) {
-			print '<meta http-equiv="refresh" content="'.GETPOSTINT('autorefresh').'">';
+			print '<meta http-equiv="refresh" content="' . GETPOSTINT('autorefresh') . '">';
 		}
 
 		// Displays title
@@ -1952,7 +1963,7 @@
 		print '<title>';
 		$titletoshow = '';
 		if ($title && preg_match('/showapp/', getDolGlobalString('MAIN_HTML_TITLE'))) {
-			$titletoshow = dol_htmlentities($appli.' - '.$title);
+			$titletoshow = dol_htmlentities($appli . ' - ' . $title);
 		} elseif ($title) {
 			$titletoshow = dol_htmlentities($title);
 		} else {
@@ -1973,82 +1984,82 @@
 		print "\n";
 
 		if (GETPOSTINT('version')) {
-			$ext = 'version='.GETPOSTINT('version'); // useful to force no cache on css/js
+			$ext = 'version=' . GETPOSTINT('version'); // useful to force no cache on css/js
 		}
 		// Refresh value of MAIN_IHM_PARAMS_REV before forging the parameter line.
 		if (GETPOST('dol_resetcache')) {
-			include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
+			include_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
 			dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", getDolGlobalInt('MAIN_IHM_PARAMS_REV') + 1, 'chaine', 0, '', $conf->entity);
 		}
 
-		$themeparam = '?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss', 'aZ09') ? '&amp;optioncss='.GETPOST('optioncss', 'aZ09', 1) : '').(empty($user->id) ? '' : ('&amp;userid='.$user->id)).'&amp;entity='.$conf->entity;
+		$themeparam = '?lang=' . $langs->defaultlang . '&amp;theme=' . $conf->theme . (GETPOST('optioncss', 'aZ09') ? '&amp;optioncss=' . GETPOST('optioncss', 'aZ09', 1) : '') . (empty($user->id) ? '' : ('&amp;userid=' . $user->id)) . '&amp;entity=' . $conf->entity;
 
-		$themeparam .= ($ext ? '&amp;'.$ext : '').'&amp;revision='.getDolGlobalInt("MAIN_IHM_PARAMS_REV");
+		$themeparam .= ($ext ? '&amp;' . $ext : '') . '&amp;revision=' . getDolGlobalInt("MAIN_IHM_PARAMS_REV");
 		if (GETPOSTISSET('dol_hide_topmenu')) {
-			$themeparam .= '&amp;dol_hide_topmenu='.GETPOSTINT('dol_hide_topmenu');
+			$themeparam .= '&amp;dol_hide_topmenu=' . GETPOSTINT('dol_hide_topmenu');
 		}
 		if (GETPOSTISSET('dol_hide_leftmenu')) {
-			$themeparam .= '&amp;dol_hide_leftmenu='.GETPOSTINT('dol_hide_leftmenu');
+			$themeparam .= '&amp;dol_hide_leftmenu=' . GETPOSTINT('dol_hide_leftmenu');
 		}
 		if (GETPOSTISSET('dol_openinpopup')) {
-			$themeparam .= '&amp;dol_openinpopup='.GETPOST('dol_openinpopup', 'aZ09');
+			$themeparam .= '&amp;dol_openinpopup=' . GETPOST('dol_openinpopup', 'aZ09');
 		}
 		if (GETPOSTISSET('dol_optimize_smallscreen')) {
-			$themeparam .= '&amp;dol_optimize_smallscreen='.GETPOSTINT('dol_optimize_smallscreen');
+			$themeparam .= '&amp;dol_optimize_smallscreen=' . GETPOSTINT('dol_optimize_smallscreen');
 		}
 		if (GETPOSTISSET('dol_no_mouse_hover')) {
-			$themeparam .= '&amp;dol_no_mouse_hover='.GETPOSTINT('dol_no_mouse_hover');
+			$themeparam .= '&amp;dol_no_mouse_hover=' . GETPOSTINT('dol_no_mouse_hover');
 		}
 		if (GETPOSTISSET('dol_use_jmobile')) {
-			$themeparam .= '&amp;dol_use_jmobile='.GETPOSTINT('dol_use_jmobile');
+			$themeparam .= '&amp;dol_use_jmobile=' . GETPOSTINT('dol_use_jmobile');
 			$conf->dol_use_jmobile = GETPOSTINT('dol_use_jmobile');
 		}
 		if (GETPOSTISSET('THEME_DARKMODEENABLED')) {
-			$themeparam .= '&amp;THEME_DARKMODEENABLED='.GETPOSTINT('THEME_DARKMODEENABLED');
+			$themeparam .= '&amp;THEME_DARKMODEENABLED=' . GETPOSTINT('THEME_DARKMODEENABLED');
 		}
 		if (GETPOSTISSET('THEME_SATURATE_RATIO')) {
-			$themeparam .= '&amp;THEME_SATURATE_RATIO='.GETPOSTINT('THEME_SATURATE_RATIO');
+			$themeparam .= '&amp;THEME_SATURATE_RATIO=' . GETPOSTINT('THEME_SATURATE_RATIO');
 		}
 
 		if (getDolGlobalString('MAIN_ENABLE_FONT_ROBOTO')) {
-			print '<link rel="preconnect" href="https://fonts.gstatic.com">'."\n";
-			print '<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@200;300;400;500;600&display=swap" rel="stylesheet">'."\n";
+			print '<link rel="preconnect" href="https://fonts.gstatic.com">' . "\n";
+			print '<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@200;300;400;500;600&display=swap" rel="stylesheet">' . "\n";
 		}
 
 		if (!defined('DISABLE_JQUERY') && !$disablejs && $conf->use_javascript_ajax) {
-			print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
+			print '<!-- Includes CSS for JQuery (Ajax library) -->' . "\n";
 			$jquerytheme = 'base';
 			if (getDolGlobalString('MAIN_USE_JQUERY_THEME')) {
 				$jquerytheme = getDolGlobalString('MAIN_USE_JQUERY_THEME');
 			}
 			if (constant('JS_JQUERY_UI')) {
-				print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // Forced JQuery
+				print '<link rel="stylesheet" type="text/css" href="' . JS_JQUERY_UI . 'css/' . $jquerytheme . '/jquery-ui.min.css' . ($ext ? '?' . $ext : '') . '">' . "\n"; // Forced JQuery
 			} else {
-				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext ? '?'.$ext : '').'">'."\n"; // JQuery
+				print '<link rel="stylesheet" type="text/css" href="' . DOL_URL_ROOT . '/includes/jquery/css/' . $jquerytheme . '/jquery-ui.css' . ($ext ? '?' . $ext : '') . '">' . "\n"; // JQuery
 			}
 			if (!defined('DISABLE_JQUERY_JNOTIFY')) {
-				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // JNotify
+				print '<link rel="stylesheet" type="text/css" href="' . DOL_URL_ROOT . '/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css' . ($ext ? '?' . $ext : '') . '">' . "\n"; // JNotify
 			}
 			if (!defined('DISABLE_SELECT2') && (getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT'))) {     // jQuery plugin "mutiselect", "multiple-select", "select2"...
 				$tmpplugin = !getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') ? constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
-				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext ? '?'.$ext : '').'">'."\n";
+				print '<link rel="stylesheet" type="text/css" href="' . DOL_URL_ROOT . '/includes/jquery/plugins/' . $tmpplugin . '/dist/css/' . $tmpplugin . '.css' . ($ext ? '?' . $ext : '') . '">' . "\n";
 			}
 		}
 
 		if (!defined('DISABLE_FONT_AWSOME')) {
-			print '<!-- Includes CSS for font awesome -->'."\n";
+			print '<!-- Includes CSS for font awesome -->' . "\n";
 			$fontawesome_directory = getDolGlobalString('MAIN_FONTAWESOME_DIRECTORY', '/theme/common/fontawesome-5');
-			print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.$fontawesome_directory.'/css/all.min.css'.($ext ? '?'.$ext : '').'">'."\n";
+			print '<link rel="stylesheet" type="text/css" href="' . DOL_URL_ROOT . $fontawesome_directory . '/css/all.min.css' . ($ext ? '?' . $ext : '') . '">' . "\n";
 		}
 
-		print '<!-- Includes CSS for Dolibarr theme -->'."\n";
+		print '<!-- Includes CSS for Dolibarr theme -->' . "\n";
 		// Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
 		$themepath = dol_buildpath($conf->css, 1);
 		$themesubdir = '';
 		if (!empty($conf->modules_parts['theme'])) {	// This slow down
 			foreach ($conf->modules_parts['theme'] as $reldir) {
-				if (file_exists(dol_buildpath($reldir.$conf->css, 0))) {
-					$themepath = dol_buildpath($reldir.$conf->css, 1);
+				if (file_exists(dol_buildpath($reldir . $conf->css, 0))) {
+					$themepath = dol_buildpath($reldir . $conf->css, 1);
 					$themesubdir = $reldir;
 					break;
 				}
@@ -2056,15 +2067,15 @@
 		}
 
 		//print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
-		print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
+		print '<link rel="stylesheet" type="text/css" href="' . $themepath . $themeparam . '">' . "\n";
 		if (getDolGlobalString('MAIN_FIX_FLASH_ON_CHROME')) {
-			print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
+			print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->' . "\n" . '<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">' . "\n";
 		}
 
 		// LEAFLET AND GEOMAN
 		if (getDolGlobalString('MAIN_USE_GEOPHP')) {
-			print '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/leaflet/leaflet.css'.($ext ? '?'.$ext : '')."\">\n";
-			print '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/leaflet/leaflet-geoman.css'.($ext ? '?'.$ext : '')."\">\n";
+			print '<link rel="stylesheet" href="' . DOL_URL_ROOT . '/includes/leaflet/leaflet.css' . ($ext ? '?' . $ext : '') . "\">\n";
+			print '<link rel="stylesheet" href="' . DOL_URL_ROOT . '/includes/leaflet/leaflet-geoman.css' . ($ext ? '?' . $ext : '') . "\">\n";
 		}
 
 		// CSS forced by modules (relative url starting with /)
@@ -2074,19 +2085,19 @@
 				$filescss = (array) $filescss; // To be sure filecss is an array
 				foreach ($filescss as $cssfile) {
 					if (empty($cssfile)) {
-						dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
+						dol_syslog("Warning: module " . $modcss . " declared a css path file into its descriptor that is empty.", LOG_WARNING);
 					}
 					// cssfile is a relative path
 					$urlforcss = dol_buildpath($cssfile, 1);
 					if ($urlforcss && $urlforcss != '/') {
-						print '<!-- Includes CSS added by module '.$modcss.' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.$urlforcss;
+						print '<!-- Includes CSS added by module ' . $modcss . ' -->' . "\n" . '<link rel="stylesheet" type="text/css" href="' . $urlforcss;
 						// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
 						if (!preg_match('/\.css$/i', $cssfile)) {
 							print $themeparam;
 						}
-						print '">'."\n";
+						print '">' . "\n";
 					} else {
-						dol_syslog("Warning: module ".$modcss." declared a css path file for a file we can't find.", LOG_WARNING);
+						dol_syslog("Warning: module " . $modcss . " declared a css path file for a file we can't find.", LOG_WARNING);
 					}
 				}
 			}
@@ -2099,107 +2110,107 @@
 				} else {
 					$urltofile = dol_buildpath($cssfile, 1);
 				}
-				print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.$urltofile;
+				print '<!-- Includes CSS added by page -->' . "\n" . '<link rel="stylesheet" type="text/css" title="default" href="' . $urltofile;
 				// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
 				if (!preg_match('/\.css$/i', $cssfile)) {
 					print $themeparam;
 				}
-				print '">'."\n";
+				print '">' . "\n";
 			}
 		}
 
 		// Custom CSS
 		if (getDolGlobalString('MAIN_IHM_CUSTOM_CSS')) {
 			// If a custom CSS was set, we add link to the custom css php file
-			print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/custom.css.php'.($ext ? '?'.$ext : '').'&amp;revision='.getDolGlobalInt("MAIN_IHM_PARAMS_REV").'">'."\n";
+			print '<link rel="stylesheet" type="text/css" href="' . DOL_URL_ROOT . '/theme/custom.css.php' . ($ext ? '?' . $ext : '') . '&amp;revision=' . getDolGlobalInt("MAIN_IHM_PARAMS_REV") . '">' . "\n";
 		}
 
 		// Output standard javascript links
 		if (!defined('DISABLE_JQUERY') && !$disablejs && !empty($conf->use_javascript_ajax)) {
 			// JQuery. Must be before other includes
-			print '<!-- Includes JS for JQuery -->'."\n";
+			print '<!-- Includes JS for JQuery -->' . "\n";
 			if (defined('JS_JQUERY') && constant('JS_JQUERY')) {
-				print '<script nonce="'.getNonce().'" src="'.JS_JQUERY.'jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . JS_JQUERY . 'jquery.min.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			} else {
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/js/jquery.min.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			}
 			if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) {
-				print '<script nonce="'.getNonce().'" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . JS_JQUERY_UI . 'jquery-ui.min.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			} else {
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/js/jquery-ui.min.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			}
 			// jQuery jnotify
 			if (!getDolGlobalString('MAIN_DISABLE_JQUERY_JNOTIFY') && !defined('DISABLE_JQUERY_JNOTIFY')) {
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/plugins/jnotify/jquery.jnotify.min.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			}
 			// Table drag and drop lines
 			if (empty($disableforlogin) && !defined('DISABLE_JQUERY_TABLEDND')) {
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/plugins/tablednd/jquery.tablednd.min.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			}
 			// Chart
 			if (empty($disableforlogin) && (!getDolGlobalString('MAIN_JS_GRAPH') || getDolGlobalString('MAIN_JS_GRAPH') == 'chart') && !defined('DISABLE_JS_GRAPH')) {
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/nnnick/chartjs/dist/chart.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/nnnick/chartjs/dist/chart.min.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			}
 
 			// jQuery jeditable for Edit In Place features
 			if (getDolGlobalString('MAIN_USE_JQUERY_JEDITABLE') && !defined('DISABLE_JQUERY_JEDITABLE')) {
-				print '<!-- JS to manage editInPlace feature -->'."\n";
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
-				print '<script>'."\n";
-				print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
-				print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
-				print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n"; // Added in title attribute of span
-				print 'var placeholderInPlace = \'&nbsp;\';'."\n"; // If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
-				print 'var cancelInPlace = \''.$langs->trans("Cancel").'\';'."\n";
-				print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
-				print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
+				print '<!-- JS to manage editInPlace feature -->' . "\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/plugins/jeditable/jquery.jeditable.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
+				print '<script>' . "\n";
+				print 'var urlSaveInPlace = \'' . DOL_URL_ROOT . '/core/ajax/saveinplace.php\';' . "\n";
+				print 'var urlLoadInPlace = \'' . DOL_URL_ROOT . '/core/ajax/loadinplace.php\';' . "\n";
+				print 'var tooltipInPlace = \'' . $langs->transnoentities('ClickToEdit') . '\';' . "\n"; // Added in title attribute of span
+				print 'var placeholderInPlace = \'&nbsp;\';' . "\n"; // If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
+				print 'var cancelInPlace = \'' . $langs->trans("Cancel") . '\';' . "\n";
+				print 'var submitInPlace = \'' . $langs->trans('Ok') . '\';' . "\n";
+				print 'var indicatorInPlace = \'<img src="' . DOL_URL_ROOT . "/theme/" . $conf->theme . "/img/working.gif" . '">\';' . "\n";
 				print 'var withInPlace = 300;'; // width in pixel for default string edit
-				print '</script>'."\n";
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '</script>' . "\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/core/js/editinplace.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			}
 			// jQuery Timepicker
 			if (getDolGlobalString('MAIN_USE_JQUERY_TIMEPICKER') || defined('REQUIRE_JQUERY_TIMEPICKER')) {
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext ? '&amp;'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/core/js/timepicker.js.php?lang=' . $langs->defaultlang . ($ext ? '&amp;' . $ext : '') . '"></script>' . "\n";
 			}
 			if (!defined('DISABLE_SELECT2') && (getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT'))) {
 				// jQuery plugin "mutiselect", "multiple-select", "select2", ...
 				$tmpplugin = !getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') ? constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; // We include full because we need the support of containerCssClass
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/plugins/' . $tmpplugin . '/dist/js/' . $tmpplugin . '.full.min.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n"; // We include full because we need the support of containerCssClass
 			}
 			if (!defined('DISABLE_MULTISELECT')) {     // jQuery plugin "mutiselect" to select with checkboxes. Can be removed once we have an enhanced search tool
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/jquery/plugins/multiselect/jquery.multi-select.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			}
 		}
 
 		if (!$disablejs && !empty($conf->use_javascript_ajax)) {
 			// CKEditor
 			if (empty($disableforlogin) && (isModEnabled('fckeditor') && (!getDolGlobalString('FCKEDITOR_EDITORNAME') || getDolGlobalString('FCKEDITOR_EDITORNAME') == 'ckeditor') && !defined('DISABLE_CKEDITOR')) || defined('FORCE_CKEDITOR')) {
-				print '<!-- Includes JS for CKEditor -->'."\n";
-				$pathckeditor = DOL_URL_ROOT.'/includes/ckeditor/ckeditor/';
+				print '<!-- Includes JS for CKEditor -->' . "\n";
+				$pathckeditor = DOL_URL_ROOT . '/includes/ckeditor/ckeditor/';
 				$jsckeditor = 'ckeditor.js';
 				if (constant('JS_CKEDITOR')) {
 					// To use external ckeditor 4 js lib
 					$pathckeditor = constant('JS_CKEDITOR');
 				}
-				print '<script nonce="'.getNonce().'">';
+				print '<script nonce="' . getNonce() . '">';
 				print '/* enable ckeditor by main.inc.php */';
-				print 'var CKEDITOR_BASEPATH = \''.dol_escape_js($pathckeditor).'\';'."\n";
-				print 'var ckeditorConfig = \''.dol_escape_js(dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext ? '?'.$ext : ''), 1)).'\';'."\n"; // $themesubdir='' in standard usage
-				print 'var ckeditorFilebrowserBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
-				print 'var ckeditorFilebrowserImageBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
-				print '</script>'."\n";
-				print '<script src="'.$pathckeditor.$jsckeditor.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print 'var CKEDITOR_BASEPATH = \'' . dol_escape_js($pathckeditor) . '\';' . "\n";
+				print 'var ckeditorConfig = \'' . dol_escape_js(dol_buildpath($themesubdir . '/theme/' . $conf->theme . '/ckeditor/config.js' . ($ext ? '?' . $ext : ''), 1)) . '\';' . "\n"; // $themesubdir='' in standard usage
+				print 'var ckeditorFilebrowserBrowseUrl = \'' . DOL_URL_ROOT . '/core/filemanagerdol/browser/default/browser.php?Connector=' . DOL_URL_ROOT . '/core/filemanagerdol/connectors/php/connector.php\';' . "\n";
+				print 'var ckeditorFilebrowserImageBrowseUrl = \'' . DOL_URL_ROOT . '/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector=' . DOL_URL_ROOT . '/core/filemanagerdol/connectors/php/connector.php\';' . "\n";
+				print '</script>' . "\n";
+				print '<script src="' . $pathckeditor . $jsckeditor . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 				print '<script>';
 				if (GETPOST('mode', 'aZ09') == 'Full_inline') {
-					print 'CKEDITOR.disableAutoInline = false;'."\n";
+					print 'CKEDITOR.disableAutoInline = false;' . "\n";
 				} else {
-					print 'CKEDITOR.disableAutoInline = true;'."\n";
+					print 'CKEDITOR.disableAutoInline = true;' . "\n";
 				}
-				print '</script>'."\n";
+				print '</script>' . "\n";
 			}
 
 			// Browser notifications (if NOREQUIREMENU is on, it is mostly a page for popup, so we do not enable notif too. We hide also for public pages).
@@ -2212,19 +2223,19 @@
 					$enablebrowsernotif = false;
 				}
 				if ($enablebrowsernotif) {
-					print '<!-- Includes JS of Dolibarr (browser layout = '.$conf->browser->layout.')-->'."\n";
-					print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php?lang='.$langs->defaultlang.($ext ? '&amp;'.$ext : '').'"></script>'."\n";
+					print '<!-- Includes JS of Dolibarr (browser layout = ' . $conf->browser->layout . ')-->' . "\n";
+					print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/core/js/lib_notification.js.php?lang=' . $langs->defaultlang . ($ext ? '&amp;' . $ext : '') . '"></script>' . "\n";
 				}
 			}
 
 			// Global js function
-			print '<!-- Includes JS of Dolibarr -->'."\n";
-			print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext ? '&amp;'.$ext : '').'"></script>'."\n";
+			print '<!-- Includes JS of Dolibarr -->' . "\n";
+			print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/core/js/lib_head.js.php?lang=' . $langs->defaultlang . ($ext ? '&amp;' . $ext : '') . '"></script>' . "\n";
 
 			// Leaflet TODO use dolibarr files
 			if (getDolGlobalString('MAIN_USE_GEOPHP')) {
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/leaflet/leaflet.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/includes/leaflet/leaflet-geoman.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/leaflet/leaflet.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/includes/leaflet/leaflet-geoman.min.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			}
 
 			// JS forced by modules (relative url starting with /)
@@ -2236,22 +2247,22 @@
 						// jsfile is a relative path
 						$urlforjs = dol_buildpath($jsfile, 1);
 						if ($urlforjs && $urlforjs != '/') {
-							print '<!-- Include JS added by module '.$modjs.'-->'."\n";
-							print '<script nonce="'.getNonce().'" src="'.$urlforjs.((strpos($jsfile, '?') === false) ? '?' : '&amp;').'lang='.$langs->defaultlang.'"></script>'."\n";
+							print '<!-- Include JS added by module ' . $modjs . '-->' . "\n";
+							print '<script nonce="' . getNonce() . '" src="' . $urlforjs . ((strpos($jsfile, '?') === false) ? '?' : '&amp;') . 'lang=' . $langs->defaultlang . '"></script>' . "\n";
 						} else {
-							dol_syslog("Warning: module ".$modjs." declared a js path file for a file we can't find.", LOG_WARNING);
+							dol_syslog("Warning: module " . $modjs . " declared a js path file for a file we can't find.", LOG_WARNING);
 						}
 					}
 				}
 			}
 			// JS forced by page in top_htmlhead (relative url starting with /)
 			if (is_array($arrayofjs)) {
-				print '<!-- Includes JS added by page -->'."\n";
+				print '<!-- Includes JS added by page -->' . "\n";
 				foreach ($arrayofjs as $jsfile) {
 					if (preg_match('/^(http|\/\/)/i', $jsfile)) {
-						print '<script nonce="'.getNonce().'" src="'.$jsfile.((strpos($jsfile, '?') === false) ? '?' : '&amp;').'lang='.$langs->defaultlang.'"></script>'."\n";
+						print '<script nonce="' . getNonce() . '" src="' . $jsfile . ((strpos($jsfile, '?') === false) ? '?' : '&amp;') . 'lang=' . $langs->defaultlang . '"></script>' . "\n";
 					} else {
-						print '<script nonce="'.getNonce().'" src="'.dol_buildpath($jsfile, 1).((strpos($jsfile, '?') === false) ? '?' : '&amp;').'lang='.$langs->defaultlang.'"></script>'."\n";
+						print '<script nonce="' . getNonce() . '" src="' . dol_buildpath($jsfile, 1) . ((strpos($jsfile, '?') === false) ? '?' : '&amp;') . 'lang=' . $langs->defaultlang . '"></script>' . "\n";
 					}
 				}
 			}
@@ -2259,14 +2270,14 @@
 
 		//If you want to load custom javascript file from your selected theme directory
 		if (getDolGlobalString('ALLOW_THEME_JS')) {
-			$theme_js = dol_buildpath('/theme/'.$conf->theme.'/'.$conf->theme.'.js', 0);
+			$theme_js = dol_buildpath('/theme/' . $conf->theme . '/' . $conf->theme . '.js', 0);
 			if (file_exists($theme_js)) {
-				print '<script nonce="'.getNonce().'" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/'.$conf->theme.'.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
+				print '<script nonce="' . getNonce() . '" src="' . DOL_URL_ROOT . '/theme/' . $conf->theme . '/' . $conf->theme . '.js' . ($ext ? '?' . $ext : '') . '"></script>' . "\n";
 			}
 		}
 
 		if (!empty($head)) {
-			print $head."\n";
+			print $head . "\n";
 		}
 		if (getDolGlobalString('MAIN_HTML_HEADER')) {
 			print getDolGlobalString('MAIN_HTML_HEADER') . "\n";
@@ -2324,16 +2335,16 @@
 	 */
 	if ((empty($conf->dol_hide_topmenu) || GETPOSTINT('dol_invisible_topmenu')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) {
 		if (!isset($form) || !is_object($form)) {
-			include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
+			include_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php';
 			$form = new Form($db);
 		}
 
-		print "\n".'<!-- Start top horizontal -->'."\n";
+		print "\n" . '<!-- Start top horizontal -->' . "\n";
 
-		print '<header id="id-top" class="side-nav-vert'.(GETPOSTINT('dol_invisible_topmenu') ? ' hidden' : '').'">'; // dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
+		print '<header id="id-top" class="side-nav-vert' . (GETPOSTINT('dol_invisible_topmenu') ? ' hidden' : '') . '">'; // dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
 
 		// Show menu entries
-		print '<div id="tmenu_tooltip'.(!getDolGlobalString('MAIN_MENU_INVERT') ? '' : 'invert').'" class="tmenu">'."\n";
+		print '<div id="tmenu_tooltip' . (!getDolGlobalString('MAIN_MENU_INVERT') ? '' : 'invert') . '" class="tmenu">' . "\n";
 		// @phan-suppress-next-line PhanRedefinedClassReference
 		$menumanager->atarget = $target;
 		// @phan-suppress-next-line PhanRedefinedClassReference
@@ -2345,18 +2356,18 @@
 		if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
 			$appli = getDolGlobalString('MAIN_APPLICATION_TITLE');
 			if (preg_match('/\d\.\d/', $appli)) {
-				if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
-					$appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
+				if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli)) {
+					$appli .= " (" . DOL_VERSION . ")"; // If new title contains a version that is different than core
 				}
 			} else {
-				$appli .= " ".DOL_VERSION;
+				$appli .= " " . DOL_VERSION;
 			}
 		} else {
-			$appli .= " ".DOL_VERSION;
+			$appli .= " " . DOL_VERSION;
 		}
 
 		if (getDolGlobalInt('MAIN_FEATURES_LEVEL')) {
-			$appli .= "<br>".$langs->trans("LevelOfFeature").': '.getDolGlobalInt('MAIN_FEATURES_LEVEL');
+			$appli .= "<br>" . $langs->trans("LevelOfFeature") . ': ' . getDolGlobalInt('MAIN_FEATURES_LEVEL');
 		}
 
 		$logouttext = '';
@@ -2372,18 +2383,18 @@
 				$stringforfirstkey .= ' CTL +';
 			}
 			if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http') {
-				$logouthtmltext .= $langs->trans("Logout").'<br>';
-				$logouttext .= '<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php?token='.newToken().'">';
-				$logouttext .= img_picto($langs->trans('Logout').' ('.$stringforfirstkey.' l)', 'sign-out', '', 0, 0, 0, '', 'atoplogin valignmiddle');
+				$logouthtmltext .= $langs->trans("Logout") . '<br>';
+				$logouttext .= '<a accesskey="l" href="' . DOL_URL_ROOT . '/user/logout.php?token=' . newToken() . '">';
+				$logouttext .= img_picto($langs->trans('Logout') . ' (' . $stringforfirstkey . ' l)', 'sign-out', '', 0, 0, 0, '', 'atoplogin valignmiddle');
 				$logouttext .= '</a>';
 			} else {
 				$logouthtmltext .= $langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]);
-				$logouttext .= img_picto($langs->trans('Logout').' ('.$stringforfirstkey.' l)', 'sign-out', '', 0, 0, 0, '', 'atoplogin valignmiddle opacitymedium');
+				$logouttext .= img_picto($langs->trans('Logout') . ' (' . $stringforfirstkey . ' l)', 'sign-out', '', 0, 0, 0, '', 'atoplogin valignmiddle opacitymedium');
 			}
 		}
 
 
-		print '<div class="login_block usedropdown">'."\n";
+		print '<div class="login_block usedropdown">' . "\n";
 
 
 		// Add block for tools
@@ -2412,7 +2423,7 @@
 
 		$toprightmenu .= '</div>';
 
-		$toprightmenu .= '</div>'."\n";		 // end div class="login_block_tools"
+		$toprightmenu .= '</div>' . "\n";		 // end div class="login_block_tools"
 
 
 		// Add block for other tools
@@ -2433,7 +2444,7 @@
 
 		// Link to module builder
 		if (isModEnabled('modulebuilder')) {
-			$text = '<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="modulebuilder">';
+			$text = '<a href="' . DOL_URL_ROOT . '/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="modulebuilder">';
 			//$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
 			$text .= '<span class="fa fa-bug atoplogin valignmiddle"></span>';
 			$text .= '</a>';
@@ -2453,19 +2464,19 @@
 					}
 					if (!is_array($value)) {
 						if ($value !== '') {
-							$qs .= '&'.urlencode($key).'='.urlencode($value);
+							$qs .= '&' . urlencode($key) . '=' . urlencode($value);
 						}
 					} else {
 						foreach ($value as $value2) {
 							if (($value2 !== '') && (!is_array($value2))) {
-								$qs .= '&'.urlencode($key).'[]='.urlencode($value2);
+								$qs .= '&' . urlencode($key) . '[]=' . urlencode($value2);
 							}
 						}
 					}
 				}
 			}
-			$qs .= (($qs && $morequerystring) ? '&' : '').$morequerystring;
-			$text = '<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs ? '&' : '').'optioncss=print" target="_blank" rel="noopener noreferrer">';
+			$qs .= (($qs && $morequerystring) ? '&' : '') . $morequerystring;
+			$text = '<a href="' . dol_escape_htmltag($_SERVER["PHP_SELF"]) . '?' . $qs . ($qs ? '&' : '') . 'optioncss=print" target="_blank" rel="noopener noreferrer">';
 			//$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
 			$text .= '<span class="fa fa-print atoplogin valignmiddle"></span>';
 			$text .= '</a>';
@@ -2497,13 +2508,13 @@
 			// Link to help pages
 			if ($helpbaseurl && $helppage) {
 				$text = '';
-				$title = $langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage').', ';
+				$title = $langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage') . ', ';
 				if ($mode == 'wiki') {
-					$title .= '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$langs->trans("PageWiki").' '.dol_escape_htmltag('"'.strtr($helppage, '_', ' ').'"');
+					$title .= '<br>' . img_picto('', 'globe', 'class="pictofixedwidth"') . $langs->trans("PageWiki") . ' ' . dol_escape_htmltag('"' . strtr($helppage, '_', ' ') . '"');
 					if ($helppresent) {
-						$title .= ' <span class="opacitymedium">('.$langs->trans("DedicatedPageAvailable").')</span>';
+						$title .= ' <span class="opacitymedium">(' . $langs->trans("DedicatedPageAvailable") . ')</span>';
 					} else {
-						$title .= ' <span class="opacitymedium">('.$langs->trans("HomePage").')</span>';
+						$title .= ' <span class="opacitymedium">(' . $langs->trans("HomePage") . ')</span>';
 					}
 				}
 				$text .= '<a class="help" target="_blank" rel="noopener noreferrer" href="';
@@ -2515,8 +2526,8 @@
 					$text .= sprintf($helpbaseurl, $helppage);
 				}
 				$text .= '">';
-				$text .= '<span class="fa fa-question-circle atoplogin valignmiddle'.($helppresent ? ' '.$helppresent : '').'"></span>';
-				$text .= '<span class="fa fa-long-arrow-alt-up helppresentcircle'.($helppresent ? '' : ' unvisible').'"></span>';
+				$text .= '<span class="fa fa-question-circle atoplogin valignmiddle' . ($helppresent ? ' ' . $helppresent : '') . '"></span>';
+				$text .= '<span class="fa fa-long-arrow-alt-up helppresentcircle' . ($helppresent ? '' : ' unvisible') . '"></span>';
 				$text .= '</a>';
 				// @phan-suppress-next-line PhanPluginSuspiciousParamPosition
 				$toprightmenu .= $form->textwithtooltip('', $title, 2, 1, $text, 'login_block_elem', 2);
@@ -2525,13 +2536,13 @@
 			// Version
 			if (getDolGlobalString('MAIN_SHOWDATABASENAMEINHELPPAGESLINK')) {
 				$langs->load('admin');
-				$appli .= '<br>'.$langs->trans("Database").': '.$db->database_name;
+				$appli .= '<br>' . $langs->trans("Database") . ': ' . $db->database_name;
 			}
 		}
 
 		// Version
 		if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && getDolGlobalInt('MAIN_HIDE_VERSION') == 0) {
-			$text = '<span class="aversion"><span class="hideonsmartphone small">'.DOL_VERSION.'</span></span>';
+			$text = '<span class="aversion"><span class="hideonsmartphone small">' . DOL_VERSION . '</span></span>';
 			// @phan-suppress-next-line PhanPluginSuspiciousParamPosition
 			$toprightmenu .= $form->textwithtooltip('', $appli, 2, 1, $text, 'login_block_elem', 2);
 		}
@@ -2555,7 +2566,7 @@
 
 		$toprightmenu .= '</div>';
 
-		$toprightmenu .= '</div>'."\n";
+		$toprightmenu .= '</div>' . "\n";
 
 
 		print $toprightmenu;
@@ -2608,19 +2619,19 @@
 			$nophoto = '/public/theme/common/user_woman.png';
 		}
 
-		$userImage = '<img class="photo photouserphoto userphoto" alt="" src="'.DOL_URL_ROOT.$nophoto.'" aria-hidden="true">';
-		$userDropDownImage = '<img class="photo dropdown-user-image" alt="" src="'.DOL_URL_ROOT.$nophoto.'">';
+		$userImage = '<img class="photo photouserphoto userphoto" alt="" src="' . DOL_URL_ROOT . $nophoto . '" aria-hidden="true">';
+		$userDropDownImage = '<img class="photo dropdown-user-image" alt="" src="' . DOL_URL_ROOT . $nophoto . '">';
 	}
 
 	$dropdownBody = '';
-	$dropdownBody .= '<span id="topmenulogincompanyinfo-btn"><i class="fa fa-caret-right"></i> '.$langs->trans("ShowCompanyInfos").'</span>';
+	$dropdownBody .= '<span id="topmenulogincompanyinfo-btn"><i class="fa fa-caret-right"></i> ' . $langs->trans("ShowCompanyInfos") . '</span>';
 	$dropdownBody .= '<div id="topmenulogincompanyinfo" >';
 
-	$dropdownBody .= '<br><b>'.$langs->trans("Company").'</b>: <span>'.dol_escape_htmltag($mysoc->name).'</span>';
+	$dropdownBody .= '<br><b>' . $langs->trans("Company") . '</b>: <span>' . dol_escape_htmltag($mysoc->name) . '</span>';
 	$idprofcursor = 0;
 	while ($idprofcursor < 10) {
 		$idprofcursor++;
-		$constkeyforprofid = 'MAIN_INFO_PROFID'.$idprofcursor;
+		$constkeyforprofid = 'MAIN_INFO_PROFID' . $idprofcursor;
 		if ($idprofcursor == 1) {
 			$constkeyforprofid = 'MAIN_INFO_SIREN';
 		}
@@ -2633,70 +2644,70 @@
 		if ($idprofcursor == 4) {
 			$constkeyforprofid = 'MAIN_INFO_RCS';
 		}
-		$showprofid = (($idprofcursor <= 6) && $langs->transcountry("ProfId".$idprofcursor, $mysoc->country_code) != '-');
+		$showprofid = (($idprofcursor <= 6) && $langs->transcountry("ProfId" . $idprofcursor, $mysoc->country_code) != '-');
 		if ($idprofcursor > 6 && getDolGlobalString($constkeyforprofid)) {
 			$showprofid = true;
 		}
 		if ($showprofid) {
-			$dropdownBody .= '<br><b>'.$langs->transcountry("ProfId".$idprofcursor, $mysoc->country_code).'</b>: <span>'.dol_print_profids(getDolGlobalString($constkeyforprofid), '1').'</span>';
+			$dropdownBody .= '<br><b>' . $langs->transcountry("ProfId" . $idprofcursor, $mysoc->country_code) . '</b>: <span>' . dol_print_profids(getDolGlobalString($constkeyforprofid), '1') . '</span>';
 		}
 	}
-	$dropdownBody .= '<br><b>'.$langs->trans("VATIntraShort").'</b>: <span>'.dol_print_profids(getDolGlobalString("MAIN_INFO_TVAINTRA"), 'VAT').'</span>';
-	$dropdownBody .= '<br><b>'.$langs->trans("Country").'</b>: <span>'.($mysoc->country_code ? $langs->trans("Country".$mysoc->country_code) : '').'</span>';
+	$dropdownBody .= '<br><b>' . $langs->trans("VATIntraShort") . '</b>: <span>' . dol_print_profids(getDolGlobalString("MAIN_INFO_TVAINTRA"), 'VAT') . '</span>';
+	$dropdownBody .= '<br><b>' . $langs->trans("Country") . '</b>: <span>' . ($mysoc->country_code ? $langs->trans("Country" . $mysoc->country_code) : '') . '</span>';
 	if (isModEnabled('multicurrency')) {
-		$dropdownBody .= '<br><b>'.$langs->trans("Currency").'</b>: <span>'.$conf->currency.'</span>';
+		$dropdownBody .= '<br><b>' . $langs->trans("Currency") . '</b>: <span>' . $conf->currency . '</span>';
 	}
 	$dropdownBody .= '</div>';
 
 	$dropdownBody .= '<br>';
-	$dropdownBody .= '<span id="topmenuloginmoreinfo-btn"><i class="fa fa-caret-right"></i> '.$langs->trans("ShowMoreInfos").'</span>';
+	$dropdownBody .= '<span id="topmenuloginmoreinfo-btn"><i class="fa fa-caret-right"></i> ' . $langs->trans("ShowMoreInfos") . '</span>';
 	$dropdownBody .= '<div id="topmenuloginmoreinfo" >';
 
 	// login infos
 	if (!empty($user->admin)) {
-		$dropdownBody .= '<br><b>'.$langs->trans("Administrator").'</b>: '.yn($user->admin);
+		$dropdownBody .= '<br><b>' . $langs->trans("Administrator") . '</b>: ' . yn($user->admin);
 	}
 	$company = '';
 	if (!empty($user->socid)) {	// Add third party for external users
 		$thirdpartystatic = new Societe($db);
 		$thirdpartystatic->fetch($user->socid);
-		$companylink = ' '.$thirdpartystatic->getNomUrl(2); // picto only of company
-		$company = ' ('.$langs->trans("Company").': '.$thirdpartystatic->name.')';
+		$companylink = ' ' . $thirdpartystatic->getNomUrl(2); // picto only of company
+		$company = ' (' . $langs->trans("Company") . ': ' . $thirdpartystatic->name . ')';
 	}
-	$type = ($user->socid ? $langs->trans("External").$company : $langs->trans("Internal"));
-	$dropdownBody .= '<br><b>'.$langs->trans("Type").':</b> '.$type;
-	$dropdownBody .= '<br><b>'.$langs->trans("Status").'</b>: '.$user->getLibStatut(0);
+	$type = ($user->socid ? $langs->trans("External") . $company : $langs->trans("Internal"));
+	$dropdownBody .= '<br><b>' . $langs->trans("Type") . ':</b> ' . $type;
+	$dropdownBody .= '<br><b>' . $langs->trans("Status") . '</b>: ' . $user->getLibStatut(0);
 	$dropdownBody .= '<br>';
 
-	$dropdownBody .= '<br><u>'.$langs->trans("Session").'</u>';
-	$dropdownBody .= '<br><b>'.$langs->trans("IPAddress").'</b>: '.dol_escape_htmltag($_SERVER["REMOTE_ADDR"]);
+	$dropdownBody .= '<br><u>' . $langs->trans("Session") . '</u>';
+	$dropdownBody .= '<br><b>' . $langs->trans("IPAddress") . '</b>: ' . dol_escape_htmltag($_SERVER["REMOTE_ADDR"]);
 	if (getDolGlobalString('MAIN_MODULE_MULTICOMPANY')) {
-		$dropdownBody .= '<br><b>'.$langs->trans("ConnectedOnMultiCompany").':</b> '.$conf->entity.' (user entity '.$user->entity.')';
+		$dropdownBody .= '<br><b>' . $langs->trans("ConnectedOnMultiCompany") . ':</b> ' . $conf->entity . ' (user entity ' . $user->entity . ')';
 	}
-	$dropdownBody .= '<br><b>'.$langs->trans("AuthenticationMode").':</b> '.$_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)');
-	$dropdownBody .= '<br><b>'.$langs->trans("ConnectedSince").':</b> '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser');
-	$dropdownBody .= '<br><b>'.$langs->trans("PreviousConnexion").':</b> '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser');
-	$dropdownBody .= '<br><b>'.$langs->trans("CurrentTheme").':</b> '.$conf->theme;
+	$dropdownBody .= '<br><b>' . $langs->trans("AuthenticationMode") . ':</b> ' . $_SESSION["dol_authmode"] . (empty($dolibarr_main_demo) ? '' : ' (demo)');
+	$dropdownBody .= '<br><b>' . $langs->trans("ConnectedSince") . ':</b> ' . dol_print_date($user->datelastlogin, "dayhour", 'tzuser');
+	$dropdownBody .= '<br><b>' . $langs->trans("PreviousConnexion") . ':</b> ' . dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser');
+	$dropdownBody .= '<br><b>' . $langs->trans("CurrentTheme") . ':</b> ' . $conf->theme;
 	// @phan-suppress-next-line PhanRedefinedClassReference
-	$dropdownBody .= '<br><b>'.$langs->trans("CurrentMenuManager").':</b> '.(isset($menumanager) ? $menumanager->name : 'unknown');
+	$dropdownBody .= '<br><b>' . $langs->trans("CurrentMenuManager") . ':</b> ' . (isset($menumanager) ? $menumanager->name : 'unknown');
 	$langFlag = picto_from_langcode($langs->getDefaultLang());
-	$dropdownBody .= '<br><b>'.$langs->trans("CurrentUserLanguage").':</b> '.($langFlag ? $langFlag.' ' : '').$langs->getDefaultLang();
+	$dropdownBody .= '<br><b>' . $langs->trans("CurrentUserLanguage") . ':</b> ' . ($langFlag ? $langFlag . ' ' : '') . $langs->getDefaultLang();
 
 	$tz = (int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst'];
-	$dropdownBody .= '<br><b>'.$langs->trans("ClientTZ").':</b> '.($tz ? ($tz >= 0 ? '+' : '').$tz : '');
-	$dropdownBody .= ' ('.$_SESSION['dol_tz_string'].')';
+	$dropdownBody .= '<br><b>' . $langs->trans("ClientTZ") . ':</b> ' . ($tz ? ($tz >= 0 ? '+' : '') . $tz : '');
+	$dropdownBody .= ' (' . $_SESSION['dol_tz_string'] . ')';
 	//$dropdownBody .= ' &nbsp; &nbsp; &nbsp; '.$langs->trans("DaylingSavingTime").': ';
 	//if ($_SESSION['dol_dst'] > 0) $dropdownBody .= yn(1);
 	//else $dropdownBody .= yn(0);
 
-	$dropdownBody .= '<br><b>'.$langs->trans("Browser").':</b> '.$conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' <small class="opacitymedium">('.dol_escape_htmltag($_SERVER['HTTP_USER_AGENT']).')</small>';
-	$dropdownBody .= '<br><b>'.$langs->trans("Layout").':</b> '.$conf->browser->layout;
-	$dropdownBody .= '<br><b>'.$langs->trans("Screen").':</b> '.$_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight'];
+	$dropdownBody .= '<br><b>' . $langs->trans("Browser") . ':</b> ' . $conf->browser->name . ($conf->browser->version ? ' ' . $conf->browser->version : '') . ' <small class="opacitymedium">(' . dol_escape_htmltag($_SERVER['HTTP_USER_AGENT']) . ')</small>';
+	$dropdownBody .= '<br><b>' . $langs->trans("Layout") . ':</b> ' . $conf->browser->layout;
+	$dropdownBody .= '<br><b>' . $langs->trans("Screen") . ':</b> ' . $_SESSION['dol_screenwidth'] . ' x ' . $_SESSION['dol_screenheight'];
 	if ($conf->browser->layout == 'phone') {
-		$dropdownBody .= '<br><b>'.$langs->trans("Phone").':</b> '.$langs->trans("Yes");
+		$dropdownBody .= '<br><b>' . $langs->trans("Phone") . ':</b> ' . $langs->trans("Yes");
 	}
 	if (!empty($_SESSION["disablemodules"])) {
-		$dropdownBody .= '<br><b>'.$langs->trans("DisabledModules").':</b> <br>'.implode(', ', explode(',', $_SESSION["disablemodules"]));
+		$dropdownBody .= '<br><b>' . $langs->trans("DisabledModules") . ':</b> <br>' . implode(', ', explode(',', $_SESSION["disablemodules"]));
 	}
 	$dropdownBody .= '</div>';
 
@@ -2712,7 +2723,7 @@
 	}
 
 	if (empty($urllogout)) {
-		$urllogout = DOL_URL_ROOT.'/user/logout.php?token='.newToken();
+		$urllogout = DOL_URL_ROOT . '/user/logout.php?token=' . newToken();
 	}
 
 	// accesskey is for Windows or Linux:  ALT + key for chrome, ALT + SHIFT + KEY for firefox
@@ -2727,14 +2738,14 @@
 	}
 
 	// Defined the links for bottom of card
-	$profilLink = '<a accesskey="u" href="'.DOL_URL_ROOT.'/user/card.php?id='.$user->id.'" class="button-top-menu-dropdown" title="'.dol_escape_htmltag($langs->trans("YourUserFile").' ('.$stringforfirstkey.' u)').'"><i class="fa fa-user"></i>  '.$langs->trans("Card").'</a>';
-	$urltovirtualcard = '/user/virtualcard.php?id='.((int) $user->id);
-	$virtuelcardLink = dolButtonToOpenUrlInDialogPopup('publicvirtualcardmenu', $langs->transnoentitiesnoconv("PublicVirtualCardUrl").(is_object($user) ? ' - '.$user->getFullName($langs) : '').' ('.$stringforfirstkey.' v)', img_picto($langs->trans("PublicVirtualCardUrl").' ('.$stringforfirstkey.' v)', 'card', ''), $urltovirtualcard, '', 'button-top-menu-dropdown marginleftonly nohover', "closeTopMenuLoginDropdown()", '', 'v');
-	$logoutLink = '<a accesskey="l" href="'.$urllogout.'" class="button-top-menu-dropdown" title="'.dol_escape_htmltag($langs->trans("Logout").' ('.$stringforfirstkey.' l)').'"><i class="fa fa-sign-out-alt pictofixedwidth"></i><span class="hideonsmartphone">'.$langs->trans("Logout").'</span></a>';
+	$profilLink = '<a accesskey="u" href="' . DOL_URL_ROOT . '/user/card.php?id=' . $user->id . '" class="button-top-menu-dropdown" title="' . dol_escape_htmltag($langs->trans("YourUserFile") . ' (' . $stringforfirstkey . ' u)') . '"><i class="fa fa-user"></i>  ' . $langs->trans("Card") . '</a>';
+	$urltovirtualcard = '/user/virtualcard.php?id=' . ((int) $user->id);
+	$virtuelcardLink = dolButtonToOpenUrlInDialogPopup('publicvirtualcardmenu', $langs->transnoentitiesnoconv("PublicVirtualCardUrl") . (is_object($user) ? ' - ' . $user->getFullName($langs) : '') . ' (' . $stringforfirstkey . ' v)', img_picto($langs->trans("PublicVirtualCardUrl") . ' (' . $stringforfirstkey . ' v)', 'card', ''), $urltovirtualcard, '', 'button-top-menu-dropdown marginleftonly nohover', "closeTopMenuLoginDropdown()", '', 'v');
+	$logoutLink = '<a accesskey="l" href="' . $urllogout . '" class="button-top-menu-dropdown" title="' . dol_escape_htmltag($langs->trans("Logout") . ' (' . $stringforfirstkey . ' l)') . '"><i class="fa fa-sign-out-alt pictofixedwidth"></i><span class="hideonsmartphone">' . $langs->trans("Logout") . '</span></a>';
 
-	$profilName = $user->getFullName($langs).' ('.$user->login.')';
+	$profilName = $user->getFullName($langs) . ' (' . $user->login . ')';
 	if (!empty($user->admin)) {
-		$profilName = '<i class="far fa-star classfortooltip" title="'.$langs->trans("Administrator").'" ></i> '.$profilName;
+		$profilName = '<i class="far fa-star classfortooltip" title="' . $langs->trans("Administrator") . '" ></i> ' . $profilName;
 	}
 
 	// Define version to show
@@ -2742,38 +2753,38 @@
 	if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
 		$appli = getDolGlobalString('MAIN_APPLICATION_TITLE');
 		if (preg_match('/\d\.\d/', $appli)) {
-			if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
-				$appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
+			if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli)) {
+				$appli .= " (" . DOL_VERSION . ")"; // If new title contains a version that is different than core
 			}
 		} else {
-			$appli .= " ".DOL_VERSION;
+			$appli .= " " . DOL_VERSION;
 		}
 	} else {
-		$appli .= " ".DOL_VERSION;
+		$appli .= " " . DOL_VERSION;
 	}
 
 	if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
 		$btnUser = '<!-- div for user link -->
 	    <div id="topmenu-login-dropdown" class="userimg atoplogin dropdown user user-menu inline-block">
-	        <a href="'.DOL_URL_ROOT.'/user/card.php?id='.$user->id.'" class="dropdown-toggle login-dropdown-a valignmiddle" data-toggle="dropdown">
-	            '.$userImage.(empty($user->photo) ? '<!-- no photo so show also the login --><span class="hidden-xs maxwidth200 atoploginusername hideonsmartphone paddingleft valignmiddle small">'.dol_trunc($user->firstname ? $user->firstname : $user->login, 10).'</span>' : '').'
+	        <a href="' . DOL_URL_ROOT . '/user/card.php?id=' . $user->id . '" class="dropdown-toggle login-dropdown-a valignmiddle" data-toggle="dropdown">
+	            ' . $userImage . (empty($user->photo) ? '<!-- no photo so show also the login --><span class="hidden-xs maxwidth200 atoploginusername hideonsmartphone paddingleft valignmiddle small">' . dol_trunc($user->firstname ? $user->firstname : $user->login, 10) . '</span>' : '') . '
 	        </a>
 	        <div class="dropdown-menu">
 	            <!-- User image -->
 	            <div class="user-header">
-	                '.$userDropDownImage.'
+	                ' . $userDropDownImage . '
 	                <p>
-	                    '.$profilName.'<br>';
+	                    ' . $profilName . '<br>';
 		$title = '';
 		if ($user->datelastlogin) {
-			$title = $langs->trans("ConnectedSince").' : '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser');
+			$title = $langs->trans("ConnectedSince") . ' : ' . dol_print_date($user->datelastlogin, "dayhour", 'tzuser');
 			if ($user->datepreviouslogin) {
-				$title .= '<br>'.$langs->trans("PreviousConnexion").' : '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser');
+				$title .= '<br>' . $langs->trans("PreviousConnexion") . ' : ' . dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser');
 			}
 		}
-		$btnUser .= '<small class="classfortooltip" title="'.dol_escape_htmltag($title).'" ><i class="fa fa-user-clock"></i> '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser').'</small><br>';
+		$btnUser .= '<small class="classfortooltip" title="' . dol_escape_htmltag($title) . '" ><i class="fa fa-user-clock"></i> ' . dol_print_date($user->datelastlogin, "dayhour", 'tzuser') . '</small><br>';
 		if ($user->datepreviouslogin) {
-			$btnUser .= '<small class="classfortooltip" title="'.dol_escape_htmltag($title).'" ><i class="fa fa-user-clock opacitymedium"></i> '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser').'</small><br>';
+			$btnUser .= '<small class="classfortooltip" title="' . dol_escape_htmltag($title) . '" ><i class="fa fa-user-clock opacitymedium"></i> ' . dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser') . '</small><br>';
 		}
 
 		//$btnUser .= '<small class="classfortooltip"><i class="fa fa-cog"></i> '.$langs->trans("Version").' '.$appli.'</small>';
@@ -2782,18 +2793,18 @@
 	            </div>
 
 	            <!-- Menu Body user-->
-	            <div class="user-body">'.$dropdownBody.'</div>
+	            <div class="user-body">' . $dropdownBody . '</div>
 
 	            <!-- Menu Footer-->
 	            <div class="user-footer">
 	                <div class="pull-left">
-	                    '.$profilLink.'
+	                    ' . $profilLink . '
 	                </div>
 	                <div class="pull-left">
-	                    '.$virtuelcardLink.'
+	                    ' . $virtuelcardLink . '
 	                </div>
 	                <div class="pull-right">
-	                    '.$logoutLink.'
+	                    ' . $logoutLink . '
 	                </div>
 	                <div class="clearboth"></div>
 	            </div>
@@ -2803,8 +2814,8 @@
 	} else {
 		$btnUser = '<!-- div for user link text browser -->
 	    <div id="topmenu-login-dropdown" class="userimg atoplogin dropdown user user-menu inline-block">
-	    	<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$user->id.'" class="valignmiddle" alt="'.$langs->trans("MyUserCard").'">
-	    	'.$userImage.(empty($user->photo) ? '<span class="hidden-xs maxwidth200 atoploginusername hideonsmartphone paddingleft small valignmiddle">'.dol_trunc($user->firstname ? $user->firstname : $user->login, 10).'</span>' : '').'
+	    	<a href="' . DOL_URL_ROOT . '/user/card.php?id=' . $user->id . '" class="valignmiddle" alt="' . $langs->trans("MyUserCard") . '">
+	    	' . $userImage . (empty($user->photo) ? '<span class="hidden-xs maxwidth200 atoploginusername hideonsmartphone paddingleft small valignmiddle">' . dol_trunc($user->firstname ? $user->firstname : $user->login, 10) . '</span>' : '') . '
 	    	</a>
 		</div>';
 	}
@@ -2891,8 +2902,8 @@
 	if (!empty($conf->use_javascript_ajax)) {
 		$html .= '<!-- div for quick add link -->
     <div id="topmenu-quickadd-dropdown" class="atoplogin dropdown inline-block">
-        <a accesskey="a" class="dropdown-toggle login-dropdown-a nofocusvisible" data-toggle="dropdown" href="#" title="'.$langs->trans('QuickAdd').' ('.$stringforfirstkey.' a)"><i class="fa fa-plus-circle"></i></a>
-        <div class="dropdown-menu">'.printDropdownQuickadd().'</div>
+        <a accesskey="a" class="dropdown-toggle login-dropdown-a nofocusvisible" data-toggle="dropdown" href="#" title="' . $langs->trans('QuickAdd') . ' (' . $stringforfirstkey . ' a)"><i class="fa fa-plus-circle"></i></a>
+        <div class="dropdown-menu">' . printDropdownQuickadd() . '</div>
     </div>';
 		if (!defined('JS_JQUERY_DISABLE_DROPDOWN')) {    // This may be set by some pages that use different jquery version to avoid errors
 			$html .= '
@@ -2913,7 +2924,7 @@
 
             // Key map shortcut
             $(document).keydown(function(event){
-				var ostype = \''.dol_escape_js($conf->browser->os).'\';
+				var ostype = \'' . dol_escape_js($conf->browser->os) . '\';
 				if (ostype === "macintosh") {
 					if ( event.which === 65 && event.ctrlKey ) {
 						console.log(\'control + a : trigger open quick add dropdown\');
@@ -2976,14 +2987,14 @@
 
 
 	if (!empty($conf->use_javascript_ajax)) {
-		$urlforuploadpage = DOL_URL_ROOT.'/core/upload_page.php';
+		$urlforuploadpage = DOL_URL_ROOT . '/core/upload_page.php';
 		if (!is_numeric(getDolGlobalString('MAIN_USE_TOP_MENU_IMPORT_FILE'))) {
 			$urlforuploadpage = getDolGlobalString('MAIN_USE_TOP_MENU_IMPORT_FILE');
 		}
 
 		$html .= '<!-- div for link to upload file -->
     <div id="topmenu-uploadfile-dropdown" class="atoplogin dropdown inline-block">
-        <a accesskey="i" class="dropdown-togglex login-dropdown-a nofocusvisible" data-toggle="dropdown" href="'.$urlforuploadpage.'" title="'.$langs->trans('UploadFile').' ('.$stringforfirstkey.' i)"><i class="fa fa-upload"></i></a>
+        <a accesskey="i" class="dropdown-togglex login-dropdown-a nofocusvisible" data-toggle="dropdown" href="' . $urlforuploadpage . '" title="' . $langs->trans('UploadFile') . ' (' . $stringforfirstkey . ' i)"><i class="fa fa-upload"></i></a>
     </div>';
 	}
 
@@ -3162,8 +3173,8 @@
 		$langs->load(explode('@', $item['title'])[1]);
 		$langs->load(explode('@', $item['name'])[1]);
 		$dropDownQuickAddHtml .= '
-			<a class="dropdown-item quickadd-item" href="'.DOL_URL_ROOT.$item['url'].'" title="'.$langs->trans(explode('@', $item['title'])[0]).'">
-			'. img_picto('', $item['picto'], 'style="width:18px;"') . ' ' . $langs->trans(explode('@', $item['name'])[0]) . '</a>
+			<a class="dropdown-item quickadd-item" href="' . DOL_URL_ROOT . $item['url'] . '" title="' . $langs->trans(explode('@', $item['title'])[0]) . '">
+			' . img_picto('', $item['picto'], 'style="width:18px;"') . ' ' . $langs->trans(explode('@', $item['name'])[0]) . '</a>
 		';
 	}
 
@@ -3212,7 +3223,7 @@
 	}
 
 	if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) {	    // This may be set by some pages that use different jquery version to avoid errors
-		include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php';
+		include_once DOL_DOCUMENT_ROOT . '/bookmarks/bookmarks.lib.php';
 		$langs->load("bookmarks");
 
 		if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
@@ -3222,9 +3233,9 @@
 		} else {
 			$html .= '<!-- div for bookmark link -->
 	        <div id="topmenu-bookmark-dropdown" class="dropdown inline-block">
-	            <a accesskey="b" class="dropdown-toggle login-dropdown-a nofocusvisible" data-toggle="dropdown" href="#" title="'.$langs->trans('Bookmarks').' ('.$stringforfirstkey.' b)"><i class="fa fa-star"></i></a>
+	            <a accesskey="b" class="dropdown-toggle login-dropdown-a nofocusvisible" data-toggle="dropdown" href="#" title="' . $langs->trans('Bookmarks') . ' (' . $stringforfirstkey . ' b)"><i class="fa fa-star"></i></a>
 	            <div class="dropdown-menu">
-	                '.printDropdownBookmarksList().'
+	                ' . printDropdownBookmarksList() . '
 	            </div>
 	        </div>';
 
@@ -3247,7 +3258,7 @@
 
 	            // Key map shortcut
 	            jQuery(document).keydown(function(event) {
-					var ostype = \''.dol_escape_js($conf->browser->os).'\';
+					var ostype = \'' . dol_escape_js($conf->browser->os) . '\';
 					if (ostype === "macintosh") {
 						if ( event.which === 66 && event.ctrlKey ) {
 							console.log("Click on control + b : trigger open bookmark dropdown");
@@ -3288,7 +3299,7 @@
 
 	$usedbyinclude = 1;
 	$arrayresult = array();
-	include DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php'; // This sets $arrayresult
+	include DOL_DOCUMENT_ROOT . '/core/ajax/selectsearchbox.php'; // This sets $arrayresult
 
 	// accesskey is for Windows or Linux:  ALT + key for chrome, ALT + SHIFT + KEY for firefox
 	// accesskey is for Mac:               CTRL + key for all browsers
@@ -3301,7 +3312,7 @@
 		$stringforfirstkey .= ' CTL +';
 	}
 
-	$searchInput = '<input type="search" name="search_all"'.($stringforfirstkey ? ' title="'.dol_escape_htmltag($stringforfirstkey.' s').'"' : '').' id="top-global-search-input" class="dropdown-search-input search_component_input" placeholder="'.$langs->trans('Search').'" autocomplete="off">';
+	$searchInput = '<input type="search" name="search_all"' . ($stringforfirstkey ? ' title="' . dol_escape_htmltag($stringforfirstkey . ' s') . '"' : '') . ' id="top-global-search-input" class="dropdown-search-input search_component_input" placeholder="' . $langs->trans('Search') . '" autocomplete="off">';
 
 	$defaultAction = '';
 	$buttonList = '<div class="dropdown-global-search-button-list" >';
@@ -3311,25 +3322,25 @@
 		if (empty($defaultAction)) {
 			$defaultAction = $item['url'];
 		}
-		$buttonList .= '<button class="dropdown-item global-search-item tdoverflowmax300" data-target="'.dol_escape_htmltag($item['url']).'" >';
+		$buttonList .= '<button class="dropdown-item global-search-item tdoverflowmax300" data-target="' . dol_escape_htmltag($item['url']) . '" >';
 		$buttonList .= $item['text'];
 		$buttonList .= '</button>';
 	}
 	$buttonList .= '</div>';
 
-	$dropDownHtml = '<form role="search" id="top-menu-action-search" name="actionsearch" method="GET" action="'.$defaultAction.'">';
+	$dropDownHtml = '<form role="search" id="top-menu-action-search" name="actionsearch" method="GET" action="' . $defaultAction . '">';
 
 	$dropDownHtml .= '
         <!-- search input -->
         <div class="dropdown-header search-dropdown-header">
-            ' . $searchInput.'
+            ' . $searchInput . '
         </div>
     ';
 
 	$dropDownHtml .= '
         <!-- Menu Body search -->
         <div class="dropdown-body search-dropdown-body">
-        '.$buttonList.'
+        ' . $buttonList . '
         </div>
         ';
 
@@ -3348,11 +3359,11 @@
 
 	$html .= '<!-- div for Global Search -->
     <div id="topmenu-global-search-dropdown" class="atoplogin dropdown inline-block">
-        <a accesskey="s" class="dropdown-toggle login-dropdown-a nofocusvisible" data-toggle="dropdown" href="#" title="'.$langs->trans('Search').' ('.$stringforfirstkey.' s)">
+        <a accesskey="s" class="dropdown-toggle login-dropdown-a nofocusvisible" data-toggle="dropdown" href="#" title="' . $langs->trans('Search') . ' (' . $stringforfirstkey . ' s)">
             <i class="fa fa-search" aria-hidden="true" ></i>
         </a>
         <div class="dropdown-menu dropdown-search">
-            '.$dropDownHtml.'
+            ' . $dropDownHtml . '
         </div>
     </div>';
 
@@ -3472,7 +3483,7 @@
 		// Instantiate hooks for external modules
 		$hookmanager->initHooks(array('leftblock'));
 
-		print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
+		print "\n" . '<!-- Begin side-nav id-left -->' . "\n" . '<div class="side-nav"><div id="id-left">' . "\n";
 		print "\n";
 
 		if (!is_object($form)) {
@@ -3487,7 +3498,7 @@
 
 			$usedbyinclude = 1;
 			$arrayresult = array();
-			include DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php'; // This make initHooks('searchform') then set $arrayresult
+			include DOL_DOCUMENT_ROOT . '/core/ajax/selectsearchbox.php'; // This make initHooks('searchform') then set $arrayresult
 
 			if ($conf->use_javascript_ajax && !getDolGlobalString('MAIN_USE_OLD_SEARCH_FORM')) {
 				// accesskey is for Windows or Linux:  ALT + key for chrome, ALT + SHIFT + KEY for firefox
@@ -3502,13 +3513,13 @@
 				}
 
 				//$textsearch = $langs->trans("Search");
-				$textsearch = '<span class="fa fa-search paddingright pictofixedwidth"></span>'.$langs->trans("Search");
-				$searchform .= $form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, 'accesskey="s"', 1, 0, (getDolGlobalString('MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY') ? 0 : 1), 'vmenusearchselectcombo', 1, $textsearch, 1, $stringforfirstkey.' s');
+				$textsearch = '<span class="fa fa-search paddingright pictofixedwidth"></span>' . $langs->trans("Search");
+				$searchform .= $form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, 'accesskey="s"', 1, 0, (getDolGlobalString('MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY') ? 0 : 1), 'vmenusearchselectcombo', 1, $textsearch, 1, $stringforfirstkey . ' s');
 			} else {
 				if (is_array($arrayresult)) {
 					// @phan-suppress-next-line PhanEmptyForeach // array is really empty in else case.
 					foreach ($arrayresult as $key => $val) {
-						$searchform .= printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'search_all', (empty($val['shortcut']) ? '' : $val['shortcut']), 'searchleft'.$key, $val['img']);
+						$searchform .= printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'search_all', (empty($val['shortcut']) ? '' : $val['shortcut']), 'searchleft' . $key, $val['img']);
 					}
 				}
 			}
@@ -3524,10 +3535,10 @@
 
 			// Force special value for $searchform for text browsers or very old search form
 			if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') || empty($conf->use_javascript_ajax)) {
-				$urltosearch = DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
-				$searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" accesskey="s" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div></div>';
+				$urltosearch = DOL_URL_ROOT . '/core/search_page.php?showtitlebefore=1';
+				$searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="' . $urltosearch . '" accesskey="s" alt="' . dol_escape_htmltag($langs->trans("ShowSearchFields")) . '">' . $langs->trans("Search") . '...</a></div></div>';
 			} elseif ($conf->use_javascript_ajax && getDolGlobalString('MAIN_USE_OLD_SEARCH_FORM')) {
-				$searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
+				$searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="' . dol_escape_htmltag($langs->trans("ShowSearchFields")) . '">' . $langs->trans("Search") . '...</a></div><div id="divsearchforms2" style="display: none">' . $searchform . '</div>';
 				$searchform .= '<script>
             	jQuery(document).ready(function () {
             		jQuery("#divsearchforms1").click(function(){
@@ -3558,9 +3569,9 @@
 		}
 
 		// Left column
-		print '<!-- Begin left menu -->'."\n";
+		print '<!-- Begin left menu -->' . "\n";
 
-		print '<div class="vmenu"'.(getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') ? ' alt="Left menu"' : '').'>'."\n\n";
+		print '<div class="vmenu"' . (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') ? ' alt="Left menu"' : '') . '>' . "\n\n";
 
 		// Show left menu with other forms
 		// @phan-suppress-next-line PhanRedefinedClassReference
@@ -3578,7 +3589,7 @@
 		// Dolibarr version + help + bug report link
 		print "\n";
 		print "<!-- Begin Help Block-->\n";
-		print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
+		print '<div id="blockvmenuhelp" class="blockvmenuhelp">' . "\n";
 
 		// Version
 		if (getDolGlobalString('MAIN_SHOW_VERSION')) {    // Version is already on help picto and on login page.
@@ -3605,18 +3616,18 @@
 				$appli = getDolGlobalString('MAIN_APPLICATION_TITLE');
 				$doliurl = '';
 				if (preg_match('/\d\.\d/', $appli)) {
-					if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
-						$appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
+					if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli)) {
+						$appli .= " (" . DOL_VERSION . ")"; // If new title contains a version that is different than core
 					}
 				} else {
-					$appli .= " ".DOL_VERSION;
+					$appli .= " " . DOL_VERSION;
 				}
 			} else {
-				$appli .= " ".DOL_VERSION;
+				$appli .= " " . DOL_VERSION;
 			}
 			print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
 			if ($doliurl) {
-				print '<a class="help" target="_blank" rel="noopener noreferrer" href="'.$doliurl.'">';
+				print '<a class="help" target="_blank" rel="noopener noreferrer" href="' . $doliurl . '">';
 			} else {
 				print '<span class="help">';
 			}
@@ -3626,12 +3637,12 @@
 			} else {
 				print '</span>';
 			}
-			print '</div>'."\n";
+			print '</div>' . "\n";
 		}
 
 		// Link to bugtrack
 		if (getDolGlobalString('MAIN_BUGTRACK_ENABLELINK')) {
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+			require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
 
 			if (getDolGlobalString('MAIN_BUGTRACK_ENABLELINK') == 'github') {
 				$bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new?labels=Bug';
@@ -3649,12 +3660,12 @@
 				$bugbaseurl .= urlencode("[*Short description*]\n");
 				$bugbaseurl .= urlencode("\n");
 				$bugbaseurl .= urlencode("## Environment\n");
-				$bugbaseurl .= urlencode("- **Version**: ".DOL_VERSION."\n");
-				$bugbaseurl .= urlencode("- **OS**: ".php_uname('s')."\n");
-				$bugbaseurl .= urlencode("- **Web server**: ".$_SERVER["SERVER_SOFTWARE"]."\n");
-				$bugbaseurl .= urlencode("- **PHP**: ".php_sapi_name().' '.phpversion()."\n");
-				$bugbaseurl .= urlencode("- **Database**: ".$db::LABEL.' '.$db->getVersion()."\n");
-				$bugbaseurl .= urlencode("- **URL(s)**: ".$_SERVER["REQUEST_URI"]."\n");
+				$bugbaseurl .= urlencode("- **Version**: " . DOL_VERSION . "\n");
+				$bugbaseurl .= urlencode("- **OS**: " . php_uname('s') . "\n");
+				$bugbaseurl .= urlencode("- **Web server**: " . $_SERVER["SERVER_SOFTWARE"] . "\n");
+				$bugbaseurl .= urlencode("- **PHP**: " . php_sapi_name() . ' ' . phpversion() . "\n");
+				$bugbaseurl .= urlencode("- **Database**: " . $db::LABEL . ' ' . $db->getVersion() . "\n");
+				$bugbaseurl .= urlencode("- **URL(s)**: " . $_SERVER["REQUEST_URI"] . "\n");
 				$bugbaseurl .= urlencode("\n");
 				$bugbaseurl .= urlencode("## Expected and actual behavior\n");
 				$bugbaseurl .= urlencode("[*Verbose description*]\n");
@@ -3684,7 +3695,7 @@
 			}
 
 			print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
-			print '<a class="help" target="_blank" rel="noopener noreferrer" href="'.$bugbaseurl.'"><i class="fas fa-bug"></i> '.$langs->trans("FindBug").'</a>';
+			print '<a class="help" target="_blank" rel="noopener noreferrer" href="' . $bugbaseurl . '"><i class="fas fa-bug"></i> ' . $langs->trans("FindBug") . '</a>';
 			print '</div>';
 		}
 
@@ -3705,7 +3716,7 @@
 	}
 
 	print "\n";
-	print '<!-- Begin right area -->'."\n";
+	print '<!-- Begin right area -->' . "\n";
 
 	if (empty($leftmenuwithoutmainarea)) {
 		main_area($title);
@@ -3729,7 +3740,7 @@
 
 	print "\n";
 
-	print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
+	print '<!-- Begin div class="fiche" -->' . "\n" . '<div class="fiche">' . "\n";
 
 	$hookmanager->initHooks(array('main'));
 	$parameters = array();
@@ -3745,30 +3756,30 @@
 		$parameters = array();
 		$reshook = $hookmanager->executeHooks('showSocinfoOnPrint', $parameters);
 		if (empty($reshook)) {
-			print '<!-- Begin show mysoc info header -->'."\n";
-			print '<div id="mysoc-info-header">'."\n";
-			print '<table class="centpercent div-table-responsive">'."\n";
+			print '<!-- Begin show mysoc info header -->' . "\n";
+			print '<div id="mysoc-info-header">' . "\n";
+			print '<table class="centpercent div-table-responsive">' . "\n";
 			print '<tbody>';
 			print '<tr><td rowspan="0" class="width20p">';
 			if (getDolGlobalString('MAIN_SHOW_LOGO') && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && getDolGlobalString('MAIN_INFO_SOCIETE_LOGO')) {
-				print '<img id="mysoc-info-header-logo" style="max-width:100%" alt="" src="'.DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/'.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_LOGO'))).'">';
+				print '<img id="mysoc-info-header-logo" style="max-width:100%" alt="" src="' . DOL_URL_ROOT . '/viewimage.php?cache=1&modulepart=mycompany&file=' . urlencode('logos/' . dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_LOGO'))) . '">';
 			}
-			print '</td><td  rowspan="0" class="width50p"></td></tr>'."\n";
-			print '<tr><td class="titre bold">'.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_NOM')).'</td></tr>'."\n";
-			print '<tr><td>'.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS')).'<br>'.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_ZIP')).' '.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_TOWN')).'</td></tr>'."\n";
+			print '</td><td  rowspan="0" class="width50p"></td></tr>' . "\n";
+			print '<tr><td class="titre bold">' . dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_NOM')) . '</td></tr>' . "\n";
+			print '<tr><td>' . dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS')) . '<br>' . dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_ZIP')) . ' ' . dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_TOWN')) . '</td></tr>' . "\n";
 			if (getDolGlobalString('MAIN_INFO_SOCIETE_TEL')) {
-				print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Phone").' : '.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_TEL')).'</td></tr>';
+				print '<tr><td style="padding-left: 1em" class="small">' . $langs->trans("Phone") . ' : ' . dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_TEL')) . '</td></tr>';
 			}
 			if (getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) {
-				print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Email").' : '.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')).'</td></tr>';
+				print '<tr><td style="padding-left: 1em" class="small">' . $langs->trans("Email") . ' : ' . dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) . '</td></tr>';
 			}
 			if (getDolGlobalString('MAIN_INFO_SOCIETE_WEB')) {
-				print '<tr><td style="padding-left: 1em" class="small">'.$langs->trans("Web").' : '.dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_WEB')).'</td></tr>';
+				print '<tr><td style="padding-left: 1em" class="small">' . $langs->trans("Web") . ' : ' . dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_WEB')) . '</td></tr>';
 			}
 			print '</tbody>';
-			print '</table>'."\n";
-			print '</div>'."\n";
-			print '<!-- End show mysoc info header -->'."\n";
+			print '</table>' . "\n";
+			print '</div>' . "\n";
+			print '<!-- End show mysoc info header -->' . "\n";
 		}
 	}
 }
@@ -3846,20 +3857,20 @@
 	global $langs, $user;
 
 	$ret = '';
-	$ret .= '<form action="'.$urlaction.'" method="post" class="searchform nowraponall tagtr">';
-	$ret .= '<input type="hidden" name="token" value="'.newToken().'">';
-	$ret .= '<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
+	$ret .= '<form action="' . $urlaction . '" method="post" class="searchform nowraponall tagtr">';
+	$ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
+	$ret .= '<input type="hidden" name="savelogin" value="' . dol_escape_htmltag($user->login) . '">';
 	if ($showtitlebefore) {
-		$ret .= '<div class="tagtd left">'.$title.'</div> ';
+		$ret .= '<div class="tagtd left">' . $title . '</div> ';
 	}
 	$ret .= '<div class="tagtd">';
 	$ret .= img_picto('', $img, '', 0, 0, 0, '', 'paddingright width20');
-	$ret .= '<input type="text" class="flat '.$htmlmorecss.'"';
+	$ret .= '<input type="text" class="flat ' . $htmlmorecss . '"';
 	$ret .= ' style="background-repeat: no-repeat; background-position: 3px;"';
-	$ret .= ($accesskey ? ' accesskey="'.$accesskey.'"' : '');
-	$ret .= ' placeholder="'.strip_tags($title).'"';
+	$ret .= ($accesskey ? ' accesskey="' . $accesskey . '"' : '');
+	$ret .= ' placeholder="' . strip_tags($title) . '"';
 	$ret .= ($autofocus ? ' autofocus' : '');
-	$ret .= ' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
+	$ret .= ' name="' . $htmlinputname . '" id="' . $prefhtmlinputname . $htmlinputname . '" />';
 	$ret .= '<button type="submit" class="button bordertransp" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
 	$ret .= '<span class="fa fa-search"></span>';
 	$ret .= '</button>';
@@ -3888,7 +3899,7 @@
 		global $contextpage, $page, $limit, $mode;
 		global $dolibarr_distrib;
 
-		$ext = 'layout='.urlencode($conf->browser->layout).'&version='.urlencode(DOL_VERSION);
+		$ext = 'layout=' . urlencode($conf->browser->layout) . '&version=' . urlencode(DOL_VERSION);
 
 		// Hook to add more things on all pages within fiche DIV
 		$llxfooter = '';
@@ -3911,7 +3922,7 @@
 		if (is_object($user) && !empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp)) {
 			// Clean and save data
 			foreach ($user->lastsearch_values_tmp as $key => $val) {
-				unset($_SESSION['lastsearch_values_tmp_'.$key]); // Clean array to rebuild it just after
+				unset($_SESSION['lastsearch_values_tmp_' . $key]); // Clean array to rebuild it just after
 				if (count($val) && empty($_POST['button_removefilter']) && empty($_POST['button_removefilter_x'])) {
 					if (empty($val['sortfield'])) {
 						unset($val['sortfield']);
@@ -3919,9 +3930,9 @@
 					if (empty($val['sortorder'])) {
 						unset($val['sortorder']);
 					}
-					dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criteria)");
-					$_SESSION['lastsearch_values_tmp_'.$key] = json_encode($val);
-					unset($_SESSION['lastsearch_values_'.$key]);
+					dol_syslog('Save lastsearch_values_tmp_' . $key . '=' . json_encode($val, 0) . " (systematic recording of last search criteria)");
+					$_SESSION['lastsearch_values_tmp_' . $key] = json_encode($val);
+					unset($_SESSION['lastsearch_values_' . $key]);
 				}
 			}
 		}
@@ -3930,45 +3941,45 @@
 		$relativepathstring = $_SERVER["PHP_SELF"];
 		// Clean $relativepathstring
 		if (constant('DOL_URL_ROOT')) {
-			$relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
+			$relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_URL_ROOT'), '/') . '/', '', $relativepathstring);
 		}
 		$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
 		$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
 		if (preg_match('/list\.php$/', $relativepathstring)) {
-			unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
-			unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
-			unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
-			unset($_SESSION['lastsearch_mode_tmp_'.$relativepathstring]);
+			unset($_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring]);
+			unset($_SESSION['lastsearch_page_tmp_' . $relativepathstring]);
+			unset($_SESSION['lastsearch_limit_tmp_' . $relativepathstring]);
+			unset($_SESSION['lastsearch_mode_tmp_' . $relativepathstring]);
 
 			if (!empty($contextpage)) {
-				$_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring] = $contextpage;
+				$_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring] = $contextpage;
 			}
 			if (!empty($page) && $page > 0) {
-				$_SESSION['lastsearch_page_tmp_'.$relativepathstring] = $page;
+				$_SESSION['lastsearch_page_tmp_' . $relativepathstring] = $page;
 			}
 			if (!empty($limit) && $limit != $conf->liste_limit) {
-				$_SESSION['lastsearch_limit_tmp_'.$relativepathstring] = $limit;
+				$_SESSION['lastsearch_limit_tmp_' . $relativepathstring] = $limit;
 			}
 			if (!empty($mode)) {
-				$_SESSION['lastsearch_mode_tmp_'.$relativepathstring] = $mode;
+				$_SESSION['lastsearch_mode_tmp_' . $relativepathstring] = $mode;
 			}
 
-			unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
-			unset($_SESSION['lastsearch_page_'.$relativepathstring]);
-			unset($_SESSION['lastsearch_limit_'.$relativepathstring]);
-			unset($_SESSION['lastsearch_mode_'.$relativepathstring]);
+			unset($_SESSION['lastsearch_contextpage_' . $relativepathstring]);
+			unset($_SESSION['lastsearch_page_' . $relativepathstring]);
+			unset($_SESSION['lastsearch_limit_' . $relativepathstring]);
+			unset($_SESSION['lastsearch_mode_' . $relativepathstring]);
 		}
 
 		// Core error message
 		if (getDolGlobalString('MAIN_CORE_ERROR')) {
 			// Ajax version
 			if ($conf->use_javascript_ajax) {
-				$title = img_warning().' '.$langs->trans('CoreErrorTitle');
+				$title = img_warning() . ' ' . $langs->trans('CoreErrorTitle');
 				print ajax_dialog($title, $langs->trans('CoreErrorMessage'));
 			} else {
 				// html version
-				$msg = img_warning().' '.$langs->trans('CoreErrorMessage');
-				print '<div class="error">'.$msg.'</div>';
+				$msg = img_warning() . ' ' . $langs->trans('CoreErrorMessage');
+				print '<div class="error">' . $msg . '</div>';
 			}
 
 			//define("MAIN_CORE_ERROR",0);      // Constant was defined and we can't change value of a constant
@@ -3976,19 +3987,19 @@
 
 		print "\n\n";
 
-		print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
+		print '</div> <!-- End div class="fiche" -->' . "\n"; // End div fiche
 
 		if (empty($conf->dol_hide_leftmenu) && !GETPOST('dol_openinpopup', 'aZ09')) {
-			print '</div> <!-- End div id-right -->'."\n"; // End div id-right
+			print '</div> <!-- End div id-right -->' . "\n"; // End div id-right
 		}
 
 		if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) {
-			print '</div> <!-- End div id-container -->'."\n"; // End div container
+			print '</div> <!-- End div id-container -->' . "\n"; // End div container
 		}
 
 		print "\n";
 		if ($comment) {
-			print '<!-- '.$comment.' -->'."\n";
+			print '<!-- ' . $comment . ' -->' . "\n";
 		}
 
 		printCommonFooter($zone);
@@ -3998,40 +4009,36 @@
 		}
 
 		if (!empty($conf->use_javascript_ajax)) {
-			print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
-			print '<script src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n";
+			print "\n" . '<!-- Includes JS Footer of Dolibarr -->' . "\n";
+			print '<script src="' . DOL_URL_ROOT . '/core/js/lib_foot.js.php?lang=' . $langs->defaultlang . ($ext ? '&' . $ext : '') . '"></script>' . "\n";
 		}
 
 		// JS wrapper to add log when clicking on download or preview
 		if (isModEnabled('blockedlog') && is_object($object) && !empty($object->id) && $object->id > 0) {
 			if (in_array($object->element, array('facture')) && $object->statut > 0) {       // Restrict for the moment to element 'facture'
 				print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
-				?>
+?>
 				<script>
-				jQuery(document).ready(function () {
-					$('a.documentpreview').click(function() {
-						console.log("Call /blockedlog/ajax/block-add on a.documentpreview");
-						$.post('<?php echo DOL_URL_ROOT."/blockedlog/ajax/block-add.php" ?>'
-								, {
-									id:<?php echo $object->id; ?>
-									, element:'<?php echo dol_escape_js($object->element) ?>'
-									, action:'DOC_PREVIEW'
-									, token: '<?php echo currentToken(); ?>'
-								}
-						);
-					});
-					$('a.documentdownload').click(function() {
-						console.log("Call /blockedlog/ajax/block-add a.documentdownload");
-						$.post('<?php echo DOL_URL_ROOT."/blockedlog/ajax/block-add.php" ?>'
-								, {
-									id:<?php echo $object->id; ?>
-									, element:'<?php echo dol_escape_js($object->element) ?>'
-									, action:'DOC_DOWNLOAD'
-									, token: '<?php echo currentToken(); ?>'
-								}
-						);
+					jQuery(document).ready(function() {
+						$('a.documentpreview').click(function() {
+							console.log("Call /blockedlog/ajax/block-add on a.documentpreview");
+							$.post('<?php echo DOL_URL_ROOT . "/blockedlog/ajax/block-add.php" ?>', {
+								id: <?php echo $object->id; ?>,
+								element: '<?php echo dol_escape_js($object->element) ?>',
+								action: 'DOC_PREVIEW',
+								token: '<?php echo currentToken(); ?>'
+							});
+						});
+						$('a.documentdownload').click(function() {
+							console.log("Call /blockedlog/ajax/block-add a.documentdownload");
+							$.post('<?php echo DOL_URL_ROOT . "/blockedlog/ajax/block-add.php" ?>', {
+								id: <?php echo $object->id; ?>,
+								element: '<?php echo dol_escape_js($object->element) ?>',
+								action: 'DOC_DOWNLOAD',
+								token: '<?php echo currentToken(); ?>'
+							});
+						});
 					});
-				});
 				</script>
 				<?php
 			}
@@ -4039,30 +4046,32 @@
 
 		// A div for the #dialogforpopup popup
 		print "\n<!-- A div to allow dialog popup by jQuery('#dialogforpopup').dialog() -->\n";
-		print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
+		print '<div id="dialogforpopup" style="display: none;"></div>' . "\n";
 
 		// Add code for the asynchronous anonymous first ping (for telemetry)
 		// You can use &forceping=1 in parameters to force the ping if the ping was already sent.
 		$forceping = GETPOST('forceping', 'alpha');
-		if (($_SERVER["PHP_SELF"] == DOL_URL_ROOT.'/index.php') || $forceping) {
+		if (($_SERVER["PHP_SELF"] == DOL_URL_ROOT . '/index.php') || $forceping) {
 			//print '<!-- instance_unique_id='.$conf->file->instance_unique_id.' MAIN_FIRST_PING_OK_ID='.$conf->global->MAIN_FIRST_PING_OK_ID.' -->';
-			$hash_unique_id = dol_hash('dolibarr'.$conf->file->instance_unique_id, 'sha256');	// Note: if the global salt changes, this hash changes too so ping may be counted twice. We don't mind. It is for statistics purpose only.
+			$hash_unique_id = dol_hash('dolibarr' . $conf->file->instance_unique_id, 'sha256');	// Note: if the global salt changes, this hash changes too so ping may be counted twice. We don't mind. It is for statistics purpose only.
 
-			if (!getDolGlobalString('MAIN_FIRST_PING_OK_DATE')
+			if (
+				!getDolGlobalString('MAIN_FIRST_PING_OK_DATE')
 				|| (!empty($conf->file->instance_unique_id) && ($hash_unique_id != $conf->global->MAIN_FIRST_PING_OK_ID) && (getDolGlobalString('MAIN_FIRST_PING_OK_ID') != 'disabled'))
-			|| $forceping) {
+				|| $forceping
+			) {
 				// No ping done if we are into an alpha version
 				if (strpos('alpha', DOL_VERSION) > 0 && !$forceping) {
 					print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. It is an alpha version -->\n";
-				} elseif (empty($_COOKIE['DOLINSTALLNOPING_'.$hash_unique_id]) || $forceping) {	// Cookie is set when we uncheck the checkbox in the installation wizard.
+				} elseif (empty($_COOKIE['DOLINSTALLNOPING_' . $hash_unique_id]) || $forceping) {	// Cookie is set when we uncheck the checkbox in the installation wizard.
 					// MAIN_LAST_PING_KO_DATE
 					// Disable ping if MAIN_LAST_PING_KO_DATE is set and is recent (this month)
 					if (getDolGlobalString('MAIN_LAST_PING_KO_DATE') && substr($conf->global->MAIN_LAST_PING_KO_DATE, 0, 6) == dol_print_date(dol_now(), '%Y%m') && !$forceping) {
 						print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. An error already occurred this month, we will try later. -->\n";
 					} else {
-						include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+						include_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
 
-						print "\n".'<!-- Includes JS for Ping of Dolibarr forceping='.$forceping.' MAIN_FIRST_PING_OK_DATE='.getDolGlobalString("MAIN_FIRST_PING_OK_DATE").' MAIN_FIRST_PING_OK_ID='.getDolGlobalString("MAIN_FIRST_PING_OK_ID").' MAIN_LAST_PING_KO_DATE='.getDolGlobalString("MAIN_LAST_PING_KO_DATE").' -->'."\n";
+						print "\n" . '<!-- Includes JS for Ping of Dolibarr forceping=' . $forceping . ' MAIN_FIRST_PING_OK_DATE=' . getDolGlobalString("MAIN_FIRST_PING_OK_DATE") . ' MAIN_FIRST_PING_OK_ID=' . getDolGlobalString("MAIN_FIRST_PING_OK_ID") . ' MAIN_LAST_PING_KO_DATE=' . getDolGlobalString("MAIN_LAST_PING_KO_DATE") . ' -->' . "\n";
 						print "\n<!-- JS CODE TO ENABLE the anonymous Ping -->\n";
 						$url_for_ping = getDolGlobalString('MAIN_URL_FOR_PING', "https://ping.dolibarr.org/");
 						// Try to guess the distrib used
@@ -4073,58 +4082,69 @@
 						if (!empty($dolibarr_distrib)) {
 							$distrib = $dolibarr_distrib;
 						}
-						?>
-							<script>
-							jQuery(document).ready(function (tmp) {
+				?>
+						<script>
+							jQuery(document).ready(function(tmp) {
 								console.log("Try Ping with hash_unique_id is dol_hash('dolibarr'+instance_unique_id, 'sha256')");
 								$.ajax({
-									  method: "POST",
-									  url: "<?php echo $url_for_ping ?>",
-									  timeout: 500,     // timeout milliseconds
-									  cache: false,
-									  data: {
-										  hash_algo: 'dol_hash-sha256',
-										  hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>',
-										  action: 'dolibarrping',
-										  version: '<?php echo (float) DOL_VERSION; ?>',
-										  entity: '<?php echo (int) $conf->entity; ?>',
-										  dbtype: '<?php echo dol_escape_js($db->type); ?>',
-										  country_code: '<?php echo $mysoc->country_code ? dol_escape_js($mysoc->country_code) : 'unknown'; ?>',
-										  php_version: '<?php echo dol_escape_js(phpversion()); ?>',
-										  os_version: '<?php echo dol_escape_js(version_os('smr')); ?>',
-										  db_version: '<?php echo dol_escape_js(version_db()); ?>',
-										  distrib: '<?php echo $distrib ? dol_escape_js($distrib) : 'unknown'; ?>',
-										  token: 'notrequired'
-									  },
-									  success: function (data, status, xhr) {   // success callback function (data contains body of response)
-											console.log("Ping ok");
-											$.ajax({
-												method: 'GET',
-												url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>',
-												timeout: 500,     // timeout milliseconds
-												cache: false,
-												data: { hash_algo: 'dol_hash-sha256', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: 'firstpingok', token: '<?php echo currentToken(); ?>' },	// for update
-											  });
-									  },
-									  error: function (data,status,xhr) {   // error callback function
-											console.log("Ping ko: " + data);
-											$.ajax({
-												  method: 'GET',
-												  url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>',
-												  timeout: 500,     // timeout milliseconds
-												  cache: false,
-												  data: { hash_algo: 'dol_hash-sha256', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: 'firstpingko', token: '<?php echo currentToken(); ?>' },
-												});
-									  }
+									method: "POST",
+									url: "<?php echo $url_for_ping ?>",
+									timeout: 500, // timeout milliseconds
+									cache: false,
+									data: {
+										hash_algo: 'dol_hash-sha256',
+										hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>',
+										action: 'dolibarrping',
+										version: '<?php echo (float) DOL_VERSION; ?>',
+										entity: '<?php echo (int) $conf->entity; ?>',
+										dbtype: '<?php echo dol_escape_js($db->type); ?>',
+										country_code: '<?php echo $mysoc->country_code ? dol_escape_js($mysoc->country_code) : 'unknown'; ?>',
+										php_version: '<?php echo dol_escape_js(phpversion()); ?>',
+										os_version: '<?php echo dol_escape_js(version_os('smr')); ?>',
+										db_version: '<?php echo dol_escape_js(version_db()); ?>',
+										distrib: '<?php echo $distrib ? dol_escape_js($distrib) : 'unknown'; ?>',
+										token: 'notrequired'
+									},
+									success: function(data, status,
+										xhr) { // success callback function (data contains body of response)
+										console.log("Ping ok");
+										$.ajax({
+											method: 'GET',
+											url: '<?php echo DOL_URL_ROOT . '/core/ajax/pingresult.php'; ?>',
+											timeout: 500, // timeout milliseconds
+											cache: false,
+											data: {
+												hash_algo: 'dol_hash-sha256',
+												hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>',
+												action: 'firstpingok',
+												token: '<?php echo currentToken(); ?>'
+											}, // for update
+										});
+									},
+									error: function(data, status, xhr) { // error callback function
+										console.log("Ping ko: " + data);
+										$.ajax({
+											method: 'GET',
+											url: '<?php echo DOL_URL_ROOT . '/core/ajax/pingresult.php'; ?>',
+											timeout: 500, // timeout milliseconds
+											cache: false,
+											data: {
+												hash_algo: 'dol_hash-sha256',
+												hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>',
+												action: 'firstpingko',
+												token: '<?php echo currentToken(); ?>'
+											},
+										});
+									}
 								});
 							});
-							</script>
-						<?php
+						</script>
+<?php
 					}
 				} else {
 					$now = dol_now();
 					print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. It was disabled -->\n";
-					include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
+					include_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
 					dolibarr_set_const($db, 'MAIN_FIRST_PING_OK_DATE', dol_print_date($now, 'dayhourlog', 'gmt'), 'chaine', 0, '', $conf->entity);
 					dolibarr_set_const($db, 'MAIN_FIRST_PING_OK_ID', 'disabled', 'chaine', 0, '', $conf->entity);
 				}

########## product/stock/stockatdate.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/product/stock/stockatdate.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/product/stock/stockatdate.php	2025-03-17 14:05:55.243517000 +0000
@@ -29,12 +29,12 @@
 
 // Load Dolibarr environment
 require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
-require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
-require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
-require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php';
+require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.commande.class.php';
+require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
 require_once './lib/replenishment.lib.php';
 
 /**
@@ -150,25 +150,27 @@
 	$warehouseStatus[] = Entrepot::STATUS_OPEN_INTERNAL;
 }
 
+
+
 // Get array with current stock per product, warehouse
 $stock_prod_warehouse = array();
 $stock_prod = array();
 if ($date && $dateIsValid) {	// Avoid heavy sql if mandatory date is not defined
 	$sql = "SELECT ps.fk_product, ps.fk_entrepot as fk_warehouse,";
 	$sql .= " SUM(ps.reel) AS stock";
-	$sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
-	$sql .= ", ".MAIN_DB_PREFIX."entrepot as w";
-	$sql .= ", ".MAIN_DB_PREFIX."product as p";
-	$sql .= " WHERE w.entity IN (".getEntity('stock').")";
+	$sql .= " FROM " . MAIN_DB_PREFIX . "product_stock as ps";
+	$sql .= ", " . MAIN_DB_PREFIX . "entrepot as w";
+	$sql .= ", " . MAIN_DB_PREFIX . "product as p";
+	$sql .= " WHERE w.entity IN (" . getEntity('stock') . ")";
 	$sql .= " AND w.rowid = ps.fk_entrepot AND p.rowid = ps.fk_product";
 	if (getDolGlobalString('ENTREPOT_EXTRA_STATUS') && count($warehouseStatus)) {
-		$sql .= " AND w.statut IN (".$db->sanitize(implode(',', $warehouseStatus)).")";
+		$sql .= " AND w.statut IN (" . $db->sanitize(implode(',', $warehouseStatus)) . ")";
 	}
 	if ($productid > 0) {
-		$sql .= " AND ps.fk_product = ".((int) $productid);
+		$sql .= " AND ps.fk_product = " . ((int) $productid);
 	}
 	if (! empty($search_fk_warehouse)) {
-		$sql .= " AND ps.fk_entrepot IN (".$db->sanitize(implode(",", $search_fk_warehouse)).")";
+		$sql .= " AND ps.fk_entrepot IN (" . $db->sanitize(implode(",", $search_fk_warehouse)) . ")";
 	}
 	if ($search_ref) {
 		$sql .= natural_search("p.ref", $search_ref);
@@ -178,6 +180,7 @@
 	}
 	$sql .= " GROUP BY fk_product, fk_entrepot";
 	//print $sql;
+	// var_dump("Premire requete" . $sql);
 
 	$resql = $db->query($sql);
 	if ($resql) {
@@ -213,30 +216,30 @@
 $movements_prod_nb = array();
 if ($date && $dateIsValid) {
 	$sql = "SELECT sm.fk_product, sm.fk_entrepot, SUM(sm.value) AS stock, COUNT(sm.rowid) AS nbofmovement";
-	$sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as sm";
-	$sql .= ", ".MAIN_DB_PREFIX."entrepot as w";
-	$sql .= ", ".MAIN_DB_PREFIX."product as p";
-	$sql .= " WHERE w.entity IN (".getEntity('stock').")";
+	$sql .= " FROM " . MAIN_DB_PREFIX . "stock_mouvement as sm";
+	$sql .= ", " . MAIN_DB_PREFIX . "entrepot as w";
+	$sql .= ", " . MAIN_DB_PREFIX . "product as p";
+	$sql .= " WHERE w.entity IN (" . getEntity('stock') . ")";
 	$sql .= " AND w.rowid = sm.fk_entrepot AND p.rowid = sm.fk_product ";
 	if (getDolGlobalString('ENTREPOT_EXTRA_STATUS') && count($warehouseStatus)) {
-		$sql .= " AND w.statut IN (".$db->sanitize(implode(',', $warehouseStatus)).")";
+		$sql .= " AND w.statut IN (" . $db->sanitize(implode(',', $warehouseStatus)) . ")";
 	}
 	if ($mode == 'future') {
-		$sql .= " AND sm.datem <= '".$db->idate($dateendofday)."'";
+		$sql .= " AND sm.datem <= '" . $db->idate($dateendofday) . "'";
 	} else {
-		$sql .= " AND sm.datem >= '".$db->idate($dateendofday)."'";
+		$sql .= " AND sm.datem >= '" . $db->idate($dateendofday) . "'";
 	}
 	if ($productid > 0) {
-		$sql .= " AND sm.fk_product = ".((int) $productid);
+		$sql .= " AND sm.fk_product = " . ((int) $productid);
 	}
 	if (!empty($search_fk_warehouse)) {
-		$sql .= " AND sm.fk_entrepot IN (".$db->sanitize(implode(",", $search_fk_warehouse)).")";
+		$sql .= " AND sm.fk_entrepot IN (" . $db->sanitize(implode(",", $search_fk_warehouse)) . ")";
 	}
 	if ($search_ref) {
-		$sql .= " AND p.ref LIKE '%".$db->escape($search_ref)."%' ";
+		$sql .= " AND p.ref LIKE '%" . $db->escape($search_ref) . "%' ";
 	}
 	if ($search_nom) {
-		$sql .= " AND p.label LIKE '%".$db->escape($search_nom)."%' ";
+		$sql .= " AND p.label LIKE '%" . $db->escape($search_nom) . "%' ";
 	}
 	$sql .= " GROUP BY sm.fk_product, sm.fk_entrepot";
 
@@ -299,23 +302,23 @@
 $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
 $sql .= $hookmanager->resPrint;
 
-$sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
+$sql .= ' FROM ' . MAIN_DB_PREFIX . 'product as p';
 if (!empty($search_fk_warehouse)) {
-	$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot IN ('.$db->sanitize(implode(",", $search_fk_warehouse)).")";
+	$sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'product_stock as ps ON p.rowid = ps.fk_product AND ps.fk_entrepot IN (' . $db->sanitize(implode(",", $search_fk_warehouse)) . ")";
 }
 // Add fields from hooks
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldListJoin', $parameters); // Note that $action and $object may have been modified by hook
 $sql .= $hookmanager->resPrint;
-$sql .= ' WHERE p.entity IN ('.getEntity('product').')';
+$sql .= ' WHERE p.entity IN (' . getEntity('product') . ')';
 if ($productid > 0) {
-	$sql .= " AND p.rowid = ".((int) $productid);
+	$sql .= " AND p.rowid = " . ((int) $productid);
 }
 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
 	$sql .= " AND p.fk_product_type = 0";
 }
 if (!empty($canvas)) {
-	$sql .= " AND p.canvas = '".$db->escape($canvas)."'";
+	$sql .= " AND p.canvas = '" . $db->escape($canvas) . "'";
 }
 if ($search_ref) {
 	$sql .= natural_search('p.ref', $search_ref);
@@ -325,6 +328,11 @@
 }
 $sql .= ' GROUP BY p.rowid, p.ref, p.label, p.description, p.price, p.pmp, p.price_ttc, p.price_base_type, p.fk_product_type, p.desiredstock, p.seuil_stock_alerte,';
 $sql .= ' p.tms, p.duration, p.tobuy, p.stock';
+
+//MODIF JOSE
+if (!empty($search_fk_warehouse) || $search_fk_warehouse == 0) {
+	$sql .= ' HAVING SUM(ps.reel) > 0 OR SUM(p.pmp * ps.reel) > 0 ';
+}
 // Add where from hooks
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
@@ -339,6 +347,52 @@
 $sql .= $db->order($sortfield, $sortorder);
 
 $nbtotalofrecords = '';
+
+//MODIF JOSE
+$result = $db->query($sql);
+$total_buying_price = 0;
+$total_current_stock = 0;
+$total_virtual_stock = 0;
+
+if ($result) {
+	while ($objp = $db->fetch_object($result)) {
+		$currentstock = 0;
+		if (!empty($search_fk_warehouse)) {
+			foreach ($search_fk_warehouse as $val) {
+				if (!is_numeric($currentstock)) {
+					$currentstock = 0;
+				}
+				$currentstock += isset($stock_prod_warehouse[$objp->rowid][$val]) ? (float) $stock_prod_warehouse[$objp->rowid][$val] : 0;
+			}
+		} else {
+			$currentstock = isset($stock_prod[$objp->rowid]) ? (float) $stock_prod[$objp->rowid] : 0;
+		}
+
+		$stock = $currentstock;
+		if (!empty($search_fk_warehouse)) {
+			foreach ($search_fk_warehouse as $val) {
+				$stock -= isset($movements_prod_warehouse[$objp->rowid][$val]) ? (float) $movements_prod_warehouse[$objp->rowid][$val] : 0;
+			}
+		} else {
+			$stock -= isset($movements_prod[$objp->rowid]) ? (float) $movements_prod[$objp->rowid] : 0;
+		}
+
+		$total_current_stock += $currentstock;
+		$total_buying_price += $stock * $objp->pmp;
+		$total_virtual_stock += isset($objp->sellvalue) ? (float) $objp->sellvalue : 0;
+
+		$_GET['total_current_stock'] = $objforcount->total_ht ?? 0;
+		$_GET['total_buying_price'] = $objforcount->total_tva ?? 0;
+		$_GET['total_virtual_stock'] = $objforcount->total_ttc ?? 0;
+	}
+	$db->free($result);
+} else {
+	dol_print_error($db);
+}
+
+//END MODIF JOSE 
+
+
 if ($date && $dateIsValid) {	// We avoid a heavy sql if mandatory parameter date not yet defined
 	if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
 		$result = $db->query($sql);
@@ -379,22 +433,22 @@
 if ($ext == 'csv') {
 	top_httphead("text/csv");
 	//header("Content-Type: text/csv");
-	header("Content-Disposition: attachment; filename=stock".($date ? '-'.date("Y-m-d", $date) : '').".csv");
+	header("Content-Disposition: attachment; filename=stock" . ($date ? '-' . date("Y-m-d", $date) : '') . ".csv");
 
 	// Lines of title
 	print implode(";", ($mode == 'future') ?
-		array('"Product Reference"', '"Label"', '"Current Stock"', '"'.$stocklabel.'"', '"Virtual Stock"') :
-		array('"Product Reference"', '"Label"', '"'.$stocklabel.'"', '"Estimated Stock Value"', '"Estimate Sell Value"', '"Movements"', '"Current Stock"'))."\r\n";
+		array('"Product Reference"', '"Label"', '"Current Stock"', '"' . $stocklabel . '"', '"Virtual Stock"') :
+		array('"Product Reference"', '"Label"', '"' . $stocklabel . '"', '"Estimated Stock Value"', '"Estimate Sell Value"', '"Movements"', '"Current Stock"')) . "\r\n";
 } else {
 	llxHeader('', $title, $helpurl, '', 0, 0, '', '', '', 'mod-product page-stock_stockatdate');
 
 	$head = array();
 
-	$head[0][0] = DOL_URL_ROOT.'/product/stock/stockatdate.php';
+	$head[0][0] = DOL_URL_ROOT . '/product/stock/stockatdate.php';
 	$head[0][1] = $langs->trans("StockAtDateInPast");
 	$head[0][2] = 'stockatdatepast';
 
-	$head[1][0] = DOL_URL_ROOT.'/product/stock/stockatdate.php?mode=future';
+	$head[1][0] = DOL_URL_ROOT . '/product/stock/stockatdate.php?mode=future';
 	$head[1][1] = $langs->trans("StockAtDateInFuture");
 	$head[1][2] = 'stockatdatefuture';
 
@@ -407,26 +461,26 @@
 	if ($mode == 'future') {
 		$desc = $langs->trans("StockAtDateFutureDesc");
 	}
-	print '<span class="opacitymedium">'.$desc.'</span><br>'."\n";
-	print '<br>'."\n";
+	print '<span class="opacitymedium">' . $desc . '</span><br>' . "\n";
+	print '<br>' . "\n";
 
-	print '<form name="formFilterWarehouse" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
-	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<form name="formFilterWarehouse" method="POST" action="' . $_SERVER["PHP_SELF"] . '">';
+	print '<input type="hidden" name="token" value="' . newToken() . '">';
 	print '<input type="hidden" name="action" value="filter">';
-	print '<input type="hidden" name="mode" value="'.$mode.'">';
+	print '<input type="hidden" name="mode" value="' . $mode . '">';
 
 	print '<div class="inline-block valignmiddle" style="padding-right: 20px;">';
-	print '<span class="fieldrequired">'.$langs->trans('Date').'</span> '.$form->selectDate(($date ? $date : -1), 'date');
+	print '<span class="fieldrequired">' . $langs->trans('Date') . '</span> ' . $form->selectDate(($date ? $date : -1), 'date');
 
 	print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddingrightonly">&nbsp;</span> ';
-	print img_picto('', 'product', 'class="pictofixedwidth"').' ';
+	print img_picto('', 'product', 'class="pictofixedwidth"') . ' ';
 	print '</span> ';
 	print $form->select_produits($productid, 'productid', '', 0, 0, -1, 2, '', 0, array(), 0, $langs->trans('Product'), 0, 'maxwidth300', 0, '', null, 1);
 
 	if ($mode != 'future') {
 		// A virtual stock in future has no sense on a per warehouse view, so no filter on warehouse is available for stock at date in future
 		print ' <span class="clearbothonsmartphone marginleftonly paddingleftonly marginrightonly paddingrightonly">&nbsp;</span> ';
-		print img_picto('', 'stock', 'class="pictofixedwidth"').$langs->trans("Warehouse").' :';
+		print img_picto('', 'stock', 'class="pictofixedwidth"') . $langs->trans("Warehouse") . ' :';
 		print '</span> ';
 		$selected = ((GETPOSTISSET('search_fk_warehouse') || GETPOSTISSET('fk_warehouse')) ? $search_fk_warehouse : 'ifonenodefault');
 		print $formproduct->selectWarehouses($selected, 'search_fk_warehouse', '', 1, 0, 0, $langs->trans('Warehouse'), 0, 0, array(), 'minwidth200', array(), 1, false, 'e.ref', 1);
@@ -441,53 +495,69 @@
 	}
 
 	print '<div class="inline-block valignmiddle">';
-	print '<input type="submit" class="button" name="valid" value="'.$langs->trans('Refresh').'">';
+	print '<input type="submit" class="button" name="valid" value="' . $langs->trans('Refresh') . '">';
 	print '</div>';
 
 	//print '</form>';
 
 	$param = '';
 	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
-		$param .= '&contextpage='.urlencode($contextpage);
+		$param .= '&contextpage=' . urlencode($contextpage);
 	}
 	if ($limit > 0 && $limit != $conf->liste_limit) {
-		$param .= '&limit='.((int) $limit);
+		$param .= '&limit=' . ((int) $limit);
 	}
-	$param .= '&mode='.$mode;
+	$param .= '&mode=' . $mode;
 	$param_warehouse = '';
 	if (!empty($search_fk_warehouse)) {
 		foreach ($search_fk_warehouse as $val) {
-			$param_warehouse .= '&search_fk_warehouse[]='.$val;
+			$param_warehouse .= '&search_fk_warehouse[]=' . $val;
 		}
 		$param .= $param_warehouse;
 	}
 	if ($productid > 0) {
-		$param .= '&productid='.(int) $productid;
+		$param .= '&productid=' . (int) $productid;
 	}
 	if (GETPOSTINT('dateday') > 0) {
-		$param .= '&dateday='.GETPOSTINT('dateday');
+		$param .= '&dateday=' . GETPOSTINT('dateday');
 	}
 	if (GETPOSTINT('datemonth') > 0) {
-		$param .= '&datemonth='.GETPOSTINT('datemonth');
+		$param .= '&datemonth=' . GETPOSTINT('datemonth');
 	}
 	if (GETPOSTINT('dateyear') > 0) {
-		$param .= '&dateyear='.GETPOSTINT('dateyear');
+		$param .= '&dateyear=' . GETPOSTINT('dateyear');
 	}
 
 	// TODO Move this into the title line ?
 	print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'stock', 0, '', '', $limit, 0, 0, 1);
 
+	// //MODIF JOSE
+	// if ($mode !== 'future' && !empty($date) && $dateIsValid) {
+
+	// 	print '<div style="display: flex; justify-content: center; gap: 20px; margin-bottom: 20px;">';
+	// 	printBox($langs->trans("Valorisation à l'achat"), price($total_buying_price));
+	// 	printBox($langs->trans("Stock actuel"), price($total_current_stock));
+	// 	if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
+	// 		printBox($langs->trans("Valeur vente"), price($total_virtual_stock));
+	// 	}
+
+	// 	print '</div>';
+	// }
+	// //END MODIF JOSE
+
+
+
 	print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you don't need reserved height for your table
 	if ($num) {
 		print '<p>';
-		print '<a href="stockatdate.php?output=csv&sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder).'&type='.((int) $type).'&mode='.urlencode($mode).
-			(($productid > 0) ? "&productid=".((int) $productid) : '').
-			$param_warehouse.
-			"&search_ref=".dol_escape_htmltag($search_ref).
-			"&search_nom=".dol_escape_htmltag($search_nom).
-			(GETPOSTISSET('dateday') ? "&dateday=".GETPOSTINT('dateday') : '').
-			(GETPOSTISSET('datemonth') ? "&datemonth=".GETPOSTINT('datemonth') : '').
-			(GETPOSTISSET('dateyear') ? "&dateyear=".GETPOSTINT('dateyear') : '').
+		print '<a href="stockatdate.php?output=csv&sortfield=' . urlencode($sortfield) . '&sortorder=' . urlencode($sortorder) . '&type=' . ((int) $type) . '&mode=' . urlencode($mode) .
+			(($productid > 0) ? "&productid=" . ((int) $productid) : '') .
+			$param_warehouse .
+			"&search_ref=" . dol_escape_htmltag($search_ref) .
+			"&search_nom=" . dol_escape_htmltag($search_nom) .
+			(GETPOSTISSET('dateday') ? "&dateday=" . GETPOSTINT('dateday') : '') .
+			(GETPOSTISSET('datemonth') ? "&datemonth=" . GETPOSTINT('datemonth') : '') .
+			(GETPOSTISSET('dateyear') ? "&dateyear=" . GETPOSTINT('dateyear') : '') .
 			'" title="Download CSV" />';
 		print img_picto('', 'download', 'class="pictofixedwidth"');
 		print 'Download CSV';
@@ -496,16 +566,16 @@
 	}
 	print '<table class="liste centpercent">';
 
-	print '<input type="hidden" name="token" value="'.newToken().'">';
-	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
-	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
-	print '<input type="hidden" name="type" value="'.$type.'">';
-	print '<input type="hidden" name="mode" value="'.$mode.'">';
+	print '<input type="hidden" name="token" value="' . newToken() . '">';
+	print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
+	print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
+	print '<input type="hidden" name="type" value="' . $type . '">';
+	print '<input type="hidden" name="mode" value="' . $mode . '">';
 
 	// Fields title search
 	print '<tr class="liste_titre_filter">';
-	print '<td class="liste_titre"><input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'"></td>';
-	print '<td class="liste_titre"><input class="flat" type="text" name="search_nom" size="8" value="'.dol_escape_htmltag($search_nom).'"></td>';
+	print '<td class="liste_titre"><input class="flat" type="text" name="search_ref" size="8" value="' . dol_escape_htmltag($search_ref) . '"></td>';
+	print '<td class="liste_titre"><input class="flat" type="text" name="search_nom" size="8" value="' . dol_escape_htmltag($search_nom) . '"></td>';
 	print '<td class="liste_titre"></td>';
 	print '<td class="liste_titre"></td>';
 	print '<td class="liste_titre"></td>';
@@ -543,9 +613,9 @@
 		print_liste_field_titre('VirtualStock', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ', 'VirtualStockDesc');
 	} else {
 		print_liste_field_titre($stocklabel, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ');
-		$tooltiptext = $langs->trans("QtyAtDate").' x '.$langs->trans("AverageUnitPricePMPShort").' ('.$langs->trans("Currently").')';
+		$tooltiptext = $langs->trans("QtyAtDate") . ' x ' . $langs->trans("AverageUnitPricePMPShort") . ' (' . $langs->trans("Currently") . ')';
 		print_liste_field_titre("EstimatedStockValue", $_SERVER["PHP_SELF"], "estimatedvalue", '', $param, '', $sortfield, $sortorder, 'right ', $tooltiptext, 1);
-		$tooltiptext = $langs->trans("QtyAtDate").' x '.$langs->trans("SellingPrice").' ('.$langs->trans("Currently").')';
+		$tooltiptext = $langs->trans("QtyAtDate") . ' x ' . $langs->trans("SellingPrice") . ' (' . $langs->trans("Currently") . ')';
 		print_liste_field_titre("EstimatedStockValueSell", $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right ', $tooltiptext, 1);
 		$tooltiptext = $langs->trans("MovementsSinceDate");
 		print_liste_field_titre('', $_SERVER["PHP_SELF"], '', '', $param, '', '', '', 'right ', $tooltiptext, 1);
@@ -562,6 +632,8 @@
 	print "</tr>\n";
 }
 
+
+
 $totalbuyingprice = 0;
 $totalsellingprice = 0;
 $totalcurrentstock = 0;
@@ -635,30 +707,43 @@
 		if ($ext == 'csv') {
 			if ($mode == 'future') {
 				print implode(";", array(
-					'"'.$objp->ref.'"',
-					'"'.$objp->label.'"',
-					'"'.price2num($currentstock, 'MS').'"',
-					'"'.price2num($stock, 'MS').'"',
-					'"'.price2num($virtualstock, 'MS').'"'))."\r\n";
+					'"' . $objp->ref . '"',
+					'"' . $objp->label . '"',
+					'"' . price2num($currentstock, 'MS') . '"',
+					'"' . price2num($stock, 'MS') . '"',
+					'"' . price2num($virtualstock, 'MS') . '"'
+				)) . "\r\n";
 				$totalvirtualstock += $virtualstock;
 			} else {
 				print implode(";", array(
-					'"'.$objp->ref.'"',
-					'"'.$objp->label.'"',
-					'"'.price(price2num($stock, 'MS')).'"',
-					price2num($stock * $objp->pmp, 'MT') ? '"'.price2num($stock * $objp->pmp, 'MT').'"' : '',
-					!getDolGlobalString('PRODUIT_MULTIPRICES') ? '"'.price2num($stock * $objp->price, 'MT').'"' : '"'.$langs->trans("Variable").'('.$langs->trans("OptionMULTIPRICESIsOn").')"',
+					'"' . $objp->ref . '"',
+					'"' . $objp->label . '"',
+					'"' . price(price2num($stock, 'MS')) . '"',
+					price2num($stock * $objp->pmp, 'MT') ? '"' . price2num($stock * $objp->pmp, 'MT') . '"' : '',
+					!getDolGlobalString('PRODUIT_MULTIPRICES') ? '"' . price2num($stock * $objp->price, 'MT') . '"' : '"' . $langs->trans("Variable") . '(' . $langs->trans("OptionMULTIPRICESIsOn") . ')"',
 					"$nbofmovement",
-					'"'.price2num($currentstock, 'MS').'"'))."\r\n";
+					'"' . price2num($currentstock, 'MS') . '"'
+				)) . "\r\n";
 				$totalbuyingprice += $stock * $objp->pmp;
 				$totalsellingprice += $stock * $objp->price;
 			}
 			$totalcurrentstock += $currentstock;
 		} else {
+
+			$estimatedvalue = $stock * $objp->pmp;
+
+			// if ($stock == 0 && $estimatedvalue == 0) {
+			// 	var_dump("Exclusion de la ligne :", $objp->ref, "Stock:", $stock, "Estimated Value:", $estimatedvalue);
+			// }
+
+			// if ($stock == 0) {
+			// 	continue;
+			// }
+
 			print '<tr class="oddeven">';
 
 			// Product ref
-			print '<td class="nowrap">'.$prod->getNomUrl(1, '').'</td>';
+			print '<td class="nowrap">' . $prod->getNomUrl(1, '') . '</td>';
 
 			// Product label
 			print '<td>';
@@ -667,26 +752,27 @@
 
 			if ($mode == 'future') {
 				// Current stock
-				print '<td class="right">'.price(price2num($currentstock, 'MS')).'</td>';
+				print '<td class="right">' . price(price2num($currentstock, 'MS')) . '</td>';
 				//$totalcurrentstock += $currentstock;
 
 				print '<td class="right"></td>';
 
 				// Virtual stock at date
-				print '<td class="right">'.price(price2num($stock, 'MS')).'</td>';
+				print '<td class="right">' . price(price2num($stock, 'MS')) . '</td>';
 
 				// Final virtual stock
-				print '<td class="right">'.price(price2num($virtualstock, 'MS')).'</td>';
+				print '<td class="right">' . price(price2num($virtualstock, 'MS')) . '</td>';
 				$totalvirtualstock += $virtualstock;
 			} else {
+
+
 				// Stock at date
-				print '<td class="right">'.($stock ? price(price2num($stock, 'MS')) : ('<span class="opacitymedium">0</span>')).'</td>';
+				print '<td class="right">' . ($stock ? price(price2num($stock, 'MS')) : ('<span class="opacitymedium">0</span>')) . '</td>';
 
 				// PMP value
-				$estimatedvalue = $stock * $objp->pmp;
-				print '<td class="right" title="'.dolPrintHTMLForAttribute($langs->trans("AverageUnitPricePMPShort").' ('.$langs->trans("Currently").'): '.price(price2num($objp->pmp, 'MU'), 1)).'">';
+				print '<td class="right" title="' . dolPrintHTMLForAttribute($langs->trans("AverageUnitPricePMPShort") . ' (' . $langs->trans("Currently") . '): ' . price(price2num($objp->pmp, 'MU'), 1)) . '">';
 				if (price2num($estimatedvalue, 'MT')) {
-					print '<span class="amount">'.price(price2num($estimatedvalue, 'MT'), 1).'</span>';
+					print '<span class="amount">' . price(price2num($estimatedvalue, 'MT'), 1) . '</span>';
 				} else {
 					print '';
 				}
@@ -696,7 +782,7 @@
 				// Selling value
 				print '<td class="right"';
 				if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
-					print ' title="'.dolPrintHTMLForAttribute($langs->trans("SellingPrice").' ('.$langs->trans("Currently").'): '.price(price2num($objp->price, 'MU'), 1));
+					print ' title="' . dolPrintHTMLForAttribute($langs->trans("SellingPrice") . ' (' . $langs->trans("Currently") . '): ' . price(price2num($objp->price, 'MU'), 1));
 				}
 				print '">';
 				if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
@@ -708,31 +794,31 @@
 					$totalsellingprice += $stock * $objp->price;
 				} else {
 					$htmltext = $langs->trans("OptionMULTIPRICESIsOn");
-					print $form->textwithtooltip('<span class="opacitymedium">'.$langs->trans("Variable").'</span>', $htmltext);
+					print $form->textwithtooltip('<span class="opacitymedium">' . $langs->trans("Variable") . '</span>', $htmltext);
 				}
 				print '</td>';
 
 				// Movements
 				print '<td class="right">';
 				if ($nbofmovement > 0) {
-					$url = DOL_URL_ROOT.'/product/stock/movement_list.php?idproduct='.$objp->rowid;
+					$url = DOL_URL_ROOT . '/product/stock/movement_list.php?idproduct=' . $objp->rowid;
 					if (GETPOSTISSET('datemonth')) {
-						$url .= '&search_date_startday='.GETPOSTINT('dateday');
-						$url .= '&search_date_startmonth='.GETPOSTINT('datemonth');
-						$url .= '&search_date_startyear='.GETPOSTINT('dateyear');
+						$url .= '&search_date_startday=' . GETPOSTINT('dateday');
+						$url .= '&search_date_startmonth=' . GETPOSTINT('datemonth');
+						$url .= '&search_date_startyear=' . GETPOSTINT('dateyear');
 					}
 					if (count($search_fk_warehouse) > 1) {
 						$url = '';	// Do not show link, multi warehouse as filter not managed yet by target page
 					} else {
 						foreach ($search_fk_warehouse as $val) {
-							$url .= ($val > 0 ? '&search_warehouse='.((int) $val) : '');
+							$url .= ($val > 0 ? '&search_warehouse=' . ((int) $val) : '');
 						}
 					}
 					if ($url) {
-						print '<a href="'.$url.'">';
+						print '<a href="' . $url . '">';
 					}
 					print $langs->trans("Movements");
-					print '<span class="tabs paddingleft"><span class="badge">'.$nbofmovement.'</span></span>';
+					print '<span class="tabs paddingleft"><span class="badge">' . $nbofmovement . '</span></span>';
 					if ($url) {
 						print '</a>';
 					}
@@ -740,7 +826,7 @@
 				print '</td>';
 
 				// Current stock
-				print '<td class="right">'.($currentstock ? price(price2num($currentstock, 'MS')) : '<span class="opacitymedium">0</span>').'</td>';
+				print '<td class="right">' . ($currentstock ? price(price2num($currentstock, 'MS')) : '<span class="opacitymedium">0</span>') . '</td>';
 			}
 			$totalcurrentstock += $currentstock;
 
@@ -752,7 +838,7 @@
 			// Action
 			print '<td class="right"></td>';
 
-			print '</tr>'."\n";
+			print '</tr>' . "\n";
 		}
 	}
 	$i++;
@@ -773,42 +859,44 @@
 	print implode(
 		";",
 		($mode == 'future') ? array(
-		'"'.$langs->trans("Totalforthispage").'"',
-		'',
-		$productid > 0 ? price2num($totalcurrentstock, 'MS') : '',
-		'',
-		price(price2num($totalvirtualstock, 'MS'))) :
-		array(
-		'"'.$langs->trans("Totalforthispage").'"',
-		'',
-		'',
-		'"'.price2num($totalbuyingprice, 'MT').'"',
-		!getDolGlobalString('PRODUIT_MULTIPRICES') ? '"'.price2num($totalsellingprice, 'MT').'"' : '',
-		'',
-		$productid > 0 ? price2num($totalcurrentstock, 'MS') : '')
+			'"' . $langs->trans("Totalforthispage") . '"',
+			'',
+			$productid > 0 ? price2num($totalcurrentstock, 'MS') : '',
+			'',
+			price(price2num($totalvirtualstock, 'MS'))
+		) :
+			array(
+				'"' . $langs->trans("Totalforthispage") . '"',
+				'',
+				'',
+				'"' . price2num($totalbuyingprice, 'MT') . '"',
+				!getDolGlobalString('PRODUIT_MULTIPRICES') ? '"' . price2num($totalsellingprice, 'MT') . '"' : '',
+				'',
+				$productid > 0 ? price2num($totalcurrentstock, 'MS') : ''
+			)
 	);
 } else {
 	if (empty($date) || !$dateIsValid) {
-		print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("EnterADateCriteria").'</span></td></tr>';
+		print '<tr><td colspan="' . $colspan . '"><span class="opacitymedium">' . $langs->trans("EnterADateCriteria") . '</span></td></tr>';
 	} else {
 		print '<tr class="liste_total">';
-		print '<td>'.$langs->trans("Totalforthispage").'</td>';
+		print '<td>' . $langs->trans("Totalforthispage") . '</td>';
 		print '<td></td>';
 		if ($mode == 'future') {
-			print '<td class="right">'.price(price2num($totalcurrentstock, 'MS')).'</td>';
+			print '<td class="right">' . price(price2num($totalcurrentstock, 'MS')) . '</td>';
 			print '<td></td>';
 			print '<td></td>';
-			print '<td class="right">'.price(price2num($totalvirtualstock, 'MS')).'</td>';
+			print '<td class="right">' . price(price2num($totalvirtualstock, 'MS')) . '</td>';
 		} else {
 			print '<td></td>';
-			print '<td class="right">'.price(price2num($totalbuyingprice, 'MT')).'</td>';
+			print '<td class="right">' . price(price2num($totalbuyingprice, 'MT')) . '</td>';
 			if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
-				print '<td class="right">'.price(price2num($totalsellingprice, 'MT')).'</td>';
+				print '<td class="right">' . price(price2num($totalsellingprice, 'MT')) . '</td>';
 			} else {
 				print '<td></td>';
 			}
 			print '<td></td>';
-			print '<td class="right">'.($productid > 0 ? price(price2num($totalcurrentstock, 'MS')) : '').'</td>';
+			print '<td class="right">' . ($productid > 0 ? price(price2num($totalcurrentstock, 'MS')) : '') . '</td>';
 		}
 		print '<td></td>';
 		print '</tr>';

########## public/payment/paymentok.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/public/payment/paymentok.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/public/payment/paymentok.php	2025-03-26 13:32:51.319080000 +0000
@@ -948,7 +948,7 @@
 					$ispostactionok = -1;
 					$error++; // Not yet supported
 				}
-				$paiement->paiementid   = $paymentTypeId;
+				$paiement->paiementid  = $paymentTypeId;
 				$paiement->num_payment = '';
 				$paiement->note_public  = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
 				$paiement->ext_payment_id = $TRANSACTIONID;		// TODO LDR May be we should store py_... instead of pi_... but we started with pi_... so we continue.

########## public/stripe/ipn.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/public/stripe/ipn.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/public/stripe/ipn.php	2025-05-06 09:38:45.569450000 +0000
@@ -44,18 +44,18 @@
 
 // Load Dolibarr environment
 require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php';
-require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
-require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
-require_once DOL_DOCUMENT_ROOT.'/includes/stripe/stripe-php/init.php';
-require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/ccountry.class.php';
+require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
+require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
+require_once DOL_DOCUMENT_ROOT . '/includes/stripe/stripe-php/init.php';
+require_once DOL_DOCUMENT_ROOT . '/stripe/class/stripe.class.php';
 /**
  * @var Conf $conf
  * @var DoliDB $db
@@ -63,82 +63,147 @@
  */
 
 // You can find your endpoint's secret in your webhook settings
-if (GETPOSTISSET('connect')) {
-	if (GETPOSTISSET('test')) {
-		$endpoint_secret = getDolGlobalString('STRIPE_TEST_WEBHOOK_CONNECT_KEY');
-		$service = 'StripeTest';
-		$servicestatus = 0;
-	} else {
-		$endpoint_secret = getDolGlobalString('STRIPE_LIVE_WEBHOOK_CONNECT_KEY');
-		$service = 'StripeLive';
-		$servicestatus = 1;
-	}
-} else {
-	if (GETPOSTISSET('test')) {
-		$endpoint_secret = getDolGlobalString('STRIPE_TEST_WEBHOOK_KEY');
-		$service = 'StripeTest';
-		$servicestatus = 0;
-	} else {
-		$endpoint_secret = getDolGlobalString('STRIPE_LIVE_WEBHOOK_KEY');
-		$service = 'StripeLive';
-		$servicestatus = 1;
+// if (GETPOSTISSET('connect')) {
+// 	if (GETPOSTISSET('test')) {
+// 		$endpoint_secret = getDolGlobalString('STRIPE_TEST_WEBHOOK_CONNECT_KEY');
+// 		$service = 'StripeTest';
+// 		$servicestatus = 0;
+// 	} else {
+// 		$endpoint_secret = getDolGlobalString('STRIPE_LIVE_WEBHOOK_CONNECT_KEY');
+// 		$service = 'StripeLive';
+// 		$servicestatus = 1;
+// 	}
+// } else {
+// 	if (GETPOSTISSET('test')) {
+// 		$endpoint_secret = getDolGlobalString('STRIPE_TEST_WEBHOOK_KEY');
+// 		$service = 'StripeTest';
+// 		$servicestatus = 0;
+// 	} else {
+// 		$endpoint_secret = getDolGlobalString('STRIPE_LIVE_WEBHOOK_KEY');
+// 		$service = 'StripeLive';
+// 		$servicestatus = 1;
+// 	}
+// }
+
+// if (!isModEnabled('stripe')) {
+// 	httponly_accessforbidden('Module Stripe not enabled');
+// }
+
+// if (empty($endpoint_secret)) {
+// 	httponly_accessforbidden('Error: Setup of module Stripe not complete for mode '.dol_escape_htmltag($service).'. The WEBHOOK_KEY is not defined.', 400, 1);
+// }
+
+// if (getDolGlobalString('STRIPE_USER_ACCOUNT_FOR_ACTIONS')) {
+// 	// We set the user to use for all ipn actions in Dolibarr
+// 	$user = new User($db);
+// 	$user->fetch(getDolGlobalString('STRIPE_USER_ACCOUNT_FOR_ACTIONS'));
+// 	$user->loadRights();
+// } else {
+// 	httponly_accessforbidden('Error: Setup of module Stripe not complete for mode '.dol_escape_htmltag($service).'. The STRIPE_USER_ACCOUNT_FOR_ACTIONS is not defined.', 400, 1);
+// }
+
+// $now = dol_now();
+
+// // Security
+// // The test on security key is done later into constructEvent() method.
+
+
+// /*
+//  * Actions
+//  */
+
+// $payload = @file_get_contents("php://input");
+// $sig_header = empty($_SERVER["HTTP_STRIPE_SIGNATURE"]) ? '' : $_SERVER["HTTP_STRIPE_SIGNATURE"];
+// $event = null;
+
+// if (getDolGlobalString('STRIPE_DEBUG')) {
+// 	$fh = fopen(DOL_DATA_ROOT.'/dolibarr_stripeipn_payload.log', 'w+');
+// 	if ($fh) {
+// 		fwrite($fh, dol_print_date(dol_now('gmt'), 'standard').' IPN Called. service='.$service.' HTTP_STRIPE_SIGNATURE='.$sig_header."\n");
+// 		fwrite($fh, $payload);
+// 		fclose($fh);
+// 		dolChmod(DOL_DATA_ROOT.'/dolibarr_stripeipn_payload.log');
+// 	}
+// }
+
+// $error = 0;
+
+// try {
+// 	$event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret);
+// } catch (UnexpectedValueException $e) {
+// 	// Invalid payload
+// 	httponly_accessforbidden('Invalid payload', 400);
+// } catch (\Stripe\Exception\SignatureVerificationException $e) {
+// 	httponly_accessforbidden('Invalid signature. May be a hook for an event created by another Stripe env ? Check setup of your keys whsec_...', 400);
+// } catch (Exception $e) {
+// 	httponly_accessforbidden('Error '.$e->getMessage(), 400);
+// }
+
+$payload = @file_get_contents("php://input");
+$sig_header = empty($_SERVER["HTTP_STRIPE_SIGNATURE"]) ? '' : $_SERVER["HTTP_STRIPE_SIGNATURE"];
+
+// On tente de parser sans signature pour récupérer l'account
+$tmp_event = json_decode($payload);
+$account_from_event = !empty($tmp_event->account) ? $tmp_event->account : null;
+
+if (!$account_from_event) {
+	httponly_accessforbidden("Stripe account ID not found in webhook payload", 400);
+}
+
+// Mapping personnalisé
+$stripeAccounts = array(
+	'RIDIN' => getDolGlobalString('STRIPE_CONNECT_ID_RIDIN'),
+	'FESTI' => getDolGlobalString('STRIPE_CONNECT_ID_FESTI'),
+);
+$env = GETPOSTISSET('test') ? 'TEST' : 'LIVE';
+
+// Trouver le code correspondant à l'account Stripe
+$account_code = null;
+foreach ($stripeAccounts as $code => $stripe_id) {
+	if ($account_from_event === $stripe_id) {
+		$account_code = $code;
+		break;
 	}
 }
 
+if (!$account_code) {
+	httponly_accessforbidden("No matching Stripe account configuration for ID: $account_from_event", 400);
+}
+
+// Charger la bonne clé webhook
+$endpoint_secret = getDolGlobalString("STRIPE_{$env}_WEBHOOK_KEY_{$account_code}");
+$service = ($env === 'TEST') ? 'StripeTest' : 'StripeLive';
+$servicestatus = ($env === 'TEST') ? 0 : 1;
+
 if (!isModEnabled('stripe')) {
 	httponly_accessforbidden('Module Stripe not enabled');
 }
 
 if (empty($endpoint_secret)) {
-	httponly_accessforbidden('Error: Setup of module Stripe not complete for mode '.dol_escape_htmltag($service).'. The WEBHOOK_KEY is not defined.', 400, 1);
+	httponly_accessforbidden("Webhook key not configured for account $account_code in $env environment", 400);
 }
 
+// Charger l'utilisateur
 if (getDolGlobalString('STRIPE_USER_ACCOUNT_FOR_ACTIONS')) {
-	// We set the user to use for all ipn actions in Dolibarr
 	$user = new User($db);
 	$user->fetch(getDolGlobalString('STRIPE_USER_ACCOUNT_FOR_ACTIONS'));
 	$user->loadRights();
 } else {
-	httponly_accessforbidden('Error: Setup of module Stripe not complete for mode '.dol_escape_htmltag($service).'. The STRIPE_USER_ACCOUNT_FOR_ACTIONS is not defined.', 400, 1);
+	httponly_accessforbidden("Missing STRIPE_USER_ACCOUNT_FOR_ACTIONS constant", 400);
 }
 
-$now = dol_now();
-
-// Security
-// The test on security key is done later into constructEvent() method.
-
-
-/*
- * Actions
- */
-
-$payload = @file_get_contents("php://input");
-$sig_header = empty($_SERVER["HTTP_STRIPE_SIGNATURE"]) ? '' : $_SERVER["HTTP_STRIPE_SIGNATURE"];
-$event = null;
-
-if (getDolGlobalString('STRIPE_DEBUG')) {
-	$fh = fopen(DOL_DATA_ROOT.'/dolibarr_stripeipn_payload.log', 'w+');
-	if ($fh) {
-		fwrite($fh, dol_print_date(dol_now('gmt'), 'standard').' IPN Called. service='.$service.' HTTP_STRIPE_SIGNATURE='.$sig_header."\n");
-		fwrite($fh, $payload);
-		fclose($fh);
-		dolChmod(DOL_DATA_ROOT.'/dolibarr_stripeipn_payload.log');
-	}
-}
-
-$error = 0;
-
+// ConstructEvent sécurisé
 try {
 	$event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret);
 } catch (UnexpectedValueException $e) {
-	// Invalid payload
 	httponly_accessforbidden('Invalid payload', 400);
 } catch (\Stripe\Exception\SignatureVerificationException $e) {
-	httponly_accessforbidden('Invalid signature. May be a hook for an event created by another Stripe env ? Check setup of your keys whsec_...', 400);
+	httponly_accessforbidden('Invalid signature for webhook', 400);
 } catch (Exception $e) {
-	httponly_accessforbidden('Error '.$e->getMessage(), 400);
+	httponly_accessforbidden('Error: ' . $e->getMessage(), 400);
 }
 
+
 // Do something with $event
 
 $langs->load("main");
@@ -146,10 +211,10 @@
 
 if (isModEnabled('multicompany') && !empty($conf->stripeconnect->enabled) && is_object($mc)) {
 	$sql = "SELECT entity";
-	$sql .= " FROM ".MAIN_DB_PREFIX."oauth_token";
-	$sql .= " WHERE service = '".$db->escape($service)."' and tokenstring LIKE '%".$db->escape($db->escapeforlike($event->account))."%'";
+	$sql .= " FROM " . MAIN_DB_PREFIX . "oauth_token";
+	$sql .= " WHERE service = '" . $db->escape($service) . "' and tokenstring LIKE '%" . $db->escape($db->escapeforlike($event->account)) . "%'";
 
-	dol_syslog(get_class($db)."::fetch", LOG_DEBUG);
+	dol_syslog(get_class($db) . "::fetch", LOG_DEBUG);
 	$result = $db->query($sql);
 	if ($result) {
 		if ($db->num_rows($result)) {
@@ -175,29 +240,29 @@
 
 top_httphead();
 
-dol_syslog("***** Stripe IPN was called with event->type=".$event->type." service=".$service);
+dol_syslog("***** Stripe IPN was called with event->type=" . $event->type . " service=" . $service);
 
 
 if ($event->type == 'payout.created' && getDolGlobalString('STRIPE_AUTO_RECORD_PAYOUT')) {
 	// When a payout is created by Stripe to transfer money to your account
 	$error = 0;
 
-	$result = dolibarr_set_const($db, $service."_NEXTPAYOUT", date('Y-m-d H:i:s', $event->data->object->arrival_date), 'chaine', 0, '', $conf->entity);
+	$result = dolibarr_set_const($db, $service . "_NEXTPAYOUT", date('Y-m-d H:i:s', $event->data->object->arrival_date), 'chaine', 0, '', $conf->entity);
 
 	if ($result > 0) {
-		$subject = '['.$societeName.'] Notification - Stripe payout scheduled';
+		$subject = '[' . $societeName . '] Notification - Stripe payout scheduled';
 		if (!empty($user->email)) {
-			$sendto = dolGetFirstLastname($user->firstname, $user->lastname)." <".$user->email.">";
+			$sendto = dolGetFirstLastname($user->firstname, $user->lastname) . " <" . $user->email . ">";
 		} else {
-			$sendto = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL') . '" <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL').'>';
+			$sendto = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL') . '" <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL') . '>';
 		}
 		$replyto = $sendto;
 		$sendtocc = '';
 		if (getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL')) {
-			$sendtocc = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL') . '" <' . getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL').'>';
+			$sendtocc = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL') . '" <' . getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL') . '>';
 		}
 
-		$message = "A bank transfer of ".price2num($event->data->object->amount / 100)." ".$event->data->object->currency." should arrive in your account the ".dol_print_date($event->data->object->arrival_date, 'dayhour');
+		$message = "A bank transfer of " . price2num($event->data->object->amount / 100) . " " . $event->data->object->currency . " should arrive in your account the " . dol_print_date($event->data->object->arrival_date, 'dayhour');
 
 		$mailfile = new CMailFile(
 			$subject,
@@ -224,7 +289,7 @@
 } elseif ($event->type == 'payout.paid' && getDolGlobalString('STRIPE_AUTO_RECORD_PAYOUT')) {
 	// When a payout to transfer money to your account is completely done
 	$error = 0;
-	$result = dolibarr_set_const($db, $service."_NEXTPAYOUT", 0, 'chaine', 0, '', $conf->entity);
+	$result = dolibarr_set_const($db, $service . "_NEXTPAYOUT", 0, 'chaine', 0, '', $conf->entity);
 	if ($result) {
 		$langs->load("errors");
 
@@ -232,7 +297,7 @@
 		$label = $event->data->object->description;
 		$amount = $event->data->object->amount / 100;
 		$amount_to = $event->data->object->amount / 100;
-		require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
+		require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
 
 		$accountfrom = new Account($db);
 		$accountfrom->fetch(getDolGlobalInt('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS'));
@@ -265,13 +330,13 @@
 			}
 
 			if (!$error) {
-				$result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert');
+				$result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT . '/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert');
 			}
 			if (!($result > 0)) {
 				$error++;
 			}
 			if (!$error) {
-				$result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert');
+				$result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT . '/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert');
 			}
 			if (!($result > 0)) {
 				$error++;
@@ -285,19 +350,19 @@
 
 			// Send email
 			if (!$error) {
-				$subject = '['.$societeName.'] - NotificationOTIFICATION] Stripe payout done';
+				$subject = '[' . $societeName . '] - NotificationOTIFICATION] Stripe payout done';
 				if (!empty($user->email)) {
-					$sendto = dolGetFirstLastname($user->firstname, $user->lastname)." <".$user->email.">";
+					$sendto = dolGetFirstLastname($user->firstname, $user->lastname) . " <" . $user->email . ">";
 				} else {
-					$sendto = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL') . '" <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL').'>';
+					$sendto = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL') . '" <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL') . '>';
 				}
 				$replyto = $sendto;
 				$sendtocc = '';
 				if (getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL')) {
-					$sendtocc = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL') . '" <' . getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL').'>';
+					$sendtocc = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL') . '" <' . getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL') . '>';
 				}
 
-				$message = "A bank transfer of ".price2num($event->data->object->amount / 100)." ".$event->data->object->currency." has been done to your account the ".dol_print_date($event->data->object->arrival_date, 'dayhour');
+				$message = "A bank transfer of " . price2num($event->data->object->amount / 100) . " " . $event->data->object->currency . " has been done to your account the " . dol_print_date($event->data->object->arrival_date, 'dayhour');
 
 				$mailfile = new CMailFile(
 					$subject,
@@ -332,7 +397,7 @@
 } elseif ($event->type == 'customer.deleted') {
 	// When a customer account is delete on Stripe side
 	$db->begin();
-	$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_account WHERE key_account = '".$db->escape($event->data->object->id)."' AND site = 'stripe'";
+	$sql = "DELETE FROM " . MAIN_DB_PREFIX . "societe_account WHERE key_account = '" . $db->escape($event->data->object->id) . "' AND site = 'stripe'";
 	$db->query($sql);
 	$db->commit();
 } elseif ($event->type == 'payment_intent.succeeded') {
@@ -355,12 +420,12 @@
 	$payment_amount = 0;
 	$payment_amountInDolibarr = 0;
 
-	dol_syslog("Try to find a payment in database for the payment_intent id = ".$TRANSACTIONID);
+	dol_syslog("Try to find a payment in database for the payment_intent id = " . $TRANSACTIONID);
 
 	$sql = "SELECT pi.rowid, pi.fk_facture, pi.fk_prelevement_bons, pi.amount, pi.type, pi.traite";
-	$sql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pi";
-	$sql .= " WHERE pi.ext_payment_id = '".$db->escape($TRANSACTIONID)."'";
-	$sql .= " AND pi.ext_payment_site = '".$db->escape($service)."'";
+	$sql .= " FROM " . MAIN_DB_PREFIX . "prelevement_demande as pi";
+	$sql .= " WHERE pi.ext_payment_id = '" . $db->escape($TRANSACTIONID) . "'";
+	$sql .= " AND pi.ext_payment_site = '" . $db->escape($service) . "'";
 
 	$result = $db->query($sql);
 	if ($result) {
@@ -376,9 +441,9 @@
 					$payment_amountInDolibarr = $obj->amount;
 					$paymentTypeCodeInDolibarr = $obj->type;
 
-					dol_syslog("Found a request in database to pay with direct debit generated (pdid = ".$pdid." directdebitorcreditransfer_id=".$directdebitorcreditransfer_id.")");
+					dol_syslog("Found a request in database to pay with direct debit generated (pdid = " . $pdid . " directdebitorcreditransfer_id=" . $directdebitorcreditransfer_id . ")");
 				} else {
-					dol_syslog("Found a request in database not yet generated (pdid = ".$pdid." directdebitorcreditransfer_id=".$directdebitorcreditransfer_id."). Was the order deleted after being sent ?", LOG_WARNING);
+					dol_syslog("Found a request in database not yet generated (pdid = " . $pdid . " directdebitorcreditransfer_id=" . $directdebitorcreditransfer_id . "). Was the order deleted after being sent ?", LOG_WARNING);
 				}
 			}
 			if ($obj->type == 'card' || empty($obj->type)) {
@@ -389,15 +454,15 @@
 					$payment_amountInDolibarr = $obj->amount;
 					$paymentTypeCodeInDolibarr = empty($obj->type) ? 'card' : $obj->type;
 
-					dol_syslog("Found a request in database to pay with card (pdid = ".$pdid."). We should fix status traite to 1");
+					dol_syslog("Found a request in database to pay with card (pdid = " . $pdid . "). We should fix status traite to 1");
 				} else {
-					dol_syslog("Found a request in database to pay with card (pdid = ".$pdid.") already set to traite=1. Nothing to fix.");
+					dol_syslog("Found a request in database to pay with card (pdid = " . $pdid . ") already set to traite=1. Nothing to fix.");
 				}
 			}
 		} else {
-			dol_syslog("Payment intent ".$TRANSACTIONID." not found into database, so ignored.");
+			dol_syslog("Payment intent " . $TRANSACTIONID . " not found into database, so ignored.");
 			http_response_code(200);
-			print "Payment intent ".$TRANSACTIONID." not found into database, so ignored.";
+			print "Payment intent " . $TRANSACTIONID . " not found into database, so ignored.";
 			return 1;
 		}
 	} else {
@@ -411,7 +476,7 @@
 
 		$stripeacc = $stripearrayofkeysbyenv[$servicestatus]['secret_key'];
 
-		dol_syslog("Get the Stripe payment object for the payment method id = ".json_encode($paymentmethodstripeid));
+		dol_syslog("Get the Stripe payment object for the payment method id = " . json_encode($paymentmethodstripeid));
 
 		$s = new \Stripe\StripeClient($stripeacc);
 
@@ -446,7 +511,7 @@
 			} else {
 				$paiement->multicurrency_amounts = [$invoice_id => $payment_amount];   // Array with all payments dispatching
 
-				$postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
+				$postactionmessages[] = 'Payment was done in a currency (' . $currencyCodeType . ') other than the expected currency of company (' . $conf->currency . ')';
 				$ispostactionok = -1;
 				// Not yet supported, so error
 				$error++;
@@ -454,9 +519,9 @@
 
 			// Get ID of payment PRE
 			$paiement->paiementcode = $paymentTypeCode;
-			$sql = "SELECT id FROM ".MAIN_DB_PREFIX."c_paiement";
-			$sql .= " WHERE code = '".$db->escape($paymentTypeCode)."'";
-			$sql .= " AND entity IN (".getEntity('c_paiement').")";
+			$sql = "SELECT id FROM " . MAIN_DB_PREFIX . "c_paiement";
+			$sql .= " WHERE code = '" . $db->escape($paymentTypeCode) . "'";
+			$sql .= " AND entity IN (" . getEntity('c_paiement') . ")";
 			$resql = $db->query($sql);
 			if ($resql) {
 				$obj = $db->fetch_object($resql);
@@ -468,18 +533,18 @@
 			$paiement->num_payment = '';
 			$paiement->note_public = '';
 			$paiement->note_private = 'StripeSepa payment received by IPN webhook - ' . dol_print_date($now, 'standard') . ' (TZ server) using servicestatus=' . $servicestatus . ($ipaddress ? ' from ip ' . $ipaddress : '') . ' - Transaction ID = ' . $TRANSACTIONID;
-			$paiement->ext_payment_id = $TRANSACTIONID.':'.$customer_id.'@'.$stripearrayofkeysbyenv[$servicestatus]['publishable_key'];		// May be we should store py_... instead of pi_... but we started with pi_... so we continue.
+			$paiement->ext_payment_id = $TRANSACTIONID . ':' . $customer_id . '@' . $stripearrayofkeysbyenv[$servicestatus]['publishable_key'];		// May be we should store py_... instead of pi_... but we started with pi_... so we continue.
 			$paiement->ext_payment_site = $service;
 
 			$ispaymentdone = 0;
-			$sql = "SELECT p.rowid FROM ".MAIN_DB_PREFIX."paiement as p";
-			$sql .= " WHERE p.ext_payment_id = '".$db->escape($paiement->ext_payment_id)."'";
-			$sql .= " AND p.ext_payment_site = '".$db->escape($paiement->ext_payment_site)."'";
+			$sql = "SELECT p.rowid FROM " . MAIN_DB_PREFIX . "paiement as p";
+			$sql .= " WHERE p.ext_payment_id = '" . $db->escape($paiement->ext_payment_id) . "'";
+			$sql .= " AND p.ext_payment_site = '" . $db->escape($paiement->ext_payment_site) . "'";
 			$result = $db->query($sql);
 			if ($result) {
 				if ($db->num_rows($result)) {
 					$ispaymentdone = 1;
-					dol_syslog('* Payment for ext_payment_id '.$paiement->ext_payment_id.' already done. We do not recreate the payment');
+					dol_syslog('* Payment for ext_payment_id ' . $paiement->ext_payment_id . ' already done. We do not recreate the payment');
 				}
 			}
 
@@ -506,16 +571,16 @@
 			if (!$error && isModEnabled('bank')) {
 				// Search again the payment to see if it is already linked to a bank payment record (We should always find the payment that was created before).
 				$ispaymentdone = 0;
-				$sql = "SELECT p.rowid, p.fk_bank FROM ".MAIN_DB_PREFIX."paiement as p";
-				$sql .= " WHERE p.ext_payment_id = '".$db->escape($paiement->ext_payment_id)."'";
-				$sql .= " AND p.ext_payment_site = '".$db->escape($paiement->ext_payment_site)."'";
+				$sql = "SELECT p.rowid, p.fk_bank FROM " . MAIN_DB_PREFIX . "paiement as p";
+				$sql .= " WHERE p.ext_payment_id = '" . $db->escape($paiement->ext_payment_id) . "'";
+				$sql .= " AND p.ext_payment_site = '" . $db->escape($paiement->ext_payment_site) . "'";
 				$sql .= " AND p.fk_bank <> 0";
 				$result = $db->query($sql);
 				if ($result) {
 					if ($db->num_rows($result)) {
 						$ispaymentdone = 1;
 						$obj = $db->fetch_object($result);
-						dol_syslog('* Payment already linked to bank record '.$obj->fk_bank.' . We do not recreate the link');
+						dol_syslog('* Payment already linked to bank record ' . $obj->fk_bank . ' . We do not recreate the link');
 					}
 				}
 				if (!$ispaymentdone) {
@@ -547,14 +612,14 @@
 				$bon = new BonPrelevement($db);
 				$idbon = 0;
 				$sql = "SELECT dp.fk_prelevement_bons as idbon";
-				$sql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as dp";
-				$sql .= " JOIN ".MAIN_DB_PREFIX."prelevement_bons as pb"; // Here we join to prevent modification of a prelevement bon already credited
+				$sql .= " FROM " . MAIN_DB_PREFIX . "prelevement_demande as dp";
+				$sql .= " JOIN " . MAIN_DB_PREFIX . "prelevement_bons as pb"; // Here we join to prevent modification of a prelevement bon already credited
 				$sql .= " ON pb.rowid = dp.fk_prelevement_bons";
-				$sql .= " WHERE dp.fk_facture = ".((int) $invoice_id);
+				$sql .= " WHERE dp.fk_facture = " . ((int) $invoice_id);
 				$sql .= " AND dp.sourcetype = 'facture'";
-				$sql .= " AND dp.ext_payment_id = '".$db->escape($TRANSACTIONID)."'";
+				$sql .= " AND dp.ext_payment_id = '" . $db->escape($TRANSACTIONID) . "'";
 				$sql .= " AND dp.traite = 1";
-				$sql .= " AND statut = ".((int) $bon::STATUS_TRANSFERED); // To be sure that it's not already credited
+				$sql .= " AND statut = " . ((int) $bon::STATUS_TRANSFERED); // To be sure that it's not already credited
 				$result = $db->query($sql);
 				if ($result) {
 					if ($db->num_rows($result)) {
@@ -571,13 +636,13 @@
 				}
 
 				if (!$error && !empty($idbon)) {
-					$sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
-					$sql .= " SET fk_user_credit = ".((int) $user->id);
-					$sql .= ", statut = ".((int) $bon::STATUS_CREDITED);
-					$sql .= ", date_credit = '".$db->idate($now)."'";
+					$sql = "UPDATE " . MAIN_DB_PREFIX . "prelevement_bons";
+					$sql .= " SET fk_user_credit = " . ((int) $user->id);
+					$sql .= ", statut = " . ((int) $bon::STATUS_CREDITED);
+					$sql .= ", date_credit = '" . $db->idate($now) . "'";
 					$sql .= ", credite = 1";
-					$sql .= " WHERE rowid = ".((int) $idbon);
-					$sql .= " AND statut = ".((int) $bon::STATUS_TRANSFERED);
+					$sql .= " WHERE rowid = " . ((int) $idbon);
+					$sql .= " AND statut = " . ((int) $bon::STATUS_TRANSFERED);
 
 					$result = $db->query($sql);
 					if (!$result) {
@@ -588,9 +653,9 @@
 				}
 
 				if (!$error && !empty($idbon)) {
-					$sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
+					$sql = "UPDATE " . MAIN_DB_PREFIX . "prelevement_lignes";
 					$sql .= " SET statut = 2";
-					$sql .= " WHERE fk_prelevement_bons = ".((int) $idbon);
+					$sql .= " WHERE fk_prelevement_bons = " . ((int) $idbon);
 					$result = $db->query($sql);
 					if (!$result) {
 						$postactionmessages[] = $db->lasterror();
@@ -610,7 +675,7 @@
 				return -1;
 			}
 		} else {
-			dol_syslog("The payment mode of this payment is ".$paymentTypeCode." in Stripe and ".$paymentTypeCodeInDolibarr." in Dolibarr. This case is not managed by the IPN");
+			dol_syslog("The payment mode of this payment is " . $paymentTypeCode . " in Stripe and " . $paymentTypeCodeInDolibarr . " in Dolibarr. This case is not managed by the IPN");
 		}
 	} else {
 		dol_syslog("Nothing to do in database because we don't know paymentTypeIdInDolibarr");
@@ -662,17 +727,17 @@
 		$objpaymentmodetype = $object->last_payment_error->payment_method->type;
 	}
 
-	dol_syslog("objpayid=".$objpayid." objpaymentmodetype=".$objpaymentmodetype." objerrcode=".$objerrcode);
+	dol_syslog("objpayid=" . $objpayid . " objpaymentmodetype=" . $objpaymentmodetype . " objerrcode=" . $objerrcode);
 
 	// If this is a differed payment for SEPA, add a line into agenda events
 	if ($objpaymentmodetype == 'sepa_debit') {
 		$db->begin();
 
-		require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
+		require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
 		$actioncomm = new ActionComm($db);
 
 		if ($objinvoiceid > 0) {
-			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+			require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
 			$invoice = new Facture($db);
 			$invoice->fetch($objinvoiceid);
 
@@ -692,7 +757,7 @@
 			$actioncomm->ip = getUserRemoteIP();
 		}
 
-		$actioncomm->note_private = 'Error returned on payment id '.$objpayid.' after SEPA payment request '.$objpaydesc.'<br>Error code is: '.$objerrcode.'<br>Error message is: '.$objerrmessage;
+		$actioncomm->note_private = 'Error returned on payment id ' . $objpayid . ' after SEPA payment request ' . $objpaydesc . '<br>Error code is: ' . $objerrcode . '<br>Error message is: ' . $objerrmessage;
 		$actioncomm->label = 'Payment error (SEPA Stripe)';
 
 		$result = $actioncomm->create($user);
@@ -713,8 +778,8 @@
 	// TODO: create fees
 } elseif ($event->type == 'payment_method.attached') {
 	// When we link a payment method with a customer on Stripe side
-	require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php';
-	require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/societe/class/companypaymentmode.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/societe/class/societeaccount.class.php';
 	$societeaccount = new SocieteAccount($db);
 
 	$companypaymentmode = new CompanyPaymentMode($db);
@@ -762,9 +827,9 @@
 	}
 } elseif ($event->type == 'payment_method.updated') {
 	// When we update a payment method on Stripe side
-	require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/societe/class/companypaymentmode.class.php';
 	$companypaymentmode = new CompanyPaymentMode($db);
-	$companypaymentmode->fetch(0, '', 0, '', " AND stripe_card_ref = '".$db->escape($event->data->object->id)."'");
+	$companypaymentmode->fetch(0, '', 0, '', " AND stripe_card_ref = '" . $db->escape($event->data->object->id) . "'");
 	if ($companypaymentmode->id > 0) {
 		// If we found a payment mode with the ID
 		$companypaymentmode->bank            = null;
@@ -797,7 +862,7 @@
 } elseif ($event->type == 'payment_method.detached') {
 	// When we remove a payment method on Stripe side
 	$db->begin();
-	$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_rib WHERE number = '".$db->escape($event->data->object->id)."' and status = ".((int) $servicestatus);
+	$sql = "DELETE FROM " . MAIN_DB_PREFIX . "societe_rib WHERE number = '" . $db->escape($event->data->object->id) . "' and status = " . ((int) $servicestatus);
 	$db->query($sql);
 	$db->commit();
 } elseif ($event->type == 'charge.succeeded') {
@@ -808,10 +873,10 @@
 	// Deprecated.
 } elseif ($event->type == 'charge.dispute.closed') {
 	// When a dispute to cancel a SEPA payment is finished
-	dol_syslog("object = ".var_export($event->data, true));
+	dol_syslog("object = " . var_export($event->data, true));
 } elseif ($event->type == 'charge.dispute.funds_withdrawn') {
 	// When a dispute/withdraw to cancel a SEPA payment is done
-	dol_syslog("object = ".var_export($event->data, true));
+	dol_syslog("object = " . var_export($event->data, true));
 
 	global $stripearrayofkeysbyenv;
 	$error = 0;
@@ -833,12 +898,12 @@
 	$payment_amount = 0;
 	$payment_amountInDolibarr = 0;
 
-	dol_syslog("Try to find the payment in database for the payment_intent id = ".$TRANSACTIONID);
+	dol_syslog("Try to find the payment in database for the payment_intent id = " . $TRANSACTIONID);
 
 	$sql = "SELECT pi.rowid, pi.fk_facture, pi.fk_prelevement_bons, pi.amount, pi.type, pi.traite";
-	$sql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pi";
-	$sql .= " WHERE pi.ext_payment_id = '".$db->escape($TRANSACTIONID)."'";
-	$sql .= " AND pi.ext_payment_site = '".$db->escape($service)."'";
+	$sql .= " FROM " . MAIN_DB_PREFIX . "prelevement_demande as pi";
+	$sql .= " WHERE pi.ext_payment_id = '" . $db->escape($TRANSACTIONID) . "'";
+	$sql .= " AND pi.ext_payment_site = '" . $db->escape($service) . "'";
 
 	$result = $db->query($sql);
 	if ($result) {
@@ -852,7 +917,7 @@
 				$payment_amountInDolibarr = $obj->amount;
 				$paymentTypeCodeInDolibarr = $obj->type;
 
-				dol_syslog("Found the payment intent for ban in database (pdid = ".$pdid." directdebitorcreditransfer_id=".$directdebitorcreditransfer_id.")");
+				dol_syslog("Found the payment intent for ban in database (pdid = " . $pdid . " directdebitorcreditransfer_id=" . $directdebitorcreditransfer_id . ")");
 			}
 			if ($obj->type == 'card' || empty($obj->type)) {
 				// This is a card payment.
@@ -861,12 +926,12 @@
 				$payment_amountInDolibarr = $obj->amount;
 				$paymentTypeCodeInDolibarr = empty($obj->type) ? 'card' : $obj->type;
 
-				dol_syslog("Found the payment intent for card in database (pdid = ".$pdid." directdebitorcreditransfer_id=".$directdebitorcreditransfer_id.")");
+				dol_syslog("Found the payment intent for card in database (pdid = " . $pdid . " directdebitorcreditransfer_id=" . $directdebitorcreditransfer_id . ")");
 			}
 		} else {
-			dol_syslog("Payment intent ".$TRANSACTIONID." not found into database, so ignored.");
+			dol_syslog("Payment intent " . $TRANSACTIONID . " not found into database, so ignored.");
 			http_response_code(200);
-			print "Payment intent ".$TRANSACTIONID." not found into database, so ignored.";
+			print "Payment intent " . $TRANSACTIONID . " not found into database, so ignored.";
 			return 1;
 		}
 	} else {
@@ -875,16 +940,16 @@
 		return -1;
 	}
 
-	dol_syslog("objinvoiceid=".$invoice_id);
+	dol_syslog("objinvoiceid=" . $invoice_id);
 	$tmpinvoice = new Facture($db);
 	$tmpinvoice->fetch($invoice_id);
 	$tmpinvoice->fetch_thirdparty();
 
-	dol_syslog("The payment disputed is ".$amountdispute." and the invoice is ".$payment_amountInDolibarr);
+	dol_syslog("The payment disputed is " . $amountdispute . " and the invoice is " . $payment_amountInDolibarr);
 
 	if ($amountdispute != $payment_amountInDolibarr) {
 		http_response_code(500);
-		print "The payment disputed is ".$amountdispute." and the invoice is ".$payment_amountInDolibarr.". Amount differs, we don't know what to do.";
+		print "The payment disputed is " . $amountdispute . " and the invoice is " . $payment_amountInDolibarr . ". Amount differs, we don't know what to do.";
 		return -1;
 	}
 
@@ -905,7 +970,7 @@
 	*/
 	$paiement->paiementid   = dol_getIdFromCode($db, 'PRE', 'c_paiement', 'code', 'id', 1);
 	$paiement->num_payment  = $object->id;	// A string like 'du_...'
-	$paiement->note_public = 'Fund withdrawn by bank. Reason: '.$reason;
+	$paiement->note_public = 'Fund withdrawn by bank. Reason: ' . $reason;
 	$paiement->note_private = '';
 	$paiement->fk_account   = $accountfrom->id;
 
@@ -916,7 +981,7 @@
 	if ($alreadytransferedinaccounting) {
 		// TODO Test if invoice already in accountancy.
 		// What to do ?
-		$errormsg = 'Error: the invoice '.$tmpinvoice->id.' is already transferred into accounting. Don\'t know what to do.';
+		$errormsg = 'Error: the invoice ' . $tmpinvoice->id . ' is already transferred into accounting. Don\'t know what to do.';
 		$error++;
 	}
 
@@ -924,7 +989,7 @@
 		// Switch back the invoice to status validated
 		$result = $tmpinvoice->setStatut(Facture::STATUS_VALIDATED);
 		if ($result < 0) {
-			$errormsg = $tmpinvoice->error.implode(', ', $tmpinvoice->errors);
+			$errormsg = $tmpinvoice->error . implode(', ', $tmpinvoice->errors);
 			$error++;
 		}
 	}
@@ -932,7 +997,7 @@
 	if (! $error) {
 		$paiement_id = $paiement->create($user, 0, $tmpinvoice->thirdparty); // This include regenerating documents
 		if ($paiement_id < 0) {
-			$errormsg = $paiement->error.implode(', ', $paiement->errors);
+			$errormsg = $paiement->error . implode(', ', $paiement->errors);
 			$error++;
 		}
 	}

########## societe/class/societe.class.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/societe/class/societe.class.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/societe/class/societe.class.php	2025-02-27 08:48:52.570391000 +0000
@@ -4630,10 +4630,6 @@
 		$this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
 		$this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
 		$this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
-		$this->idprof7 = getDolGlobalString('MAIN_INFO_PROFID7');
-		$this->idprof8 = getDolGlobalString('MAIN_INFO_PROFID8');
-		$this->idprof9 = getDolGlobalString('MAIN_INFO_PROFID9');
-		$this->idprof10 = getDolGlobalString('MAIN_INFO_PROFID10');
 		$this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarily INTRA.
 		$this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
 		$this->capital = is_numeric(getDolGlobalString('MAIN_INFO_CAPITAL')) ? (float) price2num(getDolGlobalString('MAIN_INFO_CAPITAL')) : 0;

########## stripe/admin/stripe.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/stripe/admin/stripe.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/stripe/admin/stripe.php	2025-05-06 13:40:12.082202000 +0000
@@ -28,11 +28,11 @@
 
 // Load Dolibarr environment
 require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/stripe/lib/stripe.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
-require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
+require_once DOL_DOCUMENT_ROOT . '/stripe/lib/stripe.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
+require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
+require_once DOL_DOCUMENT_ROOT . '/stripe/class/stripe.class.php';
 
 $servicename = 'Stripe';
 
@@ -63,9 +63,19 @@
  */
 $error = 0;
 
+$stripeAccounts = array(
+	'ridin' => 'Ridin’Family',
+	'festi' => 'Festibike',
+);
+
+
+
 if ($action == 'setvalue' && $user->admin) {
+
+
 	$db->begin();
 
+
 	if (empty($conf->stripeconnect->enabled)) {
 		$result = dolibarr_set_const($db, "STRIPE_TEST_PUBLISHABLE_KEY", GETPOST('STRIPE_TEST_PUBLISHABLE_KEY', 'alpha'), 'chaine', 0, '', $conf->entity);
 		if (!($result > 0)) {
@@ -100,6 +110,24 @@
 			$error++;
 		}
 	}
+
+
+	//MODIF JOSE
+	$result = dolibarr_set_const($db, "STRIPE_AUTO_ADD_FEES_TO_BANK", GETPOST('STRIPE_AUTO_ADD_FEES_TO_BANK', 'int'), 'yesno', 0, '', $conf->entity);
+	if (!($result > 0)) $error++;
+
+	$date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int'));
+	$date_end = dol_mktime(23, 59, 59, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int'));
+
+	$result = dolibarr_set_const($db, "STRIPE_FEES_DATE_START", $date_start, 'chaine', 0, '', $conf->entity);
+	if (!($result > 0)) $error++;
+
+	$result = dolibarr_set_const($db, "STRIPE_FEES_DATE_END", $date_end, 'chaine', 0, '', $conf->entity);
+	if (!($result > 0)) $error++;
+
+	//END MODIF 
+
+
 	$result = dolibarr_set_const($db, "ONLINE_PAYMENT_CREDITOR", GETPOST('ONLINE_PAYMENT_CREDITOR', 'alpha'), 'chaine', 0, '', $conf->entity);
 	if (!($result > 0)) {
 		$error++;
@@ -168,6 +196,192 @@
 	}
 }
 
+
+if ($action == 'manual_reconcile_stripe_payments' && $user->admin) {
+
+	require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
+
+	$langs->load("bills");
+	$stripe = new Stripe($db);
+	$added = 0;
+	$options = [];
+
+	$service = (getDolGlobalString('STRIPE_LIVE') && !GETPOST('forcesandbox')) ? 'StripeLive' : 'StripeTest';
+	$stripeacc = $stripe->getStripeAccount($service);
+	if ($stripeacc) $options['stripe_account'] = $stripeacc;
+
+	try {
+		$txn_all = \Stripe\Charge::all(['limit' => 100], $options);
+		$date_start2 = dol_mktime(0, 0, 0, GETPOST('date_start2month', 'int'), GETPOST('date_start2day', 'int'), GETPOST('date_start2year', 'int'));
+		$date_end2 = dol_mktime(23, 59, 59, GETPOST('date_end2month', 'int'), GETPOST('date_end2day', 'int'), GETPOST('date_end2year', 'int'));
+
+
+		foreach ($txn_all->data as $txn) {
+
+
+			if (
+				(empty($date_start2) || $txn->created >= $date_start2) &&
+				(empty($date_end2) || $txn->created <= $date_end2)
+			) {
+
+				$ext_payment_id = $txn->payment_intent;
+
+
+				//Duplicate?
+				$sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "paiement WHERE ext_payment_id = '" . $db->escape($ext_payment_id) . "'";
+				$resql = $db->query($sql);
+				if ($resql && $db->num_rows($resql) > 0) continue;
+
+				$object_id = 0;
+
+
+
+				if (!empty($txn->metadata->dol_id)) {
+
+					$object_id = $txn->metadata->dol_id;
+
+
+
+					if ($txn->metadata->dol_type == "invoice" || $txn->metadata->dol_type == "facture") {
+						$object = new Facture($db);
+						if ($object->fetch($object_id) <= 0) continue;
+					} elseif ($txn->metadata->dol_type == "order" || $txn->metadata->dol_type == "commande") {
+						$object = new Commande($db);
+						if ($object->fetch($object_id) <= 0) continue;
+					}
+				}
+
+
+
+				if (!$object_id && !empty($txn->metadata->order_id)) {
+					require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
+					$refClient = '#' . $txn->metadata->order_id;
+					$object_id = trouverIdFactureParRefClient($refClient);
+				}
+
+				// $thirdparty_id = 0;
+				// if (!empty($txn->metadata->customer_email)) {
+				// 	$thirdparty_id = trouverIdTiersParEmail($txn->metadata->customer_email);
+				// }
+
+
+				if (!$object_id) {
+					continue;
+				}
+				$paiement = new Paiement($db);
+				$paiement->datepaye = dol_now();
+				$paiement->amounts = [$object->id => $txn->amount / 100];
+				$paiement->paiementid = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
+				if (empty($paiement->paiementid)) {
+					$paiement->paiementid = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
+				}
+				$paiement->ext_payment_id = $ext_payment_id;
+				$paiement->ext_payment_site = 'Stripe';
+				$paiement->note_public = 'Paiement Stripe réconcilié manuellement';
+				$paiement->num_payment = $ext_payment_id;
+
+				$db->begin();
+				if ($paiement->create($user) > 0) {
+					$bankaccountid = getDolGlobalInt('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
+					$label = '(CustomerInvoicePayment)';
+					if ($bankaccountid > 0) {
+						$res = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
+						if ($res > 0) {
+							$db->commit();
+							$added++;
+
+							setEventMessage("Paiement Stripe réconcilié pour la facture ID " . $object->id . " (Montant: " . price($txn->amount / 100, 0, '', 1, -1, -1, $txn->currency) . ")", 'mesgs');
+
+							dol_syslog("STRIPE RECONCILIATION: Paiement créé pour facture ID " . $object->id . ", ext_payment_id=" . $ext_payment_id . ", montant=" . ($txn->amount / 100) . " " . strtoupper($txn->currency), LOG_INFO);
+						} else {
+							dol_syslog("STRIPE RECONCILIATION ERROR: Échec de addPaymentToBank pour facture ID " . $object->id, LOG_ERR);
+							$db->rollback();
+						}
+					} else {
+						dol_syslog("STRIPE RECONCILIATION ERROR: Aucun compte bancaire Stripe défini", LOG_WARNING);
+						setEventMessage("Aucun compte bancaire Stripe défini", 'warnings');
+						$db->rollback();
+					}
+				} else {
+					dol_syslog("STRIPE RECONCILIATION ERROR: Échec de création du paiement pour la facture ID " . $object->id . ". Erreur: " . $paiement->error, LOG_ERR);
+					$db->rollback();
+				}
+			}
+		}
+		setEventMessage($langs->trans("StripeManualPaymentsAdded", $added), 'mesgs');
+	} catch (Exception $e) {
+		setEventMessage($e->getMessage(), 'errors');
+	}
+}
+
+
+if ($action == 'manual_update_stripe_fees' && $user->admin) {
+
+	require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/stripe/class/stripe.class.php';
+
+	$langs->load("stripe");
+
+	$stripe = new Stripe($db);
+	$form = new Form($db);
+
+	$fk_account_stripe = 5;
+
+	$date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int'));
+	$date_end = dol_mktime(23, 59, 59, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int'));
+
+	$added = 0;
+	$error = 0;
+	$logDetails = [];
+
+
+	try {
+		$service = (getDolGlobalString('STRIPE_LIVE') && !GETPOST('forcesandbox')) ? 'StripeLive' : 'StripeTest';
+		$stripeacc = $stripe->getStripeAccount($service);
+
+		$params = array('limit' => 100);
+		$options = $stripeacc ? array('stripe_account' => $stripeacc) : array();
+
+		$txn_all = \Stripe\BalanceTransaction::all($params, $options);
+
+		foreach ($txn_all->data as $txn) {
+			if ($txn->fee > 0) {
+				if (($txn->created >= $date_start) && ($txn->created <= $date_end)) {
+					$res = stripeAddPaymentFeeOnBank(
+						$txn->source,
+						$txn->fee / 100,
+						$fk_account_stripe,
+						$txn->id,
+						$txn->created,
+						$txn->created
+					);
+					if ($res > 0) {
+						$added++;
+						$logDetails[] = [
+							'date' => dol_print_date($txn->created, 'dayhour'),
+							'id' => $txn->id,
+							'amount' => price($txn->fee / 100, 0, '', 1, -1, -1, strtoupper($txn->currency)),
+						];
+					}
+				}
+			}
+		}
+
+		setEventMessage($langs->trans("StripeManualFeesAdded", $added), 'mesgs');
+
+		// Log et popup
+		if (!empty($logDetails)) {
+			foreach ($logDetails as $log) {
+				dol_syslog("Stripe fee added: " . $log['date'] . ' - ' . $log['id'] . ' : ' . $log['amount']);
+			}
+		}
+	} catch (Exception $e) {
+		setEventMessage($e->getMessage(), 'errors');
+	}
+}
+
 if ($action == "setlive") {
 	$liveenable = GETPOSTINT('value');
 	$res = dolibarr_set_const($db, "STRIPE_LIVE", $liveenable, 'yesno', 0, '', $conf->entity);
@@ -189,34 +403,34 @@
 
 llxHeader('', $langs->trans("StripeSetup"));
 
-$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
-print load_fiche_titre($langs->trans("ModuleSetup").' Stripe', $linkback);
+$linkback = '<a href="' . DOL_URL_ROOT . '/admin/modules.php?restore_lastsearch_values=1">' . $langs->trans("BackToModuleList") . '</a>';
+print load_fiche_titre($langs->trans("ModuleSetup") . ' Stripe', $linkback);
 
 $head = stripeadmin_prepare_head();
 
-print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
-print '<input type="hidden" name="token" value="'.newToken().'">';
+print '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '">';
+print '<input type="hidden" name="token" value="' . newToken() . '">';
 print '<input type="hidden" name="action" value="setvalue">';
 
 print dol_get_fiche_head($head, 'stripeaccount', '', -1);
 
 $stripearrayofwebhookevents = array('account.updated', 'payout.created', 'payout.paid', 'charge.pending', 'charge.refunded', 'charge.succeeded', 'charge.failed', 'payment_intent.succeeded', 'payment_intent.payment_failed', 'payment_method.attached', 'payment_method.updated', 'payment_method.card_automatically_updated', 'payment_method.detached', 'source.chargeable', 'customer.deleted');
 
-print '<span class="opacitymedium">'.$langs->trans("StripeDesc")."</span><br>\n";
+print '<span class="opacitymedium">' . $langs->trans("StripeDesc") . "</span><br>\n";
 
 print '<br>';
 
 print '<div class="div-table-responsive-no-min">';
 print '<table class="noborder centpercent">';
 print '<tr class="liste_titre">';
-print '<td>'.$langs->trans("AccountParameter").'</td>';
-print '<td>'.$langs->trans("Value").'</td>';
+print '<td>' . $langs->trans("AccountParameter") . '</td>';
+print '<td>' . $langs->trans("Value") . '</td>';
 print '<td></td>';
 print "</tr>\n";
 
 print '<tr class="oddeven">';
 print '<td>';
-print $langs->trans("StripeLiveEnabled").'</td><td>';
+print $langs->trans("StripeLiveEnabled") . '</td><td>';
 if ($conf->use_javascript_ajax) {
 	print ajax_constantonoff('STRIPE_LIVE');
 } else {
@@ -227,30 +441,30 @@
 
 if (empty($conf->stripeconnect->enabled)) {
 	print '<tr class="oddeven"><td>';
-	print '<span class="fieldrequired">'.$langs->trans("STRIPE_TEST_PUBLISHABLE_KEY").'</span></td><td>';
-	print '<input class="minwidth300" type="text" name="STRIPE_TEST_PUBLISHABLE_KEY" value="' . getDolGlobalString('STRIPE_TEST_PUBLISHABLE_KEY').'" placeholder="'.$langs->trans("Example").': pk_test_xxxxxxxxxxxxxxxxxxxxxxxx">';
+	print '<span class="fieldrequired">' . $langs->trans("STRIPE_TEST_PUBLISHABLE_KEY") . '</span></td><td>';
+	print '<input class="minwidth300" type="text" name="STRIPE_TEST_PUBLISHABLE_KEY" value="' . getDolGlobalString('STRIPE_TEST_PUBLISHABLE_KEY') . '" placeholder="' . $langs->trans("Example") . ': pk_test_xxxxxxxxxxxxxxxxxxxxxxxx">';
 	print '</td><td></td></tr>';
 
 	print '<tr class="oddeven"><td>';
-	print '<span class="titlefield fieldrequired">'.$langs->trans("STRIPE_TEST_SECRET_KEY").'</span></td><td>';
-	print '<input class="minwidth300" type="text" name="STRIPE_TEST_SECRET_KEY" value="' . getDolGlobalString('STRIPE_TEST_SECRET_KEY').'" placeholder="'.$langs->trans("Example").': sk_test_xxxxxxxxxxxxxxxxxxxxxxxx">';
+	print '<span class="titlefield fieldrequired">' . $langs->trans("STRIPE_TEST_SECRET_KEY") . '</span></td><td>';
+	print '<input class="minwidth300" type="text" name="STRIPE_TEST_SECRET_KEY" value="' . getDolGlobalString('STRIPE_TEST_SECRET_KEY') . '" placeholder="' . $langs->trans("Example") . ': sk_test_xxxxxxxxxxxxxxxxxxxxxxxx">';
 	print '</td><td></td></tr>';
 
 	print '<tr class="oddeven"><td>';
-	print '<span class="titlefield">'.$langs->trans("STRIPE_TEST_WEBHOOK_KEY").'</span></td><td>';
+	print '<span class="titlefield">' . $langs->trans("STRIPE_TEST_WEBHOOK_KEY") . '</span></td><td>';
 	if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {
-		print '<input class="minwidth300" type="text" name="STRIPE_TEST_WEBHOOK_ID" value="'.getDolGlobalString('STRIPE_TEST_WEBHOOK_ID').'" placeholder="'.$langs->trans("Example").': we_xxxxxxxxxxxxxxxxxxxxxxxx">';
+		print '<input class="minwidth300" type="text" name="STRIPE_TEST_WEBHOOK_ID" value="' . getDolGlobalString('STRIPE_TEST_WEBHOOK_ID') . '" placeholder="' . $langs->trans("Example") . ': we_xxxxxxxxxxxxxxxxxxxxxxxx">';
 		print '<br>';
 	}
-	print '<input class="minwidth300" type="text" name="STRIPE_TEST_WEBHOOK_KEY" value="'.getDolGlobalString('STRIPE_TEST_WEBHOOK_KEY').'" placeholder="'.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx">';
-	$out = img_picto('', 'globe').' <span class="opacitymedium">'.$langs->trans("ToOfferALinkForTestWebhook").'</span> ';
+	print '<input class="minwidth300" type="text" name="STRIPE_TEST_WEBHOOK_KEY" value="' . getDolGlobalString('STRIPE_TEST_WEBHOOK_KEY') . '" placeholder="' . $langs->trans("Example") . ': whsec_xxxxxxxxxxxxxxxxxxxxxxxx">';
+	$out = img_picto('', 'globe') . ' <span class="opacitymedium">' . $langs->trans("ToOfferALinkForTestWebhook") . '</span> ';
 	$url = dol_buildpath('/public/stripe/ipn.php', 3);
 	$url .= '?test=1';
 	//global $dolibarr_main_instance_unique_id;
 	//$url .= '&securitykey='.dol_hash('stripeipn-'.$dolibarr_main_instance_unique_id.'-'.$conf->global->STRIPE_TEST_PUBLISHABLE_KEY, 'md5');
-	$out .= '<input type="text" id="onlinetestwebhookurl" class="minwidth500" value="'.$url.'" disabled>';
+	$out .= '<input type="text" id="onlinetestwebhookurl" class="minwidth500" value="' . $url . '" disabled>';
 	$out .= ajax_autoselect("onlinetestwebhookurl");
-	print '<br>'.$out;
+	print '<br>' . $out;
 	print '</td><td>';
 	if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {
 		if (getDolGlobalString('STRIPE_TEST_WEBHOOK_KEY') && getDolGlobalString('STRIPE_TEST_SECRET_KEY') && getDolGlobalString('STRIPE_TEST_WEBHOOK_ID')) {
@@ -271,10 +485,10 @@
 					$endpoint->save();
 
 					if ($endpoint->status == 'enabled') {
-						print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=ipn&webhook='.$endpoint->id.'&status=0">';
+						print '<a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=ipn&webhook=' . $endpoint->id . '&status=0">';
 						print img_picto($langs->trans("Activated"), 'switch_on');
 					} else {
-						print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=ipn&webhook='.$endpoint->id.'&status=1">';
+						print '<a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=ipn&webhook=' . $endpoint->id . '&status=1">';
 						print img_picto($langs->trans("Disabled"), 'switch_off');
 					}
 				} catch (Exception $e) {
@@ -287,43 +501,93 @@
 			print img_picto($langs->trans("Inactive"), 'statut5');
 		}
 	}
-	print'</td></tr>';
-} else {
-	print '<tr class="oddeven"><td>'.$langs->trans("StripeConnect").'</td>';
-	print '<td><b>'.$langs->trans("StripeConnect_Mode").'</b><br>';
-	print $langs->trans("STRIPE_APPLICATION_FEE_PLATFORM").' ';
-	print price($conf->global->STRIPE_APPLICATION_FEE_PERCENT);
-	print '% + ';
-	print price($conf->global->STRIPE_APPLICATION_FEE);
-	print ' '.$langs->getCurrencySymbol($conf->currency).' '.$langs->trans("minimum").' '.price($conf->global->STRIPE_APPLICATION_FEE_MINIMAL).' '.$langs->getCurrencySymbol($conf->currency);
-	print '</td><td></td></tr>';
+	print '</td></tr>';
 }
 
+// 	//MODIF JOSE
+// if (empty($conf->stripeconnect->enabled)) {
+// 	foreach ($stripeAccounts as $code => $label) {
+// 		print '<tr class="liste_titre"><td colspan="3">' . $langs->trans("StripeAccountConfig") . ' (TEST) - ' . $label . '</td></tr>';
+
+// 		print '<tr class="oddeven"><td>' . $langs->trans("STRIPE_TEST_PUBLISHABLE_KEY") . '</td>';
+// 		print '<td class="right"><input class="minwidth300" type="text" name="STRIPE_TEST_PUBLISHABLE_KEY_' . strtoupper($code) . '" value="' . dol_escape_htmltag(getDolGlobalString('STRIPE_TEST_PUBLISHABLE_KEY_' . strtoupper($code))) . '"></td><td></td></tr>';
+
+// 		print '<tr class="oddeven"><td>' . $langs->trans("STRIPE_TEST_SECRET_KEY") . '</td>';
+// 		print '<td class="right"><input class="minwidth300" type="text" name="STRIPE_TEST_SECRET_KEY_' . strtoupper($code) . '" value="' . dol_escape_htmltag(getDolGlobalString('STRIPE_TEST_SECRET_KEY_' . strtoupper($code))) . '"></td><td></td></tr>';
+
+// 		print '<tr class="oddeven"><td>' . $langs->trans("STRIPE_TEST_WEBHOOK_KEY") . '</td>';
+// 		print '<td class="right">';
+// 		print '<input class="minwidth300" type="text" name="STRIPE_TEST_WEBHOOK_ID_' . strtoupper($code) . '" value="' . dol_escape_htmltag(getDolGlobalString('STRIPE_TEST_WEBHOOK_ID_' . strtoupper($code))) . '" placeholder="we_..."><br>';
+// 		print '<input class="minwidth300" type="text" name="STRIPE_TEST_WEBHOOK_KEY_' . strtoupper($code) . '" value="' . dol_escape_htmltag(getDolGlobalString('STRIPE_TEST_WEBHOOK_KEY_' . strtoupper($code))) . '" placeholder="whsec_...">';
+
+// 		$url = dol_buildpath('/public/stripe/ipn.php', 3) . '?test=1?account=' . $code;;
+// 		$out = img_picto('', 'globe') . ' <span class="opacitymedium">' . $langs->trans("ToOfferALinkForTestWebhook") . '</span> ';
+// 		$out .= '<input type="text" id="onlinetestwebhookurl_' . $code . '" class="minwidth500" value="' . $url . '" disabled>';
+// 		$out .= ajax_autoselect("onlinetestwebhookurl_" . $code);
+// 		print '<br>' . $out;
+// 		print '</td><td></td></tr>';
+// 	}
+// } else {
+// 	print '<tr class="oddeven"><td>' . $langs->trans("StripeConnect") . '</td>';
+// 	print '<td><b>' . $langs->trans("StripeConnect_Mode") . '</b><br>';
+// 	print $langs->trans("STRIPE_APPLICATION_FEE_PLATFORM") . ' ';
+// 	print price($conf->global->STRIPE_APPLICATION_FEE_PERCENT);
+// 	print '% + ';
+// 	print price($conf->global->STRIPE_APPLICATION_FEE);
+// 	print ' ' . $langs->getCurrencySymbol($conf->currency) . ' ' . $langs->trans("minimum") . ' ' . price($conf->global->STRIPE_APPLICATION_FEE_MINIMAL) . ' ' . $langs->getCurrencySymbol($conf->currency);
+// 	print '</td><td></td></tr>';
+// }
+
+// if (empty($conf->stripeconnect->enabled)) {
+// 	foreach ($stripeAccounts as $code => $label) {
+// 		print '<tr class="liste_titre"><td colspan="3">' . $langs->trans("StripeAccountConfig") . ' (LIVE) - ' . $label . '</td></tr>';
+
+// 		print '<tr class="oddeven"><td>' . $langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY") . '</td>';
+// 		print '<td class="right"><input class="minwidth300" type="text" name="STRIPE_LIVE_PUBLISHABLE_KEY_' . strtoupper($code) . '" value="' . dol_escape_htmltag(getDolGlobalString('STRIPE_LIVE_PUBLISHABLE_KEY_' . strtoupper($code))) . '"></td><td></td></tr>';
+
+// 		print '<tr class="oddeven"><td>' . $langs->trans("STRIPE_LIVE_SECRET_KEY") . '</td>';
+// 		print '<td class="right"><input class="minwidth300" type="text" name="STRIPE_LIVE_SECRET_KEY_' . strtoupper($code) . '" value="' . dol_escape_htmltag(getDolGlobalString('STRIPE_LIVE_SECRET_KEY_' . strtoupper($code))) . '"></td><td></td></tr>';
+
+// 		print '<tr class="oddeven"><td>' . $langs->trans("STRIPE_LIVE_WEBHOOK_KEY") . '</td>';
+// 		print '<td class="right">';
+// 		print '<input class="minwidth300" type="text" name="STRIPE_LIVE_WEBHOOK_ID_' . strtoupper($code) . '" value="' . dol_escape_htmltag(getDolGlobalString('STRIPE_LIVE_WEBHOOK_ID_' . strtoupper($code))) . '" placeholder="we_..."><br>';
+// 		print '<input class="minwidth300" type="text" name="STRIPE_LIVE_WEBHOOK_KEY_' . strtoupper($code) . '" value="' . dol_escape_htmltag(getDolGlobalString('STRIPE_LIVE_WEBHOOK_KEY_' . strtoupper($code))) . '" placeholder="whsec_...">';
+
+// 		$url = dol_buildpath('/public/stripe/ipn.php', 3) . '?account=' . $code;
+// 		$out = img_picto('', 'globe') . ' <span class="opacitymedium">' . $langs->trans("ToOfferALinkForLiveWebhook") . '</span> ';
+// 		$out .= '<input type="text" id="onlinelivewebhookurl_' . $code . '" class="minwidth500" value="' . $url . '" disabled>';
+// 		$out .= ajax_autoselect("onlinelivewebhookurl_" . $code);
+// 		print '<br>' . $out;
+// 		print '</td><td></td></tr>';
+// 	}
+// }
+
+
 if (empty($conf->stripeconnect->enabled)) {
 	print '<tr class="oddeven"><td>';
-	print '<span class="fieldrequired">'.$langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY").'</span></td><td>';
-	print '<input class="minwidth300" type="text" name="STRIPE_LIVE_PUBLISHABLE_KEY" value="'.getDolGlobalString('STRIPE_LIVE_PUBLISHABLE_KEY').'" placeholder="'.$langs->trans("Example").': pk_live_xxxxxxxxxxxxxxxxxxxxxxxx">';
+	print '<span class="fieldrequired">' . $langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY") . '</span></td><td>';
+	print '<input class="minwidth300" type="text" name="STRIPE_LIVE_PUBLISHABLE_KEY" value="' . getDolGlobalString('STRIPE_LIVE_PUBLISHABLE_KEY') . '" placeholder="' . $langs->trans("Example") . ': pk_live_xxxxxxxxxxxxxxxxxxxxxxxx">';
 	print '</td><td></td></tr>';
 
 	print '<tr class="oddeven"><td>';
-	print '<span class="fieldrequired">'.$langs->trans("STRIPE_LIVE_SECRET_KEY").'</span></td><td>';
-	print '<input class="minwidth300" type="text" name="STRIPE_LIVE_SECRET_KEY" value="'.getDolGlobalString('STRIPE_LIVE_SECRET_KEY').'" placeholder="'.$langs->trans("Example").': sk_live_xxxxxxxxxxxxxxxxxxxxxxxx">';
+	print '<span class="fieldrequired">' . $langs->trans("STRIPE_LIVE_SECRET_KEY") . '</span></td><td>';
+	print '<input class="minwidth300" type="text" name="STRIPE_LIVE_SECRET_KEY" value="' . getDolGlobalString('STRIPE_LIVE_SECRET_KEY') . '" placeholder="' . $langs->trans("Example") . ': sk_live_xxxxxxxxxxxxxxxxxxxxxxxx">';
 	print '</td><td></td></tr>';
 
 	print '<tr class="oddeven"><td>';
-	print '<span class="titlefield">'.$langs->trans("STRIPE_LIVE_WEBHOOK_KEY").'</span></td><td>';
+	print '<span class="titlefield">' . $langs->trans("STRIPE_LIVE_WEBHOOK_KEY") . '</span></td><td>';
 	if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {
-		print '<input class="minwidth300" type="text" name="STRIPE_LIVE_WEBHOOK_ID" value="'.getDolGlobalString('STRIPE_LIVE_WEBHOOK_ID').'" placeholder="'.$langs->trans("Example").': we_xxxxxxxxxxxxxxxxxxxxxxxx">';
+		print '<input class="minwidth300" type="text" name="STRIPE_LIVE_WEBHOOK_ID" value="' . getDolGlobalString('STRIPE_LIVE_WEBHOOK_ID') . '" placeholder="' . $langs->trans("Example") . ': we_xxxxxxxxxxxxxxxxxxxxxxxx">';
 		print '<br>';
 	}
-	print '<input class="minwidth300" type="text" name="STRIPE_LIVE_WEBHOOK_KEY" value="'.getDolGlobalString('STRIPE_LIVE_WEBHOOK_KEY').'" placeholder="'.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx">';
-	$out = img_picto('', 'globe', 'class="pictofixedwidth"').' <span class="opacitymedium">'.$langs->trans("ToOfferALinkForLiveWebhook").'</span> ';
+	print '<input class="minwidth300" type="text" name="STRIPE_LIVE_WEBHOOK_KEY" value="' . getDolGlobalString('STRIPE_LIVE_WEBHOOK_KEY') . '" placeholder="' . $langs->trans("Example") . ': whsec_xxxxxxxxxxxxxxxxxxxxxxxx">';
+	$out = img_picto('', 'globe', 'class="pictofixedwidth"') . ' <span class="opacitymedium">' . $langs->trans("ToOfferALinkForLiveWebhook") . '</span> ';
 	$url = dol_buildpath('/public/stripe/ipn.php', 3);
 	//global $dolibarr_main_instance_unique_id;
 	//$url .= '?securitykey='.dol_hash('stripeipn-'.$dolibarr_main_instance_unique_id.'-'.$conf->global->STRIPE_LIVE_PUBLISHABLE_KEY, 'md5');
-	$out .= '<input type="text" id="onlinelivewebhookurl" class="minwidth500" value="'.$url.'" disabled>';
+	$out .= '<input type="text" id="onlinelivewebhookurl" class="minwidth500" value="' . $url . '" disabled>';
 	$out .= ajax_autoselect("onlinelivewebhookurl", '0');
-	print '<br>'.$out;
+	print '<br>' . $out;
 	print '</td><td>';
 	if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {
 		if (getDolGlobalString('STRIPE_LIVE_WEBHOOK_KEY') && getDolGlobalString('STRIPE_LIVE_SECRET_KEY') && getDolGlobalString('STRIPE_LIVE_WEBHOOK_ID')) {
@@ -343,10 +607,10 @@
 					// @phan-suppress-next-line PhanDeprecatedFunction
 					$endpoint->save();
 					if ($endpoint->status == 'enabled') {
-						print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=ipn&webhook='.$endpoint->id.'&status=0">';
+						print '<a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=ipn&webhook=' . $endpoint->id . '&status=0">';
 						print img_picto($langs->trans("Activated"), 'switch_on');
 					} else {
-						print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=ipn&webhook='.$endpoint->id.'&status=1">';
+						print '<a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=ipn&webhook=' . $endpoint->id . '&status=1">';
 						print img_picto($langs->trans("Disabled"), 'switch_off');
 					}
 				} catch (Exception $e) {
@@ -369,18 +633,18 @@
 print '<div class="div-table-responsive-no-min">';
 print '<table class="noborder centpercent">';
 print '<tr class="liste_titre">';
-print '<td>'.$langs->trans("UsageParameter").'</td>';
-print '<td>'.$langs->trans("Value").'</td>';
+print '<td>' . $langs->trans("UsageParameter") . '</td>';
+print '<td>' . $langs->trans("Value") . '</td>';
 print "</tr>\n";
 
 print '<tr class="oddeven"><td>';
-print $langs->trans("PublicVendorName").'</td><td>';
-print '<input class="minwidth300" type="text" name="ONLINE_PAYMENT_CREDITOR" value="'.getDolGlobalString('ONLINE_PAYMENT_CREDITOR').'">';
-print ' &nbsp; <span class="opacitymedium">'.$langs->trans("Example").': '.$mysoc->name.'</span>';
+print $langs->trans("PublicVendorName") . '</td><td>';
+print '<input class="minwidth300" type="text" name="ONLINE_PAYMENT_CREDITOR" value="' . getDolGlobalString('ONLINE_PAYMENT_CREDITOR') . '">';
+print ' &nbsp; <span class="opacitymedium">' . $langs->trans("Example") . ': ' . $mysoc->name . '</span>';
 print '</td></tr>';
 
 print '<tr class="oddeven"><td>';
-print $langs->trans("BankAccount").'</td><td>';
+print $langs->trans("BankAccount") . '</td><td>';
 print img_picto('', 'bank_account', 'class="pictofixedwidth"');
 $form->select_comptes(getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS'), 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1);
 print '</td></tr>';
@@ -388,7 +652,7 @@
 
 // Param to record automatically payouts (received from IPN payout.paid and payout.created)
 print '<tr class="oddeven"><td>';
-print $langs->trans("StripeAutoRecordPayout").'</td><td>';
+print $langs->trans("StripeAutoRecordPayout") . '</td><td>';
 if ($conf->use_javascript_ajax) {
 	print ajax_constantonoff('STRIPE_AUTO_RECORD_PAYOUT', array(), null, 0, 0, 1);
 } else {
@@ -399,12 +663,12 @@
 
 if (getDolGlobalInt('STRIPE_AUTO_RECORD_PAYOUT')) {
 	print '<tr class="oddeven"><td>';
-	print $langs->trans("StripeUserAccountForActions").'</td><td>';
-	print img_picto('', 'user', 'class="pictofixedwidth"').$form->select_dolusers(getDolGlobalString('STRIPE_USER_ACCOUNT_FOR_ACTIONS'), 'STRIPE_USER_ACCOUNT_FOR_ACTIONS', 0);
+	print $langs->trans("StripeUserAccountForActions") . '</td><td>';
+	print img_picto('', 'user', 'class="pictofixedwidth"') . $form->select_dolusers(getDolGlobalString('STRIPE_USER_ACCOUNT_FOR_ACTIONS'), 'STRIPE_USER_ACCOUNT_FOR_ACTIONS', 0);
 	print '</td></tr>';
 
 	print '<tr class="oddeven"><td>';
-	print $langs->trans("BankAccountForBankTransfer").'</td><td>';
+	print $langs->trans("BankAccountForBankTransfer") . '</td><td>';
 	print img_picto('', 'bank_account', 'class="pictofixedwidth"');
 	$form->select_comptes(getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS'), 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1);
 	print '</td></tr>';
@@ -413,7 +677,7 @@
 // Card Present for Stripe Terminal
 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {	// TODO Not used by current code
 	print '<tr class="oddeven"><td>';
-	print $langs->trans("STRIPE_CARD_PRESENT").'</td><td>';
+	print $langs->trans("STRIPE_CARD_PRESENT") . '</td><td>';
 	if ($conf->use_javascript_ajax) {
 		print ajax_constantonoff('STRIPE_CARD_PRESENT');
 	} else {
@@ -426,7 +690,7 @@
 // Locations for Stripe Terminal
 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {	// TODO Not used by current code
 	print '<tr class="oddeven"><td>';
-	print $langs->trans("TERMINAL_LOCATION").'</td><td>';
+	print $langs->trans("TERMINAL_LOCATION") . '</td><td>';
 	$service = 'StripeTest';
 	$servicestatus = 0;
 	if (getDolGlobalString('STRIPE_LIVE') && !GETPOST('forcesandbox', 'alpha')) {
@@ -459,7 +723,7 @@
 			}
 		}
 	} catch (Exception $e) {
-		print $e->getMessage().'<br>';
+		print $e->getMessage() . '<br>';
 	}
 
 	// Define the array $location
@@ -476,7 +740,7 @@
 }
 
 print '<tr class="oddeven"><td>';
-print $langs->trans("STRIPE_SEPA_DIRECT_DEBIT").'</td><td>';
+print $langs->trans("STRIPE_SEPA_DIRECT_DEBIT") . '</td><td>';
 if ($conf->use_javascript_ajax) {
 	print ajax_constantonoff('STRIPE_SEPA_DIRECT_DEBIT');
 } else {
@@ -489,7 +753,7 @@
 // Activate Klarna
 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {	// TODO Not used by current code
 	print '<tr class="oddeven"><td>';
-	print $langs->trans("STRIPE_KLARNA").'</td><td>';
+	print $langs->trans("STRIPE_KLARNA") . '</td><td>';
 	if ($conf->use_javascript_ajax) {
 		print ajax_constantonoff('STRIPE_KLARNA');
 	} else {
@@ -502,88 +766,88 @@
 // Activate Bancontact
 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {	// TODO Not used by current code
 	print '<tr class="oddeven"><td>';
-	print $langs->trans("STRIPE_BANCONTACT").'</td><td>';
+	print $langs->trans("STRIPE_BANCONTACT") . '</td><td>';
 	if ($conf->use_javascript_ajax) {
 		print ajax_constantonoff('STRIPE_BANCONTACT');
 	} else {
 		$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
 		print $form->selectarray("STRIPE_BANCONTACT", $arrval, $conf->global->STRIPE_BANCONTACT);
 	}
-	print ' &nbsp; <span class="opacitymedium">'.$langs->trans("ExampleOnlyForBECustomers").'</span>';
+	print ' &nbsp; <span class="opacitymedium">' . $langs->trans("ExampleOnlyForBECustomers") . '</span>';
 	print '</td></tr>';
 }
 
 // Activate iDEAL
 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {	// TODO Not used by current code
 	print '<tr class="oddeven"><td>';
-	print $langs->trans("STRIPE_IDEAL").'</td><td>';
+	print $langs->trans("STRIPE_IDEAL") . '</td><td>';
 	if ($conf->use_javascript_ajax) {
 		print ajax_constantonoff('STRIPE_IDEAL');
 	} else {
 		$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
 		print $form->selectarray("STRIPE_IDEAL", $arrval, $conf->global->STRIPE_SEPA_DIRECT_DEBIT);
 	}
-	print ' &nbsp; <span class="opacitymedium">'.$langs->trans("ExampleOnlyForNLCustomers").'</span>';
+	print ' &nbsp; <span class="opacitymedium">' . $langs->trans("ExampleOnlyForNLCustomers") . '</span>';
 	print '</td></tr>';
 }
 
 // Activate Giropay
 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {	// TODO Not used by current code
 	print '<tr class="oddeven"><td>';
-	print $langs->trans("STRIPE_GIROPAY").'</td><td>';
+	print $langs->trans("STRIPE_GIROPAY") . '</td><td>';
 	if ($conf->use_javascript_ajax) {
 		print ajax_constantonoff('STRIPE_GIROPAY');
 	} else {
 		$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
 		print $form->selectarray("STRIPE_GIROPAY", $arrval, $conf->global->STRIPE_GIROPAY);
 	}
-	print ' &nbsp; <span class="opacitymedium">'.$langs->trans("ExampleOnlyForDECustomers").'</span>';
+	print ' &nbsp; <span class="opacitymedium">' . $langs->trans("ExampleOnlyForDECustomers") . '</span>';
 	print '</td></tr>';
 }
 
 // Activate Sofort
 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) {	// TODO Not used by current code
 	print '<tr class="oddeven"><td>';
-	print $langs->trans("STRIPE_SOFORT").'</td><td>';
+	print $langs->trans("STRIPE_SOFORT") . '</td><td>';
 	if ($conf->use_javascript_ajax) {
 		print ajax_constantonoff('STRIPE_SOFORT');
 	} else {
 		$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
 		print $form->selectarray("STRIPE_SOFORT", $arrval, $conf->global->STRIPE_SOFORT);
 	}
-	print ' &nbsp; <span class="opacitymedium">'.$langs->trans("ExampleOnlyForATBEDEITNLESCustomers").'</span>';
+	print ' &nbsp; <span class="opacitymedium">' . $langs->trans("ExampleOnlyForATBEDEITNLESCustomers") . '</span>';
 	print '</td></tr>';
 }
 
 print '<tr class="oddeven"><td>';
-print $langs->trans("CSSUrlForPaymentForm").'</td><td>';
-print '<input class="width500" type="text" name="ONLINE_PAYMENT_CSS_URL" value="' . getDolGlobalString('ONLINE_PAYMENT_CSS_URL').'">';
-print ' &nbsp; <span class="opacitymedium">'.$langs->trans("Example").': http://mysite/mycss.css</span>';
+print $langs->trans("CSSUrlForPaymentForm") . '</td><td>';
+print '<input class="width500" type="text" name="ONLINE_PAYMENT_CSS_URL" value="' . getDolGlobalString('ONLINE_PAYMENT_CSS_URL') . '">';
+print ' &nbsp; <span class="opacitymedium">' . $langs->trans("Example") . ': http://mysite/mycss.css</span>';
 print '</td></tr>';
 
 print '<tr class="oddeven"><td>';
-print $langs->trans("MessageForm").'</td><td>';
+print $langs->trans("MessageForm") . '</td><td>';
 $doleditor = new DolEditor('ONLINE_PAYMENT_MESSAGE_FORM', getDolGlobalString("ONLINE_PAYMENT_MESSAGE_FORM"), '', 100, 'dolibarr_details', 'In', false, true, true, ROWS_2, '90%');
 $doleditor->Create();
 print '</td></tr>';
 
 print '<tr class="oddeven"><td>';
-print $langs->trans("MessageOK").'</td><td>';
+print $langs->trans("MessageOK") . '</td><td>';
 $doleditor = new DolEditor('ONLINE_PAYMENT_MESSAGE_OK', getDolGlobalString("ONLINE_PAYMENT_MESSAGE_OK"), '', 100, 'dolibarr_details', 'In', false, true, true, ROWS_2, '90%');
 $doleditor->Create();
 print '</td></tr>';
 
 print '<tr class="oddeven"><td>';
-print $langs->trans("MessageKO").'</td><td>';
+print $langs->trans("MessageKO") . '</td><td>';
 $doleditor = new DolEditor('ONLINE_PAYMENT_MESSAGE_KO', getDolGlobalString("ONLINE_PAYMENT_MESSAGE_KO"), '', 100, 'dolibarr_details', 'In', false, true, true, ROWS_2, '90%');
 $doleditor->Create();
 print '</td></tr>';
 
 print '<tr class="oddeven"><td>';
-print $langs->trans("ONLINE_PAYMENT_SENDEMAIL").'</td><td>';
+print $langs->trans("ONLINE_PAYMENT_SENDEMAIL") . '</td><td>';
 print img_picto('', 'email', 'class="pictofixedwidth"');
-print '<input class="minwidth200" type="text" name="ONLINE_PAYMENT_SENDEMAIL" value="' . getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL').'">';
-print ' &nbsp; <span class="opacitymedium">'.$langs->trans("Example").': myemail@myserver.com, Payment service &lt;myemail2@myserver2.com&gt;</span>';
+print '<input class="minwidth200" type="text" name="ONLINE_PAYMENT_SENDEMAIL" value="' . getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL') . '">';
+print ' &nbsp; <span class="opacitymedium">' . $langs->trans("Example") . ': myemail@myserver.com, Payment service &lt;myemail2@myserver2.com&gt;</span>';
 print '</td></tr>';
 
 print '</table>';
@@ -595,16 +859,16 @@
 print '<table class="noborder centpercent">';
 
 print '<tr class="liste_titre">';
-print '<td>'.$langs->trans("UrlGenerationParameters").'</td>';
-print '<td>'.$langs->trans("Value").'</td>';
+print '<td>' . $langs->trans("UrlGenerationParameters") . '</td>';
+print '<td>' . $langs->trans("Value") . '</td>';
 print "</tr>\n";
 
 // Payment token for URL
 print '<tr class="oddeven"><td>';
-print $langs->trans("SecurityToken").'</td><td>';
-print '<input class="minwidth300"  type="text" id="PAYMENT_SECURITY_TOKEN" name="PAYMENT_SECURITY_TOKEN" value="' . getDolGlobalString('PAYMENT_SECURITY_TOKEN').'">';
+print $langs->trans("SecurityToken") . '</td><td>';
+print '<input class="minwidth300"  type="text" id="PAYMENT_SECURITY_TOKEN" name="PAYMENT_SECURITY_TOKEN" value="' . getDolGlobalString('PAYMENT_SECURITY_TOKEN') . '">';
 if (!empty($conf->use_javascript_ajax)) {
-	print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"');
+	print '&nbsp;' . img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"');
 }
 if (getDolGlobalString('PAYMENT_SECURITY_ACCEPT_ANY_TOKEN')) {
 	$langs->load("errors");
@@ -613,7 +877,7 @@
 print '</td></tr>';
 
 print '<tr class="oddeven"><td>';
-print $langs->trans("SecurityTokenIsUnique").'</td><td>';
+print $langs->trans("SecurityTokenIsUnique") . '</td><td>';
 if ($conf->use_javascript_ajax) {
 	print ajax_constantonoff('PAYMENT_SECURITY_TOKEN_UNIQUE', array(), null, 0, 0, 1);
 } else {
@@ -622,6 +886,26 @@
 }
 print '</td></tr>';
 
+
+
+
+
+//MODIF JOSE
+// $date_start = getDolGlobalInt('STRIPE_FEES_DATE_START');
+// $date_end = getDolGlobalInt('STRIPE_FEES_DATE_END');
+
+
+// print '<tr class="oddeven"><td>';
+// print $langs->trans("StartDateForFeesImport") . '</td><td>';
+// print $form->selectDate($date_start ? $date_start : '', 'date_start', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
+// print '</td></tr>';
+
+// print '<tr class="oddeven"><td>';
+// print $langs->trans("EndDateForFeesImport") . '</td><td>';
+// print $form->selectDate($date_end ? $date_end : '', 'date_end', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
+// print '</td></tr>';
+//END MODIF
+
 print '</table>';
 print '</div>';
 
@@ -633,21 +917,102 @@
 
 print '<br><br>';
 
+print '<div class="div-table-responsive-no-min">';
+print '<table class="noborder centpercent">';
+
+$date_start = GETPOSTISSET('date_startday') ? dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int')) : getDolGlobalInt('STRIPE_FEES_DATE_START');
+$date_end = GETPOSTISSET('date_endday') ? dol_mktime(23, 59, 59, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int')) : getDolGlobalInt('STRIPE_FEES_DATE_END');
+
+print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';
+print '<input type="hidden" name="token" value="' . newToken() . '">';
+print '<input type="hidden" name="action" value="manual_update_stripe_fees">';
+
+
+print '<tr class="liste_titre">';
+print '<td>' . $langs->trans("Update des fees") . '</td>';
+print '<td class="right">' . $langs->trans("Valeur") . '</td>';
+print "</tr>\n";
+
+print '<tr class="oddeven"><td>';
+print $langs->trans("StripeAutoAddFeesToBank") . '<td class="right">';
+if ($conf->use_javascript_ajax) {
+	print ajax_constantonoff('STRIPE_AUTO_ADD_FEES_TO_BANK', array(), null, 0, 0, 1);
+} else {
+	$arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes"));
+	print $form->selectarray("STRIPE_AUTO_ADD_FEES_TO_BANK", $arrval, getDolGlobalInt('STRIPE_AUTO_ADD_FEES_TO_BANK'));
+}
+print '</td></tr>';
+
+if (getDolGlobalInt('STRIPE_AUTO_ADD_FEES_TO_BANK')) {
+
+	print '<tr class="oddeven">';
+	print '<td>' . $langs->trans("PeriodeToUpdate") . '</td>';
+	print '<td class="right">';
+
+	print '<span style="margin-right: 10px;">' . $langs->trans("DateStart") . '</span>';
+	print $form->selectDate($date_start ?: '', 'date_start', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
+
+
+	print '<span style="margin-right: 10px;">' . $langs->trans("DateEnd") . '</span>';
+	print $form->selectDate($date_end ?: '', 'date_end', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
+
+	print '<input type="submit" class="button" value="' . $langs->trans("UpdateFees") . '">';
+
+
+	print '</td>';
+	print '</tr>';
+}
+
+print '</form>';
+
+$date_start2 = dol_mktime(0, 0, 0, GETPOST('date_start2month', 'int'), GETPOST('date_start2day', 'int'), GETPOST('date_start2year', 'int'));
+$date_end2 = dol_mktime(23, 59, 59, GETPOST('date_end2month', 'int'), GETPOST('date_end2day', 'int'), GETPOST('date_end2year', 'int'));
+
+
+print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';
+print '<input type="hidden" name="token" value="' . newToken() . '">';
+print '<input type="hidden" name="action" value="manual_reconcile_stripe_payments">';
+
+print '<tr class="oddeven">';
+print '<td>' . $langs->trans("PeriodeToreconciliate") . '</td>';
+print '<td class="right">';
+
+
+print '<span style="margin-right: 10px;">' . $langs->trans("DateStart") . '</span>';
+print $form->selectDate($date_start2 ?: '', 'date_start2', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
+
+print '<span style="margin-right: 10px;">' . $langs->trans("DateEnd") . '</span>';
+print $form->selectDate($date_end2 ?: '', 'date_end2', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzserver');
+
+print '<input type="submit" class="button" value="' . $langs->trans("ReconcileButton") . '">';
+print '</td>';
+print '</tr>';
+print '</form>';
+
+
+
+print '</table>';
+print '</div>';
+
+
+
+print '<br><br>';
+
 
 $token = '';
 
-include DOL_DOCUMENT_ROOT.'/core/tpl/onlinepaymentlinks.tpl.php';
+include DOL_DOCUMENT_ROOT . '/core/tpl/onlinepaymentlinks.tpl.php';
 
-print info_admin($langs->trans("ExampleOfTestCreditCard", '4242424242424242 (no 3DSecure) or 4000000000003063 (3DSecure required) or 4000002760003184 (3DSecure2 required on all transaction) or 4000003800000446 (3DSecure2 required, the off-session allowed)', '4000000000000101', '4000000000000069', '4000000000000341').'. '.$langs->trans('SeeAlso', 'https://docs.stripe.com/testing?testing-method=card-numbers'));
+print info_admin($langs->trans("ExampleOfTestCreditCard", '4242424242424242 (no 3DSecure) or 4000000000003063 (3DSecure required) or 4000002760003184 (3DSecure2 required on all transaction) or 4000003800000446 (3DSecure2 required, the off-session allowed)', '4000000000000101', '4000000000000069', '4000000000000341') . '. ' . $langs->trans('SeeAlso', 'https://docs.stripe.com/testing?testing-method=card-numbers'));
 
 if (getDolGlobalString('STRIPE_SEPA_DIRECT_DEBIT')) {
-	print info_admin($langs->trans("ExampleOfTestBankAcountForSEPA", 'AT611904300234573201 (pending->succeed) or AT861904300235473202 (pending->failed)').'. '.$langs->trans('SeeAlso', 'https://docs.stripe.com/testing?payment-method=sepa-direct-debit'));
+	print info_admin($langs->trans("ExampleOfTestBankAcountForSEPA", 'AT611904300234573201 (pending->succeed) or AT861904300235473202 (pending->failed)') . '. ' . $langs->trans('SeeAlso', 'https://docs.stripe.com/testing?payment-method=sepa-direct-debit'));
 }
 
 
 
 if (!empty($conf->use_javascript_ajax)) {
-	print "\n".'<script type="text/javascript">';
+	print "\n" . '<script type="text/javascript">';
 	print '$(document).ready(function () {
 	            $("#apidoc").hide();
 	            $("#apidoca").click(function() {

########## stripe/charge.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/stripe/charge.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/stripe/charge.php	2025-03-26 09:08:29.319289000 +0000
@@ -21,15 +21,15 @@
 
 // Load Dolibarr environment
 require '../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
-require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
-require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
+require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
+require_once DOL_DOCUMENT_ROOT . '/stripe/class/stripe.class.php';
 //require_once DOL_DOCUMENT_ROOT.'/core/lib/stripe.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
+require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
 if (isModEnabled('accounting')) {
-	require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
 }
 
 /**
@@ -100,28 +100,28 @@
 	$totalnboflines = '';
 	$moreforfilter = '';
 	$list = null;
-	if (GETPOSTISSET('starting_after_'.$page)) {
-		$option['starting_after'] = GETPOST('starting_after_'.$page, 'alphanohtml');
+	if (GETPOSTISSET('starting_after_' . $page)) {
+		$option['starting_after'] = GETPOST('starting_after_' . $page, 'alphanohtml');
 	}
-	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
+	print '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '">';
 	if ($optioncss != '') {
-		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+		print '<input type="hidden" name="optioncss" value="' . $optioncss . '">';
 	}
 
-	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="token" value="' . newToken() . '">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="action" value="list">';
-	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
-	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
-	print '<input type="hidden" name="page" value="'.$page.'">';
+	print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
+	print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
+	print '<input type="hidden" name="page" value="' . $page . '">';
 
 	$title = $langs->trans("StripeChargeList");
-	$title .= ($stripeacc ? ' (Stripe connection with Stripe OAuth Connect account '.$stripeacc.')' : ' (Stripe connection with keys from Stripe module setup)');
+	$title .= ($stripeacc ? ' (Stripe connection with Stripe OAuth Connect account ' . $stripeacc . ')' : ' (Stripe connection with keys from Stripe module setup)');
 
 	print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'title_accountancy.png', 0, '', 'hidepaginationprevious', $limit);
 
 	print '<div class="div-table-responsive">';
-	print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
+	print '<table class="tagtable liste' . ($moreforfilter ? " listwithfilterbefore" : "") . '">' . "\n";
 
 	print '<tr class="liste_titre">';
 	print_liste_field_titre("StripePaymentId", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder);
@@ -147,18 +147,21 @@
 
 		//if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
 		if ($limit > 0 && $limit != $conf->liste_limit) {
-			$param .= '&limit='.((int) $limit);
+			$param .= '&limit=' . ((int) $limit);
 		}
-		$param .= '&starting_after_'.($page + 1).'='.$list->data[($limit - 1)]->id;
+		$param .= '&starting_after_' . ($page + 1) . '=' . $list->data[($limit - 1)]->id;
 		//$param.='&ending_before_'.($page+1).'='.$list->data[($limit-1)]->id;
 	} catch (Exception $e) {
-		print '<tr><td colspan="8">'.$e->getMessage().'</td></td>';
+		print '<tr><td colspan="8">' . $e->getMessage() . '</td></td>';
 	}
 
 	//print $list;
 	$i = 0;
 	if (!empty($list)) {
 		foreach ($list->data as $charge) {
+
+			
+
 			'@phan-var-force \Stripe\Charge $charge';  // TStripeObject suggested, but is a template
 			if ($i >= $limit) {
 				break;
@@ -169,9 +172,9 @@
 			} elseif ($charge->paid == '1') {
 				$status = img_picto($langs->trans((string) $charge->status), 'statut4');
 			} else {
-				$label = $langs->trans("Message").": ".$charge->failure_message."<br>";
-				$label .= $langs->trans("Network").": ".$charge->outcome->network_status."<br>";
-				$label .= $langs->trans("Status").": ".$langs->trans((string) $charge->outcome->seller_message);
+				$label = $langs->trans("Message") . ": " . $charge->failure_message . "<br>";
+				$label .= $langs->trans("Network") . ": " . $charge->outcome->network_status . "<br>";
+				$label .= $langs->trans("Status") . ": " . $langs->trans((string) $charge->outcome->seller_message);
 				$status = $form->textwithpicto(img_picto($langs->trans((string) $charge->status), 'statut8'), $label, -1);
 			}
 
@@ -218,34 +221,35 @@
 			print '<tr class="oddeven">';
 
 			if (!empty($stripeacc)) {
-				$connect = $stripeacc.'/';
+				$connect = $stripeacc . '/';
 			} else {
 				$connect = '';
 			}
 
 			// Ref
-			$url = 'https://dashboard.stripe.com/'.$connect.'test/payments/'.$charge->id;
+			$url = 'https://dashboard.stripe.com/' . $connect . 'test/payments/' . $charge->id;
 			if ($servicestatus) {
-				$url = 'https://dashboard.stripe.com/'.$connect.'payments/'.$charge->id;
+				$url = 'https://dashboard.stripe.com/' . $connect . 'payments/' . $charge->id;
 			}
 			print '<td class="tdoverflowmax150">';
-			print "<a href='".$url."' target='_stripe'>".img_picto($langs->trans('ShowInStripe'), 'globe')." ".$charge->id."</a>";
+			print "<a href='" . $url . "' target='_stripe'>" . img_picto($langs->trans('ShowInStripe'), 'globe') . " " . $charge->id . "</a>";
 			if ($charge->payment_intent) {
-				print '<br><span class="opacitymedium">'.$charge->payment_intent.'</span>';
+				var_dump($charge->payment_intent);
+				print '<br><span class="opacitymedium">' . $charge->payment_intent . '</span>';
 			}
 			print "</td>\n";
 
 			// Stripe customer
 			print '<td class="tdoverflowmax150">';
 			if (isModEnabled('stripe') && !empty($stripeacc)) {
-				$connect = $stripeacc.'/';
+				$connect = $stripeacc . '/';
 			}
-			$url = 'https://dashboard.stripe.com/'.$connect.'test/customers/'.$charge->customer;
+			$url = 'https://dashboard.stripe.com/' . $connect . 'test/customers/' . $charge->customer;
 			if ($servicestatus) {
-				$url = 'https://dashboard.stripe.com/'.$connect.'customers/'.$charge->customer;
+				$url = 'https://dashboard.stripe.com/' . $connect . 'customers/' . $charge->customer;
 			}
 			if (!empty($charge->customer)) {
-				print '<a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe'), 'globe').' '.$charge->customer.'</a>';
+				print '<a href="' . $url . '" target="_stripe">' . img_picto($langs->trans('ShowInStripe'), 'globe') . ' ' . $charge->customer . '</a>';
 			}
 			print "</td>\n";
 
@@ -264,7 +268,7 @@
 				$object = new Commande($db);
 				$object->fetch($charge->metadata->dol_id);
 				if ($object->id > 0) {
-					print "<a href='".DOL_URL_ROOT."/commande/card.php?id=".$object->id."'>".img_picto('', 'order')." ".$object->ref."</a>";
+					print "<a href='" . DOL_URL_ROOT . "/commande/card.php?id=" . $object->id . "'>" . img_picto('', 'order') . " " . $object->ref . "</a>";
 				} else {
 					print $FULLTAG;
 				}
@@ -272,7 +276,7 @@
 				$object = new Facture($db);
 				$object->fetch($charge->metadata->dol_id);
 				if ($object->id > 0) {
-					print "<a href='".DOL_URL_ROOT."/compta/facture/card.php?facid=".$charge->metadata->dol_id."'>".img_picto('', 'bill')." ".$object->ref."</a>";
+					print "<a href='" . DOL_URL_ROOT . "/compta/facture/card.php?facid=" . $charge->metadata->dol_id . "'>" . img_picto('', 'bill') . " " . $object->ref . "</a>";
 				} else {
 					print $FULLTAG;
 				}
@@ -282,13 +286,13 @@
 			print "</td>\n";
 
 			// Date payment
-			print '<td class="center nowraponall">'.dol_print_date($charge->created, 'dayhour')."</td>\n";
+			print '<td class="center nowraponall">' . dol_print_date($charge->created, 'dayhour') . "</td>\n";
 			// Type
 			print '<td>';
 			print $type;
 			print '</td>';
 			// Amount
-			print '<td class="right"><span class="amount">'.price(($charge->amount - $charge->amount_refunded) / 100, 0, '', 1, - 1, - 1, strtoupper($charge->currency))."</span></td>";
+			print '<td class="right"><span class="amount">' . price(($charge->amount - $charge->amount_refunded) / 100, 0, '', 1, -1, -1, strtoupper($charge->currency)) . "</span></td>";
 			// Status
 			print '<td class="nowraponall">';
 			print $status;

########## stripe/lib/stripe.lib.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/stripe/lib/stripe.lib.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/stripe/lib/stripe.lib.php	2025-03-26 10:14:51.002969000 +0000
@@ -23,7 +23,7 @@
  *  \brief			Library for common stripe functions
  */
 
-require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/core/lib/payments.lib.php';
 
 /**
  *  Define head array for tabs of stripe tools setup pages
@@ -37,7 +37,7 @@
 	$h = 0;
 	$head = array();
 
-	$head[$h][0] = DOL_URL_ROOT."/stripe/admin/stripe.php";
+	$head[$h][0] = DOL_URL_ROOT . "/stripe/admin/stripe.php";
 	$head[$h][1] = $langs->trans("Stripe");
 	$head[$h][2] = 'stripeaccount';
 	$h++;
@@ -70,11 +70,11 @@
 	// Juridical status
 	$line1 = "";
 	if ($fromcompany->forme_juridique_code) {
-		$line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel((string) $fromcompany->forme_juridique_code);
+		$line1 .= ($line1 ? " - " : "") . getFormeJuridiqueLabel((string) $fromcompany->forme_juridique_code);
 	}
 	// Capital
 	if ($fromcompany->capital) {
-		$line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency);
+		$line1 .= ($line1 ? " - " : "") . $langs->transnoentities("CapitalOf", $fromcompany->capital) . " " . $langs->transnoentities("Currency" . $conf->currency);
 	}
 
 	$reg = array();
@@ -85,7 +85,7 @@
 		if (preg_match('/\((.*)\)/i', $field, $reg)) {
 			$field = $reg[1];
 		}
-		$line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1;
+		$line1 .= ($line1 ? " - " : "") . $field . ": " . $fromcompany->idprof1;
 	}
 	// Prof Id 2
 	if ($fromcompany->idprof2) {
@@ -93,7 +93,7 @@
 		if (preg_match('/\((.*)\)/i', $field, $reg)) {
 			$field = $reg[1];
 		}
-		$line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2;
+		$line1 .= ($line1 ? " - " : "") . $field . ": " . $fromcompany->idprof2;
 	}
 
 	// Second line of company infos
@@ -104,7 +104,7 @@
 		if (preg_match('/\((.*)\)/i', $field, $reg)) {
 			$field = $reg[1];
 		}
-		$line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3;
+		$line2 .= ($line2 ? " - " : "") . $field . ": " . $fromcompany->idprof3;
 	}
 	// Prof Id 4
 	if ($fromcompany->idprof4) {
@@ -112,17 +112,145 @@
 		if (preg_match('/\((.*)\)/i', $field, $reg)) {
 			$field = $reg[1];
 		}
-		$line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4;
+		$line2 .= ($line2 ? " - " : "") . $field . ": " . $fromcompany->idprof4;
 	}
 	// IntraCommunautary VAT
 	if ($fromcompany->tva_intra != '') {
-		$line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra;
+		$line2 .= ($line2 ? " - " : "") . $langs->transnoentities("VATIntraShort") . ": " . $fromcompany->tva_intra;
 	}
 
-	print '<br><br><hr>'."\n";
-	print '<div class="center"><span style="font-size: 10px;">'."\n";
-	print $fromcompany->name.'<br>';
-	print $line1.'<br>';
+	print '<br><br><hr>' . "\n";
+	print '<div class="center"><span style="font-size: 10px;">' . "\n";
+	print $fromcompany->name . '<br>';
+	print $line1 . '<br>';
 	print $line2;
-	print '</span></div>'."\n";
+	print '</span></div>' . "\n";
 }
+
+//MODIF JOSE
+/**
+ * Add a line on bank account with Stripe fees
+ *
+ * @param string  $ref         Reference to add in the description (e.g. transaction ID)
+ * @param float   $totalamount Fee amount to insert (should be positive, will be inverted in the function)
+ * @param int     $fk_account  ID of the Stripe bank account in Dolibarr
+ * @param string  $stripe_id   Stripe transaction ID (used in num_chq to detect duplicates)
+ * @param int     $date        Payment date (timestamp), default now
+ * @param int     $datev       Value date (timestamp), default now
+ * @return int                 Bank line ID or -1 on error
+ */
+function stripeAddPaymentFeeOnBank($ref, $totalamount, $fk_account, $stripe_id, $date = null, $datev = null)
+{
+	global $db, $conf, $user, $langs;
+
+	$db->begin();
+	$error = 0;
+
+	if (empty($date))  $date = dol_now();
+	if (empty($datev)) $datev = dol_now();
+
+	$amount = 0 - abs($totalamount);
+
+	include_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
+	$acc = new Account($db);
+	$result = $acc->fetch($fk_account);
+	if ($result < 0) {
+		return -1;
+	}
+
+	$label = $langs->trans('StripeFees');
+	if (!empty($ref)) {
+		$label .= " " . $ref;
+	} elseif (!empty($date)) {
+		$label .= " " . dol_print_date($date, 'day');
+	}
+
+	$sql = "SELECT count(*) as count FROM " . MAIN_DB_PREFIX . "bank
+	        WHERE num_chq = '" . $db->escape($stripe_id) . "'
+	          AND fk_account = '" . (int) $fk_account . "'
+	          AND amount = " . (float) $amount;
+	$resql = $db->query($sql);
+	if ($resql) {
+		$obj = $db->fetch_object($resql);
+		if ($obj->count > 0) {
+			dol_syslog("stripeAddPaymentFeeOnBank duplicate found for ID $stripe_id");
+			$db->commit();
+			return 0;
+		} else {
+			dol_syslog("stripeAddPaymentFeeOnBank inserting fee for ID $stripe_id");
+
+			$bank_line_id = $acc->addline(
+				$date,
+				'PRE',
+				$label,
+				$amount,
+				$stripe_id,
+				'',
+				$user,
+				'',
+				'',
+				'',
+				$datev
+			);
+
+			if ($bank_line_id <= 0) {
+				$error++;
+				$db->rollback();
+				return -1;
+			}
+		}
+	} else {
+		$error++;
+		$db->rollback();
+		return -1;
+	}
+
+	$db->commit();
+	return $bank_line_id;
+}
+
+
+function trouverIdTiersParEmail($email)
+{
+	global $db; // Obtenir l'objet de connexion à la base de données de Dolibarr
+
+	// Préparer la requête SQL pour récupérer l'ID du tiers en fonction de l'email
+	// $sql = "SELECT fk_soc FROM llx_socpeople WHERE email = '$email'";
+	$sql = "SELECT fk_soc FROM llx_socpeople WHERE email = '" . $db->escape($email) . "'";
+
+	// Exécuter la requête avec la méthode fetch_array pour obtenir un tableau de résultats
+
+	$result = $db->query($sql);
+	if ($result) {
+		// Récupérer l'ID du tiers
+		$row = $db->fetch_array($result);
+		if ($row) {
+			$idTiers = $row['fk_soc'];
+			return $idTiers;
+		}
+	}
+
+	return false;
+}
+
+function trouverIdFactureParRefClient($refClient)
+{
+	global $db; // Obtenir l'objet de connexion à la base de données de Dolibarr
+
+	// Préparer la requête SQL pour récupérer l'ID de la facture en fonction de la référence client
+	$sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "facture WHERE ref_client = '" . $db->escape($refClient) . "'";
+
+	// Exécuter la requête avec la méthode query pour obtenir un résultat
+	$result = $db->query($sql);
+	if ($result) {
+		// Récupérer l'ID de la facture
+		$row = $db->fetch_array($result);
+		if ($row) {
+			$idFacture = $row['rowid'];
+			return $idFacture;
+		}
+	}
+
+	return false;
+}
+//END MODIF
\ No newline at end of file

########## stripe/transaction.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/stripe/transaction.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/stripe/transaction.php	2025-03-25 13:43:28.398088000 +0000
@@ -21,15 +21,15 @@
 
 // Load Dolibarr environment
 require '../main.inc.php';
-require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
-require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
-require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
-//require_once DOL_DOCUMENT_ROOT.'/core/lib/stripe.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
-require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
+require_once DOL_DOCUMENT_ROOT . '/stripe/class/stripe.class.php';
+require_once DOL_DOCUMENT_ROOT . '/stripe/lib/stripe.lib.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
+require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
 if (isModEnabled('accounting')) {
-	require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
+	require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
 }
 
 /**
@@ -94,25 +94,28 @@
 	print $langs->trans('ErrorStripeAccountNotDefined');
 }*/
 
+
+
+
 if (!$rowid) {
-	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
+	print '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '">';
 	if ($optioncss != '') {
-		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+		print '<input type="hidden" name="optioncss" value="' . $optioncss . '">';
 	}
-	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="token" value="' . newToken() . '">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="action" value="list">';
-	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
-	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
-	print '<input type="hidden" name="page" value="'.$page.'">';
+	print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
+	print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
+	print '<input type="hidden" name="page" value="' . $page . '">';
 
 	$title = $langs->trans("StripeTransactionList");
-	$title .= (!empty($stripeacc) ? ' (Stripe connection with Stripe OAuth Connect account '.$stripeacc.')' : ' (Stripe connection with keys from Stripe module setup)');
+	$title .= (!empty($stripeacc) ? ' (Stripe connection with Stripe OAuth Connect account ' . $stripeacc . ')' : ' (Stripe connection with keys from Stripe module setup)');
 
 	print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit);
 
 	print '<div class="div-table-responsive">';
-	print '<table class="tagtable liste'.(!empty($moreforfilter) ? " listwithfilterbefore" : "").'">'."\n";
+	print '<table class="tagtable liste' . (!empty($moreforfilter) ? " listwithfilterbefore" : "") . '">' . "\n";
 
 	print '<tr class="liste_titre">';
 	print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder);
@@ -124,6 +127,9 @@
 	print "</tr>\n";
 	$connect = "";
 
+	//MODIF JOSE
+	$fk_account_stripe = 5;
+
 	try {
 		if ($stripeacc) {
 			$txn_all = \Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripeacc));
@@ -173,7 +179,7 @@
 
 			// Ref
 			if (!empty($stripeacc)) {
-				$connect = $stripeacc.'/';
+				$connect = $stripeacc . '/';
 			}
 
 			// Ref
@@ -185,14 +191,15 @@
 				$origin = "payments";
 			}
 
-			$url = 'https://dashboard.stripe.com/'.$connect.'test/'.$origin.'/'.$txn->source;
+			$url = 'https://dashboard.stripe.com/' . $connect . 'test/' . $origin . '/' . $txn->source;
 			if ($servicestatus) {
-				$url = 'https://dashboard.stripe.com/'.$connect.$origin.'/'.$txn->source;
+				$url = 'https://dashboard.stripe.com/' . $connect . $origin . '/' . $txn->source;
 			}
 			if ($txn->type == 'stripe_fee' || $txn->type == 'reserve_transaction') {
-				print "<td>".$txn->type."</td>";
+
+				print "<td>" . $txn->type . "</td>";
 			} else {
-				print "<td><a href='".$url."' target='_stripe'>".img_picto($langs->trans('ShowInStripe'), 'globe')." ".$txn->source."</a></td>\n";
+				print "<td><a href='" . $url . "' target='_stripe'>" . img_picto($langs->trans('ShowInStripe'), 'globe') . " " . $txn->source . "</a></td>\n";
 			}
 
 			// Stripe customer
@@ -219,12 +226,28 @@
 			//}
 			//print "</td>\n";
 			// Date payment
-			print '<td class="center">'.dol_print_date($txn->created, 'dayhour')."</td>\n";
+			print '<td class="center">' . dol_print_date($txn->created, 'dayhour') . "</td>\n";
 			// Type
-			print '<td>'.$txn->type.'</td>';
+			print '<td>' . $txn->type . '</td>';
 			// Amount
-			print '<td class="right"><span class="amount">'.price(($txn->amount) / 100, 0, '', 1, - 1, - 1, strtoupper($txn->currency))."</span></td>";
-			print '<td class="right"><span class="amount">'.price(($txn->fee) / 100, 0, '', 1, - 1, - 1, strtoupper($txn->currency))."</span></td>";
+			print '<td class="right"><span class="amount">' . price(($txn->amount) / 100, 0, '', 1, -1, -1, strtoupper($txn->currency)) . "</span></td>";
+			print '<td class="right"><span class="amount">' . price(($txn->fee) / 100, 0, '', 1, -1, -1, strtoupper($txn->currency)) . "</span></td>";
+
+			//MODIF JOSE
+			if ($txn->fee > 0 && getDolGlobalInt('STRIPE_AUTO_ADD_FEES_TO_BANK')) {
+
+
+				stripeAddPaymentFeeOnBank(
+					$txn->source,
+					$txn->fee / 100,
+					$fk_account_stripe,
+					$txn->id,
+					$txn->created,
+					$txn->created
+				);
+			}
+			//END MODIF
+
 			// Status
 			print "<td class='right'>";
 			if ($txn->status == 'available') {
@@ -238,7 +261,7 @@
 			print "</tr>\n";
 		}
 	} catch (Exception $e) {
-		print '<tr><td colspan="6">'.$e->getMessage().'</td></td>';
+		print '<tr><td colspan="6">' . $e->getMessage() . '</td></td>';
 	}
 	print "</table>";
 	print '</div>';

########## viewimage.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/viewimage.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/viewimage.php	2025-02-27 08:48:52.889060000 +0000
@@ -189,17 +189,20 @@
  * View
  */
 
-$cachestring = GETPOST("cache", 'aZ09');	// May be 1, or an int, or a hash
-if ($cachestring) {
+if (GETPOST("cache", 'alpha')) {
 	// Important: The following code is to avoid a page request by the browser and PHP CPU at each Dolibarr page access.
 	// We are here when param cache=xxx to force a cache policy:
 	//  xxx=1 means cache of 3600s
 	//  xxx=abcdef or 123456789 means a cache of 1 week (the key will be modified to get break cache use)
 	if (empty($dolibarr_nocache)) {
-		$delaycache = ((is_numeric($cachestring) && (int) $cachestring > 1 && (int) $cachestring < 999999) ? $cachestring : '3600');
+		if (GETPOST('cache', 'alpha') != '1') {
+			$delaycache = 3600 * 24 * 7;
+		} else {
+			$delaycache = 3600;
+		}
 		header('Cache-Control: max-age='.$delaycache.', public, must-revalidate');
 		header('Pragma: cache'); // This is to avoid to have Pragma: no-cache set by proxy or web server
-		header('Expires: '.gmdate('D, d M Y H:i:s', time() + (int) $delaycache).' GMT');	// This is to avoid to have Expires set by proxy or web server
+		header('Expires: '.gmdate('D, d M Y H:i:s', time() + $delaycache).' GMT');	// This is to avoid to have Expires set by proxy or web server
 	} else {
 		// If any cache on files were disable by config file (for test purpose)
 		header('Cache-Control: no-cache');

########## website/samples/wrapper.php
--- /homez.786/ridinteadu/_serious_analysis/van_21.0.0/dolibarr-21.0.0/htdocs/website/samples/wrapper.php	2025-03-03 15:58:17.000000000 +0000
+++ /homez.786/ridinteadu/seriousbeta/dolibarr/htdocs/website/samples/wrapper.php	2025-02-27 08:48:53.029658000 +0000
@@ -38,6 +38,7 @@
 if ($limit <= 0 || $limit > 100) {
 	$limit = 20;
 }
+$cachedelay = GETPOSTINT('cachedelay');		// The delay in second of the cache
 
 // Parameters for RSS
 $rss = GETPOST('rss', 'aZ09');
@@ -128,13 +129,12 @@
 $original_file = str_replace("../", "/", $original_file);
 
 // Cache or not
-$cachestring = GETPOST("cache", 'aZ09');	// May be 1, or an int (delay in second of the cache if < 999999, or a timestamp), or a hash
+$cachestring = GETPOST("cache", 'aZ09');	// May be 1, or an int, or a hash
 if ($cachestring || image_format_supported($original_file) >= 0) {
-	// Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
-	$delaycache = GETPOSTINT('cachedelay') ? GETPOSTINT('cachedelay') : ((is_numeric($cachestring) && (int) $cachestring > 1 && (int) $cachestring < 999999) ? $cachestring : '3600');
-	header('Cache-Control: max-age='.$delaycache.', public, must-revalidate');
+	// Important: Following code is to avoid page request by browser and PHP CPU at
+	// each Dolibarr page access.
+	header('Cache-Control: max-age='.((is_numeric($cachestring) && (int) $cachestring > 1 && (int) $cachestring < 999999) ? $cachestring : '3600').', public, must-revalidate');
 	header('Pragma: cache'); // This is to avoid having Pragma: no-cache
-	header('Expires: '.gmdate('D, d M Y H:i:s', time() + (int) $delaycache).' GMT');	// This is to avoid to have Expires set by proxy or web server
 }
 
 $refname = basename(dirname($original_file)."/");
