浏览代码

Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop

Laurent Destailleur 4 年之前
父节点
当前提交
0009ce1646
共有 95 个文件被更改,包括 8280 次插入3334 次删除
  1. 172 92
      htdocs/accountancy/admin/account.php
  2. 210 166
      htdocs/accountancy/admin/accountmodel.php
  3. 13 16
      htdocs/accountancy/admin/card.php
  4. 7 9
      htdocs/accountancy/admin/categories.php
  5. 229 175
      htdocs/accountancy/admin/categories_list.php
  6. 0 1
      htdocs/accountancy/admin/closure.php
  7. 1 2
      htdocs/accountancy/admin/defaultaccounts.php
  8. 1 2
      htdocs/accountancy/admin/export.php
  9. 18 12
      htdocs/accountancy/admin/fiscalyear.php
  10. 12 13
      htdocs/accountancy/admin/fiscalyear_card.php
  11. 4 2
      htdocs/accountancy/admin/fiscalyear_info.php
  12. 1 0
      htdocs/accountancy/admin/index.php
  13. 182 139
      htdocs/accountancy/admin/journals_list.php
  14. 158 85
      htdocs/accountancy/admin/productaccount.php
  15. 138 82
      htdocs/accountancy/admin/subaccount.php
  16. 46 32
      htdocs/accountancy/bookkeeping/balance.php
  17. 1 2
      htdocs/accountancy/bookkeeping/balancebymonth.php
  18. 50 48
      htdocs/accountancy/bookkeeping/card.php
  19. 198 150
      htdocs/accountancy/bookkeeping/list.php
  20. 143 85
      htdocs/accountancy/bookkeeping/listbyaccount.php
  21. 13 9
      htdocs/accountancy/bookkeeping/listbysubaccount.php
  22. 0 1
      htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php
  23. 0 1
      htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php
  24. 112 69
      htdocs/accountancy/class/accountancycategory.class.php
  25. 63 74
      htdocs/accountancy/class/accountancyexport.class.php
  26. 1 2
      htdocs/accountancy/class/accountancysystem.class.php
  27. 81 53
      htdocs/accountancy/class/accountingaccount.class.php
  28. 53 35
      htdocs/accountancy/class/accountingjournal.class.php
  29. 60 47
      htdocs/accountancy/class/bookkeeping.class.php
  30. 10 8
      htdocs/accountancy/class/lettering.class.php
  31. 23 20
      htdocs/accountancy/closure/index.php
  32. 8 8
      htdocs/accountancy/customer/card.php
  33. 56 37
      htdocs/accountancy/customer/index.php
  34. 86 44
      htdocs/accountancy/customer/lines.php
  35. 125 65
      htdocs/accountancy/customer/list.php
  36. 8 8
      htdocs/accountancy/expensereport/card.php
  37. 47 29
      htdocs/accountancy/expensereport/index.php
  38. 55 29
      htdocs/accountancy/expensereport/lines.php
  39. 70 34
      htdocs/accountancy/expensereport/list.php
  40. 14 16
      htdocs/accountancy/index.php
  41. 76 63
      htdocs/accountancy/journal/expensereportsjournal.php
  42. 116 106
      htdocs/accountancy/journal/purchasesjournal.php
  43. 114 100
      htdocs/accountancy/journal/sellsjournal.php
  44. 8 8
      htdocs/accountancy/supplier/card.php
  45. 50 35
      htdocs/accountancy/supplier/index.php
  46. 90 47
      htdocs/accountancy/supplier/lines.php
  47. 124 63
      htdocs/accountancy/supplier/list.php
  48. 6 8
      htdocs/accountancy/tpl/export_journal.tpl.php
  49. 84 104
      htdocs/admin/workstation.php
  50. 9 8
      htdocs/asset/admin/assets_extrafields.php
  51. 9 8
      htdocs/asset/admin/assets_type_extrafields.php
  52. 6 7
      htdocs/asset/admin/setup.php
  53. 42 36
      htdocs/asset/card.php
  54. 35 25
      htdocs/asset/class/asset.class.php
  55. 40 45
      htdocs/asset/class/asset_type.class.php
  56. 14 13
      htdocs/asset/document.php
  57. 4 2
      htdocs/asset/info.php
  58. 192 123
      htdocs/asset/list.php
  59. 36 33
      htdocs/asset/note.php
  60. 66 71
      htdocs/asset/type.php
  61. 4 8
      htdocs/asterisk/cidlookup.php
  62. 54 28
      htdocs/asterisk/wrapper.php
  63. 46 57
      htdocs/barcode/codeinit.php
  64. 44 58
      htdocs/barcode/printsheet.php
  65. 14 16
      htdocs/comm/propal/class/propal.class.php
  66. 6 4
      htdocs/core/js/lib_head.js.php
  67. 11 0
      htdocs/core/lib/project.lib.php
  68. 15 0
      htdocs/core/modules/modEventOrganization.class.php
  69. 1058 0
      htdocs/eventorganization/class/conferenceorbooth.class.php
  70. 287 0
      htdocs/eventorganization/conferenceorbooth_agenda.php
  71. 550 0
      htdocs/eventorganization/conferenceorbooth_card.php
  72. 197 0
      htdocs/eventorganization/conferenceorbooth_contact.php
  73. 234 0
      htdocs/eventorganization/conferenceorbooth_document.php
  74. 678 0
      htdocs/eventorganization/conferenceorbooth_list.php
  75. 184 0
      htdocs/eventorganization/conferenceorbooth_note.php
  76. 225 0
      htdocs/eventorganization/eventorganizationindex.php
  77. 85 0
      htdocs/eventorganization/lib/eventorganization_conferenceorbooth.lib.php
  78. 6 6
      htdocs/install/mysql/data/llx_c_email_templates.sql
  79. 11 6
      htdocs/install/mysql/migration/13.0.0-14.0.0.sql
  80. 4 0
      htdocs/install/mysql/tables/llx_projet.sql
  81. 18 3
      htdocs/langs/en_US/eventorganization.lang
  82. 2 2
      htdocs/product/index.php
  83. 9 9
      htdocs/projet/card.php
  84. 26 1
      htdocs/projet/class/project.class.php
  85. 344 0
      htdocs/projet/event.php
  86. 96 0
      htdocs/projet/list.php
  87. 120 108
      htdocs/workstation/class/workstation.class.php
  88. 8 14
      htdocs/workstation/class/workstationresource.class.php
  89. 8 14
      htdocs/workstation/class/workstationusergroup.class.php
  90. 13 6
      htdocs/workstation/lib/workstation_workstation.lib.php
  91. 41 63
      htdocs/workstation/workstation_agenda.php
  92. 63 77
      htdocs/workstation/workstation_card.php
  93. 17 45
      htdocs/workstation/workstation_document.php
  94. 203 161
      htdocs/workstation/workstation_list.php
  95. 9 41
      htdocs/workstation/workstation_note.php

+ 172 - 92
htdocs/accountancy/admin/account.php

@@ -49,20 +49,30 @@ $search_pcgtype = GETPOST('search_pcgtype', 'alpha');
 $chartofaccounts = GETPOST('chartofaccounts', 'int');
 
 // Security check
-if ($user->socid > 0) accessforbidden();
-if (!$user->rights->accounting->chartofaccount) accessforbidden();
+if ($user->socid > 0) {
+	accessforbidden();
+}
+if (!$user->rights->accounting->chartofaccount) {
+	accessforbidden();
+}
 
 // Load variable for pagination
 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield) $sortfield = "aa.account_number";
-if (!$sortorder) $sortorder = "ASC";
+if (!$sortfield) {
+	$sortfield = "aa.account_number";
+}
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
 
 $arrayfields = array(
 	'aa.account_number'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1),
@@ -74,7 +84,9 @@ $arrayfields = array(
 	'aa.active'=>array('label'=>$langs->trans("Activated"), 'checked'=>1)
 );
 
-if ($conf->global->MAIN_FEATURES_LEVEL < 2) unset($arrayfields['aa.reconcilable']);
+if ($conf->global->MAIN_FEATURES_LEVEL < 2) {
+	unset($arrayfields['aa.reconcilable']);
+}
 
 $accounting = new AccountingAccount($db);
 
@@ -84,21 +96,27 @@ $accounting = new AccountingAccount($db);
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha')) { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha')) {
+	$massaction = '';
+}
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
-	if (!empty($cancel)) $action = '';
+if (empty($reshook)) {
+	if (!empty($cancel)) {
+		$action = '';
+	}
 
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
-	{
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
 		$search_account = "";
 		$search_label = "";
 		$search_labelshort = "";
@@ -107,23 +125,21 @@ if (empty($reshook))
 		$search_array_options = array();
 	}
 	if ((GETPOST('valid_change_chart', 'alpha') && GETPOST('chartofaccounts', 'int') > 0)	// explicit click on button 'Change and load' with js on
-		|| (GETPOST('chartofaccounts', 'int') > 0 && GETPOST('chartofaccounts', 'int') != $conf->global->CHARTOFACCOUNTS))	// a submit of form is done and chartofaccounts combo has been modified
-	{
-		if ($chartofaccounts > 0)
-		{
+		|| (GETPOST('chartofaccounts', 'int') > 0 && GETPOST('chartofaccounts', 'int') != $conf->global->CHARTOFACCOUNTS)) {	// a submit of form is done and chartofaccounts combo has been modified
+		if ($chartofaccounts > 0) {
 			// Get language code for this $chartofaccounts
 			$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_country as c, '.MAIN_DB_PREFIX.'accounting_system as a';
 			$sql .= ' WHERE c.rowid = a.fk_country AND a.rowid = '.(int) $chartofaccounts;
 			$resql = $db->query($sql);
-			if ($resql)
-			{
+			if ($resql) {
 				$obj = $db->fetch_object($resql);
 				$country_code = $obj->code;
-			} else dol_print_error($db);
+			} else {
+				dol_print_error($db);
+			}
 
 			// Try to load sql file
-			if ($country_code)
-			{
+			if ($country_code) {
 				$sqlfile = DOL_DOCUMENT_ROOT.'/install/mysql/data/llx_accounting_account_'.strtolower($country_code).'.sql';
 
 				$offsetforchartofaccount = 0;
@@ -131,16 +147,14 @@ if (empty($reshook))
 				// and pass CCCNNNNN + (num of company * 100 000 000) as offset to the run_sql as a new parameter to say to update sql on the fly to add offset to rowid and account_parent value.
 				// This is to be sure there is no conflict for each chart of account, whatever is country, whatever is company when multicompany is used.
 				$tmp = file_get_contents($sqlfile);
-				if (preg_match('/-- ADD (\d+) to rowid/ims', $tmp, $reg))
-				{
+				if (preg_match('/-- ADD (\d+) to rowid/ims', $tmp, $reg)) {
 					$offsetforchartofaccount += $reg[1];
 				}
 				$offsetforchartofaccount += ($conf->entity * 100000000);
 
 				$result = run_sql($sqlfile, 1, $conf->entity, 1, '', 'default', 32768, 0, $offsetforchartofaccount);
 
-				if ($result > 0)
-				{
+				if ($result > 0) {
 					setEventMessages($langs->trans("ChartLoaded"), null, 'mesgs');
 				} else {
 					setEventMessages($langs->trans("ErrorDuringChartLoad"), null, 'warnings');
@@ -198,8 +212,11 @@ $sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.account_number, aa.a
 $sql .= " a2.rowid as rowid2, a2.label as label2, a2.account_number as account_number2";
 $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa";
 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version AND aa.entity = ".$conf->entity;
-if ($db->type == 'pgsql') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity;
-else $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity;
+if ($db->type == 'pgsql') {
+	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity;
+} else {
+	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = ".$conf->entity;
+}
 $sql .= " WHERE asy.rowid = ".$pcgver;
 //print $sql;
 if (strlen(trim($search_account))) {
@@ -224,31 +241,38 @@ if (strlen(trim($search_account))) {
 			$search_account_tmp_clean = $search_account_tmp;
 			$search_account_clean = $search_account;
 			$startchar = '%';
-			if (strpos($search_account_tmp, '^') === 0)
-			{
+			if (strpos($search_account_tmp, '^') === 0) {
 				$startchar = '';
 				$search_account_tmp_clean = preg_replace('/^\^/', '', $search_account_tmp);
 				$search_account_clean = preg_replace('/^\^/', '', $search_account);
 			}
 			$sql .= " AND (aa.account_number LIKE '".$db->escape($startchar.$search_account_tmp_clean)."'";
 			$sql .= " OR aa.account_number LIKE '".$db->escape($startchar.$search_account_clean)."%')";
-		} else $sql .= natural_search("aa.account_number", $search_account_tmp);
+		} else {
+			$sql .= natural_search("aa.account_number", $search_account_tmp);
+		}
 	}
 }
-if (strlen(trim($search_label)))			$sql .= natural_search("aa.label", $search_label);
-if (strlen(trim($search_labelshort)))       $sql .= natural_search("aa.labelshort", $search_labelshort);
-if (strlen(trim($search_accountparent)) && $search_accountparent != '-1')	$sql .= natural_search("aa.account_parent", $search_accountparent, 2);
-if (strlen(trim($search_pcgtype)))			$sql .= natural_search("aa.pcg_type", $search_pcgtype);
+if (strlen(trim($search_label))) {
+	$sql .= natural_search("aa.label", $search_label);
+}
+if (strlen(trim($search_labelshort))) {
+	$sql .= natural_search("aa.labelshort", $search_labelshort);
+}
+if (strlen(trim($search_accountparent)) && $search_accountparent != '-1') {
+	$sql .= natural_search("aa.account_parent", $search_accountparent, 2);
+}
+if (strlen(trim($search_pcgtype))) {
+	$sql .= natural_search("aa.pcg_type", $search_pcgtype);
+}
 $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$resql = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($resql);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -259,22 +283,36 @@ $sql .= $db->plimit($limit + 1, $offset);
 dol_syslog('accountancy/admin/account.php:: $sql='.$sql);
 $resql = $db->query($sql);
 
-if ($resql)
-{
+if ($resql) {
 	$num = $db->num_rows($resql);
 
 	$param = '';
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-	if ($search_account) $param .= '&search_account='.urlencode($search_account);
-	if ($search_label) $param .= '&search_label='.urlencode($search_label);
-	if ($search_labelshort) $param .= '&search_labelshort='.urlencode($search_labelshort);
-	if ($search_accountparent > 0 || $search_accountparent == '0') $param .= '&search_accountparent='.urlencode($search_accountparent);
-	if ($search_pcgtype) $param .= '&search_pcgtype='.urlencode($search_pcgtype);
-	if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
-
-	if (!empty($conf->use_javascript_ajax))
-	{
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.urlencode($limit);
+	}
+	if ($search_account) {
+		$param .= '&search_account='.urlencode($search_account);
+	}
+	if ($search_label) {
+		$param .= '&search_label='.urlencode($search_label);
+	}
+	if ($search_labelshort) {
+		$param .= '&search_labelshort='.urlencode($search_labelshort);
+	}
+	if ($search_accountparent > 0 || $search_accountparent == '0') {
+		$param .= '&search_accountparent='.urlencode($search_accountparent);
+	}
+	if ($search_pcgtype) {
+		$param .= '&search_pcgtype='.urlencode($search_pcgtype);
+	}
+	if ($optioncss != '') {
+		$param .= '&optioncss='.urlencode($optioncss);
+	}
+
+	if (!empty($conf->use_javascript_ajax)) {
 		print '<!-- Add javascript to reload page when we click "Change plan" -->
 			<script type="text/javascript">
 			$(document).ready(function () {
@@ -288,7 +326,9 @@ if ($resql)
 	}
 
 	print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="action" value="list">';
@@ -322,7 +362,9 @@ if ($resql)
 
 			$i++;
 		}
-	} else dol_print_error($db);
+	} else {
+		dol_print_error($db);
+	}
 	print "</select>";
 	print ajax_combobox("chartofaccounts");
 	print '<input type="'.(empty($conf->use_javascript_ajax) ? 'submit' : 'button').'" class="button" name="change_chart" id="change_chart" value="'.dol_escape_htmltag($langs->trans("ChangeAndLoad")).'">';
@@ -341,17 +383,31 @@ if ($resql)
 
 	// Line for search fields
 	print '<tr class="liste_titre_filter">';
-	if (!empty($arrayfields['aa.account_number']['checked']))	print '<td class="liste_titre"><input type="text" class="flat width100" name="search_account" value="'.$search_account.'"></td>';
-	if (!empty($arrayfields['aa.label']['checked']))			print '<td class="liste_titre"><input type="text" class="flat width150" name="search_label" value="'.$search_label.'"></td>';
-	if (!empty($arrayfields['aa.labelshort']['checked']))		print '<td class="liste_titre"><input type="text" class="flat width100" name="search_labelshort" value="'.$search_labelshort.'"></td>';
+	if (!empty($arrayfields['aa.account_number']['checked'])) {
+		print '<td class="liste_titre"><input type="text" class="flat width100" name="search_account" value="'.$search_account.'"></td>';
+	}
+	if (!empty($arrayfields['aa.label']['checked'])) {
+		print '<td class="liste_titre"><input type="text" class="flat width150" name="search_label" value="'.$search_label.'"></td>';
+	}
+	if (!empty($arrayfields['aa.labelshort']['checked'])) {
+		print '<td class="liste_titre"><input type="text" class="flat width100" name="search_labelshort" value="'.$search_labelshort.'"></td>';
+	}
 	if (!empty($arrayfields['aa.account_parent']['checked'])) {
 		print '<td class="liste_titre">';
 		print $formaccounting->select_account($search_accountparent, 'search_accountparent', 2);
 		print '</td>';
 	}
-	if (!empty($arrayfields['aa.pcg_type']['checked']))		    print '<td class="liste_titre"><input type="text" class="flat width100" name="search_pcgtype" value="'.$search_pcgtype.'"></td>';
-	if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (!empty($arrayfields['aa.reconcilable']['checked']))   print '<td class="liste_titre">&nbsp;</td>'; }
-	if (!empty($arrayfields['aa.active']['checked']))			print '<td class="liste_titre">&nbsp;</td>';
+	if (!empty($arrayfields['aa.pcg_type']['checked'])) {
+		print '<td class="liste_titre"><input type="text" class="flat width100" name="search_pcgtype" value="'.$search_pcgtype.'"></td>';
+	}
+	if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
+		if (!empty($arrayfields['aa.reconcilable']['checked'])) {
+			print '<td class="liste_titre">&nbsp;</td>';
+		}
+	}
+	if (!empty($arrayfields['aa.active']['checked'])) {
+		print '<td class="liste_titre">&nbsp;</td>';
+	}
 	print '<td class="liste_titre maxwidthsearch">';
 	$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
 	print $searchpicto;
@@ -359,13 +415,29 @@ if ($resql)
 	print '</tr>';
 
 	print '<tr class="liste_titre">';
-	if (!empty($arrayfields['aa.account_number']['checked']))	print_liste_field_titre($arrayfields['aa.account_number']['label'], $_SERVER["PHP_SELF"], "aa.account_number", "", $param, '', $sortfield, $sortorder);
-	if (!empty($arrayfields['aa.label']['checked']))			print_liste_field_titre($arrayfields['aa.label']['label'], $_SERVER["PHP_SELF"], "aa.label", "", $param, '', $sortfield, $sortorder);
-	if (!empty($arrayfields['aa.labelshort']['checked']))		print_liste_field_titre($arrayfields['aa.labelshort']['label'], $_SERVER["PHP_SELF"], "aa.labelshort", "", $param, '', $sortfield, $sortorder);
-	if (!empty($arrayfields['aa.account_parent']['checked']))	print_liste_field_titre($arrayfields['aa.account_parent']['label'], $_SERVER["PHP_SELF"], "aa.account_parent", "", $param, '', $sortfield, $sortorder, 'left ');
-	if (!empty($arrayfields['aa.pcg_type']['checked']))			print_liste_field_titre($arrayfields['aa.pcg_type']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_type', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_type']['help']);
-	if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (!empty($arrayfields['aa.reconcilable']['checked']))	print_liste_field_titre($arrayfields['aa.reconcilable']['label'], $_SERVER["PHP_SELF"], 'aa.reconcilable', '', $param, '', $sortfield, $sortorder); }
-	if (!empty($arrayfields['aa.active']['checked']))			print_liste_field_titre($arrayfields['aa.active']['label'], $_SERVER["PHP_SELF"], 'aa.active', '', $param, '', $sortfield, $sortorder);
+	if (!empty($arrayfields['aa.account_number']['checked'])) {
+		print_liste_field_titre($arrayfields['aa.account_number']['label'], $_SERVER["PHP_SELF"], "aa.account_number", "", $param, '', $sortfield, $sortorder);
+	}
+	if (!empty($arrayfields['aa.label']['checked'])) {
+		print_liste_field_titre($arrayfields['aa.label']['label'], $_SERVER["PHP_SELF"], "aa.label", "", $param, '', $sortfield, $sortorder);
+	}
+	if (!empty($arrayfields['aa.labelshort']['checked'])) {
+		print_liste_field_titre($arrayfields['aa.labelshort']['label'], $_SERVER["PHP_SELF"], "aa.labelshort", "", $param, '', $sortfield, $sortorder);
+	}
+	if (!empty($arrayfields['aa.account_parent']['checked'])) {
+		print_liste_field_titre($arrayfields['aa.account_parent']['label'], $_SERVER["PHP_SELF"], "aa.account_parent", "", $param, '', $sortfield, $sortorder, 'left ');
+	}
+	if (!empty($arrayfields['aa.pcg_type']['checked'])) {
+		print_liste_field_titre($arrayfields['aa.pcg_type']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_type', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_type']['help']);
+	}
+	if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
+		if (!empty($arrayfields['aa.reconcilable']['checked'])) {
+			print_liste_field_titre($arrayfields['aa.reconcilable']['label'], $_SERVER["PHP_SELF"], 'aa.reconcilable', '', $param, '', $sortfield, $sortorder);
+		}
+	}
+	if (!empty($arrayfields['aa.active']['checked'])) {
+		print_liste_field_titre($arrayfields['aa.active']['label'], $_SERVER["PHP_SELF"], 'aa.active', '', $param, '', $sortfield, $sortorder);
+	}
 	print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
 	print "</tr>\n";
 
@@ -374,8 +446,7 @@ if ($resql)
 
 	$totalarray = array();
 	$i = 0;
-	while ($i < min($num, $limit))
-	{
+	while ($i < min($num, $limit)) {
 		$obj = $db->fetch_object($resql);
 
 		$accountstatic->id = $obj->rowid;
@@ -385,39 +456,40 @@ if ($resql)
 		print '<tr class="oddeven">';
 
 		// Account number
-		if (!empty($arrayfields['aa.account_number']['checked']))
-		{
+		if (!empty($arrayfields['aa.account_number']['checked'])) {
 			print "<td>";
 			print $accountstatic->getNomUrl(1, 0, 0, '', 0, 1, 0, 'accountcard');
 			print "</td>\n";
-			if (!$i) $totalarray['nbfield']++;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
 		}
 
 		// Account label
-		if (!empty($arrayfields['aa.label']['checked']))
-		{
+		if (!empty($arrayfields['aa.label']['checked'])) {
 			print "<td>";
 			print $obj->label;
 			print "</td>\n";
-			if (!$i) $totalarray['nbfield']++;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
 		}
 
 		// Account label to show (label short)
-		if (!empty($arrayfields['aa.labelshort']['checked']))
-		{
+		if (!empty($arrayfields['aa.labelshort']['checked'])) {
 			print "<td>";
 			print $obj->labelshort;
 			print "</td>\n";
-			if (!$i) $totalarray['nbfield']++;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
 		}
 
 		// Account parent
-		if (!empty($arrayfields['aa.account_parent']['checked']))
-		{
+		if (!empty($arrayfields['aa.account_parent']['checked'])) {
 			// Note: obj->account_parent is a foreign key to a rowid. It is field in child table and obj->rowid2 is same, but in parent table.
 			// So for orphans, obj->account_parent is set but not obj->rowid2
-			if (!empty($obj->account_parent) && !empty($obj->rowid2))
-			{
+			if (!empty($obj->account_parent) && !empty($obj->rowid2)) {
 				print "<td>";
 				print '<!-- obj->account_parent = '.$obj->account_parent.' obj->rowid2 = '.$obj->rowid2.' -->';
 				$accountparent->id = $obj->rowid2;
@@ -425,24 +497,29 @@ if ($resql)
 				$accountparent->account_number = $obj->account_number2; // Sotre an account number for output
 				print $accountparent->getNomUrl(1);
 				print "</td>\n";
-				if (!$i) $totalarray['nbfield']++;
+				if (!$i) {
+					$totalarray['nbfield']++;
+				}
 			} else {
 				print '<td>';
 				if (!empty($obj->account_parent)) {
 					print '<!-- Bad value for obj->account_parent = '.$obj->account_parent.': is a rowid that does not exists -->';
 				}
 				print '</td>';
-				if (!$i) $totalarray['nbfield']++;
+				if (!$i) {
+					$totalarray['nbfield']++;
+				}
 			}
 		}
 
 		// Chart of accounts type
-		if (!empty($arrayfields['aa.pcg_type']['checked']))
-		{
+		if (!empty($arrayfields['aa.pcg_type']['checked'])) {
 			print "<td>";
 			print $obj->pcg_type;
 			print "</td>\n";
-			if (!$i) $totalarray['nbfield']++;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
 		}
 
 		if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
@@ -466,8 +543,7 @@ if ($resql)
 		}
 
 		// Activated or not
-		if (!empty($arrayfields['aa.active']['checked']))
-		{
+		if (!empty($arrayfields['aa.active']['checked'])) {
 			print '<td class="center">';
 			if (empty($obj->active)) {
 				print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$obj->rowid.'&action=enable&mode=0">';
@@ -479,7 +555,9 @@ if ($resql)
 				print '</a>';
 			}
 			print '</td>';
-			if (!$i) $totalarray['nbfield']++;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
 		}
 
 		// Action
@@ -494,7 +572,9 @@ if ($resql)
 			print '</a>';
 		}
 		print '</td>'."\n";
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 
 		print "</tr>\n";
 		$i++;

+ 210 - 166
htdocs/accountancy/admin/accountmodel.php

@@ -39,7 +39,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
-if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
+if (!empty($conf->accounting->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
+}
 
 // Load translation files required by the page
 $langs->loadLangs(array("errors", "admin", "companies", "resource", "holiday", "compta", "accountancy", "hrm"));
@@ -62,7 +64,9 @@ $active = 1;
 $sortfield = GETPOST("sortfield", 'aZ09comma');
 $sortorder = GETPOST("sortorder", 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $listlimit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
@@ -71,8 +75,12 @@ $search_country_id = GETPOST('search_country_id', 'int');
 
 
 // Security check
-if ($user->socid > 0) accessforbidden();
-if (!$user->rights->accounting->chartofaccount) accessforbidden();
+if ($user->socid > 0) {
+	accessforbidden();
+}
+if (!$user->rights->accounting->chartofaccount) {
+	accessforbidden();
+}
 
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@@ -139,14 +147,12 @@ $sourceList = array();
  * Actions
  */
 
-if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter_x', 'alpha'))
-{
+if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter_x', 'alpha')) {
 	$search_country_id = '';
 }
 
 // Actions add or modify an entry into a dictionary
-if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
-{
+if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) {
 	$listfield = explode(',', str_replace(' ', '', $tabfield[$id]));
 	$listfieldinsert = explode(',', $tabfieldinsert[$id]);
 	$listfieldmodify = explode(',', $tabfieldinsert[$id]);
@@ -154,17 +160,21 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 
 	// Check that all fields are filled
 	$ok = 1;
-	foreach ($listfield as $f => $value)
-	{
-		if ($value == 'country_id' && in_array($tablib[$id], array('Pcg_version'))) continue; // For some pages, country is not mandatory
-		if ((!GETPOSTISSET($value)) || GETPOST($value) == '')
-		{
+	foreach ($listfield as $f => $value) {
+		if ($value == 'country_id' && in_array($tablib[$id], array('Pcg_version'))) {
+			continue; // For some pages, country is not mandatory
+		}
+		if ((!GETPOSTISSET($value)) || GETPOST($value) == '') {
 			$ok = 0;
 			$fieldnamekey = $listfield[$f];
 			// We take translate key of field
 
-			if ($fieldnamekey == 'pcg_version')  $fieldnamekey = 'Pcg_version';
-			if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label'))  $fieldnamekey = 'Label';
+			if ($fieldnamekey == 'pcg_version') {
+				$fieldnamekey = 'Pcg_version';
+			}
+			if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) {
+				$fieldnamekey = 'Label';
+			}
 
 			setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors');
 		}
@@ -174,36 +184,30 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 		$ok = 0;
 		setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors');
 	}
-	if (GETPOSTISSET("pcg_version"))
-	{
-		if (GETPOST("pcg_version") == '0')
-		{
+	if (GETPOSTISSET("pcg_version")) {
+		if (GETPOST("pcg_version") == '0') {
 			$ok = 0;
 			setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors');
 		}
 		/*if (!is_numeric($_POST['code']))	// disabled, code may not be in numeric base
-    	{
-	    	$ok = 0;
-	    	$msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'<br>';
-	    }*/
+		{
+			$ok = 0;
+			$msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'<br>';
+		}*/
 	}
-	if (GETPOSTISSET("country") && (GETPOST("country") == '0') && ($id != 2))
-	{
+	if (GETPOSTISSET("country") && (GETPOST("country") == '0') && ($id != 2)) {
 		$ok = 0;
 		setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("Country")), null, 'errors');
 	}
 
 	// Si verif ok et action add, on ajoute la ligne
-	if ($ok && GETPOST('actionadd', 'alpha'))
-	{
-		if ($tabrowid[$id])
-		{
+	if ($ok && GETPOST('actionadd', 'alpha')) {
+		if ($tabrowid[$id]) {
 			// Recupere id libre pour insertion
 			$newid = 0;
 			$sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id];
 			$result = $db->query($sql);
-			if ($result)
-			{
+			if ($result) {
 				$obj = $db->fetch_object($result);
 				$newid = ($obj->newid + 1);
 			} else {
@@ -214,34 +218,39 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 		// Add new entry
 		$sql = "INSERT INTO ".$tabname[$id]." (";
 		// List of fields
-		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert))
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) {
 			$sql .= $tabrowid[$id].",";
+		}
 		$sql .= $tabfieldinsert[$id];
 		$sql .= ",active)";
 		$sql .= " VALUES(";
 
 		// List of values
-		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert))
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) {
 			$sql .= $newid.",";
+		}
 		$i = 0;
-		foreach ($listfieldinsert as $f => $value)
-		{
+		foreach ($listfieldinsert as $f => $value) {
 			if ($value == 'price' || preg_match('/^amount/i', $value) || $value == 'taux') {
 				$_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]], 'MU');
 			} elseif ($value == 'entity') {
 				$_POST[$listfieldvalue[$i]] = $conf->entity;
 			}
-			if ($i) $sql .= ",";
-			if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null";
-			else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			if ($i) {
+				$sql .= ",";
+			}
+			if ($_POST[$listfieldvalue[$i]] == '') {
+				$sql .= "null";
+			} else {
+				$sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			}
 			$i++;
 		}
 		$sql .= ",1)";
 
 		dol_syslog("actionadd", LOG_DEBUG);
 		$result = $db->query($sql);
-		if ($result)	// Add is ok
-		{
+		if ($result) {	// Add is ok
 			setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
 			$_POST = array('id'=>$id); // Clean $_POST array, we keep only
 		} else {
@@ -254,30 +263,36 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 	}
 
 	// Si verif ok et action modify, on modifie la ligne
-	if ($ok && GETPOST('actionmodify', 'alpha'))
-	{
-		if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+	if ($ok && GETPOST('actionmodify', 'alpha')) {
+		if ($tabrowid[$id]) {
+			$rowidcol = $tabrowid[$id];
+		} else {
+			$rowidcol = "rowid";
+		}
 
 		// Modify entry
 		$sql = "UPDATE ".$tabname[$id]." SET ";
 		// Modifie valeur des champs
-		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify))
-		{
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) {
 			$sql .= $tabrowid[$id]."=";
 			$sql .= "'".$db->escape($rowid)."', ";
 		}
 		$i = 0;
-		foreach ($listfieldmodify as $field)
-		{
+		foreach ($listfieldmodify as $field) {
 			if ($field == 'price' || preg_match('/^amount/i', $field) || $field == 'taux') {
 				$_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]], 'MU');
 			} elseif ($field == 'entity') {
 				$_POST[$listfieldvalue[$i]] = $conf->entity;
 			}
-			if ($i) $sql .= ",";
+			if ($i) {
+				$sql .= ",";
+			}
 			$sql .= $field."=";
-			if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null";
-			else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			if ($_POST[$listfieldvalue[$i]] == '') {
+				$sql .= "null";
+			} else {
+				$sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			}
 			$i++;
 		}
 		$sql .= " WHERE ".$rowidcol." = ".((int) $rowid);
@@ -285,31 +300,30 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 		dol_syslog("actionmodify", LOG_DEBUG);
 		//print $sql;
 		$resql = $db->query($sql);
-		if (!$resql)
-		{
+		if (!$resql) {
 			setEventMessages($db->error(), null, 'errors');
 		}
 	}
 	//$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
 }
 
-if (GETPOST('actioncancel', 'alpha'))
-{
+if (GETPOST('actioncancel', 'alpha')) {
 	//$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
 }
 
-if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == 'confirm_delete' && $confirm == 'yes') {       // delete
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	$sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol." = ".((int) $rowid);
 
 	dol_syslog("delete", LOG_DEBUG);
 	$result = $db->query($sql);
-	if (!$result)
-	{
-		if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
-		{
+	if (!$result) {
+		if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') {
 			setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
 		} else {
 			dol_print_error($db);
@@ -318,9 +332,12 @@ if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
 }
 
 // activate
-if ($action == $acts[0])
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == $acts[0]) {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -329,16 +346,18 @@ if ($action == $acts[0])
 	}
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
 
 // disable
-if ($action == $acts[1])
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == $acts[1]) {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -347,16 +366,18 @@ if ($action == $acts[1])
 	}
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
 
 // favorite
-if ($action == 'activate_favorite')
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == 'activate_favorite') {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -365,16 +386,18 @@ if ($action == 'activate_favorite')
 	}
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
 
 // disable favorite
-if ($action == 'disable_favorite')
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == 'disable_favorite') {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -383,8 +406,7 @@ if ($action == 'disable_favorite')
 	}
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
@@ -406,8 +428,7 @@ print load_fiche_titre($titre, $linkback, 'title_accountancy');
 
 
 // Confirmation de la suppression de la ligne
-if ($action == 'delete')
-{
+if ($action == 'delete') {
 	print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.urlencode($page).'&' : '').'sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder).'&rowid='.urlencode($rowid).'&code='.urlencode($code).'&id='.urlencode($id), $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1);
 }
 //var_dump($elementList);
@@ -415,20 +436,23 @@ if ($action == 'delete')
 /*
  * Show a dictionary
  */
-if ($id)
-{
+if ($id) {
 	// Complete requete recherche valeurs avec critere de tri
 	$sql = $tabsql[$id];
 
-	if ($search_country_id > 0)
-	{
-		if (preg_match('/ WHERE /', $sql)) $sql .= " AND ";
-		else $sql .= " WHERE ";
+	if ($search_country_id > 0) {
+		if (preg_match('/ WHERE /', $sql)) {
+			$sql .= " AND ";
+		} else {
+			$sql .= " WHERE ";
+		}
 		$sql .= " c.rowid = ".$search_country_id;
 	}
 
 	// If sort order is "country", we use country_code instead
-	if ($sortfield == 'country') $sortfield = 'country_code';
+	if ($sortfield == 'country') {
+		$sortfield = 'country_code';
+	}
 	$sql .= $db->order($sortfield, $sortorder);
 	$sql .= $db->plimit($listlimit + 1, $offset);
 	//print $sql;
@@ -442,30 +466,35 @@ if ($id)
 	print '<table class="noborder centpercent">';
 
 	// Form to add a new line
-	if ($tabname[$id])
-	{
+	if ($tabname[$id]) {
 		$fieldlist = explode(',', $tabfield[$id]);
 
 		// Line for title
 		print '<tr class="liste_titre">';
-		foreach ($fieldlist as $field => $value)
-		{
+		foreach ($fieldlist as $field => $value) {
 			// Determine le nom du champ par rapport aux noms possibles
 			// dans les dictionnaires de donnees
 			$valuetoshow = ucfirst($fieldlist[$field]); // Par defaut
 			$valuetoshow = $langs->trans($valuetoshow); // try to translate
 			$class = "left";
-			if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); }
-			if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label')
-			{
+			if ($fieldlist[$field] == 'code') {
+				$valuetoshow = $langs->trans("Code");
+			}
+			if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') {
 				$valuetoshow = $langs->trans("Label");
 			}
 			if ($fieldlist[$field] == 'country') {
-				if (in_array('region_id', $fieldlist)) { print '<td>&nbsp;</td>'; continue; }		// For region page, we do not show the country input
+				if (in_array('region_id', $fieldlist)) {
+					print '<td>&nbsp;</td>'; continue;
+				}		// For region page, we do not show the country input
 				$valuetoshow = $langs->trans("Country");
 			}
-			if ($fieldlist[$field] == 'country_id') { $valuetoshow = ''; }
-			if ($fieldlist[$field] == 'pcg_version' || $fieldlist[$field] == 'fk_pcg_version') { $valuetoshow = $langs->trans("Pcg_version"); }
+			if ($fieldlist[$field] == 'country_id') {
+				$valuetoshow = '';
+			}
+			if ($fieldlist[$field] == 'pcg_version' || $fieldlist[$field] == 'fk_pcg_version') {
+				$valuetoshow = $langs->trans("Pcg_version");
+			}
 
 			if ($valuetoshow != '') {
 				print '<td class="'.$class.'">';
@@ -492,12 +521,11 @@ if ($id)
 
 		$obj = new stdClass();
 		// If data was already input, we define them in obj to populate input fields.
-		if (GETPOST('actionadd', 'alpha'))
-		{
-			foreach ($fieldlist as $key=>$val)
-			{
-				if (GETPOST($val))
+		if (GETPOST('actionadd', 'alpha')) {
+			foreach ($fieldlist as $key => $val) {
+				if (GETPOST($val)) {
 					$obj->$val = GETPOST($val);
+				}
 			}
 		}
 
@@ -506,8 +534,7 @@ if ($id)
 		$reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
 		$error = $hookmanager->error; $errors = $hookmanager->errors;
 
-		if (empty($reshook))
-		{
+		if (empty($reshook)) {
 			fieldListAccountModel($fieldlist, $obj, $tabname[$id], 'add');
 		}
 
@@ -526,20 +553,24 @@ if ($id)
 	// List of available values in database
 	dol_syslog("htdocs/admin/dict", LOG_DEBUG);
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$num = $db->num_rows($resql);
 		$i = 0;
 
 		$param = '&id='.$id;
-		if ($search_country_id > 0) $param .= '&search_country_id='.$search_country_id;
+		if ($search_country_id > 0) {
+			$param .= '&search_country_id='.$search_country_id;
+		}
 		$paramwithsearch = $param;
-		if ($sortorder) $paramwithsearch .= '&sortorder='.$sortorder;
-		if ($sortfield) $paramwithsearch .= '&sortfield='.$sortfield;
+		if ($sortorder) {
+			$paramwithsearch .= '&sortorder='.$sortorder;
+		}
+		if ($sortfield) {
+			$paramwithsearch .= '&sortfield='.$sortfield;
+		}
 
 		// There is several pages
-		if ($num > $listlimit)
-		{
+		if ($num > $listlimit) {
 			print '<tr class="none"><td class="right" colspan="'.(3 + count($fieldlist)).'">';
 			print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), '<li class="pagination"><span>'.$langs->trans("Page").' '.($page + 1).'</span></li>');
 			print '</td></tr>';
@@ -547,16 +578,15 @@ if ($id)
 
 		// Title line with search boxes
 		print '<tr class="liste_titre liste_titre_add">';
-		foreach ($fieldlist as $field => $value)
-		{
+		foreach ($fieldlist as $field => $value) {
 			$showfield = 1; // By defaut
 
-			if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; }
+			if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') {
+				$showfield = 0;
+			}
 
-			if ($showfield)
-			{
-				if ($value == 'country')
-				{
+			if ($showfield) {
+				if ($value == 'country') {
 					print '<td class="liste_titre">';
 					print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth200 maxwidthonsmartphone');
 					print '</td>';
@@ -582,16 +612,13 @@ if ($id)
 		print getTitleFieldOfList('');
 		print '</tr>';
 
-		if ($num)
-		{
+		if ($num) {
 			// Lines with values
-			while ($i < $num)
-			{
+			while ($i < $num) {
 				$obj = $db->fetch_object($resql);
 				//print_r($obj);
 				print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
-				if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code)))
-				{
+				if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) {
 					print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">';
 					print '<input type="hidden" name="token" value="'.newToken().'">';
 					print '<input type="hidden" name="page" value="'.$page.'">';
@@ -602,39 +629,35 @@ if ($id)
 					$reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
 					$error = $hookmanager->error; $errors = $hookmanager->errors;
 
-					if (empty($reshook)) fieldListAccountModel($fieldlist, $obj, $tabname[$id], 'edit');
+					if (empty($reshook)) {
+						fieldListAccountModel($fieldlist, $obj, $tabname[$id], 'edit');
+					}
 
 					print '<td colspan="3" class="right"><a name="'.(!empty($obj->rowid) ? $obj->rowid : $obj->code).'">&nbsp;</a><input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
 					print '&nbsp;<input type="submit" class="button button-cancel" name="actioncancel" value="'.$langs->trans("Cancel").'"></td>';
 				} else {
-				  	$tmpaction = 'view';
+					$tmpaction = 'view';
 					$parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
 					$reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
 
 					$error = $hookmanager->error; $errors = $hookmanager->errors;
 
-					if (empty($reshook))
-					{
-						foreach ($fieldlist as $field => $value)
-						{
+					if (empty($reshook)) {
+						foreach ($fieldlist as $field => $value) {
 							$showfield = 1;
 							$class = "left";
 							$valuetoshow = $obj->{$fieldlist[$field]};
-							if ($value == 'type_template')
-							{
+							if ($value == 'type_template') {
 								$valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow;
 							}
-							if ($value == 'element')
-							{
+							if ($value == 'element') {
 								$valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow;
-							} elseif ($value == 'source')
-							{
+							} elseif ($value == 'source') {
 								$valuetoshow = isset($sourceList[$valuetoshow]) ? $sourceList[$valuetoshow] : $valuetoshow;
 							} elseif ($valuetoshow == 'all') {
 								$valuetoshow = $langs->trans('All');
 							} elseif ($fieldlist[$field] == 'country') {
-								if (empty($obj->country_code))
-								{
+								if (empty($obj->country_code)) {
 									$valuetoshow = '-';
 								} else {
 									$key = $langs->trans("Country".strtoupper($obj->country_code));
@@ -645,9 +668,13 @@ if ($id)
 							}
 
 							$class = 'tddict';
-							if ($fieldlist[$field] == 'tracking') $class .= ' tdoverflowauto';
+							if ($fieldlist[$field] == 'tracking') {
+								$class .= ' tdoverflowauto';
+							}
 							// Show value for field
-							if ($showfield) print '<!-- '.$fieldlist[$field].' --><td class="'.$class.'">'.$valuetoshow.'</td>';
+							if ($showfield) {
+								print '<!-- '.$fieldlist[$field].' --><td class="'.$class.'">'.$valuetoshow.'</td>';
+							}
 						}
 					}
 
@@ -655,22 +682,33 @@ if ($id)
 					$iserasable = 1; $canbedisabled = 1; $canbemodified = 1; // true by default
 
 					$url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '');
-					if ($param) $url .= '&'.$param;
+					if ($param) {
+						$url .= '&'.$param;
+					}
 					$url .= '&';
 
 					// Active
 					print '<td class="center nowrap">';
-					if ($canbedisabled) print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
-					else print $langs->trans("AlwaysActive");
+					if ($canbedisabled) {
+						print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
+					} else {
+						print $langs->trans("AlwaysActive");
+					}
 					print "</td>";
 
 					// Modify link
-					if ($canbemodified) print '<td class="center"><a class="reposition editfielda" href="'.$url.'action=edit&token='.newToken().'">'.img_edit().'</a></td>';
-					else print '<td>&nbsp;</td>';
+					if ($canbemodified) {
+						print '<td class="center"><a class="reposition editfielda" href="'.$url.'action=edit&token='.newToken().'">'.img_edit().'</a></td>';
+					} else {
+						print '<td>&nbsp;</td>';
+					}
 
 					// Delete link
-					if ($iserasable) print '<td class="center"><a href="'.$url.'action=delete&token='.newToken().'">'.img_delete().'</a></td>';
-					else print '<td>&nbsp;</td>';
+					if ($iserasable) {
+						print '<td class="center"><a href="'.$url.'action=delete&token='.newToken().'">'.img_delete().'</a></td>';
+					} else {
+						print '<td>&nbsp;</td>';
+					}
 
 					print "</tr>\n";
 				}
@@ -714,12 +752,9 @@ function fieldListAccountModel($fieldlist, $obj = '', $tabname = '', $context =
 	$formcompany = new FormCompany($db);
 	$formaccounting = new FormAccounting($db);
 
-	foreach ($fieldlist as $field => $value)
-	{
-		if ($fieldlist[$field] == 'country')
-		{
-			if (in_array('region_id', $fieldlist))
-			{
+	foreach ($fieldlist as $field => $value) {
+		if ($fieldlist[$field] == 'country') {
+			if (in_array('region_id', $fieldlist)) {
 				print '<td>';
 				//print join(',',$fieldlist);
 				print '</td>';
@@ -729,18 +764,19 @@ function fieldListAccountModel($fieldlist, $obj = '', $tabname = '', $context =
 			$fieldname = 'country';
 			print $form->select_country((!empty($obj->country_code) ? $obj->country_code : (!empty($obj->country) ? $obj->country : '')), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone');
 			print '</td>';
-		} elseif ($fieldlist[$field] == 'country_id')
-		{
-			if (!in_array('country', $fieldlist))	// If there is already a field country, we don't show country_id (avoid duplicate)
-			{
+		} elseif ($fieldlist[$field] == 'country_id') {
+			if (!in_array('country', $fieldlist)) {	// If there is already a field country, we don't show country_id (avoid duplicate)
 				$country_id = (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]} : 0);
 				print '<td>';
 				print '<input type="hidden" name="'.$fieldlist[$field].'" value="'.$country_id.'">';
 				print '</td>';
 			}
 		} elseif ($fieldlist[$field] == 'type_cdr') {
-			if ($fieldlist[$field] == 'type_cdr') print '<td class="center">';
-			else print '<td>';
+			if ($fieldlist[$field] == 'type_cdr') {
+				print '<td class="center">';
+			} else {
+				print '<td>';
+			}
 			if ($fieldlist[$field] == 'type_cdr') {
 				print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''));
 			} else {
@@ -752,10 +788,18 @@ function fieldListAccountModel($fieldlist, $obj = '', $tabname = '', $context =
 		} else {
 			print '<td>';
 			$size = ''; $class = '';
-			if ($fieldlist[$field] == 'code') $size = 'size="8" ';
-			if ($fieldlist[$field] == 'position') $size = 'size="4" ';
-			if ($fieldlist[$field] == 'libelle') $size = 'centpercent';
-			if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'sens' || $fieldlist[$field] == 'category_type') $size = 'size="2" ';
+			if ($fieldlist[$field] == 'code') {
+				$size = 'size="8" ';
+			}
+			if ($fieldlist[$field] == 'position') {
+				$size = 'size="4" ';
+			}
+			if ($fieldlist[$field] == 'libelle') {
+				$size = 'centpercent';
+			}
+			if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'sens' || $fieldlist[$field] == 'category_type') {
+				$size = 'size="2" ';
+			}
 			print '<input type="text" '.$size.' class="flat'.($class ? ' '.$class : '').'" value="'.(isset($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'">';
 			print '</td>';
 		}

+ 13 - 16
htdocs/accountancy/admin/card.php

@@ -46,8 +46,12 @@ $account_number = GETPOST('account_number', 'string');
 $label = GETPOST('label', 'alpha');
 
 // Security check
-if ($user->socid > 0) accessforbidden();
-if (!$user->rights->accounting->chartofaccount) accessforbidden();
+if ($user->socid > 0) {
+	accessforbidden();
+}
+if (!$user->rights->accounting->chartofaccount) {
+	accessforbidden();
+}
 
 
 $object = new AccountingAccount($db);
@@ -57,22 +61,18 @@ $object = new AccountingAccount($db);
  * Action
  */
 
-if (GETPOST('cancel', 'alpha'))
-{
+if (GETPOST('cancel', 'alpha')) {
 	$urltogo = $backtopage ? $backtopage : dol_buildpath('/accountancy/admin/account.php', 1);
 	header("Location: ".$urltogo);
 	exit;
 }
 
-if ($action == 'add' && $user->rights->accounting->chartofaccount)
-{
+if ($action == 'add' && $user->rights->accounting->chartofaccount) {
 	if (!$cancel) {
-		if (!$account_number)
-		{
+		if (!$account_number) {
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountNumber")), null, 'errors');
 			$action = 'create';
-		} elseif (!$label)
-		{
+		} elseif (!$label) {
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors');
 			$action = 'create';
 		} else {
@@ -130,12 +130,10 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount)
 	}
 } elseif ($action == 'edit' && $user->rights->accounting->chartofaccount) {
 	if (!$cancel) {
-		if (!$account_number)
-		{
+		if (!$account_number) {
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountNumber")), null, 'errors');
 			$action = 'update';
-		} elseif (!$label)
-		{
+		} elseif (!$label) {
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors');
 			$action = 'update';
 		} else {
@@ -286,8 +284,7 @@ if ($action == 'create') {
 		$head = accounting_prepare_head($object);
 
 		// Edit mode
-		if ($action == 'update')
-		{
+		if ($action == 'update') {
 			print dol_get_fiche_head($head, 'card', $langs->trans('AccountAccounting'), 0, 'billr');
 
 			print '<form name="update" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n";

+ 7 - 9
htdocs/accountancy/admin/categories.php

@@ -46,8 +46,7 @@ if ($cat_id == 0) {
 }
 
 // Security check
-if (empty($user->rights->accounting->chartofaccount))
-{
+if (empty($user->rights->accounting->chartofaccount)) {
 	accessforbidden();
 }
 
@@ -62,8 +61,9 @@ $accountingcategory = new AccountancyCategory($db);
 if (!empty($selectcpt)) {
 	$cpts = array();
 	foreach ($selectcpt as $selectedoption) {
-		if (!array_key_exists($selectedoption, $cpts))
+		if (!array_key_exists($selectedoption, $cpts)) {
 			$cpts[$selectedoption] = "'".$selectedoption."'";
+		}
 	}
 
 	$return = $accountingcategory->updateAccAcc($cat_id, $cpts);
@@ -114,8 +114,7 @@ print '<input class="button" type="submit" value="'.$langs->trans("Select").'">'
 print '</td></tr>';
 
 // Select the accounts
-if (!empty($cat_id))
-{
+if (!empty($cat_id)) {
 	$return = $accountingcategory->getAccountsWithNoCategory($cat_id);
 	if ($return < 0) {
 		setEventMessages(null, $accountingcategory->errors, 'errors');
@@ -124,8 +123,7 @@ if (!empty($cat_id))
 	print '<td>';
 
 	$arraykeyvalue = array();
-	foreach ($accountingcategory->lines_cptbk as $key => $val)
-	{
+	foreach ($accountingcategory->lines_cptbk as $key => $val) {
 		$arraykeyvalue[length_accountg($val->numero_compte)] = length_accountg($val->numero_compte).' ('.$val->label_compte.($val->doc_ref ? ' '.$val->doc_ref : '').')';
 	}
 
@@ -152,8 +150,8 @@ print '</form>';
 
 
 if ($action == 'display' || $action == 'delete') {
-    print "<table class='noborder' width='100%'>\n";
-    print '<tr class="liste_titre">';
+	print "<table class='noborder' width='100%'>\n";
+	print '<tr class="liste_titre">';
 	print '<td class="liste_titre">'.$langs->trans("AccountAccounting")."</td>";
 	print '<td class="liste_titre" colspan="2">'.$langs->trans("Label")."</td>";
 	print "</tr>\n";

+ 229 - 175
htdocs/accountancy/admin/categories_list.php

@@ -57,7 +57,9 @@ $active = 1;
 $sortfield = GETPOST("sortfield", 'aZ09comma');
 $sortorder = GETPOST("sortorder", 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $listlimit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
@@ -133,14 +135,12 @@ $sourceList = array();
  * Actions
  */
 
-if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter_x', 'alpha'))
-{
+if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter_x', 'alpha')) {
 	$search_country_id = '';
 }
 
 // Actions add or modify an entry into a dictionary
-if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
-{
+if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) {
 	$listfield = explode(',', str_replace(' ', '', $tabfield[$id]));
 	$listfieldinsert = explode(',', $tabfieldinsert[$id]);
 	$listfieldmodify = explode(',', $tabfieldinsert[$id]);
@@ -148,57 +148,73 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 
 	// Check that all fields are filled
 	$ok = 1;
-	foreach ($listfield as $f => $value)
-	{
-		if ($value == 'formula' && empty($_POST['formula'])) continue;
-		if ($value == 'range_account' && empty($_POST['range_account'])) continue;
-		if ($value == 'country' || $value == 'country_id') continue;
-		if (!GETPOSTISSET($value) || GETPOST($value) == '')
-		{
+	foreach ($listfield as $f => $value) {
+		if ($value == 'formula' && empty($_POST['formula'])) {
+			continue;
+		}
+		if ($value == 'range_account' && empty($_POST['range_account'])) {
+			continue;
+		}
+		if ($value == 'country' || $value == 'country_id') {
+			continue;
+		}
+		if (!GETPOSTISSET($value) || GETPOST($value) == '') {
 			$ok = 0;
 			$fieldnamekey = $listfield[$f];
 			// We take translate key of field
-			if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label'))  $fieldnamekey = 'Label';
-			if ($fieldnamekey == 'code') $fieldnamekey = 'Code';
-			if ($fieldnamekey == 'note') $fieldnamekey = 'Note';
-			if ($fieldnamekey == 'type') $fieldnamekey = 'Type';
-			if ($fieldnamekey == 'position') $fieldnamekey = 'Position';
-			if ($fieldnamekey == 'category_type') $fieldnamekey = 'Calculated';
+			if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) {
+				$fieldnamekey = 'Label';
+			}
+			if ($fieldnamekey == 'code') {
+				$fieldnamekey = 'Code';
+			}
+			if ($fieldnamekey == 'note') {
+				$fieldnamekey = 'Note';
+			}
+			if ($fieldnamekey == 'type') {
+				$fieldnamekey = 'Type';
+			}
+			if ($fieldnamekey == 'position') {
+				$fieldnamekey = 'Position';
+			}
+			if ($fieldnamekey == 'category_type') {
+				$fieldnamekey = 'Calculated';
+			}
 
 			setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors');
 		}
 	}
-	if (GETPOSTISSET("code"))
-	{
-		if ($_POST["code"] == '0')
-		{
+	if (GETPOSTISSET("code")) {
+		if ($_POST["code"] == '0') {
 			$ok = 0;
 			setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors');
 		}
 	}
-	if (!is_numeric(GETPOST('position', 'alpha')))
-	{
+	if (!is_numeric(GETPOST('position', 'alpha'))) {
 		$langs->loadLangs(array("errors"));
-   		$ok = 0;
-   		setEventMessages($langs->transnoentities('ErrorFieldMustBeANumeric', $langs->transnoentities("Position")), null, 'errors');
+		$ok = 0;
+		setEventMessages($langs->transnoentities('ErrorFieldMustBeANumeric', $langs->transnoentities("Position")), null, 'errors');
 	}
 
 	// Clean some parameters
-	if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"] = ''; // If empty, we force to null
-	if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"] = ''; // If empty, we force to null
-	if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"] = ''; // If empty, we force to null
+	if ($_POST["accountancy_code"] <= 0) {
+		$_POST["accountancy_code"] = ''; // If empty, we force to null
+	}
+	if ($_POST["accountancy_code_sell"] <= 0) {
+		$_POST["accountancy_code_sell"] = ''; // If empty, we force to null
+	}
+	if ($_POST["accountancy_code_buy"] <= 0) {
+		$_POST["accountancy_code_buy"] = ''; // If empty, we force to null
+	}
 
 	// Si verif ok et action add, on ajoute la ligne
-	if ($ok && GETPOST('actionadd', 'alpha'))
-	{
-		if ($tabrowid[$id])
-		{
+	if ($ok && GETPOST('actionadd', 'alpha')) {
+		if ($tabrowid[$id]) {
 			// Recupere id libre pour insertion
 			$newid = 0;
 			$sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id];
 			$result = $db->query($sql);
-			if ($result)
-			{
+			if ($result) {
 				$obj = $db->fetch_object($result);
 				$newid = ($obj->newid + 1);
 			} else {
@@ -209,30 +225,37 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 		// Add new entry
 		$sql = "INSERT INTO ".$tabname[$id]." (";
 		// List of fields
-		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) $sql .= $tabrowid[$id].",";
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) {
+			$sql .= $tabrowid[$id].",";
+		}
 		$sql .= $tabfieldinsert[$id];
 		$sql .= ",active)";
 		$sql .= " VALUES(";
 
 		// List of values
-		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) $sql .= $newid.",";
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) {
+			$sql .= $newid.",";
+		}
 		$i = 0;
-		foreach ($listfieldinsert as $f => $value)
-		{
+		foreach ($listfieldinsert as $f => $value) {
 			if ($value == 'entity') {
 				$_POST[$listfieldvalue[$i]] = $conf->entity;
 			}
-			if ($i) $sql .= ",";
-			if ($_POST[$listfieldvalue[$i]] == '' && !$listfieldvalue[$i] == 'formula') $sql .= "null"; // For vat, we want/accept code = ''
-			else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			if ($i) {
+				$sql .= ",";
+			}
+			if ($_POST[$listfieldvalue[$i]] == '' && !$listfieldvalue[$i] == 'formula') {
+				$sql .= "null"; // For vat, we want/accept code = ''
+			} else {
+				$sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			}
 			$i++;
 		}
 		$sql .= ",1)";
 
 		dol_syslog("actionadd", LOG_DEBUG);
 		$result = $db->query($sql);
-		if ($result)	// Add is ok
-		{
+		if ($result) {	// Add is ok
 			setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
 			$_POST = array('id'=>$id); // Clean $_POST array, we keep only
 		} else {
@@ -245,30 +268,36 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 	}
 
 	// Si verif ok et action modify, on modifie la ligne
-	if ($ok && GETPOST('actionmodify', 'alpha'))
-	{
-		if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+	if ($ok && GETPOST('actionmodify', 'alpha')) {
+		if ($tabrowid[$id]) {
+			$rowidcol = $tabrowid[$id];
+		} else {
+			$rowidcol = "rowid";
+		}
 
 		// Modify entry
 		$sql = "UPDATE ".$tabname[$id]." SET ";
 		// Modifie valeur des champs
-		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify))
-		{
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) {
 			$sql .= $tabrowid[$id]."=";
 			$sql .= "'".$db->escape($rowid)."', ";
 		}
 		$i = 0;
-		foreach ($listfieldmodify as $field)
-		{
+		foreach ($listfieldmodify as $field) {
 			if ($field == 'fk_country' && $_POST['country'] > 0) {
 				$_POST[$listfieldvalue[$i]] = $_POST['country'];
 			} elseif ($field == 'entity') {
 				$_POST[$listfieldvalue[$i]] = $conf->entity;
 			}
-			if ($i) $sql .= ",";
+			if ($i) {
+				$sql .= ",";
+			}
 			$sql .= $field."=";
-			if ($_POST[$listfieldvalue[$i]] == '' && !$listfieldvalue[$i] == 'range_account') $sql .= "null"; // For range_account, we want/accept code = ''
-			else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			if ($_POST[$listfieldvalue[$i]] == '' && !$listfieldvalue[$i] == 'range_account') {
+				$sql .= "null"; // For range_account, we want/accept code = ''
+			} else {
+				$sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			}
 			$i++;
 		}
 		$sql .= " WHERE ".$rowidcol." = ".((int) $rowid);
@@ -276,31 +305,30 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 		dol_syslog("actionmodify", LOG_DEBUG);
 		//print $sql;
 		$resql = $db->query($sql);
-		if (!$resql)
-		{
+		if (!$resql) {
 			setEventMessages($db->error(), null, 'errors');
 		}
 	}
 	//$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
 }
 
-if (GETPOST('actioncancel', 'alpha'))
-{
+if (GETPOST('actioncancel', 'alpha')) {
 	//$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
 }
 
-if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == 'confirm_delete' && $confirm == 'yes') {       // delete
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	$sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol." = ".((int) $rowid);
 
 	dol_syslog("delete", LOG_DEBUG);
 	$result = $db->query($sql);
-	if (!$result)
-	{
-		if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
-		{
+	if (!$result) {
+		if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') {
 			setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
 		} else {
 			dol_print_error($db);
@@ -309,9 +337,12 @@ if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
 }
 
 // activate
-if ($action == $acts[0])
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == $acts[0]) {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -320,16 +351,18 @@ if ($action == $acts[0])
 	}
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
 
 // disable
-if ($action == $acts[1])
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == $acts[1]) {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -338,16 +371,18 @@ if ($action == $acts[1])
 	}
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
 
 // favorite
-if ($action == 'activate_favorite')
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == 'activate_favorite') {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -356,16 +391,18 @@ if ($action == 'activate_favorite')
 	}
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
 
 // disable favorite
-if ($action == 'disable_favorite')
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == 'disable_favorite') {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -374,8 +411,7 @@ if ($action == 'disable_favorite')
 	}
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
@@ -399,8 +435,7 @@ print load_fiche_titre($titre, $linkback, $titlepicto);
 print '<span class="opacitymedium">'.$langs->trans("AccountingAccountGroupsDesc", $langs->transnoentitiesnoconv("ByPersonalizedAccountGroups")).'</span><br><br>';
 
 // Confirmation de la suppression de la ligne
-if ($action == 'delete')
-{
+if ($action == 'delete') {
 	print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id.($search_country_id > 0 ? '&search_country_id='.$search_country_id : ''), $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1);
 }
 //var_dump($elementList);
@@ -408,20 +443,23 @@ if ($action == 'delete')
 /*
  * Show a dictionary
  */
-if ($id)
-{
+if ($id) {
 	// Complete requete recherche valeurs avec critere de tri
 	$sql = $tabsql[$id];
 
-	if ($search_country_id > 0)
-	{
-		if (preg_match('/ WHERE /', $sql)) $sql .= " AND ";
-		else $sql .= " WHERE ";
+	if ($search_country_id > 0) {
+		if (preg_match('/ WHERE /', $sql)) {
+			$sql .= " AND ";
+		} else {
+			$sql .= " WHERE ";
+		}
 		$sql .= " (a.fk_country = ".$search_country_id." OR a.fk_country = 0)";
 	}
 
 	// If sort order is "country", we use country_code instead
-	if ($sortfield == 'country') $sortfield = 'country_code';
+	if ($sortfield == 'country') {
+		$sortfield = 'country_code';
+	}
 	$sql .= $db->order($sortfield, $sortorder);
 	$sql .= $db->plimit($listlimit + 1, $offset);
 	//print $sql;
@@ -436,14 +474,12 @@ if ($id)
 	print '<table class="noborder centpercent">';
 
 	// Form to add a new line
-	if ($tabname[$id])
-	{
+	if ($tabname[$id]) {
 		$fieldlist = explode(',', $tabfield[$id]);
 
 		// Line for title
 		print '<tr class="liste_titre">';
-		foreach ($fieldlist as $field => $value)
-		{
+		foreach ($fieldlist as $field => $value) {
 			// Determine le nom du champ par rapport aux noms possibles
 			// dans les dictionnaires de donnees
 			$valuetoshow = ucfirst($fieldlist[$field]); // Par defaut
@@ -489,9 +525,13 @@ if ($id)
 
 			if ($valuetoshow != '') {
 				print '<td class="'.$class.'">';
-				if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1, $valuetoshow).'</a>';
-				elseif (!empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]);
-				else print $valuetoshow;
+				if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) {
+					print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1, $valuetoshow).'</a>';
+				} elseif (!empty($tabhelp[$id][$value])) {
+					print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]);
+				} else {
+					print $valuetoshow;
+				}
 				print '</td>';
 			}
 		}
@@ -509,12 +549,11 @@ if ($id)
 
 		$obj = new stdClass();
 		// If data was already input, we define them in obj to populate input fields.
-		if (GETPOST('actionadd', 'alpha'))
-		{
-			foreach ($fieldlist as $key=>$val)
-			{
-				if (GETPOST($val) != '')
+		if (GETPOST('actionadd', 'alpha')) {
+			foreach ($fieldlist as $key => $val) {
+				if (GETPOST($val) != '') {
 					$obj->$val = GETPOST($val);
+				}
 			}
 		}
 
@@ -523,18 +562,19 @@ if ($id)
 		$reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
 		$error = $hookmanager->error; $errors = $hookmanager->errors;
 
-		if (empty($reshook))
-		{
-	   		fieldListAccountingCategories($fieldlist, $obj, $tabname[$id], 'add');
+		if (empty($reshook)) {
+			fieldListAccountingCategories($fieldlist, $obj, $tabname[$id], 'add');
 		}
 
 		print '<td colspan="4" class="right">';
-	   	print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
+		print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
 		print '</td>';
 		print "</tr>";
 
 		$colspan = count($fieldlist) + 3;
-		if ($id == 32) $colspan++;
+		if ($id == 32) {
+			$colspan++;
+		}
 
 		print '<tr><td colspan="'.$colspan.'">&nbsp;</td></tr>'; // Keep &nbsp; to have a line with enough height
 	}
@@ -542,20 +582,26 @@ if ($id)
 	// List of available record in database
 	dol_syslog("htdocs/admin/dict", LOG_DEBUG);
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$num = $db->num_rows($resql);
 		$i = 0;
 
 		$param = '&id='.$id;
-		if ($search_country_id > 0) $param .= '&search_country_id='.$search_country_id;
+		if ($search_country_id > 0) {
+			$param .= '&search_country_id='.$search_country_id;
+		}
 		$paramwithsearch = $param;
-		if ($sortorder) $paramwithsearch .= '&sortorder='.$sortorder;
-		if ($sortfield) $paramwithsearch .= '&sortfield='.$sortfield;
-		if (GETPOST('from', 'alpha')) $paramwithsearch .= '&from='.GETPOST('from', 'alpha');
+		if ($sortorder) {
+			$paramwithsearch .= '&sortorder='.$sortorder;
+		}
+		if ($sortfield) {
+			$paramwithsearch .= '&sortfield='.$sortfield;
+		}
+		if (GETPOST('from', 'alpha')) {
+			$paramwithsearch .= '&from='.GETPOST('from', 'alpha');
+		}
 		// There is several pages
-		if ($num > $listlimit)
-		{
+		if ($num > $listlimit) {
 			print '<tr class="none"><td class="right" colspan="'.(3 + count($fieldlist)).'">';
 			print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), '<li class="pagination"><span>'.$langs->trans("Page").' '.($page + 1).'</span></li>');
 			print '</td></tr>';
@@ -564,16 +610,15 @@ if ($id)
 		// Title line with search boxes
 		print '<tr class="liste_titre liste_titre_add liste_titre_filter">';
 		$filterfound = 0;
-		foreach ($fieldlist as $field => $value)
-		{
+		foreach ($fieldlist as $field => $value) {
 			$showfield = 1; // By defaut
 
-			if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; }
+			if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') {
+				$showfield = 0;
+			}
 
-			if ($showfield)
-			{
-				if ($value == 'country')
-				{
+			if ($showfield) {
+				if ($value == 'country') {
 					print '<td class="liste_titre">';
 					print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth200 maxwidthonsmartphone');
 					print '</td>';
@@ -587,8 +632,7 @@ if ($id)
 		print '<td class="liste_titre"></td>';
 		print '<td class="liste_titre"></td>';
 		print '<td class="liste_titre center">';
-		if ($filterfound)
-		{
+		if ($filterfound) {
 			$searchpicto = $form->showFilterAndCheckAddButtons(0);
 			print $searchpicto;
 		}
@@ -597,8 +641,7 @@ if ($id)
 
 		// Title of lines
 		print '<tr class="liste_titre">';
-		foreach ($fieldlist as $field => $value)
-		{
+		foreach ($fieldlist as $field => $value) {
 			// Determine le nom du champ par rapport aux noms possibles
 			// dans les dictionnaires de donnees
 			$showfield = 1; // By defaut
@@ -677,23 +720,22 @@ if ($id)
 		print getTitleFieldOfList('');
 		print '</tr>';
 
-		if ($num)
-		{
+		if ($num) {
 			// Lines with values
-			while ($i < $num)
-			{
+			while ($i < $num) {
 				$obj = $db->fetch_object($resql);
 				//print_r($obj);
 				print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
-				if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code)))
-				{
+				if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) {
 					$tmpaction = 'edit';
 					$parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
 					$reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
 					$error = $hookmanager->error; $errors = $hookmanager->errors;
 
 					// Show fields
-					if (empty($reshook)) fieldListAccountingCategories($fieldlist, $obj, $tabname[$id], 'edit');
+					if (empty($reshook)) {
+						fieldListAccountingCategories($fieldlist, $obj, $tabname[$id], 'edit');
+					}
 
 					print '<td></td>';
 					print '<td></td>';
@@ -712,21 +754,17 @@ if ($id)
 
 					$error = $hookmanager->error; $errors = $hookmanager->errors;
 
-					if (empty($reshook))
-					{
-						foreach ($fieldlist as $field => $value)
-						{
+					if (empty($reshook)) {
+						foreach ($fieldlist as $field => $value) {
 							$showfield = 1;
 							$class = "left";
 							$valuetoshow = $obj->{$fieldlist[$field]};
-							if ($value == 'category_type')
-							{
+							if ($value == 'category_type') {
 								$valuetoshow = yn($valuetoshow);
 							} elseif ($valuetoshow == 'all') {
 								$valuetoshow = $langs->trans('All');
 							} elseif ($fieldlist[$field] == 'country') {
-								if (empty($obj->country_code))
-								{
+								if (empty($obj->country_code)) {
 									$valuetoshow = '-';
 								} else {
 									$key = $langs->trans("Country".strtoupper($obj->country_code));
@@ -748,48 +786,59 @@ if ($id)
 
 							$class = 'tddict';
 							// Show value for field
-							if ($showfield) print '<!-- '.$fieldlist[$field].' --><td class="'.$class.'">'.$valuetoshow.'</td>';
+							if ($showfield) {
+								print '<!-- '.$fieldlist[$field].' --><td class="'.$class.'">'.$valuetoshow.'</td>';
+							}
 						}
 					}
 
 					// Can an entry be erased or disabled ?
 					$iserasable = 1; $canbedisabled = 1; $canbemodified = 1; // true by default
-					if (isset($obj->code))
-					{
-						if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i', $obj->code))) { $iserasable = 0; $canbedisabled = 0; }
+					if (isset($obj->code)) {
+						if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i', $obj->code))) {
+							$iserasable = 0; $canbedisabled = 0;
+						}
 					}
 
 					$canbemodified = $iserasable;
 
 					$url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '');
-					if ($param) $url .= '&'.$param;
+					if ($param) {
+						$url .= '&'.$param;
+					}
 					$url .= '&';
 
 					// Active
 					print '<td class="center" class="nowrap">';
-					if ($canbedisabled) print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
-					else {
+					if ($canbedisabled) {
+						print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
+					} else {
 						print $langs->trans("AlwaysActive");
 					}
 					print "</td>";
 
 					// Modify link
-					if ($canbemodified) print '<td class="center"><a class="reposition editfielda" href="'.$url.'action=edit">'.img_edit().'</a></td>';
-					else print '<td>&nbsp;</td>';
+					if ($canbemodified) {
+						print '<td class="center"><a class="reposition editfielda" href="'.$url.'action=edit">'.img_edit().'</a></td>';
+					} else {
+						print '<td>&nbsp;</td>';
+					}
 
 					// Delete link
-					if ($iserasable)
-					{
+					if ($iserasable) {
 						print '<td class="center">';
-						if ($user->admin) print '<a href="'.$url.'action=delete">'.img_delete().'</a>';
+						if ($user->admin) {
+							print '<a href="'.$url.'action=delete">'.img_delete().'</a>';
+						}
 						//else print '<a href="#">'.img_delete().'</a>';    // Some dictionary can be edited by other profile than admin
 						print '</td>';
-					} else print '<td>&nbsp;</td>';
+					} else {
+						print '<td>&nbsp;</td>';
+					}
 
 					// Link to setup the group
 					print '<td class="center">';
-					if (empty($obj->formula))
-					{
+					if (empty($obj->formula)) {
 						print '<a href="'.DOL_URL_ROOT.'/accountancy/admin/categories.php?action=display&save_lastsearch_values=1&account_category='.$obj->rowid.'">';
 						print $langs->trans("ListOfAccounts");
 						print '</a>';
@@ -836,26 +885,23 @@ function fieldListAccountingCategories($fieldlist, $obj = '', $tabname = '', $co
 
 	$formadmin = new FormAdmin($db);
 	$formcompany = new FormCompany($db);
-	if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db);
+	if (!empty($conf->accounting->enabled)) {
+		$formaccounting = new FormAccounting($db);
+	}
 
-	foreach ($fieldlist as $field => $value)
-	{
-		if ($fieldlist[$field] == 'country')
-		{
+	foreach ($fieldlist as $field => $value) {
+		if ($fieldlist[$field] == 'country') {
 			print '<td>';
 			$fieldname = 'country';
-			if ($context == 'add')
-			{
+			if ($context == 'add') {
 				$fieldname = 'country_id';
 				print $form->select_country(GETPOST('country_id', 'int'), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone');
 			} else {
 				print $form->select_country((!empty($obj->country_code) ? $obj->country_code : (!empty($obj->country) ? $obj->country : $mysoc->country_code)), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone');
 			}
 			print '</td>';
-		} elseif ($fieldlist[$field] == 'country_id')
-		{
-			if (!in_array('country', $fieldlist))	// If there is already a field country, we don't show country_id (avoid duplicate)
-			{
+		} elseif ($fieldlist[$field] == 'country_id') {
+			if (!in_array('country', $fieldlist)) {	// If there is already a field country, we don't show country_id (avoid duplicate)
 				$country_id = (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]} : 0);
 				print '<td>';
 				print '<input type="hidden" name="'.$fieldlist[$field].'" value="'.$country_id.'">';
@@ -870,10 +916,18 @@ function fieldListAccountingCategories($fieldlist, $obj = '', $tabname = '', $co
 		} else {
 			print '<td>';
 			$size = ''; $class = '';
-			if ($fieldlist[$field] == 'code') $class = 'maxwidth100';
-			if ($fieldlist[$field] == 'position') $class = 'maxwidth50';
-			if ($fieldlist[$field] == 'libelle') $class = 'quatrevingtpercent';
-			if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'category_type') $size = 'size="2" ';
+			if ($fieldlist[$field] == 'code') {
+				$class = 'maxwidth100';
+			}
+			if ($fieldlist[$field] == 'position') {
+				$class = 'maxwidth50';
+			}
+			if ($fieldlist[$field] == 'libelle') {
+				$class = 'quatrevingtpercent';
+			}
+			if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'category_type') {
+				$size = 'size="2" ';
+			}
 			print '<input type="text" '.$size.'class="flat'.($class ? ' '.$class : '').'" value="'.(isset($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'">';
 			print '</td>';
 		}

+ 0 - 1
htdocs/accountancy/admin/closure.php

@@ -62,7 +62,6 @@ if ($action == 'update') {
 
 	foreach ($list_account_main as $constname) {
 		$constvalue = GETPOST($constname, 'alpha');
-
 		if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) {
 			$error++;
 		}

+ 1 - 2
htdocs/accountancy/admin/defaultaccounts.php

@@ -38,8 +38,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
 $langs->loadLangs(array("compta", "bills", "admin", "accountancy", "salaries", "loan"));
 
 // Security check
-if (empty($user->rights->accounting->chartofaccount))
-{
+if (empty($user->rights->accounting->chartofaccount)) {
 	accessforbidden();
 }
 

+ 1 - 2
htdocs/accountancy/admin/export.php

@@ -36,8 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancyexport.class.php';
 $langs->loadLangs(array("compta", "bills", "admin", "accountancy"));
 
 // Security access
-if (empty($user->rights->accounting->chartofaccount))
-{
+if (empty($user->rights->accounting->chartofaccount)) {
 	accessforbidden();
 }
 

+ 18 - 12
htdocs/accountancy/admin/fiscalyear.php

@@ -32,21 +32,29 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield) $sortfield = "f.rowid"; // Set here default search field
-if (!$sortorder) $sortorder = "ASC";
+if (!$sortfield) {
+	$sortfield = "f.rowid"; // Set here default search field
+}
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
 
 // Load translation files required by the page
 $langs->loadLangs(array("admin", "compta"));
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->fiscalyear->write)              // If we can read accounting records, we should be able to see fiscal year.
+}
+if (!$user->rights->accounting->fiscalyear->write) {              // If we can read accounting records, we should be able to see fiscal year.
 	accessforbidden();
+}
 
 $error = 0;
 
@@ -58,8 +66,9 @@ static $tmpstatut2label = array(
 $statut2label = array(
 		''
 );
-foreach ($tmpstatut2label as $key => $val)
+foreach ($tmpstatut2label as $key => $val) {
 	$statut2label[$key] = $langs->trans($val);
+}
 
 $errors = array();
 
@@ -92,12 +101,10 @@ $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$result = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($result);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -106,8 +113,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
 $sql .= $db->plimit($limit + 1, $offset);
 
 $result = $db->query($sql);
-if ($result)
-{
+if ($result) {
 	$num = $db->num_rows($result);
 
 	$i = 0;

+ 12 - 13
htdocs/accountancy/admin/fiscalyear_card.php

@@ -31,10 +31,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php';
 $langs->loadLangs(array("admin", "compta"));
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (empty($user->rights->accounting->fiscalyear->write))
+}
+if (empty($user->rights->accounting->fiscalyear->write)) {
 	accessforbidden();
+}
 
 $error = 0;
 
@@ -50,8 +52,9 @@ static $tmpstatut2label = array(
 $statut2label = array(
 		''
 );
-foreach ($tmpstatut2label as $key => $val)
+foreach ($tmpstatut2label as $key => $val) {
 	$statut2label[$key] = $langs->trans($val);
+}
 
 $object = new Fiscalyear($db);
 
@@ -113,10 +116,8 @@ if ($action == 'confirm_delete' && $confirm == "yes") {
 		header("Location: ./fiscalyear.php");
 		exit();
 	}
-}
-
-// Update record
-elseif ($action == 'update') {
+} elseif ($action == 'update') {
+	// Update record
 	if (!GETPOST('cancel', 'alpha')) {
 		$result = $object->fetch($id);
 
@@ -151,8 +152,7 @@ $title = $langs->trans("Fiscalyear")." - ".$langs->trans("Card");
 $helpurl = "";
 llxHeader("", $title, $helpurl);
 
-if ($action == 'create')
-{
+if ($action == 'create') {
 	print load_fiche_titre($langs->trans("NewFiscalYear"));
 
 	print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
@@ -298,11 +298,10 @@ if ($action == 'create')
 
 			print dol_get_fiche_end();
 
-			if (!empty($user->rights->accounting->fiscalyear->write))
-			{
+			if (!empty($user->rights->accounting->fiscalyear->write)) {
 				/*
-    			 * Barre d'actions
-    			 */
+				 * Barre d'actions
+				 */
 				print '<div class="tabsAction">';
 
 				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&token='.newToken().'&id='.$id.'">'.$langs->trans('Modify').'</a>';

+ 4 - 2
htdocs/accountancy/admin/fiscalyear_info.php

@@ -30,10 +30,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php';
 $langs->loadLangs(array("admin", "compta"));
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->fiscalyear->write)
+}
+if (!$user->rights->accounting->fiscalyear->write) {
 	accessforbidden();
+}
 
 $id = GETPOST('id', 'int');
 

+ 1 - 0
htdocs/accountancy/admin/index.php

@@ -279,6 +279,7 @@ print '</tr>';
 
 print '<tr class="oddeven">';
 print '<td>'.$langs->trans("ACCOUNTANCY_COMBO_FOR_AUX").'</td>';
+
 if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) {
 	print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?token='.newToken().'&enablesubsidiarylist&value=0">';
 	print img_picto($langs->trans("Activated"), 'switch_on');

+ 182 - 139
htdocs/accountancy/admin/journals_list.php

@@ -22,7 +22,9 @@
  * \brief		Setup page to configure journals
  */
 
-if (!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET
+if (!defined('CSRFCHECK_WITH_TOKEN')) {
+	define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET
+}
 
 require '../../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
@@ -43,8 +45,7 @@ $rowid = GETPOST('rowid', 'alpha');
 $code = GETPOST('code', 'alpha');
 
 // Security access
-if (empty($user->rights->accounting->chartofaccount))
-{
+if (empty($user->rights->accounting->chartofaccount)) {
 	accessforbidden();
 }
 
@@ -60,12 +61,18 @@ $active = 1;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $listlimit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (empty($sortfield)) $sortfield = 'code';
-if (empty($sortorder)) $sortorder = 'ASC';
+if (empty($sortfield)) {
+	$sortfield = 'code';
+}
+if (empty($sortorder)) {
+	$sortorder = 'ASC';
+}
 
 $error = 0;
 
@@ -145,14 +152,12 @@ $sourceList = array(
  * Actions
  */
 
-if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter_x', 'alpha'))
-{
+if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter_x', 'alpha')) {
 	$search_country_id = '';
 }
 
 // Actions add or modify an entry into a dictionary
-if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
-{
+if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) {
 	$listfield = explode(',', str_replace(' ', '', $tabfield[$id]));
 	$listfieldinsert = explode(',', $tabfieldinsert[$id]);
 	$listfieldmodify = explode(',', $tabfieldinsert[$id]);
@@ -160,48 +165,53 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 
 	// Check that all fields are filled
 	$ok = 1;
-	foreach ($listfield as $f => $value)
-	{
-		if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label'))  $fieldnamekey = 'Label';
-		if ($fieldnamekey == 'code') $fieldnamekey = 'Code';
-		if ($fieldnamekey == 'nature') $fieldnamekey = 'NatureOfJournal';
+	foreach ($listfield as $f => $value) {
+		if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) {
+			$fieldnamekey = 'Label';
+		}
+		if ($fieldnamekey == 'code') {
+			$fieldnamekey = 'Code';
+		}
+		if ($fieldnamekey == 'nature') {
+			$fieldnamekey = 'NatureOfJournal';
+		}
 	}
 	// Other checks
-	if (GETPOSTISSET("code"))
-	{
-		if (GETPOST("code") == '0')
-		{
+	if (GETPOSTISSET("code")) {
+		if (GETPOST("code") == '0') {
 			$ok = 0;
 			setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors');
 		}
 		/*if (!is_numeric($_POST['code']))	// disabled, code may not be in numeric base
-    	{
-	    	$ok = 0;
-	    	$msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'<br>';
-	    }*/
+		{
+			$ok = 0;
+			$msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'<br>';
+		}*/
 	}
-	if (!GETPOST('label', 'alpha'))
-	{
+	if (!GETPOST('label', 'alpha')) {
 		setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
 		$ok = 0;
 	}
 
 	// Clean some parameters
-	if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"] = ''; // If empty, we force to null
-	if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"] = ''; // If empty, we force to null
-	if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"] = ''; // If empty, we force to null
+	if ($_POST["accountancy_code"] <= 0) {
+		$_POST["accountancy_code"] = ''; // If empty, we force to null
+	}
+	if ($_POST["accountancy_code_sell"] <= 0) {
+		$_POST["accountancy_code_sell"] = ''; // If empty, we force to null
+	}
+	if ($_POST["accountancy_code_buy"] <= 0) {
+		$_POST["accountancy_code_buy"] = ''; // If empty, we force to null
+	}
 
 	// Si verif ok et action add, on ajoute la ligne
-	if ($ok && GETPOST('actionadd', 'alpha'))
-	{
-		if ($tabrowid[$id])
-		{
+	if ($ok && GETPOST('actionadd', 'alpha')) {
+		if ($tabrowid[$id]) {
 			// Recupere id libre pour insertion
 			$newid = 0;
 			$sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id];
 			$result = $db->query($sql);
-			if ($result)
-			{
+			if ($result) {
 				$obj = $db->fetch_object($result);
 				$newid = ($obj->newid + 1);
 			} else {
@@ -212,32 +222,37 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 		// Add new entry
 		$sql = "INSERT INTO ".$tabname[$id]." (";
 		// List of fields
-		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert))
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) {
 			$sql .= $tabrowid[$id].",";
+		}
 		$sql .= $tabfieldinsert[$id];
 		$sql .= ",active,entity)";
 		$sql .= " VALUES(";
 
 		// List of values
-		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert))
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) {
 			$sql .= $newid.",";
+		}
 		$i = 0;
-		foreach ($listfieldinsert as $f => $value)
-		{
+		foreach ($listfieldinsert as $f => $value) {
 			if ($value == 'entity') {
 				$_POST[$listfieldvalue[$i]] = $conf->entity;
 			}
-			if ($i) $sql .= ",";
-			if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; // For vat, we want/accept code = ''
-			else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			if ($i) {
+				$sql .= ",";
+			}
+			if ($_POST[$listfieldvalue[$i]] == '') {
+				$sql .= "null"; // For vat, we want/accept code = ''
+			} else {
+				$sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			}
 			$i++;
 		}
 		$sql .= ",1,".$conf->entity.")";
 
 		dol_syslog("actionadd", LOG_DEBUG);
 		$result = $db->query($sql);
-		if ($result)	// Add is ok
-		{
+		if ($result) {	// Add is ok
 			setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
 			$_POST = array('id'=>$id); // Clean $_POST array, we keep only
 		} else {
@@ -250,30 +265,36 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 	}
 
 	// Si verif ok et action modify, on modifie la ligne
-	if ($ok && GETPOST('actionmodify', 'alpha'))
-	{
-		if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+	if ($ok && GETPOST('actionmodify', 'alpha')) {
+		if ($tabrowid[$id]) {
+			$rowidcol = $tabrowid[$id];
+		} else {
+			$rowidcol = "rowid";
+		}
 
 		// Modify entry
 		$sql = "UPDATE ".$tabname[$id]." SET ";
 		// Modifie valeur des champs
-		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify))
-		{
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) {
 			$sql .= $tabrowid[$id]."=";
 			$sql .= "'".$db->escape($rowid)."', ";
 		}
 		$i = 0;
-		foreach ($listfieldmodify as $field)
-		{
+		foreach ($listfieldmodify as $field) {
 			if ($field == 'price' || preg_match('/^amount/i', $field) || $field == 'taux') {
 				$_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]], 'MU');
 			} elseif ($field == 'entity') {
 				$_POST[$listfieldvalue[$i]] = $conf->entity;
 			}
-			if ($i) $sql .= ",";
+			if ($i) {
+				$sql .= ",";
+			}
 			$sql .= $field."=";
-			if ($_POST[$listfieldvalue[$i]] == '' && !($listfieldvalue[$i] == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = ''
-			else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			if ($_POST[$listfieldvalue[$i]] == '' && !($listfieldvalue[$i] == 'code' && $id == 10)) {
+				$sql .= "null"; // For vat, we want/accept code = ''
+			} else {
+				$sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			}
 			$i++;
 		}
 		$sql .= " WHERE ".$rowidcol." = ".((int) $rowid);
@@ -282,8 +303,7 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 		dol_syslog("actionmodify", LOG_DEBUG);
 		//print $sql;
 		$resql = $db->query($sql);
-		if (!$resql)
-		{
+		if (!$resql) {
 			setEventMessages($db->error(), null, 'errors');
 		}
 	}
@@ -295,19 +315,20 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 //	$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
 //}
 
-if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == 'confirm_delete' && $confirm == 'yes') {       // delete
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	$sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol." = ".((int) $rowid);
 	$sql .= " AND entity = ".$conf->entity;
 
 	dol_syslog("delete", LOG_DEBUG);
 	$result = $db->query($sql);
-	if (!$result)
-	{
-		if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
-		{
+	if (!$result) {
+		if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') {
 			setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
 		} else {
 			dol_print_error($db);
@@ -316,9 +337,12 @@ if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
 }
 
 // activate
-if ($action == $acts[0])
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == $acts[0]) {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -328,16 +352,18 @@ if ($action == $acts[0])
 	$sql .= " AND entity = ".$conf->entity;
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
 
 // disable
-if ($action == $acts[1])
-{
-	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+if ($action == $acts[1]) {
+	if ($tabrowid[$id]) {
+		$rowidcol = $tabrowid[$id];
+	} else {
+		$rowidcol = "rowid";
+	}
 
 	if ($rowid) {
 		$sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol." = ".((int) $rowid);
@@ -347,8 +373,7 @@ if ($action == $acts[1])
 	$sql .= " AND entity = ".$conf->entity;
 
 	$result = $db->query($sql);
-	if (!$result)
-	{
+	if (!$result) {
 		dol_print_error($db);
 	}
 }
@@ -365,8 +390,7 @@ llxHeader();
 
 $titre = $langs->trans("DictionarySetup");
 $linkback = '';
-if ($id)
-{
+if ($id) {
 	$titre .= ' - '.$langs->trans($tablib[$id]);
 	$titlepicto = 'title_accountancy';
 }
@@ -375,8 +399,7 @@ print load_fiche_titre($titre, $linkback, $titlepicto);
 
 
 // Confirmation de la suppression de la ligne
-if ($action == 'delete')
-{
+if ($action == 'delete') {
 	print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1);
 }
 //var_dump($elementList);
@@ -384,14 +407,15 @@ if ($action == 'delete')
 /*
  * Show a dictionary
  */
-if ($id)
-{
+if ($id) {
 	// Complete requete recherche valeurs avec critere de tri
 	$sql = $tabsql[$id];
 	$sql .= " WHERE a.entity = ".$conf->entity;
 
 	// If sort order is "country", we use country_code instead
-	if ($sortfield == 'country') $sortfield = 'country_code';
+	if ($sortfield == 'country') {
+		$sortfield = 'country_code';
+	}
 	$sql .= $db->order($sortfield, $sortorder);
 	$sql .= $db->plimit($listlimit + 1, $offset);
 
@@ -405,14 +429,12 @@ if ($id)
 	print '<table class="noborder centpercent">';
 
 	// Form to add a new line
-	if ($tabname[$id])
-	{
+	if ($tabname[$id]) {
 		$fieldlist = explode(',', $tabfield[$id]);
 
 		// Line for title
 		print '<tr class="liste_titre">';
-		foreach ($fieldlist as $field => $value)
-		{
+		foreach ($fieldlist as $field => $value) {
 			// Determine le nom du champ par rapport aux noms possibles
 			// dans les dictionnaires de donnees
 			$valuetoshow = ucfirst($fieldlist[$field]); // Par defaut
@@ -430,9 +452,13 @@ if ($id)
 
 			if ($valuetoshow != '') {
 				print '<td class="'.$class.'">';
-				if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1, $valuetoshow).'</a>';
-				elseif (!empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]);
-				else print $valuetoshow;
+				if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) {
+					print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1, $valuetoshow).'</a>';
+				} elseif (!empty($tabhelp[$id][$value])) {
+					print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]);
+				} else {
+					print $valuetoshow;
+				}
 				print '</td>';
 			}
 		}
@@ -450,12 +476,11 @@ if ($id)
 
 		$obj = new stdClass();
 		// If data was already input, we define them in obj to populate input fields.
-		if (GETPOST('actionadd', 'alpha'))
-		{
-			foreach ($fieldlist as $key=>$val)
-			{
-				if (GETPOST($val) != '')
+		if (GETPOST('actionadd', 'alpha')) {
+			foreach ($fieldlist as $key => $val) {
+				if (GETPOST($val) != '') {
 					$obj->$val = GETPOST($val);
+				}
 			}
 		}
 
@@ -464,13 +489,12 @@ if ($id)
 		$reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
 		$error = $hookmanager->error; $errors = $hookmanager->errors;
 
-		if (empty($reshook))
-		{
-	   		fieldListJournal($fieldlist, $obj, $tabname[$id], 'add');
+		if (empty($reshook)) {
+			fieldListJournal($fieldlist, $obj, $tabname[$id], 'add');
 		}
 
 		print '<td colspan="4" class="right">';
-	   	print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
+		print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
 		print '</td>';
 		print "</tr>";
 
@@ -482,21 +506,27 @@ if ($id)
 	// List of available record in database
 	dol_syslog("htdocs/admin/dict", LOG_DEBUG);
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$num = $db->num_rows($resql);
 		$i = 0;
 
 		$param = '&id='.$id;
-		if ($search_country_id > 0) $param .= '&search_country_id='.$search_country_id;
+		if ($search_country_id > 0) {
+			$param .= '&search_country_id='.$search_country_id;
+		}
 		$paramwithsearch = $param;
-		if ($sortorder) $paramwithsearch .= '&sortorder='.$sortorder;
-		if ($sortfield) $paramwithsearch .= '&sortfield='.$sortfield;
-		if (GETPOST('from', 'alpha')) $paramwithsearch .= '&from='.GETPOST('from', 'alpha');
+		if ($sortorder) {
+			$paramwithsearch .= '&sortorder='.$sortorder;
+		}
+		if ($sortfield) {
+			$paramwithsearch .= '&sortfield='.$sortfield;
+		}
+		if (GETPOST('from', 'alpha')) {
+			$paramwithsearch .= '&from='.GETPOST('from', 'alpha');
+		}
 
 		// There is several pages
-		if ($num > $listlimit)
-		{
+		if ($num > $listlimit) {
 			print '<tr class="none"><td class="right" colspan="'.(3 + count($fieldlist)).'">';
 			print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), '<li class="pagination"><span>'.$langs->trans("Page").' '.($page + 1).'</span></li>');
 			print '</td></tr>';
@@ -519,8 +549,7 @@ if ($id)
 
 		// Title of lines
 		print '<tr class="liste_titre liste_titre_add">';
-		foreach ($fieldlist as $field => $value)
-		{
+		foreach ($fieldlist as $field => $value) {
 			// Determine le nom du champ par rapport aux noms possibles
 			// dans les dictionnaires de donnees
 			$showfield = 1; // By defaut
@@ -528,11 +557,11 @@ if ($id)
 			$sortable = 1;
 			$valuetoshow = '';
 			/*
-            $tmparray=getLabelOfField($fieldlist[$field]);
-            $showfield=$tmp['showfield'];
-            $valuetoshow=$tmp['valuetoshow'];
-            $align=$tmp['align'];
-            $sortable=$tmp['sortable'];
+			$tmparray=getLabelOfField($fieldlist[$field]);
+			$showfield=$tmp['showfield'];
+			$valuetoshow=$tmp['valuetoshow'];
+			$align=$tmp['align'];
+			$sortable=$tmp['sortable'];
 			*/
 			$valuetoshow = ucfirst($fieldlist[$field]); // By defaut
 			$valuetoshow = $langs->trans($valuetoshow); // try to translate
@@ -557,23 +586,22 @@ if ($id)
 		print getTitleFieldOfList('');
 		print '</tr>';
 
-		if ($num)
-		{
+		if ($num) {
 			// Lines with values
-			while ($i < $num)
-			{
+			while ($i < $num) {
 				$obj = $db->fetch_object($resql);
 				//print_r($obj);
 				print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
-				if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code)))
-				{
+				if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) {
 					$tmpaction = 'edit';
 					$parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
 					$reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
 					$error = $hookmanager->error; $errors = $hookmanager->errors;
 
 					// Show fields
-					if (empty($reshook)) fieldListJournal($fieldlist, $obj, $tabname[$id], 'edit');
+					if (empty($reshook)) {
+						fieldListJournal($fieldlist, $obj, $tabname[$id], 'edit');
+					}
 
 					print '<td class="center" colspan="4">';
 					print '<input type="hidden" name="page" value="'.$page.'">';
@@ -583,17 +611,15 @@ if ($id)
 					print '<div name="'.(!empty($obj->rowid) ? $obj->rowid : $obj->code).'"></div>';
 					print '</td>';
 				} else {
-				  	$tmpaction = 'view';
+					$tmpaction = 'view';
 					$parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
 					$reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
 
 					$error = $hookmanager->error; $errors = $hookmanager->errors;
 
-					if (empty($reshook))
-					{
+					if (empty($reshook)) {
 						$langs->load("accountancy");
-						foreach ($fieldlist as $field => $value)
-						{
+						foreach ($fieldlist as $field => $value) {
 							$showfield = 1;
 							$class = "left";
 							$valuetoshow = $obj->{$fieldlist[$field]};
@@ -608,7 +634,9 @@ if ($id)
 
 							$class = 'tddict';
 							// Show value for field
-							if ($showfield) print '<!-- '.$fieldlist[$field].' --><td class="'.$class.'">'.$valuetoshow.'</td>';
+							if ($showfield) {
+								print '<!-- '.$fieldlist[$field].' --><td class="'.$class.'">'.$valuetoshow.'</td>';
+							}
 						}
 					}
 
@@ -630,27 +658,38 @@ if ($id)
 					$canbemodified = $iserasable;
 
 					$url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '');
-					if ($param) $url .= '&'.$param;
+					if ($param) {
+						$url .= '&'.$param;
+					}
 					$url .= '&';
 
 					// Active
 					print '<td class="nowrap center">';
-					if ($canbedisabled) print '<a href="'.$url.'action='.$acts[$obj->active].'&token='.newToken().'">'.$actl[$obj->active].'</a>';
-					else print $langs->trans("AlwaysActive");
+					if ($canbedisabled) {
+						print '<a href="'.$url.'action='.$acts[$obj->active].'&token='.newToken().'">'.$actl[$obj->active].'</a>';
+					} else {
+						print $langs->trans("AlwaysActive");
+					}
 					print "</td>";
 
 					// Modify link
-					if ($canbemodified) print '<td class="center"><a class="reposition editfielda" href="'.$url.'action=edit&token='.newToken().'">'.img_edit().'</a></td>';
-					else print '<td>&nbsp;</td>';
+					if ($canbemodified) {
+						print '<td class="center"><a class="reposition editfielda" href="'.$url.'action=edit&token='.newToken().'">'.img_edit().'</a></td>';
+					} else {
+						print '<td>&nbsp;</td>';
+					}
 
 					// Delete link
-					if ($iserasable)
-					{
+					if ($iserasable) {
 						print '<td class="center">';
-						if ($user->admin) print '<a href="'.$url.'action=delete&token='.newToken().'">'.img_delete().'</a>';
+						if ($user->admin) {
+							print '<a href="'.$url.'action=delete&token='.newToken().'">'.img_delete().'</a>';
+						}
 						//else print '<a href="#">'.img_delete().'</a>';    // Some dictionary can be edited by other profile than admin
 						print '</td>';
-					} else print '<td>&nbsp;</td>';
+					} else {
+						print '<td>&nbsp;</td>';
+					}
 
 					print '<td></td>';
 
@@ -698,10 +737,8 @@ function fieldListJournal($fieldlist, $obj = '', $tabname = '', $context = '')
 	$formadmin = new FormAdmin($db);
 	$formcompany = new FormCompany($db);
 
-	foreach ($fieldlist as $field => $value)
-	{
-		if ($fieldlist[$field] == 'nature')
-		{
+	foreach ($fieldlist as $field => $value) {
+		if ($fieldlist[$field] == 'nature') {
 			print '<td>';
 			print $form->selectarray('nature', $sourceList, (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''));
 			print '</td>';
@@ -710,9 +747,15 @@ function fieldListJournal($fieldlist, $obj = '', $tabname = '', $context = '')
 		} else {
 			print '<td>';
 			$size = ''; $class = '';
-			if ($fieldlist[$field] == 'code')  $class = 'maxwidth100';
-			if ($fieldlist[$field] == 'label') $class = 'quatrevingtpercent';
-			if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'sens' || $fieldlist[$field] == 'category_type') $size = 'size="2" ';
+			if ($fieldlist[$field] == 'code') {
+				$class = 'maxwidth100';
+			}
+			if ($fieldlist[$field] == 'label') {
+				$class = 'quatrevingtpercent';
+			}
+			if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'sens' || $fieldlist[$field] == 'category_type') {
+				$size = 'size="2" ';
+			}
 			print '<input type="text" '.$size.'class="flat'.($class ? ' '.$class : '').'" value="'.(isset($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'">';
 			print '</td>';
 		}

+ 158 - 85
htdocs/accountancy/admin/productaccount.php

@@ -41,8 +41,9 @@ $langs->loadLangs(array("companies", "compta", "accountancy", "products"));
 if (empty($conf->accounting->enabled)) {
 	accessforbidden();
 }
-if (!$user->rights->accounting->bind->write)
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 // search & action GETPOST
 $action = GETPOST('action', 'aZ09');
@@ -60,7 +61,9 @@ $search_desc = GETPOST('search_desc', 'alpha');
 $search_vat = GETPOST('search_vat', 'alpha');
 $search_current_account = GETPOST('search_current_account', 'alpha');
 $search_current_account_valid = GETPOST('search_current_account_valid', 'alpha');
-if ($search_current_account_valid == '') $search_current_account_valid = 'withoutvalidaccount';
+if ($search_current_account_valid == '') {
+	$search_current_account_valid = 'withoutvalidaccount';
+}
 $search_onsell = GETPOST('search_onsell', 'alpha');
 $search_onpurchase = GETPOST('search_onpurchase', 'alpha');
 
@@ -68,20 +71,30 @@ $accounting_product_mode = GETPOST('accounting_product_mode', 'alpha');
 $btn_changeaccount = GETPOST('changeaccount', 'alpha');
 $btn_changetype = GETPOST('changetype', 'alpha');
 
-if (empty($accounting_product_mode)) $accounting_product_mode = 'ACCOUNTANCY_SELL';
+if (empty($accounting_product_mode)) {
+	$accounting_product_mode = 'ACCOUNTANCY_SELL';
+}
 
 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION);
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield) $sortfield = "p.ref";
-if (!$sortorder) $sortorder = "ASC";
+if (!$sortfield) {
+	$sortfield = "p.ref";
+}
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
 
-if (empty($action)) $action = 'list';
+if (empty($action)) {
+	$action = 'list';
+}
 
 $arrayfields = array();
 
@@ -90,16 +103,21 @@ $arrayfields = array();
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
 // Purge search criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
 	$search_ref = '';
 	$search_label = '';
 	$search_desc = '';
@@ -142,13 +160,11 @@ if ($action == 'update') {
 			$arrayofdifferentselectedvalues = array();
 
 			$cpt = 0; $ok = 0; $ko = 0;
-			foreach ($chk_prod as $productid)
-			{
+			foreach ($chk_prod as $productid) {
 				$accounting_account_id = GETPOST('codeventil_'.$productid);
 
 				$result = 0;
-				if ($accounting_account_id > 0)
-				{
+				if ($accounting_account_id > 0) {
 					$arrayofdifferentselectedvalues[$accounting_account_id] = $accounting_account_id;
 					$result = $accounting->fetch($accounting_account_id, null, 1);
 				}
@@ -181,8 +197,7 @@ if ($action == 'update') {
 					$sql .= " WHERE rowid = ".((int) $productid);
 
 					dol_syslog("/accountancy/admin/productaccount.php sql=".$sql, LOG_DEBUG);
-					if ($db->query($sql))
-					{
+					if ($db->query($sql)) {
 						$ok++;
 						$db->commit();
 					} else {
@@ -195,8 +210,12 @@ if ($action == 'update') {
 			}
 		}
 
-		if ($ko) setEventMessages($langs->trans("XLineFailedToBeBinded", $ko), null, 'errors');
-		if ($ok) setEventMessages($langs->trans("XLineSuccessfullyBinded", $ok), null, 'mesgs');
+		if ($ko) {
+			setEventMessages($langs->trans("XLineFailedToBeBinded", $ko), null, 'errors');
+		}
+		if ($ok) {
+			setEventMessages($langs->trans("XLineSuccessfullyBinded", $ok), null, 'mesgs');
+		}
 	}
 }
 
@@ -243,7 +262,9 @@ llxHeader('', $langs->trans("ProductsBinding"));
 
 $pcgverid = $conf->global->CHARTOFACCOUNTS;
 $pcgvercode = dol_getIdFromCode($db, $pcgverid, 'accounting_system', 'rowid', 'pcg_version');
-if (empty($pcgvercode)) $pcgvercode = $pcgverid;
+if (empty($pcgvercode)) {
+	$pcgvercode = $pcgverid;
+}
 
 $sql = "SELECT p.rowid, p.ref, p.label, p.description, p.tosell, p.tobuy, p.tva_tx,";
 $sql .= " p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export,";
@@ -254,17 +275,13 @@ $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON";
 if ($accounting_product_mode == 'ACCOUNTANCY_BUY') {
 	$sql .= " p.accountancy_code_buy = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'";
-} elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA')
-{
+} elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA') {
 	$sql .= " p.accountancy_code_buy_intra = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'";
-} elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_EXPORT')
-{
+} elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_EXPORT') {
 	$sql .= " p.accountancy_code_buy_export = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'";
-} elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL')
-{
+} elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL') {
 	$sql .= " p.accountancy_code_sell = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'";
-} elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA')
-{
+} elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA') {
 	$sql .= " p.accountancy_code_sell_intra = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'";
 } else {
 	$sql .= " p.accountancy_code_sell_export = aa.account_number AND aa.fk_pcg_version = '".$db->escape($pcgvercode)."'";
@@ -295,12 +312,10 @@ if ($accounting_product_mode == 'ACCOUNTANCY_BUY') {
 		$sql .= natural_search("p.accountancy_code_sell_export", $search_current_account);
 	}
 }
-if ($search_current_account_valid == 'withoutvalidaccount')
-{
+if ($search_current_account_valid == 'withoutvalidaccount') {
 	$sql .= " AND aa.account_number IS NULL";
 }
-if ($search_current_account_valid == 'withvalidaccount')
-{
+if ($search_current_account_valid == 'withvalidaccount') {
 	$sql .= " AND aa.account_number IS NOT NULL";
 }
 // Add search filter like
@@ -316,18 +331,20 @@ if (strlen(trim($search_desc))) {
 if (strlen(trim($search_vat))) {
 	$sql .= natural_search("p.tva_tx", price2num($search_vat), 1);
 }
-if ($search_onsell != '' && $search_onsell != '-1') $sql .= natural_search('p.tosell', $search_onsell, 1);
-if ($search_onpurchase != '' && $search_onpurchase != '-1') $sql .= natural_search('p.tobuy', $search_onpurchase, 1);
+if ($search_onsell != '' && $search_onsell != '-1') {
+	$sql .= natural_search('p.tosell', $search_onsell, 1);
+}
+if ($search_onpurchase != '' && $search_onpurchase != '-1') {
+	$sql .= natural_search('p.tobuy', $search_onpurchase, 1);
+}
 
 $sql .= $db->order($sortfield, $sortorder);
 
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$result = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($result);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -337,24 +354,43 @@ $sql .= $db->plimit($limit + 1, $offset);
 
 dol_syslog("/accountancy/admin/productaccount.php:: sql=".$sql, LOG_DEBUG);
 $result = $db->query($sql);
-if ($result)
-{
+if ($result) {
 	$num = $db->num_rows($result);
 	$i = 0;
 
 	$param = '';
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-	if ($search_ref > 0) $param .= "&search_desc=".urlencode($search_ref);
-	if ($search_label > 0) $param .= "&search_desc=".urlencode($search_label);
-	if ($search_desc > 0) $param .= "&search_desc=".urlencode($search_desc);
-	if ($search_vat > 0) $param .= '&search_vat='.urlencode($search_vat);
-	if ($search_current_account > 0) $param .= "&search_current_account=".urlencode($search_current_account);
-	if ($search_current_account_valid && $search_current_account_valid != '-1') $param .= "&search_current_account_valid=".urlencode($search_current_account_valid);
-	if ($accounting_product_mode) $param .= '&accounting_product_mode='.urlencode($accounting_product_mode);
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.urlencode($limit);
+	}
+	if ($search_ref > 0) {
+		$param .= "&search_desc=".urlencode($search_ref);
+	}
+	if ($search_label > 0) {
+		$param .= "&search_desc=".urlencode($search_label);
+	}
+	if ($search_desc > 0) {
+		$param .= "&search_desc=".urlencode($search_desc);
+	}
+	if ($search_vat > 0) {
+		$param .= '&search_vat='.urlencode($search_vat);
+	}
+	if ($search_current_account > 0) {
+		$param .= "&search_current_account=".urlencode($search_current_account);
+	}
+	if ($search_current_account_valid && $search_current_account_valid != '-1') {
+		$param .= "&search_current_account_valid=".urlencode($search_current_account_valid);
+	}
+	if ($accounting_product_mode) {
+		$param .= '&accounting_product_mode='.urlencode($accounting_product_mode);
+	}
 
 	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="action" value="update">';
@@ -375,8 +411,7 @@ if ($result)
 	print '<tr class="oddeven"><td><input type="radio" name="accounting_product_mode" value="ACCOUNTANCY_SELL"'.($accounting_product_mode == 'ACCOUNTANCY_SELL' ? ' checked' : '').'> '.$langs->trans('OptionModeProductSell').'</td>';
 	print '<td>'.$langs->trans('OptionModeProductSellDesc');
 	print "</td></tr>\n";
-	if ($mysoc->isInEEC())
-	{
+	if ($mysoc->isInEEC()) {
 		print '<tr class="oddeven"><td><input type="radio" name="accounting_product_mode" value="ACCOUNTANCY_SELL_INTRA"'.($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA' ? ' checked' : '').'> '.$langs->trans('OptionModeProductSellIntra').'</td>';
 		print '<td>'.$langs->trans('OptionModeProductSellIntraDesc');
 		print "</td></tr>\n";
@@ -386,8 +421,7 @@ if ($result)
 	print "</td></tr>\n";
 	print '<tr class="oddeven"><td><input type="radio" name="accounting_product_mode" value="ACCOUNTANCY_BUY"'.($accounting_product_mode == 'ACCOUNTANCY_BUY' ? ' checked' : '').'> '.$langs->trans('OptionModeProductBuy').'</td>';
 	print '<td>'.$langs->trans('OptionModeProductBuyDesc')."</td></tr>\n";
-	if ($mysoc->isInEEC())
-	{
+	if ($mysoc->isInEEC()) {
 		print '<tr class="oddeven"><td><input type="radio" name="accounting_product_mode" value="ACCOUNTANCY_BUY_INTRA"'.($accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA' ? ' checked' : '').'> '.$langs->trans('OptionModeProductBuyIntra').'</td>';
 		print '<td>'.$langs->trans('OptionModeProductBuyDesc')."</td></tr>\n";
 	}
@@ -419,13 +453,14 @@ if ($result)
 	print '<td class="liste_titre"><input type="text" class="flat" size="10" name="search_label" value="'.dol_escape_htmltag($search_label).'"></td>';
 	print '<td class="liste_titre right"><input type="text" class="flat maxwidth50 right" size="5" name="search_vat" placeholder="%" value="'.dol_escape_htmltag($search_vat).'"></td>';
 
-	if (!empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) print '<td class="liste_titre"><input type="text" class="flat" size="20" name="search_desc" value="'.dol_escape_htmltag($search_desc).'"></td>';
+	if (!empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) {
+		print '<td class="liste_titre"><input type="text" class="flat" size="20" name="search_desc" value="'.dol_escape_htmltag($search_desc).'"></td>';
+	}
 	// On sell
 	if ($accounting_product_mode == 'ACCOUNTANCY_SELL' || $accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') {
 		print '<td class="liste_titre center">'.$form->selectyesno('search_onsell', $search_onsell, 1, false, 1).'</td>';
-	}
-	// On buy
-	elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY' || $accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_BUY_EXPORT') {
+	} elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY' || $accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_BUY_EXPORT') {
+		// On buy
 		print '<td class="liste_titre center">'.$form->selectyesno('search_onpurchase', $search_onpurchase, 1, false, 1).'</td>';
 	}
 	// Current account
@@ -444,7 +479,9 @@ if ($result)
 	print '<tr class="liste_titre">';
 	print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder);
 	print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", "", $param, '', $sortfield, $sortorder);
-	if (!empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "p.description", "", $param, '', $sortfield, $sortorder);
+	if (!empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) {
+		print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "p.description", "", $param, '', $sortfield, $sortorder);
+	}
 	print_liste_field_titre("VATRate", $_SERVER["PHP_SELF"], "p.tva_tx", "", $param, '', $sortfield, $sortorder, 'right ');
 	// On sell / On purchase
 	if ($accounting_product_mode == 'ACCOUNTANCY_SELL') {
@@ -466,7 +503,7 @@ if ($result)
 		print_liste_field_titre("OnBuy", $_SERVER["PHP_SELF"], "p.tobuy", "", $param, '', $sortfield, $sortorder, 'center ');
 		$fieldtosortaccount = "p.accountancy_code_buy_export";
 	}
-   	print_liste_field_titre("CurrentDedicatedAccountingAccount", $_SERVER["PHP_SELF"], $fieldtosortaccount, "", $param, '', $sortfield, $sortorder);
+	print_liste_field_titre("CurrentDedicatedAccountingAccount", $_SERVER["PHP_SELF"], $fieldtosortaccount, "", $param, '', $sortfield, $sortorder);
 	print_liste_field_titre("AssignDedicatedAccountingAccount");
 	$clickpitco = $form->showCheckAddButtons('checkforselect', 1);
 	print_liste_field_titre($clickpitco, '', '', '', '', '', '', '', 'center ');
@@ -475,8 +512,7 @@ if ($result)
 	$product_static = new Product($db);
 
 	$i = 0;
-	while ($i < min($num, $limit))
-	{
+	while ($i < min($num, $limit)) {
 		$obj = $db->fetch_object($result);
 
 		// Ref produit as link
@@ -558,8 +594,7 @@ if ($result)
 
 		print '<td class="left">'.$obj->label.'</td>';
 
-		if (!empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC))
-		{
+		if (!empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) {
 			// TODO ADJUST DESCRIPTION SIZE
 			// print '<td class="left">' . $obj->description . '</td>';
 			// TODO: we should set a user defined value to adjust user square / wide screen size
@@ -572,32 +607,46 @@ if ($result)
 		print vatrate($obj->tva_tx);
 		print '</td>';
 
-		if ($accounting_product_mode == 'ACCOUNTANCY_SELL' || $accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT')
+		if ($accounting_product_mode == 'ACCOUNTANCY_SELL' || $accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_SELL_EXPORT') {
 			print '<td class="center">'.$product_static->getLibStatut(3, 0).'</td>';
+		}
 
-		if ($accounting_product_mode == 'ACCOUNTANCY_BUY' || $accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_BUY_EXPORT')
+		if ($accounting_product_mode == 'ACCOUNTANCY_BUY' || $accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA' || $accounting_product_mode == 'ACCOUNTANCY_BUY_EXPORT') {
 			print '<td class="center">'.$product_static->getLibStatut(3, 1).'</td>';
+		}
 
 		// Current accounting account
 		print '<td class="left">';
 		if ($accounting_product_mode == 'ACCOUNTANCY_BUY') {
 			print length_accountg($obj->accountancy_code_buy);
-			if ($obj->accountancy_code_buy && empty($obj->aaid)) print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			if ($obj->accountancy_code_buy && empty($obj->aaid)) {
+				print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			}
 		} elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA') {
 			print length_accountg($obj->accountancy_code_buy_intra);
-			if ($obj->accountancy_code_buy_intra && empty($obj->aaid)) print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			if ($obj->accountancy_code_buy_intra && empty($obj->aaid)) {
+				print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			}
 		} elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_EXPORT') {
 			print length_accountg($obj->accountancy_code_buy_export);
-			if ($obj->accountancy_code_buy_export && empty($obj->aaid)) print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			if ($obj->accountancy_code_buy_export && empty($obj->aaid)) {
+				print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			}
 		} elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL') {
 			print length_accountg($obj->accountancy_code_sell);
-			if ($obj->accountancy_code_sell && empty($obj->aaid)) print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			if ($obj->accountancy_code_sell && empty($obj->aaid)) {
+				print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			}
 		} elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA') {
 			print length_accountg($obj->accountancy_code_sell_intra);
-			if ($obj->accountancy_code_sell_intra && empty($obj->aaid)) print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			if ($obj->accountancy_code_sell_intra && empty($obj->aaid)) {
+				print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			}
 		} else {
 			print length_accountg($obj->accountancy_code_sell_export);
-			if ($obj->accountancy_code_sell_export && empty($obj->aaid)) print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			if ($obj->accountancy_code_sell_export && empty($obj->aaid)) {
+				print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount"));
+			}
 		}
 		print '</td>';
 
@@ -607,58 +656,82 @@ if ($result)
 			// Accounting account buy
 			print '<td class="left">';
 			//$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha');        This is id and we need a code
-			if (empty($defaultvalue)) $defaultvalue = $compta_prodbuy;
+			if (empty($defaultvalue)) {
+				$defaultvalue = $compta_prodbuy;
+			}
 			$codesell = length_accountg($obj->accountancy_code_buy);
-			if (!empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid
+			if (!empty($obj->aaid)) {
+				$defaultvalue = ''; // Do not suggest default new value is code is already valid
+			}
 			print $form->select_account($defaultvalue, 'codeventil_'.$product_static->id, 1, array(), 1, 0, 'maxwidth300 maxwidthonsmartphone productforselect');
 			print '</td>';
 		} elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_INTRA') {
 			// Accounting account buy intra (In EEC)
 			print '<td class="left">';
 			//$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha');        This is id and we need a code
-			if (empty($defaultvalue)) $defaultvalue = $compta_prodbuy;
+			if (empty($defaultvalue)) {
+				$defaultvalue = $compta_prodbuy;
+			}
 			$codesell = length_accountg($obj->accountancy_code_buy_intra);
 			//var_dump($defaultvalue.' - '.$codesell.' - '.$compta_prodsell);
-			if (!empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid
+			if (!empty($obj->aaid)) {
+				$defaultvalue = ''; // Do not suggest default new value is code is already valid
+			}
 			print $form->select_account($defaultvalue, 'codeventil_'.$product_static->id, 1, array(), 1, 0, 'maxwidth300 maxwidthonsmartphone productforselect');
 			print '</td>';
 		} elseif ($accounting_product_mode == 'ACCOUNTANCY_BUY_EXPORT') {
 			// Accounting account buy export (Out of EEC)
 			print '<td class="left">';
 			//$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha');        This is id and we need a code
-			if (empty($defaultvalue)) $defaultvalue = $compta_prodbuy;
+			if (empty($defaultvalue)) {
+				$defaultvalue = $compta_prodbuy;
+			}
 			$codesell = length_accountg($obj->accountancy_code_buy_export);
 			//var_dump($defaultvalue.' - '.$codesell.' - '.$compta_prodsell);
-			if (!empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid
+			if (!empty($obj->aaid)) {
+				$defaultvalue = ''; // Do not suggest default new value is code is already valid
+			}
 			print $form->select_account($defaultvalue, 'codeventil_'.$product_static->id, 1, array(), 1, 0, 'maxwidth300 maxwidthonsmartphone productforselect');
 			print '</td>';
 		} elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL') {
 			// Accounting account sell
 			print '<td class="left">';
 			//$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha');        This is id and we need a code
-			if (empty($defaultvalue)) $defaultvalue = $compta_prodsell;
+			if (empty($defaultvalue)) {
+				$defaultvalue = $compta_prodsell;
+			}
 			$codesell = length_accountg($obj->accountancy_code_sell);
 			//var_dump($defaultvalue.' - '.$codesell.' - '.$compta_prodsell);
-			if (!empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid
+			if (!empty($obj->aaid)) {
+				$defaultvalue = ''; // Do not suggest default new value is code is already valid
+			}
 			print $form->select_account($defaultvalue, 'codeventil_'.$product_static->id, 1, array(), 1, 0, 'maxwidth300 maxwidthonsmartphone productforselect');
 			print '</td>';
 		} elseif ($accounting_product_mode == 'ACCOUNTANCY_SELL_INTRA') {
 			// Accounting account sell intra (In EEC)
 			print '<td class="left">';
 			//$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha');        This is id and we need a code
-			if (empty($defaultvalue)) $defaultvalue = $compta_prodsell;
+			if (empty($defaultvalue)) {
+				$defaultvalue = $compta_prodsell;
+			}
 			$codesell = length_accountg($obj->accountancy_code_sell_intra);
 			//var_dump($defaultvalue.' - '.$codesell.' - '.$compta_prodsell);
-			if (!empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid
+			if (!empty($obj->aaid)) {
+				$defaultvalue = ''; // Do not suggest default new value is code is already valid
+			}
 			print $form->select_account($defaultvalue, 'codeventil_'.$product_static->id, 1, array(), 1, 0, 'maxwidth300 maxwidthonsmartphone productforselect');
 			print '</td>';
 		} else {
 			// Accounting account sell export (Out of EEC)
 			print '<td class="left">';
 			//$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha');        This is id and we need a code
-			if (empty($defaultvalue)) $defaultvalue = $compta_prodsell;
+			if (empty($defaultvalue)) {
+				$defaultvalue = $compta_prodsell;
+			}
 			$codesell = length_accountg($obj->accountancy_code_sell_export);
-			if (!empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid
+			if (!empty($obj->aaid)) {
+				$defaultvalue = ''; // Do not suggest default new value is code is already valid
+			}
 			print $form->select_account($defaultvalue, 'codeventil_'.$product_static->id, 1, array(), 1, 0, 'maxwidth300 maxwidthonsmartphone productforselect');
 			print '</td>';
 		}

+ 138 - 82
htdocs/accountancy/admin/subaccount.php

@@ -43,20 +43,30 @@ $search_label = GETPOST('search_label', 'alpha');
 $search_type = GETPOST('search_type', 'int');
 
 // Security check
-if ($user->socid > 0) accessforbidden();
-if (!$user->rights->accounting->chartofaccount) accessforbidden();
+if ($user->socid > 0) {
+	accessforbidden();
+}
+if (!$user->rights->accounting->chartofaccount) {
+	accessforbidden();
+}
 
 // Load variable for pagination
 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield) $sortfield = "label";
-if (!$sortorder) $sortorder = "ASC";
+if (!$sortfield) {
+	$sortfield = "label";
+}
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
 
 $arrayfields = array(
 	'subaccount'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1),
@@ -65,27 +75,35 @@ $arrayfields = array(
 	'reconcilable'=>array('label'=>$langs->trans("Reconcilable"), 'checked'=>1)
 );
 
-if ($conf->global->MAIN_FEATURES_LEVEL < 2) unset($arrayfields['reconcilable']);
+if ($conf->global->MAIN_FEATURES_LEVEL < 2) {
+	unset($arrayfields['reconcilable']);
+}
 
 /*
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha')) { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha')) {
+	$massaction = '';
+}
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
-	if (!empty($cancel)) $action = '';
+if (empty($reshook)) {
+	if (!empty($cancel)) {
+		$action = '';
+	}
 
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
-	{
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
 		$search_subaccount = "";
 		$search_label = "";
 		$search_type = "";
@@ -132,19 +150,24 @@ if (strlen(trim($search_subaccount))) {
 			$search_subaccount_tmp_clean = $search_subaccount_tmp;
 			$search_subaccount_clean = $search_subaccount;
 			$startchar = '%';
-			if (strpos($search_subaccount_tmp, '^') === 0)
-			{
+			if (strpos($search_subaccount_tmp, '^') === 0) {
 				$startchar = '';
 				$search_subaccount_tmp_clean = preg_replace('/^\^/', '', $search_subaccount_tmp);
 				$search_subaccount_clean = preg_replace('/^\^/', '', $search_subaccount);
 			}
 			$sql .= " AND (sa.code_compta LIKE '".$db->escape($startchar.$search_subaccount_tmp_clean)."'";
 			$sql .= " OR sa.code_compta LIKE '".$db->escape($startchar.$search_subaccount_clean)."%')";
-		} else $sql .= natural_search("sa.code_compta", $search_subaccount_tmp);
+		} else {
+			$sql .= natural_search("sa.code_compta", $search_subaccount_tmp);
+		}
 	}
 }
-if (strlen(trim($search_label)))				$sql .= natural_search("sa.nom", $search_label);
-if (!empty($search_type) && $search_type >= 0)	$sql .= " HAVING type LIKE '".$db->escape($search_type)."'";
+if (strlen(trim($search_label))) {
+	$sql .= natural_search("sa.nom", $search_label);
+}
+if (!empty($search_type) && $search_type >= 0) {
+	$sql .= " HAVING type LIKE '".$db->escape($search_type)."'";
+}
 
 // Supplier
 $sql .= " UNION ";
@@ -174,19 +197,24 @@ if (strlen(trim($search_subaccount))) {
 			$search_subaccount_tmp_clean = $search_subaccount_tmp;
 			$search_subaccount_clean = $search_subaccount;
 			$startchar = '%';
-			if (strpos($search_subaccount_tmp, '^') === 0)
-			{
+			if (strpos($search_subaccount_tmp, '^') === 0) {
 				$startchar = '';
 				$search_subaccount_tmp_clean = preg_replace('/^\^/', '', $search_subaccount_tmp);
 				$search_subaccount_clean = preg_replace('/^\^/', '', $search_subaccount);
 			}
 			$sql .= " AND (sa.code_compta_fournisseur LIKE '".$db->escape($startchar.$search_subaccount_tmp_clean)."'";
 			$sql .= " OR sa.code_compta_fournisseur LIKE '".$db->escape($startchar.$search_subaccount_clean)."%')";
-		} else $sql .= natural_search("sa.code_compta_fournisseur", $search_subaccount_tmp);
+		} else {
+			$sql .= natural_search("sa.code_compta_fournisseur", $search_subaccount_tmp);
+		}
 	}
 }
-if (strlen(trim($search_label)))				$sql .= natural_search("sa.nom", $search_label);
-if (!empty($search_type) && $search_type >= 0)	$sql .= " HAVING type LIKE '".$db->escape($search_type)."'";
+if (strlen(trim($search_label))) {
+	$sql .= natural_search("sa.nom", $search_label);
+}
+if (!empty($search_type) && $search_type >= 0) {
+	$sql .= " HAVING type LIKE '".$db->escape($search_type)."'";
+}
 
 // User
 $sql .= " UNION ";
@@ -216,30 +244,33 @@ if (strlen(trim($search_subaccount))) {
 			$search_subaccount_tmp_clean = $search_subaccount_tmp;
 			$search_subaccount_clean = $search_subaccount;
 			$startchar = '%';
-			if (strpos($search_subaccount_tmp, '^') === 0)
-			{
+			if (strpos($search_subaccount_tmp, '^') === 0) {
 				$startchar = '';
 				$search_subaccount_tmp_clean = preg_replace('/^\^/', '', $search_subaccount_tmp);
 				$search_subaccount_clean = preg_replace('/^\^/', '', $search_subaccount);
 			}
 			$sql .= " AND (u.accountancy_code LIKE '".$db->escape($startchar.$search_subaccount_tmp_clean)."'";
 			$sql .= " OR u.accountancy_code LIKE '".$db->escape($startchar.$search_subaccount_clean)."%')";
-		} else $sql .= natural_search("u.accountancy_code", $search_subaccount_tmp);
+		} else {
+			$sql .= natural_search("u.accountancy_code", $search_subaccount_tmp);
+		}
 	}
 }
-if (strlen(trim($search_label)))				$sql .= natural_search("u.lastname", $search_label);
-if (!empty($search_type) && $search_type >= 0)	$sql .= " HAVING type LIKE '".$db->escape($search_type)."'";
+if (strlen(trim($search_label))) {
+	$sql .= natural_search("u.lastname", $search_label);
+}
+if (!empty($search_type) && $search_type >= 0) {
+	$sql .= " HAVING type LIKE '".$db->escape($search_type)."'";
+}
 
 $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$resql = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($resql);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -250,19 +281,30 @@ $sql .= $db->plimit($limit + 1, $offset);
 dol_syslog('accountancy/admin/subaccount.php:: $sql='.$sql);
 $resql = $db->query($sql);
 
-if ($resql)
-{
+if ($resql) {
 	$num = $db->num_rows($resql);
 
 	$param = '';
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-	if ($search_subaccount) $param .= '&search_subaccount='.urlencode($search_subaccount);
-	if ($search_label) $param .= '&search_label='.urlencode($search_label);
-	if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.urlencode($limit);
+	}
+	if ($search_subaccount) {
+		$param .= '&search_subaccount='.urlencode($search_subaccount);
+	}
+	if ($search_label) {
+		$param .= '&search_label='.urlencode($search_label);
+	}
+	if ($optioncss != '') {
+		$param .= '&optioncss='.urlencode($optioncss);
+	}
 
 	print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="action" value="list">';
@@ -285,10 +327,20 @@ if ($resql)
 
 	// Line for search fields
 	print '<tr class="liste_titre_filter">';
-	if (!empty($arrayfields['subaccount']['checked']))	print '<td class="liste_titre"><input type="text" class="flat" size="10" name="search_subaccount" value="'.$search_subaccount.'"></td>';
-	if (!empty($arrayfields['label']['checked']))		print '<td class="liste_titre"><input type="text" class="flat" size="20" name="search_label" value="'.$search_label.'"></td>';
-	if (!empty($arrayfields['type']['checked']))		print '<td class="liste_titre center">'.$form->selectarray('search_type', array('1'=>$langs->trans('Customer'), '2'=>$langs->trans('Supplier'), '3'=>$langs->trans('Employee')), $search_type, 1).'</td>';
-	if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (!empty($arrayfields['reconcilable']['checked']))   print '<td class="liste_titre">&nbsp;</td>'; }
+	if (!empty($arrayfields['subaccount']['checked'])) {
+		print '<td class="liste_titre"><input type="text" class="flat" size="10" name="search_subaccount" value="'.$search_subaccount.'"></td>';
+	}
+	if (!empty($arrayfields['label']['checked'])) {
+		print '<td class="liste_titre"><input type="text" class="flat" size="20" name="search_label" value="'.$search_label.'"></td>';
+	}
+	if (!empty($arrayfields['type']['checked'])) {
+		print '<td class="liste_titre center">'.$form->selectarray('search_type', array('1'=>$langs->trans('Customer'), '2'=>$langs->trans('Supplier'), '3'=>$langs->trans('Employee')), $search_type, 1).'</td>';
+	}
+	if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
+		if (!empty($arrayfields['reconcilable']['checked'])) {
+			print '<td class="liste_titre">&nbsp;</td>';
+		}
+	}
 	print '<td class="liste_titre maxwidthsearch">';
 	$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
 	print $searchpicto;
@@ -296,62 +348,69 @@ if ($resql)
 	print '</tr>';
 
 	print '<tr class="liste_titre">';
-	if (!empty($arrayfields['subaccount']['checked']))	print_liste_field_titre($arrayfields['subaccount']['label'], $_SERVER["PHP_SELF"], "subaccount", "", $param, '', $sortfield, $sortorder);
-	if (!empty($arrayfields['label']['checked']))		print_liste_field_titre($arrayfields['label']['label'], $_SERVER["PHP_SELF"], "label", "", $param, '', $sortfield, $sortorder);
-	if (!empty($arrayfields['type']['checked']))		print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder, 'center ');
-	if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (!empty($arrayfields['reconcilable']['checked']))	print_liste_field_titre($arrayfields['reconcilable']['label'], $_SERVER["PHP_SELF"], 'reconcilable', '', $param, '', $sortfield, $sortorder, 'center '); }
+	if (!empty($arrayfields['subaccount']['checked'])) {
+		print_liste_field_titre($arrayfields['subaccount']['label'], $_SERVER["PHP_SELF"], "subaccount", "", $param, '', $sortfield, $sortorder);
+	}
+	if (!empty($arrayfields['label']['checked'])) {
+		print_liste_field_titre($arrayfields['label']['label'], $_SERVER["PHP_SELF"], "label", "", $param, '', $sortfield, $sortorder);
+	}
+	if (!empty($arrayfields['type']['checked'])) {
+		print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder, 'center ');
+	}
+	if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
+		if (!empty($arrayfields['reconcilable']['checked'])) {
+			print_liste_field_titre($arrayfields['reconcilable']['label'], $_SERVER["PHP_SELF"], 'reconcilable', '', $param, '', $sortfield, $sortorder, 'center ');
+		}
+	}
 	print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
 	print "</tr>\n";
 
 	$totalarray = array();
 	$i = 0;
-	while ($i < min($num, $limit))
-	{
+	while ($i < min($num, $limit)) {
 		$obj = $db->fetch_object($resql);
 
 		print '<tr class="oddeven">';
 
 		// Account number
-		if (!empty($arrayfields['subaccount']['checked']))
-		{
+		if (!empty($arrayfields['subaccount']['checked'])) {
 			print "<td>";
 			print length_accounta($obj->subaccount);
 			print "</td>\n";
-			if (!$i) $totalarray['nbfield']++;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
 		}
 
 		// Subaccount label
-		if (!empty($arrayfields['label']['checked']))
-		{
+		if (!empty($arrayfields['label']['checked'])) {
 			print "<td>";
 			print $obj->label;
 			print "</td>\n";
-			if (!$i) $totalarray['nbfield']++;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
 		}
 
 		// Type
-		if (!empty($arrayfields['type']['checked']))
-		{
+		if (!empty($arrayfields['type']['checked'])) {
 			print '<td class="center">';
 			$s = '';
 			// Customer
-			if ($obj->type == 1)
-			{
+			if ($obj->type == 1) {
 				$s .= '<a class="customer-back" style="padding-left: 6px; padding-right: 6px" title="'.$langs->trans("Customer").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$obj->rowid.'">'.$langs->trans("Customer").'</a>';
-			}
-			// Supplier
-			elseif ($obj->type == 2)
-			{
+			} elseif ($obj->type == 2) {
+				// Supplier
 				$s .= '<a class="vendor-back" style="padding-left: 6px; padding-right: 6px" title="'.$langs->trans("Supplier").'" href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$obj->rowid.'">'.$langs->trans("Supplier").'</a>';
-			}
-			// User
-			elseif ($obj->type == 3)
-			{
+			} elseif ($obj->type == 3) {
+				// User
 				$s .= '<a class="user-back" style="padding-left: 6px; padding-right: 6px" title="'.$langs->trans("Employee").'" href="'.DOL_URL_ROOT.'/user/card.php?id='.$obj->id.'">'.$langs->trans("Employee").'</a>';
 			}
 			print $s;
 			print '</td>';
-			if (!$i) $totalarray['nbfield']++;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
 		}
 
 		if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
@@ -376,25 +435,22 @@ if ($resql)
 
 		// Action
 		print '<td class="center">';
-			$e = '';
-			// Customer
-		if ($obj->type == 1)
-			{
+		$e = '';
+		// Customer
+		if ($obj->type == 1) {
 			$e .= '<a class="editfielda" title="'.$langs->trans("Customer").'" href="'.DOL_URL_ROOT.'/societe/card.php?action=edit&socid='.$obj->rowid.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">'.img_edit().'</a>';
-		}
+		} elseif ($obj->type == 2) {
 			// Supplier
-		elseif ($obj->type == 2)
-			{
 			$e .= '<a class="editfielda" title="'.$langs->trans("Supplier").'" href="'.DOL_URL_ROOT.'/societe/card.php?action=edit&socid='.$obj->rowid.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">'.img_edit().'</a>';
-		}
+		} elseif ($obj->type == 3) {
 			// User
-		elseif ($obj->type == 3)
-			{
 			$e .= '<a class="editfielda" title="'.$langs->trans("Employee").'" href="'.DOL_URL_ROOT.'/user/card.php?action=edit&id='.$obj->rowid.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'">'.img_edit().'</a>';
 		}
-			print $e;
+		print $e;
 		print '</td>'."\n";
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 
 		print '</tr>'."\n";
 		$i++;

+ 46 - 32
htdocs/accountancy/bookkeeping/balance.php

@@ -48,7 +48,9 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; }     // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
+if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
@@ -74,8 +76,7 @@ $formaccounting = new FormAccounting($db);
 $formother = new FormOther($db);
 $form = new Form($db);
 
-if (empty($search_date_start) && !GETPOSTISSET('formfilteraction'))
-{
+if (empty($search_date_start) && !GETPOSTISSET('formfilteraction')) {
 	$sql = "SELECT date_start, date_end from ".MAIN_DB_PREFIX."accounting_fiscalyear ";
 	$sql .= " WHERE date_start < '".$db->idate(dol_now())."' AND date_end > '".$db->idate(dol_now())."'";
 	$sql .= $db->plimit(1);
@@ -87,11 +88,12 @@ if (empty($search_date_start) && !GETPOSTISSET('formfilteraction'))
 	} else {
 		$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
 		$year_start = dol_print_date(dol_now(), '%Y');
-		if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year
+		if (dol_print_date(dol_now(), '%m') < $month_start) {
+			$year_start--; // If current month is lower that starting fiscal month, we start last year
+		}
 		$year_end = $year_start + 1;
 		$month_end = $month_start - 1;
-		if ($month_end < 1)
-		{
+		if ($month_end < 1) {
 			$month_end = 12;
 			$year_end--;
 		}
@@ -99,13 +101,21 @@ if (empty($search_date_start) && !GETPOSTISSET('formfilteraction'))
 		$search_date_end = dol_get_last_day($year_end, $month_end);
 	}
 }
-if ($sortorder == "") $sortorder = "ASC";
-if ($sortfield == "") $sortfield = "t.numero_compte";
+if ($sortorder == "") {
+	$sortorder = "ASC";
+}
+if ($sortfield == "") {
+	$sortfield = "t.numero_compte";
+}
 
 
 $param = '';
-if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+	$param .= '&contextpage='.urlencode($contextpage);
+}
+if ($limit > 0 && $limit != $conf->liste_limit) {
+	$param .= '&limit='.urlencode($limit);
+}
 
 $filter = array();
 if (!empty($search_date_start)) {
@@ -129,8 +139,7 @@ if (!empty($search_accountancy_code_end)) {
  * Action
  */
 
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 	$show_subgroup = '';
 	$search_date_start = '';
 	$search_date_end = '';
@@ -144,8 +153,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
  * View
  */
 
-if ($action == 'export_csv')
-{
+if ($action == 'export_csv') {
 	$sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
 
 	$filename = 'balance';
@@ -157,8 +165,7 @@ if ($action == 'export_csv')
 		setEventMessages($object->error, $object->errors, 'errors');
 	}
 
-	foreach ($object->lines as $line)
-	{
+	foreach ($object->lines as $line) {
 		print length_accountg($line->numero_compte).$sep;
 		print $object->get_compte_desc($line->numero_compte).$sep;
 		print price($line->debit).$sep;
@@ -176,12 +183,10 @@ $title_page = $langs->trans("AccountBalance");
 llxHeader('', $title_page);
 
 
-if ($action != 'export_csv')
-{
+if ($action != 'export_csv') {
 	// List
 	$nbtotalofrecords = '';
-	if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-	{
+	if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 		$nbtotalofrecords = $object->fetchAllBalance($sortorder, $sortfield, 0, 0, $filter);
 		if ($nbtotalofrecords < 0) {
 			setEventMessages($object->error, $object->errors, 'errors');
@@ -194,7 +199,9 @@ if ($action != 'export_csv')
 	}
 
 	print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="action" id="action" value="list">';
@@ -263,7 +270,9 @@ if ($action != 'export_csv')
 
 	print '<tr class="liste_titre">';
 	print_liste_field_titre("AccountAccounting", $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder);
-	if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) print_liste_field_titre("OpeningBalance", $_SERVER['PHP_SELF'], "", $param, "", 'class="right"', $sortfield, $sortorder);
+	if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) {
+		print_liste_field_titre("OpeningBalance", $_SERVER['PHP_SELF'], "", $param, "", 'class="right"', $sortfield, $sortorder);
+	}
 	print_liste_field_titre("Debit", $_SERVER['PHP_SELF'], "t.debit", "", $param, 'class="right"', $sortfield, $sortorder);
 	print_liste_field_titre("Credit", $_SERVER['PHP_SELF'], "t.credit", "", $param, 'class="right"', $sortfield, $sortorder);
 	print_liste_field_titre("Balance", $_SERVER["PHP_SELF"], "", $param, "", 'class="right"', $sortfield, $sortorder);
@@ -298,8 +307,7 @@ if ($action != 'export_csv')
 		}
 	}
 
-	foreach ($object->lines as $line)
-	{
+	foreach ($object->lines as $line) {
 		// reset before the fetch (in case of the fetch fails)
 		$accountingaccountstatic->id = 0;
 		$accountingaccountstatic->account_number = '';
@@ -336,15 +344,16 @@ if ($action != 'export_csv')
 			//$link = '<a href="' . DOL_URL_ROOT . '/accountancy/admin/card.php?action=create&token=' . newToken() . '&accountingaccount=' . length_accountg($line->numero_compte) . '">' . img_edit_add() . '</a>';
 		}
 
-		if (!empty($show_subgroup))
-		{
+		if (!empty($show_subgroup)) {
 			// Show accounting account
 			if (empty($displayed_account) || $root_account_number != $displayed_account) {
 				// Show subtotal per accounting account
 				if ($displayed_account != "") {
 					print '<tr class="liste_total">';
 					print '<td class="right">'.$langs->trans("SubTotal").':</td>';
-					if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) print '<td class="nowrap right">'.price($sous_total_opening_balance).'</td>';
+					if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) {
+						print '<td class="nowrap right">'.price($sous_total_opening_balance).'</td>';
+					}
 					print '<td class="nowrap right">'.price($sous_total_debit).'</td>';
 					print '<td class="nowrap right">'.price($sous_total_credit).'</td>';
 					if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) {
@@ -370,7 +379,9 @@ if ($action != 'export_csv')
 
 		print '<tr class="oddeven">';
 		print '<td>'.$accounting_account.'</td>';
-		if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) print '<td class="nowraponall right">'.price($opening_balance).'</td>';
+		if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) {
+			print '<td class="nowraponall right">'.price($opening_balance).'</td>';
+		}
 
 		$urlzoom = '';
 		if ($line->numero_compte) {
@@ -402,10 +413,11 @@ if ($action != 'export_csv')
 		$sous_total_opening_balance += $opening_balance;
 	}
 
-	if (!empty($show_subgroup))
-	{
+	if (!empty($show_subgroup)) {
 		print '<tr class="liste_total"><td class="right">'.$langs->trans("SubTotal").':</td>';
-		if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) print '<td class="nowrap right">'.price($sous_total_opening_balance).'</td>';
+		if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) {
+			print '<td class="nowrap right">'.price($sous_total_opening_balance).'</td>';
+		}
 		print '<td class="nowrap right">'.price($sous_total_debit).'</td>';
 		print '<td class="nowrap right">'.price($sous_total_credit).'</td>';
 		if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) {
@@ -418,7 +430,9 @@ if ($action != 'export_csv')
 	}
 
 	print '<tr class="liste_total"><td class="right">'.$langs->trans("AccountBalance").':</td>';
-	if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) print '<td class="nowrap right">'.price($total_opening_balance).'</td>';
+	if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) {
+		print '<td class="nowrap right">'.price($total_opening_balance).'</td>';
+	}
 	print '<td class="nowrap right">'.price($total_debit).'</td>';
 	print '<td class="nowrap right">'.price($total_credit).'</td>';
 	if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) {

+ 1 - 2
htdocs/accountancy/bookkeeping/balancebymonth.php

@@ -73,8 +73,7 @@ $y = $year_current;
 print '<table class="noborder centpercent">';
 print '<tr class="liste_titre">';
 print '<td width=150>'.$langs->trans("Label").'</td>';
-for ($i = 1; $i <= 12; $i++)
-{
+for ($i = 1; $i <= 12; $i++) {
 	print '<td class="right">'.$langs->trans("MonthShort".sprintf("%02s", $i)).'</td>';
 }
 print '<td class="center"><strong>'.$langs->trans("Total").'</strong></td>';

+ 50 - 48
htdocs/accountancy/bookkeeping/card.php

@@ -73,9 +73,13 @@ $debit = price2num(GETPOST('debit', 'alpha'));
 $credit = price2num(GETPOST('credit', 'alpha'));
 
 $save = GETPOST('save', 'alpha');
-if (!empty($save)) $action = 'add';
+if (!empty($save)) {
+	$action = 'add';
+}
 $update = GETPOST('update', 'alpha');
-if (!empty($update)) $action = 'confirm_update';
+if (!empty($update)) {
+	$action = 'confirm_update';
+}
 
 $object = new BookKeeping($db);
 
@@ -92,15 +96,13 @@ if ($action == "confirm_update") {
 		setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors');
 		$action = 'update';
 	}
-	if (empty($accountingaccount_number) || $accountingaccount_number == '-1')
-	{
+	if (empty($accountingaccount_number) || $accountingaccount_number == '-1') {
 		$error++;
 		setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("AccountAccountingShort")), null, 'errors');
 		$action = 'update';
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		$object = new BookKeeping($db);
 
 		$result = $object->fetch($id, null, $mode);
@@ -145,14 +147,12 @@ if ($action == "confirm_update") {
 } elseif ($action == "add") {
 	$error = 0;
 
-	if ((floatval($debit) != 0.0) && (floatval($credit) != 0.0))
-	{
+	if ((floatval($debit) != 0.0) && (floatval($credit) != 0.0)) {
 		$error++;
 		setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors');
 		$action = '';
 	}
-	if (empty($accountingaccount_number) || $accountingaccount_number == '-1')
-	{
+	if (empty($accountingaccount_number) || $accountingaccount_number == '-1') {
 		$error++;
 		setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("AccountAccountingShort")), null, 'errors');
 		$action = '';
@@ -228,15 +228,13 @@ if ($action == "confirm_update") {
 		$action = 'create';
 		$error++;
 	}
-	if (!GETPOST('doc_ref', 'alpha'))
-	{
+	if (!GETPOST('doc_ref', 'alpha')) {
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Piece")), null, 'errors');
 		$action = 'create';
 		$error++;
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		$object->label_compte = '';
 		$object->debit = 0;
 		$object->credit = 0;
@@ -255,8 +253,7 @@ if ($action == "confirm_update") {
 		if ($result < 0) {
 			setEventMessages($object->error, $object->errors, 'errors');
 		} else {
-			if ($mode != '_tmp')
-			{
+			if ($mode != '_tmp') {
 				setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
 			}
 			$action = 'update';
@@ -272,8 +269,7 @@ if ($action == 'setdate') {
 	if ($result < 0) {
 		setEventMessages($object->error, $object->errors, 'errors');
 	} else {
-		if ($mode != '_tmp')
-		{
+		if ($mode != '_tmp') {
 			setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
 		}
 		$action = '';
@@ -286,8 +282,7 @@ if ($action == 'setjournal') {
 	if ($result < 0) {
 		setEventMessages($object->error, $object->errors, 'errors');
 	} else {
-		if ($mode != '_tmp')
-		{
+		if ($mode != '_tmp') {
 			setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
 		}
 		$action = '';
@@ -300,8 +295,7 @@ if ($action == 'setdocref') {
 	if ($result < 0) {
 		setEventMessages($object->error, $object->errors, 'errors');
 	} else {
-		if ($mode != '_tmp')
-		{
+		if ($mode != '_tmp') {
 			setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
 		}
 		$action = '';
@@ -335,20 +329,20 @@ if ($action == 'delete') {
 	print $formconfirm;
 }
 
-if ($action == 'create')
-{
+if ($action == 'create') {
 	print load_fiche_titre($langs->trans("CreateMvts"));
 
 	$object = new BookKeeping($db);
 	$next_num_mvt = $object->getNextNumMvt('_tmp');
 
-	if (empty($next_num_mvt))
-	{
+	if (empty($next_num_mvt)) {
 		dol_print_error('', 'Failed to get next piece number');
 	}
 
 	print '<form action="'.$_SERVER["PHP_SELF"].'" name="create_mvt" method="POST">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="confirm_create">'."\n";
 	print '<input type="hidden" name="next_num_mvt" value="'.$next_num_mvt.'">'."\n";
@@ -405,8 +399,7 @@ if ($action == 'create')
 		setEventMessages($object->error, $object->errors, 'errors');
 	}
 
-	if (!empty($object->piece_num))
-	{
+	if (!empty($object->piece_num)) {
 		$backlink = '<a href="'.DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?restore_lastsearch_values=1">'.$langs->trans('BackToList').'</a>';
 
 		print load_fiche_titre($langs->trans("UpdateMvts"), $backlink);
@@ -439,13 +432,16 @@ if ($action == 'create')
 		print '<table class="nobordernopadding" width="100%"><tr><td>';
 		print $langs->trans('Docdate');
 		print '</td>';
-		if ($action != 'editdate')
-		print '<td class="right"><a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=editdate&amp;piece_num='.$object->piece_num.'&amp;mode='.$mode.'">'.img_edit($langs->transnoentitiesnoconv('SetDate'), 1).'</a></td>';
+		if ($action != 'editdate') {
+			print '<td class="right"><a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=editdate&amp;piece_num='.$object->piece_num.'&amp;mode='.$mode.'">'.img_edit($langs->transnoentitiesnoconv('SetDate'), 1).'</a></td>';
+		}
 		print '</tr></table>';
 		print '</td><td colspan="3">';
 		if ($action == 'editdate') {
 			print '<form name="setdate" action="'.$_SERVER["PHP_SELF"].'?piece_num='.$object->piece_num.'" method="post">';
-			if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+			if ($optioncss != '') {
+				print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+			}
 			print '<input type="hidden" name="token" value="'.newToken().'">';
 			print '<input type="hidden" name="action" value="setdate">';
 			print '<input type="hidden" name="mode" value="'.$mode.'">';
@@ -463,13 +459,16 @@ if ($action == 'create')
 		print '<table class="nobordernopadding" width="100%"><tr><td>';
 		print $langs->trans('Codejournal');
 		print '</td>';
-		if ($action != 'editjournal')
-		print '<td class="right"><a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=editjournal&amp;piece_num='.$object->piece_num.'&amp;mode='.$mode.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'</a></td>';
+		if ($action != 'editjournal') {
+			print '<td class="right"><a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=editjournal&amp;piece_num='.$object->piece_num.'&amp;mode='.$mode.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'</a></td>';
+		}
 		print '</tr></table>';
 		print '</td><td>';
 		if ($action == 'editjournal') {
 			print '<form name="setjournal" action="'.$_SERVER["PHP_SELF"].'?piece_num='.$object->piece_num.'" method="post">';
-			if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+			if ($optioncss != '') {
+				print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+			}
 			print '<input type="hidden" name="token" value="'.newToken().'">';
 			print '<input type="hidden" name="action" value="setjournal">';
 			print '<input type="hidden" name="mode" value="'.$mode.'">';
@@ -487,13 +486,16 @@ if ($action == 'create')
 		print '<table class="nobordernopadding" width="100%"><tr><td>';
 		print $langs->trans('Piece');
 		print '</td>';
-		if ($action != 'editdocref')
-		print '<td class="right"><a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=editdocref&amp;piece_num='.$object->piece_num.'&amp;mode='.$mode.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'</a></td>';
+		if ($action != 'editdocref') {
+			print '<td class="right"><a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=editdocref&amp;piece_num='.$object->piece_num.'&amp;mode='.$mode.'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'</a></td>';
+		}
 		print '</tr></table>';
 		print '</td><td>';
 		if ($action == 'editdocref') {
 			print '<form name="setdocref" action="'.$_SERVER["PHP_SELF"].'?piece_num='.$object->piece_num.'" method="post">';
-			if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+			if ($optioncss != '') {
+				print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+			}
 			print '<input type="hidden" name="token" value="'.newToken().'">';
 			print '<input type="hidden" name="action" value="setdocref">';
 			print '<input type="hidden" name="mode" value="'.$mode.'">';
@@ -516,8 +518,7 @@ if ($action == 'create')
 		print '<table class="border tableforfield" width="100%">';
 
 		// Doc type
-		if (!empty($object->doc_type))
-		{
+		if (!empty($object->doc_type)) {
 			print '<tr>';
 			print '<td class="titlefield">'.$langs->trans("Doctype").'</td>';
 			print '<td>'.$object->doc_type.'</td>';
@@ -589,7 +590,9 @@ if ($action == 'create')
 			print load_fiche_titre($langs->trans("ListeMvts"), '', '');
 
 			print '<form action="'.$_SERVER["PHP_SELF"].'?piece_num='.$object->piece_num.'" method="post">';
-			if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+			if ($optioncss != '') {
+				print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+			}
 			print '<input type="hidden" name="token" value="'.newToken().'">';
 			print '<input type="hidden" name="doc_date" value="'.$object->doc_date.'">'."\n";
 			print '<input type="hidden" name="doc_type" value="'.$object->doc_type.'">'."\n";
@@ -664,7 +667,9 @@ if ($action == 'create')
 						print '</a> &nbsp;';
 
 						$actiontodelete = 'delete';
-						if ($mode == '_tmp' || $action != 'delmouv') $actiontodelete = 'confirm_delete';
+						if ($mode == '_tmp' || $action != 'delmouv') {
+							$actiontodelete = 'confirm_delete';
+						}
 
 						print '<a href="'.$_SERVER["PHP_SELF"].'?action='.$actiontodelete.'&id='.$line->id.'&piece_num='.urlencode($line->piece_num).'&mode='.urlencode($mode).'&token='.urlencode(newToken()).'">';
 						print img_delete();
@@ -678,8 +683,7 @@ if ($action == 'create')
 				$total_debit = price2num($total_debit, 'MT');
 				$total_credit = price2num($total_credit, 'MT');
 
-				if ($total_debit != $total_credit)
-				{
+				if ($total_debit != $total_credit) {
 					setEventMessages(null, array($langs->trans('MvtNotCorrectlyBalanced', $total_debit, $total_credit)), 'warnings');
 				}
 
@@ -710,12 +714,10 @@ if ($action == 'create')
 				print '</table>';
 
 
-				if ($mode == '_tmp' && $action == '')
-				{
+				if ($mode == '_tmp' && $action == '') {
 					print '<br>';
 					print '<div class="center">';
-					if ($total_debit == $total_credit)
-					{
+					if ($total_debit == $total_credit) {
 						print '<a class="button" href="'.$_SERVER["PHP_SELF"].'?piece_num='.$object->piece_num.'&action=valid">'.$langs->trans("ValidTransaction").'</a>';
 					} else {
 						print '<input type="submit" class="button" disabled="disabled" href="#" title="'.dol_escape_htmltag($langs->trans("MvtNotCorrectlyBalanced", $debit, $credit)).'" value="'.dol_escape_htmltag($langs->trans("ValidTransaction")).'">';

+ 198 - 150
htdocs/accountancy/bookkeeping/list.php

@@ -94,12 +94,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0) { $page = 0; }
+if (empty($page) || $page < 0) {
+	$page = 0;
+}
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if ($sortorder == "") $sortorder = "ASC";
-if ($sortfield == "") $sortfield = "t.piece_num,t.rowid";
+if ($sortorder == "") {
+	$sortorder = "ASC";
+}
+if ($sortfield == "") {
+	$sortfield = "t.piece_num,t.rowid";
+}
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 $object = new BookKeeping($db);
@@ -108,10 +114,8 @@ $hookmanager->initHooks(array('bookkeepinglist'));
 $formaccounting = new FormAccounting($db);
 $form = new Form($db);
 
-if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !GETPOSTISSET('begin') && !GETPOSTISSET('formfilteraction') && GETPOST('page', 'int') == '' && !GETPOST('noreset', 'int') && $user->rights->accounting->mouvements->export)
-{
-	if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('restore_lastsearch_values') && !GETPOST('search_accountancy_code_start'))
-	{
+if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !GETPOSTISSET('begin') && !GETPOSTISSET('formfilteraction') && GETPOST('page', 'int') == '' && !GETPOST('noreset', 'int') && $user->rights->accounting->mouvements->export) {
+	if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('restore_lastsearch_values') && !GETPOST('search_accountancy_code_start')) {
 		$query = "SELECT date_start, date_end from ".MAIN_DB_PREFIX."accounting_fiscalyear ";
 		$query .= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."' limit 1";
 		$res = $db->query($query);
@@ -123,11 +127,12 @@ if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !GE
 		} else {
 			$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
 			$year_start = dol_print_date(dol_now(), '%Y');
-			if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year
+			if (dol_print_date(dol_now(), '%m') < $month_start) {
+				$year_start--; // If current month is lower that starting fiscal month, we start last year
+			}
 			$year_end = $year_start + 1;
 			$month_end = $month_start - 1;
-			if ($month_end < 1)
-			{
+			if ($month_end < 1) {
 				$month_end = 12;
 				$year_end--;
 			}
@@ -154,11 +159,15 @@ $arrayfields = array(
 	't.date_export'=>array('label'=>$langs->trans("DateExport"), 'checked'=>1),
 );
 
-if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) unset($arrayfields['t.lettering_code']);
+if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) {
+	unset($arrayfields['t.lettering_code']);
+}
 
 $listofformat = AccountancyExport::getType();
 $formatexportset = $conf->global->ACCOUNTING_EXPORT_MODELCSV;
-if (empty($listofformat[$formatexportset])) $formatexportset = 1;
+if (empty($listofformat[$formatexportset])) {
+	$formatexportset = 1;
+}
 
 $error = 0;
 
@@ -167,19 +176,23 @@ $error = 0;
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
 
 $parameters = array('socid'=>$socid);
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-	{
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 		$search_mvt_num = '';
 		$search_doc_type = '';
 		$search_doc_ref = '';
@@ -348,8 +361,7 @@ if ($action == 'delbookkeepingyearconfirm' && $user->rights->accounting->mouveme
 		$deljournal = 0;
 	}
 
-	if (!empty($delmonth) || !empty($delyear) || !empty($deljournal))
-	{
+	if (!empty($delmonth) || !empty($delyear) || !empty($deljournal)) {
 		$result = $object->deleteByYearAndJournal($delyear, $deljournal, '', ($delmonth > 0 ? $delmonth : 0));
 		if ($result < 0) {
 			setEventMessages($object->error, $object->errors, 'errors');
@@ -381,7 +393,9 @@ if ($action == 'delmouvconfirm' && $user->rights->accounting->mouvements->suppri
 }
 if ($action == 'setreexport') {
 	$setreexport = GETPOST('value', 'int');
-	if (!dolibarr_set_const($db, "ACCOUNTING_REEXPORT", $setreexport, 'yesno', 0, '', $conf->entity)) $error++;
+	if (!dolibarr_set_const($db, "ACCOUNTING_REEXPORT", $setreexport, 'yesno', 0, '', $conf->entity)) {
+		$error++;
+	}
 
 	if (!$error) {
 		if ($conf->global->ACCOUNTING_REEXPORT == 1) {
@@ -475,26 +489,22 @@ if ($action == 'export_fileconfirm' && $user->rights->accounting->mouvements->ex
 	// TODO Replace the fetchAll + ->export later that consume too much memory on large export with the query($sql) and loop on each line to export them.
 	$result = $object->fetchAll($sortorder, $sortfield, 0, 0, $filter, 'AND', $conf->global->ACCOUNTING_REEXPORT);
 
-	if ($result < 0)
-	{
+	if ($result < 0) {
 		setEventMessages($object->error, $object->errors, 'errors');
 	} else {
 		// Export files
 		$accountancyexport = new AccountancyExport($db);
 		$accountancyexport->export($object->lines, $formatexportset);
 
-		if (!empty($accountancyexport->errors))
-		{
+		if (!empty($accountancyexport->errors)) {
 			setEventMessages('', $accountancyexport->errors, 'errors');
 		} else {
 			// Specify as export : update field date_export
 			$error = 0;
 			$db->begin();
 
-			if (is_array($object->lines))
-			{
-				foreach ($object->lines as $movement)
-				{
+			if (is_array($object->lines)) {
+				foreach ($object->lines as $movement) {
 					$now = dol_now();
 
 					$sql = " UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping";
@@ -504,16 +514,14 @@ if ($action == 'export_fileconfirm' && $user->rights->accounting->mouvements->ex
 
 					dol_syslog("/accountancy/bookeeping/list.php Function export_file Specify movements as exported sql=".$sql, LOG_DEBUG);
 					$result = $db->query($sql);
-					if (!$result)
-					{
+					if (!$result) {
 						$error++;
 						break;
 					}
 				}
 			}
 
-			if (!$error)
-			{
+			if (!$error) {
 				$db->commit();
 				// setEventMessages($langs->trans("AllExportedMovementsWereRecordedAsExported"), null, 'mesgs');
 			} else {
@@ -538,26 +546,22 @@ $title_page = $langs->trans("Operations").' - '.$langs->trans("Journals");
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$resql = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($resql);
-	if (($page * $limit) > $nbtotalofrecords)	// if total of record found is smaller than page * limit, goto and load page 0
-	{
+	if (($page * $limit) > $nbtotalofrecords) {	// if total of record found is smaller than page * limit, goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
 }
 // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
-if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords)
-{
+if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) {
 	$num = $nbtotalofrecords;
 } else {
 	$sql .= $db->plimit($limit + 1, $offset);
 
 	$resql = $db->query($sql);
-	if (!$resql)
-	{
+	if (!$resql) {
 		dol_print_error($db);
 		exit;
 	}
@@ -636,19 +640,28 @@ if ($action == 'delbookkeepingyear') {
 }
 
 //$param='';	param started before
-if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+	$param .= '&contextpage='.urlencode($contextpage);
+}
+if ($limit > 0 && $limit != $conf->liste_limit) {
+	$param .= '&limit='.urlencode($limit);
+}
 
 print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
 print '<input type="hidden" name="token" value="'.newToken().'">';
 print '<input type="hidden" name="action" value="list">';
-if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.urlencode($optioncss).'">';
+if ($optioncss != '') {
+	print '<input type="hidden" name="optioncss" value="'.urlencode($optioncss).'">';
+}
 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 print '<input type="hidden" name="sortfield" value="'.urlencode($sortfield).'">';
 print '<input type="hidden" name="sortorder" value="'.urlencode($sortorder).'">';
 
-if (count($filter)) $buttonLabel = $langs->trans("ExportFilteredList");
-else $buttonLabel = $langs->trans("ExportList");
+if (count($filter)) {
+	$buttonLabel = $langs->trans("ExportFilteredList");
+} else {
+	$buttonLabel = $langs->trans("ExportList");
+}
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
@@ -661,14 +674,18 @@ if (empty($reshook)) {
 	}
 	$newcardbutton .= '<span class="valignmiddle marginrightonly">'.$langs->trans("IncludeDocsAlreadyExported").'</span>';
 
-	if (!empty($user->rights->accounting->mouvements->export)) $newcardbutton .= dolGetButtonTitle($buttonLabel, $langs->trans("ExportFilteredList").' ('.$listofformat[$formatexportset].')', 'fa fa-file-export paddingleft', $_SERVER["PHP_SELF"].'?action=export_file'.($param ? '&'.$param : ''), $user->rights->accounting->mouvements->export);
+	if (!empty($user->rights->accounting->mouvements->export)) {
+		$newcardbutton .= dolGetButtonTitle($buttonLabel, $langs->trans("ExportFilteredList").' ('.$listofformat[$formatexportset].')', 'fa fa-file-export paddingleft', $_SERVER["PHP_SELF"].'?action=export_file'.($param ? '&'.$param : ''), $user->rights->accounting->mouvements->export);
+	}
 
 	$newcardbutton .= dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param, '', 1, array('morecss' => 'marginleftonly btnTitleSelected'));
 	$newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly'));
 	$newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly'));
 
 	$url = './card.php?action=create';
-	if (!empty($socid)) $url .= '&socid='.$socid;
+	if (!empty($socid)) {
+		$url .= '&socid='.$socid;
+	}
 	$newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', $url, '', $user->rights->accounting->mouvements->creer);
 }
 
@@ -676,12 +693,17 @@ print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield,
 
 $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
 $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
-if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
+if ($massactionbutton) {
+	$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
+}
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
-if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
-else $moreforfilter = $hookmanager->resPrint;
+if (empty($reshook)) {
+	$moreforfilter .= $hookmanager->resPrint;
+} else {
+	$moreforfilter = $hookmanager->resPrint;
+}
 
 print '<div class="div-table-responsive">';
 print '<table class="tagtable liste centpercent">';
@@ -690,18 +712,15 @@ print '<table class="tagtable liste centpercent">';
 print '<tr class="liste_titre_filter">';
 
 // Movement number
-if (!empty($arrayfields['t.piece_num']['checked']))
-{
+if (!empty($arrayfields['t.piece_num']['checked'])) {
 	print '<td class="liste_titre"><input type="text" name="search_mvt_num" size="6" value="'.dol_escape_htmltag($search_mvt_num).'"></td>';
 }
 // Code journal
-if (!empty($arrayfields['t.code_journal']['checked']))
-{
+if (!empty($arrayfields['t.code_journal']['checked'])) {
 	print '<td class="liste_titre center"><input type="text" name="search_ledger_code" size="3" value="'.(is_array($search_ledger_code) ? join('|', $search_ledger_code) : $search_ledger_code).'"></td>';
 }
 // Date document
-if (!empty($arrayfields['t.doc_date']['checked']))
-{
+if (!empty($arrayfields['t.doc_date']['checked'])) {
 	print '<td class="liste_titre center">';
 	print '<div class="nowrap">';
 	print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From"));
@@ -712,13 +731,11 @@ if (!empty($arrayfields['t.doc_date']['checked']))
 	print '</td>';
 }
 // Ref document
-if (!empty($arrayfields['t.doc_ref']['checked']))
-{
+if (!empty($arrayfields['t.doc_ref']['checked'])) {
 	print '<td class="liste_titre"><input type="text" name="search_doc_ref" size="8" value="'.dol_escape_htmltag($search_doc_ref).'"></td>';
 }
 // Accountancy account
-if (!empty($arrayfields['t.numero_compte']['checked']))
-{
+if (!empty($arrayfields['t.numero_compte']['checked'])) {
 	print '<td class="liste_titre">';
 	print '<div class="nowrap">';
 	print $langs->trans('From').' ';
@@ -731,14 +748,12 @@ if (!empty($arrayfields['t.numero_compte']['checked']))
 	print '</td>';
 }
 // Subledger account
-if (!empty($arrayfields['t.subledger_account']['checked']))
-{
+if (!empty($arrayfields['t.subledger_account']['checked'])) {
 	print '<td class="liste_titre">';
 	print '<div class="nowrap">';
 	// TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not
 	// use setup of keypress to select thirdparty and this hang browser on large database.
-	if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX))
-	{
+	if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) {
 		print $langs->trans('From').' ';
 		print $formaccounting->select_auxaccount($search_accountancy_aux_code_start, 'search_accountancy_aux_code_start', 1);
 	} else {
@@ -748,8 +763,7 @@ if (!empty($arrayfields['t.subledger_account']['checked']))
 	print '<div class="nowrap">';
 	// TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not
 	// use setup of keypress to select thirdparty and this hang browser on large database.
-	if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX))
-	{
+	if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) {
 		print $langs->trans('to').' ';
 		print $formaccounting->select_auxaccount($search_accountancy_aux_code_end, 'search_accountancy_aux_code_end', 1);
 	} else {
@@ -759,29 +773,25 @@ if (!empty($arrayfields['t.subledger_account']['checked']))
 	print '</td>';
 }
 // Label operation
-if (!empty($arrayfields['t.label_operation']['checked']))
-{
+if (!empty($arrayfields['t.label_operation']['checked'])) {
 	print '<td class="liste_titre">';
 	print '<input type="text" size="7" class="flat" name="search_mvt_label" value="'.$search_mvt_label.'"/>';
 	print '</td>';
 }
 // Debit
-if (!empty($arrayfields['t.debit']['checked']))
-{
+if (!empty($arrayfields['t.debit']['checked'])) {
 	print '<td class="liste_titre right">';
 	print '<input type="text" class="flat" name="search_debit" size="4" value="'.dol_escape_htmltag($search_debit).'">';
 	print '</td>';
 }
 // Credit
-if (!empty($arrayfields['t.credit']['checked']))
-{
+if (!empty($arrayfields['t.credit']['checked'])) {
 	print '<td class="liste_titre right">';
 	print '<input type="text" class="flat" name="search_credit" size="4" value="'.dol_escape_htmltag($search_credit).'">';
 	print '</td>';
 }
 // Lettering code
-if (!empty($arrayfields['t.lettering_code']['checked']))
-{
+if (!empty($arrayfields['t.lettering_code']['checked'])) {
 	print '<td class="liste_titre center">';
 	print '<input type="text" size="3" class="flat" name="search_lettering_code" value="'.$search_lettering_code.'"/>';
 	print '<br><span class="nowrap"><input type="checkbox" name="search_not_reconciled" value="notreconciled"'.($search_not_reconciled == 'notreconciled' ? ' checked' : '').'>'.$langs->trans("NotReconciled").'</span>';
@@ -794,8 +804,7 @@ $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // N
 print $hookmanager->resPrint;
 
 // Date creation
-if (!empty($arrayfields['t.date_creation']['checked']))
-{
+if (!empty($arrayfields['t.date_creation']['checked'])) {
 	print '<td class="liste_titre center">';
 	print '<div class="nowrap">';
 	print $form->selectDate($search_date_creation_start, 'date_creation_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From"));
@@ -806,8 +815,7 @@ if (!empty($arrayfields['t.date_creation']['checked']))
 	print '</td>';
 }
 // Date modification
-if (!empty($arrayfields['t.tms']['checked']))
-{
+if (!empty($arrayfields['t.tms']['checked'])) {
 	print '<td class="liste_titre center">';
 	print '<div class="nowrap">';
 	print $form->selectDate($search_date_modification_start, 'date_modification_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From"));
@@ -818,8 +826,7 @@ if (!empty($arrayfields['t.tms']['checked']))
 	print '</td>';
 }
 // Date export
-if (!empty($arrayfields['t.date_export']['checked']))
-{
+if (!empty($arrayfields['t.date_export']['checked'])) {
 	print '<td class="liste_titre center">';
 	print '<div class="nowrap">';
 	print $form->selectDate($search_date_export_start, 'date_export_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From"));
@@ -837,23 +844,49 @@ print '</td>';
 print "</tr>\n";
 
 print '<tr class="liste_titre">';
-if (!empty($arrayfields['t.piece_num']['checked']))			print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, "", $sortfield, $sortorder);
-if (!empty($arrayfields['t.code_journal']['checked']))			print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center ');
-if (!empty($arrayfields['t.doc_date']['checked']))				print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center ');
-if (!empty($arrayfields['t.doc_ref']['checked']))				print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder);
-if (!empty($arrayfields['t.numero_compte']['checked']))		print_liste_field_titre($arrayfields['t.numero_compte']['label'], $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder);
-if (!empty($arrayfields['t.subledger_account']['checked']))	print_liste_field_titre($arrayfields['t.subledger_account']['label'], $_SERVER['PHP_SELF'], "t.subledger_account", "", $param, "", $sortfield, $sortorder);
-if (!empty($arrayfields['t.label_operation']['checked']))		print_liste_field_titre($arrayfields['t.label_operation']['label'], $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder);
-if (!empty($arrayfields['t.debit']['checked']))				print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right ');
-if (!empty($arrayfields['t.credit']['checked']))				print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right ');
-if (!empty($arrayfields['t.lettering_code']['checked']))		print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['t.piece_num']['checked'])) {
+	print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, "", $sortfield, $sortorder);
+}
+if (!empty($arrayfields['t.code_journal']['checked'])) {
+	print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center ');
+}
+if (!empty($arrayfields['t.doc_date']['checked'])) {
+	print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center ');
+}
+if (!empty($arrayfields['t.doc_ref']['checked'])) {
+	print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder);
+}
+if (!empty($arrayfields['t.numero_compte']['checked'])) {
+	print_liste_field_titre($arrayfields['t.numero_compte']['label'], $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder);
+}
+if (!empty($arrayfields['t.subledger_account']['checked'])) {
+	print_liste_field_titre($arrayfields['t.subledger_account']['label'], $_SERVER['PHP_SELF'], "t.subledger_account", "", $param, "", $sortfield, $sortorder);
+}
+if (!empty($arrayfields['t.label_operation']['checked'])) {
+	print_liste_field_titre($arrayfields['t.label_operation']['label'], $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder);
+}
+if (!empty($arrayfields['t.debit']['checked'])) {
+	print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right ');
+}
+if (!empty($arrayfields['t.credit']['checked'])) {
+	print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right ');
+}
+if (!empty($arrayfields['t.lettering_code']['checked'])) {
+	print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center ');
+}
 // Hook fields
 $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
 $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
 print $hookmanager->resPrint;
-if (!empty($arrayfields['t.date_creation']['checked']))		print_liste_field_titre($arrayfields['t.date_creation']['label'], $_SERVER['PHP_SELF'], "t.date_creation", "", $param, '', $sortfield, $sortorder, 'center ');
-if (!empty($arrayfields['t.tms']['checked']))					print_liste_field_titre($arrayfields['t.tms']['label'], $_SERVER['PHP_SELF'], "t.tms", "", $param, '', $sortfield, $sortorder, 'center ');
-if (!empty($arrayfields['t.date_export']['checked']))          print_liste_field_titre($arrayfields['t.date_export']['label'], $_SERVER['PHP_SELF'], "t.date_export", "", $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['t.date_creation']['checked'])) {
+	print_liste_field_titre($arrayfields['t.date_creation']['label'], $_SERVER['PHP_SELF'], "t.date_creation", "", $param, '', $sortfield, $sortorder, 'center ');
+}
+if (!empty($arrayfields['t.tms']['checked'])) {
+	print_liste_field_titre($arrayfields['t.tms']['label'], $_SERVER['PHP_SELF'], "t.tms", "", $param, '', $sortfield, $sortorder, 'center ');
+}
+if (!empty($arrayfields['t.date_export']['checked'])) {
+	print_liste_field_titre($arrayfields['t.date_export']['label'], $_SERVER['PHP_SELF'], "t.date_export", "", $param, '', $sortfield, $sortorder, 'center ');
+}
 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
 print "</tr>\n";
 
@@ -864,10 +897,11 @@ $line = new BookKeepingLine();
 // --------------------------------------------------------------------
 $i = 0;
 $totalarray = array();
-while ($i < min($num, $limit))
-{
+while ($i < min($num, $limit)) {
 	$obj = $db->fetch_object($resql);
-	if (empty($obj)) break; // Should not happen
+	if (empty($obj)) {
+		break; // Should not happen
+	}
 
 	$line->id = $obj->rowid;
 	$line->doc_date = $db->jdate($obj->doc_date);
@@ -902,38 +936,39 @@ while ($i < min($num, $limit))
 	print '<tr class="oddeven">';
 
 	// Piece number
-	if (!empty($arrayfields['t.piece_num']['checked']))
-	{
+	if (!empty($arrayfields['t.piece_num']['checked'])) {
 		print '<td>';
 		$object->id = $line->id;
 		$object->piece_num = $line->piece_num;
 		print $object->getNomUrl(1, '', 0, '', 1);
 		print '</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Journal code
-	if (!empty($arrayfields['t.code_journal']['checked']))
-	{
+	if (!empty($arrayfields['t.code_journal']['checked'])) {
 		$accountingjournal = new AccountingJournal($db);
 		$result = $accountingjournal->fetch('', $line->code_journal);
 		$journaltoshow = (($result > 0) ? $accountingjournal->getNomUrl(0, 0, 0, '', 0) : $line->code_journal);
 		print '<td class="center">'.$journaltoshow.'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Document date
-	if (!empty($arrayfields['t.doc_date']['checked']))
-	{
+	if (!empty($arrayfields['t.doc_date']['checked'])) {
 		print '<td class="center">'.dol_print_date($line->doc_date, 'day').'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Document ref
-	if (!empty($arrayfields['t.doc_ref']['checked']))
-	{
-		if ($line->doc_type == 'customer_invoice')
-		{
+	if (!empty($arrayfields['t.doc_ref']['checked'])) {
+		if ($line->doc_type == 'customer_invoice') {
 			$langs->loadLangs(array('bills'));
 
 			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
@@ -945,8 +980,7 @@ while ($i < min($num, $limit))
 			$filedir = $conf->facture->dir_output.'/'.dol_sanitizeFileName($line->doc_ref);
 			$urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id;
 			$documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir);
-		} elseif ($line->doc_type == 'supplier_invoice')
-		{
+		} elseif ($line->doc_type == 'supplier_invoice') {
 			$langs->loadLangs(array('bills'));
 
 			require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
@@ -958,8 +992,7 @@ while ($i < min($num, $limit))
 			$filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($line->fk_doc, 2, 0, 0, $objectstatic, $modulepart).dol_sanitizeFileName($line->doc_ref);
 			$subdir = get_exdir($objectstatic->id, 2, 0, 0, $objectstatic, $modulepart).dol_sanitizeFileName($line->doc_ref);
 			$documentlink = $formfile->getDocumentsLink($objectstatic->element, $subdir, $filedir);
-		} elseif ($line->doc_type == 'expense_report')
-		{
+		} elseif ($line->doc_type == 'expense_report') {
 			$langs->loadLangs(array('trips'));
 
 			require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
@@ -971,8 +1004,7 @@ while ($i < min($num, $limit))
 			$filedir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($line->doc_ref);
 			$urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id;
 			$documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir);
-		} elseif ($line->doc_type == 'bank')
-		{
+		} elseif ($line->doc_type == 'bank') {
 			require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 			$objectstatic = new AccountLine($db);
 			$objectstatic->fetch($line->fk_doc);
@@ -986,8 +1018,7 @@ while ($i < min($num, $limit))
 		// Picto + Ref
 		print '<td class="nobordernopadding nowrap">';
 
-		if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report')
-		{
+		if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report') {
 			print $objectstatic->getNomUrl(1, '', 0, 0, '', 0, -1, 1);
 			print $documentlink;
 		} elseif ($line->doc_type == 'bank') {
@@ -1000,53 +1031,65 @@ while ($i < min($num, $limit))
 		print '</td></tr></table>';
 
 		print "</td>\n";
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Account number
-	if (!empty($arrayfields['t.numero_compte']['checked']))
-	{
+	if (!empty($arrayfields['t.numero_compte']['checked'])) {
 		print '<td>'.length_accountg($line->numero_compte).'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Subledger account
-	if (!empty($arrayfields['t.subledger_account']['checked']))
-	{
+	if (!empty($arrayfields['t.subledger_account']['checked'])) {
 		print '<td>'.length_accounta($line->subledger_account).'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Label operation
-	if (!empty($arrayfields['t.label_operation']['checked']))
-	{
+	if (!empty($arrayfields['t.label_operation']['checked'])) {
 		print '<td>'.$line->label_operation.'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Amount debit
-	if (!empty($arrayfields['t.debit']['checked']))
-	{
+	if (!empty($arrayfields['t.debit']['checked'])) {
 		print '<td class="nowrap right">'.($line->debit != 0 ? price($line->debit) : '').'</td>';
-		if (!$i) $totalarray['nbfield']++;
-		if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totaldebit';
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
+		if (!$i) {
+			$totalarray['pos'][$totalarray['nbfield']] = 'totaldebit';
+		}
 		$totalarray['val']['totaldebit'] += $line->debit;
 	}
 
 	// Amount credit
-	if (!empty($arrayfields['t.credit']['checked']))
-	{
+	if (!empty($arrayfields['t.credit']['checked'])) {
 		print '<td class="nowrap right">'.($line->credit != 0 ? price($line->credit) : '').'</td>';
-		if (!$i) $totalarray['nbfield']++;
-		if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalcredit';
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
+		if (!$i) {
+			$totalarray['pos'][$totalarray['nbfield']] = 'totalcredit';
+		}
 		$totalarray['val']['totalcredit'] += $line->credit;
 	}
 
 	// Lettering code
-	if (!empty($arrayfields['t.lettering_code']['checked']))
-	{
+	if (!empty($arrayfields['t.lettering_code']['checked'])) {
 		print '<td class="center">'.$line->lettering_code.'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Fields from hook
@@ -1055,24 +1098,27 @@ while ($i < min($num, $limit))
 	print $hookmanager->resPrint;
 
 	// Creation operation date
-	if (!empty($arrayfields['t.date_creation']['checked']))
-	{
+	if (!empty($arrayfields['t.date_creation']['checked'])) {
 		print '<td class="center">'.dol_print_date($line->date_creation, 'dayhour').'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Modification operation date
-	if (!empty($arrayfields['t.tms']['checked']))
-	{
+	if (!empty($arrayfields['t.tms']['checked'])) {
 		print '<td class="center">'.dol_print_date($line->date_modification, 'dayhour').'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Exported operation date
-	if (!empty($arrayfields['t.date_export']['checked']))
-	{
+	if (!empty($arrayfields['t.date_export']['checked'])) {
 		print '<td class="center">'.dol_print_date($line->date_export, 'dayhour').'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Action column
@@ -1087,7 +1133,9 @@ while ($i < min($num, $limit))
 	}
 	print '</td>';
 
-	if (!$i) $totalarray['nbfield']++;
+	if (!$i) {
+		$totalarray['nbfield']++;
+	}
 
 	print "</tr>\n";
 

+ 143 - 85
htdocs/accountancy/bookkeeping/listbyaccount.php

@@ -85,12 +85,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0) { $page = 0; }
+if (empty($page) || $page < 0) {
+	$page = 0;
+}
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if ($sortorder == "") $sortorder = "ASC";
-if ($sortfield == "") $sortfield = "t.doc_date,t.rowid";
+if ($sortorder == "") {
+	$sortorder = "ASC";
+}
+if ($sortfield == "") {
+	$sortfield = "t.doc_date,t.rowid";
+}
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 $object = new BookKeeping($db);
@@ -113,11 +119,12 @@ if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('searc
 	} else {
 		$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
 		$year_start = dol_print_date(dol_now(), '%Y');
-		if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year
+		if (dol_print_date(dol_now(), '%m') < $month_start) {
+			$year_start--; // If current month is lower that starting fiscal month, we start last year
+		}
 		$year_end = $year_start + 1;
 		$month_end = $month_start - 1;
-		if ($month_end < 1)
-		{
+		if ($month_end < 1) {
 			$month_end = 12;
 			$year_end--;
 		}
@@ -139,7 +146,9 @@ $arrayfields = array(
 	't.date_export'=>array('label'=>$langs->trans("DateExport"), 'checked'=>1),
 );
 
-if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) unset($arrayfields['t.lettering_code']);
+if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) {
+	unset($arrayfields['t.lettering_code']);
+}
 
 if ($search_date_start && empty($search_date_startyear)) {
 	$tmparray = dol_getdate($search_date_start);
@@ -159,19 +168,23 @@ if ($search_date_end && empty($search_date_endyear)) {
  * Action
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
 
 $parameters = array('socid'=>$socid);
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-	{
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 		$search_doc_date = '';
 		$search_accountancy_code = '';
 		$search_accountancy_code_start = '';
@@ -305,8 +318,7 @@ if ($action == 'delbookkeepingyearconfirm' && $user->rights->accounting->mouveme
 		$deljournal = 0;
 	}
 
-	if (!empty($delmonth) || !empty($delyear) || !empty($deljournal))
-	{
+	if (!empty($delmonth) || !empty($delyear) || !empty($deljournal)) {
 		$result = $object->deleteByYearAndJournal($delyear, $deljournal, '', ($delmonth > 0 ? $delmonth : 0));
 		if ($result < 0) {
 			setEventMessages($object->error, $object->errors, 'errors');
@@ -418,7 +430,9 @@ if ($action == 'delbookkeepingyear') {
 print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
 print '<input type="hidden" name="token" value="'.newToken().'">';
 print '<input type="hidden" name="action" value="list">';
-if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+if ($optioncss != '') {
+	print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+}
 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
 print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
@@ -432,18 +446,27 @@ if (empty($reshook)) {
 	$newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/card.php?action=create');
 }
 
-if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+	$param .= '&contextpage='.urlencode($contextpage);
+}
+if ($limit > 0 && $limit != $conf->liste_limit) {
+	$param .= '&limit='.urlencode($limit);
+}
 
 print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1);
 
 $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
 $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
-if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
+if ($massactionbutton) {
+	$selectedfields .= $form->showCheckAddButtons('checkforselect', 1);
+}
 
 // Reverse sort order
-if (preg_match('/^asc/i', $sortorder)) $sortorder = "asc";
-else $sortorder = "desc";
+if (preg_match('/^asc/i', $sortorder)) {
+	$sortorder = "asc";
+} else {
+	$sortorder = "desc";
+}
 
 $moreforfilter = '';
 
@@ -460,8 +483,11 @@ $moreforfilter .= '</div>';
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
-if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
-else $moreforfilter = $hookmanager->resPrint;
+if (empty($reshook)) {
+	$moreforfilter .= $hookmanager->resPrint;
+} else {
+	$moreforfilter = $hookmanager->resPrint;
+}
 
 print '<div class="liste_titre liste_titre_bydiv centpercent">';
 print $moreforfilter;
@@ -474,8 +500,7 @@ print '<table class="tagtable liste centpercent">';
 print '<tr class="liste_titre_filter">';
 
 // Movement number
-if (!empty($arrayfields['t.piece_num']['checked']))
-{
+if (!empty($arrayfields['t.piece_num']['checked'])) {
 	print '<td class="liste_titre"><input type="text" name="search_mvt_num" size="6" value="'.dol_escape_htmltag($search_mvt_num).'"></td>';
 }
 // Code journal
@@ -512,8 +537,7 @@ if (!empty($arrayfields['t.credit']['checked'])) {
 	print '<td class="liste_titre right"><input type="text" class="flat" name="search_credit" size="4" value="'.dol_escape_htmltag($search_credit).'"></td>';
 }
 // Lettering code
-if (!empty($arrayfields['t.lettering_code']['checked']))
-{
+if (!empty($arrayfields['t.lettering_code']['checked'])) {
 	print '<td class="liste_titre center">';
 	print '<input type="text" size="3" class="flat" name="search_lettering_code" value="'.$search_lettering_code.'"/>';
 	print '<br><span class="nowrap"><input type="checkbox" name="search_not_reconciled" value="notreconciled"'.($search_not_reconciled == 'notreconciled' ? ' checked' : '').'>'.$langs->trans("NotReconciled").'</span>';
@@ -544,15 +568,33 @@ print '</td>';
 print "</tr>\n";
 
 print '<tr class="liste_titre">';
-if (!empty($arrayfields['t.piece_num']['checked']))				print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, '', $sortfield, $sortorder);
-if (!empty($arrayfields['t.code_journal']['checked']))			print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center ');
-if (!empty($arrayfields['t.doc_date']['checked']))				print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center ');
-if (!empty($arrayfields['t.doc_ref']['checked']))				print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder);
-if (!empty($arrayfields['t.label_operation']['checked']))		print_liste_field_titre($arrayfields['t.label_operation']['label'], $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder);
-if (!empty($arrayfields['t.debit']['checked']))					print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right ');
-if (!empty($arrayfields['t.credit']['checked']))				print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right ');
-if (!empty($arrayfields['t.lettering_code']['checked']))		print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center ');
-if (!empty($arrayfields['t.date_export']['checked']))			print_liste_field_titre($arrayfields['t.date_export']['label'], $_SERVER['PHP_SELF'], "t.date_export", "", $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['t.piece_num']['checked'])) {
+	print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, '', $sortfield, $sortorder);
+}
+if (!empty($arrayfields['t.code_journal']['checked'])) {
+	print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center ');
+}
+if (!empty($arrayfields['t.doc_date']['checked'])) {
+	print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center ');
+}
+if (!empty($arrayfields['t.doc_ref']['checked'])) {
+	print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder);
+}
+if (!empty($arrayfields['t.label_operation']['checked'])) {
+	print_liste_field_titre($arrayfields['t.label_operation']['label'], $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder);
+}
+if (!empty($arrayfields['t.debit']['checked'])) {
+	print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right ');
+}
+if (!empty($arrayfields['t.credit']['checked'])) {
+	print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right ');
+}
+if (!empty($arrayfields['t.lettering_code']['checked'])) {
+	print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center ');
+}
+if (!empty($arrayfields['t.date_export']['checked'])) {
+	print_liste_field_titre($arrayfields['t.date_export']['label'], $_SERVER['PHP_SELF'], "t.date_export", "", $param, '', $sortfield, $sortorder, 'center ');
+}
 // Hook fields
 $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
 $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
@@ -571,8 +613,7 @@ $displayed_account_number = null; // Start with undefined to be able to distingu
 // --------------------------------------------------------------------
 $i = 0;
 $totalarray = array();
-while ($i < min($num, $limit))
-{
+while ($i < min($num, $limit)) {
 	$line = $object->lines[$i];
 
 	$total_debit += $line->debit;
@@ -586,11 +627,15 @@ while ($i < min($num, $limit))
 		$colnumber = 5;
 		$colnumberend = 7;
 
-		if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) $colnumber--;
-		if (empty($arrayfields['t.date_export']['checked'])) $colnumber--;
+		if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) {
+			$colnumber--;
+		}
+		if (empty($arrayfields['t.date_export']['checked'])) {
+			$colnumber--;
+		}
 
-        $colspan = $totalarray['nbfield'] - $colnumber;
-        $colspanend = $totalarray['nbfield'] - $colnumberend;
+		$colspan = $totalarray['nbfield'] - $colnumber;
+		$colspanend = $totalarray['nbfield'] - $colnumberend;
 		// Show a subtotal by accounting account
 		if (isset($displayed_account_number)) {
 			print '<tr class="liste_total">';
@@ -603,8 +648,7 @@ while ($i < min($num, $limit))
 			$balance = $sous_total_debit - $sous_total_credit;
 			print '<tr class="liste_total">';
 			print '<td class="right" colspan="'.$colspan.'">'.$langs->trans("Balance").':</td>';
-			if ($balance > 0)
-			{
+			if ($balance > 0) {
 				print '<td class="nowraponall right">';
 				print price($sous_total_debit - $sous_total_credit);
 				print '</td>';
@@ -622,8 +666,11 @@ while ($i < min($num, $limit))
 		// Show the break account
 		print "<tr>";
 		print '<td colspan="'.($totalarray['nbfield'] ? $totalarray['nbfield'] : 10).'" style="font-weight:bold; border-bottom: 1pt solid black;">';
-		if ($line->numero_compte != "" && $line->numero_compte != '-1') print length_accountg($line->numero_compte).' : '.$object->get_compte_desc($line->numero_compte);
-		else print '<span class="error">'.$langs->trans("Unknown").'</span>';
+		if ($line->numero_compte != "" && $line->numero_compte != '-1') {
+			print length_accountg($line->numero_compte).' : '.$object->get_compte_desc($line->numero_compte);
+		} else {
+			print '<span class="error">'.$langs->trans("Unknown").'</span>';
+		}
 		print '</td>';
 		print '</tr>';
 
@@ -638,38 +685,39 @@ while ($i < min($num, $limit))
 	print '<tr class="oddeven">';
 
 	// Piece number
-	if (!empty($arrayfields['t.piece_num']['checked']))
-	{
+	if (!empty($arrayfields['t.piece_num']['checked'])) {
 		print '<td>';
 		$object->id = $line->id;
 		$object->piece_num = $line->piece_num;
 		print $object->getNomUrl(1, '', 0, '', 1);
 		print '</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Journal code
-	if (!empty($arrayfields['t.code_journal']['checked']))
-	{
+	if (!empty($arrayfields['t.code_journal']['checked'])) {
 		$accountingjournal = new AccountingJournal($db);
 		$result = $accountingjournal->fetch('', $line->code_journal);
 		$journaltoshow = (($result > 0) ? $accountingjournal->getNomUrl(0, 0, 0, '', 0) : $line->code_journal);
 		print '<td class="center">'.$journaltoshow.'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Document date
-	if (!empty($arrayfields['t.doc_date']['checked']))
-	{
+	if (!empty($arrayfields['t.doc_date']['checked'])) {
 		print '<td class="center">'.dol_print_date($line->doc_date, 'day').'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Document ref
-	if (!empty($arrayfields['t.doc_ref']['checked']))
-	{
-		if ($line->doc_type == 'customer_invoice')
-		{
+	if (!empty($arrayfields['t.doc_ref']['checked'])) {
+		if ($line->doc_type == 'customer_invoice') {
 			$langs->loadLangs(array('bills'));
 
 			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
@@ -681,8 +729,7 @@ while ($i < min($num, $limit))
 			$filedir = $conf->facture->dir_output.'/'.dol_sanitizeFileName($line->doc_ref);
 			$urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id;
 			$documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir);
-		} elseif ($line->doc_type == 'supplier_invoice')
-		{
+		} elseif ($line->doc_type == 'supplier_invoice') {
 			$langs->loadLangs(array('bills'));
 
 			require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
@@ -694,8 +741,7 @@ while ($i < min($num, $limit))
 			$filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($line->fk_doc, 2, 0, 0, $objectstatic, $modulepart).dol_sanitizeFileName($line->doc_ref);
 			$subdir = get_exdir($objectstatic->id, 2, 0, 0, $objectstatic, $modulepart).dol_sanitizeFileName($line->doc_ref);
 			$documentlink = $formfile->getDocumentsLink($objectstatic->element, $subdir, $filedir);
-		} elseif ($line->doc_type == 'expense_report')
-		{
+		} elseif ($line->doc_type == 'expense_report') {
 			$langs->loadLangs(array('trips'));
 
 			require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
@@ -707,8 +753,7 @@ while ($i < min($num, $limit))
 			$filedir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($line->doc_ref);
 			$urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id;
 			$documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir);
-		} elseif ($line->doc_type == 'bank')
-		{
+		} elseif ($line->doc_type == 'bank') {
 			require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 			$objectstatic = new AccountLine($db);
 			$objectstatic->fetch($line->fk_doc);
@@ -722,8 +767,7 @@ while ($i < min($num, $limit))
 		// Picto + Ref
 		print '<td class="nobordernopadding">';
 
-		if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report')
-		{
+		if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report') {
 			print $objectstatic->getNomUrl(1, '', 0, 0, '', 0, -1, 1);
 			print $documentlink;
 		} elseif ($line->doc_type == 'bank') {
@@ -736,7 +780,9 @@ while ($i < min($num, $limit))
 		print '</td></tr></table>';
 
 		print "</td>\n";
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Label operation
@@ -744,38 +790,49 @@ while ($i < min($num, $limit))
 		// Affiche un lien vers la facture client/fournisseur
 		$doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref);
 		print strlen(length_accounta($line->subledger_account)) == 0 ? '<td>'.$line->label_operation.'</td>' : '<td>'.$line->label_operation.'<br><span style="font-size:0.8em">('.length_accounta($line->subledger_account).')</span></td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Amount debit
-	if (!empty($arrayfields['t.debit']['checked']))
-	{
+	if (!empty($arrayfields['t.debit']['checked'])) {
 		print '<td class="nowrap right">'.($line->debit ? price($line->debit) : '').'</td>';
-		if (!$i) $totalarray['nbfield']++;
-		if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totaldebit';
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
+		if (!$i) {
+			$totalarray['pos'][$totalarray['nbfield']] = 'totaldebit';
+		}
 		$totalarray['val']['totaldebit'] += $line->debit;
 	}
 
 	// Amount credit
 	if (!empty($arrayfields['t.credit']['checked'])) {
 		print '<td class="nowrap right">'.($line->credit ? price($line->credit) : '').'</td>';
-		if (!$i) $totalarray['nbfield']++;
-		if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalcredit';
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
+		if (!$i) {
+			$totalarray['pos'][$totalarray['nbfield']] = 'totalcredit';
+		}
 		$totalarray['val']['totalcredit'] += $line->credit;
 	}
 
 	// Lettering code
-	if (!empty($arrayfields['t.lettering_code']['checked']))
-	{
+	if (!empty($arrayfields['t.lettering_code']['checked'])) {
 		print '<td class="center">'.$line->lettering_code.'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Exported operation date
-	if (!empty($arrayfields['t.date_export']['checked']))
-	{
+	if (!empty($arrayfields['t.date_export']['checked'])) {
 		print '<td class="center">'.dol_print_date($line->date_export, 'dayhour').'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Fields from hook
@@ -794,7 +851,9 @@ while ($i < min($num, $limit))
 		}
 	}
 	print '</td>';
-	if (!$i) $totalarray['nbfield']++;
+	if (!$i) {
+		$totalarray['nbfield']++;
+	}
 
 	// Comptabilise le sous-total
 	$sous_total_debit += $line->debit;
@@ -818,8 +877,7 @@ if ($num > 0) {
 	$balance = $sous_total_debit - $sous_total_credit;
 	print '<tr class="liste_total">';
 	print '<td class="right" colspan="'.$colspan.'">'.$langs->trans("Balance").':</td>';
-	if ($balance > 0)
-	{
+	if ($balance > 0) {
 		print '<td class="nowraponall right">';
 		print price($sous_total_debit - $sous_total_credit);
 		print '</td>';

+ 13 - 9
htdocs/accountancy/bookkeeping/listbysubaccount.php

@@ -503,8 +503,7 @@ print '<table class="tagtable liste centpercent">';
 print '<tr class="liste_titre_filter">';
 
 // Movement number
-if (!empty($arrayfields['t.piece_num']['checked']))
-{
+if (!empty($arrayfields['t.piece_num']['checked'])) {
 	print '<td class="liste_titre"><input type="text" name="search_mvt_num" size="6" value="'.dol_escape_htmltag($search_mvt_num).'"></td>';
 }
 // Code journal
@@ -631,11 +630,15 @@ while ($i < min($num, $limit)) {
 		$colnumber = 5;
 		$colnumberend = 7;
 
-		if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) $colnumber--;
-		if (empty($arrayfields['t.date_export']['checked'])) $colnumber--;
+		if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) {
+			$colnumber--;
+		}
+		if (empty($arrayfields['t.date_export']['checked'])) {
+			$colnumber--;
+		}
 
-        $colspan = $totalarray['nbfield'] - $colnumber;
-        $colspanend = $totalarray['nbfield'] - $colnumberend;
+		$colspan = $totalarray['nbfield'] - $colnumber;
+		$colspanend = $totalarray['nbfield'] - $colnumberend;
 
 		// Show a subtotal by accounting account
 		if (isset($displayed_account_number)) {
@@ -838,10 +841,11 @@ while ($i < min($num, $limit)) {
 	}
 
 	// Exported operation date
-	if (!empty($arrayfields['t.date_export']['checked']))
-	{
+	if (!empty($arrayfields['t.date_export']['checked'])) {
 		print '<td class="center">'.dol_print_date($line->date_export, 'dayhour').'</td>';
-		if (!$i) $totalarray['nbfield']++;
+		if (!$i) {
+			$totalarray['nbfield']++;
+		}
 	}
 
 	// Fields from hook

+ 0 - 1
htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php

@@ -225,7 +225,6 @@ if ($resql) {
 
 	// Piece
 	print '<td><input type="text" name="search_doc_ref" value="' . $search_doc_ref . '"></td>';
-
 	print '<td colspan="6">&nbsp;</td>';
 	print '<td class="right">';
 	$searchpicto = $form->showFilterButtons();

+ 0 - 1
htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php

@@ -222,7 +222,6 @@ if ($resql) {
 
 	// Piece
 	print '<td><input type="text" name="search_doc_ref" value="' . $search_doc_ref . '"></td>';
-
 	print '<td colspan="6">&nbsp;</td>';
 	print '<td class="right">';
 	$searchpicto = $form->showFilterButtons();

+ 112 - 69
htdocs/accountancy/class/accountancycategory.class.php

@@ -153,22 +153,42 @@ class AccountancyCategory // extends CommonObject
 		$error = 0;
 
 		// Clean parameters
-		if (isset($this->code)) $this->code = trim($this->code);
-		if (isset($this->label)) $this->label = trim($this->label);
-		if (isset($this->range_account)) $this->range_account = trim($this->range_account);
-		if (isset($this->sens)) $this->sens = (int) $this->sens;
-		if (isset($this->category_type)) $this->category_type = (int) $this->category_type;
-		if (isset($this->formula)) $this->formula = trim($this->formula);
-		if (isset($this->position)) $this->position = (int) $this->position;
-		if (isset($this->fk_country)) $this->fk_country = (int) $this->fk_country;
-		if (isset($this->active)) $this->active = (int) $this->active;
+		if (isset($this->code)) {
+			$this->code = trim($this->code);
+		}
+		if (isset($this->label)) {
+			$this->label = trim($this->label);
+		}
+		if (isset($this->range_account)) {
+			$this->range_account = trim($this->range_account);
+		}
+		if (isset($this->sens)) {
+			$this->sens = (int) $this->sens;
+		}
+		if (isset($this->category_type)) {
+			$this->category_type = (int) $this->category_type;
+		}
+		if (isset($this->formula)) {
+			$this->formula = trim($this->formula);
+		}
+		if (isset($this->position)) {
+			$this->position = (int) $this->position;
+		}
+		if (isset($this->fk_country)) {
+			$this->fk_country = (int) $this->fk_country;
+		}
+		if (isset($this->active)) {
+			$this->active = (int) $this->active;
+		}
 
 		// Check parameters
 		// Put here code to add control on parameters values
 
 		// Insert request
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_accounting_category(";
-		if ($this->rowid > 0) $sql .= "rowid, ";
+		if ($this->rowid > 0) {
+			$sql .= "rowid, ";
+		}
 		$sql .= "code, ";
 		$sql .= "label, ";
 		$sql .= "range_account, ";
@@ -180,7 +200,9 @@ class AccountancyCategory // extends CommonObject
 		$sql .= "active, ";
 		$sql .= "entity";
 		$sql .= ") VALUES (";
-		if ($this->rowid > 0) $sql .= " ".$this->rowid.",";
+		if ($this->rowid > 0) {
+			$sql .= " ".$this->rowid.",";
+		}
 		$sql .= " ".(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").",";
 		$sql .= " ".(!isset($this->label) ? 'NULL' : "'".$this->db->escape($this->label)."'").",";
 		$sql .= " ".(!isset($this->range_account) ? 'NULL' : "'".$this->db->escape($this->range_account)."'").",";
@@ -197,13 +219,13 @@ class AccountancyCategory // extends CommonObject
 
 		dol_syslog(get_class($this)."::create", LOG_DEBUG);
 		$resql = $this->db->query($sql);
-		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
+		if (!$resql) {
+			$error++; $this->errors[] = "Error ".$this->db->lasterror();
+		}
 
 		// Commit or rollback
-		if ($error)
-		{
-			foreach ($this->errors as $errmsg)
-			{
+		if ($error) {
+			foreach ($this->errors as $errmsg) {
 				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
 				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
 			}
@@ -238,19 +260,21 @@ class AccountancyCategory // extends CommonObject
 		$sql .= " t.fk_country,";
 		$sql .= " t.active";
 		$sql .= " FROM ".MAIN_DB_PREFIX."c_accounting_category as t";
-		if ($id)   $sql .= " WHERE t.rowid = ".$id;
-		else {
+		if ($id) {
+			$sql .= " WHERE t.rowid = ".$id;
+		} else {
 			$sql .= " WHERE t.entity IN (".getEntity('c_accounting_category').")"; // Dont't use entity if you use rowid
-			if ($code) $sql .= " AND t.code = '".$this->db->escape($code)."'";
-			elseif ($label) $sql .= " AND t.label = '".$this->db->escape($label)."'";
+			if ($code) {
+				$sql .= " AND t.code = '".$this->db->escape($code)."'";
+			} elseif ($label) {
+				$sql .= " AND t.label = '".$this->db->escape($label)."'";
+			}
 		}
 
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
 		$resql = $this->db->query($sql);
-		if ($resql)
-		{
-			if ($this->db->num_rows($resql))
-			{
+		if ($resql) {
+			if ($this->db->num_rows($resql)) {
 				$obj = $this->db->fetch_object($resql);
 
 				$this->id            = $obj->rowid;
@@ -287,15 +311,33 @@ class AccountancyCategory // extends CommonObject
 		$error = 0;
 
 		// Clean parameters
-		if (isset($this->code)) $this->code = trim($this->code);
-		if (isset($this->label)) $this->label = trim($this->label);
-		if (isset($this->range_account)) $this->range_account = trim($this->range_account);
-		if (isset($this->sens)) $this->sens = (int) $this->sens;
-		if (isset($this->category_type)) $this->category_type = (int) $this->category_type;
-		if (isset($this->formula)) $this->formula = trim($this->formula);
-		if (isset($this->position)) $this->position = (int) $this->position;
-		if (isset($this->fk_country)) $this->fk_country = (int) $this->fk_country;
-		if (isset($this->active)) $this->active = (int) $this->active;
+		if (isset($this->code)) {
+			$this->code = trim($this->code);
+		}
+		if (isset($this->label)) {
+			$this->label = trim($this->label);
+		}
+		if (isset($this->range_account)) {
+			$this->range_account = trim($this->range_account);
+		}
+		if (isset($this->sens)) {
+			$this->sens = (int) $this->sens;
+		}
+		if (isset($this->category_type)) {
+			$this->category_type = (int) $this->category_type;
+		}
+		if (isset($this->formula)) {
+			$this->formula = trim($this->formula);
+		}
+		if (isset($this->position)) {
+			$this->position = (int) $this->position;
+		}
+		if (isset($this->fk_country)) {
+			$this->fk_country = (int) $this->fk_country;
+		}
+		if (isset($this->active)) {
+			$this->active = (int) $this->active;
+		}
 
 
 		// Check parameters
@@ -318,13 +360,13 @@ class AccountancyCategory // extends CommonObject
 
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
 		$resql = $this->db->query($sql);
-		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
+		if (!$resql) {
+			$error++; $this->errors[] = "Error ".$this->db->lasterror();
+		}
 
 		// Commit or rollback
-		if ($error)
-		{
-			foreach ($this->errors as $errmsg)
-			{
+		if ($error) {
+			foreach ($this->errors as $errmsg) {
 				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
 				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
 			}
@@ -356,13 +398,13 @@ class AccountancyCategory // extends CommonObject
 
 		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
 		$resql = $this->db->query($sql);
-		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
+		if (!$resql) {
+			$error++; $this->errors[] = "Error ".$this->db->lasterror();
+		}
 
 		// Commit or rollback
-		if ($error)
-		{
-			foreach ($this->errors as $errmsg)
-			{
+		if ($error) {
+			foreach ($this->errors as $errmsg) {
 				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
 				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
 			}
@@ -537,13 +579,13 @@ class AccountancyCategory // extends CommonObject
 		}
 
 		$accountincptsadded = array();
-		while ($obj = $this->db->fetch_object($resql))
-		{
+		while ($obj = $this->db->fetch_object($resql)) {
 			$account_number_formated = length_accountg($obj->account_number);
-			if (!empty($accountincptsadded[$account_number_formated])) continue;
+			if (!empty($accountincptsadded[$account_number_formated])) {
+				continue;
+			}
 
-			if (array_key_exists($account_number_formated, $cpts))
-			{
+			if (array_key_exists($account_number_formated, $cpts)) {
 				$accountincptsadded[$account_number_formated] = 1;
 				// We found an account number that is in list $cpts of account to add
 				$sql = "UPDATE ".MAIN_DB_PREFIX."accounting_account";
@@ -687,48 +729,49 @@ class AccountancyCategory // extends CommonObject
 		$this->sdcpermonth = array();
 
 		$sql = "SELECT SUM(t.debit) as debit, SUM(t.credit) as credit";
-		if (is_array($cpt)) $sql .= ", t.numero_compte as accountancy_account";
+		if (is_array($cpt)) {
+			$sql .= ", t.numero_compte as accountancy_account";
+		}
 		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as t";
 		//if (in_array($this->db->type, array('mysql', 'mysqli'))) $sql.=' USE INDEX idx_accounting_bookkeeping_doc_date';
 		$sql .= " WHERE t.entity = ".$conf->entity;
-		if (is_array($cpt))
-		{
+		if (is_array($cpt)) {
 			$listofaccount = '';
-			foreach ($cpt as $cptcursor)
-			{
-				if ($listofaccount) $listofaccount .= ",";
+			foreach ($cpt as $cptcursor) {
+				if ($listofaccount) {
+					$listofaccount .= ",";
+				}
 				$listofaccount .= "'".$cptcursor."'";
 			}
 			$sql .= " AND t.numero_compte IN (".$listofaccount.")";
 		} else {
 			$sql .= " AND t.numero_compte = '".$this->db->escape($cpt)."'";
 		}
-		if (!empty($date_start) && !empty($date_end) && (empty($month) || empty($year)))	// If month/year provided, it is stronger than filter date_start/date_end
+		if (!empty($date_start) && !empty($date_end) && (empty($month) || empty($year))) {	// If month/year provided, it is stronger than filter date_start/date_end
 			$sql .= " AND (t.doc_date BETWEEN '".$this->db->idate($date_start)."' AND '".$this->db->idate($date_end)."')";
+		}
 		if (!empty($month) && !empty($year)) {
 			$sql .= " AND (t.doc_date BETWEEN '".$this->db->idate(dol_get_first_day($year, $month))."' AND '".$this->db->idate(dol_get_last_day($year, $month))."')";
 		}
-		if ($thirdparty_code != 'nofilter')
-		{
+		if ($thirdparty_code != 'nofilter') {
 			$sql .= " AND t.thirdparty_code = '".$this->db->escape($thirdparty_code)."'";
 		}
-		if (is_array($cpt)) $sql .= " GROUP BY t.numero_compte";
+		if (is_array($cpt)) {
+			$sql .= " GROUP BY t.numero_compte";
+		}
 		//print $sql;
 
 		$resql = $this->db->query($sql);
-		if ($resql)
-		{
+		if ($resql) {
 			$num = $this->db->num_rows($resql);
-			if ($num)
-			{
+			if ($num) {
 				$obj = $this->db->fetch_object($resql);
 				if ($sens == 1) {
 					$this->sdc = $obj->debit - $obj->credit;
 				} else {
 					$this->sdc = $obj->credit - $obj->debit;
 				}
-				if (is_array($cpt))
-				{
+				if (is_array($cpt)) {
 					$this->sdcperaccount[$obj->accountancy_account] = $this->sdc;
 				}
 			}
@@ -760,7 +803,9 @@ class AccountancyCategory // extends CommonObject
 		$sql .= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c";
 		$sql .= " WHERE c.active = 1";
 		$sql .= " AND c.entity = ".$conf->entity;
-		if ($categorytype >= 0) $sql .= " AND c.category_type = 1";
+		if ($categorytype >= 0) {
+			$sql .= " AND c.category_type = 1";
+		}
 		$sql .= " AND (c.fk_country = ".$mysoc->country_id." OR c.fk_country = 0)";
 		$sql .= " ORDER BY c.position ASC";
 
@@ -815,8 +860,7 @@ class AccountancyCategory // extends CommonObject
 			exit();
 		}
 
-		if (!empty($cat_id))
-		{
+		if (!empty($cat_id)) {
 			$sql = "SELECT t.rowid, t.account_number, t.label as account_label";
 			$sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as t";
 			$sql .= " WHERE t.fk_accounting_category = ".$cat_id;
@@ -838,8 +882,7 @@ class AccountancyCategory // extends CommonObject
 			$num = $this->db->num_rows($resql);
 			$data = array();
 			if ($num) {
-				while ($obj = $this->db->fetch_object($resql))
-				{
+				while ($obj = $this->db->fetch_object($resql)) {
 					$data[] = array(
 							'id' => $obj->rowid,
 							'account_number' => $obj->account_number,

+ 63 - 74
htdocs/accountancy/class/accountancyexport.class.php

@@ -277,61 +277,61 @@ class AccountancyExport
 
 
 		switch ($formatexportset) {
-			case self::$EXPORT_TYPE_CONFIGURABLE :
+			case self::$EXPORT_TYPE_CONFIGURABLE:
 				$this->exportConfigurable($TData);
 				break;
-			case self::$EXPORT_TYPE_CEGID :
+			case self::$EXPORT_TYPE_CEGID:
 				$this->exportCegid($TData);
 				break;
-			case self::$EXPORT_TYPE_COALA :
+			case self::$EXPORT_TYPE_COALA:
 				$this->exportCoala($TData);
 				break;
-			case self::$EXPORT_TYPE_BOB50 :
+			case self::$EXPORT_TYPE_BOB50:
 				$this->exportBob50($TData);
 				break;
-			case self::$EXPORT_TYPE_CIEL :
+			case self::$EXPORT_TYPE_CIEL:
 				$this->exportCiel($TData);
 				break;
-			case self::$EXPORT_TYPE_QUADRATUS :
+			case self::$EXPORT_TYPE_QUADRATUS:
 				$this->exportQuadratus($TData);
 				break;
-			case self::$EXPORT_TYPE_WINFIC :
+			case self::$EXPORT_TYPE_WINFIC:
 				$this->exportWinfic($TData);
 				break;
-			case self::$EXPORT_TYPE_EBP :
+			case self::$EXPORT_TYPE_EBP:
 				$this->exportEbp($TData);
 				break;
-			case self::$EXPORT_TYPE_COGILOG :
+			case self::$EXPORT_TYPE_COGILOG:
 				$this->exportCogilog($TData);
 				break;
-			case self::$EXPORT_TYPE_AGIRIS :
+			case self::$EXPORT_TYPE_AGIRIS:
 				$this->exportAgiris($TData);
 				break;
-			case self::$EXPORT_TYPE_OPENCONCERTO :
+			case self::$EXPORT_TYPE_OPENCONCERTO:
 				$this->exportOpenConcerto($TData);
 				break;
-			case self::$EXPORT_TYPE_SAGE50_SWISS :
+			case self::$EXPORT_TYPE_SAGE50_SWISS:
 				$this->exportSAGE50SWISS($TData);
 				break;
-			case self::$EXPORT_TYPE_CHARLEMAGNE :
+			case self::$EXPORT_TYPE_CHARLEMAGNE:
 				$this->exportCharlemagne($TData);
 				break;
-			case self::$EXPORT_TYPE_LDCOMPTA :
+			case self::$EXPORT_TYPE_LDCOMPTA:
 				$this->exportLDCompta($TData);
 				break;
-			case self::$EXPORT_TYPE_LDCOMPTA10 :
+			case self::$EXPORT_TYPE_LDCOMPTA10:
 				$this->exportLDCompta10($TData);
 				break;
-			case self::$EXPORT_TYPE_GESTIMUMV3 :
+			case self::$EXPORT_TYPE_GESTIMUMV3:
 				$this->exportGestimumV3($TData);
 				break;
-			case self::$EXPORT_TYPE_GESTIMUMV5 :
+			case self::$EXPORT_TYPE_GESTIMUMV5:
 				$this->exportGestimumV5($TData);
 				break;
-			case self::$EXPORT_TYPE_FEC :
+			case self::$EXPORT_TYPE_FEC:
 				$this->exportFEC($TData);
 				break;
-			case self::$EXPORT_TYPE_FEC2 :
+			case self::$EXPORT_TYPE_FEC2:
 				$this->exportFEC2($TData);
 				break;
 			default:
@@ -481,8 +481,9 @@ class AccountancyExport
 		$date_ecriture = dol_print_date(dol_now(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be yyyymmdd
 		foreach ($TData as $data) {
 			$code_compta = $data->numero_compte;
-			if (!empty($data->subledger_account))
+			if (!empty($data->subledger_account)) {
 				$code_compta = $data->subledger_account;
+			}
 
 			$Tab = array();
 			$Tab['num_ecriture'] = str_pad($i, 5);
@@ -522,8 +523,9 @@ class AccountancyExport
 		// $date_ecriture = dol_print_date(time(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy
 		foreach ($TData as $data) {
 			$code_compta = $data->numero_compte;
-			if (!empty($data->subledger_account))
+			if (!empty($data->subledger_account)) {
 				$code_compta = $data->subledger_account;
+			}
 
 			$Tab = array();
 			$Tab['type_ligne'] = 'M';
@@ -539,17 +541,17 @@ class AccountancyExport
 			$Tab['libelle_ecriture'] = str_pad(self::trunc(dol_string_unaccent($data->doc_ref).' '.dol_string_unaccent($data->label_operation), 20), 20);
 
 			// Credit invoice - invert sens
-            if ($data->montant < 0) {
-                if ($data->sens == 'C') {
-                    $Tab['sens'] = 'D';
-                } else {
-                    $Tab['sens'] = 'C';
-                }
-                $Tab['signe_montant'] = '-';
-            } else {
-                $Tab['sens'] = $data->sens; // C or D
-                $Tab['signe_montant'] = '+';
-            }
+			if ($data->montant < 0) {
+				if ($data->sens == 'C') {
+					$Tab['sens'] = 'D';
+				} else {
+					$Tab['sens'] = 'C';
+				}
+				$Tab['signe_montant'] = '-';
+			} else {
+				$Tab['sens'] = $data->sens; // C or D
+				$Tab['signe_montant'] = '+';
+			}
 
 			// The amount must be in centimes without decimal points.
 			$Tab['montant'] = str_pad(abs($data->montant * 100), 12, '0', STR_PAD_LEFT);
@@ -616,8 +618,9 @@ class AccountancyExport
 		//$date_ecriture = dol_print_date(time(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy
 		foreach ($TData as $data) {
 			$code_compta = $data->numero_compte;
-			if (!empty($data->subledger_account))
+			if (!empty($data->subledger_account)) {
 				$code_compta = $data->subledger_account;
+			}
 
 			$Tab = array();
 			//$Tab['type_ligne'] = 'M';
@@ -849,14 +852,14 @@ class AccountancyExport
 		print $end_line;
 
 		foreach ($objectLines as $line) {
-            if ($line->debit == 0 && $line->credit == 0) {
-                unset($array[$line]);
-            } else {
-                $date_creation = dol_print_date($line->date_creation, '%Y%m%d');
-                $date_document = dol_print_date($line->doc_date, '%Y%m%d');
-                $date_lettering = dol_print_date($line->date_lettering, '%Y%m%d');
-                $date_validation = dol_print_date($line->date_validated, '%Y%m%d');
-                $date_limit_payment = dol_print_date($line->date_lim_reglement, '%Y%m%d');
+			if ($line->debit == 0 && $line->credit == 0) {
+				unset($array[$line]);
+			} else {
+				$date_creation = dol_print_date($line->date_creation, '%Y%m%d');
+				$date_document = dol_print_date($line->doc_date, '%Y%m%d');
+				$date_lettering = dol_print_date($line->date_lettering, '%Y%m%d');
+				$date_validation = dol_print_date($line->date_validated, '%Y%m%d');
+				$date_limit_payment = dol_print_date($line->date_lim_reglement, '%Y%m%d');
 
 				// FEC:JournalCode
 				print $line->code_journal . $separator;
@@ -1048,21 +1051,17 @@ class AccountancyExport
 		$thisPieceNum = "";
 		$thisPieceAccountNr = "";
 		$aSize = count($objectLines);
-		foreach ($objectLines as $aIndex=>$line)
-		{
+		foreach ($objectLines as $aIndex => $line) {
 			$sammelBuchung = false;
-			if ($aIndex - 2 >= 0 && $objectLines[$aIndex - 2]->piece_num == $line->piece_num)
-			{
+			if ($aIndex - 2 >= 0 && $objectLines[$aIndex - 2]->piece_num == $line->piece_num) {
 				$sammelBuchung = true;
-			} elseif ($aIndex + 2 < $aSize && $objectLines[$aIndex + 2]->piece_num == $line->piece_num)
-			{
+			} elseif ($aIndex + 2 < $aSize && $objectLines[$aIndex + 2]->piece_num == $line->piece_num) {
 				$sammelBuchung = true;
 			} elseif ($aIndex + 1 < $aSize
 					&& $objectLines[$aIndex + 1]->piece_num == $line->piece_num
 					&& $aIndex - 1 < $aSize
 					&& $objectLines[$aIndex - 1]->piece_num == $line->piece_num
-					)
-			{
+					) {
 				$sammelBuchung = true;
 			}
 
@@ -1076,8 +1075,7 @@ class AccountancyExport
 			// Kto
 			print length_accountg($line->numero_compte).$this->separator;
 			// S/H
-			if ($line->sens == 'D')
-			{
+			if ($line->sens == 'D') {
 				print 'S'.$this->separator;
 			} else {
 				print 'H'.$this->separator;
@@ -1085,10 +1083,8 @@ class AccountancyExport
 			//Grp
 			print self::trunc($line->code_journal, 1).$this->separator;
 			// GKto
-			if (empty($line->code_tiers))
-			{
-				if ($line->piece_num == $thisPieceNum)
-				{
+			if (empty($line->code_tiers)) {
+				if ($line->piece_num == $thisPieceNum) {
 					print length_accounta($thisPieceAccountNr).$this->separator;
 				} else {
 					print "div".$this->separator;
@@ -1106,8 +1102,7 @@ class AccountancyExport
 			print "0".$this->separator;
 
 			//MTyp 1=Fibu Einzelbuchung 2=Sammebuchung
-			if ($sammelBuchung)
-			{
+			if ($sammelBuchung) {
 				print "2".$this->separator;
 			} else {
 				print "1".$this->separator;
@@ -1115,8 +1110,7 @@ class AccountancyExport
 			// Code
 			print '""'.$this->separator;
 			// Netto
-			if ($line->montant >= 0)
-			{
+			if ($line->montant >= 0) {
 				print $line->montant.$this->separator;
 			} else {
 				print ($line->montant * -1).$this->separator;
@@ -1127,18 +1121,15 @@ class AccountancyExport
 			print "0.00".$this->separator;
 			// Tx1
 			$line1 = self::toAnsi($line->label_compte, 29);
-			if ($line1 == "LIQ" || $line1 == "LIQ Beleg ok" || strlen($line1) <= 3)
-			{
+			if ($line1 == "LIQ" || $line1 == "LIQ Beleg ok" || strlen($line1) <= 3) {
 				$line1 = "";
 			}
 			$line2 = self::toAnsi($line->doc_ref, 29);
-			if (strlen($line1) == 0)
-			{
+			if (strlen($line1) == 0) {
 				$line1 = $line2;
 				$line2 = "";
 			}
-			if (strlen($line1) > 0 && strlen($line2) > 0 && (strlen($line1) + strlen($line2)) < 27)
-			{
+			if (strlen($line1) > 0 && strlen($line2) > 0 && (strlen($line1) + strlen($line2)) < 27) {
 				$line1 = $line1.' / '.$line2;
 				$line2 = "";
 			}
@@ -1156,8 +1147,7 @@ class AccountancyExport
 
 			print $this->end_line;
 
-			if ($line->piece_num !== $thisPieceNum)
-			{
+			if ($line->piece_num !== $thisPieceNum) {
 				$thisPieceNum = $line->piece_num;
 				$thisPieceAccountNr = $line->numero_compte;
 			}
@@ -1320,15 +1310,14 @@ class AccountancyExport
 				$sql .= " WHERE code_client = '".$this->db->escape($line->thirdparty_code)."'";
 				$resql = $this->db->query($sql);
 
-				if ($resql && $this->db->num_rows($resql) > 0)
-				{
+				if ($resql && $this->db->num_rows($resql) > 0) {
 					$soc = $this->db->fetch_object($resql);
 
 					$address = array('', '', '');
 					if (strpos($soc->address, "\n") !== false) {
 						$address = explode("\n", $soc->address);
 						if (is_array($address) && count($address) > 0) {
-							foreach ($address as $key=>$data) {
+							foreach ($address as $key => $data) {
 								$address[$key] = str_replace(array("\t", "\n", "\r"), "", $data);
 								$address[$key] = dol_trunc($address[$key], 40, 'right', 'UTF-8', 1);
 							}
@@ -1603,8 +1592,9 @@ class AccountancyExport
 
 			print self::trunc($line->code_journal, 6).$separator; //Journal code
 
-			if (!empty($line->subledger_account)) $account = $line->subledger_account;
-			else {
+			if (!empty($line->subledger_account)) {
+				$account = $line->subledger_account;
+			} else {
 				$account = $line->numero_compte;
 			}
 			print self::trunc($account, 15).$separator; //Account number
@@ -1785,8 +1775,7 @@ class AccountancyExport
 	public static function toAnsi($str, $size = -1)
 	{
 		$retVal = dol_string_nohtmltag($str, 1, 'Windows-1251');
-		if ($retVal >= 0 && $size >= 0)
-		{
+		if ($retVal >= 0 && $size >= 0) {
 			$retVal = mb_substr($retVal, 0, $size, 'Windows-1251');
 		}
 		return $retVal;

+ 1 - 2
htdocs/accountancy/class/accountancysystem.class.php

@@ -95,8 +95,7 @@ class AccountancySystem
 	{
 		global $conf;
 
-		if ($rowid > 0 || $ref)
-		{
+		if ($rowid > 0 || $ref) {
 			$sql  = "SELECT a.rowid, a.pcg_version, a.label, a.active";
 			$sql .= " FROM ".MAIN_DB_PREFIX."accounting_system as a";
 			$sql .= " WHERE";

+ 81 - 53
htdocs/accountancy/class/accountingaccount.class.php

@@ -236,19 +236,23 @@ class AccountingAccount extends CommonObject
 		$now = dol_now();
 
 		// Clean parameters
-		if (isset($this->fk_pcg_version))
+		if (isset($this->fk_pcg_version)) {
 			$this->fk_pcg_version = trim($this->fk_pcg_version);
-		if (isset($this->pcg_type))
+		}
+		if (isset($this->pcg_type)) {
 			$this->pcg_type = trim($this->pcg_type);
-		if (isset($this->account_number))
+		}
+		if (isset($this->account_number)) {
 			$this->account_number = trim($this->account_number);
-		if (isset($this->label))
+		}
+		if (isset($this->label)) {
 			$this->label = trim($this->label);
-		if (isset($this->labelshort))
+		}
+		if (isset($this->labelshort)) {
 			$this->labelshort = trim($this->labelshort);
+		}
 
-		if (empty($this->pcg_type) || $this->pcg_type == '-1')
-		{
+		if (empty($this->pcg_type) || $this->pcg_type == '-1') {
 			$this->pcg_type = 'XXXXXX';
 		}
 		// Check parameters
@@ -329,8 +333,7 @@ class AccountingAccount extends CommonObject
 	public function update($user)
 	{
 		// Check parameters
-		if (empty($this->pcg_type) || $this->pcg_type == '-1')
-		{
+		if (empty($this->pcg_type) || $this->pcg_type == '-1') {
 			$this->pcg_type = 'XXXXXX';
 		}
 
@@ -456,7 +459,9 @@ class AccountingAccount extends CommonObject
 		global $langs, $conf;
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
 
-		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
+		if (!empty($conf->dol_no_mouse_hover)) {
+			$notooltip = 1; // Force disable tooltips
+		}
 
 		$result = '';
 
@@ -474,31 +479,36 @@ class AccountingAccount extends CommonObject
 
 		// Add param to save lastsearch_values or not
 		$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
-		if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
-		if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+		if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+			$add_save_lastsearch_values = 1;
+		}
+		if ($add_save_lastsearch_values) {
+			$url .= '&save_lastsearch_values=1';
+		}
 
 		$picto = 'billr';
 		$label = '';
 
-		if (empty($this->labelshort) || $withcompletelabel == 1)
-		{
+		if (empty($this->labelshort) || $withcompletelabel == 1) {
 			$labeltoshow = $this->label;
 		} else {
 			$labeltoshow = $this->labelshort;
 		}
 
 		$label = '<u>'.$labelurl.'</u>';
-		if (!empty($this->account_number))
+		if (!empty($this->account_number)) {
 			$label .= '<br><b>'.$langs->trans('AccountAccounting').':</b> '.length_accountg($this->account_number);
-		if (!empty($labeltoshow))
+		}
+		if (!empty($labeltoshow)) {
 			$label .= '<br><b>'.$langs->trans('Label').':</b> '.$labeltoshow;
-		if ($moretitle) $label .= ' - '.$moretitle;
+		}
+		if ($moretitle) {
+			$label .= ' - '.$moretitle;
+		}
 
 		$linkclose = '';
-		if (empty($notooltip))
-		{
-			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
-			{
+		if (empty($notooltip)) {
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
 				$label = $labelurl;
 				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
 			}
@@ -510,19 +520,26 @@ class AccountingAccount extends CommonObject
 		$linkstart .= $linkclose.'>';
 		$linkend = '</a>';
 
-		if ($nourl)
-		{
+		if ($nourl) {
 			$linkstart = '';
 			$linkclose = '';
 			$linkend = '';
 		}
 
 		$label_link = length_accountg($this->account_number);
-		if ($withlabel) $label_link .= ' - '.($nourl ? '<span class="opacitymedium">' : '').$labeltoshow.($nourl ? '</span>' : '');
+		if ($withlabel) {
+			$label_link .= ' - '.($nourl ? '<span class="opacitymedium">' : '').$labeltoshow.($nourl ? '</span>' : '');
+		}
 
-		if ($withpicto) $result .= ($linkstart.img_object(($notooltip ? '' : $label), $picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
-		if ($withpicto && $withpicto != 2) $result .= ' ';
-		if ($withpicto != 2) $result .= $linkstart.$label_link.$linkend;
+		if ($withpicto) {
+			$result .= ($linkstart.img_object(($notooltip ? '' : $label), $picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
+		}
+		if ($withpicto && $withpicto != 2) {
+			$result .= ' ';
+		}
+		if ($withpicto != 2) {
+			$result .= $linkstart.$label_link.$linkend;
+		}
 		return $result;
 	}
 
@@ -576,8 +593,7 @@ class AccountingAccount extends CommonObject
 		$result = $this->checkUsage();
 
 		$fieldtouse = 'active';
-		if ($mode == 1)
-		{
+		if ($mode == 1) {
 			$fieldtouse = 'reconcilable';
 		}
 
@@ -664,30 +680,42 @@ class AccountingAccount extends CommonObject
 		global $langs;
 		$langs->loadLangs(array("users"));
 
-		if ($mode == 0)
-		{
-			if ($status == 1) return $langs->trans('Enabled');
-			elseif ($status == 0) return $langs->trans('Disabled');
-		} elseif ($mode == 1)
-		{
-			if ($status == 1) return $langs->trans('Enabled');
-			elseif ($status == 0) return $langs->trans('Disabled');
-		} elseif ($mode == 2)
-		{
-			if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled');
-			elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled');
-		} elseif ($mode == 3)
-		{
-			if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4');
-			elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5');
-		} elseif ($mode == 4)
-		{
-			if ($status == 1) return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled');
-			elseif ($status == 0) return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled');
-		} elseif ($mode == 5)
-		{
-			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4');
-			elseif ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5');
+		if ($mode == 0) {
+			if ($status == 1) {
+				return $langs->trans('Enabled');
+			} elseif ($status == 0) {
+				return $langs->trans('Disabled');
+			}
+		} elseif ($mode == 1) {
+			if ($status == 1) {
+				return $langs->trans('Enabled');
+			} elseif ($status == 0) {
+				return $langs->trans('Disabled');
+			}
+		} elseif ($mode == 2) {
+			if ($status == 1) {
+				return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled');
+			} elseif ($status == 0) {
+				return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled');
+			}
+		} elseif ($mode == 3) {
+			if ($status == 1) {
+				return img_picto($langs->trans('Enabled'), 'statut4');
+			} elseif ($status == 0) {
+				return img_picto($langs->trans('Disabled'), 'statut5');
+			}
+		} elseif ($mode == 4) {
+			if ($status == 1) {
+				return img_picto($langs->trans('Enabled'), 'statut4').' '.$langs->trans('Enabled');
+			} elseif ($status == 0) {
+				return img_picto($langs->trans('Disabled'), 'statut5').' '.$langs->trans('Disabled');
+			}
+		} elseif ($mode == 5) {
+			if ($status == 1) {
+				return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'), 'statut4');
+			} elseif ($status == 0) {
+				return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'), 'statut5');
+			}
 		}
 	}
 }

+ 53 - 35
htdocs/accountancy/class/accountingjournal.class.php

@@ -102,23 +102,20 @@ class AccountingJournal extends CommonObject
 	{
 		global $conf;
 
-		if ($rowid || $journal_code)
-		{
+		if ($rowid || $journal_code) {
 			$sql = "SELECT rowid, code, label, nature, active";
 			$sql .= " FROM ".MAIN_DB_PREFIX."accounting_journal";
 			$sql .= " WHERE";
 			if ($rowid) {
 				$sql .= " rowid = ".((int) $rowid);
-			} elseif ($journal_code)
-			{
+			} elseif ($journal_code) {
 				$sql .= " code = '".$this->db->escape($journal_code)."'";
 				$sql .= " AND entity  = ".$conf->entity;
 			}
 
 			dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
 			$result = $this->db->query($sql);
-			if ($result)
-			{
+			if ($result) {
 				$obj = $this->db->fetch_object($result);
 
 				if ($obj) {
@@ -226,24 +223,28 @@ class AccountingJournal extends CommonObject
 	{
 		global $langs, $conf, $user;
 
-		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
+		if (!empty($conf->dol_no_mouse_hover)) {
+			$notooltip = 1; // Force disable tooltips
+		}
 
 		$result = '';
 
 		$url = DOL_URL_ROOT.'/accountancy/admin/journals_list.php?id=35';
 
 		$label = '<u>'.$langs->trans("ShowAccountingJournal").'</u>';
-		if (!empty($this->code))
+		if (!empty($this->code)) {
 			$label .= '<br><b>'.$langs->trans('Code').':</b> '.$this->code;
-		if (!empty($this->label))
+		}
+		if (!empty($this->label)) {
 			$label .= '<br><b>'.$langs->trans('Label').':</b> '.$langs->transnoentities($this->label);
-		if ($moretitle) $label .= ' - '.$moretitle;
+		}
+		if ($moretitle) {
+			$label .= ' - '.$moretitle;
+		}
 
 		$linkclose = '';
-		if (empty($notooltip))
-		{
-			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
-			{
+		if (empty($notooltip)) {
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
 				$label = $langs->trans("ShowAccountingJournal");
 				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
 			}
@@ -255,19 +256,24 @@ class AccountingJournal extends CommonObject
 		$linkstart .= $linkclose.'>';
 		$linkend = '</a>';
 
-		if ($nourl)
-		{
+		if ($nourl) {
 			$linkstart = '';
 			$linkclose = '';
 			$linkend = '';
 		}
 
 		$label_link = $this->code;
-		if ($withlabel) $label_link .= ' - '.($nourl ? '<span class="opacitymedium">' : '').$langs->transnoentities($this->label).($nourl ? '</span>' : '');
+		if ($withlabel) {
+			$label_link .= ' - '.($nourl ? '<span class="opacitymedium">' : '').$langs->transnoentities($this->label).($nourl ? '</span>' : '');
+		}
 
 		$result .= $linkstart;
-		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
-		if ($withpicto != 2) $result .= $label_link;
+		if ($withpicto) {
+			$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+		}
+		if ($withpicto != 2) {
+			$result .= $label_link;
+		}
 		$result .= $linkend;
 
 		return $result;
@@ -299,23 +305,35 @@ class AccountingJournal extends CommonObject
 
 		$langs->loadLangs(array("accountancy"));
 
-		if ($mode == 0)
-		{
+		if ($mode == 0) {
 			$prefix = '';
-			if ($nature == 9) return $langs->trans('AccountingJournalType9');
-			elseif ($nature == 5) return $langs->trans('AccountingJournalType5');
-			elseif ($nature == 4) return $langs->trans('AccountingJournalType4');
-			elseif ($nature == 3) return $langs->trans('AccountingJournalType3');
-			elseif ($nature == 2) return $langs->trans('AccountingJournalType2');
-			elseif ($nature == 1) return $langs->trans('AccountingJournalType1');
-		} elseif ($mode == 1)
-		{
-			if ($nature == 9) return $langs->trans('AccountingJournalType9');
-			elseif ($nature == 5) return $langs->trans('AccountingJournalType5');
-			elseif ($nature == 4) return $langs->trans('AccountingJournalType4');
-			elseif ($nature == 3) return $langs->trans('AccountingJournalType3');
-			elseif ($nature == 2) return $langs->trans('AccountingJournalType2');
-			elseif ($nature == 1) return $langs->trans('AccountingJournalType1');
+			if ($nature == 9) {
+				return $langs->trans('AccountingJournalType9');
+			} elseif ($nature == 5) {
+				return $langs->trans('AccountingJournalType5');
+			} elseif ($nature == 4) {
+				return $langs->trans('AccountingJournalType4');
+			} elseif ($nature == 3) {
+				return $langs->trans('AccountingJournalType3');
+			} elseif ($nature == 2) {
+				return $langs->trans('AccountingJournalType2');
+			} elseif ($nature == 1) {
+				return $langs->trans('AccountingJournalType1');
+			}
+		} elseif ($mode == 1) {
+			if ($nature == 9) {
+				return $langs->trans('AccountingJournalType9');
+			} elseif ($nature == 5) {
+				return $langs->trans('AccountingJournalType5');
+			} elseif ($nature == 4) {
+				return $langs->trans('AccountingJournalType4');
+			} elseif ($nature == 3) {
+				return $langs->trans('AccountingJournalType3');
+			} elseif ($nature == 2) {
+				return $langs->trans('AccountingJournalType2');
+			} elseif ($nature == 1) {
+				return $langs->trans('AccountingJournalType1');
+			}
 		}
 	}
 }

+ 60 - 47
htdocs/accountancy/class/bookkeeping.class.php

@@ -254,21 +254,22 @@ class BookKeeping extends CommonObject
 		if (isset($this->piece_num)) {
 			$this->piece_num = trim($this->piece_num);
 		}
-		if (empty($this->debit)) $this->debit = 0.0;
-		if (empty($this->credit)) $this->credit = 0.0;
+		if (empty($this->debit)) {
+			$this->debit = 0.0;
+		}
+		if (empty($this->credit)) {
+			$this->credit = 0.0;
+		}
 
 		// Check parameters
-		if (($this->numero_compte == "") || $this->numero_compte == '-1' || $this->numero_compte == 'NotDefined')
-		{
+		if (($this->numero_compte == "") || $this->numero_compte == '-1' || $this->numero_compte == 'NotDefined') {
 			$langs->loadLangs(array("errors"));
-			if (in_array($this->doc_type, array('bank', 'expense_report')))
-			{
+			if (in_array($this->doc_type, array('bank', 'expense_report'))) {
 				$this->errors[] = $langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet, $this->doc_type);
 			} else {
 				//$this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForInvoiceLine', $this->doc_ref,  $this->label_compte);
 				$mesg = $this->doc_ref.', '.$langs->trans("AccountAccounting").': '.$this->numero_compte;
-				if ($this->subledger_account && $this->subledger_account != $this->numero_compte)
-				{
+				if ($this->subledger_account && $this->subledger_account != $this->numero_compte) {
 					$mesg .= ', '.$langs->trans("SubledgerAccount").': '.$this->subledger_account;
 				}
 				$this->errors[] = $langs->trans('ErrorFieldAccountNotDefinedForLine', $mesg);
@@ -299,8 +300,7 @@ class BookKeeping extends CommonObject
 
 		if ($resql) {
 			$row = $this->db->fetch_object($resql);
-			if ($row->nb == 0)
-			{
+			if ($row->nb == 0) {
 				// Determine piece_num
 				$sqlnum = "SELECT piece_num";
 				$sqlnum .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
@@ -452,7 +452,9 @@ class BookKeeping extends CommonObject
 		global $dolibarr_main_authentication, $dolibarr_main_demo;
 		global $menumanager;
 
-		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
+		if (!empty($conf->dol_no_mouse_hover)) {
+			$notooltip = 1; // Force disable tooltips
+		}
 
 		$result = '';
 		$companylink = '';
@@ -463,33 +465,40 @@ class BookKeeping extends CommonObject
 
 		$url = DOL_URL_ROOT.'/accountancy/bookkeeping/card.php?piece_num='.$this->piece_num;
 
-		if ($option != 'nolink')
-		{
+		if ($option != 'nolink') {
 			// Add param to save lastsearch_values or not
 			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
-			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
-			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+				$add_save_lastsearch_values = 1;
+			}
+			if ($add_save_lastsearch_values) {
+				$url .= '&save_lastsearch_values=1';
+			}
 		}
 
 		$linkclose = '';
-		if (empty($notooltip))
-		{
-			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
-			{
+		if (empty($notooltip)) {
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
 				$label = $langs->trans("ShowTransaction");
 				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
 			}
 			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
 			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
-		} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+		} else {
+			$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+		}
 
 		$linkstart = '<a href="'.$url.'"';
 		$linkstart .= $linkclose.'>';
 		$linkend = '</a>';
 
 		$result .= $linkstart;
-		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
-		if ($withpicto != 2) $result .= $this->piece_num;
+		if ($withpicto) {
+			$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+		}
+		if ($withpicto != 2) {
+			$result .= $this->piece_num;
+		}
 		$result .= $linkend;
 		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
 
@@ -569,8 +578,12 @@ class BookKeeping extends CommonObject
 		if (isset($this->piece_num)) {
 			$this->piece_num = trim($this->piece_num);
 		}
-		if (empty($this->debit)) $this->debit = 0;
-		if (empty($this->credit)) $this->credit = 0;
+		if (empty($this->debit)) {
+			$this->debit = 0;
+		}
+		if (empty($this->credit)) {
+			$this->credit = 0;
+		}
 
 		$this->debit = price2num($this->debit, 'MT');
 		$this->credit = price2num($this->credit, 'MT');
@@ -828,14 +841,14 @@ class BookKeeping extends CommonObject
 					$sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
 				} elseif ($key == 't.credit' || $key == 't.debit') {
 					$sqlwhere[] = natural_search($key, $value, 1, 1);
-                } elseif ($key == 't.reconciled_option') {
-                    $sqlwhere[] = 't.lettering_code IS NULL';
-                } elseif ($key == 't.code_journal' && !empty($value)) {
-                	if (is_array($value)) {
-                		$sqlwhere[] = natural_search("t.code_journal", join(',', $value), 3, 1);
-                	} else {
-                    	$sqlwhere[] = natural_search("t.code_journal", $value, 3, 1);
-                	}
+				} elseif ($key == 't.reconciled_option') {
+					$sqlwhere[] = 't.lettering_code IS NULL';
+				} elseif ($key == 't.code_journal' && !empty($value)) {
+					if (is_array($value)) {
+						$sqlwhere[] = natural_search("t.code_journal", join(',', $value), 3, 1);
+					} else {
+						$sqlwhere[] = natural_search("t.code_journal", $value, 3, 1);
+					}
 				} else {
 					$sqlwhere[] = natural_search($key, $value, 0, 1);
 				}
@@ -1009,8 +1022,7 @@ class BookKeeping extends CommonObject
 			$num = $this->db->num_rows($resql);
 
 			$i = 0;
-			while (($obj = $this->db->fetch_object($resql)) && (empty($limit) || $i < min($limit, $num)))
-			{
+			while (($obj = $this->db->fetch_object($resql)) && (empty($limit) || $i < min($limit, $num))) {
 				$line = new BookKeepingLine();
 
 				$line->id = $obj->rowid;
@@ -1118,13 +1130,11 @@ class BookKeeping extends CommonObject
 		}
 
 		$resql = $this->db->query($sql);
-		if ($resql)
-		{
+		if ($resql) {
 			$num = $this->db->num_rows($resql);
 
 			$i = 0;
-			while (($obj = $this->db->fetch_object($resql)) && (empty($limit) || $i < min($limit, $num)))
-			{
+			while (($obj = $this->db->fetch_object($resql)) && (empty($limit) || $i < min($limit, $num))) {
 				$line = new BookKeepingLine();
 
 				$line->numero_compte = $obj->numero_compte;
@@ -1404,13 +1414,11 @@ class BookKeeping extends CommonObject
 	{
 		global $langs;
 
-		if (empty($delyear) && empty($journal))
-		{
+		if (empty($delyear) && empty($journal)) {
 			$this->error = 'ErrorOneFieldRequired';
 			return -1;
 		}
-		if (!empty($delmonth) && empty($delyear))
-		{
+		if (!empty($delmonth) && empty($delyear)) {
 			$this->error = 'YearRequiredIfMonthDefined';
 			return -2;
 		}
@@ -1422,7 +1430,9 @@ class BookKeeping extends CommonObject
 		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
 		$sql .= " WHERE 1 = 1";
 		$sql .= dolSqlDateFilter('doc_date', 0, $delmonth, $delyear);
-		if (!empty($journal)) $sql .= " AND code_journal = '".$this->db->escape($journal)."'";
+		if (!empty($journal)) {
+			$sql .= " AND code_journal = '".$this->db->escape($journal)."'";
+		}
 		$sql .= " AND entity IN (".getEntity('accountancy').")";
 
 		// TODO: In a future we must forbid deletion if record is inside a closed fiscal period.
@@ -1617,8 +1627,12 @@ class BookKeeping extends CommonObject
 
 		if ($result) {
 			$obj = $this->db->fetch_object($result);
-			if ($obj) $result = $obj->max;
-			if (empty($result)) $result = 1;
+			if ($obj) {
+				$result = $obj->max;
+			}
+			if (empty($result)) {
+				$result = 1;
+			}
 			return $result;
 		} else {
 			$this->error = "Error ".$this->db->lasterror();
@@ -1760,8 +1774,7 @@ class BookKeeping extends CommonObject
 
 		$this->db->begin();
 
-		if ($direction == 0)
-		{
+		if ($direction == 0) {
 			$next_piecenum = $this->getNextNumMvt();
 			$now = dol_now();
 

+ 10 - 8
htdocs/accountancy/class/lettering.class.php

@@ -67,12 +67,15 @@ class Lettering extends BookKeeping
 		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as bk";
 		$sql .= " LEFT JOIN  ".MAIN_DB_PREFIX."bank_url as bu ON(bk.fk_doc = bu.fk_bank AND bu.type IN ('payment', 'payment_supplier') ) ";
 		$sql .= " WHERE ( ";
-		if ($object->code_compta != "")
+		if ($object->code_compta != "") {
 			$sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."'  ";
-		if ($object->code_compta != "" && $object->code_compta_fournisseur != "")
+		}
+		if ($object->code_compta != "" && $object->code_compta_fournisseur != "") {
 			$sql .= " OR ";
-		if ($object->code_compta_fournisseur != "")
+		}
+		if ($object->code_compta_fournisseur != "") {
 			$sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
+		}
 
 		$sql .= " ) AND (bk.date_lettering ='' OR bk.date_lettering IS NULL) ";
 		$sql .= "  AND (bk.lettering_code != '' OR bk.lettering_code IS NULL) ";
@@ -89,8 +92,7 @@ class Lettering extends BookKeeping
 				$ids = array();
 				$ids_fact = array();
 
-				if ($obj->type == 'payment_supplier')
-				{
+				if ($obj->type == 'payment_supplier') {
 					$sql = 'SELECT DISTINCT bk.rowid, facf.ref, facf.ref_supplier, payf.fk_bank, facf.rowid as fact_id';
 					$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn facf ";
 					$sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfacf ON  payfacf.fk_facturefourn=facf.rowid";
@@ -244,8 +246,9 @@ class Lettering extends BookKeeping
 		if ($result) {
 			$obj = $this->db->fetch_object($result);
 			$lettre = (empty($obj->lettering_code) ? 'AAA' : $obj->lettering_code);
-			if (!empty($obj->lettering_code))
+			if (!empty($obj->lettering_code)) {
 				$lettre++;
+			}
 		} else {
 			$this->errors[] = 'Error'.$this->db->lasterror();
 			$error++;
@@ -269,8 +272,7 @@ class Lettering extends BookKeeping
 
 		$now = dol_now();
 
-		if (!$error)
-		{
+		if (!$error) {
 			$sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET";
 			$sql .= " lettering_code='".$this->db->escape($lettre)."'";
 			$sql .= " , date_lettering = '".$this->db->idate($now)."'"; // todo correct date it's false

+ 23 - 20
htdocs/accountancy/closure/index.php

@@ -39,23 +39,27 @@ $action = GETPOST('action', 'aZ09');
 if (empty($conf->accounting->enabled)) {
 	accessforbidden();
 }
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->fiscalyear->write)
+}
+if (!$user->rights->accounting->fiscalyear->write) {
 	accessforbidden();
+}
 
 $object = new BookKeeping($db);
 
 $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
-if (GETPOST("year", 'int')) $year_start = GETPOST("year", 'int');
-else {
+if (GETPOST("year", 'int')) {
+	$year_start = GETPOST("year", 'int');
+} else {
 	$year_start = dol_print_date(dol_now(), '%Y');
-	if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year
+	if (dol_print_date(dol_now(), '%m') < $month_start) {
+		$year_start--; // If current month is lower that starting fiscal month, we start last year
+	}
 }
 $year_end = $year_start + 1;
 $month_end = $month_start - 1;
-if ($month_end < 1)
-{
+if ($month_end < 1) {
 	$month_end = 12;
 	$year_end--;
 }
@@ -69,8 +73,7 @@ $year_current = $year_start;
 if ($action == 'validate_movements_confirm' && $user->rights->accounting->fiscalyear->write) {
 	$result = $object->fetchAll();
 
-	if ($result < 0)
-	{
+	if ($result < 0) {
 		setEventMessages($object->error, $object->errors, 'errors');
 	} else {
 		// Specify as export : update field date_validated on selected month/year
@@ -80,30 +83,26 @@ if ($action == 'validate_movements_confirm' && $user->rights->accounting->fiscal
 		$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'));
 
-		if (is_array($object->lines))
-		{
-			foreach ($object->lines as $movement)
-			{
+		if (is_array($object->lines)) {
+			foreach ($object->lines as $movement) {
 				$now = dol_now();
 
 				$sql = " UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping";
 				$sql .= " SET date_validated = '".$db->idate($now)."'";
 				$sql .= " WHERE rowid = ".$movement->id;
 				$sql .= " AND doc_date >= '" . dol_print_date($date_start, 'dayrfc') . "'";
-                $sql .= " AND doc_date <= '" . dol_print_date($date_end, 'dayrfc') . "'";
+				$sql .= " AND doc_date <= '" . dol_print_date($date_end, 'dayrfc') . "'";
 
 				dol_syslog("/accountancy/closure/index.php :: Function validate_movement_confirm Specify movements as validated sql=".$sql, LOG_DEBUG);
 				$result = $db->query($sql);
-				if (!$result)
-				{
+				if (!$result) {
 					$error++;
 					break;
 				}
 			}
 		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			$db->commit();
 			setEventMessages($langs->trans("AllMovementsWereRecordedAsValidated"), null, 'mesgs');
 		} else {
@@ -171,7 +170,9 @@ print '<div class="div-table-responsive-no-min">';
 print '<table class="noborder centpercent">';
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 }
 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -179,7 +180,9 @@ print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>'
 $sql = "SELECT COUNT(b.rowid) as detail,";
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	$sql .= "  SUM(".$db->ifsql('MONTH(b.doc_date)='.$j, '1', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 }
 $sql .= " COUNT(b.rowid) as total";

+ 8 - 8
htdocs/accountancy/customer/card.php

@@ -38,19 +38,20 @@ $codeventil = GETPOST('codeventil', 'int');
 $id = GETPOST('id', 'int');
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
+}
 
 
 /*
  * Actions
  */
 
-if ($action == 'ventil' && $user->rights->accounting->bind->write)
-{
-	if (!$cancel)
-	{
-		if ($codeventil < 0) $codeventil = 0;
+if ($action == 'ventil' && $user->rights->accounting->bind->write) {
+	if (!$cancel) {
+		if ($codeventil < 0) {
+			$codeventil = 0;
+		}
 
 		$sql = " UPDATE ".MAIN_DB_PREFIX."facturedet";
 		$sql .= " SET fk_code_ventilation = ".$codeventil;
@@ -61,8 +62,7 @@ if ($action == 'ventil' && $user->rights->accounting->bind->write)
 			setEventMessages($db->lasterror(), null, 'errors');
 		} else {
 			setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
-			if ($backtopage)
-			{
+			if ($backtopage) {
 				header("Location: ".$backtopage);
 				exit();
 			}

+ 56 - 37
htdocs/accountancy/customer/index.php

@@ -39,22 +39,26 @@ $langs->loadLangs(array("compta", "bills", "other", "main", "accountancy"));
 if (empty($conf->accounting->enabled)) {
 	accessforbidden();
 }
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->bind->write)
+}
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 
 $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
-if (GETPOST("year", 'int')) $year_start = GETPOST("year", 'int');
-else {
+if (GETPOST("year", 'int')) {
+	$year_start = GETPOST("year", 'int');
+} else {
 	$year_start = dol_print_date(dol_now(), '%Y');
-	if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year
+	if (dol_print_date(dol_now(), '%m') < $month_start) {
+		$year_start--; // If current month is lower that starting fiscal month, we start last year
+	}
 }
 $year_end = $year_start + 1;
 $month_end = $month_start - 1;
-if ($month_end < 1)
-{
+if ($month_end < 1) {
 	$month_end = 12;
 	$year_end--;
 }
@@ -72,8 +76,7 @@ $chartaccountcode = dol_getIdFromCode($db, $conf->global->CHARTOFACCOUNTS, 'acco
  * Actions
  */
 
-if ($action == 'clean' || $action == 'validatehistory')
-{
+if ($action == 'clean' || $action == 'validatehistory') {
 	// Clean database
 	$db->begin();
 	$sql1 = "UPDATE ".MAIN_DB_PREFIX."facturedet as fd";
@@ -187,15 +190,13 @@ if ($action == 'validatehistory') {
 				$suggestedaccountingaccountfor = '';
 			}
 
-			if ($objp->aarowid_suggest > 0)
-			{
+			if ($objp->aarowid_suggest > 0) {
 				$sqlupdate = "UPDATE ".MAIN_DB_PREFIX."facturedet";
 				$sqlupdate .= " SET fk_code_ventilation = ".$objp->aarowid_suggest;
 				$sqlupdate .= " WHERE fk_code_ventilation <= 0 AND product_type <= 2 AND rowid = ".$objp->rowid;
 
 				$resqlupdate = $db->query($sqlupdate);
-				if (!$resqlupdate)
-				{
+				if (!$resqlupdate) {
 					$error++;
 					setEventMessages($db->lasterror(), null, 'errors');
 					break;
@@ -206,8 +207,7 @@ if ($action == 'validatehistory') {
 		}
 	}
 
-	if ($error)
-	{
+	if ($error) {
 		$db->rollback();
 	} else {
 		$db->commit();
@@ -246,7 +246,9 @@ print '<tr class="liste_titre"><td width="200">'.$langs->trans("Account").'</td>
 print '<td width="200" class="left">'.$langs->trans("Label").'</td>';
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 }
 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -255,7 +257,9 @@ $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account
 $sql .= "  ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	$sql .= "  SUM(".$db->ifsql('MONTH(f.datef)='.$j, 'fd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 }
 $sql .= "  SUM(fd.total_ht) as total";
@@ -286,16 +290,18 @@ if ($resql) {
 
 	while ($row = $db->fetch_row($resql)) {
 		print '<tr class="oddeven"><td>';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("Unknown");
-		} else print length_accountg($row[0]);
+		} else {
+			print length_accountg($row[0]);
+		}
 		print '</td>';
 		print '<td class="left">';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/customer/list.php?search_year='.$y, $langs->transnoentitiesnoconv("ToBind"));
-		} else print $row[1];
+		} else {
+			print $row[1];
+		}
 		print '</td>';
 		for ($i = 2; $i <= 12; $i++) {
 			print '<td class="nowrap right">'.price($row[$i]).'</td>';
@@ -324,7 +330,9 @@ print '<tr class="liste_titre"><td width="200">'.$langs->trans("Account").'</td>
 print '<td width="200" class="left">'.$langs->trans("Label").'</td>';
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 }
 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -333,7 +341,9 @@ $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account
 $sql .= "  ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	$sql .= "  SUM(".$db->ifsql('MONTH(f.datef)='.$j, 'fd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 }
 $sql .= "  SUM(fd.total_ht) as total";
@@ -364,17 +374,19 @@ if ($resql) {
 
 	while ($row = $db->fetch_row($resql)) {
 		print '<tr class="oddeven"><td>';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("Unknown");
-		} else print length_accountg($row[0]);
+		} else {
+			print length_accountg($row[0]);
+		}
 		print '</td>';
 
 		print '<td class="left">';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/customer/list.php?search_year='.$y, $langs->transnoentitiesnoconv("ToBind"));
-		} else print $row[1];
+		} else {
+			print $row[1];
+		}
 		print '</td>';
 
 		for ($i = 2; $i <= 12; $i++) {
@@ -392,8 +404,7 @@ print "</table>\n";
 print '</div>';
 
 
-if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. Why showing a report that should rely on result of this step ?
-{
+if ($conf->global->MAIN_FEATURES_LEVEL > 0) { // This part of code looks strange. Why showing a report that should rely on result of this step ?
 	print '<br>';
 	print '<br>';
 
@@ -405,7 +416,9 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange.
 	print '<tr class="liste_titre"><td width="400" class="left">'.$langs->trans("TotalVente").'</td>';
 	for ($i = 1; $i <= 12; $i++) {
 		$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-		if ($j > 12) $j -= 12;
+		if ($j > 12) {
+			$j -= 12;
+		}
 		print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 	}
 	print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -413,7 +426,9 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange.
 	$sql = "SELECT '".$db->escape($langs->trans("TotalVente"))."' AS total,";
 	for ($i = 1; $i <= 12; $i++) {
 		$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-		if ($j > 12) $j -= 12;
+		if ($j > 12) {
+			$j -= 12;
+		}
 		$sql .= "  SUM(".$db->ifsql('MONTH(f.datef)='.$j, 'fd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 	}
 	$sql .= "  SUM(fd.total_ht) as total";
@@ -462,7 +477,9 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange.
 		print '<tr class="liste_titre"><td width="400">'.$langs->trans("TotalMarge").'</td>';
 		for ($i = 1; $i <= 12; $i++) {
 			$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-			if ($j > 12) $j -= 12;
+			if ($j > 12) {
+				$j -= 12;
+			}
 			print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 		}
 		print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -470,7 +487,9 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange.
 		$sql = "SELECT '".$db->escape($langs->trans("Vide"))."' AS marge,";
 		for ($i = 1; $i <= 12; $i++) {
 			$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-			if ($j > 12) $j -= 12;
+			if ($j > 12) {
+				$j -= 12;
+			}
 			$sql .= "  SUM(".$db->ifsql('MONTH(f.datef)='.$j, '(fd.total_ht-(fd.qty * fd.buy_price_ht))', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 		}
 		$sql .= "  SUM((fd.total_ht-(fd.qty * fd.buy_price_ht))) as total";

+ 86 - 44
htdocs/accountancy/customer/lines.php

@@ -64,12 +64,15 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0) $page = 0;
+if (empty($page) || $page < 0) {
+	$page = 0;
+}
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield)
+if (!$sortfield) {
 	$sortfield = "f.datef, f.ref, fd.rowid";
+}
 if (!$sortorder) {
 	if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE > 0) {
 		$sortorder = "DESC";
@@ -77,10 +80,12 @@ if (!$sortorder) {
 }
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->bind->write)
+}
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 $formaccounting = new FormAccounting($db);
 
@@ -90,8 +95,7 @@ $formaccounting = new FormAccounting($db);
  */
 
 // Purge search criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 	$search_societe = '';
 	$search_lineid = '';
 	$search_ref = '';
@@ -111,14 +115,12 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
 if (is_array($changeaccount) && count($changeaccount) > 0) {
 	$error = 0;
 
-	if (!(GETPOST('account_parent', 'int') >= 0))
-	{
+	if (!(GETPOST('account_parent', 'int') >= 0)) {
 		$error++;
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Account")), null, 'errors');
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		$db->begin();
 
 		$sql1 = "UPDATE ".MAIN_DB_PREFIX."facturedet as l";
@@ -231,16 +233,23 @@ $sql .= dolSqlDateFilter('f.datef', $search_day, $search_month, $search_year);
 if (strlen(trim($search_country))) {
 	$arrayofcode = getCountriesInEEC();
 	$country_code_in_EEC = $country_code_in_EEC_without_me = '';
-	foreach ($arrayofcode as $key => $value)
-	{
+	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 ($value != $mysoc->country_code) {
+			$country_code_in_EEC_without_me .= ($country_code_in_EEC_without_me ? "," : "")."'".$value."'";
+		}
+	}
+	if ($search_country == 'special_allnotme') {
+		$sql .= " AND co.code <> '".$db->escape($mysoc->country_code)."'";
+	} elseif ($search_country == 'special_eec') {
+		$sql .= " AND co.code IN (".$country_code_in_EEC.")";
+	} elseif ($search_country == 'special_eecnotme') {
+		$sql .= " AND co.code IN (".$country_code_in_EEC_without_me.")";
+	} elseif ($search_country == 'special_noteec') {
+		$sql .= " AND co.code NOT IN (".$country_code_in_EEC.")";
+	} else {
+		$sql .= natural_search("co.code", $search_country);
 	}
-	if ($search_country == 'special_allnotme')     $sql .= " AND co.code <> '".$db->escape($mysoc->country_code)."'";
-	elseif ($search_country == 'special_eec')      $sql .= " AND co.code IN (".$country_code_in_EEC.")";
-	elseif ($search_country == 'special_eecnotme') $sql .= " AND co.code IN (".$country_code_in_EEC_without_me.")";
-	elseif ($search_country == 'special_noteec')   $sql .= " AND co.code NOT IN (".$country_code_in_EEC.")";
-	else $sql .= natural_search("co.code", $search_country);
 }
 if (strlen(trim($search_tvaintra))) {
 	$sql .= natural_search("s.tva_intra", $search_tvaintra);
@@ -250,12 +259,10 @@ $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$result = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($result);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -270,24 +277,54 @@ if ($result) {
 	$i = 0;
 
 	$param = '';
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-	if ($search_societe)	$param .= "&search_societe=".urlencode($search_societe);
-	if ($search_invoice)	$param .= "&search_invoice=".urlencode($search_invoice);
-	if ($search_ref)		$param .= "&search_ref=".urlencode($search_ref);
-	if ($search_label)		$param .= "&search_label=".urlencode($search_label);
-	if ($search_desc)		$param .= "&search_desc=".urlencode($search_desc);
-	if ($search_account)	$param .= "&search_account=".urlencode($search_account);
-	if ($search_vat)		$param .= "&search_vat=".urlencode($search_vat);
-	if ($search_day)        $param .= '&search_day='.urlencode($search_day);
-	if ($search_month)      $param .= '&search_month='.urlencode($search_month);
-	if ($search_year)       $param .= '&search_year='.urlencode($search_year);
-	if ($search_country)  	$param .= "&search_country=".urlencode($search_country);
-	if ($search_tvaintra)	$param .= "&search_tvaintra=".urlencode($search_tvaintra);
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.urlencode($limit);
+	}
+	if ($search_societe) {
+		$param .= "&search_societe=".urlencode($search_societe);
+	}
+	if ($search_invoice) {
+		$param .= "&search_invoice=".urlencode($search_invoice);
+	}
+	if ($search_ref) {
+		$param .= "&search_ref=".urlencode($search_ref);
+	}
+	if ($search_label) {
+		$param .= "&search_label=".urlencode($search_label);
+	}
+	if ($search_desc) {
+		$param .= "&search_desc=".urlencode($search_desc);
+	}
+	if ($search_account) {
+		$param .= "&search_account=".urlencode($search_account);
+	}
+	if ($search_vat) {
+		$param .= "&search_vat=".urlencode($search_vat);
+	}
+	if ($search_day) {
+		$param .= '&search_day='.urlencode($search_day);
+	}
+	if ($search_month) {
+		$param .= '&search_month='.urlencode($search_month);
+	}
+	if ($search_year) {
+		$param .= '&search_year='.urlencode($search_year);
+	}
+	if ($search_country) {
+		$param .= "&search_country=".urlencode($search_country);
+	}
+	if ($search_tvaintra) {
+		$param .= "&search_tvaintra=".urlencode($search_tvaintra);
+	}
 
 	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'."\n";
 	print '<input type="hidden" name="action" value="ventil">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
@@ -313,8 +350,8 @@ if ($result) {
 	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) {
 		print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.dol_escape_htmltag($search_day).'">';
 	}
-   	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.dol_escape_htmltag($search_month).'">';
-   	$formother->select_year($search_year, 'search_year', 1, 20, 5);
+	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.dol_escape_htmltag($search_month).'">';
+	$formother->select_year($search_year, 'search_year', 1, 20, 5);
 	print '</td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref" value="'.dol_escape_htmltag($search_ref).'"></td>';
 	//print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_label" value="' . dol_escape_htmltag($search_label) . '"></td>';
@@ -402,9 +439,15 @@ if ($result) {
 
 		// Ref Product
 		print '<td class="tdoverflowmax100">';
-		if ($productstatic->id > 0) print $productstatic->getNomUrl(1);
-		if ($productstatic->id > 0 && $objp->product_label) print '<br>';
-		if ($objp->product_label) print '<span class="opacitymedium">'.$objp->product_label.'</span>';
+		if ($productstatic->id > 0) {
+			print $productstatic->getNomUrl(1);
+		}
+		if ($productstatic->id > 0 && $objp->product_label) {
+			print '<br>';
+		}
+		if ($objp->product_label) {
+			print '<span class="opacitymedium">'.$objp->product_label.'</span>';
+		}
 		print '</td>';
 
 		print '<td class="tdoverflowonsmartphone">';
@@ -422,8 +465,7 @@ if ($result) {
 
 		// Country
 		print '<td>';
-		if ($objp->country_code)
-		{
+		if ($objp->country_code) {
 			print $langs->trans("Country".$objp->country_code).' ('.$objp->country_code.')';
 		}
 		print '</td>';

+ 125 - 65
htdocs/accountancy/customer/list.php

@@ -72,12 +72,15 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0) { $page = 0; }
+if (empty($page) || $page < 0) {
+	$page = 0;
+}
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield)
+if (!$sortfield) {
 	$sortfield = "f.datef, f.ref, l.rowid";
+}
 if (!$sortorder) {
 	if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO > 0) {
 		$sortorder = "DESC";
@@ -85,10 +88,12 @@ if (!$sortorder) {
 }
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->bind->write)
+}
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 $hookmanager->initHooks(array('accountancycustomerlist'));
@@ -102,18 +107,22 @@ $chartaccountcode = dol_getIdFromCode($db, $conf->global->CHARTOFACCOUNTS, 'acco
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	// Purge search criteria
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
-	{
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
 		$search_societe = '';
 		$search_lineid = '';
 		$search_ref = '';
@@ -155,8 +164,7 @@ if ($massaction == 'ventil') {
 			$monId = $maLigneCourante[0];
 			$monCompte = GETPOST('codeventil'.$monId);
 
-			if ($monCompte <= 0)
-			{
+			if ($monCompte <= 0) {
 				$msg .= '<div><span style="color:red">'.$langs->trans("Lineofinvoice", $monId).' - '.$langs->trans("NoAccountSelected").'</span></div>';
 				$ko++;
 			} else {
@@ -195,8 +203,7 @@ $formother = new FormOther($db);
 
 llxHeader('', $langs->trans("Ventilation"));
 
-if (empty($chartaccountcode))
-{
+if (empty($chartaccountcode)) {
 	print $langs->trans("ErrorChartOfAccountSystemNotSelected");
 	// End of page
 	llxFooter();
@@ -264,16 +271,23 @@ $sql .= dolSqlDateFilter('f.datef', $search_day, $search_month, $search_year);
 if (strlen(trim($search_country))) {
 	$arrayofcode = getCountriesInEEC();
 	$country_code_in_EEC = $country_code_in_EEC_without_me = '';
-	foreach ($arrayofcode as $key => $value)
-	{
+	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 ($value != $mysoc->country_code) {
+			$country_code_in_EEC_without_me .= ($country_code_in_EEC_without_me ? "," : "")."'".$value."'";
+		}
+	}
+	if ($search_country == 'special_allnotme') {
+		$sql .= " AND co.code <> '".$db->escape($mysoc->country_code)."'";
+	} elseif ($search_country == 'special_eec') {
+		$sql .= " AND co.code IN (".$country_code_in_EEC.")";
+	} elseif ($search_country == 'special_eecnotme') {
+		$sql .= " AND co.code IN (".$country_code_in_EEC_without_me.")";
+	} elseif ($search_country == 'special_noteec') {
+		$sql .= " AND co.code NOT IN (".$country_code_in_EEC.")";
+	} else {
+		$sql .= natural_search("co.code", $search_country);
 	}
-	if ($search_country == 'special_allnotme')     $sql .= " AND co.code <> '".$db->escape($mysoc->country_code)."'";
-	elseif ($search_country == 'special_eec')      $sql .= " AND co.code IN (".$country_code_in_EEC.")";
-	elseif ($search_country == 'special_eecnotme') $sql .= " AND co.code IN (".$country_code_in_EEC_without_me.")";
-	elseif ($search_country == 'special_noteec')   $sql .= " AND co.code NOT IN (".$country_code_in_EEC.")";
-	else $sql .= natural_search("co.code", $search_country);
 }
 if (strlen(trim($search_tvaintra))) {
 	$sql .= natural_search("s.tva_intra", $search_tvaintra);
@@ -294,12 +308,10 @@ $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$result = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($result);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -321,20 +333,48 @@ if ($result) {
 	$arrayofselected = is_array($toselect) ? $toselect : array();
 
 	$param = '';
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-	if ($search_societe)     $param .= '&search_societe='.urlencode($search_societe);
-	if ($search_lineid)      $param .= '&search_lineid='.urlencode($search_lineid);
-	if ($search_day)         $param .= '&search_day='.urlencode($search_day);
-	if ($search_month)       $param .= '&search_month='.urlencode($search_month);
-	if ($search_year)        $param .= '&search_year='.urlencode($search_year);
-	if ($search_invoice)     $param .= '&search_invoice='.urlencode($search_invoice);
-	if ($search_ref)         $param .= '&search_ref='.urlencode($search_ref);
-	if ($search_desc)        $param .= '&search_desc='.urlencode($search_desc);
-	if ($search_amount)      $param .= '&search_amount='.urlencode($search_amount);
-	if ($search_vat)         $param .= '&search_vat='.urlencode($search_vat);
-	if ($search_country)  	 $param .= "&search_country=".urlencode($search_country);
-	if ($search_tvaintra)	 $param .= "&search_tvaintra=".urlencode($search_tvaintra);
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.urlencode($limit);
+	}
+	if ($search_societe) {
+		$param .= '&search_societe='.urlencode($search_societe);
+	}
+	if ($search_lineid) {
+		$param .= '&search_lineid='.urlencode($search_lineid);
+	}
+	if ($search_day) {
+		$param .= '&search_day='.urlencode($search_day);
+	}
+	if ($search_month) {
+		$param .= '&search_month='.urlencode($search_month);
+	}
+	if ($search_year) {
+		$param .= '&search_year='.urlencode($search_year);
+	}
+	if ($search_invoice) {
+		$param .= '&search_invoice='.urlencode($search_invoice);
+	}
+	if ($search_ref) {
+		$param .= '&search_ref='.urlencode($search_ref);
+	}
+	if ($search_desc) {
+		$param .= '&search_desc='.urlencode($search_desc);
+	}
+	if ($search_amount) {
+		$param .= '&search_amount='.urlencode($search_amount);
+	}
+	if ($search_vat) {
+		$param .= '&search_vat='.urlencode($search_vat);
+	}
+	if ($search_country) {
+		$param .= "&search_country=".urlencode($search_country);
+	}
+	if ($search_tvaintra) {
+		$param .= "&search_tvaintra=".urlencode($search_tvaintra);
+	}
 
 	$arrayofmassactions = array(
 		'ventil'=>$langs->trans("Ventilate")
@@ -347,7 +387,9 @@ if ($result) {
 
 	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'."\n";
 	print '<input type="hidden" name="action" value="ventil">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
@@ -358,7 +400,9 @@ if ($result) {
 
 	print '<span class="opacitymedium">'.$langs->trans("DescVentilTodoCustomer").'</span></br><br>';
 
-	if ($msg) print $msg.'<br>';
+	if ($msg) {
+		print $msg.'<br>';
+	}
 
 	$moreforfilter = '';
 
@@ -370,11 +414,11 @@ if ($result) {
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth25" name="search_lineid" value="'.dol_escape_htmltag($search_lineid).'"></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="'.dol_escape_htmltag($search_invoice).'"></td>';
 	print '<td class="liste_titre center nowraponall minwidth100imp">';
-   	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) {
+	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) {
 		print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.$search_day.'">';
 	}
-   	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
-   	$formother->select_year($search_year, 'search_year', 1, 20, 5);
+	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
+	$formother->select_year($search_year, 'search_year', 1, 20, 5);
 	print '</td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref" value="'.dol_escape_htmltag($search_ref).'"></td>';
 	//print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_label" value="' . dol_escape_htmltag($search_label) . '"></td>';
@@ -410,7 +454,9 @@ if ($result) {
 	print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', '', '', 'nowraponall ');
 	print_liste_field_titre("IntoAccount", '', '', '', '', '', '', '', 'center ');
 	$checkpicto = '';
-	if ($massactionbutton) $checkpicto = $form->showCheckAddButtons('checkforselect', 1);
+	if ($massactionbutton) {
+		$checkpicto = $form->showCheckAddButtons('checkforselect', 1);
+	}
 	print_liste_field_titre($checkpicto, '', '', '', '', '', '', '', 'center ');
 	print "</tr>\n";
 
@@ -503,7 +549,9 @@ if ($result) {
 				}
 			}
 		}
-		if ($objp->code_sell_l == -1) $objp->code_sell_l = '';
+		if ($objp->code_sell_l == -1) {
+			$objp->code_sell_l = '';
+		}
 
 		// Level 2: Search suggested account for product/service (similar code exists in page index.php to make automatic binding)
 		$suggestedaccountingaccountfor = '';
@@ -553,8 +601,12 @@ if ($result) {
 		} else {
 			$code_sell_p_notset = 'color:orange';
 		}
-		if (empty($objp->code_sell_l) && empty($objp->code_sell_p)) $code_sell_p_notset = 'color:red';
-		if ($suggestedaccountingaccountfor == 'eecwithoutvatnumber' && empty($code_sell_p_notset)) $code_sell_p_notset = 'color:orange';
+		if (empty($objp->code_sell_l) && empty($objp->code_sell_p)) {
+			$code_sell_p_notset = 'color:red';
+		}
+		if ($suggestedaccountingaccountfor == 'eecwithoutvatnumber' && empty($code_sell_p_notset)) {
+			$code_sell_p_notset = 'color:orange';
+		}
 
 		// $objp->code_sell_l is now default code of product/service
 		// $objp->code_sell_p is now code of product/service
@@ -575,7 +627,9 @@ if ($result) {
 		if ($product_static->id > 0) {
 			print $product_static->getNomUrl(1);
 		}
-		if ($objp->product_label) print '<br><span class="opacitymedium small">'.$objp->product_label.'</span>';
+		if ($objp->product_label) {
+			print '<br><span class="opacitymedium small">'.$objp->product_label.'</span>';
+		}
 		print '</td>';
 
 		print '<td class="tdoverflowonsmartphone small">';
@@ -589,8 +643,9 @@ if ($result) {
 		print '</td>';
 
 		// Vat rate
-		if ($objp->vat_tx_l != $objp->vat_tx_p)
+		if ($objp->vat_tx_l != $objp->vat_tx_p) {
 			$code_vat_differ = 'font-weight:bold; text-decoration:blink; color:red';
+		}
 		print '<td style="'.$code_vat_differ.'" class="right">';
 		print vatrate($objp->tva_tx_line.($objp->vat_src_code ? ' ('.$objp->vat_src_code.')' : ''));
 		print '</td>';
@@ -610,22 +665,27 @@ if ($result) {
 		print '<td>';
 		$s = '<span class="small">1. '.(($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': </span>';
 		$shelp = '';
-		if ($suggestedaccountingaccountbydefaultfor == 'eec') $shelp .= $langs->trans("SaleEEC");
-		elseif ($suggestedaccountingaccountbydefaultfor == 'export') $shelp .= $langs->trans("SaleExport");
+		if ($suggestedaccountingaccountbydefaultfor == 'eec') {
+			$shelp .= $langs->trans("SaleEEC");
+		} elseif ($suggestedaccountingaccountbydefaultfor == 'export') {
+			$shelp .= $langs->trans("SaleExport");
+		}
 		$s .= ($objp->code_sell_l > 0 ? length_accountg($objp->code_sell_l) : '<span style="'.$code_sell_p_notset.'">'.$langs->trans("NotDefined").'</span>');
 		print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1);
-		if ($objp->product_id > 0)
-		{
+		if ($objp->product_id > 0) {
 			print '<br>';
 			$s = '<span class="small">2. '.(($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': </span>';
 			$shelp = ''; $ttype = 'help';
-			if ($suggestedaccountingaccountfor == 'eec') $shelp = $langs->trans("SaleEEC");
-			elseif ($suggestedaccountingaccountfor == 'eecwithvat') $shelp = $langs->trans("SaleEECWithVAT");
-			elseif ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') {
+			if ($suggestedaccountingaccountfor == 'eec') {
+				$shelp = $langs->trans("SaleEEC");
+			} elseif ($suggestedaccountingaccountfor == 'eecwithvat') {
+				$shelp = $langs->trans("SaleEECWithVAT");
+			} elseif ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') {
 				$shelp = $langs->trans("SaleEECWithoutVATNumber");
 				$ttype = 'warning';
+			} elseif ($suggestedaccountingaccountfor == 'export') {
+				$shelp = $langs->trans("SaleExport");
 			}
-			elseif ($suggestedaccountingaccountfor == 'export') $shelp = $langs->trans("SaleExport");
 			$s .= (empty($objp->code_sell_p) ? '<span style="'.$code_sell_p_notset.'">'.$langs->trans("NotDefined").'</span>' : length_accountg($objp->code_sell_p));
 			print $form->textwithpicto($s, $shelp, 1, $ttype, '', 0, 2, '', 1);
 		} else {
@@ -649,10 +709,8 @@ if ($result) {
 		// Suggested accounting account
 		print '<td>';
 		$suggestedid = $objp->aarowid_suggest;
-		if (empty($suggestedid) && empty($objp->code_sell_p) && !empty($objp->code_sell_l) && empty($conf->global->ACCOUNTANCY_DO_NOT_AUTOFILL_ACCOUNT_WITH_GENERIC))
-		{
-			if (empty($accountingaccount_codetotid_cache[$objp->code_sell_l]))
-			{
+		if (empty($suggestedid) && empty($objp->code_sell_p) && !empty($objp->code_sell_l) && empty($conf->global->ACCOUNTANCY_DO_NOT_AUTOFILL_ACCOUNT_WITH_GENERIC)) {
+			if (empty($accountingaccount_codetotid_cache[$objp->code_sell_l])) {
 				$tmpaccount = new AccountingAccount($db);
 				$tmpaccount->fetch(0, $objp->code_sell_l, 1);
 				if ($tmpaccount->id > 0) {
@@ -669,7 +727,9 @@ if ($result) {
 		// Column with checkbox
 		print '<td class="center">';
 		$ischecked = $objp->aarowid_suggest;
-		if ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') $ischecked = 0;
+		if ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') {
+			$ischecked = 0;
+		}
 		print '<input type="checkbox" class="flat checkforselect checkforselect'.$objp->rowid.'" name="toselect[]" value="'.$objp->rowid."_".$i.'"'.($ischecked ? "checked" : "").'/>';
 		print '</td>';
 

+ 8 - 8
htdocs/accountancy/expensereport/card.php

@@ -42,19 +42,20 @@ $codeventil = GETPOST('codeventil', 'int');
 $id = GETPOST('id', 'int');
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
+}
 
 
 /*
  * Actions
  */
 
-if ($action == 'ventil' && $user->rights->accounting->bind->write)
-{
-	if (!$cancel)
-	{
-		if ($codeventil < 0) $codeventil = 0;
+if ($action == 'ventil' && $user->rights->accounting->bind->write) {
+	if (!$cancel) {
+		if ($codeventil < 0) {
+			$codeventil = 0;
+		}
 
 		$sql = " UPDATE ".MAIN_DB_PREFIX."expensereport_det";
 		$sql .= " SET fk_code_ventilation = ".$codeventil;
@@ -65,8 +66,7 @@ if ($action == 'ventil' && $user->rights->accounting->bind->write)
 			setEventMessages($db->lasterror(), null, 'errors');
 		} else {
 			setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
-			if ($backtopage)
-			{
+			if ($backtopage) {
 				header("Location: ".$backtopage);
 				exit();
 			}

+ 47 - 29
htdocs/accountancy/expensereport/index.php

@@ -36,21 +36,25 @@ $langs->loadLangs(array("compta", "bills", "other", "main", "accountancy"));
 if (empty($conf->accounting->enabled)) {
 	accessforbidden();
 }
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->bind->write)
+}
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
-if (GETPOST("year", 'int')) $year_start = GETPOST("year", 'int');
-else {
+if (GETPOST("year", 'int')) {
+	$year_start = GETPOST("year", 'int');
+} else {
 	$year_start = dol_print_date(dol_now(), '%Y');
-	if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year
+	if (dol_print_date(dol_now(), '%m') < $month_start) {
+		$year_start--; // If current month is lower that starting fiscal month, we start last year
+	}
 }
 $year_end = $year_start + 1;
 $month_end = $month_start - 1;
-if ($month_end < 1)
-{
+if ($month_end < 1) {
 	$month_end = 12;
 	$year_end--;
 }
@@ -67,8 +71,7 @@ $action = GETPOST('action', 'aZ09');
  * Actions
  */
 
-if ($action == 'clean' || $action == 'validatehistory')
-{
+if ($action == 'clean' || $action == 'validatehistory') {
 	// Clean database
 	$db->begin();
 	$sql1 = "UPDATE ".MAIN_DB_PREFIX."expensereport_det as erd";
@@ -156,7 +159,9 @@ print '<tr class="liste_titre"><td width="200">'.$langs->trans("Account").'</td>
 print '<td width="200" class="left">'.$langs->trans("Label").'</td>';
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 }
 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -165,7 +170,9 @@ $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account
 $sql .= "  ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	$sql .= "  SUM(".$db->ifsql('MONTH(er.date_debut)='.$j, 'erd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 }
 $sql .= " SUM(erd.total_ht) as total";
@@ -190,16 +197,18 @@ if ($resql) {
 
 	while ($row = $db->fetch_row($resql)) {
 		print '<tr class="oddeven"><td>';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("Unknown");
-		} else print length_accountg($row[0]);
+		} else {
+			print length_accountg($row[0]);
+		}
 		print '</td>';
 		print '<td class="left">';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/expensereport/list.php?search_year='.$y, $langs->transnoentitiesnoconv("ToBind"));
-		} else print $row[1];
+		} else {
+			print $row[1];
+		}
 		print '</td>';
 		for ($i = 2; $i <= 12; $i++) {
 			print '<td class="nowrap right">'.price($row[$i]).'</td>';
@@ -229,7 +238,9 @@ print '<tr class="liste_titre"><td width="200">'.$langs->trans("Account").'</td>
 print '<td width="200" class="left">'.$langs->trans("Label").'</td>';
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 }
 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -238,7 +249,9 @@ $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account
 $sql .= "  ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	$sql .= "  SUM(".$db->ifsql('MONTH(er.date_debut)='.$j, 'erd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 }
 $sql .= " ROUND(SUM(erd.total_ht),2) as total";
@@ -263,17 +276,19 @@ if ($resql) {
 
 	while ($row = $db->fetch_row($resql)) {
 		print '<tr class="oddeven"><td>';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("Unknown");
-		} else print length_accountg($row[0]);
+		} else {
+			print length_accountg($row[0]);
+		}
 		print '</td>';
 
 		print '<td class="left">';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/expensereport/list.php?search_year='.$y, $langs->transnoentitiesnoconv("ToBind"));
-		} else print $row[1];
+		} else {
+			print $row[1];
+		}
 		print '</td>';
 		for ($i = 2; $i <= 12; $i++) {
 			print '<td class="nowrap right">'.price($row[$i]).'</td>';
@@ -291,8 +306,7 @@ print '</div>';
 
 
 
-if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. Why showing a report where results depends on next step (so not yet available) ?
-{
+if ($conf->global->MAIN_FEATURES_LEVEL > 0) { // This part of code looks strange. Why showing a report where results depends on next step (so not yet available) ?
 	print '<br>';
 	print '<br>';
 
@@ -304,7 +318,9 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange.
 	print '<tr class="liste_titre"><td width="400" class="left">'.$langs->trans("Total").'</td>';
 	for ($i = 1; $i <= 12; $i++) {
 		$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-		if ($j > 12) $j -= 12;
+		if ($j > 12) {
+			$j -= 12;
+		}
 		print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 	}
 	print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -312,7 +328,9 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange.
 	$sql = "SELECT '".$db->escape($langs->trans("TotalExpenseReport"))."' AS label,";
 	for ($i = 1; $i <= 12; $i++) {
 		$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-		if ($j > 12) $j -= 12;
+		if ($j > 12) {
+			$j -= 12;
+		}
 		$sql .= " SUM(".$db->ifsql('MONTH(er.date_create)='.$j, 'erd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 	}
 	$sql .= " SUM(erd.total_ht) as total";

+ 55 - 29
htdocs/accountancy/expensereport/lines.php

@@ -58,12 +58,15 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0) $page = 0;
+if (empty($page) || $page < 0) {
+	$page = 0;
+}
 $pageprev = $page - 1;
 $pagenext = $page + 1;
 $offset = $limit * $page;
-if (!$sortfield)
+if (!$sortfield) {
 	$sortfield = "erd.date, erd.rowid";
+}
 if (!$sortorder) {
 	if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE > 0) {
 		$sortorder = "DESC";
@@ -71,10 +74,12 @@ if (!$sortorder) {
 }
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->bind->write)
+}
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 $formaccounting = new FormAccounting($db);
 
@@ -84,8 +89,7 @@ $formaccounting = new FormAccounting($db);
  */
 
 // Purge search criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers
 	$search_login = '';
 	$search_expensereport = '';
 	$search_label = '';
@@ -101,14 +105,12 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
 if (is_array($changeaccount) && count($changeaccount) > 0) {
 	$error = 0;
 
-	if (!(GETPOST('account_parent', 'int') >= 0))
-	{
+	if (!(GETPOST('account_parent', 'int') >= 0)) {
 		$error++;
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Account")), null, 'errors');
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		$db->begin();
 
 		$sql1 = "UPDATE ".MAIN_DB_PREFIX."expensereport_det as erd";
@@ -205,12 +207,10 @@ $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$result = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($result);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -226,21 +226,45 @@ if ($result) {
 	$i = 0;
 
 	$param = '';
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-	if ($search_login)       $param .= '&search_login='.urlencode($search_login);
-	if ($search_expensereport) $param .= "&search_expensereport=".urlencode($search_expensereport);
-	if ($search_label)		$param .= "&search_label=".urlencode($search_label);
-	if ($search_desc)		$param .= "&search_desc=".urlencode($search_desc);
-	if ($search_account)	$param .= "&search_account=".urlencode($search_account);
-	if ($search_vat)		$param .= "&search_vat=".urlencode($search_vat);
-	if ($search_day)        $param .= '&search_day='.urlencode($search_day);
-	if ($search_month)      $param .= '&search_month='.urlencode($search_month);
-	if ($search_year)       $param .= '&search_year='.urlencode($search_year);
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.urlencode($limit);
+	}
+	if ($search_login) {
+		$param .= '&search_login='.urlencode($search_login);
+	}
+	if ($search_expensereport) {
+		$param .= "&search_expensereport=".urlencode($search_expensereport);
+	}
+	if ($search_label) {
+		$param .= "&search_label=".urlencode($search_label);
+	}
+	if ($search_desc) {
+		$param .= "&search_desc=".urlencode($search_desc);
+	}
+	if ($search_account) {
+		$param .= "&search_account=".urlencode($search_account);
+	}
+	if ($search_vat) {
+		$param .= "&search_vat=".urlencode($search_vat);
+	}
+	if ($search_day) {
+		$param .= '&search_day='.urlencode($search_day);
+	}
+	if ($search_month) {
+		$param .= '&search_month='.urlencode($search_month);
+	}
+	if ($search_year) {
+		$param .= '&search_year='.urlencode($search_year);
+	}
 
 	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'."\n";
 	print '<input type="hidden" name="action" value="ventil">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
@@ -268,9 +292,11 @@ if ($result) {
 		print '<td class="liste_titre"></td>';
 	}
 	print '<td class="liste_titre center">';
-   	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.$search_day.'">';
-   	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
-   	$formother->select_year($search_year, 'search_year', 1, 20, 5);
+	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) {
+		print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.$search_day.'">';
+	}
+	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
+	$formother->select_year($search_year, 'search_year', 1, 20, 5);
 	print '</td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_label" value="'.dol_escape_htmltag($search_label).'"></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_desc" value="'.dol_escape_htmltag($search_desc).'"></td>';

+ 70 - 34
htdocs/accountancy/expensereport/list.php

@@ -68,12 +68,15 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0) { $page = 0; }
+if (empty($page) || $page < 0) {
+	$page = 0;
+}
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield)
+if (!$sortfield) {
 	$sortfield = "erd.date, erd.rowid";
+}
 if (!$sortorder) {
 	if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO > 0) {
 		$sortorder = "DESC";
@@ -81,10 +84,12 @@ if (!$sortorder) {
 }
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->bind->write)
+}
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 $formaccounting = new FormAccounting($db);
 $accounting = new AccountingAccount($db);
@@ -96,12 +101,15 @@ $chartaccountcode = dol_getIdFromCode($db, $conf->global->CHARTOFACCOUNTS, 'acco
  * Action
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
 
 // Purge search criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
 	$search_login = '';
 	$search_expensereport = '';
 	$search_label = '';
@@ -137,8 +145,7 @@ if ($massaction == 'ventil') {
 			$monId = $maLigneCourante[0];
 			$monCompte = GETPOST('codeventil'.$monId);
 
-			if ($monCompte <= 0)
-			{
+			if ($monCompte <= 0) {
 				$msg .= '<div><span style="color:red">'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'</span></div>';
 				$ko++;
 			} else {
@@ -177,8 +184,7 @@ $formother = new FormOther($db);
 
 llxHeader('', $langs->trans("ExpenseReportsVentilation"));
 
-if (empty($chartaccountcode))
-{
+if (empty($chartaccountcode)) {
 	print $langs->trans("ErrorChartOfAccountSystemNotSelected");
 	// End of page
 	llxFooter();
@@ -231,12 +237,10 @@ $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$result = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($result);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -253,18 +257,42 @@ if ($result) {
 	$arrayofselected = is_array($toselect) ? $toselect : array();
 
 	$param = '';
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-	if ($search_login)       $param .= '&search_login='.urlencode($search_login);
-	if ($search_lineid)      $param .= '&search_lineid='.urlencode($search_lineid);
-	if ($search_day)         $param .= '&search_day='.urlencode($search_day);
-	if ($search_month)       $param .= '&search_month='.urlencode($search_month);
-	if ($search_year)        $param .= '&search_year='.urlencode($search_year);
-	if ($search_expensereport) $param .= '&search_expensereport='.urlencode($search_expensereport);
-	if ($search_label)       $param .= '&search_label='.urlencode($search_label);
-	if ($search_desc)        $param .= '&search_desc='.urlencode($search_desc);
-	if ($search_amount)      $param .= '&search_amount='.urlencode($search_amount);
-	if ($search_vat)         $param .= '&search_vat='.urlencode($search_vat);
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.urlencode($limit);
+	}
+	if ($search_login) {
+		$param .= '&search_login='.urlencode($search_login);
+	}
+	if ($search_lineid) {
+		$param .= '&search_lineid='.urlencode($search_lineid);
+	}
+	if ($search_day) {
+		$param .= '&search_day='.urlencode($search_day);
+	}
+	if ($search_month) {
+		$param .= '&search_month='.urlencode($search_month);
+	}
+	if ($search_year) {
+		$param .= '&search_year='.urlencode($search_year);
+	}
+	if ($search_expensereport) {
+		$param .= '&search_expensereport='.urlencode($search_expensereport);
+	}
+	if ($search_label) {
+		$param .= '&search_label='.urlencode($search_label);
+	}
+	if ($search_desc) {
+		$param .= '&search_desc='.urlencode($search_desc);
+	}
+	if ($search_amount) {
+		$param .= '&search_amount='.urlencode($search_amount);
+	}
+	if ($search_vat) {
+		$param .= '&search_vat='.urlencode($search_vat);
+	}
 
 	$arrayofmassactions = array(
 		'ventil' => $langs->trans("Ventilate")
@@ -274,7 +302,9 @@ if ($result) {
 
 	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'."\n";
 	print '<input type="hidden" name="action" value="ventil">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
@@ -285,7 +315,9 @@ if ($result) {
 
 	print '<span class="opacitymedium">'.$langs->trans("DescVentilTodoExpenseReport").'</span></br><br>';
 
-	if ($msg) print $msg.'<br>';
+	if ($msg) {
+		print $msg.'<br>';
+	}
 
 	$moreforfilter = '';
 
@@ -301,9 +333,11 @@ if ($result) {
 		print '<td class="liste_titre"></td>';
 	}
 	print '<td class="liste_titre center nowraponall minwidth100imp">';
-   	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.$search_day.'">';
-   	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
-   	$formother->select_year($search_year, 'search_year', 1, 20, 5);
+	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) {
+		print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.$search_day.'">';
+	}
+	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
+	$formother->select_year($search_year, 'search_year', 1, 20, 5);
 	print '</td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_label" value="'.dol_escape_htmltag($search_label).'"></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidthonsmartphone" name="search_desc" value="'.dol_escape_htmltag($search_desc).'"></td>';
@@ -332,7 +366,9 @@ if ($result) {
 	print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', '', '', 'nowraponall ');
 	print_liste_field_titre("IntoAccount", '', '', '', '', '', '', '', '');
 	$checkpicto = '';
-	if ($massactionbutton) $checkpicto = $form->showCheckAddButtons('checkforselect', 1);
+	if ($massactionbutton) {
+		$checkpicto = $form->showCheckAddButtons('checkforselect', 1);
+	}
 	print_liste_field_titre($checkpicto, '', '', '', '', '', '', '', 'center ');
 	print "</tr>\n";
 

+ 14 - 16
htdocs/accountancy/index.php

@@ -32,8 +32,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
 $langs->loadLangs(array("compta", "bills", "other", "accountancy", "loans", "banks", "admin", "dict"));
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
+}
 
 // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks
 $hookmanager->initHooks(array('accountancyindex'));
@@ -43,8 +44,8 @@ $hookmanager->initHooks(array('accountancyindex'));
  * Actions
  */
 
-if (GETPOST('addbox'))	// Add box (when submit is done from a form when ajax disabled)
-{
+if (GETPOST('addbox')) {
+	// Add box (when submit is done from a form when ajax disabled)
 	require_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
 	$zone = GETPOST('areacode', 'aZ09');
 	$userid = GETPOST('userid', 'int');
@@ -52,7 +53,9 @@ if (GETPOST('addbox'))	// Add box (when submit is done from a form when ajax dis
 	$boxorder .= GETPOST('boxcombo', 'aZ09');
 
 	$result = InfoBox::saveboxorder($db, $zone, $boxorder, $userid);
-	if ($result > 0) setEventMessages($langs->trans("BoxAdded"), null);
+	if ($result > 0) {
+		setEventMessages($langs->trans("BoxAdded"), null);
+	}
 }
 
 
@@ -62,8 +65,7 @@ if (GETPOST('addbox'))	// Add box (when submit is done from a form when ajax dis
 
 llxHeader('', $langs->trans("AccountancyArea"));
 
-if ($conf->accounting->enabled)
-{
+if ($conf->accounting->enabled) {
 	$step = 0;
 
 	$resultboxes = FormOther::getBoxesArea($user, "27"); // Load $resultboxes (selectboxlist + boxactivated + boxlista + boxlistb)
@@ -71,8 +73,7 @@ if ($conf->accounting->enabled)
 	$helpisexpanded = empty($resultboxes['boxactivated']) || (empty($resultboxes['boxlista']) && empty($resultboxes['boxlistb'])); // If there is no widget, the tooltip help is expanded by default.
 	$showtutorial = '';
 
-	if (!$helpisexpanded)
-	{
+	if (!$helpisexpanded) {
 		$showtutorial  = '<div align="right"><a href="#" id="show_hide">';
 		$showtutorial .= img_picto('', 'chevron-down');
 		$showtutorial .= ' '.$langs->trans("ShowTutorial");
@@ -141,8 +142,7 @@ if ($conf->accounting->enabled)
 	$s = str_replace('{s}', $textlink, $s);
 	print $s;
 	print "<br>\n";
-	if (!empty($conf->tax->enabled))
-	{
+	if (!empty($conf->tax->enabled)) {
 		$textlink = '<a href="'.DOL_URL_ROOT.'/admin/dict.php?id=7&from=accountancy"><strong>'.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuTaxAccounts").'</strong></a>';
 		$step++;
 		$s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescContrib", $step, '{s}');
@@ -150,8 +150,7 @@ if ($conf->accounting->enabled)
 		print $s;
 		print "<br>\n";
 	}
-	if (!empty($conf->expensereport->enabled))  // TODO Move this in the default account page because this is only one accounting account per purpose, not several.
-	{
+	if (!empty($conf->expensereport->enabled)) {  // TODO Move this in the default account page because this is only one accounting account per purpose, not several.
 		$step++;
 		$s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescExpenseReport", $step, '{s}');
 		$s = str_replace('{s}', '<a href="'.DOL_URL_ROOT.'/admin/dict.php?id=17&from=accountancy"><strong>'.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuExpenseReportAccounts").'</strong></a>', $s);
@@ -190,8 +189,7 @@ if ($conf->accounting->enabled)
 	print $s;
 	print "<br>\n";
 
-	if (!empty($conf->expensereport->enabled) || !empty($conf->deplacement->enabled))
-	{
+	if (!empty($conf->expensereport->enabled) || !empty($conf->deplacement->enabled)) {
 		$step++;
 		$s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64 + $step), $langs->transnoentitiesnoconv("ExpenseReports"), '{s}')."\n";
 		$s = str_replace('{s}', '<a href="'.DOL_URL_ROOT.'/accountancy/expensereport/index.php"><strong>'.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("ExpenseReportsVentilation").'</strong></a>', $s);
@@ -218,8 +216,8 @@ if ($conf->accounting->enabled)
 	print '<div class="fichecenter fichecenterbis">';
 
 	/*
-     * Show boxes
-     */
+	 * Show boxes
+	 */
 	$boxlist .= '<div class="twocolumns">';
 
 	$boxlist .= '<div class="firstcolumn fichehalfleft boxhalfleft" id="boxhalfleft">';

+ 76 - 63
htdocs/accountancy/journal/expensereportsjournal.php

@@ -51,13 +51,16 @@ $date_endmonth = GETPOST('date_endmonth');
 $date_endday = GETPOST('date_endday');
 $date_endyear = GETPOST('date_endyear');
 $in_bookkeeping = GETPOST('in_bookkeeping');
-if ($in_bookkeeping == '') $in_bookkeeping = 'notyet';
+if ($in_bookkeeping == '') {
+	$in_bookkeeping = 'notyet';
+}
 
 $now = dol_now();
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
+}
 
 /*
  * Actions
@@ -73,8 +76,7 @@ $journal_label = $accountingjournalstatic->label;
 $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
 $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
 
-if (empty($date_startmonth) || empty($date_endmonth))
-{
+if (empty($date_startmonth) || empty($date_endmonth)) {
 	// Period by default on transfer
 	$dates = getDefaultDatesForTransfer();
 	$date_start = $dates['date_start'];
@@ -83,8 +85,7 @@ if (empty($date_startmonth) || empty($date_endmonth))
 	$pastmonth = $dates['pastmonth'];
 }
 
-if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) // We define date_start and date_end, only if we did not submit the form
-{
+if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) { // We define date_start and date_end, only if we did not submit the form
 	$date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
 	$date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
 }
@@ -101,19 +102,18 @@ $sql .= " JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = er.fk_user_author";
 $sql .= " WHERE er.fk_statut > 0";
 $sql .= " AND erd.fk_code_ventilation > 0";
 $sql .= " AND er.entity IN (".getEntity('expensereport', 0).")"; // We don't share object for accountancy
-if ($date_start && $date_end)
+if ($date_start && $date_end) {
 	$sql .= " AND er.date_debut >= '".$db->idate($date_start)."' AND er.date_debut <= '".$db->idate($date_end)."'";
+}
 // Define begin binding date
 if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
 	$sql .= " AND er.date_debut >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
 }
 // Already in bookkeeping or not
-if ($in_bookkeeping == 'already')
-{
+if ($in_bookkeeping == 'already') {
 	$sql .= " AND er.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab  WHERE ab.doc_type='expense_report')";
 }
-if ($in_bookkeeping == 'notyet')
-{
+if ($in_bookkeeping == 'notyet') {
 	$sql .= " AND er.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab  WHERE ab.doc_type='expense_report')";
 }
 $sql .= " ORDER BY er.date_debut";
@@ -150,8 +150,7 @@ if ($result) {
 		$compta_localtax2 = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $cpttva);
 
 		// Define array to display all VAT rates that use this accounting account $compta_tva
-		if (price2num($obj->tva_tx) || !empty($obj->vat_src_code))
-		{
+		if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
 			$def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '')] = (vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
 		}
 
@@ -161,11 +160,21 @@ if ($result) {
 		$taber[$obj->rowid]["fk_expensereportdet"] = $obj->erdid;
 
 		// Avoid warnings
-		if (!isset($tabttc[$obj->rowid][$compta_user])) $tabttc[$obj->rowid][$compta_user] = 0;
-		if (!isset($tabht[$obj->rowid][$compta_fees])) $tabht[$obj->rowid][$compta_fees] = 0;
-		if (!isset($tabtva[$obj->rowid][$compta_tva])) $tabtva[$obj->rowid][$compta_tva] = 0;
-		if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
-		if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
+		if (!isset($tabttc[$obj->rowid][$compta_user])) {
+			$tabttc[$obj->rowid][$compta_user] = 0;
+		}
+		if (!isset($tabht[$obj->rowid][$compta_fees])) {
+			$tabht[$obj->rowid][$compta_fees] = 0;
+		}
+		if (!isset($tabtva[$obj->rowid][$compta_tva])) {
+			$tabtva[$obj->rowid][$compta_tva] = 0;
+		}
+		if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
+			$tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
+		}
+		if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
+			$tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
+		}
 
 		$tabttc[$obj->rowid][$compta_user] += $obj->total_ttc;
 		$tabht[$obj->rowid][$compta_fees] += $obj->total_ht;
@@ -189,8 +198,7 @@ if ($action == 'writebookkeeping') {
 	$now = dol_now();
 	$error = 0;
 
-	foreach ($taber as $key => $val)		// Loop on each expense report
-	{
+	foreach ($taber as $key => $val) {		// Loop on each expense report
 		$errorforline = 0;
 
 		$totalcredit = 0;
@@ -199,8 +207,7 @@ if ($action == 'writebookkeeping') {
 		$db->begin();
 
 		// Thirdparty
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			foreach ($tabttc[$key] as $k => $mt) {
 				if ($mt) {
 					$bookkeeping = new BookKeeping($db);
@@ -232,8 +239,7 @@ if ($action == 'writebookkeeping') {
 
 					$result = $bookkeeping->create($user);
 					if ($result < 0) {
-						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-						{
+						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 							$error++;
 							$errorforline++;
 							//setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
@@ -248,8 +254,7 @@ if ($action == 'writebookkeeping') {
 		}
 
 		// Fees
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			foreach ($tabht[$key] as $k => $mt) {
 				if ($mt) {
 					// get compte id and label
@@ -280,8 +285,7 @@ if ($action == 'writebookkeeping') {
 
 						$result = $bookkeeping->create($user);
 						if ($result < 0) {
-							if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-							{
+							if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 								$error++;
 								$errorforline++;
 								//setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
@@ -297,14 +301,16 @@ if ($action == 'writebookkeeping') {
 		}
 
 		// VAT
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			$listoftax = array(0, 1, 2);
-			foreach ($listoftax as $numtax)
-			{
+			foreach ($listoftax as $numtax) {
 				$arrayofvat = $tabtva;
-				if ($numtax == 1) $arrayofvat = $tablocaltax1;
-				if ($numtax == 2) $arrayofvat = $tablocaltax2;
+				if ($numtax == 1) {
+					$arrayofvat = $tablocaltax1;
+				}
+				if ($numtax == 2) {
+					$arrayofvat = $tablocaltax2;
+				}
 
 				foreach ($arrayofvat[$key] as $k => $mt) {
 					if ($mt) {
@@ -338,8 +344,7 @@ if ($action == 'writebookkeeping') {
 
 						$result = $bookkeeping->create($user);
 						if ($result < 0) {
-							if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-							{
+							if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 								$error++;
 								$errorforline++;
 								//setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
@@ -355,21 +360,18 @@ if ($action == 'writebookkeeping') {
 		}
 
 		// Protection against a bug on line before
-		if (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))
-		{
+		if (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT')) {
 			$error++;
 			$errorforline++;
 			setEventMessages('Try to insert a non balanced transaction in book for '.$val["ref"].'. Canceled. Surely a bug.', null, 'errors');
 		}
 
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			$db->commit();
 		} else {
 			$db->rollback();
 
-			if ($error >= 10)
-			{
+			if ($error >= 10) {
 				setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
 				break; // Break in the foreach
 			}
@@ -380,8 +382,7 @@ if ($action == 'writebookkeeping') {
 
 	if (empty($error) && count($tabpay) > 0) {
 		setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
-	} elseif (count($tabpay) == $error)
-	{
+	} elseif (count($tabpay) == $error) {
 		setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
 	} else {
 		setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
@@ -390,8 +391,7 @@ if ($action == 'writebookkeeping') {
 	$action = '';
 
 	// Must reload data, so we make a redirect
-	if (count($tabpay) != $error)
-	{
+	if (count($tabpay) != $error) {
 		$param = 'id_journal='.$id_journal;
 		$param .= '&date_startday='.$date_startday;
 		$param .= '&date_startmonth='.$date_startmonth;
@@ -503,12 +503,17 @@ if (empty($action) || $action == 'view') {
 	}
 	print '<div class="tabsAction tabsActionNoBottom">';
 
-	if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
+	if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') {
+		print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
+	}
 	if (empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) || $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT == '-1') {
 		print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
 	} else {
-		if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
-		else print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
+		if ($in_bookkeeping == 'notyet') {
+			print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
+		} else {
+			print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
+		}
 	}
 	print '</div>';
 
@@ -573,10 +578,11 @@ if (empty($action) || $action == 'view') {
 				// Account
 				print "<td>";
 				$accountoshow = length_accountg($k);
-				if (($accountoshow == "") || $accountoshow == 'NotDefined')
-				{
+				if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 					print '<span class="error">'.$langs->trans("FeeAccountNotDefined").'</span>';
-				} else print $accountoshow;
+				} else {
+					print $accountoshow;
+				}
 				print '</td>';
 				// Subledger account
 				print "<td>";
@@ -602,18 +608,20 @@ if (empty($action) || $action == 'view') {
 			// Account
 			print "<td>";
 			$accountoshow = length_accounta($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT);
-			if (($accountoshow == "") || $accountoshow == 'NotDefined')
-			{
+			if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 				print '<span class="error">'.$langs->trans("MainAccountForUsersNotDefined").'</span>';
-			} else print $accountoshow;
+			} else {
+				print $accountoshow;
+			}
 			print "</td>";
 			// Subledger account
 			print "<td>";
 			$accountoshow = length_accounta($k);
-			if (($accountoshow == "") || $accountoshow == 'NotDefined')
-			{
+			if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 				print '<span class="error">'.$langs->trans("UserAccountNotDefined").'</span>';
-			} else print $accountoshow;
+			} else {
+				print $accountoshow;
+			}
 			print '</td>';
 			print "<td>".$userstatic->getNomUrl(0, 'user', 16).' - '.$langs->trans("SubledgerAccount")."</td>";
 			print '<td class="right nowraponall">'.($mt < 0 ? price(-$mt) : '')."</td>";
@@ -625,8 +633,12 @@ if (empty($action) || $action == 'view') {
 		$listoftax = array(0, 1, 2);
 		foreach ($listoftax as $numtax) {
 			$arrayofvat = $tabtva;
-			if ($numtax == 1) $arrayofvat = $tablocaltax1;
-			if ($numtax == 2) $arrayofvat = $tablocaltax2;
+			if ($numtax == 1) {
+				$arrayofvat = $tablocaltax1;
+			}
+			if ($numtax == 2) {
+				$arrayofvat = $tablocaltax2;
+			}
 
 			foreach ($arrayofvat[$key] as $k => $mt) {
 				if ($mt) {
@@ -637,10 +649,11 @@ if (empty($action) || $action == 'view') {
 					// Account
 					print "<td>";
 					$accountoshow = length_accountg($k);
-					if (($accountoshow == "") || $accountoshow == 'NotDefined')
-					{
+					if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 						print '<span class="error">'.$langs->trans("VATAccountNotDefined").'</span>';
-					} else print $accountoshow;
+					} else {
+						print $accountoshow;
+					}
 					print "</td>";
 					// Subledger account
 					print "<td>";

+ 116 - 106
htdocs/accountancy/journal/purchasesjournal.php

@@ -51,13 +51,16 @@ $date_endmonth = GETPOST('date_endmonth');
 $date_endday = GETPOST('date_endday');
 $date_endyear = GETPOST('date_endyear');
 $in_bookkeeping = GETPOST('in_bookkeeping');
-if ($in_bookkeeping == '') $in_bookkeeping = 'notyet';
+if ($in_bookkeeping == '') {
+	$in_bookkeeping = 'notyet';
+}
 
 $now = dol_now();
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
+}
 
 $hookmanager->initHooks(array('purchasesjournal'));
 $parameters = array();
@@ -78,8 +81,7 @@ $journal_label = $accountingjournalstatic->label;
 $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
 $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
 
-if (empty($date_startmonth) || empty($date_endmonth))
-{
+if (empty($date_startmonth) || empty($date_endmonth)) {
 	// Period by default on transfer
 	$dates = getDefaultDatesForTransfer();
 	$date_start = $dates['date_start'];
@@ -88,8 +90,7 @@ if (empty($date_startmonth) || empty($date_endmonth))
 	$pastmonth = $dates['pastmonth'];
 }
 
-if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) // We define date_start and date_end, only if we did not submit the form
-{
+if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) { // We define date_start and date_end, only if we did not submit the form
 	$date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
 	$date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
 }
@@ -111,19 +112,18 @@ if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
 } else {
 	$sql .= " AND f.type IN (".FactureFournisseur::TYPE_STANDARD.",".FactureFournisseur::TYPE_REPLACEMENT.",".FactureFournisseur::TYPE_CREDIT_NOTE.",".FactureFournisseur::TYPE_DEPOSIT.",".FactureFournisseur::TYPE_SITUATION.")";
 }
-if ($date_start && $date_end)
+if ($date_start && $date_end) {
 	$sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
+}
 // Define begin binding date
 if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
 	$sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
 }
 // Already in bookkeeping or not
-if ($in_bookkeeping == 'already')
-{
+if ($in_bookkeeping == 'already') {
 	$sql .= " AND f.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='supplier_invoice')";
 }
-if ($in_bookkeeping == 'notyet')
-{
+if ($in_bookkeeping == 'notyet') {
 	$sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='supplier_invoice')";
 }
 $sql .= " ORDER BY f.datef";
@@ -156,9 +156,9 @@ if ($result) {
 
 		$compta_prod = $obj->compte;
 		if (empty($compta_prod)) {
-			if ($obj->product_type == 0)
+			if ($obj->product_type == 0) {
 				$compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : 'NotDefined';
-			else {
+			} else {
 				$compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : 'NotDefined';
 			}
 		}
@@ -170,8 +170,7 @@ if ($result) {
 		$compta_counterpart_tva_npr = (!empty($conf->global->ACCOUNTING_COUNTERPART_VAT_NPR)) ? $conf->global->ACCOUNTING_COUNTERPART_VAT_NPR : 'NotDefined';
 
 		// Define array to display all VAT rates that use this accounting account $compta_tva
-		if (price2num($obj->tva_tx) || !empty($obj->vat_src_code))
-		{
+		if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
 			$def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '')] = (vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
 		}
 
@@ -189,17 +188,26 @@ if ($result) {
 		//$tabfac[$obj->rowid]["fk_facturefourndet"] = $obj->fdid;
 
 		// Avoid warnings
-		if (!isset($tabttc[$obj->rowid][$compta_soc])) $tabttc[$obj->rowid][$compta_soc] = 0;
-		if (!isset($tabht[$obj->rowid][$compta_prod])) $tabht[$obj->rowid][$compta_prod] = 0;
-		if (!isset($tabtva[$obj->rowid][$compta_tva])) $tabtva[$obj->rowid][$compta_tva] = 0;
-		if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
-		if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
+		if (!isset($tabttc[$obj->rowid][$compta_soc])) {
+			$tabttc[$obj->rowid][$compta_soc] = 0;
+		}
+		if (!isset($tabht[$obj->rowid][$compta_prod])) {
+			$tabht[$obj->rowid][$compta_prod] = 0;
+		}
+		if (!isset($tabtva[$obj->rowid][$compta_tva])) {
+			$tabtva[$obj->rowid][$compta_tva] = 0;
+		}
+		if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
+			$tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
+		}
+		if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
+			$tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
+		}
 
 		$tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc;
 		$tabht[$obj->rowid][$compta_prod] += $obj->total_ht;
 		$tabtva[$obj->rowid][$compta_tva] += $obj->total_tva;
-		if (!empty($line->tva_npr))	// Add an entry for counterpart
-		{
+		if (!empty($line->tva_npr)) {	// Add an entry for counterpart
 			$tabother[$obj->rowid][$compta_counterpart_tva_npr] += $obj->total_tva;
 		}
 		$tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
@@ -226,14 +234,14 @@ foreach ($tabfac as $key => $val) {		// Loop on each invoice
 	$sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
 	$sql .= " AND fd.total_ttc <> 0 AND fk_facture_fourn = ".$key;
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$obj = $db->fetch_object($resql);
-		if ($obj->nb > 0)
-		{
+		if ($obj->nb > 0) {
 			$errorforinvoice[$key] = 'somelinesarenotbound';
 		}
-	} else dol_print_error($db);
+	} else {
+		dol_print_error($db);
+	}
 }
 //var_dump($errorforinvoice);exit;
 
@@ -274,31 +282,29 @@ if ($action == 'writebookkeeping') {
 
 		// Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
 		$replacedinvoice = 0;
-		if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED)
-		{
+		if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
 			$replacedinvoice = 1;
 			$alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
-			if ($alreadydispatched) $replacedinvoice = 2;
+			if ($alreadydispatched) {
+				$replacedinvoice = 2;
+			}
 		}
 
 		// If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
-		if ($replacedinvoice == 1)
-		{
+		if ($replacedinvoice == 1) {
 			$db->rollback();
 			continue;
 		}
 
 		// Error if some lines are not binded/ready to be journalized
-		if ($errorforinvoice[$key] == 'somelinesarenotbound')
-		{
+		if ($errorforinvoice[$key] == 'somelinesarenotbound') {
 			$error++;
 			$errorforline++;
 			setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
 		}
 
 		// Thirdparty
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			foreach ($tabttc[$key] as $k => $mt) {
 				$bookkeeping = new BookKeeping($db);
 				$bookkeeping->doc_date = $val["date"];
@@ -331,8 +337,7 @@ if ($action == 'writebookkeeping') {
 
 				$result = $bookkeeping->create($user);
 				if ($result < 0) {
-					if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-					{
+					if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 						$error++;
 						$errorforline++;
 						$errorforinvoice[$key] = 'alreadyjournalized';
@@ -348,8 +353,7 @@ if ($action == 'writebookkeeping') {
 		}
 
 		// Product / Service
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			foreach ($tabht[$key] as $k => $mt) {
 				// get compte id and label
 				if ($accountingaccount->fetch(null, $k, true)) {
@@ -381,8 +385,7 @@ if ($action == 'writebookkeeping') {
 
 					$result = $bookkeeping->create($user);
 					if ($result < 0) {
-						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-						{
+						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 							$error++;
 							$errorforline++;
 							$errorforinvoice[$key] = 'alreadyjournalized';
@@ -400,14 +403,16 @@ if ($action == 'writebookkeeping') {
 
 		// VAT
 		// var_dump($tabtva);
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			$listoftax = array(0, 1, 2);
-			foreach ($listoftax as $numtax)
-			{
+			foreach ($listoftax as $numtax) {
 				$arrayofvat = $tabtva;
-				if ($numtax == 1) $arrayofvat = $tablocaltax1;
-				if ($numtax == 2) $arrayofvat = $tablocaltax2;
+				if ($numtax == 1) {
+					$arrayofvat = $tablocaltax1;
+				}
+				if ($numtax == 2) {
+					$arrayofvat = $tablocaltax2;
+				}
 
 				foreach ($arrayofvat[$key] as $k => $mt) {
 					if ($mt) {
@@ -442,8 +447,7 @@ if ($action == 'writebookkeeping') {
 
 						$result = $bookkeeping->create($user);
 						if ($result < 0) {
-							if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-							{
+							if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 								$error++;
 								$errorforline++;
 								$errorforinvoice[$key] = 'alreadyjournalized';
@@ -462,8 +466,7 @@ if ($action == 'writebookkeeping') {
 
 		// Counterpart of VAT for VAT NPR
 		// var_dump($tabother);
-		if (!$errorforline && is_array($tabother[$key]))
-		{
+		if (!$errorforline && is_array($tabother[$key])) {
 			foreach ($tabother[$key] as $k => $mt) {
 				if ($mt) {
 					$bookkeeping = new BookKeeping($db);
@@ -493,8 +496,7 @@ if ($action == 'writebookkeeping') {
 
 					$result = $bookkeeping->create($user);
 					if ($result < 0) {
-						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-						{
+						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 							$error++;
 							$errorforline++;
 							$errorforinvoice[$key] = 'alreadyjournalized';
@@ -511,22 +513,19 @@ if ($action == 'writebookkeeping') {
 		}
 
 		// Protection against a bug on lines before
-		if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT')))
-		{
+		if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
 			$error++;
 			$errorforline++;
 			$errorforinvoice[$key] = 'amountsnotbalanced';
 			setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
 		}
 
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			$db->commit();
 		} else {
 			$db->rollback();
 
-			if ($error >= 10)
-			{
+			if ($error >= 10) {
 				setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
 				break; // Break in the foreach
 			}
@@ -537,8 +536,7 @@ if ($action == 'writebookkeeping') {
 
 	if (empty($error) && count($tabpay) > 0) {
 		setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
-	} elseif (count($tabpay) == $error)
-	{
+	} elseif (count($tabpay) == $error) {
 		setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
 	} else {
 		setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
@@ -547,8 +545,7 @@ if ($action == 'writebookkeeping') {
 	$action = '';
 
 	// Must reload data, so we make a redirect
-	if (count($tabpay) != $error)
-	{
+	if (count($tabpay) != $error) {
 		$param = 'id_journal='.$id_journal;
 		$param .= '&date_startday='.$date_startday;
 		$param .= '&date_startmonth='.$date_startmonth;
@@ -579,8 +576,7 @@ if ($action == 'exportcsv') {		// ISO and not UTF8 !
 	$companystatic = new Fournisseur($db);
 	$invoicestatic = new FactureFournisseur($db);
 
-	foreach ($tabfac as $key => $val)
-	{
+	foreach ($tabfac as $key => $val) {
 		$companystatic->id = $tabcompany[$key]['id'];
 		$companystatic->name = $tabcompany[$key]['name'];
 		$companystatic->code_compta = $tabcompany[$key]['code_compta'];
@@ -600,16 +596,16 @@ if ($action == 'exportcsv') {		// ISO and not UTF8 !
 
 		// Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
 		$replacedinvoice = 0;
-		if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED)
-		{
+		if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
 			$replacedinvoice = 1;
 			$alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
-			if ($alreadydispatched) $replacedinvoice = 2;
+			if ($alreadydispatched) {
+				$replacedinvoice = 2;
+			}
 		}
 
 		// If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
-		if ($replacedinvoice == 1)
-		{
+		if ($replacedinvoice == 1) {
 			continue;
 		}
 
@@ -657,8 +653,12 @@ if ($action == 'exportcsv') {		// ISO and not UTF8 !
 		$listoftax = array(0, 1, 2);
 		foreach ($listoftax as $numtax) {
 			$arrayofvat = $tabtva;
-			if ($numtax == 1) $arrayofvat = $tablocaltax1;
-			if ($numtax == 2) $arrayofvat = $tablocaltax2;
+			if ($numtax == 1) {
+				$arrayofvat = $tablocaltax1;
+			}
+			if ($numtax == 2) {
+				$arrayofvat = $tablocaltax2;
+			}
 
 			foreach ($arrayofvat[$key] as $k => $mt) {
 				if ($mt) {
@@ -679,8 +679,7 @@ if ($action == 'exportcsv') {		// ISO and not UTF8 !
 			}
 
 			// VAT counterpart for NPR
-			if (is_array($tabother[$key]))
-			{
+			if (is_array($tabother[$key])) {
 				foreach ($tabother[$key] as $k => $mt) {
 					if ($mt) {
 						print '"'.$key.'"'.$sep;
@@ -733,12 +732,17 @@ if (empty($action) || $action == 'view') {
 		print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
 	}
 	print '<div class="tabsAction tabsActionNoBottom">';
-	if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
+	if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') {
+		print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
+	}
 	if (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') {
 		print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
 	} else {
-		if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
-		else print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
+		if ($in_bookkeeping == 'notyet') {
+			print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
+		} else {
+			print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
+		}
 	}
 	print '</div>';
 
@@ -781,8 +785,7 @@ if (empty($action) || $action == 'view') {
 	$invoicestatic = new FactureFournisseur($db);
 	$companystatic = new Fournisseur($db);
 
-	foreach ($tabfac as $key => $val)
-	{
+	foreach ($tabfac as $key => $val) {
 		$companystatic->id = $tabcompany[$key]['id'];
 		$companystatic->name = $tabcompany[$key]['name'];
 		$companystatic->code_compta = $tabcompany[$key]['code_compta'];
@@ -802,16 +805,16 @@ if (empty($action) || $action == 'view') {
 
 		// Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
 		$replacedinvoice = 0;
-		if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED)
-		{
+		if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
 			$replacedinvoice = 1;
 			$alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
-			if ($alreadydispatched) $replacedinvoice = 2;
+			if ($alreadydispatched) {
+				$replacedinvoice = 2;
+			}
 		}
 
 		// If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
-		if ($replacedinvoice == 1)
-		{
+		if ($replacedinvoice == 1) {
 			print '<tr class="oddeven">';
 			print "<!-- Replaced invoice -->";
 			print "<td>".$date."</td>";
@@ -831,8 +834,7 @@ if (empty($action) || $action == 'view') {
 
 			continue;
 		}
-		if ($errorforinvoice[$key] == 'somelinesarenotbound')
-		{
+		if ($errorforinvoice[$key] == 'somelinesarenotbound') {
 			print '<tr class="oddeven">';
 			print "<!-- Some lines are not bound -->";
 			print "<td>".$date."</td>";
@@ -860,18 +862,20 @@ if (empty($action) || $action == 'view') {
 			// Account
 			print "<td>";
 			$accountoshow = length_accounta($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER);
-			if (($accountoshow == "") || $accountoshow == 'NotDefined')
-			{
+			if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 				print '<span class="error">'.$langs->trans("MainAccountForSuppliersNotDefined").'</span>';
-			} else print $accountoshow;
+			} else {
+				print $accountoshow;
+			}
 			print '</td>';
 			// Subledger account
 			print "<td>";
 			$accountoshow = length_accounta($k);
-			if (($accountoshow == "") || $accountoshow == 'NotDefined')
-			{
+			if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 				print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
-			} else print $accountoshow;
+			} else {
+				print $accountoshow;
+			}
 			print '</td>';
 			print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("SubledgerAccount")."</td>";
 			print '<td class="right nowraponall">'.($mt < 0 ? price(-$mt) : '')."</td>";
@@ -891,10 +895,11 @@ if (empty($action) || $action == 'view') {
 			// Account
 			print "<td>";
 			$accountoshow = length_accountg($k);
-			if (($accountoshow == "") || $accountoshow == 'NotDefined')
-			{
+			if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 				print '<span class="error">'.$langs->trans("ProductAccountNotDefined").'</span>';
-			} else print $accountoshow;
+			} else {
+				print $accountoshow;
+			}
 			print "</td>";
 			// Subledger account
 			print "<td>";
@@ -911,8 +916,12 @@ if (empty($action) || $action == 'view') {
 		$listoftax = array(0, 1, 2);
 		foreach ($listoftax as $numtax) {
 			$arrayofvat = $tabtva;
-			if ($numtax == 1) $arrayofvat = $tablocaltax1;
-			if ($numtax == 2) $arrayofvat = $tablocaltax2;
+			if ($numtax == 1) {
+				$arrayofvat = $tablocaltax1;
+			}
+			if ($numtax == 2) {
+				$arrayofvat = $tablocaltax2;
+			}
 
 			foreach ($arrayofvat[$key] as $k => $mt) {
 				if ($mt) {
@@ -923,10 +932,11 @@ if (empty($action) || $action == 'view') {
 					// Account
 					print "<td>";
 					$accountoshow = length_accountg($k);
-					if (($accountoshow == "") || $accountoshow == 'NotDefined')
-					{
+					if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 						print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Purchase").')</span>';
-					} else print $accountoshow;
+					} else {
+						print $accountoshow;
+					}
 					print "</td>";
 					// Subledger account
 					print "<td>";
@@ -942,8 +952,7 @@ if (empty($action) || $action == 'view') {
 		}
 
 		// VAT counterpart for NPR
-		if (is_array($tabother[$key]))
-		{
+		if (is_array($tabother[$key])) {
 			foreach ($tabother[$key] as $k => $mt) {
 				if ($mt) {
 					print '<tr class="oddeven">';
@@ -953,10 +962,11 @@ if (empty($action) || $action == 'view') {
 					// Account
 					print '<td>';
 					$accountoshow = length_accountg($k);
-					if ($accountoshow == '' || $accountoshow == 'NotDefined')
-					{
+					if ($accountoshow == '' || $accountoshow == 'NotDefined') {
 						print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("NPR counterpart").'). Set ACCOUNTING_COUNTERPART_VAT_NPR to the subvention account</span>';
-					} else print $accountoshow;
+					} else {
+						print $accountoshow;
+					}
 					print '</td>';
 					// Subledger account
 					print "<td>";

+ 114 - 100
htdocs/accountancy/journal/sellsjournal.php

@@ -53,13 +53,16 @@ $date_endmonth = GETPOST('date_endmonth');
 $date_endday = GETPOST('date_endday');
 $date_endyear = GETPOST('date_endyear');
 $in_bookkeeping = GETPOST('in_bookkeeping');
-if ($in_bookkeeping == '') $in_bookkeeping = 'notyet';
+if ($in_bookkeeping == '') {
+	$in_bookkeeping = 'notyet';
+}
 
 $now = dol_now();
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
+}
 
 $hookmanager->initHooks(array('sellsjournal'));
 $parameters = array();
@@ -81,8 +84,7 @@ $journal_label = $accountingjournalstatic->label;
 $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
 $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
 
-if (empty($date_startmonth) || empty($date_endmonth))
-{
+if (empty($date_startmonth) || empty($date_endmonth)) {
 	// Period by default on transfer
 	$dates = getDefaultDatesForTransfer();
 	$date_start = $dates['date_start'];
@@ -91,8 +93,7 @@ if (empty($date_startmonth) || empty($date_endmonth))
 	$pastmonth = $dates['pastmonth'];
 }
 
-if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) // We define date_start and date_end, only if we did not submit the form
-{
+if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) { // We define date_start and date_end, only if we did not submit the form
 	$date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
 	$date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
 }
@@ -115,20 +116,19 @@ if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {	// Non common s
 	$sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
 }
 $sql .= " AND fd.product_type IN (0,1)";
-if ($date_start && $date_end)
+if ($date_start && $date_end) {
 	$sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
+}
 // Define begin binding date
 if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
 	$sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
 }
 // Already in bookkeeping or not
-if ($in_bookkeeping == 'already')
-{
+if ($in_bookkeeping == 'already') {
 	$sql .= " AND f.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
 	//	$sql .= " AND fd.rowid IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";		// Useless, we save one line for all products with same account
 }
-if ($in_bookkeeping == 'notyet')
-{
+if ($in_bookkeeping == 'notyet') {
 	$sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
 	// $sql .= " AND fd.rowid NOT IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";		// Useless, we save one line for all products with same account
 }
@@ -162,9 +162,9 @@ if ($result) {
 
 		$compta_prod = $obj->compte;
 		if (empty($compta_prod)) {
-			if ($obj->product_type == 0)
+			if ($obj->product_type == 0) {
 				$compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : 'NotDefined';
-			else {
+			} else {
 				$compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : 'NotDefined';
 			}
 		}
@@ -175,8 +175,7 @@ if ($result) {
 		$compta_localtax2 = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
 
 		// Define array to display all VAT rates that use this accounting account $compta_tva
-		if (price2num($obj->tva_tx) || !empty($obj->vat_src_code))
-		{
+		if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
 			$def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '')] = (vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
 		}
 
@@ -207,15 +206,27 @@ if ($result) {
 		//$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
 
 		// Avoid warnings
-		if (!isset($tabttc[$obj->rowid][$compta_soc])) $tabttc[$obj->rowid][$compta_soc] = 0;
-		if (!isset($tabht[$obj->rowid][$compta_prod])) $tabht[$obj->rowid][$compta_prod] = 0;
-		if (!isset($tabtva[$obj->rowid][$compta_tva])) $tabtva[$obj->rowid][$compta_tva] = 0;
-		if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
-		if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
+		if (!isset($tabttc[$obj->rowid][$compta_soc])) {
+			$tabttc[$obj->rowid][$compta_soc] = 0;
+		}
+		if (!isset($tabht[$obj->rowid][$compta_prod])) {
+			$tabht[$obj->rowid][$compta_prod] = 0;
+		}
+		if (!isset($tabtva[$obj->rowid][$compta_tva])) {
+			$tabtva[$obj->rowid][$compta_tva] = 0;
+		}
+		if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
+			$tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
+		}
+		if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
+			$tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
+		}
 
 		$tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
 		$tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
-		if (empty($line->tva_npr)) $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; // We ignore line if VAT is a NPR
+		if (empty($line->tva_npr)) {
+			$tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; // We ignore line if VAT is a NPR
+		}
 		$tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
 		$tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
 		$tabcompany[$obj->rowid] = array(
@@ -240,14 +251,14 @@ foreach ($tabfac as $key => $val) {		// Loop on each invoice
 	$sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
 	$sql .= " AND fd.total_ttc <> 0 AND fk_facture = ".$key;
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$obj = $db->fetch_object($resql);
-		if ($obj->nb > 0)
-		{
+		if ($obj->nb > 0) {
 			$errorforinvoice[$key] = 'somelinesarenotbound';
 		}
-	} else dol_print_error($db);
+	} else {
+		dol_print_error($db);
+	}
 }
 //var_dump($errorforinvoice);exit;
 
@@ -285,31 +296,29 @@ if ($action == 'writebookkeeping') {
 
 		// Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
 		$replacedinvoice = 0;
-		if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
-		{
+		if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
 			$replacedinvoice = 1;
 			$alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
-			if ($alreadydispatched) $replacedinvoice = 2;
+			if ($alreadydispatched) {
+				$replacedinvoice = 2;
+			}
 		}
 
 		// If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
-		if ($replacedinvoice == 1)
-		{
+		if ($replacedinvoice == 1) {
 			$db->rollback();
 			continue;
 		}
 
 		// Error if some lines are not binded/ready to be journalized
-		if ($errorforinvoice[$key] == 'somelinesarenotbound')
-		{
+		if ($errorforinvoice[$key] == 'somelinesarenotbound') {
 			$error++;
 			$errorforline++;
 			setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
 		}
 
 		// Thirdparty
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			foreach ($tabttc[$key] as $k => $mt) {
 				$bookkeeping = new BookKeeping($db);
 				$bookkeeping->doc_date = $val["date"];
@@ -342,8 +351,7 @@ if ($action == 'writebookkeeping') {
 
 				$result = $bookkeeping->create($user);
 				if ($result < 0) {
-					if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-					{
+					if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 						$error++;
 						$errorforline++;
 						$errorforinvoice[$key] = 'alreadyjournalized';
@@ -359,8 +367,7 @@ if ($action == 'writebookkeeping') {
 		}
 
 		// Product / Service
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			foreach ($tabht[$key] as $k => $mt) {
 				// get compte id and label
 				if ($accountingaccount->fetch(null, $k, true)) {
@@ -392,8 +399,7 @@ if ($action == 'writebookkeeping') {
 
 					$result = $bookkeeping->create($user);
 					if ($result < 0) {
-						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-						{
+						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 							$error++;
 							$errorforline++;
 							$errorforinvoice[$key] = 'alreadyjournalized';
@@ -410,14 +416,16 @@ if ($action == 'writebookkeeping') {
 		}
 
 		// VAT
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			$listoftax = array(0, 1, 2);
-			foreach ($listoftax as $numtax)
-			{
+			foreach ($listoftax as $numtax) {
 				$arrayofvat = $tabtva;
-				if ($numtax == 1) $arrayofvat = $tablocaltax1;
-				if ($numtax == 2) $arrayofvat = $tablocaltax2;
+				if ($numtax == 1) {
+					$arrayofvat = $tablocaltax1;
+				}
+				if ($numtax == 2) {
+					$arrayofvat = $tablocaltax2;
+				}
 
 				foreach ($arrayofvat[$key] as $k => $mt) {
 					if ($mt) {
@@ -452,8 +460,7 @@ if ($action == 'writebookkeeping') {
 
 						$result = $bookkeeping->create($user);
 						if ($result < 0) {
-			   				if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-							{
+							if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
 								$error++;
 								$errorforline++;
 								$errorforinvoice[$key] = 'alreadyjournalized';
@@ -471,22 +478,19 @@ if ($action == 'writebookkeeping') {
 		}
 
 		// Protection against a bug on lines before
-		if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT')))
-		{
+		if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
 			$error++;
 			$errorforline++;
 			$errorforinvoice[$key] = 'amountsnotbalanced';
 			setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
 		}
 
-		if (!$errorforline)
-		{
+		if (!$errorforline) {
 			$db->commit();
 		} else {
 			$db->rollback();
 
-			if ($error >= 10)
-			{
+			if ($error >= 10) {
 				setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
 				break; // Break in the foreach
 			}
@@ -506,8 +510,7 @@ if ($action == 'writebookkeeping') {
 	$action = '';
 
 	// Must reload data, so we make a redirect
-	if (count($tabpay) != $error)
-	{
+	if (count($tabpay) != $error) {
 		$param = 'id_journal='.$id_journal;
 		$param .= '&date_startday='.$date_startday;
 		$param .= '&date_startmonth='.$date_startmonth;
@@ -540,8 +543,7 @@ if ($action == 'exportcsv') {		// ISO and not UTF8 !
 	$companystatic = new Client($db);
 	$invoicestatic = new Facture($db);
 
-	foreach ($tabfac as $key => $val)
-	{
+	foreach ($tabfac as $key => $val) {
 		$companystatic->id = $tabcompany[$key]['id'];
 		$companystatic->name = $tabcompany[$key]['name'];
 		$companystatic->code_compta = $tabcompany[$key]['code_compta'];
@@ -559,16 +561,16 @@ if ($action == 'exportcsv') {		// ISO and not UTF8 !
 
 		// Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
 		$replacedinvoice = 0;
-		if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
-		{
+		if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
 			$replacedinvoice = 1;
 			$alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
-			if ($alreadydispatched) $replacedinvoice = 2;
+			if ($alreadydispatched) {
+				$replacedinvoice = 2;
+			}
 		}
 
 		// If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
-		if ($replacedinvoice == 1)
-		{
+		if ($replacedinvoice == 1) {
 			continue;
 		}
 
@@ -616,8 +618,12 @@ if ($action == 'exportcsv') {		// ISO and not UTF8 !
 		$listoftax = array(0, 1, 2);
 		foreach ($listoftax as $numtax) {
 			$arrayofvat = $tabtva;
-			if ($numtax == 1) $arrayofvat = $tablocaltax1;
-			if ($numtax == 2) $arrayofvat = $tablocaltax2;
+			if ($numtax == 1) {
+				$arrayofvat = $tablocaltax1;
+			}
+			if ($numtax == 2) {
+				$arrayofvat = $tablocaltax2;
+			}
 
 			foreach ($arrayofvat[$key] as $k => $mt) {
 				if ($mt) {
@@ -651,9 +657,9 @@ if (empty($action) || $action == 'view') {
 	$exportlink = '';
 	$builddate = dol_now();
 	$description .= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
-	if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
+	if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
 		$description .= $langs->trans("DepositsAreNotIncluded");
-	else {
+	} else {
 		$description .= $langs->trans("DepositsAreIncluded");
 	}
 
@@ -672,12 +678,17 @@ if (empty($action) || $action == 'view') {
 		print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
 	}
 	print '<div class="tabsAction tabsActionNoBottom">';
-	if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
+	if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') {
+		print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
+	}
 	if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
 		print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
 	} else {
-		if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
-		else print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
+		if ($in_bookkeeping == 'notyet') {
+			print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
+		} else {
+			print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
+		}
 	}
 	print '</div>';
 
@@ -720,8 +731,7 @@ if (empty($action) || $action == 'view') {
 	$companystatic = new Client($db);
 	$invoicestatic = new Facture($db);
 
-	foreach ($tabfac as $key => $val)
-	{
+	foreach ($tabfac as $key => $val) {
 		$companystatic->id = $tabcompany[$key]['id'];
 		$companystatic->name = $tabcompany[$key]['name'];
 		$companystatic->code_compta = $tabcompany[$key]['code_compta'];
@@ -739,16 +749,16 @@ if (empty($action) || $action == 'view') {
 
 		// Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
 		$replacedinvoice = 0;
-		if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
-		{
+		if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
 			$replacedinvoice = 1;
 			$alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
-			if ($alreadydispatched) $replacedinvoice = 2;
+			if ($alreadydispatched) {
+				$replacedinvoice = 2;
+			}
 		}
 
 		// If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
-		if ($replacedinvoice == 1)
-		{
+		if ($replacedinvoice == 1) {
 			print '<tr class="oddeven">';
 			print "<!-- Replaced invoice -->";
 			print "<td>".$date."</td>";
@@ -768,8 +778,7 @@ if (empty($action) || $action == 'view') {
 
 			continue;
 		}
-		if ($errorforinvoice[$key] == 'somelinesarenotbound')
-		{
+		if ($errorforinvoice[$key] == 'somelinesarenotbound') {
 			print '<tr class="oddeven">';
 			print "<!-- Some lines are not bound -->";
 			print "<td>".$date."</td>";
@@ -789,8 +798,7 @@ if (empty($action) || $action == 'view') {
 		}
 
 		// Third party
-		foreach ($tabttc[$key] as $k => $mt)
-		{
+		foreach ($tabttc[$key] as $k => $mt) {
 			print '<tr class="oddeven">';
 			print "<!-- Thirdparty -->";
 			print "<td>".$date."</td>";
@@ -798,18 +806,20 @@ if (empty($action) || $action == 'view') {
 			// Account
 			print "<td>";
 			$accountoshow = length_accounta($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER);
-			if (($accountoshow == "") || $accountoshow == 'NotDefined')
-			{
+			if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 				print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
-			} else print $accountoshow;
+			} else {
+				print $accountoshow;
+			}
 			print '</td>';
 			// Subledger account
 			print "<td>";
 			$accountoshow = length_accounta($k);
-			if (($accountoshow == "") || $accountoshow == 'NotDefined')
-			{
+			if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 				print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
-			} else print $accountoshow;
+			} else {
+				print $accountoshow;
+			}
 			print '</td>';
 			print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("SubledgerAccount")."</td>";
 			print '<td class="right nowraponall">'.($mt >= 0 ? price($mt) : '')."</td>";
@@ -818,8 +828,7 @@ if (empty($action) || $action == 'view') {
 		}
 
 		// Product / Service
-		foreach ($tabht[$key] as $k => $mt)
-		{
+		foreach ($tabht[$key] as $k => $mt) {
 			$accountingaccount = new AccountingAccount($db);
 			$accountingaccount->fetch(null, $k, true);
 
@@ -830,10 +839,11 @@ if (empty($action) || $action == 'view') {
 			// Account
 			print "<td>";
 			$accountoshow = length_accountg($k);
-			if (($accountoshow == "") || $accountoshow == 'NotDefined')
-			{
+			if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 				print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
-			} else print $accountoshow;
+			} else {
+				print $accountoshow;
+			}
 			print "</td>";
 			// Subledger account
 			print "<td>";
@@ -848,11 +858,14 @@ if (empty($action) || $action == 'view') {
 
 		// VAT
 		$listoftax = array(0, 1, 2);
-		foreach ($listoftax as $numtax)
-		{
+		foreach ($listoftax as $numtax) {
 			$arrayofvat = $tabtva;
-			if ($numtax == 1) $arrayofvat = $tablocaltax1;
-			if ($numtax == 2) $arrayofvat = $tablocaltax2;
+			if ($numtax == 1) {
+				$arrayofvat = $tablocaltax1;
+			}
+			if ($numtax == 2) {
+				$arrayofvat = $tablocaltax2;
+			}
 
 			foreach ($arrayofvat[$key] as $k => $mt) {
 				if ($mt) {
@@ -863,10 +876,11 @@ if (empty($action) || $action == 'view') {
 					// Account
 					print "<td>";
 					$accountoshow = length_accountg($k);
-					if (($accountoshow == "") || $accountoshow == 'NotDefined')
-					{
+					if (($accountoshow == "") || $accountoshow == 'NotDefined') {
 						print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Sale").')</span>';
-					} else print $accountoshow;
+					} else {
+						print $accountoshow;
+					}
 					print "</td>";
 					// Subledger account
 					print "<td>";

+ 8 - 8
htdocs/accountancy/supplier/card.php

@@ -42,19 +42,20 @@ $codeventil = GETPOST('codeventil', 'int');
 $id = GETPOST('id', 'int');
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
+}
 
 
 /*
  * Actions
  */
 
-if ($action == 'ventil' && $user->rights->accounting->bind->write)
-{
-	if (!$cancel)
-	{
-		if ($codeventil < 0) $codeventil = 0;
+if ($action == 'ventil' && $user->rights->accounting->bind->write) {
+	if (!$cancel) {
+		if ($codeventil < 0) {
+			$codeventil = 0;
+		}
 
 		$sql = " UPDATE ".MAIN_DB_PREFIX."facture_fourn_det";
 		$sql .= " SET fk_code_ventilation = ".$codeventil;
@@ -65,8 +66,7 @@ if ($action == 'ventil' && $user->rights->accounting->bind->write)
 			setEventMessages($db->lasterror(), null, 'errors');
 		} else {
 			setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
-			if ($backtopage)
-			{
+			if ($backtopage) {
 				header("Location: ".$backtopage);
 				exit();
 			}

+ 50 - 35
htdocs/accountancy/supplier/index.php

@@ -37,22 +37,26 @@ $langs->loadLangs(array("compta", "bills", "other", "main", "accountancy"));
 if (empty($conf->accounting->enabled)) {
 	accessforbidden();
 }
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->bind->write)
+}
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 
 $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
-if (GETPOST("year", 'int')) $year_start = GETPOST("year", 'int');
-else {
+if (GETPOST("year", 'int')) {
+	$year_start = GETPOST("year", 'int');
+} else {
 	$year_start = dol_print_date(dol_now(), '%Y');
-	if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year
+	if (dol_print_date(dol_now(), '%m') < $month_start) {
+		$year_start--; // If current month is lower that starting fiscal month, we start last year
+	}
 }
 $year_end = $year_start + 1;
 $month_end = $month_start - 1;
-if ($month_end < 1)
-{
+if ($month_end < 1) {
 	$month_end = 12;
 	$year_end--;
 }
@@ -70,8 +74,7 @@ $chartaccountcode = dol_getIdFromCode($db, $conf->global->CHARTOFACCOUNTS, 'acco
  * Actions
  */
 
-if ($action == 'clean' || $action == 'validatehistory')
-{
+if ($action == 'clean' || $action == 'validatehistory') {
 	// Clean database
 	$db->begin();
 	$sql1 = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det as fd";
@@ -177,15 +180,13 @@ if ($action == 'validatehistory') {
 				$suggestedaccountingaccountfor = '';
 			}
 
-			if ($objp->aarowid_suggest > 0)
-			{
+			if ($objp->aarowid_suggest > 0) {
 				$sqlupdate = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det";
 				$sqlupdate .= " SET fk_code_ventilation = ".$objp->aarowid_suggest;
 				$sqlupdate .= " WHERE fk_code_ventilation <= 0 AND product_type <= 2 AND rowid = ".$objp->rowid;
 
 				$resqlupdate = $db->query($sqlupdate);
-				if (!$resqlupdate)
-				{
+				if (!$resqlupdate) {
 					$error++;
 					setEventMessages($db->lasterror(), null, 'errors');
 					break;
@@ -196,8 +197,7 @@ if ($action == 'validatehistory') {
 		}
 	}
 
-	if ($error)
-	{
+	if ($error) {
 		$db->rollback();
 	} else {
 		$db->commit();
@@ -235,7 +235,9 @@ print '<tr class="liste_titre"><td width="200">'.$langs->trans("Account").'</td>
 print '<td width="200" class="left">'.$langs->trans("Label").'</td>';
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 }
 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -244,7 +246,9 @@ $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account
 $sql .= "  ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	$sql .= "  SUM(".$db->ifsql('MONTH(ff.datef)='.$j, 'ffd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 }
 $sql .= "  SUM(ffd.total_ht) as total";
@@ -270,16 +274,18 @@ if ($resql) {
 
 	while ($row = $db->fetch_row($resql)) {
 		print '<tr class="oddeven"><td>';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("Unknown");
-		} else print length_accountg($row[0]);
+		} else {
+			print length_accountg($row[0]);
+		}
 		print '</td>';
 		print '<td class="left">';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/supplier/list.php?search_year='.$y, $langs->transnoentitiesnoconv("ToBind"));
-		} else print $row[1];
+		} else {
+			print $row[1];
+		}
 		print '</td>';
 		for ($i = 2; $i <= 12; $i++) {
 			print '<td class="nowrap right">'.price($row[$i]).'</td>';
@@ -308,7 +314,9 @@ print '<tr class="liste_titre"><td width="200">'.$langs->trans("Account").'</td>
 print '<td width="200" class="left">'.$langs->trans("Label").'</td>';
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 }
 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -317,7 +325,9 @@ $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account
 $sql .= "  ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
 for ($i = 1; $i <= 12; $i++) {
 	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-	if ($j > 12) $j -= 12;
+	if ($j > 12) {
+		$j -= 12;
+	}
 	$sql .= "  SUM(".$db->ifsql('MONTH(ff.datef)='.$j, 'ffd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 }
 $sql .= "  SUM(ffd.total_ht) as total";
@@ -343,16 +353,18 @@ if ($resql) {
 
 	while ($row = $db->fetch_row($resql)) {
 		print '<tr class="oddeven"><td>';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("Unknown");
-		} else print length_accountg($row[0]);
+		} else {
+			print length_accountg($row[0]);
+		}
 		print '</td>';
 		print '<td class="left">';
-		if ($row[0] == 'tobind')
-		{
+		if ($row[0] == 'tobind') {
 			print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/supplier/list.php?search_year='.$y, $langs->transnoentitiesnoconv("ToBind"));
-		} else print $row[1];
+		} else {
+			print $row[1];
+		}
 		print '</td>';
 		for ($i = 2; $i <= 12; $i++) {
 			print '<td class="nowrap right">'.price($row[$i]).'</td>';
@@ -370,8 +382,7 @@ print '</div>';
 
 
 
-if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. Why showing a report that should rely on result of this step ?
-{
+if ($conf->global->MAIN_FEATURES_LEVEL > 0) { // This part of code looks strange. Why showing a report that should rely on result of this step ?
 	print '<br>';
 	print '<br>';
 
@@ -383,7 +394,9 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange.
 	print '<tr class="liste_titre"><td width="400" class="left">'.$langs->trans("Total").'</td>';
 	for ($i = 1; $i <= 12; $i++) {
 		$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-		if ($j > 12) $j -= 12;
+		if ($j > 12) {
+			$j -= 12;
+		}
 		print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
 	}
 	print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
@@ -391,7 +404,9 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange.
 	$sql = "SELECT '".$db->escape($langs->trans("CAHTF"))."' AS label,";
 	for ($i = 1; $i <= 12; $i++) {
 		$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
-		if ($j > 12) $j -= 12;
+		if ($j > 12) {
+			$j -= 12;
+		}
 		$sql .= "  SUM(".$db->ifsql('MONTH(ff.datef)='.$j, 'ffd.total_ht', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
 	}
 	$sql .= "  SUM(ffd.total_ht) as total";

+ 90 - 47
htdocs/accountancy/supplier/lines.php

@@ -65,12 +65,15 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0) $page = 0;
+if (empty($page) || $page < 0) {
+	$page = 0;
+}
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield)
+if (!$sortfield) {
 	$sortfield = "f.datef, f.ref, l.rowid";
+}
 if (!$sortorder) {
 	if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE > 0) {
 		$sortorder = "DESC";
@@ -78,10 +81,12 @@ if (!$sortorder) {
 }
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->bind->write)
+}
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 $formaccounting = new FormAccounting($db);
 
@@ -91,8 +96,7 @@ $formaccounting = new FormAccounting($db);
  */
 
 // Purge search criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 	$search_societe = '';
 	$search_lineid = '';
 	$search_ref = '';
@@ -112,15 +116,13 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
 if (is_array($changeaccount) && count($changeaccount) > 0) {
 	$error = 0;
 
-	if (!(GETPOST('account_parent', 'int') >= 0))
-	{
+	if (!(GETPOST('account_parent', 'int') >= 0)) {
 		$error++;
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Account")), null, 'errors');
 	}
 
 
-	if (!$error)
-	{
+	if (!$error) {
 		$db->begin();
 
 		$sql1 = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det as l";
@@ -224,16 +226,23 @@ $sql .= dolSqlDateFilter('f.datef', $search_day, $search_month, $search_year);
 if (strlen(trim($search_country))) {
 	$arrayofcode = getCountriesInEEC();
 	$country_code_in_EEC = $country_code_in_EEC_without_me = '';
-	foreach ($arrayofcode as $key => $value)
-	{
+	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 ($value != $mysoc->country_code) {
+			$country_code_in_EEC_without_me .= ($country_code_in_EEC_without_me ? "," : "")."'".$value."'";
+		}
+	}
+	if ($search_country == 'special_allnotme') {
+		$sql .= " AND co.code <> '".$db->escape($mysoc->country_code)."'";
+	} elseif ($search_country == 'special_eec') {
+		$sql .= " AND co.code IN (".$country_code_in_EEC.")";
+	} elseif ($search_country == 'special_eecnotme') {
+		$sql .= " AND co.code IN (".$country_code_in_EEC_without_me.")";
+	} elseif ($search_country == 'special_noteec') {
+		$sql .= " AND co.code NOT IN (".$country_code_in_EEC.")";
+	} else {
+		$sql .= natural_search("co.code", $search_country);
 	}
-	if ($search_country == 'special_allnotme')     $sql .= " AND co.code <> '".$db->escape($mysoc->country_code)."'";
-	elseif ($search_country == 'special_eec')      $sql .= " AND co.code IN (".$country_code_in_EEC.")";
-	elseif ($search_country == 'special_eecnotme') $sql .= " AND co.code IN (".$country_code_in_EEC_without_me.")";
-	elseif ($search_country == 'special_noteec')   $sql .= " AND co.code NOT IN (".$country_code_in_EEC.")";
-	else $sql .= natural_search("co.code", $search_country);
 }
 if (strlen(trim($search_tvaintra))) {
 	$sql .= natural_search("s.tva_intra", $search_tvaintra);
@@ -249,12 +258,10 @@ $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$result = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($result);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -269,24 +276,54 @@ if ($result) {
 	$i = 0;
 
 	$param = '';
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-	if ($search_societe)	$param .= "&search_societe=".urlencode($search_societe);
-	if ($search_invoice)	$param .= "&search_invoice=".urlencode($search_invoice);
-	if ($search_ref)		$param .= "&search_ref=".urlencode($search_ref);
-	if ($search_label)		$param .= "&search_label=".urlencode($search_label);
-	if ($search_desc)		$param .= "&search_desc=".urlencode($search_desc);
-	if ($search_account)	$param .= "&search_account=".urlencode($search_account);
-	if ($search_vat)		$param .= "&search_vat=".urlencode($search_vat);
-	if ($search_day)        $param .= '&search_day='.urlencode($search_day);
-	if ($search_month)      $param .= '&search_month='.urlencode($search_month);
-	if ($search_year)       $param .= '&search_year='.urlencode($search_year);
-	if ($search_country) 	$param .= "&search_country=".urlencode($search_country);
-	if ($search_tvaintra)	$param .= "&search_tvaintra=".urlencode($search_tvaintra);
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.urlencode($limit);
+	}
+	if ($search_societe) {
+		$param .= "&search_societe=".urlencode($search_societe);
+	}
+	if ($search_invoice) {
+		$param .= "&search_invoice=".urlencode($search_invoice);
+	}
+	if ($search_ref) {
+		$param .= "&search_ref=".urlencode($search_ref);
+	}
+	if ($search_label) {
+		$param .= "&search_label=".urlencode($search_label);
+	}
+	if ($search_desc) {
+		$param .= "&search_desc=".urlencode($search_desc);
+	}
+	if ($search_account) {
+		$param .= "&search_account=".urlencode($search_account);
+	}
+	if ($search_vat) {
+		$param .= "&search_vat=".urlencode($search_vat);
+	}
+	if ($search_day) {
+		$param .= '&search_day='.urlencode($search_day);
+	}
+	if ($search_month) {
+		$param .= '&search_month='.urlencode($search_month);
+	}
+	if ($search_year) {
+		$param .= '&search_year='.urlencode($search_year);
+	}
+	if ($search_country) {
+		$param .= "&search_country=".urlencode($search_country);
+	}
+	if ($search_tvaintra) {
+		$param .= "&search_tvaintra=".urlencode($search_tvaintra);
+	}
 
 	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'."\n";
 	print '<input type="hidden" name="action" value="ventil">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
@@ -311,9 +348,11 @@ if ($result) {
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="'.dol_escape_htmltag($search_invoice).'"></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_label" value="'.dol_escape_htmltag($search_label).'"></td>';
 	print '<td class="liste_titre center nowraponall">';
-   	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.$search_day.'">';
-   	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
-   	$formother->select_year($search_year, 'search_year', 1, 20, 5);
+	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) {
+		print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.$search_day.'">';
+	}
+	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
+	$formother->select_year($search_year, 'search_year', 1, 20, 5);
 	print '</td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref" value="'.dol_escape_htmltag($search_ref).'"></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_desc" value="'.dol_escape_htmltag($search_desc).'"></td>';
@@ -355,8 +394,7 @@ if ($result) {
 	$accountingaccountstatic = new AccountingAccount($db);
 
 	$i = 0;
-	while ($i < min($num_lines, $limit))
-	{
+	while ($i < min($num_lines, $limit)) {
 		$objp = $db->fetch_object($result);
 
 		$facturefournisseur_static->ref = $objp->ref;
@@ -405,9 +443,15 @@ if ($result) {
 
 		// Ref Product
 		print '<td class="tdoverflowmax100">';
-		if ($productstatic->id > 0) print $productstatic->getNomUrl(1);
-		if ($productstatic->id > 0 && $objp->product_label) print '<br>';
-		if ($objp->product_label) print '<span class="opacitymedium">'.$objp->product_label.'</span>';
+		if ($productstatic->id > 0) {
+			print $productstatic->getNomUrl(1);
+		}
+		if ($productstatic->id > 0 && $objp->product_label) {
+			print '<br>';
+		}
+		if ($objp->product_label) {
+			print '<span class="opacitymedium">'.$objp->product_label.'</span>';
+		}
 		print '</td>';
 
 		print '<td class="tdoverflowonsmartphone">';
@@ -425,8 +469,7 @@ if ($result) {
 
 		// Country
 		print '<td>';
-		if ($objp->country_code)
-		{
+		if ($objp->country_code) {
 			print $langs->trans("Country".$objp->country_code).' ('.$objp->country_code.')';
 		}
 		print '</td>';

+ 124 - 63
htdocs/accountancy/supplier/list.php

@@ -73,12 +73,15 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0) { $page = 0; }
+if (empty($page) || $page < 0) {
+	$page = 0;
+}
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield)
+if (!$sortfield) {
 	$sortfield = "f.datef, f.ref, l.rowid";
+}
 if (!$sortorder) {
 	if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO > 0) {
 		$sortorder = "DESC";
@@ -86,10 +89,12 @@ if (!$sortorder) {
 }
 
 // Security check
-if ($user->socid > 0)
+if ($user->socid > 0) {
 	accessforbidden();
-if (!$user->rights->accounting->bind->write)
+}
+if (!$user->rights->accounting->bind->write) {
 	accessforbidden();
+}
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 $hookmanager->initHooks(array('accountancysupplierlist'));
@@ -107,18 +112,22 @@ $chartaccountcode = dol_getIdFromCode($db, $conf->global->CHARTOFACCOUNTS, 'acco
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	// Purge search criteria
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
-	{
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
 		$search_societe = '';
 		$search_lineid = '';
 		$search_ref = '';
@@ -160,8 +169,7 @@ if ($massaction == 'ventil') {
 			$monId = $maLigneCourante[0];
 			$monCompte = GETPOST('codeventil'.$monId);
 
-			if ($monCompte <= 0)
-			{
+			if ($monCompte <= 0) {
 				$msg .= '<div><span style="color:red">'.$langs->trans("Lineofinvoice").' '.$monId.' - '.$langs->trans("NoAccountSelected").'</span></div>';
 				$ko++;
 			} else {
@@ -200,8 +208,7 @@ $formother = new FormOther($db);
 
 llxHeader('', $langs->trans("SuppliersVentilation"));
 
-if (empty($chartaccountcode))
-{
+if (empty($chartaccountcode)) {
 	print $langs->trans("ErrorChartOfAccountSystemNotSelected");
 	// End of page
 	llxFooter();
@@ -269,16 +276,23 @@ $sql .= dolSqlDateFilter('f.datef', $search_day, $search_month, $search_year);
 if (strlen(trim($search_country))) {
 	$arrayofcode = getCountriesInEEC();
 	$country_code_in_EEC = $country_code_in_EEC_without_me = '';
-	foreach ($arrayofcode as $key => $value)
-	{
+	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 ($value != $mysoc->country_code) {
+			$country_code_in_EEC_without_me .= ($country_code_in_EEC_without_me ? "," : "")."'".$value."'";
+		}
+	}
+	if ($search_country == 'special_allnotme') {
+		$sql .= " AND co.code <> '".$db->escape($mysoc->country_code)."'";
+	} elseif ($search_country == 'special_eec') {
+		$sql .= " AND co.code IN (".$country_code_in_EEC.")";
+	} elseif ($search_country == 'special_eecnotme') {
+		$sql .= " AND co.code IN (".$country_code_in_EEC_without_me.")";
+	} elseif ($search_country == 'special_noteec') {
+		$sql .= " AND co.code NOT IN (".$country_code_in_EEC.")";
+	} else {
+		$sql .= natural_search("co.code", $search_country);
 	}
-	if ($search_country == 'special_allnotme')     $sql .= " AND co.code <> '".$db->escape($mysoc->country_code)."'";
-	elseif ($search_country == 'special_eec')      $sql .= " AND co.code IN (".$country_code_in_EEC.")";
-	elseif ($search_country == 'special_eecnotme') $sql .= " AND co.code IN (".$country_code_in_EEC_without_me.")";
-	elseif ($search_country == 'special_noteec')   $sql .= " AND co.code NOT IN (".$country_code_in_EEC.")";
-	else $sql .= natural_search("co.code", $search_country);
 }
 if (strlen(trim($search_tvaintra))) {
 	$sql .= natural_search("s.tva_intra", $search_tvaintra);
@@ -299,12 +313,10 @@ $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$result = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($result);
-	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 then paging size (filtering), goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
@@ -322,21 +334,51 @@ if ($result) {
 	$arrayofselected = is_array($toselect) ? $toselect : array();
 
 	$param = '';
-	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-	if ($search_societe)     $param .= '&search_societe='.urlencode($search_societe);
-	if ($search_lineid)      $param .= '&search_lineid='.urlencode($search_lineid);
-	if ($search_day)         $param .= '&search_day='.urlencode($search_day);
-	if ($search_month)       $param .= '&search_month='.urlencode($search_month);
-	if ($search_year)        $param .= '&search_year='.urlencode($search_year);
-	if ($search_invoice)     $param .= '&search_invoice='.urlencode($search_invoice);
-	if ($search_ref)         $param .= '&search_ref='.urlencode($search_ref);
-	if ($search_label)       $param .= '&search_label='.urlencode($search_label);
-	if ($search_desc)        $param .= '&search_desc='.urlencode($search_desc);
-	if ($search_amount)      $param .= '&search_amount='.urlencode($search_amount);
-	if ($search_vat)         $param .= '&search_vat='.urlencode($search_vat);
-	if ($search_country) 	 $param .= "&search_country=".urlencode($search_country);
-	if ($search_tvaintra)	 $param .= "&search_tvaintra=".urlencode($search_tvaintra);
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+		$param .= '&contextpage='.urlencode($contextpage);
+	}
+	if ($limit > 0 && $limit != $conf->liste_limit) {
+		$param .= '&limit='.urlencode($limit);
+	}
+	if ($search_societe) {
+		$param .= '&search_societe='.urlencode($search_societe);
+	}
+	if ($search_lineid) {
+		$param .= '&search_lineid='.urlencode($search_lineid);
+	}
+	if ($search_day) {
+		$param .= '&search_day='.urlencode($search_day);
+	}
+	if ($search_month) {
+		$param .= '&search_month='.urlencode($search_month);
+	}
+	if ($search_year) {
+		$param .= '&search_year='.urlencode($search_year);
+	}
+	if ($search_invoice) {
+		$param .= '&search_invoice='.urlencode($search_invoice);
+	}
+	if ($search_ref) {
+		$param .= '&search_ref='.urlencode($search_ref);
+	}
+	if ($search_label) {
+		$param .= '&search_label='.urlencode($search_label);
+	}
+	if ($search_desc) {
+		$param .= '&search_desc='.urlencode($search_desc);
+	}
+	if ($search_amount) {
+		$param .= '&search_amount='.urlencode($search_amount);
+	}
+	if ($search_vat) {
+		$param .= '&search_vat='.urlencode($search_vat);
+	}
+	if ($search_country) {
+		$param .= "&search_country=".urlencode($search_country);
+	}
+	if ($search_tvaintra) {
+		$param .= "&search_tvaintra=".urlencode($search_tvaintra);
+	}
 
 	$arrayofmassactions = array(
 		'ventil'=>$langs->trans("Ventilate")
@@ -349,7 +391,9 @@ if ($result) {
 
 	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'."\n";
 	print '<input type="hidden" name="action" value="ventil">';
-	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	if ($optioncss != '') {
+		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	}
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
@@ -360,7 +404,9 @@ if ($result) {
 
 	print '<span class="opacitymedium">'.$langs->trans("DescVentilTodoCustomer").'</span></br><br>';
 
-	if ($msg) print $msg.'<br>';
+	if ($msg) {
+		print $msg.'<br>';
+	}
 
 	$moreforfilter = '';
 
@@ -373,9 +419,11 @@ if ($result) {
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="'.dol_escape_htmltag($search_invoice).'"></td>';
 	//print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_label" value="'.dol_escape_htmltag($search_label).'"></td>';
 	print '<td class="liste_titre center nowraponall minwidth100imp">';
-   	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.$search_day.'">';
-   	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
-   	$formother->select_year($search_year, 'search_year', 1, 20, 5);
+	if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) {
+		print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_day" value="'.$search_day.'">';
+	}
+	print '<input class="flat valignmiddle maxwidth25" type="text" maxlength="2" name="search_month" value="'.$search_month.'">';
+	$formother->select_year($search_year, 'search_year', 1, 20, 5);
 	print '</td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref" value="'.dol_escape_htmltag($search_ref).'"></td>';
 	print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_desc" value="'.dol_escape_htmltag($search_desc).'"></td>';
@@ -411,7 +459,9 @@ if ($result) {
 	print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', '', '', 'nowraponall ');
 	print_liste_field_titre("IntoAccount", '', '', '', '', '', '', '', 'center ');
 	$checkpicto = '';
-	if ($massactionbutton) $checkpicto = $form->showCheckAddButtons('checkforselect', 1);
+	if ($massactionbutton) {
+		$checkpicto = $form->showCheckAddButtons('checkforselect', 1);
+	}
 	print_liste_field_titre($checkpicto, '', '', '', '', '', '', '', 'center ');
 	print "</tr>\n";
 
@@ -496,7 +546,9 @@ if ($result) {
 				}
 			}
 		}
-		if ($objp->code_sell_l == -1) $objp->code_sell_l = '';
+		if ($objp->code_sell_l == -1) {
+			$objp->code_sell_l = '';
+		}
 
 		// Level 2: Search suggested account for product/service (similar code exists in page index.php to make automatic binding)
 		$suggestedaccountingaccountfor = '';
@@ -528,7 +580,9 @@ if ($result) {
 		} else {
 			$code_buy_p_notset = 'color:orange';
 		}
-		if (empty($objp->code_buy_l) && empty($objp->code_buy_p)) $code_buy_p_notset = 'color:red';
+		if (empty($objp->code_buy_l) && empty($objp->code_buy_p)) {
+			$code_buy_p_notset = 'color:red';
+		}
 
 		// $objp->code_buy_l is now default code of product/service
 		// $objp->code_buy_p is now code of product/service
@@ -551,9 +605,12 @@ if ($result) {
 
 		// Ref Product
 		print '<td class="tdoverflowmax150">';
-		if ($product_static->id > 0)
+		if ($product_static->id > 0) {
 			print $product_static->getNomUrl(1);
-		if ($objp->product_label) print '<br><span class="opacitymedium small">'.$objp->product_label.'</span>';
+		}
+		if ($objp->product_label) {
+			print '<br><span class="opacitymedium small">'.$objp->product_label.'</span>';
+		}
 		print '</td>';
 
 		// Description
@@ -568,8 +625,9 @@ if ($result) {
 		print '</td>';
 
 		// Vat rate
-		if ($objp->vat_tx_l != $objp->vat_tx_p)
+		if ($objp->vat_tx_l != $objp->vat_tx_p) {
 			$code_vat_differ = 'font-weight:bold; text-decoration:blink; color:red';
+		}
 		print '<td style="'.$code_vat_differ.'" class="right">';
 		print vatrate($objp->tva_tx_line.($objp->vat_src_code ? ' ('.$objp->vat_src_code.')' : ''));
 		print '</td>';
@@ -590,17 +648,22 @@ if ($result) {
 		print '<td>';
 		$s = '<span class="small">1. '.(($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': </span>';
 		$shelp = '';
-		if ($suggestedaccountingaccountbydefaultfor == 'eec') $shelp .= $langs->trans("SaleEEC");
-		elseif ($suggestedaccountingaccountbydefaultfor == 'export') $shelp .= $langs->trans("SaleExport");
+		if ($suggestedaccountingaccountbydefaultfor == 'eec') {
+			$shelp .= $langs->trans("SaleEEC");
+		} elseif ($suggestedaccountingaccountbydefaultfor == 'export') {
+			$shelp .= $langs->trans("SaleExport");
+		}
 		$s .= ($objp->code_buy_l > 0 ? length_accountg($objp->code_buy_l) : '<span style="'.$code_buy_p_notset.'">'.$langs->trans("NotDefined").'</span>');
 		print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1);
-		if ($objp->product_id > 0)
-		{
+		if ($objp->product_id > 0) {
 			print '<br>';
 			$s = '<span class="small">2. '.(($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': </span>';
 			$shelp = '';
-			if ($suggestedaccountingaccountfor == 'eec') $shelp = $langs->trans("SaleEEC");
-			elseif ($suggestedaccountingaccountfor == 'export') $shelp = $langs->trans("SaleExport");
+			if ($suggestedaccountingaccountfor == 'eec') {
+				$shelp = $langs->trans("SaleEEC");
+			} elseif ($suggestedaccountingaccountfor == 'export') {
+				$shelp = $langs->trans("SaleExport");
+			}
 			$s .= (empty($objp->code_buy_p) ? '<span style="'.$code_buy_p_notset.'">'.$langs->trans("NotDefined").'</span>' : length_accountg($objp->code_buy_p));
 			print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1);
 		} else {
@@ -620,10 +683,8 @@ if ($result) {
 		// Suggested accounting account
 		print '<td>';
 		$suggestedid = $objp->aarowid_suggest;
-		if (empty($suggestedid) && empty($objp->code_buy_p) && !empty($objp->code_buy_l) && empty($conf->global->ACCOUNTANCY_DO_NOT_AUTOFILL_ACCOUNT_WITH_GENERIC))
-		{
-			if (empty($accountingaccount_codetotid_cache[$objp->code_buy_l]))
-			{
+		if (empty($suggestedid) && empty($objp->code_buy_p) && !empty($objp->code_buy_l) && empty($conf->global->ACCOUNTANCY_DO_NOT_AUTOFILL_ACCOUNT_WITH_GENERIC)) {
+			if (empty($accountingaccount_codetotid_cache[$objp->code_buy_l])) {
 				$tmpaccount = new AccountingAccount($db);
 				$tmpaccount->fetch(0, $objp->code_buy_l, 1);
 				if ($tmpaccount->id > 0) {

+ 6 - 8
htdocs/accountancy/tpl/export_journal.tpl.php

@@ -17,8 +17,7 @@
  */
 
 // Protection to avoid direct call of template
-if (empty($conf) || !is_object($conf))
-{
+if (empty($conf) || !is_object($conf)) {
 	print "Error, template page can't be called as URL";
 	exit;
 }
@@ -37,11 +36,9 @@ header('Content-Type: text/csv');
 include_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancyexport.class.php';
 $accountancyexport = new AccountancyExport($db);
 
-if ($accountancyexport->getFormatCode($formatexportset) == $accountancyexport::$EXPORT_TYPE_FEC && $type_export == "general_ledger") // Specific filename for FEC model export into the general ledger
-{
+if ($accountancyexport->getFormatCode($formatexportset) == $accountancyexport::$EXPORT_TYPE_FEC && $type_export == "general_ledger") { // Specific filename for FEC model export into the general ledger
 	// FEC format is defined here: https://www.legifrance.gouv.fr/affichCodeArticle.do?idArticle=LEGIARTI000027804775&cidTexte=LEGITEXT000006069583&dateTexte=20130802&oldAction=rechCodeArticle
-	if (empty($search_date_end))
-	{
+	if (empty($search_date_end)) {
 		// TODO Get the max date into bookeeping table
 		$search_date_end = dol_now();
 	}
@@ -49,8 +46,9 @@ if ($accountancyexport->getFormatCode($formatexportset) == $accountancyexport::$
 	$tmparray = dol_getdate($datetouseforfilename);
 	$fiscalmonth = empty($conf->global->SOCIETE_FISCAL_MONTH_START) ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START;
 	// Define end of month to use
-	if ($tmparray['mon'] <= $fiscalmonth) $tmparray['mon'] = $fiscalmonth;
-	else {
+	if ($tmparray['mon'] <= $fiscalmonth) {
+		$tmparray['mon'] = $fiscalmonth;
+	} else {
 		$tmparray['mon'] = $fiscalmonth;
 		$tmparray['year']++;
 	}

+ 84 - 104
htdocs/admin/workstation.php

@@ -17,7 +17,7 @@
  */
 
 /**
- * \file    workstation/admin/setup.php
+ * \file    htdocs/admin/workstation.php
  * \ingroup workstation
  * \brief   Workstation setup page.
  */
@@ -31,10 +31,12 @@ require_once DOL_DOCUMENT_ROOT . '/workstation/lib/workstation.lib.php';
 //require_once "../class/myclass.class.php";
 
 // Translations
-$langs->loadLangs(array("admin", "workstation@workstation"));
+$langs->loadLangs(array("admin", "workstation"));
 
 // Access control
-if (!$user->admin) accessforbidden();
+if (!$user->admin) {
+	accessforbidden();
+}
 
 // Parameters
 $action = GETPOST('action', 'aZ09');
@@ -55,28 +57,28 @@ $setupnotempty = 0;
  * Actions
  */
 
-if ((float) DOL_VERSION >= 6)
-{
+if ((float) DOL_VERSION >= 6) {
 	include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
 }
 
-if ($action == 'updateMask')
-{
+if ($action == 'updateMask') {
 	$maskconstorder = GETPOST('maskconstWorkstation', 'alpha');
 	$maskorder = GETPOST('maskWorkstation', 'alpha');
 
-	if ($maskconstorder) $res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity);
+	if ($maskconstorder) {
+		$res = dolibarr_set_const($db, $maskconstorder, $maskorder, 'chaine', 0, '', $conf->entity);
+	}
 
-	if (!($res > 0)) $error++;
+	if (!($res > 0)) {
+		$error++;
+	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
 	} else {
 		setEventMessages($langs->trans("Error"), null, 'errors');
 	}
-} elseif ($action == 'specimen')
-{
+} elseif ($action == 'specimen') {
 	$modele = GETPOST('module', 'alpha');
 	$tmpobjectkey = GETPOST('object');
 
@@ -86,25 +88,21 @@ if ($action == 'updateMask')
 	// Search template files
 	$file = ''; $classname = ''; $filefound = 0;
 	$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
-	foreach ($dirmodels as $reldir)
-	{
+	foreach ($dirmodels as $reldir) {
 		$file = dol_buildpath($reldir."core/modules/workstation/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".modules.php", 0);
-		if (file_exists($file))
-		{
+		if (file_exists($file)) {
 			$filefound = 1;
 			$classname = "pdf_".$modele;
 			break;
 		}
 	}
 
-	if ($filefound)
-	{
+	if ($filefound) {
 		require_once $file;
 
 		$module = new $classname($db);
 
-		if ($module->write_file($tmpobject, $langs) > 0)
-		{
+		if ($module->write_file($tmpobject, $langs) > 0) {
 			header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf");
 			return;
 		} else {
@@ -115,31 +113,24 @@ if ($action == 'updateMask')
 		setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors');
 		dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR);
 	}
-}
-
-// Activate a model
-elseif ($action == 'set')
-{
+} elseif ($action == 'set') {
+	// Activate a model
 	$ret = addDocumentModel($value, $type, $label, $scandir);
-} elseif ($action == 'del')
-{
+} elseif ($action == 'del') {
 	$tmpobjectkey = GETPOST('object');
 
 	$ret = delDocumentModel($value, $type);
-	if ($ret > 0)
-	{
+	if ($ret > 0) {
 		$constforval = strtoupper($tmpobjectkey).'_ADDON_PDF';
-		if ($conf->global->$constforval == "$value") dolibarr_del_const($db, $constforval, $conf->entity);
+		if ($conf->global->$constforval == "$value") {
+			dolibarr_del_const($db, $constforval, $conf->entity);
+		}
 	}
-}
-
-// Set default model
-elseif ($action == 'setdoc')
-{
+} elseif ($action == 'setdoc') {
+	// Set default model
 	$tmpobjectkey = GETPOST('object');
 	$constforval = strtoupper($tmpobjectkey).'_ADDON_PDF';
-	if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity))
-	{
+	if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity)) {
 		// The constant that was read before the new set
 		// We therefore requires a variable to have a coherent view
 		$conf->global->$constforval = $value;
@@ -147,12 +138,10 @@ elseif ($action == 'setdoc')
 
 	// On active le modele
 	$ret = delDocumentModel($value, $type);
-	if ($ret > 0)
-	{
+	if ($ret > 0) {
 		$ret = addDocumentModel($value, $type, $label, $scandir);
 	}
-} elseif ($action == 'setmod')
-{
+} elseif ($action == 'setmod') {
 	// TODO Check if numbering module chosen can be activated
 	// by calling method canBeActivated
 	$tmpobjectkey = GETPOST('object');
@@ -186,8 +175,7 @@ print dol_get_fiche_head($head, 'settings', '', -1, "workstation@workstation");
 //echo '<span class="opacitymedium">'.$langs->trans("WorkstationSetupPage").'</span><br><br>';
 
 
-if ($action == 'edit')
-{
+if ($action == 'edit') {
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="update">';
@@ -195,8 +183,7 @@ if ($action == 'edit')
 	print '<table class="noborder centpercent">';
 	print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
 
-	foreach ($arrayofparameters as $key => $val)
-	{
+	foreach ($arrayofparameters as $key => $val) {
 		print '<tr class="oddeven"><td>';
 		$tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : '');
 		print $form->textwithpicto($langs->trans($key), $tooltiphelp);
@@ -211,13 +198,11 @@ if ($action == 'edit')
 	print '</form>';
 	print '<br>';
 } else {
-	if (!empty($arrayofparameters))
-	{
+	if (!empty($arrayofparameters)) {
 		print '<table class="noborder centpercent">';
 		print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
 
-		foreach ($arrayofparameters as $key => $val)
-		{
+		foreach ($arrayofparameters as $key => $val) {
 			$setupnotempty++;
 
 			print '<tr class="oddeven"><td>';
@@ -243,7 +228,9 @@ $myTmpObjects['workstation'] = array('includerefgeneration'=>1, 'includedocgener
 
 
 foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
-	if ($myTmpObjectKey == 'MyObject') continue;
+	if ($myTmpObjectKey == 'MyObject') {
+		continue;
+	}
 	if ($myTmpObjectArray['includerefgeneration']) {
 		/*
 		 * Orders Numbering model
@@ -263,19 +250,14 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 
 		clearstatcache();
 
-		foreach ($dirmodels as $reldir)
-		{
+		foreach ($dirmodels as $reldir) {
 			$dir = dol_buildpath($reldir."core/modules/".$moduledir);
 
-			if (is_dir($dir))
-			{
+			if (is_dir($dir)) {
 				$handle = opendir($dir);
-				if (is_resource($handle))
-				{
-					while (($file = readdir($handle)) !== false)
-					{
-						if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php')
-						{
+				if (is_resource($handle)) {
+					while (($file = readdir($handle)) !== false) {
+						if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') {
 							$file = substr($file, 0, dol_strlen($file) - 4);
 
 							require_once $dir.'/'.$file.'.php';
@@ -283,11 +265,14 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 							$module = new $file($db);
 
 							// Show modules according to features level
-							if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue;
-							if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue;
+							if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
+								continue;
+							}
+							if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
+								continue;
+							}
 
-							if ($module->isEnabled())
-							{
+							if ($module->isEnabled()) {
 								dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php');
 
 								print '<tr class="oddeven"><td>'.$module->name."</td><td>\n";
@@ -300,14 +285,16 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 								if (preg_match('/^Error/', $tmp)) {
 									$langs->load("errors");
 									print '<div class="error">'.$langs->trans($tmp).'</div>';
-								} elseif ($tmp == 'NotConfigured') print $langs->trans($tmp);
-								else print $tmp;
+								} elseif ($tmp == 'NotConfigured') {
+									print $langs->trans($tmp);
+								} else {
+									print $tmp;
+								}
 								print '</td>'."\n";
 
 								print '<td class="center">';
 								$constforvar = 'WORKSTATION_'.strtoupper($myTmpObjectKey).'_ADDON';
-								if ($conf->global->$constforvar == $file)
-								{
+								if ($conf->global->$constforvar == $file) {
 									print img_picto($langs->trans("Activated"), 'switch_on');
 								} else {
 									print '<a href="'.$_SERVER["PHP_SELF"].'?action=setmod&token='.newToken().'&object='.strtolower($myTmpObjectKey).'&value='.urlencode($file).'">';
@@ -327,8 +314,9 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 								if ("$nextval" != $langs->trans("NotAvailable")) {  // Keep " on nextval
 									$htmltooltip .= ''.$langs->trans("NextValue").': ';
 									if ($nextval) {
-										if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured')
+										if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') {
 											$nextval = $langs->trans($nextval);
+										}
 											$htmltooltip .= $nextval.'<br>';
 									} else {
 										$htmltooltip .= $langs->trans($module->error).'<br>';
@@ -366,12 +354,10 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 		$sql .= " WHERE type = '".$db->escape($type)."'";
 		$sql .= " AND entity = ".$conf->entity;
 		$resql = $db->query($sql);
-		if ($resql)
-		{
+		if ($resql) {
 			$i = 0;
 			$num_rows = $db->num_rows($resql);
-			while ($i < $num_rows)
-			{
+			while ($i < $num_rows) {
 				$array = $db->fetch_array($resql);
 				array_push($def, $array[0]);
 				$i++;
@@ -392,31 +378,23 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 
 		clearstatcache();
 
-		foreach ($dirmodels as $reldir)
-		{
-			foreach (array('', '/doc') as $valdir)
-			{
+		foreach ($dirmodels as $reldir) {
+			foreach (array('', '/doc') as $valdir) {
 				$realpath = $reldir."core/modules/".$moduledir.$valdir;
 				$dir = dol_buildpath($realpath);
 
-				if (is_dir($dir))
-				{
+				if (is_dir($dir)) {
 					$handle = opendir($dir);
-					if (is_resource($handle))
-					{
-						while (($file = readdir($handle)) !== false)
-						{
+					if (is_resource($handle)) {
+						while (($file = readdir($handle)) !== false) {
 							$filelist[] = $file;
 						}
 						closedir($handle);
 						arsort($filelist);
 
-						foreach ($filelist as $file)
-						{
-							if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file))
-							{
-								if (file_exists($dir.'/'.$file))
-								{
+						foreach ($filelist as $file) {
+							if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) {
+								if (file_exists($dir.'/'.$file)) {
 									$name = substr($file, 4, dol_strlen($file) - 16);
 									$classname = substr($file, 0, dol_strlen($file) - 12);
 
@@ -424,21 +402,26 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 									$module = new $classname($db);
 
 									$modulequalified = 1;
-									if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0;
-									if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0;
+									if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
+										$modulequalified = 0;
+									}
+									if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
+										$modulequalified = 0;
+									}
 
-									if ($modulequalified)
-									{
+									if ($modulequalified) {
 										print '<tr class="oddeven"><td width="100">';
 										print (empty($module->name) ? $name : $module->name);
 										print "</td><td>\n";
-										if (method_exists($module, 'info')) print $module->info($langs);
-										else print $module->description;
+										if (method_exists($module, 'info')) {
+											print $module->info($langs);
+										} else {
+											print $module->description;
+										}
 										print '</td>';
 
 										// Active
-										if (in_array($name, $def))
-										{
+										if (in_array($name, $def)) {
 											print '<td class="center">'."\n";
 											print '<a href="'.$_SERVER["PHP_SELF"].'?action=del&amp;token='.newToken().'&amp;value='.$name.'">';
 											print img_picto($langs->trans("Enabled"), 'switch_on');
@@ -453,8 +436,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 										// Default
 										print '<td class="center">';
 										$constforvar = 'WORKSTATION_'.strtoupper($myTmpObjectKey).'_ADDON';
-										if ($conf->global->$constforvar == $name)
-										{
+										if ($conf->global->$constforvar == $name) {
 											print img_picto($langs->trans("Default"), 'on');
 										} else {
 											print '<a href="'.$_SERVER["PHP_SELF"].'?action=setdoc&amp;token='.newToken().'&amp;value='.$name.'&amp;scan_dir='.$module->scandir.'&amp;label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
@@ -464,8 +446,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 										// Info
 										$htmltooltip = ''.$langs->trans("Name").': '.$module->name;
 										$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
-										if ($module->type == 'pdf')
-										{
+										if ($module->type == 'pdf') {
 											$htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
 										}
 										$htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file;
@@ -480,8 +461,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
 
 										// Preview
 										print '<td class="center">';
-										if ($module->type == 'pdf')
-										{
+										if ($module->type == 'pdf') {
 											print '<a href="'.$_SERVER["PHP_SELF"].'?action=specimen&module='.$name.'&object='.$myTmpObjectKey.'">'.img_object($langs->trans("Preview"), 'generic').'</a>';
 										} else {
 											print img_object($langs->trans("PreviewNotAvailable"), 'generic');

+ 9 - 8
htdocs/asset/admin/assets_extrafields.php

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

+ 9 - 8
htdocs/asset/admin/assets_type_extrafields.php

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

+ 6 - 7
htdocs/asset/admin/setup.php

@@ -32,7 +32,9 @@ global $langs, $user;
 $langs->loadLangs(array("admin", "assets"));
 
 // Access control
-if (!$user->admin) accessforbidden();
+if (!$user->admin) {
+	accessforbidden();
+}
 
 // Parameters
 $action = GETPOST('action', 'aZ09');
@@ -63,8 +65,7 @@ $head = asset_admin_prepare_head();
 print dol_get_fiche_head($head, 'settings', $langs->trans("Assets"), -1, 'generic');
 
 
-if ($action == 'edit')
-{
+if ($action == 'edit') {
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="update">';
@@ -72,8 +73,7 @@ if ($action == 'edit')
 	print '<table class="noborder centpercent">';
 	print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
 
-	foreach ($arrayofparameters as $key => $val)
-	{
+	foreach ($arrayofparameters as $key => $val) {
 		print '<tr class="oddeven"><td>';
 		print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip'));
 		print '</td><td><input name="'.$key.'"  class="flat '.(empty($val['css']) ? 'minwidth200' : $val['css']).'" value="'.$conf->global->$key.'"></td></tr>';
@@ -91,8 +91,7 @@ if ($action == 'edit')
 	print '<table class="noborder centpercent">';
 	print '<tr class="liste_titre"><td class="titlefield">'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
 
-	foreach ($arrayofparameters as $key => $val)
-	{
+	foreach ($arrayofparameters as $key => $val) {
 		print '<tr class="oddeven"><td>';
 		print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip'));
 		print '</td><td>'.$conf->global->$key.'</td></tr>';

+ 42 - 36
htdocs/asset/card.php

@@ -55,18 +55,23 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen
 // Initialize array of search criterias
 $search_all = GETPOST("search_all", 'alpha');
 $search = array();
-foreach ($object->fields as $key => $val)
-{
-	if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha');
+foreach ($object->fields as $key => $val) {
+	if (GETPOST('search_'.$key, 'alpha')) {
+		$search[$key] = GETPOST('search_'.$key, 'alpha');
+	}
 }
 
-if (empty($action) && empty($id) && empty($ref)) $action = 'view';
+if (empty($action) && empty($id) && empty($ref)) {
+	$action = 'view';
+}
 
 // Load object
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
 
 // Security check
-if (!empty($user->socid)) $socid = $user->socid;
+if (!empty($user->socid)) {
+	$socid = $user->socid;
+}
 $result = restrictedArea($user, 'asset', $id);
 
 $permissiontoread = $user->rights->asset->read;
@@ -83,10 +88,11 @@ $upload_dir = $conf->mymodule->multidir_output[isset($object->entity) ? $object-
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	$error = 0;
 
 	$backurlforlist = dol_buildpath('/asset/list.php', 1);
@@ -109,12 +115,10 @@ if (empty($reshook))
 	// Action to build doc
 	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
 
-	if ($action == 'set_thirdparty' && $permissiontoadd)
-	{
+	if ($action == 'set_thirdparty' && $permissiontoadd) {
 		$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MYOBJECT_MODIFY');
 	}
-	if ($action == 'classin' && $permissiontoadd)
-	{
+	if ($action == 'classin' && $permissiontoadd) {
 		$object->setProject(GETPOST('projectid', 'int'));
 	}
 
@@ -138,15 +142,18 @@ $help_url = '';
 llxHeader('', $title, $help_url);
 
 // Part to create
-if ($action == 'create')
-{
+if ($action == 'create') {
 	print load_fiche_titre($langs->trans("NewAsset"), '', 'accountancy');
 
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="add">';
-	if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
-	if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	if ($backtopage) {
+		print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
+	}
+	if ($backtopageforcancel) {
+		print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	}
 
 	print dol_get_fiche_head(array(), '');
 
@@ -174,8 +181,7 @@ if ($action == 'create')
 }
 
 // Part to edit record
-if (($id || $ref) && $action == 'edit')
-{
+if (($id || $ref) && $action == 'edit') {
 	print load_fiche_titre($langs->trans("Assets"));
 
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@@ -183,8 +189,12 @@ if (($id || $ref) && $action == 'edit')
 	print '<input type="hidden" name="action" value="update">';
 	print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
 	print '<input type="hidden" name="id" value="'.$object->id.'">';
-	if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
-	if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	if ($backtopage) {
+		print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
+	}
+	if ($backtopageforcancel) {
+		print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	}
 
 	print dol_get_fiche_head();
 
@@ -208,8 +218,7 @@ if (($id || $ref) && $action == 'edit')
 }
 
 // Part to show record
-if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create')))
-{
+if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
 	$res = $object->fetch_optionals();
 
 	$head = asset_prepare_head($object);
@@ -218,16 +227,18 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	$formconfirm = '';
 
 	// Confirmation to delete
-	if ($action == 'delete')
-	{
+	if ($action == 'delete') {
 		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteAssets'), $langs->trans('ConfirmDeleteAsset'), 'confirm_delete', '', 0, 1);
 	}
 
 	// Call Hook formConfirm
 	$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
 	$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-	if (empty($reshook)) $formconfirm .= $hookmanager->resPrint;
-	elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint;
+	if (empty($reshook)) {
+		$formconfirm .= $hookmanager->resPrint;
+	} elseif ($reshook > 0) {
+		$formconfirm = $hookmanager->resPrint;
+	}
 
 	// Print form confirm
 	print $formconfirm;
@@ -274,24 +285,20 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	/*
 	 * Buttons
 	 */
-	if ($user->socid == 0)
-	{
+	if ($user->socid == 0) {
 		print '<div class="tabsAction">';
 
 		$parameters = array();
 		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
 
-		if (empty($reshook))
-		{
-			if ($user->rights->asset->write)
-			{
+		if (empty($reshook)) {
+			if ($user->rights->asset->write) {
 				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n";
 			} else {
 				print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n";
 			}
 
-			if ($user->rights->asset->delete)
-			{
+			if ($user->rights->asset->delete) {
 				print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n";
 			} else {
 				print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";
@@ -300,8 +307,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 		print "</div>";
 	}
 
-	if ($action != 'presend')
-	{
+	if ($action != 'presend') {
 		print '<div class="fichecenter"><div class="fichehalfleft">';
 		print '<a name="builddoc"></a>'; // ancre
 

+ 35 - 25
htdocs/asset/class/asset.class.php

@@ -170,8 +170,12 @@ class Asset extends CommonObject
 
 		$this->db = $db;
 
-		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible'] = 0;
-		if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled'] = 0;
+		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
+			$this->fields['rowid']['visible'] = 0;
+		}
+		if (empty($conf->multicompany->enabled)) {
+			$this->fields['entity']['enabled'] = 0;
+		}
 	}
 
 	/**
@@ -304,7 +308,9 @@ class Asset extends CommonObject
 		global $dolibarr_main_authentication, $dolibarr_main_demo;
 		global $menumanager;
 
-		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
+		if (!empty($conf->dol_no_mouse_hover)) {
+			$notooltip = 1; // Force disable tooltips
+		}
 
 		$result = '';
 		$companylink = '';
@@ -315,33 +321,40 @@ class Asset extends CommonObject
 
 		$url = dol_buildpath('/asset/card.php', 1).'?id='.$this->id;
 
-		if ($option != 'nolink')
-		{
+		if ($option != 'nolink') {
 			// Add param to save lastsearch_values or not
 			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
-			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
-			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+				$add_save_lastsearch_values = 1;
+			}
+			if ($add_save_lastsearch_values) {
+				$url .= '&save_lastsearch_values=1';
+			}
 		}
 
 		$linkclose = '';
-		if (empty($notooltip))
-		{
-			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
-			{
+		if (empty($notooltip)) {
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
 				$label = $langs->trans("ShowAssets");
 				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
 			}
 			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
 			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
-		} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+		} else {
+			$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+		}
 
 		$linkstart = '<a href="'.$url.'"';
 		$linkstart .= $linkclose.'>';
 		$linkend = '</a>';
 
 		$result .= $linkstart;
-		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
-		if ($withpicto != 2) $result .= $this->ref;
+		if ($withpicto) {
+			$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+		}
+		if ($withpicto != 2) {
+			$result .= $this->ref;
+		}
 		$result .= $linkend;
 		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
 
@@ -381,7 +394,9 @@ class Asset extends CommonObject
 		$labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
 
 		$statusType = 'status0';
-		if ($status == self::STATUS_VALIDATED) $statusType = 'status4';
+		if ($status == self::STATUS_VALIDATED) {
+			$statusType = 'status4';
+		}
 
 		return dolGetStatus($labelStatus[$status], $labelStatusShort[$status], '', $statusType, $mode);
 	}
@@ -399,28 +414,23 @@ class Asset extends CommonObject
 		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
 		$sql .= ' WHERE t.rowid = '.$id;
 		$result = $this->db->query($sql);
-		if ($result)
-		{
-			if ($this->db->num_rows($result))
-			{
+		if ($result) {
+			if ($this->db->num_rows($result)) {
 				$obj = $this->db->fetch_object($result);
 				$this->id = $obj->rowid;
-				if ($obj->fk_user_author)
-				{
+				if ($obj->fk_user_author) {
 					$cuser = new User($this->db);
 					$cuser->fetch($obj->fk_user_author);
 					$this->user_creation = $cuser;
 				}
 
-				if ($obj->fk_user_valid)
-				{
+				if ($obj->fk_user_valid) {
 					$vuser = new User($this->db);
 					$vuser->fetch($obj->fk_user_valid);
 					$this->user_validation = $vuser;
 				}
 
-				if ($obj->fk_user_cloture)
-				{
+				if ($obj->fk_user_cloture) {
 					$cluser = new User($this->db);
 					$cluser->fetch($obj->fk_user_cloture);
 					$this->user_cloture = $cluser;

+ 40 - 45
htdocs/asset/class/asset_type.class.php

@@ -131,27 +131,25 @@ class AssetType extends CommonObject
 
 		dol_syslog("Asset_type::create", LOG_DEBUG);
 		$result = $this->db->query($sql);
-		if ($result)
-		{
+		if ($result) {
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."asset_type");
 
 			$result = $this->update($user, 1);
-			if ($result < 0)
-			{
+			if ($result < 0) {
 				$this->db->rollback();
 				return -3;
 			}
 
-			if (!$notrigger)
-			{
+			if (!$notrigger) {
 				// Call trigger
 				$result = $this->call_trigger('ASSET_TYPE_CREATE', $user);
-				if ($result < 0) { $error++; }
+				if ($result < 0) {
+					$error++;
+				}
 				// End call triggers
 			}
 
-			if (!$error)
-			{
+			if (!$error) {
 				$this->db->commit();
 				return $this->id;
 			} else {
@@ -193,30 +191,27 @@ class AssetType extends CommonObject
 		$sql .= " WHERE rowid =".$this->id;
 
 		$result = $this->db->query($sql);
-		if ($result)
-		{
+		if ($result) {
 			$action = 'update';
 
 			// Actions on extra fields
-			if (!$error)
-			{
+			if (!$error) {
 				$result = $this->insertExtraFields();
-				if ($result < 0)
-				{
+				if ($result < 0) {
 					$error++;
 				}
 			}
 
-			if (!$error && !$notrigger)
-			{
+			if (!$error && !$notrigger) {
 				// Call trigger
 				$result = $this->call_trigger('ASSET_TYPE_MODIFY', $user);
-				if ($result < 0) { $error++; }
+				if ($result < 0) {
+					$error++;
+				}
 				// End call triggers
 			}
 
-			if (!$error)
-			{
+			if (!$error) {
 				$this->db->commit();
 				return 1;
 			} else {
@@ -246,11 +241,12 @@ class AssetType extends CommonObject
 		$sql .= " WHERE rowid = ".$this->id;
 
 		$resql = $this->db->query($sql);
-		if ($resql)
-		{
+		if ($resql) {
 			// Call trigger
 			$result = $this->call_trigger('ASSET_TYPE_DELETE', $user);
-			if ($result < 0) { $error++; $this->db->rollback(); return -2; }
+			if ($result < 0) {
+				$error++; $this->db->rollback(); return -2;
+			}
 			// End call triggers
 
 			$this->db->commit();
@@ -277,10 +273,8 @@ class AssetType extends CommonObject
 		dol_syslog("Asset_type::fetch", LOG_DEBUG);
 
 		$resql = $this->db->query($sql);
-		if ($resql)
-		{
-			if ($this->db->num_rows($resql))
-			{
+		if ($resql) {
+			if ($this->db->num_rows($resql)) {
 				$obj = $this->db->fetch_object($resql);
 
 				$this->id = $obj->rowid;
@@ -317,15 +311,12 @@ class AssetType extends CommonObject
 		$sql .= " WHERE entity IN (".getEntity('asset_type').")";
 
 		$resql = $this->db->query($sql);
-		if ($resql)
-		{
+		if ($resql) {
 			$nump = $this->db->num_rows($resql);
 
-			if ($nump)
-			{
+			if ($nump) {
 				$i = 0;
-				while ($i < $nump)
-				{
+				while ($i < $nump) {
 					$obj = $this->db->fetch_object($resql);
 
 					$assettypes[$obj->rowid] = $langs->trans($obj->label);
@@ -357,18 +348,16 @@ class AssetType extends CommonObject
 		$sql .= " FROM ".MAIN_DB_PREFIX."asset as a";
 		$sql .= " WHERE a.entity IN (".getEntity('asset').")";
 		$sql .= " AND a.fk_asset_type = ".$this->id;
-		if (!empty($excludefilter)) $sql .= ' AND ('.$excludefilter.')';
+		if (!empty($excludefilter)) {
+			$sql .= ' AND ('.$excludefilter.')';
+		}
 
 		dol_syslog(get_class($this)."::listAssetsForGroup", LOG_DEBUG);
 		$resql = $this->db->query($sql);
-		if ($resql)
-		{
-			while ($obj = $this->db->fetch_object($resql))
-			{
-				if (!array_key_exists($obj->rowid, $ret))
-				{
-					if ($mode < 2)
-					{
+		if ($resql) {
+			while ($obj = $this->db->fetch_object($resql)) {
+				if (!array_key_exists($obj->rowid, $ret)) {
+					if ($mode < 2) {
 						$assetstatic = new Asset($this->db);
 						if ($mode == 1) {
 							$assetstatic->fetch($obj->rowid, '', '', '', false, false);
@@ -376,7 +365,9 @@ class AssetType extends CommonObject
 							$assetstatic->fetch($obj->rowid);
 						}
 						$ret[$obj->rowid] = $assetstatic;
-					} else $ret[$obj->rowid] = $obj->rowid;
+					} else {
+						$ret[$obj->rowid] = $obj->rowid;
+					}
 				}
 			}
 
@@ -410,8 +401,12 @@ class AssetType extends CommonObject
 		$linkend = '</a>';
 
 		$result .= $linkstart;
-		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
-		if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->label, $maxlen) : $this->label);
+		if ($withpicto) {
+			$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+		}
+		if ($withpicto != 2) {
+			$result .= ($maxlen ?dol_trunc($this->label, $maxlen) : $this->label);
+		}
 		$result .= $linkend;
 
 		return $result;

+ 14 - 13
htdocs/asset/document.php

@@ -41,8 +41,7 @@ $action = GETPOST('action', 'aZ09');
 $confirm = GETPOST('confirm', 'alpha');
 
 // Security check
-if ($user->socid)
-{
+if ($user->socid) {
 	$socid = $user->socid;
 }
 $result=restrictedArea($user, 'asset', $id, '');
@@ -52,16 +51,21 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortorder) $sortorder = "ASC";
-if (!$sortfield) $sortfield = "name";
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
+if (!$sortfield) {
+	$sortfield = "name";
+}
 
 $object = new Asset($db);
-if ($object->fetch($id))
-{
+if ($object->fetch($id)) {
 	$upload_dir = $conf->asset->dir_output."/".dol_sanitizeFileName($object->ref);
 }
 
@@ -85,10 +89,8 @@ $form = new Form($db);
 
 
 
-if ($id > 0 || !empty($ref))
-{
-	if ($object->fetch($id, $ref) > 0)
-	{
+if ($id > 0 || !empty($ref)) {
+	if ($object->fetch($id, $ref) > 0) {
 		$upload_dir = $conf->asset->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
 
 		$head = asset_prepare_head($object);
@@ -97,8 +99,7 @@ if ($id > 0 || !empty($ref))
 		// Build file list
 		$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
 		$totalsize = 0;
-		foreach ($filearray as $key => $file)
-		{
+		foreach ($filearray as $key => $file) {
 			$totalsize += $file['size'];
 		}
 

+ 4 - 2
htdocs/asset/info.php

@@ -29,12 +29,14 @@ require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php';
 // Load translation files required by the page
 $langs->loadLangs(array("asset"));
 
-$id = GETPOST('id', 'int');
+$id = GETPOSTINT('id');
 $ref = GETPOST('ref', 'alpha');
 $action = GETPOST('action', 'aZ09');
 
 // Security check
-if ($user->socid) $socid = $user->socid;
+if ($user->socid) {
+	$socid = $user->socid;
+}
 $result = restrictedArea($user, 'asset', $id);
 
 $object = new Asset($db);

+ 192 - 123
htdocs/asset/list.php

@@ -50,7 +50,9 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; }     // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
+if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
@@ -68,14 +70,20 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
 
 // Default sort order (if not yet defined by previous GETPOST)
-if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
-if (!$sortorder) $sortorder = "ASC";
+if (!$sortfield) {
+	$sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
+}
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
 
 // Security check
 $socid = 0;
-if ($user->socid) $socid = $user->socid;
-if ($user->socid > 0)	// Protection if external user
-{
+if ($user->socid) {
+	$socid = $user->socid;
+}
+if ($user->socid > 0) {
+	// Protection if external user
 	//$socid = $user->socid;
 	accessforbidden();
 }
@@ -86,30 +94,31 @@ $result = restrictedArea($user, 'asset', $id);
 // Initialize array of search criterias
 $search_all = GETPOST("search_all", 'alpha');
 $search = array();
-foreach ($object->fields as $key => $val)
-{
-	if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha');
+foreach ($object->fields as $key => $val) {
+	if (GETPOST('search_'.$key, 'alpha') !== '') {
+		$search[$key] = GETPOST('search_'.$key, 'alpha');
+	}
 }
 
 // List of fields to search into when doing a "search in all"
 $fieldstosearchall = array();
-foreach ($object->fields as $key => $val)
-{
-	if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label'];
+foreach ($object->fields as $key => $val) {
+	if ($val['searchall']) {
+		$fieldstosearchall['t.'.$key] = $val['label'];
+	}
 }
 
 // Definition of fields for list
 $arrayfields = array();
-foreach ($object->fields as $key => $val)
-{
+foreach ($object->fields as $key => $val) {
 	// If $val['visible']==0, then we never show the field
-	if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']);
+	if (!empty($val['visible'])) {
+		$arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']);
+	}
 }
 // Extra fields
-if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
-{
-	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
-	{
+if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
+	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
 		if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
 			$arrayfields["ef.".$key] = array(
 				'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
@@ -132,31 +141,33 @@ $permissiontodelete = $user->rights->asset->delete;
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	// Selection of new fields
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
 	// Purge search criteria
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-	{
-		foreach ($object->fields as $key => $val)
-		{
+	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
+		foreach ($object->fields as $key => $val) {
 			$search[$key] = '';
 		}
 		$toselect = '';
 		$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'))
-	{
+		|| 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
 	}
 
@@ -185,13 +196,14 @@ $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Assets"));
 // Build and execute select
 // --------------------------------------------------------------------
 $sql = 'SELECT ';
-foreach ($object->fields as $key => $val)
-{
+foreach ($object->fields as $key => $val) {
 	$sql .= 't.'.$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.', ' : '');
+	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();
@@ -199,20 +211,32 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje
 $sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
 $sql = preg_replace('/,\s*$/', '', $sql);
 $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
-if (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 (t.rowid = ef.fk_object)";
-if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
-else $sql .= " WHERE 1 = 1";
-foreach ($search as $key => $val)
-{
-	if ($key == 'status' && $search[$key] == -1) continue;
+if (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 (t.rowid = ef.fk_object)";
+}
+if ($object->ismultientitymanaged == 1) {
+	$sql .= " WHERE t.entity IN (".getEntity($object->element).")";
+} else {
+	$sql .= " WHERE 1 = 1";
+}
+foreach ($search as $key => $val) {
+	if ($key == 'status' && $search[$key] == -1) {
+		continue;
+	}
 	$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
 	if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
-		if ($search[$key] == '-1') $search[$key] = '';
+		if ($search[$key] == '-1') {
+			$search[$key] = '';
+		}
 		$mode_search = 2;
 	}
-	if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
+	if ($search[$key] != '') {
+		$sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
+	}
+}
+if ($search_all) {
+	$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
 }
-if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
 //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
 // Add where from extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
@@ -225,7 +249,7 @@ $sql .= $hookmanager->resPrint;
 $sql.= " GROUP BY "
 foreach($object->fields as $key => $val)
 {
-    $sql.='t.'.$key.', ';
+	$sql.='t.'.$key.', ';
 }
 // Add fields from extrafields
 if (! empty($extrafields->attributes[$object->table_element]['label'])) {
@@ -242,26 +266,24 @@ $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$resql = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($resql);
-	if (($page * $limit) > $nbtotalofrecords)	// if total of record found is smaller than page * limit, goto and load page 0
-	{
+	if (($page * $limit) > $nbtotalofrecords) {	// if total of record found is smaller than page * limit, goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
 }
 // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
-if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit)))
-{
+if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) {
 	$num = $nbtotalofrecords;
 } else {
-	if ($limit) $sql .= $db->plimit($limit + 1, $offset);
+	if ($limit) {
+		$sql .= $db->plimit($limit + 1, $offset);
+	}
 
 	$resql = $db->query($sql);
-	if (!$resql)
-	{
+	if (!$resql) {
 		dol_print_error($db);
 		exit;
 	}
@@ -270,8 +292,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit
 }
 
 // Direct jump if only one record found
-if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page)
-{
+if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
 	$obj = $db->fetch_object($resql);
 	$id = $obj->rowid;
 	header("Location: ".DOL_URL_ROOT.'/asset/card.php?id='.$id);
@@ -302,14 +323,24 @@ jQuery(document).ready(function() {
 $arrayofselected = is_array($toselect) ? $toselect : array();
 
 $param = '';
-if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-foreach ($search as $key => $val)
-{
-	if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey);
-	else $param .= '&search_'.$key.'='.urlencode($search[$key]);
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+	$param .= '&contextpage='.urlencode($contextpage);
+}
+if ($limit > 0 && $limit != $conf->liste_limit) {
+	$param .= '&limit='.urlencode($limit);
+}
+foreach ($search as $key => $val) {
+	if (is_array($search[$key]) && count($search[$key])) {
+		foreach ($search[$key] as $skey) {
+			$param .= '&search_'.$key.'[]='.urlencode($skey);
+		}
+	} else {
+		$param .= '&search_'.$key.'='.urlencode($search[$key]);
+	}
+}
+if ($optioncss != '') {
+	$param .= '&optioncss='.urlencode($optioncss);
 }
-if ($optioncss != '')     $param .= '&optioncss='.urlencode($optioncss);
 // Add $param from extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 
@@ -318,12 +349,18 @@ $arrayofmassactions = array(
 	//'presend'=>$langs->trans("SendByMail"),
 	//'builddoc'=>$langs->trans("PDFMerge"),
 );
-if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
-if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
+if ($permissiontodelete) {
+	$arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
+}
+if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
+	$arrayofmassactions = array();
+}
 $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
 
 print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
-if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+if ($optioncss != '') {
+	print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+}
 print '<input type="hidden" name="token" value="'.newToken().'">';
 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 print '<input type="hidden" name="action" value="list">';
@@ -342,9 +379,10 @@ $objecttmp = new Asset($db);
 $trackid = 'asset'.$object->id;
 include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
 
-if ($sall)
-{
-	foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
+if ($sall) {
+	foreach ($fieldstosearchall as $key => $val) {
+		$fieldstosearchall[$key] = $langs->trans($val);
+	}
 	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
 }
 
@@ -355,11 +393,13 @@ $moreforfilter.= '</div>';*/
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
-if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
-else $moreforfilter = $hookmanager->resPrint;
+if (empty($reshook)) {
+	$moreforfilter .= $hookmanager->resPrint;
+} else {
+	$moreforfilter = $hookmanager->resPrint;
+}
 
-if (!empty($moreforfilter))
-{
+if (!empty($moreforfilter)) {
 	print '<div class="liste_titre liste_titre_bydiv centpercent">';
 	print $moreforfilter;
 	print '</div>';
@@ -376,20 +416,26 @@ print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" :
 // Fields title search
 // --------------------------------------------------------------------
 print '<tr class="liste_titre">';
-foreach ($object->fields as $key => $val)
-{
+foreach ($object->fields as $key => $val) {
 	$cssforfield = (empty($val['css']) ? '' : $val['css']);
-	if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center';
-	elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
-	elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
-	elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right';
-	if (!empty($arrayfields['t.'.$key]['checked']))
-	{
+	if ($key == 'status') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+	} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'right';
+	}
+	if (!empty($arrayfields['t.'.$key]['checked'])) {
 		print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
-		if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
-		elseif (strpos($val['type'], 'integer:') === 0) {
+		if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+			print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
+		} elseif (strpos($val['type'], 'integer:') === 0) {
 			print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1);
-		} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
+		} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) {
+			print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
+		}
 		print '</td>';
 	}
 }
@@ -411,15 +457,18 @@ print '</tr>'."\n";
 // Fields title label
 // --------------------------------------------------------------------
 print '<tr class="liste_titre">';
-foreach ($object->fields as $key => $val)
-{
+foreach ($object->fields as $key => $val) {
 	$cssforfield = (empty($val['css']) ? '' : $val['css']);
-	if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center';
-	elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
-	elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
-	elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right';
-	if (!empty($arrayfields['t.'.$key]['checked']))
-	{
+	if ($key == 'status') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+	} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'right';
+	}
+	if (!empty($arrayfields['t.'.$key]['checked'])) {
 		print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
 	}
 }
@@ -436,11 +485,11 @@ print '</tr>'."\n";
 
 // Detect if we need a fetch on each output line
 $needToFetchEachLine = 0;
-if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0)
-{
-	foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val)
-	{
-		if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object
+if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
+	foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
+		if (preg_match('/\$object/', $val)) {
+			$needToFetchEachLine++; // There is at least one compute field that use $object
+		}
 	}
 }
 
@@ -449,37 +498,50 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co
 // --------------------------------------------------------------------
 $i = 0;
 $totalarray = array();
-while ($i < ($limit ? min($num, $limit) : $num))
-{
+while ($i < ($limit ? min($num, $limit) : $num)) {
 	$obj = $db->fetch_object($resql);
-	if (empty($obj)) break; // Should not happen
+	if (empty($obj)) {
+		break; // Should not happen
+	}
 
 	// Store properties in $object
 	$object->setVarsFromFetchObj($obj);
 
 	// Show here line of result
 	print '<tr class="oddeven">';
-	foreach ($object->fields as $key => $val)
-	{
+	foreach ($object->fields as $key => $val) {
 		$cssforfield = (empty($val['css']) ? '' : $val['css']);
-		if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
-		elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center';
+		if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+			$cssforfield .= ($cssforfield ? ' ' : '').'center';
+		} elseif ($key == 'status') {
+			$cssforfield .= ($cssforfield ? ' ' : '').'center';
+		}
 
-		if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
-		elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+		if (in_array($val['type'], array('timestamp'))) {
+			$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+		} elseif ($key == 'ref') {
+			$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+		}
 
-		if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right';
+		if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') {
+			$cssforfield .= ($cssforfield ? ' ' : '').'right';
+		}
 
-		if (!empty($arrayfields['t.'.$key]['checked']))
-		{
+		if (!empty($arrayfields['t.'.$key]['checked'])) {
 			print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
-			if ($key == 'status') print $object->getLibStatut(5);
-			else print $object->showOutputField($val, $key, $object->$key, '');
+			if ($key == 'status') {
+				print $object->getLibStatut(5);
+			} else {
+				print $object->showOutputField($val, $key, $object->$key, '');
+			}
 			print '</td>';
-			if (!$i) $totalarray['nbfield']++;
-			if (!empty($val['isameasure']))
-			{
-				if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
+			if (!empty($val['isameasure'])) {
+				if (!$i) {
+					$totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
+				}
 				$totalarray['val']['t.'.$key] += $object->$key;
 			}
 		}
@@ -492,14 +554,17 @@ while ($i < ($limit ? min($num, $limit) : $num))
 	print $hookmanager->resPrint;
 	// Action column
 	print '<td class="nowrap center">';
-	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
-	{
+	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;
+		if (in_array($object->id, $arrayofselected)) {
+			$selected = 1;
+		}
 		print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
 	}
 	print '</td>';
-	if (!$i) $totalarray['nbfield']++;
+	if (!$i) {
+		$totalarray['nbfield']++;
+	}
 
 	print '</tr>'."\n";
 
@@ -510,10 +575,13 @@ while ($i < ($limit ? min($num, $limit) : $num))
 include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
 
 // If no record found
-if ($num == 0)
-{
+if ($num == 0) {
 	$colspan = 1;
-	foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; }
+	foreach ($arrayfields as $key => $val) {
+		if (!empty($val['checked'])) {
+			$colspan++;
+		}
+	}
 	print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
 }
 
@@ -529,10 +597,11 @@ print '</div>'."\n";
 
 print '</form>'."\n";
 
-if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords))
-{
+if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
 	$hidegeneratedfilelistifempty = 1;
-	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0;
+	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
+		$hidegeneratedfilelistifempty = 0;
+	}
 
 	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
 	$formfile = new FormFile($db);

+ 36 - 33
htdocs/asset/note.php

@@ -52,10 +52,14 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Load object
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
-if ($id > 0 || !empty($ref)) $upload_dir = $conf->asset->multidir_output[$object->entity]."/".$object->id;
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->asset->multidir_output[$object->entity]."/".$object->id;
+}
 
 // Security check
-if (!empty($user->socid)) $socid = $user->socid;
+if (!empty($user->socid)) {
+	$socid = $user->socid;
+}
 $result = restrictedArea($user, 'asset', $id);
 
 $permissionnote = 1;
@@ -79,8 +83,7 @@ $form = new Form($db);
 $help_url = '';
 llxHeader('', $langs->trans('Assets'), $help_url);
 
-if ($id > 0 || !empty($ref))
-{
+if ($id > 0 || !empty($ref)) {
 	$object->fetch_thirdparty();
 
 	$head = asset_prepare_head($object);
@@ -101,35 +104,35 @@ if ($id > 0 || !empty($ref))
 	// Project
 	if (! empty($conf->projet->enabled))
 	{
-	    $langs->load("projects");
-	    $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
-	    if ($user->rights->asset->creer)
-	    {
-	        if ($action != 'classify')
-	            //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
-	            $morehtmlref.=' : ';
-	            if ($action == 'classify') {
-	                //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
-	                $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
-	                $morehtmlref.='<input type="hidden" name="action" value="classin">';
-	                $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
-	                $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
-	                $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
-	                $morehtmlref.='</form>';
-	            } else {
-	                $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
-	            }
-	    } else {
-	        if (! empty($object->fk_project)) {
-	            $proj = new Project($db);
-	            $proj->fetch($object->fk_project);
-	            $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
-	            $morehtmlref.=$proj->ref;
-	            $morehtmlref.='</a>';
-	        } else {
-	            $morehtmlref.='';
-	        }
-	    }
+		$langs->load("projects");
+		$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+		if ($user->rights->asset->creer)
+		{
+			if ($action != 'classify')
+				//$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+				$morehtmlref.=' : ';
+				if ($action == 'classify') {
+					//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+					$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+					$morehtmlref.='<input type="hidden" name="action" value="classin">';
+					$morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
+					$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+					$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+					$morehtmlref.='</form>';
+				} else {
+					$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+				}
+		} else {
+			if (! empty($object->fk_project)) {
+				$proj = new Project($db);
+				$proj->fetch($object->fk_project);
+				$morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
+				$morehtmlref.=$proj->ref;
+				$morehtmlref.='</a>';
+			} else {
+				$morehtmlref.='';
+			}
+		}
 	}*/
 	$morehtmlref .= '</div>';
 

+ 66 - 71
htdocs/asset/type.php

@@ -26,9 +26,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php';
 require_once DOL_DOCUMENT_ROOT.'/asset/class/asset_type.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
-if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
-if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
+if (!empty($conf->accounting->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
+}
+if (!empty($conf->accounting->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
+}
+if (!empty($conf->accounting->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
+}
 
 // Load translation files required by the page
 $langs->load("assets");
@@ -44,12 +50,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortorder) {  $sortorder = "DESC"; }
-if (!$sortfield) {  $sortfield = "a.label"; }
+if (!$sortorder) {
+	$sortorder = "DESC";
+}
+if (!$sortfield) {
+	$sortfield = "a.label";
+}
 
 $label = GETPOST("label", "alpha");
 $accountancy_code_asset = GETPOST('accountancy_code_asset', 'string');
@@ -67,8 +79,7 @@ $extrafields = new ExtraFields($db);
 // fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label($object->table_element);
 
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-{
+if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 	$type = "";
 	$sall = "";
 }
@@ -86,15 +97,13 @@ $permissiontoadd = $user->rights->asset->setup_advance;
 if ($cancel) {
 	$action = '';
 
-	if (!empty($backtopage))
-	{
+	if (!empty($backtopage)) {
 		header("Location: ".$backtopage);
 		exit;
 	}
 }
 
-if ($action == 'add' && $user->rights->asset->write)
-{
+if ($action == 'add' && $user->rights->asset->write) {
 	$object->label = trim($label);
 	$object->accountancy_code_asset = trim($accountancy_code_asset);
 	$object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset);
@@ -103,7 +112,9 @@ if ($action == 'add' && $user->rights->asset->write)
 
 	// Fill array 'array_options' with data from add form
 	$ret = $extrafields->setOptionalsFromPost(null, $object);
-	if ($ret < 0) $error++;
+	if ($ret < 0) {
+		$error++;
+	}
 
 	if (empty($object->label)) {
 		$error++;
@@ -121,11 +132,9 @@ if ($action == 'add' && $user->rights->asset->write)
 		}
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		$id = $object->create($user);
-		if ($id > 0)
-		{
+		if ($id > 0) {
 			header("Location: ".$_SERVER["PHP_SELF"]);
 			exit;
 		} else {
@@ -137,8 +146,7 @@ if ($action == 'add' && $user->rights->asset->write)
 	}
 }
 
-if ($action == 'update' && $user->rights->asset->write)
-{
+if ($action == 'update' && $user->rights->asset->write) {
 	$object->fetch($rowid);
 
 	$object->oldcopy = clone $object;
@@ -151,12 +159,13 @@ if ($action == 'update' && $user->rights->asset->write)
 
 	// Fill array 'array_options' with data from add form
 	$ret = $extrafields->setOptionalsFromPost(null, $object);
-	if ($ret < 0) $error++;
+	if ($ret < 0) {
+		$error++;
+	}
 
 	$ret = $object->update($user);
 
-	if ($ret >= 0 && !count($object->errors))
-	{
+	if ($ret >= 0 && !count($object->errors)) {
 		setEventMessages($langs->trans("AssetTypeModified"), null, 'mesgs');
 	} else {
 		setEventMessages($object->error, $object->errors, 'errors');
@@ -166,13 +175,11 @@ if ($action == 'update' && $user->rights->asset->write)
 	exit;
 }
 
-if ($action == 'confirm_delete' && $user->rights->asset->write)
-{
+if ($action == 'confirm_delete' && $user->rights->asset->write) {
 	$object->fetch($rowid);
 	$res = $object->delete();
 
-	if ($res > 0)
-	{
+	if ($res > 0) {
 		setEventMessages($langs->trans("AssetsTypeDeleted"), null, 'mesgs');
 		header("Location: ".$_SERVER["PHP_SELF"]);
 		exit;
@@ -194,8 +201,7 @@ llxHeader('', $langs->trans("AssetsTypeSetup"), $helpurl);
 
 
 // List of asset type
-if (!$rowid && $action != 'create' && $action != 'edit')
-{
+if (!$rowid && $action != 'create' && $action != 'edit') {
 	//print dol_get_fiche_head('');
 
 	$sql = "SELECT d.rowid, d.label as label, d.accountancy_code_asset, d.accountancy_code_depreciation_asset, d.accountancy_code_depreciation_expense, d.note";
@@ -203,8 +209,7 @@ if (!$rowid && $action != 'create' && $action != 'edit')
 	$sql .= " WHERE d.entity IN (".getEntity('asset_type').")";
 
 	$result = $db->query($sql);
-	if ($result)
-	{
+	if ($result) {
 		$num = $db->num_rows($result);
 		$nbtotalofrecords = $num;
 
@@ -213,7 +218,9 @@ if (!$rowid && $action != 'create' && $action != 'edit')
 		$param = '';
 
 		print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
-		if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+		if ($optioncss != '') {
+			print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+		}
 		print '<input type="hidden" name="token" value="'.newToken().'">';
 		print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 		print '<input type="hidden" name="action" value="list">';
@@ -241,8 +248,7 @@ if (!$rowid && $action != 'create' && $action != 'edit')
 
 		$assettype = new AssetType($db);
 
-		while ($i < $num)
-		{
+		while ($i < $num) {
 			$objp = $db->fetch_object($result);
 
 			$assettype->id = $objp->rowid;
@@ -257,8 +263,7 @@ if (!$rowid && $action != 'create' && $action != 'edit')
 			print '<td>'.dol_escape_htmltag($objp->label).'</td>';
 
 			print '<td class="center">';
-			if (!empty($conf->accounting->enabled))
-			{
+			if (!empty($conf->accounting->enabled)) {
 				$accountingaccount = new AccountingAccount($db);
 				$accountingaccount->fetch('', $objp->accountancy_code_asset, 1);
 
@@ -269,8 +274,7 @@ if (!$rowid && $action != 'create' && $action != 'edit')
 			print '</td>';
 
 			print '<td class="center">';
-			if (!empty($conf->accounting->enabled))
-			{
+			if (!empty($conf->accounting->enabled)) {
 				$accountingaccount2 = new AccountingAccount($db);
 				$accountingaccount2->fetch('', $objp->accountancy_code_depreciation_asset, 1);
 
@@ -281,8 +285,7 @@ if (!$rowid && $action != 'create' && $action != 'edit')
 			print '</td>';
 
 			print '<td class="center">';
-			if (!empty($conf->accounting->enabled))
-			{
+			if (!empty($conf->accounting->enabled)) {
 				$accountingaccount3 = new AccountingAccount($db);
 				$accountingaccount3->fetch('', $objp->accountancy_code_depreciation_expense, 1);
 
@@ -292,9 +295,11 @@ if (!$rowid && $action != 'create' && $action != 'edit')
 			}
 			print '</td>';
 
-			if ($user->rights->asset->write)
+			if ($user->rights->asset->write) {
 				print '<td class="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit&rowid='.$objp->rowid.'">'.img_edit().'</a></td>';
-			else print '<td class="right">&nbsp;</td>';
+			} else {
+				print '<td class="right">&nbsp;</td>';
+			}
 			print "</tr>";
 			$i++;
 		}
@@ -313,10 +318,11 @@ if (!$rowid && $action != 'create' && $action != 'edit')
 /* Creation mode                                                              */
 /*                                                                            */
 /* ************************************************************************** */
-if ($action == 'create')
-{
+if ($action == 'create') {
 	$object = new AssetType($db);
-	if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db);
+	if (!empty($conf->accounting->enabled)) {
+		$formaccounting = new FormAccounting($db);
+	}
 
 	print load_fiche_titre($langs->trans("NewAssetType"));
 
@@ -331,8 +337,7 @@ if ($action == 'create')
 
 	print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Label").'</td><td><input type="text" name="label" size="40"></td></tr>';
 
-	if (!empty($conf->accounting->enabled))
-	{
+	if (!empty($conf->accounting->enabled)) {
 		// Accountancy_code_asset
 		print '<tr><td class="titlefield">'.$langs->trans("AccountancyCodeAsset").'</td>';
 		print '<td>';
@@ -375,8 +380,7 @@ if ($action == 'create')
 	$parameters = array();
 	$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
 	print $hookmanager->resPrint;
-	if (empty($reshook))
-	{
+	if (empty($reshook)) {
 		print $object->showOptionals($extrafields, 'edit', $parameters);
 	}
 	print '<tbody>';
@@ -398,10 +402,8 @@ if ($action == 'create')
 /* View mode                                                                  */
 /*                                                                            */
 /* ************************************************************************** */
-if ($rowid > 0)
-{
-	if ($action != 'edit')
-	{
+if ($rowid > 0) {
+	if ($action != 'edit') {
 		$object = new AssetType($db);
 		$object->fetch($rowid);
 		$object->fetch_optionals();
@@ -409,8 +411,7 @@ if ($rowid > 0)
 		/*
 		 * Confirmation suppression
 		 */
-		if ($action == 'delete')
-		{
+		if ($action == 'delete') {
 			print $form->formconfirm($_SERVER['PHP_SELF']."?rowid=".$object->id, $langs->trans("DeleteAnAssetType"), $langs->trans("ConfirmDeleteAssetType", $object->label), "confirm_delete", '', 0, 1);
 		}
 
@@ -437,8 +438,7 @@ if ($rowid > 0)
 		print '<td class="nowrap">';
 		print $langs->trans("AccountancyCodeAsset");
 		print '</td><td>';
-		if (!empty($conf->accounting->enabled))
-		{
+		if (!empty($conf->accounting->enabled)) {
 			$accountingaccount = new AccountingAccount($db);
 			$accountingaccount->fetch('', $object->accountancy_code_asset, 1);
 
@@ -453,8 +453,7 @@ if ($rowid > 0)
 		print '<td class="nowrap">';
 		print $langs->trans("AccountancyCodeDepreciationAsset");
 		print '</td><td>';
-		if (!empty($conf->accounting->enabled))
-		{
+		if (!empty($conf->accounting->enabled)) {
 			$accountingaccount2 = new AccountingAccount($db);
 			$accountingaccount2->fetch('', $object->accountancy_code_depreciation_asset, 1);
 
@@ -469,8 +468,7 @@ if ($rowid > 0)
 		print '<td class="nowrap">';
 		print $langs->trans("AccountancyCodeDepreciationExpense");
 		print '</td><td>';
-		if (!empty($conf->accounting->enabled))
-		{
+		if (!empty($conf->accounting->enabled)) {
 			$accountingaccount3 = new AccountingAccount($db);
 			$accountingaccount3->fetch('', $object->accountancy_code_depreciation_expense, 1);
 
@@ -499,14 +497,12 @@ if ($rowid > 0)
 		print '<div class="tabsAction">';
 
 		// Edit
-		if ($user->rights->asset->write)
-		{
+		if ($user->rights->asset->write) {
 			print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&amp;rowid='.$object->id.'">'.$langs->trans("Modify").'</a></div>';
 		}
 
 		// Delete
-		if ($user->rights->asset->write)
-		{
+		if ($user->rights->asset->write) {
 			print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=delete&token='.newToken().'&rowid='.$object->id.'">'.$langs->trans("DeleteType").'</a></div>';
 		}
 
@@ -519,12 +515,13 @@ if ($rowid > 0)
 	/*                                                                            */
 	/* ************************************************************************** */
 
-	if ($action == 'edit')
-	{
+	if ($action == 'edit') {
 		$object = new AssetType($db);
 		$object->fetch($rowid);
 		$object->fetch_optionals();
-		if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db);
+		if (!empty($conf->accounting->enabled)) {
+			$formaccounting = new FormAccounting($db);
+		}
 
 		$head = asset_type_prepare_head($object);
 
@@ -541,8 +538,7 @@ if ($rowid > 0)
 
 		print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td><input type="text" name="label" size="40" value="'.dol_escape_htmltag($object->label).'"></td></tr>';
 
-		if (!empty($conf->accounting->enabled))
-		{
+		if (!empty($conf->accounting->enabled)) {
 			// Accountancy_code_asset
 			print '<tr><td class="titlefield">'.$langs->trans("AccountancyCodeAsset").'</td>';
 			print '<td>';
@@ -585,8 +581,7 @@ if ($rowid > 0)
 		$parameters = array();
 		$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $act, $action); // Note that $action and $object may have been modified by hook
 		print $hookmanager->resPrint;
-		if (empty($reshook))
-		{
+		if (empty($reshook)) {
 			print $object->showOptionals($extrafields, 'edit', $parameters);
 		}
 

+ 4 - 8
htdocs/asterisk/cidlookup.php

@@ -33,15 +33,13 @@ $phone = GETPOST('phone');
 $notfound = $langs->trans("Unknown");
 
 // Security check
-if (empty($conf->clicktodial->enabled))
-{
+if (empty($conf->clicktodial->enabled)) {
 	print "Error: Module Click to dial is not enabled.\n";
 	exit;
 }
 
 // Check parameters
-if (empty($phone))
-{
+if (empty($phone)) {
 	print "Error: Url must be called with parameter phone=phone to search\n";
 	exit;
 }
@@ -57,11 +55,9 @@ $sql .= $db->plimit(1);
 
 dol_syslog('cidlookup search information with phone '.$phone, LOG_DEBUG);
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$obj = $db->fetch_object($resql);
-	if ($obj)
-	{
+	if ($obj) {
 		$found = $obj->name;
 	} else {
 		$found = $notfound;

+ 54 - 28
htdocs/asterisk/wrapper.php

@@ -28,13 +28,27 @@
  * 				write = system,call,log,verbose,command,agent,user
  */
 
-if (!defined('NOREQUIRESOC'))    define('NOREQUIRESOC', '1');
-if (!defined('NOREQUIRETRAN'))   define('NOREQUIRETRAN', '1');
-if (!defined('NOCSRFCHECK'))     define('NOCSRFCHECK', '1');
-if (!defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL', '1');
-if (!defined('NOREQUIREMENU'))   define('NOREQUIREMENU', '1');
-if (!defined('NOREQUIREHTML'))   define('NOREQUIREHTML', '1');
-if (!defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX', '1');
+if (!defined('NOREQUIRESOC')) {
+	define('NOREQUIRESOC', '1');
+}
+if (!defined('NOREQUIRETRAN')) {
+	define('NOREQUIRETRAN', '1');
+}
+if (!defined('NOCSRFCHECK')) {
+	define('NOCSRFCHECK', '1');
+}
+if (!defined('NOTOKENRENEWAL')) {
+	define('NOTOKENRENEWAL', '1');
+}
+if (!defined('NOREQUIREMENU')) {
+	define('NOREQUIREMENU', '1');
+}
+if (!defined('NOREQUIREHTML')) {
+	define('NOREQUIREHTML', '1');
+}
+if (!defined('NOREQUIREAJAX')) {
+	define('NOREQUIREAJAX', '1');
+}
 
 /**
  * Empty header
@@ -67,23 +81,40 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 
 
 // Security check
-if (empty($conf->clicktodial->enabled))
-{
+if (empty($conf->clicktodial->enabled)) {
 	accessforbidden();
 	exit;
 }
 
 
 // Define Asterisk setup
-if (!isset($conf->global->ASTERISK_HOST))      $conf->global->ASTERISK_HOST = "127.0.0.1";
-if (!isset($conf->global->ASTERISK_TYPE))      $conf->global->ASTERISK_TYPE = "SIP/";
-if (!isset($conf->global->ASTERISK_INDICATIF)) $conf->global->ASTERISK_INDICATIF = "0";
-if (!isset($conf->global->ASTERISK_PORT))      $conf->global->ASTERISK_PORT = 5038;
-if ($conf->global->ASTERISK_INDICATIF == 'NONE')  $conf->global->ASTERISK_INDICATIF = '';
-if (!isset($conf->global->ASTERISK_CONTEXT))   $conf->global->ASTERISK_CONTEXT = "from-internal";
-if (!isset($conf->global->ASTERISK_WAIT_TIME)) $conf->global->ASTERISK_WAIT_TIME = "30";
-if (!isset($conf->global->ASTERISK_PRIORITY))  $conf->global->ASTERISK_PRIORITY = "1";
-if (!isset($conf->global->ASTERISK_MAX_RETRY)) $conf->global->ASTERISK_MAX_RETRY = "2";
+if (!isset($conf->global->ASTERISK_HOST)) {
+	$conf->global->ASTERISK_HOST = "127.0.0.1";
+}
+if (!isset($conf->global->ASTERISK_TYPE)) {
+	$conf->global->ASTERISK_TYPE = "SIP/";
+}
+if (!isset($conf->global->ASTERISK_INDICATIF)) {
+	$conf->global->ASTERISK_INDICATIF = "0";
+}
+if (!isset($conf->global->ASTERISK_PORT)) {
+	$conf->global->ASTERISK_PORT = 5038;
+}
+if ($conf->global->ASTERISK_INDICATIF == 'NONE') {
+	$conf->global->ASTERISK_INDICATIF = '';
+}
+if (!isset($conf->global->ASTERISK_CONTEXT)) {
+	$conf->global->ASTERISK_CONTEXT = "from-internal";
+}
+if (!isset($conf->global->ASTERISK_WAIT_TIME)) {
+	$conf->global->ASTERISK_WAIT_TIME = "30";
+}
+if (!isset($conf->global->ASTERISK_PRIORITY)) {
+	$conf->global->ASTERISK_PRIORITY = "1";
+}
+if (!isset($conf->global->ASTERISK_MAX_RETRY)) {
+	$conf->global->ASTERISK_MAX_RETRY = "2";
+}
 
 
 $login = GETPOST('login');
@@ -127,11 +158,9 @@ $sql .= $db->plimit(1);
 
 dol_syslog('click to dial search information with phone '.$called, LOG_DEBUG);
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$obj = $db->fetch_object($resql);
-	if ($obj)
-	{
+	if ($obj) {
 		$found = $obj->name;
 	} else {
 		$found = $notfound;
@@ -144,16 +173,13 @@ if ($resql)
 
 $number = strtolower($called);
 $pos = strpos($number, "local");
-if (!empty($number))
-{
-	if ($pos === false)
-	{
+if (!empty($number)) {
+	if ($pos === false) {
 		$errno = 0;
 		$errstr = 0;
 		$strCallerId = "Dolibarr call $found <".strtolower($number).">";
 		$oSocket = @fsockopen($strHost, $port, $errno, $errstr, 10);
-		if (!$oSocket)
-		{
+		if (!$oSocket) {
 			print '<body>'."\n";
 			$txt = "Failed to execute fsockopen($strHost, $port, \$errno, \$errstr, 10)<br>\n";
 			print $txt;

+ 46 - 57
htdocs/barcode/codeinit.php

@@ -52,27 +52,21 @@ $maxperinit = 1000;
  */
 
 // Define barcode template for products
-if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM))
-{
+if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
 	$dirbarcodenum = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
 
-	foreach ($dirbarcodenum as $dirroot)
-	{
+	foreach ($dirbarcodenum as $dirroot) {
 		$dir = dol_buildpath($dirroot, 0);
 
 		$handle = @opendir($dir);
-		if (is_resource($handle))
-		{
-			while (($file = readdir($handle)) !== false)
-			{
-				if (preg_match('/^mod_barcode_product_.*php$/', $file))
-				{
+		if (is_resource($handle)) {
+			while (($file = readdir($handle)) !== false) {
+				if (preg_match('/^mod_barcode_product_.*php$/', $file)) {
 					$file = substr($file, 0, dol_strlen($file) - 4);
 
 					try {
 						dol_include_once($dirroot.$file.'.php');
-					} catch (Exception $e)
-					{
+					} catch (Exception $e) {
 						dol_syslog($e->getMessage(), LOG_ERR);
 					}
 
@@ -85,28 +79,23 @@ if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM))
 	}
 }
 
-if ($action == 'initbarcodeproducts')
-{
-	if (!is_object($modBarCodeProduct))
-	{
+if ($action == 'initbarcodeproducts') {
+	if (!is_object($modBarCodeProduct)) {
 		$error++;
 		setEventMessages($langs->trans("NoBarcodeNumberingTemplateDefined"), null, 'errors');
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		$productstatic = new Product($db);
 
 		$db->begin();
 
 		$nbok = 0;
-		if (!empty($eraseallbarcode))
-		{
+		if (!empty($eraseallbarcode)) {
 			$sql = "UPDATE ".MAIN_DB_PREFIX."product";
 			$sql .= " SET barcode = NULL";
 			$resql = $db->query($sql);
-			if ($resql)
-			{
+			if ($resql) {
 				setEventMessages($langs->trans("AllBarcodeReset"), null, 'mesgs');
 			} else {
 				$error++;
@@ -121,16 +110,13 @@ if ($action == 'initbarcodeproducts')
 
 			dol_syslog("codeinit", LOG_DEBUG);
 			$resql = $db->query($sql);
-			if ($resql)
-			{
+			if ($resql) {
 				$num = $db->num_rows($resql);
 
 				$i = 0; $nbok = $nbtry = 0;
-				while ($i < min($num, $maxperinit))
-				{
+				while ($i < min($num, $maxperinit)) {
 					$obj = $db->fetch_object($resql);
-					if ($obj)
-					{
+					if ($obj) {
 						$productstatic->id = $obj->rowid;
 						$productstatic->ref = $obj->ref;
 						$productstatic->type = $obj->fk_product_type;
@@ -140,7 +126,9 @@ if ($action == 'initbarcodeproducts')
 						$result = $productstatic->setValueFrom('barcode', $nextvalue, '', '', 'text', '', $user, 'PRODUCT_MODIFY');
 
 						$nbtry++;
-						if ($result > 0) $nbok++;
+						if ($result > 0) {
+							$nbok++;
+						}
 					}
 
 					$i++;
@@ -150,14 +138,12 @@ if ($action == 'initbarcodeproducts')
 				dol_print_error($db);
 			}
 
-			if (!$error)
-			{
+			if (!$error) {
 				setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
 			}
 		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			//$db->rollback();
 			$db->commit();
 		} else {
@@ -174,8 +160,12 @@ if ($action == 'initbarcodeproducts')
  * View
  */
 
-if (!$user->admin) accessforbidden();
-if (empty($conf->barcode->enabled)) accessforbidden();
+if (!$user->admin) {
+	accessforbidden();
+}
+if (empty($conf->barcode->enabled)) {
+	accessforbidden();
+}
 
 $form = new Form($db);
 
@@ -198,8 +188,7 @@ print '<input type="hidden" name="token" value="'.newToken().'">';
 print '<br>';
 
 // For thirdparty
-if ($conf->societe->enabled)
-{
+if ($conf->societe->enabled) {
 	$nbno = $nbtotal = 0;
 
 	print load_fiche_titre($langs->trans("BarcodeInitForThirdparties"), '', 'company');
@@ -207,19 +196,21 @@ if ($conf->societe->enabled)
 	print '<br>'."\n";
 	$sql = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."societe where barcode IS NULL or barcode = ''";
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$obj = $db->fetch_object($resql);
 		$nbno = $obj->nb;
-	} else dol_print_error($db);
+	} else {
+		dol_print_error($db);
+	}
 
 	$sql = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."societe";
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$obj = $db->fetch_object($resql);
 		$nbtotal = $obj->nb;
-	} else dol_print_error($db);
+	} else {
+		dol_print_error($db);
+	}
 
 	print $langs->trans("CurrentlyNWithoutBarCode", $nbno, $nbtotal, $langs->transnoentitiesnoconv("ThirdParties")).'<br>'."\n";
 
@@ -231,8 +222,7 @@ if ($conf->societe->enabled)
 
 
 // For products
-if ($conf->product->enabled || $conf->product->service)
-{
+if ($conf->product->enabled || $conf->product->service) {
 	// Example 1 : Adding jquery code
 	print '<script type="text/javascript" language="javascript">
 	function confirm_erase() {
@@ -251,32 +241,32 @@ if ($conf->product->enabled || $conf->product->service)
 	$sql .= " GROUP BY fk_product_type, datec";
 	$sql .= " ORDER BY datec";
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$num = $db->num_rows($resql);
 
 		$i = 0;
-		while ($i < $num)
-		{
+		while ($i < $num) {
 			$obj = $db->fetch_object($resql);
 			$nbno += $obj->nb;
 
 			$i++;
 		}
-	} else dol_print_error($db);
+	} else {
+		dol_print_error($db);
+	}
 
 	$sql = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."product";
 	$resql = $db->query($sql);
-	if ($resql)
-	{
+	if ($resql) {
 		$obj = $db->fetch_object($resql);
 		$nbtotal = $obj->nb;
-	} else dol_print_error($db);
+	} else {
+		dol_print_error($db);
+	}
 
 	print $langs->trans("CurrentlyNWithoutBarCode", $nbno, $nbtotal, $langs->transnoentitiesnoconv("ProductsOrServices")).'<br>'."\n";
 
-	if (is_object($modBarCodeProduct))
-	{
+	if (is_object($modBarCodeProduct)) {
 		print $langs->trans("BarCodeNumberManager").": ";
 		$objproduct = new Product($db);
 		print '<b>'.(isset($modBarCodeProduct->name) ? $modBarCodeProduct->name : $modBarCodeProduct->nom).'</b> - '.$langs->trans("NextValue").': <b>'.$modBarCodeProduct->getNextValue($objproduct).'</b><br>';
@@ -286,8 +276,7 @@ if ($conf->product->enabled || $conf->product->service)
 		$titleno = $langs->trans("NoBarcodeNumberingTemplateDefined");
 		print '<font class="warning">'.$langs->trans("NoBarcodeNumberingTemplateDefined").'</font> (<a href="'.DOL_URL_ROOT.'/admin/barcode.php">'.$langs->trans("ToGenerateCodeDefineAutomaticRuleFirst").'</a>)<br>';
 	}
-	if (empty($nbno))
-	{
+	if (empty($nbno)) {
 		$disabled1 = 1;
 	}
 

+ 44 - 58
htdocs/barcode/printsheet.php

@@ -24,7 +24,9 @@
  */
 
 if (!empty($_POST['mode']) && $_POST['mode'] === 'label') {	// Page is called to build a PDF and output, we must ne renew the token.
-	if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+	if (!defined('NOTOKENRENEWAL')) {
+		define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+	}
 }
 
 require '../main.inc.php';
@@ -59,8 +61,7 @@ $thirdpartytmp = new Societe($db);
  * Actions
  */
 
-if (GETPOST('submitproduct') && GETPOST('submitproduct'))
-{
+if (GETPOST('submitproduct') && GETPOST('submitproduct')) {
 	$action = ''; // We reset because we don't want to build doc
 	if (GETPOST('productid', 'int') > 0) {
 		$result = $producttmp->fetch(GETPOST('productid', 'int'));
@@ -70,62 +71,56 @@ if (GETPOST('submitproduct') && GETPOST('submitproduct'))
 		$forbarcode = $producttmp->barcode;
 		$fk_barcode_type = $producttmp->barcode_type;
 
-		if (empty($fk_barcode_type) && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
+		if (empty($fk_barcode_type) && !empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) {
+			$fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
+		}
 
-		if (empty($forbarcode) || empty($fk_barcode_type))
-		{
+		if (empty($forbarcode) || empty($fk_barcode_type)) {
 			setEventMessages($langs->trans("DefinitionOfBarCodeForProductNotComplete", $producttmp->getNomUrl()), null, 'warnings');
 		}
 	}
 }
-if (GETPOST('submitthirdparty') && GETPOST('submitthirdparty'))
-{
+if (GETPOST('submitthirdparty') && GETPOST('submitthirdparty')) {
 	$action = ''; // We reset because we don't want to build doc
-	if (GETPOST('socid', 'int') > 0)
-	{
+	if (GETPOST('socid', 'int') > 0) {
 		$thirdpartytmp->fetch(GETPOST('socid', 'int'));
 		$forbarcode = $thirdpartytmp->barcode;
 		$fk_barcode_type = $thirdpartytmp->barcode_type_code;
 
-		if (empty($fk_barcode_type) && !empty($conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY)) $fk_barcode_type = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
+		if (empty($fk_barcode_type) && !empty($conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY)) {
+			$fk_barcode_type = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
+		}
 
-		if (empty($forbarcode) || empty($fk_barcode_type))
-		{
+		if (empty($forbarcode) || empty($fk_barcode_type)) {
 			setEventMessages($langs->trans("DefinitionOfBarCodeForThirdpartyNotComplete", $thirdpartytmp->getNomUrl()), null, 'warnings');
 		}
 	}
 }
 
-if ($action == 'builddoc')
-{
+if ($action == 'builddoc') {
 	$result = 0; $error = 0;
 
-	if (empty($forbarcode))			// barcode value
-	{
+	if (empty($forbarcode)) {			// barcode value
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BarcodeValue")), null, 'errors');
 		$error++;
 	}
-	if (empty($fk_barcode_type))		// barcode type = barcode encoding
-	{
+	if (empty($fk_barcode_type)) {		// barcode type = barcode encoding
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BarcodeType")), null, 'errors');
 		$error++;
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		// Get encoder (barcode_type_coder) from barcode type id (barcode_type)
 		$stdobject = new GenericObject($db);
 		$stdobject->barcode_type = $fk_barcode_type;
 		$result = $stdobject->fetch_barcode();
-		if ($result <= 0)
-		{
+		if ($result <= 0) {
 			$error++;
 			setEventMessages('Failed to get bar code type information '.$stdobject->error, $stdobject->errors, 'errors');
 		}
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		$code = $forbarcode;
 		$generator = $stdobject->barcode_type_coder; // coder (loaded by fetch_barcode). Engine.
 		$encoding = strtoupper($stdobject->barcode_type_code); // code (loaded by fetch_barcode). Example 'ean', 'isbn', ...
@@ -136,34 +131,34 @@ if ($action == 'builddoc')
 		// Generate barcode
 		$dirbarcode = array_merge(array("/core/modules/barcode/doc/"), $conf->modules_parts['barcode']);
 
-		foreach ($dirbarcode as $reldir)
-		{
+		foreach ($dirbarcode as $reldir) {
 			$dir = dol_buildpath($reldir, 0);
 			$newdir = dol_osencode($dir);
 
 			// Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php)
-			if (!is_dir($newdir)) continue;
+			if (!is_dir($newdir)) {
+				continue;
+			}
 
 			$result = @include_once $newdir.$generator.'.modules.php';
-			if ($result) break;
+			if ($result) {
+				break;
+			}
 		}
 
 		// Load barcode class for generating barcode image
 		$classname = "mod".ucfirst($generator);
 		$module = new $classname($db);
-		if ($generator != 'tcpdfbarcode')
-		{
+		if ($generator != 'tcpdfbarcode') {
 			// May be phpbarcode
 			$template = 'standardlabel';
 			$is2d = false;
-			if ($module->encodingIsSupported($encoding))
-			{
+			if ($module->encodingIsSupported($encoding)) {
 				$barcodeimage = $conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png';
 				dol_delete_file($barcodeimage);
 				// File is created with full name $barcodeimage = $conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png';
 				$result = $module->writeBarCode($code, $encoding, 'Y', 4, 1);
-				if ($result <= 0 || !dol_is_file($barcodeimage))
-				{
+				if ($result <= 0 || !dol_is_file($barcodeimage)) {
 					$error++;
 					setEventMessages('Failed to generate image file of barcode for code='.$code.' encoding='.$encoding.' file='.basename($barcodeimage), null, 'errors');
 					setEventMessages($module->error, null, 'errors');
@@ -179,8 +174,7 @@ if ($action == 'builddoc')
 		}
 	}
 
-	if (!$error)
-	{
+	if (!$error) {
 		// List of values to scan for a replacement
 		$substitutionarray = array(
 			'%LOGIN%' => $user->login,
@@ -200,8 +194,7 @@ if ($action == 'builddoc')
 		complete_substitutions_array($substitutionarray, $langs);
 
 		// For labels
-		if ($mode == 'label')
-		{
+		if ($mode == 'label') {
 			$txtforsticker = "%PHOTO%"; // Photo will be barcode image, %BARCODE% posible when using TCPDF generator
 			$textleft = make_substitutions((empty($conf->global->BARCODE_LABEL_LEFT_TEXT) ? $txtforsticker : $conf->global->BARCODE_LABEL_LEFT_TEXT), $substitutionarray);
 			$textheader = make_substitutions((empty($conf->global->BARCODE_LABEL_HEADER_TEXT) ? '' : $conf->global->BARCODE_LABEL_HEADER_TEXT), $substitutionarray);
@@ -210,8 +203,7 @@ if ($action == 'builddoc')
 			$forceimgscalewidth = (empty($conf->global->BARCODE_FORCEIMGSCALEWIDTH) ? 1 : $conf->global->BARCODE_FORCEIMGSCALEWIDTH);
 			$forceimgscaleheight = (empty($conf->global->BARCODE_FORCEIMGSCALEHEIGHT) ? 1 : $conf->global->BARCODE_FORCEIMGSCALEHEIGHT);
 
-			for ($i = 0; $i < $numberofsticker; $i++)
-			{
+			for ($i = 0; $i < $numberofsticker; $i++) {
 				$arrayofrecords[] = array(
 					'textleft'=>$textleft,
 					'textheader'=>$textheader,
@@ -229,14 +221,11 @@ if ($action == 'builddoc')
 		$mesg = '';
 
 		// Build and output PDF
-		if ($mode == 'label')
-		{
-			if (!count($arrayofrecords))
-			{
+		if ($mode == 'label') {
+			if (!count($arrayofrecords)) {
 				$mesg = $langs->trans("ErrorRecordNotFound");
 			}
-			if (empty($modellabel) || $modellabel == '-1')
-			{
+			if (empty($modellabel) || $modellabel == '-1') {
 				$mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_ETIQUETTE_TYPE"));
 			}
 
@@ -269,7 +258,9 @@ if ($action == 'builddoc')
  * View
  */
 
-if (empty($conf->barcode->enabled)) accessforbidden();
+if (empty($conf->barcode->enabled)) {
+	accessforbidden();
+}
 
 $form = new Form($db);
 
@@ -300,8 +291,7 @@ print $langs->trans("DescADHERENT_ETIQUETTE_TYPE").' &nbsp; ';
 print '</div><div class="tagtd maxwidthonsmartphone" style="overflow: hidden; white-space: nowrap;">';
 // List of possible labels (defined into $_Avery_Labels variable set into core/lib/format_cards.lib.php)
 $arrayoflabels = array();
-foreach (array_keys($_Avery_Labels) as $codecards)
-{
+foreach (array_keys($_Avery_Labels) as $codecards) {
 	$labeltoshow = $_Avery_Labels[$codecards]['name'];
 	//$labeltoshow.=' ('.$_Avery_Labels[$row['code']]['paper-size'].')';
 	$arrayoflabels[$codecards] = $labeltoshow;
@@ -387,8 +377,7 @@ jQuery(document).ready(function() {
 print '<input id="fillmanually" type="radio" '.((!GETPOST("selectorforbarcode") || GETPOST("selectorforbarcode") == 'fillmanually') ? 'checked ' : '').'name="selectorforbarcode" value="fillmanually" class="radiobarcodeselect"> '.$langs->trans("FillBarCodeTypeAndValueManually").' &nbsp; ';
 print '<br>';
 
-if (!empty($user->rights->produit->lire) || !empty($user->rights->service->lire))
-{
+if (!empty($user->rights->produit->lire) || !empty($user->rights->service->lire)) {
 	print '<input id="fillfromproduct" type="radio" '.((GETPOST("selectorforbarcode") == 'fillfromproduct') ? 'checked ' : '').'name="selectorforbarcode" value="fillfromproduct" class="radiobarcodeselect"> '.$langs->trans("FillBarCodeTypeAndValueFromProduct").' &nbsp; ';
 	print '<br>';
 	print '<div class="showforproductselector">';
@@ -397,8 +386,7 @@ if (!empty($user->rights->produit->lire) || !empty($user->rights->service->lire)
 	print '</div>';
 }
 
-if (!empty($user->rights->societe->lire))
-{
+if (!empty($user->rights->societe->lire)) {
 	print '<input id="fillfromthirdparty" type="radio" '.((GETPOST("selectorforbarcode") == 'fillfromthirdparty') ? 'checked ' : '').'name="selectorforbarcode" value="fillfromthirdparty" class="radiobarcodeselect"> '.$langs->trans("FillBarCodeTypeAndValueFromThirdParty").' &nbsp; ';
 	print '<br>';
 	print '<div class="showforthirdpartyselector">';
@@ -409,12 +397,10 @@ if (!empty($user->rights->societe->lire))
 
 print '<br>';
 
-if ($producttmp->id > 0)
-{
+if ($producttmp->id > 0) {
 	print $langs->trans("BarCodeDataForProduct", '').' '.$producttmp->getNomUrl(1).'<br>';
 }
-if ($thirdpartytmp->id > 0)
-{
+if ($thirdpartytmp->id > 0) {
 	print $langs->trans("BarCodeDataForThirdparty", '').' '.$thirdpartytmp->getNomUrl(1).'<br>';
 }
 

+ 14 - 16
htdocs/comm/propal/class/propal.class.php

@@ -13,7 +13,7 @@
  * Copyright (C) 2013      Florian Henry		  	<florian.henry@open-concept.pro>
  * Copyright (C) 2014-2015 Marcos García            <marcosgdf@gmail.com>
  * Copyright (C) 2018      Nicolas ZABOURI			<info@inovea-conseil.com>
- * Copyright (C) 2018-2020 Frédéric France          <frederic.france@netlogic.fr>
+ * Copyright (C) 2018-2021 Frédéric France          <frederic.france@netlogic.fr>
  * Copyright (C) 2018      Ferran Marcet         	<fmarcet@2byte.es>
  *
  * This program is free software; you can redistribute it and/or modify
@@ -1463,14 +1463,14 @@ class Propal extends CommonObject
 		if ($ref) {
 			$sql .= " WHERE p.entity IN (".getEntity('propal').")"; // Dont't use entity if you use rowid
 			$sql .= " AND p.ref='".$this->db->escape($ref)."'";
-		} else $sql .= " WHERE p.rowid=".$rowid;
+		} else {
+			$sql .= " WHERE p.rowid=".$rowid;
+		}
 
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
 		$resql = $this->db->query($sql);
-		if ($resql)
-		{
-			if ($this->db->num_rows($resql))
-			{
+		if ($resql) {
+			if ($this->db->num_rows($resql)) {
 				$obj = $this->db->fetch_object($resql);
 
 				$this->id                   = $obj->rowid;
@@ -1481,12 +1481,12 @@ class Propal extends CommonObject
 				$this->remise               = $obj->remise;
 				$this->remise_percent       = $obj->remise_percent;
 				$this->remise_absolue       = $obj->remise_absolue;
-				$this->total                = $obj->total; // TODO deprecated
+				$this->total                = $obj->total_ttc; // TODO deprecated
+				$this->total_ttc            = $obj->total_ttc;
 				$this->total_ht             = $obj->total_ht;
 				$this->total_tva            = $obj->total_tva;
 				$this->total_localtax1		= $obj->localtax1;
 				$this->total_localtax2		= $obj->localtax2;
-				$this->total_ttc            = $obj->total;
 
 				$this->socid = $obj->fk_soc;
 				$this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
@@ -1537,8 +1537,8 @@ class Propal extends CommonObject
 				$this->extraparams = (array) json_decode($obj->extraparams, true);
 
 				$this->user_author_id = $obj->fk_user_author;
-				$this->user_valid_id  = $obj->fk_user_valid;
-				$this->user_close_id  = $obj->fk_user_cloture;
+				$this->user_valid_id = $obj->fk_user_valid;
+				$this->user_close_id = $obj->fk_user_cloture;
 
 				//Incoterms
 				$this->fk_incoterms = $obj->fk_incoterms;
@@ -1550,11 +1550,10 @@ class Propal extends CommonObject
 				$this->multicurrency_code = $obj->multicurrency_code;
 				$this->multicurrency_tx 		= $obj->multicurrency_tx;
 				$this->multicurrency_total_ht = $obj->multicurrency_total_ht;
-				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
-				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
+				$this->multicurrency_total_tva = $obj->multicurrency_total_tva;
+				$this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
 
-				if ($obj->fk_statut == self::STATUS_DRAFT)
-				{
+				if ($obj->fk_statut == self::STATUS_DRAFT) {
 					$this->brouillon = 1;
 				}
 
@@ -1568,8 +1567,7 @@ class Propal extends CommonObject
 
 				// Lines
 				$result = $this->fetch_lines();
-				if ($result < 0)
-				{
+				if ($result < 0) {
 					return -3;
 				}
 

+ 6 - 4
htdocs/core/js/lib_head.js.php

@@ -574,11 +574,12 @@ function setConstant(url, code, input, entity, strict, forcereload, userid, toke
 				$.each(data, function(key, value) {
 					$("#set_" + key).hide();
 					$("#del_" + key).show();
-					$.get( url, {
+					$.post( url, {
 						action: "set",
 						name: key,
 						value: value,
-						entity: entity
+						entity: entity,
+						token: token
 					});
 				});
 			}
@@ -644,10 +645,11 @@ function delConstant(url, code, input, entity, strict, forcereload, userid, toke
 				$.each(data, function(key, value) {
 					$("#del_" + value).hide();
 					$("#set_" + value).show();
-					$.get( url, {
+					$.post( url, {
 						action: "del",
 						name: value,
-						entity: entity
+						entity: entity,
+						token: token
 					});
 				});
 			}

+ 11 - 0
htdocs/core/lib/project.lib.php

@@ -121,6 +121,17 @@ function project_prepare_head(Project $project)
 		$h++;
 	}
 
+	if ($conf->eventorganization->enabled) {
+		$langs->load('eventorganization');
+		//TODO : Count
+		$nbConfOrBooth = 1;
+		$head[$h][0] = DOL_URL_ROOT . '/projet/event.php?id=' . $project->id;
+		$head[$h][1] = $langs->trans("ConferenceOrBoothTab");
+		if ($nbContact > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">' . $nbConfOrBooth . '</span>';
+		$head[$h][2] = 'eventorganisation';
+		$h++;
+	}
+
 	// Show more tabs from modules
 	// Entries must be declared in modules descriptor with line
 	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab

+ 15 - 0
htdocs/core/modules/modEventOrganization.class.php

@@ -256,6 +256,21 @@ class modEventOrganization extends DolibarrModules
 		$this->rights[$r][1] = 'Delete objects of EventOrganization'; // Permission label
 		$this->rights[$r][4] = 'delete'; // In php code, permission will be checked by test if ($user->rights->eventorganization->level1)
 		$r++;
+		/*$this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used)
+		$this->rights[$r][1] = 'Read objects of EventOrganization - Conference Or Booth'; // Permission label
+		$this->rights[$r][4] = 'conferenceorbooth'; // In php code, permission will be checked by test if ($user->rights->eventorganization->level1)
+		$this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->eventorganization->level1)
+		$r++;
+		$this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used)
+		$this->rights[$r][1] = 'Create/Update objects of EventOrganization - Conference Or Booth'; // Permission label
+		$this->rights[$r][4] = 'conferenceorbooth'; // In php code, permission will be checked by test if ($user->rights->eventorganization->level1)
+		$this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->eventorganization->level1)
+		$r++;
+		$this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used)
+		$this->rights[$r][1] = 'Delete objects of EventOrganization - Conference Or Booth'; // Permission label
+		$this->rights[$r][4] = 'conferenceorbooth'; // In php code, permission will be checked by test if ($user->rights->eventorganization->level1)
+		$this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->rights->eventorganization->level1)
+		$r++;*/
 		/* END MODULEBUILDER PERMISSIONS */
 
 		// Main menu entries to add

+ 1058 - 0
htdocs/eventorganization/class/conferenceorbooth.class.php

@@ -0,0 +1,1058 @@
+<?php
+/* Copyright (C) 2017  Laurent Destailleur <eldy@users.sourceforge.net>
+ * Copyright (C) ---Put here your own copyright and developer email---
+ *
+ * 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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ * \file        class/conferenceorbooth.class.php
+ * \ingroup     eventorganization
+ * \brief       This file is a CRUD class file for ConferenceOrBooth (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for ConferenceOrBooth
+ */
+class ConferenceOrBooth extends CommonObject
+{
+	/**
+	 * @var string ID of module.
+	 */
+	public $module = 'eventorganization';
+
+	/**
+	 * @var string ID to identify managed object.
+	 */
+	public $element = 'conferenceorbooth';
+
+	/**
+	 * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+	 */
+	public $table_element = 'actioncomm';
+
+	/**
+	 * @var int  Does this object support multicompany module ?
+	 * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+	 */
+	public $ismultientitymanaged = 1;
+
+	/**
+	 * @var int  Does object support extrafields ? 0=No, 1=Yes
+	 */
+	public $isextrafieldmanaged = 1;
+
+	/**
+	 * @var string String with name of icon for conferenceorbooth. Must be the part after the 'object_' into object_conferenceorbooth.png
+	 */
+	public $picto = 'conferenceorbooth@eventorganization';
+
+
+	const STATUS_DRAFT = 0;
+	const STATUS_VALIDATED = 1;
+	const STATUS_CANCELED = 9;
+
+
+	/**
+	 *  'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
+	 *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
+	 *  'label' the translation key.
+	 *  'picto' is code of a picto to show before value in forms
+	 *  'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
+	 *  'position' is the sort order of field.
+	 *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+	 *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+	 *  'noteditable' says if field is not editable (1 or 0)
+	 *  'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+	 *  'index' if we want an index in database.
+	 *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+	 *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+	 *  'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
+	 *  'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'maxwidth200', 'wordbreak', 'tdoverflowmax200'
+	 *  'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
+	 *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+	 *  'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+	 *  'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
+	 *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+	 *  'comment' is not used. You can store here any text of your choice. It is not used by application.
+	 *
+	 *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+	 */
+
+	// BEGIN MODULEBUILDER PROPERTIES
+	/**
+	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+	 */
+	public $fields=array(
+		'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
+		'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>10, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'comment'=>"Reference of object"),
+		'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'help'=>"Help text", 'showoncombobox'=>'1',),
+		//'amount' => array('type'=>'price', 'label'=>'Amount', 'enabled'=>'1', 'position'=>40, 'notnull'=>0, 'visible'=>1, 'default'=>'null', 'isameasure'=>'1', 'help'=>"Help text for amount",),
+		//'qty' => array('type'=>'real', 'label'=>'Qty', 'enabled'=>'1', 'position'=>45, 'notnull'=>0, 'visible'=>1, 'default'=>'0', 'isameasure'=>'1', 'css'=>'maxwidth75imp', 'help'=>"Help text for quantity",),
+		'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1:status=1 AND entity IN (__SHARED_ENTITIES__)', 'label'=>'ThirdParty', 'enabled'=>'1', 'position'=>50, 'notnull'=>-1, 'visible'=>1, 'index'=>1, 'help'=>"LinkToThirparty",),
+		'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1', 'label'=>'Project', 'enabled'=>'1', 'position'=>52, 'notnull'=>-1, 'visible'=>-1, 'index'=>1,),
+		'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3,),
+		'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>61, 'notnull'=>0, 'visible'=>0,),
+		'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>62, 'notnull'=>0, 'visible'=>0,),
+		'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
+		'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
+		'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
+		'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
+		'last_main_doc' => array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>'1', 'position'=>600, 'notnull'=>0, 'visible'=>0,),
+		'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
+		'model_pdf' => array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>'1', 'position'=>1010, 'notnull'=>-1, 'visible'=>0,),
+		'status' => array('type'=>'smallint', 'label'=>'Status', 'enabled'=>'1', 'position'=>1000, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Brouillon', '1'=>'Valid&eacute;', '9'=>'Annul&eacute;'),),
+	);
+	public $rowid;
+	public $ref;
+	public $label;
+	public $amount;
+	public $qty;
+	public $fk_soc;
+	public $fk_project;
+	public $description;
+	public $note_public;
+	public $note_private;
+	public $date_creation;
+	public $tms;
+	public $fk_user_creat;
+	public $fk_user_modif;
+	public $last_main_doc;
+	public $import_key;
+	public $model_pdf;
+	public $status;
+	// END MODULEBUILDER PROPERTIES
+
+
+	// If this object has a subtable with lines
+
+	// /**
+	//  * @var string    Name of subtable line
+	//  */
+	// public $table_element_line = 'eventorganization_conferenceorboothline';
+
+	// /**
+	//  * @var string    Field with ID of parent key if this object has a parent
+	//  */
+	// public $fk_element = 'fk_conferenceorbooth';
+
+	// /**
+	//  * @var string    Name of subtable class that manage subtable lines
+	//  */
+	// public $class_element_line = 'ConferenceOrBoothline';
+
+	// /**
+	//  * @var array	List of child tables. To test if we can delete object.
+	//  */
+	// protected $childtables = array();
+
+	// /**
+	//  * @var array    List of child tables. To know object to delete on cascade.
+	//  *               If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
+	//  *               call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
+	//  */
+	// protected $childtablesoncascade = array('eventorganization_conferenceorboothdet');
+
+	// /**
+	//  * @var ConferenceOrBoothLine[]     Array of subtable lines
+	//  */
+	// public $lines = array();
+
+
+
+	/**
+	 * Constructor
+	 *
+	 * @param DoliDb $db Database handler
+	 */
+	public function __construct(DoliDB $db)
+	{
+		global $conf, $langs;
+
+		$this->db = $db;
+
+		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
+		if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0;
+
+		// Example to show how to set values of fields definition dynamically
+		/*if ($user->rights->eventorganization->conferenceorbooth->read) {
+			$this->fields['myfield']['visible'] = 1;
+			$this->fields['myfield']['noteditable'] = 0;
+		}*/
+
+		// Unset fields that are disabled
+		foreach ($this->fields as $key => $val)
+		{
+			if (isset($val['enabled']) && empty($val['enabled']))
+			{
+				unset($this->fields[$key]);
+			}
+		}
+
+		// Translate some data of arrayofkeyval
+		if (is_object($langs))
+		{
+			foreach ($this->fields as $key => $val)
+			{
+				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
+				{
+					foreach ($val['arrayofkeyval'] as $key2 => $val2)
+					{
+						$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
+					}
+				}
+			}
+		}
+	}
+
+	/**
+	 * Create object into database
+	 *
+	 * @param  User $user      User that creates
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, Id of created object if OK
+	 */
+	public function create(User $user, $notrigger = false)
+	{
+		return $this->createCommon($user, $notrigger);
+	}
+
+	/**
+	 * Clone an object into another one
+	 *
+	 * @param  	User 	$user      	User that creates
+	 * @param  	int 	$fromid     Id of object to clone
+	 * @return 	mixed 				New object created, <0 if KO
+	 */
+	public function createFromClone(User $user, $fromid)
+	{
+		global $langs, $extrafields;
+		$error = 0;
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$object = new self($this->db);
+
+		$this->db->begin();
+
+		// Load source object
+		$result = $object->fetchCommon($fromid);
+		if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines();
+
+		// get lines so they will be clone
+		//foreach($this->lines as $line)
+		//	$line->fetch_optionals();
+
+		// Reset some properties
+		unset($object->id);
+		unset($object->fk_user_creat);
+		unset($object->import_key);
+
+		// Clear fields
+		if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+		if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+		if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; }
+		if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); }
+		if (property_exists($object, 'date_modification')) { $object->date_modification = null; }
+		// ...
+		// Clear extrafields that are unique
+		if (is_array($object->array_options) && count($object->array_options) > 0)
+		{
+			$extrafields->fetch_name_optionals_label($this->table_element);
+			foreach ($object->array_options as $key => $option)
+			{
+				$shortkey = preg_replace('/options_/', '', $key);
+				if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey]))
+				{
+					//var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
+					unset($object->array_options[$key]);
+				}
+			}
+		}
+
+		// Create clone
+		$object->context['createfromclone'] = 'createfromclone';
+		$result = $object->createCommon($user);
+		if ($result < 0) {
+			$error++;
+			$this->error = $object->error;
+			$this->errors = $object->errors;
+		}
+
+		if (!$error)
+		{
+			// copy internal contacts
+			if ($this->copy_linked_contact($object, 'internal') < 0)
+			{
+				$error++;
+			}
+		}
+
+		if (!$error)
+		{
+			// copy external contacts if same company
+			if (property_exists($this, 'socid') && $this->socid == $object->socid)
+			{
+				if ($this->copy_linked_contact($object, 'external') < 0)
+					$error++;
+			}
+		}
+
+		unset($object->context['createfromclone']);
+
+		// End
+		if (!$error) {
+			$this->db->commit();
+			return $object;
+		} else {
+			$this->db->rollback();
+			return -1;
+		}
+	}
+
+	/**
+	 * Load object in memory from the database
+	 *
+	 * @param int    $id   Id object
+	 * @param string $ref  Ref
+	 * @return int         <0 if KO, 0 if not found, >0 if OK
+	 */
+	public function fetch($id, $ref = null)
+	{
+		$result = $this->fetchCommon($id, $ref);
+		if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
+		return $result;
+	}
+
+	/**
+	 * Load object lines in memory from the database
+	 *
+	 * @return int         <0 if KO, 0 if not found, >0 if OK
+	 */
+	public function fetchLines()
+	{
+		$this->lines = array();
+
+		$result = $this->fetchLinesCommon();
+		return $result;
+	}
+
+
+	/**
+	 * Load list of objects in memory from the database.
+	 *
+	 * @param  string      $sortorder    Sort Order
+	 * @param  string      $sortfield    Sort field
+	 * @param  int         $limit        limit
+	 * @param  int         $offset       Offset
+	 * @param  array       $filter       Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+	 * @param  string      $filtermode   Filter mode (AND or OR)
+	 * @return array|int                 int <0 if KO, array of pages if OK
+	 */
+	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+	{
+		global $conf;
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$records = array();
+
+		$sql = 'SELECT ';
+		$sql .= $this->getFieldList();
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
+		else $sql .= ' WHERE 1 = 1';
+		// Manage filter
+		$sqlwhere = array();
+		if (count($filter) > 0) {
+			foreach ($filter as $key => $value) {
+				if ($key == 't.rowid') {
+					$sqlwhere[] = $key.'='.$value;
+				} elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+					$sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
+				} elseif ($key == 'customsql') {
+					$sqlwhere[] = $value;
+				} elseif (strpos($value, '%') === false) {
+					$sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
+				} else {
+					$sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
+				}
+			}
+		}
+		if (count($sqlwhere) > 0) {
+			$sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')';
+		}
+
+		if (!empty($sortfield)) {
+			$sql .= $this->db->order($sortfield, $sortorder);
+		}
+		if (!empty($limit)) {
+			$sql .= ' '.$this->db->plimit($limit, $offset);
+		}
+
+		$resql = $this->db->query($sql);
+		if ($resql) {
+			$num = $this->db->num_rows($resql);
+			$i = 0;
+			while ($i < ($limit ? min($limit, $num) : $num))
+			{
+				$obj = $this->db->fetch_object($resql);
+
+				$record = new self($this->db);
+				$record->setVarsFromFetchObj($obj);
+
+				$records[$record->id] = $record;
+
+				$i++;
+			}
+			$this->db->free($resql);
+
+			return $records;
+		} else {
+			$this->errors[] = 'Error '.$this->db->lasterror();
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+			return -1;
+		}
+	}
+
+	/**
+	 * Update object into database
+	 *
+	 * @param  User $user      User that modifies
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, >0 if OK
+	 */
+	public function update(User $user, $notrigger = false)
+	{
+		return $this->updateCommon($user, $notrigger);
+	}
+
+	/**
+	 * Delete object in database
+	 *
+	 * @param User $user       User that deletes
+	 * @param bool $notrigger  false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, >0 if OK
+	 */
+	public function delete(User $user, $notrigger = false)
+	{
+		return $this->deleteCommon($user, $notrigger);
+		//return $this->deleteCommon($user, $notrigger, 1);
+	}
+
+	/**
+	 *  Delete a line of object in database
+	 *
+	 *	@param  User	$user       User that delete
+	 *  @param	int		$idline		Id of line to delete
+	 *  @param 	bool 	$notrigger  false=launch triggers after, true=disable triggers
+	 *  @return int         		>0 if OK, <0 if KO
+	 */
+	public function deleteLine(User $user, $idline, $notrigger = false)
+	{
+		if ($this->status < 0)
+		{
+			$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+			return -2;
+		}
+
+		return $this->deleteLineCommon($user, $idline, $notrigger);
+	}
+
+
+	/**
+	 *	Validate object
+	 *
+	 *	@param		User	$user     		User making status change
+	 *  @param		int		$notrigger		1=Does not execute triggers, 0= execute triggers
+	 *	@return  	int						<=0 if OK, 0=Nothing done, >0 if KO
+	 */
+	public function validate($user, $notrigger = 0)
+	{
+		global $conf, $langs;
+
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+		$error = 0;
+
+		// Protection
+		if ($this->status == self::STATUS_VALIDATED)
+		{
+			dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->eventorganization->conferenceorbooth->write))
+		 || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->eventorganization->conferenceorbooth->conferenceorbooth_advance->validate))))
+		 {
+		 $this->error='NotEnoughPermissions';
+		 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
+		 return -1;
+		 }*/
+
+		$now = dol_now();
+
+		$this->db->begin();
+
+		// Define new ref
+		if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
+		{
+			$num = $this->getNextNumRef();
+		} else {
+			$num = $this->ref;
+		}
+		$this->newref = $num;
+
+		if (!empty($num)) {
+			// Validate
+			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+			$sql .= " SET ref = '".$this->db->escape($num)."',";
+			$sql .= " status = ".self::STATUS_VALIDATED;
+			if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."'";
+			if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id;
+			$sql .= " WHERE rowid = ".$this->id;
+
+			dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
+			$resql = $this->db->query($sql);
+			if (!$resql)
+			{
+				dol_print_error($this->db);
+				$this->error = $this->db->lasterror();
+				$error++;
+			}
+
+			if (!$error && !$notrigger)
+			{
+				// Call trigger
+				$result = $this->call_trigger('CONFERENCEORBOOTH_VALIDATE', $user);
+				if ($result < 0) $error++;
+				// End call triggers
+			}
+		}
+
+		if (!$error)
+		{
+			$this->oldref = $this->ref;
+
+			// Rename directory if dir was a temporary ref
+			if (preg_match('/^[\(]?PROV/i', $this->ref))
+			{
+				// Now we rename also files into index
+				$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'conferenceorbooth/".$this->db->escape($this->newref)."'";
+				$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'conferenceorbooth/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+				$resql = $this->db->query($sql);
+				if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
+
+				// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
+				$oldref = dol_sanitizeFileName($this->ref);
+				$newref = dol_sanitizeFileName($num);
+				$dirsource = $conf->eventorganization->dir_output.'/conferenceorbooth/'.$oldref;
+				$dirdest = $conf->eventorganization->dir_output.'/conferenceorbooth/'.$newref;
+				if (!$error && file_exists($dirsource))
+				{
+					dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
+
+					if (@rename($dirsource, $dirdest))
+					{
+						dol_syslog("Rename ok");
+						// Rename docs starting with $oldref with $newref
+						$listoffiles = dol_dir_list($conf->eventorganization->dir_output.'/conferenceorbooth/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+						foreach ($listoffiles as $fileentry)
+						{
+							$dirsource = $fileentry['name'];
+							$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+							$dirsource = $fileentry['path'].'/'.$dirsource;
+							$dirdest = $fileentry['path'].'/'.$dirdest;
+							@rename($dirsource, $dirdest);
+						}
+					}
+				}
+			}
+		}
+
+		// Set new ref and current status
+		if (!$error)
+		{
+			$this->ref = $num;
+			$this->status = self::STATUS_VALIDATED;
+		}
+
+		if (!$error)
+		{
+			$this->db->commit();
+			return 1;
+		} else {
+			$this->db->rollback();
+			return -1;
+		}
+	}
+
+
+	/**
+	 *	Set draft status
+	 *
+	 *	@param	User	$user			Object user that modify
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
+	 *	@return	int						<0 if KO, >0 if OK
+	 */
+	public function setDraft($user, $notrigger = 0)
+	{
+		// Protection
+		if ($this->status <= self::STATUS_DRAFT)
+		{
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->eventorganization->write))
+		 || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->eventorganization->eventorganization_advance->validate))))
+		 {
+		 $this->error='Permission denied';
+		 return -1;
+		 }*/
+
+		return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'CONFERENCEORBOOTH_UNVALIDATE');
+	}
+
+	/**
+	 *	Set cancel status
+	 *
+	 *	@param	User	$user			Object user that modify
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
+	 *	@return	int						<0 if KO, 0=Nothing done, >0 if OK
+	 */
+	public function cancel($user, $notrigger = 0)
+	{
+		// Protection
+		if ($this->status != self::STATUS_VALIDATED)
+		{
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->eventorganization->write))
+		 || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->eventorganization->eventorganization_advance->validate))))
+		 {
+		 $this->error='Permission denied';
+		 return -1;
+		 }*/
+
+		return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'CONFERENCEORBOOTH_CANCEL');
+	}
+
+	/**
+	 *	Set back to validated status
+	 *
+	 *	@param	User	$user			Object user that modify
+	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
+	 *	@return	int						<0 if KO, 0=Nothing done, >0 if OK
+	 */
+	public function reopen($user, $notrigger = 0)
+	{
+		// Protection
+		if ($this->status != self::STATUS_CANCELED)
+		{
+			return 0;
+		}
+
+		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->eventorganization->write))
+		 || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->eventorganization->eventorganization_advance->validate))))
+		 {
+		 $this->error='Permission denied';
+		 return -1;
+		 }*/
+
+		return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'CONFERENCEORBOOTH_REOPEN');
+	}
+
+	/**
+	 *  Return a link to the object card (with optionaly the picto)
+	 *
+	 *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+	 *  @param  string  $option                     On what the link point to ('nolink', ...)
+	 *  @param  int     $notooltip                  1=Disable tooltip
+	 *  @param  string  $morecss                    Add more css on link
+	 *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+	 *  @return	string                              String with URL
+	 */
+	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+	{
+		global $conf, $langs, $hookmanager;
+
+		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
+
+		$result = '';
+
+		$label = img_picto('', $this->picto).' <u>'.$langs->trans("ConferenceOrBooth").'</u>';
+		if (isset($this->status)) {
+			$label .= ' '.$this->getLibStatut(5);
+		}
+		$label .= '<br>';
+		$label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
+
+		$url = dol_buildpath('/eventorganization/conferenceorbooth_card.php', 1).'?id='.$this->id;
+
+		if ($option != 'nolink')
+		{
+			// Add param to save lastsearch_values or not
+			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
+			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+		}
+
+		$linkclose = '';
+		if (empty($notooltip))
+		{
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+			{
+				$label = $langs->trans("ShowConferenceOrBooth");
+				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+			}
+			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+		} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+
+		$linkstart = '<a href="'.$url.'"';
+		$linkstart .= $linkclose.'>';
+		$linkend = '</a>';
+
+		$result .= $linkstart;
+
+		if (empty($this->showphoto_on_popup)) {
+			if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+		} else {
+			if ($withpicto) {
+				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+				list($class, $module) = explode('@', $this->picto);
+				$upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
+				$filearray = dol_dir_list($upload_dir, "files");
+				$filename = $filearray[0]['name'];
+				if (!empty($filename)) {
+					$pospoint = strpos($filearray[0]['name'], '.');
+
+					$pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
+					if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
+						$result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$module.'" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div></div>';
+					} else {
+						$result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div>';
+					}
+
+					$result .= '</div>';
+				} else {
+					$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+				}
+			}
+		}
+
+		if ($withpicto != 2) $result .= $this->ref;
+
+		$result .= $linkend;
+		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+		global $action, $hookmanager;
+		$hookmanager->initHooks(array('conferenceorboothdao'));
+		$parameters = array('id'=>$this->id, 'getnomurl'=>$result);
+		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+		if ($reshook > 0) $result = $hookmanager->resPrint;
+		else $result .= $hookmanager->resPrint;
+
+		return $result;
+	}
+
+	/**
+	 *  Return the label of the status
+	 *
+	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+	 *  @return	string 			       Label of status
+	 */
+	public function getLibStatut($mode = 0)
+	{
+		return $this->LibStatut($this->status, $mode);
+	}
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 *  Return the status
+	 *
+	 *  @param	int		$status        Id status
+	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+	 *  @return string 			       Label of status
+	 */
+	public function LibStatut($status, $mode = 0)
+	{
+		// phpcs:enable
+		if (empty($this->labelStatus) || empty($this->labelStatusShort))
+		{
+			global $langs;
+			//$langs->load("eventorganization@eventorganization");
+			$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
+			$this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+			$this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Disabled');
+			$this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
+			$this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled');
+			$this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Disabled');
+		}
+
+		$statusType = 'status'.$status;
+		//if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
+		if ($status == self::STATUS_CANCELED) $statusType = 'status6';
+
+		return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+	}
+
+	/**
+	 *	Load the info information in the object
+	 *
+	 *	@param  int		$id       Id of object
+	 *	@return	void
+	 */
+	public function info($id)
+	{
+		$sql = 'SELECT rowid, date_creation as datec, tms as datem,';
+		$sql .= ' fk_user_creat, fk_user_modif';
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+		$sql .= ' WHERE t.rowid = '.$id;
+		$result = $this->db->query($sql);
+		if ($result)
+		{
+			if ($this->db->num_rows($result))
+			{
+				$obj = $this->db->fetch_object($result);
+				$this->id = $obj->rowid;
+				if ($obj->fk_user_author)
+				{
+					$cuser = new User($this->db);
+					$cuser->fetch($obj->fk_user_author);
+					$this->user_creation = $cuser;
+				}
+
+				if ($obj->fk_user_valid)
+				{
+					$vuser = new User($this->db);
+					$vuser->fetch($obj->fk_user_valid);
+					$this->user_validation = $vuser;
+				}
+
+				if ($obj->fk_user_cloture)
+				{
+					$cluser = new User($this->db);
+					$cluser->fetch($obj->fk_user_cloture);
+					$this->user_cloture = $cluser;
+				}
+
+				$this->date_creation     = $this->db->jdate($obj->datec);
+				$this->date_modification = $this->db->jdate($obj->datem);
+				$this->date_validation   = $this->db->jdate($obj->datev);
+			}
+
+			$this->db->free($result);
+		} else {
+			dol_print_error($this->db);
+		}
+	}
+
+	/**
+	 * Initialise object with example values
+	 * Id must be 0 if object instance is a specimen
+	 *
+	 * @return void
+	 */
+	public function initAsSpecimen()
+	{
+		$this->initAsSpecimenCommon();
+	}
+
+	/**
+	 * 	Create an array of lines
+	 *
+	 * 	@return array|int		array of lines if OK, <0 if KO
+	 */
+	public function getLinesArray()
+	{
+		$this->lines = array();
+
+		$objectline = new ConferenceOrBoothLine($this->db);
+		$result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_conferenceorbooth = '.$this->id));
+
+		if (is_numeric($result))
+		{
+			$this->error = $this->error;
+			$this->errors = $this->errors;
+			return $result;
+		} else {
+			$this->lines = $result;
+			return $this->lines;
+		}
+	}
+
+	/**
+	 *  Returns the reference to the following non used object depending on the active numbering module.
+	 *
+	 *  @return string      		Object free reference
+	 */
+	public function getNextNumRef()
+	{
+		global $langs, $conf;
+		$langs->load("eventorganization@eventorganization");
+
+		if (empty($conf->global->EVENTORGANIZATION_CONFERENCEORBOOTH_ADDON)) {
+			$conf->global->EVENTORGANIZATION_CONFERENCEORBOOTH_ADDON = 'mod_conferenceorbooth_standard';
+		}
+
+		if (!empty($conf->global->EVENTORGANIZATION_CONFERENCEORBOOTH_ADDON))
+		{
+			$mybool = false;
+
+			$file = $conf->global->EVENTORGANIZATION_CONFERENCEORBOOTH_ADDON.".php";
+			$classname = $conf->global->EVENTORGANIZATION_CONFERENCEORBOOTH_ADDON;
+
+			// Include file with class
+			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+			foreach ($dirmodels as $reldir)
+			{
+				$dir = dol_buildpath($reldir."core/modules/eventorganization/");
+
+				// Load file with numbering class (if found)
+				$mybool |= @include_once $dir.$file;
+			}
+
+			if ($mybool === false)
+			{
+				dol_print_error('', "Failed to include file ".$file);
+				return '';
+			}
+
+			if (class_exists($classname)) {
+				$obj = new $classname();
+				$numref = $obj->getNextValue($this);
+
+				if ($numref != '' && $numref != '-1')
+				{
+					return $numref;
+				} else {
+					$this->error = $obj->error;
+					//dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+					return "";
+				}
+			} else {
+				print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
+				return "";
+			}
+		} else {
+			print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
+			return "";
+		}
+	}
+
+	/**
+	 *  Create a document onto disk according to template module.
+	 *
+	 *  @param	    string		$modele			Force template to use ('' to not force)
+	 *  @param		Translate	$outputlangs	objet lang a utiliser pour traduction
+	 *  @param      int			$hidedetails    Hide details of lines
+	 *  @param      int			$hidedesc       Hide description
+	 *  @param      int			$hideref        Hide ref
+	 *  @param      null|array  $moreparams     Array to provide more information
+	 *  @return     int         				0 if KO, 1 if OK
+	 */
+	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
+	{
+		global $conf, $langs;
+
+		$result = 0;
+		$includedocgeneration = 0;
+
+		$langs->load("eventorganization@eventorganization");
+
+		if (!dol_strlen($modele)) {
+			$modele = 'standard_conferenceorbooth';
+
+			if (!empty($this->model_pdf)) {
+				$modele = $this->model_pdf;
+			} elseif (!empty($conf->global->CONFERENCEORBOOTH_ADDON_PDF)) {
+				$modele = $conf->global->CONFERENCEORBOOTH_ADDON_PDF;
+			}
+		}
+
+		$modelpath = "core/modules/eventorganization/doc/";
+
+		if ($includedocgeneration && !empty($modele)) {
+			$result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Action executed by scheduler
+	 * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
+	 * Use public function doScheduledJob($param1, $param2, ...) to get parameters
+	 *
+	 * @return	int			0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+	 */
+	public function doScheduledJob()
+	{
+		global $conf, $langs;
+
+		//$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
+
+		$error = 0;
+		$this->output = '';
+		$this->error = '';
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$now = dol_now();
+
+		$this->db->begin();
+
+		// ...
+
+		$this->db->commit();
+
+		return $error;
+	}
+}
+
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
+
+/**
+ * Class ConferenceOrBoothLine. You can also remove this and generate a CRUD class for lines objects.
+ */
+class ConferenceOrBoothLine extends CommonObjectLine
+{
+	// To complete with content of an object ConferenceOrBoothLine
+	// We should have a field rowid, fk_conferenceorbooth and position
+
+	/**
+	 * @var int  Does object support extrafields ? 0=No, 1=Yes
+	 */
+	public $isextrafieldmanaged = 0;
+
+	/**
+	 * Constructor
+	 *
+	 * @param DoliDb $db Database handler
+	 */
+	public function __construct(DoliDB $db)
+	{
+		$this->db = $db;
+	}
+}

+ 287 - 0
htdocs/eventorganization/conferenceorbooth_agenda.php

@@ -0,0 +1,287 @@
+<?php
+/* Copyright (C) 2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) ---Put here your own copyright and developer email---
+ *
+ * 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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *  \file       conferenceorbooth_agenda.php
+ *  \ingroup    eventorganization
+ *  \brief      Tab of events on ConferenceOrBooth
+ */
+
+//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
+//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
+//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
+//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');				// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
+//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
+//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
+//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', 1);		// The main.inc.php does not make a redirect if not logged, instead show simple error message
+//if (! defined("FORCECSP"))                 define('FORCECSP', 'none');				// Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
+if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
+if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
+if (!$res) die("Include of main fails");
+
+require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+dol_include_once('/eventorganization/class/conferenceorbooth.class.php');
+dol_include_once('/eventorganization/lib/eventorganization_conferenceorbooth.lib.php');
+
+
+// Load translation files required by the page
+$langs->loadLangs(array("eventorganization@eventorganization", "other"));
+
+// Get parameters
+$id = GETPOST('id', 'int');
+$ref = GETPOST('ref', 'alpha');
+$action = GETPOST('action', 'aZ09');
+$cancel = GETPOST('cancel', 'aZ09');
+$backtopage = GETPOST('backtopage', 'alpha');
+
+if (GETPOST('actioncode', 'array')) {
+	$actioncode = GETPOST('actioncode', 'array', 3);
+	if (!count($actioncode)) {
+		$actioncode = '0';
+	}
+} else {
+	$actioncode = GETPOST("actioncode", "alpha", 3) ? GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
+}
+$search_agenda_label = GETPOST('search_agenda_label');
+
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
+$sortfield = GETPOST("sortfield", 'alpha');
+$sortorder = GETPOST("sortorder", 'alpha');
+$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
+$offset = $limit * $page;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+if (!$sortfield) {
+	$sortfield = 'a.datep,a.id';
+}
+if (!$sortorder) {
+	$sortorder = 'DESC,DESC';
+}
+
+// Initialize technical objects
+$object = new ConferenceOrBooth($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('conferenceorboothagenda', 'globalcard')); // Note that conf->hooks_modules contains array
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->eventorganization->multidir_output[$object->entity]."/".$object->id;
+}
+
+// Security check - Protection if external user
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$result = restrictedArea($user, 'eventorganization', $object->id);
+
+$permissiontoadd = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_addupdatedelete.inc.php
+
+
+/*
+ *  Actions
+ */
+
+$parameters = array('id'=>$id);
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
+
+if (empty($reshook)) {
+	// Cancel
+	if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
+		header("Location: ".$backtopage);
+		exit;
+	}
+
+	// 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
+		$actioncode = '';
+		$search_agenda_label = '';
+	}
+}
+
+
+
+/*
+ *	View
+ */
+
+$form = new Form($db);
+
+if ($object->id > 0) {
+	$title = $langs->trans("Agenda");
+	//if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title;
+	$help_url = '';
+	llxHeader('', $title, $help_url);
+
+	if (!empty($conf->notification->enabled)) {
+		$langs->load("mails");
+	}
+	$head = conferenceorboothPrepareHead($object);
+
+
+	print dol_get_fiche_head($head, 'agenda', $langs->trans("ConferenceOrBooth"), -1, $object->picto);
+
+	// Object card
+	// ------------------------------------------------------------
+	$linkback = '<a href="'.dol_buildpath('/eventorganization/conferenceorbooth_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	/*
+	// Ref customer
+	$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
+	$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
+	// Thirdparty
+	$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
+	// Project
+	if (! empty($conf->projet->enabled)) {
+		$langs->load("projects");
+		$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+		if ($permissiontoadd) {
+			if ($action != 'classify') {
+				//$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+			}
+			$morehtmlref.=' : ';
+			if ($action == 'classify') {
+				//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+				$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+				$morehtmlref.='<input type="hidden" name="action" value="classin">';
+				$morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
+				$morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+				$morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+				$morehtmlref.='</form>';
+			} else {
+				$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+			}
+		} else {
+			if (! empty($object->fk_project)) {
+				$proj = new Project($db);
+				$proj->fetch($object->fk_project);
+				$morehtmlref .= ': '.$proj->getNomUrl();
+			} else {
+				$morehtmlref .= '';
+			}
+		}
+	}*/
+	$morehtmlref .= '</div>';
+
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+	print '<div class="fichecenter">';
+	print '<div class="underbanner clearboth"></div>';
+
+	$object->info($object->id);
+	dol_print_object_info($object, 1);
+
+	print '</div>';
+
+	print dol_get_fiche_end();
+
+
+
+	// Actions buttons
+
+	$objthirdparty = $object;
+	$objcon = new stdClass();
+
+	$out = '&origin='.urlencode($object->element.'@'.$object->module).'&originid='.urlencode($object->id);
+	$urlbacktopage = $_SERVER['PHP_SELF'].'?id='.$object->id;
+	$out .= '&backtopage='.urlencode($urlbacktopage);
+	$permok = $user->rights->agenda->myactions->create;
+	if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) {
+		//$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create';
+		if (get_class($objthirdparty) == 'Societe') {
+			$out .= '&socid='.urlencode($objthirdparty->id);
+		}
+		$out .= (!empty($objcon->id) ? '&contactid='.urlencode($objcon->id) : '').'&percentage=-1';
+		//$out.=$langs->trans("AddAnAction").' ';
+		//$out.=img_picto($langs->trans("AddAnAction"),'filenew');
+		//$out.="</a>";
+	}
+
+
+	print '<div class="tabsAction">';
+
+	if (!empty($conf->agenda->enabled)) {
+		if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) {
+			print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>';
+		} else {
+			print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>';
+		}
+	}
+
+	print '</div>';
+
+	if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
+		$param = '&id='.$object->id.'&socid='.$socid;
+		if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+			$param .= '&contextpage='.urlencode($contextpage);
+		}
+		if ($limit > 0 && $limit != $conf->liste_limit) {
+			$param .= '&limit='.urlencode($limit);
+		}
+
+
+		//print load_fiche_titre($langs->trans("ActionsOnConferenceOrBooth"), '', '');
+
+		// List of all actions
+		$filters = array();
+		$filters['search_agenda_label'] = $search_agenda_label;
+
+		// TODO Replace this with same code than into list.php
+		show_actions_done($conf, $langs, $db, $object, null, 0, $actioncode, '', $filters, $sortfield, $sortorder, $object->module);
+	}
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 550 - 0
htdocs/eventorganization/conferenceorbooth_card.php

@@ -0,0 +1,550 @@
+<?php
+/* Copyright (C) 2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2021		Florian Henry			<florian.henry@scopen.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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *   	\file       event.php
+ *		\ingroup    eventorganization
+ *		\brief      Page to create/edit/view conferenceorbooth
+ */
+
+require '../main.inc.php';
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.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.'/eventorganization/class/conferenceorbooth.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
+
+// Load translation files required by the page
+$langs->loadLangs(array("eventorganization", "projects"));
+
+// Get parameters
+$id = GETPOST('id', 'int');
+$ref = GETPOST('ref', 'alpha');
+$action = GETPOST('action', 'aZ09');
+$confirm = GETPOST('confirm', 'alpha');
+$cancel = GETPOST('cancel', 'aZ09');
+$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'conferenceorboothcard'; // To manage different context of search
+$backtopage = GETPOST('backtopage', 'alpha');
+$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha');
+//$lineid   = GETPOST('lineid', 'int');
+
+// Initialize technical objects
+$object = new ConferenceOrBooth($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('conferenceorboothcard', 'globalcard')); // Note that conf->hooks_modules contains array
+
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+
+// Initialize array of search criterias
+$search_all = GETPOST("search_all", 'alpha');
+$search = array();
+foreach ($object->fields as $key => $val) {
+	if (GETPOST('search_'.$key, 'alpha')) {
+		$search[$key] = GETPOST('search_'.$key, 'alpha');
+	}
+}
+
+if (empty($action) && empty($id) && empty($ref)) {
+	$action = 'view';
+}
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
+
+
+/*$permissiontoread = $user->rights->eventorganization->conferenceorbooth->read;
+$permissiontoadd = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
+$permissiontodelete = $user->rights->eventorganization->conferenceorbooth->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT);
+$permissionnote = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_setnotes.inc.php
+$permissiondellink = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_dellink.inc.php*/
+$permissiontoread = $user->rights->eventorganization->read;
+$permissiontoadd = $user->rights->eventorganization->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
+$permissiontodelete = $user->rights->eventorganization->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT);
+$permissionnote = $user->rights->eventorganization->write; // Used by the include of actions_setnotes.inc.php
+$permissiondellink = $user->rights->eventorganization->write; // Used by the include of actions_dellink.inc.php
+$upload_dir = $conf->eventorganization->multidir_output[isset($object->entity) ? $object->entity : 1];
+
+// Security check - Protection if external user
+if ($user->socid > 0) accessforbidden();
+if ($user->socid > 0) $socid = $user->socid;
+$isdraft = (($object->statut == $object::STATUS_DRAFT) ? 1 : 0);
+$result = restrictedArea($user, 'eventorganization', $object->id, '', '', 'fk_soc', 'rowid', $isdraft);
+
+if (!$permissiontoread) accessforbidden();
+
+
+/*
+ * Actions
+ */
+
+$parameters = array();
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
+
+if (empty($reshook)) {
+	$error = 0;
+
+	$backurlforlist = dol_buildpath('/eventorganization/conferenceorbooth_list.php', 1);
+
+	if (empty($backtopage) || ($cancel && empty($id))) {
+		if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
+			if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
+				$backtopage = $backurlforlist;
+			} else {
+				$backtopage = dol_buildpath('/eventorganization/conferenceorbooth_card.php', 1).'?id='.($id > 0 ? $id : '__ID__');
+			}
+		}
+	}
+
+	$triggermodname = 'EVENTORGANIZATION_CONFERENCEORBOOTH_MODIFY'; // Name of trigger action code to execute when we modify record
+
+	// Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen
+	include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
+
+	// Actions when linking object each other
+	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
+
+	// Actions when printing a doc from card
+	include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
+
+	// Action to move up and down lines of object
+	//include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php';
+
+	// Action to build doc
+	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
+
+	if ($action == 'set_thirdparty' && $permissiontoadd) {
+		$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, $triggermodname);
+	}
+	if ($action == 'classin' && $permissiontoadd) {
+		$object->setProject(GETPOST('projectid', 'int'));
+	}
+
+	// Actions to send emails
+	$triggersendname = 'EVENTORGANIZATION_CONFERENCEORBOOTH_SENTBYMAIL';
+	$autocopy = 'MAIN_MAIL_AUTOCOPY_CONFERENCEORBOOTH_TO';
+	$trackid = 'conferenceorbooth'.$object->id;
+	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
+}
+
+
+
+
+/*
+ * View
+ *
+ * Put here all code to build page
+ */
+
+$form = new Form($db);
+$formfile = new FormFile($db);
+$formproject = new FormProjets($db);
+
+$title = $langs->trans("ConferenceOrBooth");
+$help_url = '';
+llxHeader('', $title, $help_url);
+
+// Example : Adding jquery code
+/*print '<script type="text/javascript" language="javascript">
+jQuery(document).ready(function() {
+	function init_myfunc()
+	{
+		jQuery("#myid").removeAttr(\'disabled\');
+		jQuery("#myid").attr(\'disabled\',\'disabled\');
+	}
+	init_myfunc();
+	jQuery("#mybutton").click(function() {
+		init_myfunc();
+	});
+});
+</script>';*/
+
+
+// Part to create
+if ($action == 'create') {
+	print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("ConferenceOrBooth")), '', 'object_'.$object->picto);
+
+	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="action" value="add">';
+	if ($backtopage) {
+		print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
+	}
+	if ($backtopageforcancel) {
+		print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	}
+
+	print dol_get_fiche_head(array(), '');
+
+	// Set some default values
+	//if (! GETPOSTISSET('fieldname')) $_POST['fieldname'] = 'myvalue';
+
+	print '<table class="border centpercent tableforfieldcreate">'."\n";
+
+	// Common attributes
+	include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php';
+
+	// Other attributes
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
+
+	print '</table>'."\n";
+
+	print dol_get_fiche_end();
+
+	print '<div class="center">';
+	print '<input type="submit" class="button" name="add" value="'.dol_escape_htmltag($langs->trans("Create")).'">';
+	print '&nbsp; ';
+	print '<input type="'.($backtopage ? "submit" : "button").'" class="button button-cancel" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'"'.($backtopage ? '' : ' onclick="javascript:history.go(-1)"').'>'; // Cancel for create does not post form if we don't know the backtopage
+	print '</div>';
+
+	print '</form>';
+
+	//dol_set_focus('input[name="ref"]');
+}
+
+// Part to edit record
+if (($id || $ref) && $action == 'edit') {
+	print load_fiche_titre($langs->trans("ConferenceOrBooth"), '', 'object_'.$object->picto);
+
+	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="action" value="update">';
+	print '<input type="hidden" name="id" value="'.$object->id.'">';
+	if ($backtopage) {
+		print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
+	}
+	if ($backtopageforcancel) {
+		print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	}
+
+	print dol_get_fiche_head();
+
+	print '<table class="border centpercent tableforfieldedit">'."\n";
+
+	// Common attributes
+	include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php';
+
+	// Other attributes
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php';
+
+	print '</table>';
+
+	print dol_get_fiche_end();
+
+	print '<div class="center"><input type="submit" class="button button-save" name="save" value="'.$langs->trans("Save").'">';
+	print ' &nbsp; <input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
+	print '</div>';
+
+	print '</form>';
+}
+
+// Part to show record
+if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
+	$res = $object->fetch_optionals();
+
+	$head = conferenceorboothPrepareHead($object);
+	print dol_get_fiche_head($head, 'card', $langs->trans("ConferenceOrBooth"), -1, $object->picto);
+
+	$formconfirm = '';
+
+	// Confirmation to delete
+	if ($action == 'delete') {
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteConferenceOrBooth'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1);
+	}
+	// Confirmation to delete line
+	if ($action == 'deleteline') {
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1);
+	}
+	// Clone confirmation
+	if ($action == 'clone') {
+		// Create an array for form
+		$formquestion = array();
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
+	}
+
+	// Confirmation of action xxxx
+	if ($action == 'xxx') {
+		$formquestion = array();
+		/*
+		$forcecombo=0;
+		if ($conf->browser->name == 'ie') $forcecombo = 1;	// There is a bug in IE10 that make combo inside popup crazy
+		$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' => 'other',    'name' => 'idwarehouse',   'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
+		);
+		*/
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220);
+	}
+
+	// Call Hook formConfirm
+	$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
+	$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	if (empty($reshook)) {
+		$formconfirm .= $hookmanager->resPrint;
+	} elseif ($reshook > 0) {
+		$formconfirm = $hookmanager->resPrint;
+	}
+
+	// Print form confirm
+	print $formconfirm;
+
+
+	// Object card
+	// ------------------------------------------------------------
+	$linkback = '<a href="'.dol_buildpath('/eventorganization/conferenceorbooth_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	/*
+	 // Ref customer
+	 $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
+	 $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
+	 // Thirdparty
+	 $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
+	 // Project
+	 if (! empty($conf->projet->enabled)) {
+	 $langs->load("projects");
+	 $morehtmlref .= '<br>'.$langs->trans('Project') . ' ';
+	 if ($permissiontoadd) {
+	 //if ($action != 'classify') $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> ';
+	 $morehtmlref .= ' : ';
+	 if ($action == 'classify') {
+	 //$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+	 $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+	 $morehtmlref .= '<input type="hidden" name="action" value="classin">';
+	 $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
+	 $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+	 $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+	 $morehtmlref .= '</form>';
+	 } else {
+	 $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+	 }
+	 } else {
+	 if (! empty($object->fk_project)) {
+	 $proj = new Project($db);
+	 $proj->fetch($object->fk_project);
+	 $morehtmlref .= ': '.$proj->getNomUrl();
+	 } else {
+	 $morehtmlref .= '';
+	 }
+	 }
+	 }*/
+	$morehtmlref .= '</div>';
+
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+
+	print '<div class="fichecenter">';
+	print '<div class="fichehalfleft">';
+	print '<div class="underbanner clearboth"></div>';
+	print '<table class="border centpercent tableforfield">'."\n";
+
+	// Common attributes
+	//$keyforbreak='fieldkeytoswitchonsecondcolumn';	// We change column just before this field
+	//unset($object->fields['fk_project']);				// Hide field already shown in banner
+	//unset($object->fields['fk_soc']);					// Hide field already shown in banner
+	include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
+
+	// Other attributes. Fields from hook formObjectOptions and Extrafields.
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
+
+	print '</table>';
+	print '</div>';
+	print '</div>';
+
+	print '<div class="clearboth"></div>';
+
+	print dol_get_fiche_end();
+
+
+	/*
+	 * Lines
+	 */
+
+	if (!empty($object->table_element_line)) {
+		// Show object lines
+		$result = $object->getLinesArray();
+
+		print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#addline' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">
+		<input type="hidden" name="token" value="' . newToken().'">
+		<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
+		<input type="hidden" name="mode" value="">
+		<input type="hidden" name="id" value="' . $object->id.'">
+		';
+
+		if (!empty($conf->use_javascript_ajax) && $object->status == 0) {
+			include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
+		}
+
+		print '<div class="div-table-responsive-no-min">';
+		if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) {
+			print '<table id="tablelines" class="noborder noshadow" width="100%">';
+		}
+
+		if (!empty($object->lines)) {
+			$object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1);
+		}
+
+		// Form to add new line
+		if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') {
+			if ($action != 'editline') {
+				// Add products/services form
+				$object->formAddObjectLine(1, $mysoc, $soc);
+
+				$parameters = array();
+				$reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+			}
+		}
+
+		if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) {
+			print '</table>';
+		}
+		print '</div>';
+
+		print "</form>\n";
+	}
+
+
+	// Buttons for actions
+
+	if ($action != 'presend' && $action != 'editline') {
+		print '<div class="tabsAction">'."\n";
+		$parameters = array();
+		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+		if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+
+		if (empty($reshook)) {
+			// Send
+			if (empty($user->socid)) {
+				print dolGetButtonAction($langs->trans('SendMail'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle');
+			}
+
+			// Back to draft
+			if ($object->status == $object::STATUS_VALIDATED) {
+				print dolGetButtonAction($langs->trans('SetToDraft'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes', '', $permissiontoadd);
+			}
+
+			print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit', '', $permissiontoadd);
+
+			// Validate
+			if ($object->status == $object::STATUS_DRAFT) {
+				if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) {
+					print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes', '', $permissiontoadd);
+				} else {
+					$langs->load("errors");
+					//print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes', '', 0);
+					print '<a class="butActionRefused" href="" title="'.$langs->trans("ErrorAddAtLeastOneLineFirst").'">'.$langs->trans("Validate").'</a>';
+				}
+			}
+
+			// Clone
+			print dolGetButtonAction($langs->trans('ToClone'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->socid.'&action=clone&object=scrumsprint', '', $permissiontoadd);
+
+			/*
+			if ($permissiontoadd) {
+				if ($object->status == $object::STATUS_ENABLED) {
+					print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=disable">'.$langs->trans("Disable").'</a>'."\n";
+				} else {
+					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=enable">'.$langs->trans("Enable").'</a>'."\n";
+				}
+			}
+			if ($permissiontoadd) {
+				if ($object->status == $object::STATUS_VALIDATED) {
+					print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=close">'.$langs->trans("Cancel").'</a>'."\n";
+				} else {
+					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen">'.$langs->trans("Re-Open").'</a>'."\n";
+				}
+			}
+			*/
+
+			// Delete (need delete permission, or if draft, just need create/modify permission)
+			print dolGetButtonAction($langs->trans('Delete'), '', 'delete', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=delete', '', $permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd));
+		}
+		print '</div>'."\n";
+	}
+
+
+	// Select mail models is same action as presend
+	if (GETPOST('modelselected')) {
+		$action = 'presend';
+	}
+
+	if ($action != 'presend') {
+		print '<div class="fichecenter"><div class="fichehalfleft">';
+		print '<a name="builddoc"></a>'; // ancre
+
+		$includedocgeneration = 0;
+
+		// Documents
+		if ($includedocgeneration) {
+			$objref = dol_sanitizeFileName($object->ref);
+			$relativepath = $objref.'/'.$objref.'.pdf';
+			$filedir = $conf->eventorganization->dir_output.'/'.$object->element.'/'.$objref;
+			$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
+			$genallowed = $user->rights->eventorganization->conferenceorbooth->read; // If you can read, you can build the PDF to read content
+			$delallowed = $user->rights->eventorganization->conferenceorbooth->write; // If you can create/edit, you can remove a file on card
+			print $formfile->showdocuments('eventorganization:ConferenceOrBooth', $object->element.'/'.$objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang);
+		}
+
+		// Show links to link elements
+		$linktoelem = $form->showLinkToObjectBlock($object, null, array('conferenceorbooth'));
+		$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
+
+
+		print '</div><div class="fichehalfright"><div class="ficheaddleft">';
+
+		$MAXEVENT = 10;
+
+		$morehtmlright = '<a href="'.dol_buildpath('/eventorganization/conferenceorbooth_agenda.php', 1).'?id='.$object->id.'">';
+		$morehtmlright .= $langs->trans("SeeAll");
+		$morehtmlright .= '</a>';
+
+		// List of actions on element
+		include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
+		$formactions = new FormActions($db);
+		$somethingshown = $formactions->showactions($object, $object->element.'@'.$object->module, (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlright);
+
+		print '</div></div></div>';
+	}
+
+	//Select mail models is same action as presend
+	if (GETPOST('modelselected')) {
+		$action = 'presend';
+	}
+
+	// Presend form
+	$modelmail = 'conferenceorbooth';
+	$defaulttopic = 'InformationMessage';
+	$diroutput = $conf->eventorganization->dir_output;
+	$trackid = 'conferenceorbooth'.$object->id;
+
+	include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 197 - 0
htdocs/eventorganization/conferenceorbooth_contact.php

@@ -0,0 +1,197 @@
+<?php
+/* Copyright (C) 2007-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) ---Put here your own copyright and developer email---
+ *
+ * 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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *  \file       conferenceorbooth_contact.php
+ *  \ingroup    eventorganization
+ *  \brief      Tab for contacts linked to ConferenceOrBooth
+ */
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
+if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
+if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
+if (!$res) die("Include of main fails");
+
+require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
+dol_include_once('/eventorganization/class/conferenceorbooth.class.php');
+dol_include_once('/eventorganization/lib/eventorganization_conferenceorbooth.lib.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("eventorganization@eventorganization", "companies", "other", "mails"));
+
+$id     = (GETPOST('id') ?GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
+$ref    = GETPOST('ref', 'alpha');
+$lineid = GETPOST('lineid', 'int');
+$socid  = GETPOST('socid', 'int');
+$action = GETPOST('action', 'aZ09');
+
+// Initialize technical objects
+$object = new ConferenceOrBooth($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('conferenceorboothcontact', 'globalcard')); // Note that conf->hooks_modules contains array
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+
+// Security check - Protection if external user
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$result = restrictedArea($user, 'eventorganization', $object->id);
+
+$permission = $user->rights->eventorganization->conferenceorbooth->write;
+
+/*
+ * Add a new contact
+ */
+
+if ($action == 'addcontact' && $permission) {
+	$contactid = (GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int'));
+	$typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
+	$result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
+
+	if ($result >= 0) {
+		header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
+		exit;
+	} else {
+		if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
+			$langs->load("errors");
+			setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
+		} else {
+			setEventMessages($object->error, $object->errors, 'errors');
+		}
+	}
+} elseif ($action == 'swapstatut' && $permission) {
+	// Toggle the status of a contact
+	$result = $object->swapContactStatus(GETPOST('ligne'));
+} elseif ($action == 'deletecontact' && $permission) {
+	// Deletes a contact
+	$result = $object->delete_contact($lineid);
+
+	if ($result >= 0) {
+		header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
+		exit;
+	} else {
+		dol_print_error($db);
+	}
+}
+
+
+/*
+ * View
+ */
+
+$title = $langs->trans('ConferenceOrBooth')." - ".$langs->trans('ContactsAddresses');
+$help_url = '';
+//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
+llxHeader('', $title, $help_url);
+
+$form = new Form($db);
+$formcompany = new FormCompany($db);
+$contactstatic = new Contact($db);
+$userstatic = new User($db);
+
+
+/* *************************************************************************** */
+/*                                                                             */
+/* View and edit mode                                                         */
+/*                                                                             */
+/* *************************************************************************** */
+
+if ($object->id) {
+	/*
+	 * Show tabs
+	 */
+	$head = conferenceorboothPrepareHead($object);
+
+	print dol_get_fiche_head($head, 'contact', $langs->trans("ConferenceOrBooth"), -1, $object->picto);
+
+	$linkback = '<a href="'.dol_buildpath('/eventorganization/conferenceorbooth_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	/*
+	 // Ref customer
+	 $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
+	 $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
+	 // Thirdparty
+	 $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
+	 // Project
+	 if (! empty($conf->projet->enabled))
+	 {
+	 $langs->load("projects");
+	 $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+	 if ($permissiontoadd)
+	 {
+	 if ($action != 'classify')
+	 //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+	 $morehtmlref.=' : ';
+	 if ($action == 'classify') {
+	 //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+	 $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+	 $morehtmlref.='<input type="hidden" name="action" value="classin">';
+	 $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
+	 $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+	 $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+	 $morehtmlref.='</form>';
+	 } else {
+	 $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+	 }
+	 } else {
+	 if (! empty($object->fk_project)) {
+	 $proj = new Project($db);
+	 $proj->fetch($object->fk_project);
+	 $morehtmlref .= ': '.$proj->getNomUrl();
+	 } else {
+	 $morehtmlref .= '';
+	 }
+	 }
+	 }*/
+	$morehtmlref .= '</div>';
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1);
+
+	print dol_get_fiche_end();
+
+	print '<br>';
+
+	// Contacts lines (modules that overwrite templates must declare this into descriptor)
+	$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
+	foreach ($dirtpls as $reldir) {
+		$res = @include dol_buildpath($reldir.'/contacts.tpl.php');
+		if ($res) {
+			break;
+		}
+	}
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 234 - 0
htdocs/eventorganization/conferenceorbooth_document.php

@@ -0,0 +1,234 @@
+<?php
+/* Copyright (C) 2007-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) ---Put here your own copyright and developer email---
+ *
+ * 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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *  \file       conferenceorbooth_document.php
+ *  \ingroup    eventorganization
+ *  \brief      Tab for documents linked to ConferenceOrBooth
+ */
+
+//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
+//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
+//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
+//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');				// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
+//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
+//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
+//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', 1);		// The main.inc.php does not make a redirect if not logged, instead show simple error message
+//if (! defined("FORCECSP"))                 define('FORCECSP', 'none');				// Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
+if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
+if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
+if (!$res) die("Include of main fails");
+
+require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
+dol_include_once('/eventorganization/class/conferenceorbooth.class.php');
+dol_include_once('/eventorganization/lib/eventorganization_conferenceorbooth.lib.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("eventorganization@eventorganization", "companies", "other", "mails"));
+
+
+$action = GETPOST('action', 'aZ09');
+$confirm = GETPOST('confirm');
+$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int'));
+$ref = GETPOST('ref', 'alpha');
+
+// Get parameters
+$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
+$sortfield = GETPOST("sortfield", 'alpha');
+$sortorder = GETPOST("sortorder", 'alpha');
+$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
+$offset = $liste_limit * $page;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
+if (!$sortfield) {
+	$sortfield = "name";
+}
+//if (! $sortfield) $sortfield="position_name";
+
+// Initialize technical objects
+$object = new ConferenceOrBooth($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('conferenceorboothdocument', 'globalcard')); // Note that conf->hooks_modules contains array
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->eventorganization->multidir_output[$object->entity ? $object->entity : $conf->entity]."/conferenceorbooth/".get_exdir(0, 0, 0, 1, $object);
+}
+
+// Security check - Protection if external user
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$result = restrictedArea($user, 'eventorganization', $object->id);
+
+$permissiontoadd = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_addupdatedelete.inc.php
+
+
+
+/*
+ * Actions
+ */
+
+include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
+
+
+/*
+ * View
+ */
+
+$form = new Form($db);
+
+$title = $langs->trans("ConferenceOrBooth").' - '.$langs->trans("Files");
+$help_url = '';
+//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
+llxHeader('', $title, $help_url);
+
+if ($object->id) {
+	/*
+	 * Show tabs
+	 */
+	$head = conferenceorboothPrepareHead($object);
+
+	print dol_get_fiche_head($head, 'document', $langs->trans("ConferenceOrBooth"), -1, $object->picto);
+
+
+	// Build file list
+	$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
+	$totalsize = 0;
+	foreach ($filearray as $key => $file) {
+		$totalsize += $file['size'];
+	}
+
+	// Object card
+	// ------------------------------------------------------------
+	$linkback = '<a href="'.dol_buildpath('/eventorganization/conferenceorbooth_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	/*
+	 // Ref customer
+	 $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
+	 $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
+	 // Thirdparty
+	 $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
+	 // Project
+	 if (! empty($conf->projet->enabled))
+	 {
+	 $langs->load("projects");
+	 $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+	 if ($permissiontoadd)
+	 {
+	 if ($action != 'classify')
+	 //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+	 $morehtmlref.=' : ';
+	 if ($action == 'classify') {
+	 //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+	 $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+	 $morehtmlref.='<input type="hidden" name="action" value="classin">';
+	 $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
+	 $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+	 $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+	 $morehtmlref.='</form>';
+	 } else {
+	 $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+	 }
+	 } else {
+	 if (! empty($object->fk_project)) {
+	 $proj = new Project($db);
+	 $proj->fetch($object->fk_project);
+	 $morehtmlref .= ': '.$proj->getNomUrl();
+	 } else {
+	 $morehtmlref .= '';
+	 }
+	 }
+	 }*/
+	$morehtmlref .= '</div>';
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+	print '<div class="fichecenter">';
+
+	print '<div class="underbanner clearboth"></div>';
+	print '<table class="border centpercent tableforfield">';
+
+	// Number of files
+	print '<tr><td class="titlefield">'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>';
+
+	// Total size
+	print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.$totalsize.' '.$langs->trans("bytes").'</td></tr>';
+
+	print '</table>';
+
+	print '</div>';
+
+	print dol_get_fiche_end();
+
+	$modulepart = 'eventorganization';
+	//$permission = $user->rights->eventorganization->conferenceorbooth->write;
+	$permission = 1;
+	//$permtoedit = $user->rights->eventorganization->conferenceorbooth->write;
+	$permtoedit = 1;
+	$param = '&id='.$object->id;
+
+	//$relativepathwithnofile='conferenceorbooth/' . dol_sanitizeFileName($object->id).'/';
+	$relativepathwithnofile = 'conferenceorbooth/'.dol_sanitizeFileName($object->ref).'/';
+
+	include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
+} else {
+	accessforbidden('', 0, 1);
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 678 - 0
htdocs/eventorganization/conferenceorbooth_list.php

@@ -0,0 +1,678 @@
+<?php
+/* Copyright (C) 2007-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) ---Put here your own copyright and developer email---
+ *
+ * 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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *   	\file       conferenceorbooth_list.php
+ *		\ingroup    eventorganization
+ *		\brief      List page for conferenceorbooth
+ */
+
+//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
+//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
+//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
+//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');				// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
+//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
+//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
+//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', 1);		// The main.inc.php does not make a redirect if not logged, instead show simple error message
+//if (! defined("FORCECSP"))                 define('FORCECSP', 'none');				// Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
+if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
+if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
+if (!$res) die("Include of main fails");
+
+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';
+
+// load eventorganization libraries
+require_once __DIR__.'/class/conferenceorbooth.class.php';
+
+// for other modules
+//dol_include_once('/othermodule/class/otherobject.class.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("eventorganization@eventorganization", "other"));
+
+$action     = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
+$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
+$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
+$confirm    = GETPOST('confirm', 'alpha'); // Result of a confirmation
+$cancel     = GETPOST('cancel', 'alpha'); // We click on a Cancel button
+$toselect   = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
+$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'conferenceorboothlist'; // To manage different context of search
+$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
+$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
+
+$id = GETPOST('id', 'int');
+
+// Load variable for pagination
+$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
+$sortfield = GETPOST('sortfield', 'aZ09comma');
+$sortorder = GETPOST('sortorder', 'aZ09comma');
+$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
+if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1 or if we click on clear filters
+$offset = $limit * $page;
+$pageprev = $page - 1;
+$pagenext = $page + 1;
+
+// Initialize technical objects
+$object = new ConferenceOrBooth($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('conferenceorboothlist')); // Note that conf->hooks_modules contains array
+
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+//$extrafields->fetch_name_optionals_label($object->table_element_line);
+
+$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+
+// Default sort order (if not yet defined by previous GETPOST)
+if (!$sortfield) {
+	reset($object->fields);					// Reset is required to avoid key() to return null.
+	$sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
+}
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
+
+// Initialize array of search criterias
+$search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml');
+$search = array();
+foreach ($object->fields as $key => $val) {
+	if (GETPOST('search_'.$key, 'alpha') !== '') {
+		$search[$key] = GETPOST('search_'.$key, 'alpha');
+	}
+	if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
+		$search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_'.$key.'_dtstartmonth', 'int'), GETPOST('search_'.$key.'_dtstartday', 'int'), GETPOST('search_'.$key.'_dtstartyear', 'int'));
+		$search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_'.$key.'_dtendmonth', 'int'), GETPOST('search_'.$key.'_dtendday', 'int'), GETPOST('search_'.$key.'_dtendyear', 'int'));
+	}
+}
+
+// List of fields to search into when doing a "search in all"
+$fieldstosearchall = array();
+foreach ($object->fields as $key => $val) {
+	if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label'];
+}
+
+// Definition of array of fields for columns
+$arrayfields = array();
+foreach ($object->fields as $key => $val) {
+	// If $val['visible']==0, then we never show the field
+	if (!empty($val['visible'])) {
+		$visible = (int) dol_eval($val['visible'], 1);
+		$arrayfields['t.'.$key] = array(
+			'label'=>$val['label'],
+			'checked'=>(($visible < 0) ? 0 : 1),
+			'enabled'=>($visible != 3 && dol_eval($val['enabled'], 1)),
+			'position'=>$val['position'],
+			'help'=>$val['help']
+		);
+	}
+}
+// 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');
+
+$permissiontoread = $user->rights->eventorganization->conferenceorbooth->read;
+$permissiontoadd = $user->rights->eventorganization->conferenceorbooth->write;
+$permissiontodelete = $user->rights->eventorganization->conferenceorbooth->delete;
+
+// Security check
+if (empty($conf->eventorganization->enabled)) accessforbidden('Module not enabled');
+$socid = 0;
+if ($user->socid > 0) { // Protection if external user
+	//$socid = $user->socid;
+	accessforbidden();
+}
+//$result = restrictedArea($user, 'eventorganization', $id, '');
+//if (!$permissiontoread) accessforbidden();
+
+
+
+/*
+ * Actions
+ */
+
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list';
+	$massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
+
+$parameters = array();
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
+
+if (empty($reshook)) {
+	// Selection of new fields
+	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+
+	// Purge search criteria
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
+		foreach ($object->fields as $key => $val) {
+			$search[$key] = '';
+			if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
+				$search[$key.'_dtstart'] = '';
+				$search[$key.'_dtend'] = '';
+			}
+		}
+		$toselect = '';
+		$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')) {
+		$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
+	}
+
+	// Mass actions
+	$objectclass = 'ConferenceOrBooth';
+	$objectlabel = 'ConferenceOrBooth';
+	$uploaddir = $conf->eventorganization->dir_output;
+	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
+}
+
+
+
+/*
+ * View
+ */
+
+$form = new Form($db);
+
+$now = dol_now();
+
+//$help_url="EN:Module_ConferenceOrBooth|FR:Module_ConferenceOrBooth_FR|ES:Módulo_ConferenceOrBooth";
+$help_url = '';
+$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("ConferenceOrBooths"));
+
+
+// Build and execute select
+// --------------------------------------------------------------------
+$sql = 'SELECT ';
+foreach ($object->fields as $key => $val) {
+	$sql .= 't.'.$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); // Note that $action and $object may have been modified by hook
+$sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
+$sql = preg_replace('/,\s*$/', '', $sql);
+$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
+if (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 (t.rowid = ef.fk_object)";
+}
+// 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;
+if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
+else $sql .= " WHERE 1 = 1";
+foreach ($search as $key => $val) {
+	if (in_array($key, $object->fields)) {
+		if ($key == 'status' && $search[$key] == -1) continue;
+		$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
+		if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
+			if ($search[$key] == '-1') $search[$key] = '';
+			$mode_search = 2;
+		}
+		if ($search[$key] != '') {
+			$sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
+		}
+	} else {
+		if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') {
+			$columnName=preg_replace('/(_dtstart|_dtend)$/', '', $key);
+			if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) {
+				if (preg_match('/_dtstart$/', $key)) {
+					$sql .= " AND t." . $columnName . " >= '" . $db->idate($search[$key]) . "'";
+				}
+				if (preg_match('/_dtend$/', $key)) {
+					$sql .= " AND t." . $columnName . " <= '" . $db->idate($search[$key]) . "'";
+				}
+			}
+		}
+	}
+}
+if ($search_all) {
+	$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
+}
+//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
+// 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); // Note that $action and $object may have been modified by hook
+$sql .= $hookmanager->resPrint;
+
+/* If a group by is required
+$sql.= " GROUP BY ";
+foreach($object->fields as $key => $val) {
+	$sql.='t.'.$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.', ' : '');
+}
+// Add where from hooks
+$parameters=array();
+$reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters, $object);    // Note that $action and $object may have been modified by hook
+$sql.=$hookmanager->resPrint;
+$sql=preg_replace('/,\s*$/','', $sql);
+*/
+
+$sql .= $db->order($sortfield, $sortorder);
+
+// Count total nb of records
+$nbtotalofrecords = '';
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
+	$resql = $db->query($sql);
+	$nbtotalofrecords = $db->num_rows($resql);
+	if (($page * $limit) > $nbtotalofrecords) {	// if total of record found is smaller than page * limit, goto and load page 0
+		$page = 0;
+		$offset = 0;
+	}
+}
+// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
+if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) {
+	$num = $nbtotalofrecords;
+} else {
+	if ($limit) $sql .= $db->plimit($limit + 1, $offset);
+
+	$resql = $db->query($sql);
+	if (!$resql) {
+		dol_print_error($db);
+		exit;
+	}
+
+	$num = $db->num_rows($resql);
+}
+
+// Direct jump if only one record found
+if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
+	$obj = $db->fetch_object($resql);
+	$id = $obj->rowid;
+	header("Location: ".dol_buildpath('/eventorganization/conferenceorbooth_card.php', 1).'?id='.$id);
+	exit;
+}
+
+
+// Output page
+// --------------------------------------------------------------------
+
+llxHeader('', $title, $help_url);
+
+// Example : Adding jquery code
+print '<script type="text/javascript" language="javascript">
+jQuery(document).ready(function() {
+	function init_myfunc()
+	{
+		jQuery("#myid").removeAttr(\'disabled\');
+		jQuery("#myid").attr(\'disabled\',\'disabled\');
+	}
+	init_myfunc();
+	jQuery("#mybutton").click(function() {
+		init_myfunc();
+	});
+});
+</script>';
+
+$arrayofselected = is_array($toselect) ? $toselect : array();
+
+$param = '';
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+	$param .= '&contextpage='.urlencode($contextpage);
+}
+if ($limit > 0 && $limit != $conf->liste_limit) {
+	$param .= '&limit='.urlencode($limit);
+}
+foreach ($search as $key => $val) {
+	if (is_array($search[$key]) && count($search[$key])) {
+		foreach ($search[$key] as $skey) {
+			$param .= '&search_'.$key.'[]='.urlencode($skey);
+		}
+	} else {
+		$param .= '&search_'.$key.'='.urlencode($search[$key]);
+	}
+}
+if ($optioncss != '') {
+	$param .= '&optioncss='.urlencode($optioncss);
+}
+// Add $param from extra fields
+include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
+// Add $param from hooks
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object); // Note that $action and $object may have been modified by hook
+$param .= $hookmanager->resPrint;
+
+// List of mass actions available
+$arrayofmassactions = array(
+	//'validate'=>$langs->trans("Validate"),
+	//'generate_doc'=>$langs->trans("ReGeneratePDF"),
+	//'builddoc'=>$langs->trans("PDFMerge"),
+	//'presend'=>$langs->trans("SendByMail"),
+);
+if ($permissiontodelete) {
+	$arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
+}
+if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
+	$arrayofmassactions = array();
+}
+$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
+
+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="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.'">';
+
+$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/eventorganization/conferenceorbooth_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd);
+
+print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1);
+
+// Add code for pre mass action (confirmation or email presend form)
+$topicmail = "SendConferenceOrBoothRef";
+$modelmail = "conferenceorbooth";
+$objecttmp = new ConferenceOrBooth($db);
+$trackid = 'xxxx'.$object->id;
+include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
+
+if ($search_all) {
+	foreach ($fieldstosearchall as $key => $val) {
+		$fieldstosearchall[$key] = $langs->trans($val);
+	}
+	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>';
+}
+
+$moreforfilter = '';
+/*$moreforfilter.='<div class="divsearchfield">';
+$moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
+$moreforfilter.= '</div>';*/
+
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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); // This also change content of $arrayfields
+$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
+
+print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
+print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
+
+
+// Fields title search
+// --------------------------------------------------------------------
+print '<tr class="liste_titre">';
+foreach ($object->fields as $key => $val) {
+	$cssforfield = (empty($val['css']) ? '' : $val['css']);
+	if ($key == 'status') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+	} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'right';
+	}
+	if (!empty($arrayfields['t.'.$key]['checked'])) {
+		print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
+		if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+			print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
+		} elseif (strpos($val['type'], 'integer:') === 0) {
+			print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth125', 1);
+		} elseif (!preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
+			print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
+		} elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
+			print '<div class="nowrap">';
+			print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
+			print '</div>';
+			print '<div class="nowrap">';
+			print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
+			print '</div>';
+		}
+		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); // Note that $action and $object may have been modified by hook
+print $hookmanager->resPrint;
+// Action column
+print '<td class="liste_titre maxwidthsearch">';
+$searchpicto = $form->showFilterButtons();
+print $searchpicto;
+print '</td>';
+print '</tr>'."\n";
+
+
+// Fields title label
+// --------------------------------------------------------------------
+print '<tr class="liste_titre">';
+foreach ($object->fields as $key => $val) {
+	$cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
+	if ($key == 'status') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+	} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'right';
+	}
+	if (!empty($arrayfields['t.'.$key]['checked'])) {
+		print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
+	}
+}
+// 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);
+$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
+print $hookmanager->resPrint;
+// Action column
+print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
+print '</tr>'."\n";
+
+
+// Detect if we need a fetch on each output line
+$needToFetchEachLine = 0;
+if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
+	foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
+		if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object
+	}
+}
+
+
+// Loop on record
+// --------------------------------------------------------------------
+$i = 0;
+$totalarray = array();
+while ($i < ($limit ? min($num, $limit) : $num)) {
+	$obj = $db->fetch_object($resql);
+	if (empty($obj)) {
+		break; // Should not happen
+	}
+
+	// Store properties in $object
+	$object->setVarsFromFetchObj($obj);
+
+	// Show here line of result
+	print '<tr class="oddeven">';
+	foreach ($object->fields as $key => $val) {
+		$cssforfield = (empty($val['css']) ? '' : $val['css']);
+		if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+			$cssforfield .= ($cssforfield ? ' ' : '').'center';
+		} elseif ($key == 'status') {
+			$cssforfield .= ($cssforfield ? ' ' : '').'center';
+		}
+
+		if (in_array($val['type'], array('timestamp'))) {
+			$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+		} elseif ($key == 'ref') {
+			$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+		}
+
+		if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) {
+			$cssforfield .= ($cssforfield ? ' ' : '').'right';
+		}
+		//if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100';
+
+		if (!empty($arrayfields['t.'.$key]['checked'])) {
+			print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
+			if ($key == 'status') {
+				print $object->getLibStatut(5);
+			} else {
+				print $object->showOutputField($val, $key, $object->$key, '');
+			}
+			print '</td>';
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
+			if (!empty($val['isameasure'])) {
+				if (!$i) {
+					$totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
+				}
+				$totalarray['val']['t.'.$key] += $object->$key;
+			}
+		}
+	}
+	// Extra fields
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
+	// Fields from hook
+	$parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
+	$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
+	print $hookmanager->resPrint;
+	// Action column
+	print '<td class="nowrap center">';
+	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;
+		print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
+	}
+	print '</td>';
+	if (!$i) $totalarray['nbfield']++;
+
+	print '</tr>'."\n";
+
+	$i++;
+}
+
+// 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++;
+		}
+	}
+	print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
+}
+
+
+$db->free($resql);
+
+$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
+$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook
+print $hookmanager->resPrint;
+
+print '</table>'."\n";
+print '</div>'."\n";
+
+print '</form>'."\n";
+
+if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
+	$hidegeneratedfilelistifempty = 1;
+	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
+		$hidegeneratedfilelistifempty = 0;
+	}
+
+	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 .= str_replace('&amp;', '&', $param);
+
+	$filedir = $diroutputmassaction;
+	$genallowed = $permissiontoread;
+	$delallowed = $permissiontoadd;
+
+	print $formfile->showdocuments('massfilesarea_eventorganization', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 184 - 0
htdocs/eventorganization/conferenceorbooth_note.php

@@ -0,0 +1,184 @@
+<?php
+/* Copyright (C) 2007-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) ---Put here your own copyright and developer email---
+ *
+ * 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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *  \file       conferenceorbooth_note.php
+ *  \ingroup    eventorganization
+ *  \brief      Tab for notes on ConferenceOrBooth
+ */
+
+//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
+//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
+//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
+//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
+//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
+//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
+//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');				// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
+//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
+//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
+//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
+//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
+//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
+//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
+//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
+//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
+//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
+//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', 1);		// The main.inc.php does not make a redirect if not logged, instead show simple error message
+//if (! defined("FORCECSP"))                 define('FORCECSP', 'none');				// Disable all Content Security Policies
+//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
+if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
+if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
+if (!$res) die("Include of main fails");
+
+dol_include_once('/eventorganization/class/conferenceorbooth.class.php');
+dol_include_once('/eventorganization/lib/eventorganization_conferenceorbooth.lib.php');
+
+// Load translation files required by the page
+$langs->loadLangs(array("eventorganization@eventorganization", "companies"));
+
+// Get parameters
+$id = GETPOST('id', 'int');
+$ref        = GETPOST('ref', 'alpha');
+$action = GETPOST('action', 'aZ09');
+$cancel     = GETPOST('cancel', 'aZ09');
+$backtopage = GETPOST('backtopage', 'alpha');
+
+// Initialize technical objects
+$object = new ConferenceOrBooth($db);
+$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->eventorganization->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('conferenceorboothnote', 'globalcard')); // Note that conf->hooks_modules contains array
+// Fetch optionals attributes and labels
+$extrafields->fetch_name_optionals_label($object->table_element);
+
+// Security check - Protection if external user
+//if ($user->socid > 0) accessforbidden();
+//if ($user->socid > 0) $socid = $user->socid;
+//$result = restrictedArea($user, 'eventorganization', $id);
+
+// Load object
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->eventorganization->multidir_output[$object->entity]."/".$object->id;
+}
+
+$permissionnote = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_setnotes.inc.php
+$permissiontoadd = $user->rights->eventorganization->conferenceorbooth->write; // Used by the include of actions_addupdatedelete.inc.php
+
+
+
+/*
+ * Actions
+ */
+
+include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
+
+
+/*
+ * View
+ */
+
+$form = new Form($db);
+
+//$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes';
+$help_url = '';
+llxHeader('', $langs->trans('ConferenceOrBooth'), $help_url);
+
+if ($id > 0 || !empty($ref)) {
+	$object->fetch_thirdparty();
+
+	$head = conferenceorboothPrepareHead($object);
+
+	print dol_get_fiche_head($head, 'note', $langs->trans("ConferenceOrBooth"), -1, $object->picto);
+
+	// Object card
+	// ------------------------------------------------------------
+	$linkback = '<a href="'.dol_buildpath('/eventorganization/conferenceorbooth_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	/*
+	 // Ref customer
+	 $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
+	 $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1);
+	 // Thirdparty
+	 $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '');
+	 // Project
+	 if (! empty($conf->projet->enabled))
+	 {
+	 $langs->load("projects");
+	 $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+	 if ($permissiontoadd)
+	 {
+	 if ($action != 'classify')
+	 //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+	 $morehtmlref.=' : ';
+	 if ($action == 'classify') {
+	 //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+	 $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+	 $morehtmlref.='<input type="hidden" name="action" value="classin">';
+	 $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
+	 $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+	 $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+	 $morehtmlref.='</form>';
+	 } else {
+	 $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+	 }
+	 } else {
+	 if (! empty($object->fk_project)) {
+	 $proj = new Project($db);
+	 $proj->fetch($object->fk_project);
+	 $morehtmlref .= ': '.$proj->getNomUrl();
+	 } else {
+	 $morehtmlref .= '';
+	 }
+	 }
+	 }*/
+	 $morehtmlref .= '</div>';
+
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+
+	print '<div class="fichecenter">';
+	print '<div class="underbanner clearboth"></div>';
+
+
+	$cssclass = "titlefield";
+	include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
+
+	print '</div>';
+
+	print dol_get_fiche_end();
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 225 - 0
htdocs/eventorganization/eventorganizationindex.php

@@ -0,0 +1,225 @@
+<?php
+/* Copyright (C) 2001-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
+ * Copyright (C) 2004-2015 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2005-2012 Regis Houssin        <regis.houssin@inodbox.com>
+ * Copyright (C) 2015      Jean-François Ferry	<jfefe@aternatik.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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       eventorganization/eventorganizationindex.php
+ *	\ingroup    eventorganization
+ *	\brief      Home page of eventorganization top menu
+ */
+
+// Load Dolibarr environment
+$res = 0;
+// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
+if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
+// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
+$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
+while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
+if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
+if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
+// Try main.inc.php using relative path
+if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
+if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
+if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
+if (!$res) die("Include of main fails");
+
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
+
+// Load translation files required by the page
+$langs->loadLangs(array("eventorganization@eventorganization"));
+
+$action = GETPOST('action', 'aZ09');
+
+
+// Security check
+// if (! $user->rights->eventorganization->myobject->read) {
+// 	accessforbidden();
+// }
+$socid = GETPOST('socid', 'int');
+if (isset($user->socid) && $user->socid > 0) {
+	$action = '';
+	$socid = $user->socid;
+}
+
+$max = 5;
+$now = dol_now();
+
+
+/*
+ * Actions
+ */
+
+// None
+
+
+/*
+ * View
+ */
+
+$form = new Form($db);
+$formfile = new FormFile($db);
+
+llxHeader("", $langs->trans("EventOrganizationArea"));
+
+print load_fiche_titre($langs->trans("EventOrganizationArea"), '', 'eventorganization.png@eventorganization');
+
+print '<div class="fichecenter"><div class="fichethirdleft">';
+
+
+/* BEGIN MODULEBUILDER DRAFT MYOBJECT
+// Draft MyObject
+if (! empty($conf->eventorganization->enabled) && $user->rights->eventorganization->read)
+{
+	$langs->load("orders");
+
+	$sql = "SELECT c.rowid, c.ref, c.ref_client, c.total_ht, c.tva as total_tva, c.total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas";
+	$sql.= ", s.code_client";
+	$sql.= " FROM ".MAIN_DB_PREFIX."commande as c";
+	$sql.= ", ".MAIN_DB_PREFIX."societe as s";
+	if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+	$sql.= " WHERE c.fk_soc = s.rowid";
+	$sql.= " AND c.fk_statut = 0";
+	$sql.= " AND c.entity IN (".getEntity('commande').")";
+	if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
+	if ($socid)	$sql.= " AND c.fk_soc = ".$socid;
+
+	$resql = $db->query($sql);
+	if ($resql)
+	{
+		$total = 0;
+		$num = $db->num_rows($resql);
+
+		print '<table class="noborder centpercent">';
+		print '<tr class="liste_titre">';
+		print '<th colspan="3">'.$langs->trans("DraftMyObjects").($num?'<span class="badge marginleftonlyshort">'.$num.'</span>':'').'</th></tr>';
+
+		$var = true;
+		if ($num > 0)
+		{
+			$i = 0;
+			while ($i < $num)
+			{
+
+				$obj = $db->fetch_object($resql);
+				print '<tr class="oddeven"><td class="nowrap">';
+
+				$myobjectstatic->id=$obj->rowid;
+				$myobjectstatic->ref=$obj->ref;
+				$myobjectstatic->ref_client=$obj->ref_client;
+				$myobjectstatic->total_ht = $obj->total_ht;
+				$myobjectstatic->total_tva = $obj->total_tva;
+				$myobjectstatic->total_ttc = $obj->total_ttc;
+
+				print $myobjectstatic->getNomUrl(1);
+				print '</td>';
+				print '<td class="nowrap">';
+				print '</td>';
+				print '<td class="right" class="nowrap">'.price($obj->total_ttc).'</td></tr>';
+				$i++;
+				$total += $obj->total_ttc;
+			}
+			if ($total>0)
+			{
+
+				print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td colspan="2" class="right">'.price($total)."</td></tr>";
+			}
+		}
+		else
+		{
+
+			print '<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("NoOrder").'</td></tr>';
+		}
+		print "</table><br>";
+
+		$db->free($resql);
+	}
+	else
+	{
+		dol_print_error($db);
+	}
+}
+END MODULEBUILDER DRAFT MYOBJECT */
+
+
+print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
+
+
+$NBMAX = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT;
+$max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT;
+
+/* BEGIN MODULEBUILDER LASTMODIFIED MYOBJECT
+// Last modified myobject
+if (! empty($conf->eventorganization->enabled) && $user->rights->eventorganization->read)
+{
+	$sql = "SELECT s.rowid, s.ref, s.label, s.date_creation, s.tms";
+	$sql.= " FROM ".MAIN_DB_PREFIX."eventorganization_myobject as s";
+	//if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+	$sql.= " WHERE s.entity IN (".getEntity($myobjectstatic->element).")";
+	//if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
+	//if ($socid)	$sql.= " AND s.rowid = $socid";
+	$sql .= " ORDER BY s.tms DESC";
+	$sql .= $db->plimit($max, 0);
+
+	$resql = $db->query($sql);
+	if ($resql)
+	{
+		$num = $db->num_rows($resql);
+		$i = 0;
+
+		print '<table class="noborder centpercent">';
+		print '<tr class="liste_titre">';
+		print '<th colspan="2">';
+		print $langs->trans("BoxTitleLatestModifiedMyObjects", $max);
+		print '</th>';
+		print '<th class="right">'.$langs->trans("DateModificationShort").'</th>';
+		print '</tr>';
+		if ($num)
+		{
+			while ($i < $num)
+			{
+				$objp = $db->fetch_object($resql);
+
+				$myobjectstatic->id=$objp->rowid;
+				$myobjectstatic->ref=$objp->ref;
+				$myobjectstatic->label=$objp->label;
+				$myobjectstatic->status = $objp->status;
+
+				print '<tr class="oddeven">';
+				print '<td class="nowrap">'.$myobjectstatic->getNomUrl(1).'</td>';
+				print '<td class="right nowrap">';
+				print "</td>";
+				print '<td class="right nowrap">'.dol_print_date($db->jdate($objp->tms), 'day')."</td>";
+				print '</tr>';
+				$i++;
+			}
+
+			$db->free($resql);
+		} else {
+			print '<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
+		}
+		print "</table><br>";
+	}
+}
+*/
+
+print '</div></div></div>';
+
+// End of page
+llxFooter();
+$db->close();

+ 85 - 0
htdocs/eventorganization/lib/eventorganization_conferenceorbooth.lib.php

@@ -0,0 +1,85 @@
+<?php
+/* Copyright (C) ---Put here your own copyright and developer email---
+ *
+ * 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
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ * \file    lib/eventorganization_conferenceorbooth.lib.php
+ * \ingroup eventorganization
+ * \brief   Library files with common functions for ConferenceOrBooth
+ */
+
+/**
+ * Prepare array of tabs for ConferenceOrBooth
+ *
+ * @param	ConferenceOrBooth	$object		ConferenceOrBooth
+ * @return 	array					Array of tabs
+ */
+function conferenceorboothPrepareHead($object)
+{
+	global $db, $langs, $conf;
+
+	$langs->load("eventorganization@eventorganization");
+
+	$h = 0;
+	$head = array();
+
+	$head[$h][0] = dol_buildpath("/eventorganization/conferenceorbooth_card.php", 1).'?id='.$object->id;
+	$head[$h][1] = $langs->trans("Card");
+	$head[$h][2] = 'card';
+	$h++;
+
+	if (isset($object->fields['note_public']) || isset($object->fields['note_private']))
+	{
+		$nbNote = 0;
+		if (!empty($object->note_private)) $nbNote++;
+		if (!empty($object->note_public)) $nbNote++;
+		$head[$h][0] = dol_buildpath('/eventorganization/conferenceorbooth_note.php', 1).'?id='.$object->id;
+		$head[$h][1] = $langs->trans('Notes');
+		if ($nbNote > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : '');
+		$head[$h][2] = 'note';
+		$h++;
+	}
+
+	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+	require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
+	$upload_dir = $conf->eventorganization->dir_output."/conferenceorbooth/".dol_sanitizeFileName($object->ref);
+	$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
+	$nbLinks = Link::count($db, $object->element, $object->id);
+	$head[$h][0] = dol_buildpath("/eventorganization/conferenceorbooth_document.php", 1).'?id='.$object->id;
+	$head[$h][1] = $langs->trans('Documents');
+	if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';
+	$head[$h][2] = 'document';
+	$h++;
+
+	$head[$h][0] = dol_buildpath("/eventorganization/conferenceorbooth_agenda.php", 1).'?id='.$object->id;
+	$head[$h][1] = $langs->trans("Events");
+	$head[$h][2] = 'agenda';
+	$h++;
+
+	// Show more tabs from modules
+	// Entries must be declared in modules descriptor with line
+	//$this->tabs = array(
+	//	'entity:+tabname:Title:@eventorganization:/eventorganization/mypage.php?id=__ID__'
+	//); // to add new tab
+	//$this->tabs = array(
+	//	'entity:-tabname:Title:@eventorganization:/eventorganization/mypage.php?id=__ID__'
+	//); // to remove a tab
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'conferenceorbooth@eventorganization');
+
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'conferenceorbooth@eventorganization', 'remove');
+
+	return $head;
+}

+ 6 - 6
htdocs/install/mysql/data/llx_c_email_templates.sql

@@ -32,9 +32,9 @@ INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_u
 
 INSERT INTO llx_c_email_templates (entity,module,type_template,lang,private,fk_user,datec,label,position,enabled,active,topic,content,content_lines,joinfiles) VALUES (0,'recruitment','recruitmentcandidature_send','',0,null,null,'(AnswerCandidature)'                    ,100,'$conf->recruitment->enabled',1,'[__[MAIN_INFO_SOCIETE_NOM]__] __(YourCandidature)__',       '__(Hello)__ __CANDIDATE_FULLNAME__,<br><br>\n\n__(YourCandidatureAnswerMessage)__<br>__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__\n<br><br>\n__(Sincerely)__<br>__USER_SIGNATURE__',null, 0);
 
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskConf', 10, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskConf)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventConfRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskBooth', 20, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventBoothRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsBooth', 30, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventBoothSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsEvent', 40, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsEvent)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventEventSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailAttendes', 50, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailAttendes)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventBulkMailToAttendes)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailSpeakers', 60, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailSpeakers)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventBulkMailToSpeakers)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskConf', 10, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskConf)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventConfRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskBooth', 20, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBoothRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsBooth', 30, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBoothSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsEvent', 40, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsEvent)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventEventSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailAttendees', 50, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailAttendes)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBulkMailToAttendees)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailSpeakers', 60, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailSpeakers)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBulkMailToSpeakers)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);

+ 11 - 6
htdocs/install/mysql/migration/13.0.0-14.0.0.sql

@@ -167,12 +167,17 @@ ALTER TABLE llx_tva ADD COLUMN fk_account integer;
 ALTER TABLE llx_tva ALTER COLUMN paye SET DEFAULT 0;
 
 
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskConf', 10, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskConf)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventConfRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskBooth', 20, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventBoothRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsBooth', 30, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventBoothSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsEvent', 40, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsEvent)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventEventSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailAttendes', 50, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailAttendes)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventBulkMailToAttendes)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
-INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailSpeakers', 60, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailSpeakers)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOragnisationEventBulkMailToSpeakers)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskConf', 10, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskConf)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventConfRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailAskBooth', 20, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailAskBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBoothRequestWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsBooth', 30, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsBooth)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBoothSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationEmailSubsEvent', 40, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationEmailSubsEvent)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventEventSubscriptionWasReceived)__<br /><br />__ONLINE_PAYMENT_TEXT_AND_URL__<br /><br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailAttendes', 50, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailAttendes)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBulkMailToAttendees)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+INSERT INTO llx_c_email_templates (entity, module, type_template, lang, private, fk_user, datec, tms, label, position, active, topic, content, content_lines, enabled, joinfiles) values (0, '', 'eventorganization_send', '', 0, null, null, '2021-02-14 14:42:41', 'EventOrganizationMassEmailSpeakers', 60, 1, '[__[MAIN_INFO_SOCIETE_NOM]__] __(EventOrganizationMassEmailSpeakers)__', '__(Hello)__ __THIRDPARTY_NAME__,<br /><br />__(ThisIsContentOfYourOrganizationEventBulkMailToSpeakers)__<br /><br />__(Sincerely)__<br />__USER_SIGNATURE__', null, '1', null);
+
+ALTER TABLE llx_projet ADD COLUMN accept_conference_suggestions integer DEFAULT 0;
+ALTER TABLE llx_projet ADD COLUMN accept_booth_suggestions integer DEFAULT 0;
+ALTER TABLE llx_projet ADD COLUMN price_registration double(24,8);
+ALTER TABLE llx_projet ADD COLUMN price_booth double(24,8);
 
 
 -- Code enhanced - Standardize field name

+ 4 - 0
htdocs/install/mysql/tables/llx_projet.sql

@@ -48,6 +48,10 @@ create table llx_projet
   usage_task           integer DEFAULT 1,		-- Set to 1 if project is used to manage tasks and/or record timesheet
   usage_bill_time      integer DEFAULT 0,		-- Set to 1 if time spent must be converted into invoices
   usage_organize_event integer DEFAULT 0,		-- Set to 1 if you want to use project to organize an event, receive attendees subscription				
+  accept_conference_suggestions integer DEFAULT 0,		-- Set to 1 if you want to allow unknown people to suggest conferences
+  accept_booth_suggestions integer DEFAULT 0,		-- Set to 1 if you want to Allow unknown people to suggest booth
+  price_registration    double(24,8),
+  price_booth    double(24,8),
   model_pdf        varchar(255),
   last_main_doc	   varchar(255),				-- relative filepath+filename of last main generated document
   import_key	   varchar(14)					-- Import key

+ 18 - 3
htdocs/langs/en_US/eventorganization.lang

@@ -43,15 +43,30 @@ EVENTORGANIZATION_TEMPLATE_EMAIL_BULK_ATTENDES = Template of email of massaction
 #
 EventOrganizationConfOrBooth= Conference Or Booth
 ManageOrganizeEvent = Manage event organisation
+ConferenceOrBooth = Conference Or Booth
+ConferenceOrBoothTab = Conference Or Booth
 
 #
 # Template Mail
 #
-YourOragnisationEventConfRequestWasReceived = Your request for conference was received
-YourOragnisationEventBoothRequestWasReceived = Your request for booth was received
+YourOrganizationEventConfRequestWasReceived = Your request for conference was received
+YourOrganizationEventBoothRequestWasReceived = Your request for booth was received
 EventOrganizationEmailAskConf = Request for conference
 EventOrganizationEmailAskBooth = Request for booth
 EventOrganizationEmailSubsBooth = Subscription for booth
 EventOrganizationEmailSubsEvent = Subscription for an event
-EventOrganizationMassEmailAttendes = Communication to attendes
+EventOrganizationMassEmailAttendees = Communication to attendes
 EventOrganizationMassEmailSpeakers = Communication to speakers
+
+#
+# Event
+#
+AllowUnknownPeopleSuggestConf=Allow unknown people to suggest conferences
+AllowUnknownPeopleSuggestConfHelp=Allow unknown people to suggest conferences
+AllowUnknownPeopleSuggestBooth=Allow unknown people to suggest booth
+AllowUnknownPeopleSuggestBoothHelp=Allow unknown people to suggest booth
+PriceOfRegistration=Price of registration
+PriceOfRegistrationHelp=Price of registration
+PriceOfBooth=Price of subscription
+PriceOfBoothHelp=Price of subscription
+EventOrganizationICSLink=Link ICS for events

+ 2 - 2
htdocs/product/index.php

@@ -5,7 +5,7 @@
  * Copyright (C) 2014-2016  Charlie BENKE           <charlie@patas-monkey.com>
  * Copyright (C) 2015       Jean-François Ferry     <jfefe@aternatik.fr>
  * Copyright (C) 2019       Pierre Ardoin           <mapiolca@me.com>
- * Copyright (C) 2019       Frédéric France         <frederic.france@netlogic.fr>
+ * Copyright (C) 2019-2021  Frédéric France         <frederic.france@netlogic.fr>
  * Copyright (C) 2019       Nicolas ZABOURI         <info@inovea-conseil.com>
  *
  * This program is free software; you can redistribute it and/or modify
@@ -200,7 +200,7 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA
 	print '<div class="div-table-responsive-no-min">';
 	print '<table class="noborder centpercent">';
 	print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Categories").'</th></tr>';
-	print '<tr class="oddeven"><td class="center" colspan="2">';
+	print '<tr><td class="center" colspan="2">';
 	$sql = "SELECT c.label, count(*) as nb";
 	$sql .= " FROM ".MAIN_DB_PREFIX."categorie_product as cs";
 	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON cs.fk_categorie = c.rowid";

+ 9 - 9
htdocs/projet/card.php

@@ -228,7 +228,7 @@ if (empty($reshook))
 		}
 	}
 
-	if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer)
+	if ($action == 'update' && empty(GETPOST('cancel')) && $user->rights->projet->creer)
 	{
 		$error = 0;
 
@@ -1132,7 +1132,7 @@ if ($action == 'create' && $user->rights->projet->creer)
 	if ($action == 'edit' && $userWrite > 0)
 	{
 		print '<div class="center">';
-		print '<input name="update" class="button" type="submit" value="'.$langs->trans("Modify").'">&nbsp; &nbsp; &nbsp;';
+		print '<input name="update" class="button" type="submit" value="'.$langs->trans("Save").'">&nbsp; &nbsp; &nbsp;';
 		print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
 		print '</div>';
 	}
@@ -1223,14 +1223,14 @@ if ($action == 'create' && $user->rights->projet->creer)
 
 			// Send
 			if (empty($user->socid)) {
-				if ($object->statut != 2)
+				if ($object->statut != Project::STATUS_CLOSED)
 				{
 					print '<a class="butAction" href="card.php?id='.$object->id.'&amp;action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>';
 				}
 			}
 
 			// Modify
-			if ($object->statut != 2 && $user->rights->projet->creer)
+			if ($object->statut != Project::STATUS_CLOSED && $user->rights->projet->creer)
 			{
 				if ($userWrite > 0)
 				{
@@ -1241,7 +1241,7 @@ if ($action == 'create' && $user->rights->projet->creer)
 			}
 
 			// Validate
-			if ($object->statut == 0 && $user->rights->projet->creer)
+			if ($object->statut == Project::STATUS_DRAFT && $user->rights->projet->creer)
 			{
 				if ($userWrite > 0)
 				{
@@ -1252,7 +1252,7 @@ if ($action == 'create' && $user->rights->projet->creer)
 			}
 
 			// Close
-			if ($object->statut == 1 && $user->rights->projet->creer)
+			if ($object->statut == Project::STATUS_VALIDATED && $user->rights->projet->creer)
 			{
 				if ($userWrite > 0)
 				{
@@ -1263,7 +1263,7 @@ if ($action == 'create' && $user->rights->projet->creer)
 			}
 
 			// Reopen
-			if ($object->statut == 2 && $user->rights->projet->creer)
+			if ($object->statut == Project::STATUS_CLOSED && $user->rights->projet->creer)
 			{
 				if ($userWrite > 0)
 				{
@@ -1340,9 +1340,9 @@ if ($action == 'create' && $user->rights->projet->creer)
 			}
 
 			// Delete
-			if ($user->rights->projet->supprimer || ($object->statut == 0 && $user->rights->projet->creer))
+			if ($user->rights->projet->supprimer || ($object->statut == Project::STATUS_DRAFT && $user->rights->projet->creer))
 			{
-				if ($userDelete > 0 || ($object->statut == 0 && $user->rights->projet->creer))
+				if ($userDelete > 0 || ($object->statut == Project::STATUS_DRAFT && $user->rights->projet->creer))
 				{
 					print '<a class="butActionDelete" href="card.php?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a>';
 				} else {

+ 26 - 1
htdocs/projet/class/project.class.php

@@ -201,6 +201,10 @@ class Project extends CommonObject
 		'usage_opportunity' =>array('type'=>'integer', 'label'=>'UsageOpportunity', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
 		'usage_task' =>array('type'=>'integer', 'label'=>'UsageTasks', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
 		'usage_organize_event' =>array('type'=>'integer', 'label'=>'UsageOrganizeEvent', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
+		'accept_conference_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestConf', 'enabled'=>1, 'visible'=>-1, 'position'=>146),
+		'accept_booth_suggestions' =>array('type'=>'integer', 'label'=>'AllowUnknownPeopleSuggestBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>147),
+		'price_registration' =>array('type'=>'double(24,8)', 'label'=>'PriceOfRegistration', 'enabled'=>1, 'visible'=>-1, 'position'=>148),
+		'price_booth' =>array('type'=>'double(24,8)', 'label'=>'PriceOfBooth', 'enabled'=>1, 'visible'=>-1, 'position'=>149),
 		'datec' =>array('type'=>'datetime', 'label'=>'DateCreationShort', 'enabled'=>1, 'visible'=>-2, 'position'=>200),
 		'tms' =>array('type'=>'timestamp', 'label'=>'DateModificationShort', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>205),
 		'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserCreation', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>210),
@@ -257,6 +261,10 @@ class Project extends CommonObject
 
 		if (empty($conf->eventorganization->enabled)) {
 			$this->fields['usage_organize_event']['visible'] = 0;
+			$this->fields['accept_conference_suggestions']['enabled'] = 0;
+			$this->fields['accept_booth_suggestions']['enabled'] = 0;
+			$this->fields['price_registration']['enabled'] = 0;
+			$this->fields['price_booth']['enabled'] = 0;
 		}
 	}
 
@@ -316,6 +324,10 @@ class Project extends CommonObject
 		$sql .= ", usage_task";
 		$sql .= ", usage_bill_time";
 		$sql .= ", usage_organize_event";
+		$sql .= ", accept_conference_suggestions";
+		$sql .= ", accept_booth_suggestions";
+		$sql .= ", price_registration";
+		$sql .= ", price_booth";
 		$sql .= ", email_msgid";
 		$sql .= ", note_private";
 		$sql .= ", note_public";
@@ -339,6 +351,10 @@ class Project extends CommonObject
 		$sql .= ", ".($this->usage_task ? 1 : 0);
 		$sql .= ", ".($this->usage_bill_time ? 1 : 0);
 		$sql .= ", ".($this->usage_organize_event ? 1 : 0);
+		$sql .= ", ".($this->accept_conference_suggestions ? 1 : 0);
+		$sql .= ", ".($this->accept_booth_suggestions ? 1 : 0);
+		$sql .= ", ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : 'null');
+		$sql .= ", ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : 'null');
 		$sql .= ", ".($this->email_msgid ? "'".$this->db->escape($this->email_msgid)."'" : 'null');
 		$sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : 'null');
 		$sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : 'null');
@@ -442,6 +458,10 @@ class Project extends CommonObject
 			$sql .= ", usage_task = ".($this->usage_task ? 1 : 0);
 			$sql .= ", usage_bill_time = ".($this->usage_bill_time ? 1 : 0);
 			$sql .= ", usage_organize_event = ".($this->usage_organize_event ? 1 : 0);
+			$sql .= ", accept_conference_suggestions = ".($this->accept_conference_suggestions ? 1 : 0);
+			$sql .= ", accept_booth_suggestions = ".($this->accept_booth_suggestions ? 1 : 0);
+			$sql .= ", price_registration = ".(strcmp($this->price_registration, '') ? price2num($this->price_registration) : "null");
+			$sql .= ", price_booth = ".(strcmp($this->price_booth, '') ? price2num($this->price_booth) : "null");
 			$sql .= " WHERE rowid = ".$this->id;
 
 			dol_syslog(get_class($this)."::update", LOG_DEBUG);
@@ -531,7 +551,8 @@ class Project extends CommonObject
 
 		$sql = "SELECT rowid, entity, ref, title, description, public, datec, opp_amount, budget_amount,";
 		$sql .= " tms, dateo, datee, date_close, fk_soc, fk_user_creat, fk_user_modif, fk_user_close, fk_statut as status, fk_opp_status, opp_percent,";
-		$sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, email_msgid";
+		$sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, email_msgid,";
+		$sql .= " accept_conference_suggestions, accept_booth_suggestions, price_registration, price_booth";
 		$sql .= " FROM ".MAIN_DB_PREFIX."projet";
 		if (!empty($id))
 		{
@@ -588,6 +609,10 @@ class Project extends CommonObject
 				$this->usage_task = (int) $obj->usage_task;
 				$this->usage_bill_time = (int) $obj->usage_bill_time;
 				$this->usage_organize_event = (int) $obj->usage_organize_event;
+				$this->accept_conference_suggestions = (int) $obj->accept_conference_suggestions;
+				$this->accept_booth_suggestions = (int) $obj->accept_booth_suggestions;
+				$this->price_registration = $obj->price_registration;
+				$this->price_booth = $obj->price_booth;
 				$this->email_msgid = $obj->email_msgid;
 
 				$this->db->free($resql);

+ 344 - 0
htdocs/projet/event.php

@@ -0,0 +1,344 @@
+<?php
+/* Copyright (C) 2010 Regis Houssin        <regis.houssin@inodbox.com>
+ * Copyright (C) 2012 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2021 florian.henry@scopen.fr  <florian.henry@scopen.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
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ *	\file       htdocs/projet/event.php
+ *	\ingroup    project
+ *	\brief      Tab event organization
+ */
+
+require '../main.inc.php';
+require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
+
+// Load translation files required by the page
+$langs->load('projects', 'enevntorganization');
+
+$action = GETPOST('action', 'aZ09');
+$id = GETPOST('id', 'int');
+$ref = GETPOST('ref', 'alpha');
+
+$mine = $_REQUEST['mode'] == 'mine' ? 1 : 0;
+//if (! $user->rights->projet->all->lire) $mine=1;	// Special for projects
+
+$object = new Project($db);
+
+include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
+
+// Security check
+$socid = 0;
+if ($user->socid > 0) $socid = $user->socid;    // For external user, no check is done on company because readability is managed by public status of project and assignement.
+$result = restrictedArea($user, 'eventorganization', $id);
+
+$permissiontoread = $user->rights->eventorganization->read;
+$permissiontoadd = $user->rights->eventorganization->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
+$permissiontodelete = $user->rights->eventorganization->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT);
+
+/*
+ * Actions
+ */
+
+if ($action == 'update' && empty(GETPOST('cancel')) && $permissiontoadd) {
+	$error = 0;
+	$object->oldcopy = clone $object;
+
+	$object->accept_conference_suggestions=(GETPOST('accept_conference_suggestions', 'alpha') == 'on' ? 1 : 0);
+	$object->accept_booth_suggestions=(GETPOST('accept_booth_suggestions', 'alpha') == 'on' ? 1 : 0);
+	$object->price_registration=price2num(GETPOST('price_registration', 'alphanohtml'));;
+	$object->price_booth=price2num(GETPOST('price_booth', 'alphanohtml'));;
+
+	$result = $object->update($user);
+	if ($result < 0) {
+		setEventMessages($object->error, $object->errors, 'errors');
+		$db->rollback();
+		$action = 'edit';
+	} else {
+		$db->commit();
+		if (GETPOST('socid', 'int') > 0) $object->fetch_thirdparty(GETPOST('socid', 'int'));
+		else unset($object->thirdparty);
+		$action='';
+	}
+}
+
+
+
+/*
+ * View
+ */
+
+$title = $langs->trans("Project").' - '.$langs->trans("ConferenceOrBoothTab").' - '.$object->ref.' '.$object->name;
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Note");
+//TODO Make wiki docs
+$help_url = '';
+llxHeader("", $title, $help_url);
+
+$form = new Form($db);
+$userstatic = new User($db);
+
+$now = dol_now();
+
+if ($id > 0 || !empty($ref))
+{
+	$head = project_prepare_head($object);
+	print dol_get_fiche_head($head, 'eventorganisation', $langs->trans('ConferenceOrBoothTab'), -1);
+
+	// Project card
+
+	$linkback = '<a href="'.DOL_URL_ROOT.'/projet/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	// Title
+	$morehtmlref .= $object->title;
+	// Thirdparty
+	if ($object->thirdparty->id > 0)
+	{
+		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'project');
+	}
+	$morehtmlref .= '</div>';
+
+	// Define a complementary filter for search of next/prev ref.
+	if (!$user->rights->projet->all->lire)
+	{
+		$objectsListId = $object->getProjectsAuthorizedForUser($user, 0, 0);
+		$object->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
+	}
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+
+	print '<div class="fichecenter">';
+	print '<div class="fichehalfleft">';
+	print '<div class="underbanner clearboth"></div>';
+
+	print '<table class="border tableforfield" width="100%">';
+
+	// Usage
+	print '<tr><td class="tdtop">';
+	print $langs->trans("Usage");
+	print '</td>';
+	print '<td>';
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
+	{
+		print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_opportunity ? ' checked="checked"' : '')).'"> ';
+		$htmltext = $langs->trans("ProjectFollowOpportunity");
+		print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
+		print '<br>';
+	}
+	if (empty($conf->global->PROJECT_HIDE_TASKS))
+	{
+		print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_task ? ' checked="checked"' : '')).'"> ';
+		$htmltext = $langs->trans("ProjectFollowTasks");
+		print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
+		print '<br>';
+	}
+	if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
+	{
+		print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_bill_time ? ' checked="checked"' : '')).'"> ';
+		$htmltext = $langs->trans("ProjectBillTimeDescription");
+		print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
+		print '<br>';
+	}
+
+	if (!empty($conf->eventorganization->enabled))
+	{
+		print '<input type="checkbox" disabled name="usage_organize_event"'.(GETPOSTISSET('usage_organize_event') ? (GETPOST('usage_organize_event', 'alpha') != '' ? ' checked="checked"' : '') : ($object->usage_organize_event ? ' checked="checked"' : '')).'"> ';
+		$htmltext = $langs->trans("EventOrganizationDescriptionLong");
+		print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext);
+	}
+	print '</td></tr>';
+
+	// Visibility
+	print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
+	if ($object->public) print $langs->trans('SharedProject');
+	else print $langs->trans('PrivateProject');
+	print '</td></tr>';
+
+	if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES) && !empty($object->usage_opportunity))
+	{
+		// Opportunity status
+		print '<tr><td>'.$langs->trans("OpportunityStatus").'</td><td>';
+		$code = dol_getIdFromCode($db, $object->opp_status, 'c_lead_status', 'rowid', 'code');
+		if ($code) print $langs->trans("OppStatus".$code);
+		print '</td></tr>';
+
+		// Opportunity percent
+		print '<tr><td>'.$langs->trans("OpportunityProbability").'</td><td>';
+		if (strcmp($object->opp_percent, '')) print price($object->opp_percent, 0, $langs, 1, 0).' %';
+		print '</td></tr>';
+
+		// Opportunity Amount
+		print '<tr><td>'.$langs->trans("OpportunityAmount").'</td><td>';
+		/*if ($object->opp_status)
+		{
+		   print price($obj->opp_amount, 1, $langs, 1, 0, -1, $conf->currency);
+		}*/
+		if (strcmp($object->opp_amount, '')) print price($object->opp_amount, 0, $langs, 1, 0, -1, $conf->currency);
+		print '</td></tr>';
+
+		// Opportunity Weighted Amount
+		print '<tr><td>'.$langs->trans('OpportunityWeightedAmount').'</td><td>';
+		if (strcmp($object->opp_amount, '') && strcmp($object->opp_percent, '')) print price($object->opp_amount * $object->opp_percent / 100, 0, $langs, 1, 0, -1, $conf->currency);
+		print '</td></tr>';
+	}
+
+	// Date start - end
+	print '<tr><td>'.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").'</td><td>';
+	$start = dol_print_date($object->date_start, 'day');
+	print ($start ? $start : '?');
+	$end = dol_print_date($object->date_end, 'day');
+	print ' - ';
+	print ($end ? $end : '?');
+	if ($object->hasDelay()) print img_warning("Late");
+	print '</td></tr>';
+
+	// Budget
+	print '<tr><td>'.$langs->trans("Budget").'</td><td>';
+	if (strcmp($object->budget_amount, '')) print price($object->budget_amount, 0, $langs, 1, 0, 0, $conf->currency);
+	print '</td></tr>';
+
+	// Other attributes
+	$cols = 2;
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
+
+	print '</table>';
+
+	print '</div>';
+	print '<div class="fichehalfright">';
+	print '<div class="ficheaddleft">';
+	print '<div class="underbanner clearboth"></div>';
+
+	if ($action == 'edit') {
+		print '<form 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="' . $object->id . '">';
+	}
+
+	print '<table class="border tableforfield" width="100%">';
+
+	// Description
+	print '<td class="titlefield tdtop">'.$langs->trans("Description").'</td><td>';
+	print dol_htmlentitiesbr($object->description);
+	print '</td></tr>';
+
+	// Categories
+	if ($conf->categorie->enabled) {
+		print '<tr><td class="valignmiddle">'.$langs->trans("Categories").'</td><td>';
+		print $form->showCategories($object->id, Categorie::TYPE_PROJECT, 1);
+		print "</td></tr>";
+	}
+
+	if ($action == 'edit' && $permissiontoadd) {
+		//Allow unknown people to suggest conferences
+		print '<tr><td class="valignmiddle">' . $langs->trans("AllowUnknownPeopleSuggestConf") . $form->textwithpicto('', $langs->trans("AllowUnknownPeopleSuggestConfHelp")) . '</td><td>';
+		print '<input type="checkbox" name="accept_conference_suggestions"' . (GETPOSTISSET('accept_conference_suggestions') ? (GETPOST('accept_conference_suggestions', 'alpha') != '' ? ' checked="checked"' : '') : ($object->accept_conference_suggestions ? ' checked="checked"' : '')) . '"> ';
+		print "</td></tr>";
+
+		//Allow unknown people to suggest booth
+		print '<tr><td class="valignmiddle">' . $langs->trans("AllowUnknownPeopleSuggestBooth") . $form->textwithpicto('', $langs->trans("AllowUnknownPeopleSuggestBoothHelp")) . '</td><td>';
+		print '<input type="checkbox" name="accept_booth_suggestions"' . (GETPOSTISSET('accept_booth_suggestions') ? (GETPOST('accept_booth_suggestions', 'alpha') != '' ? ' checked="checked"' : '') : ($object->accept_booth_suggestions ? ' checked="checked"' : '')) . '"> ';
+		print "</td></tr>";
+
+		//Price of registration
+		print '<tr><td class="valignmiddle">' . $langs->trans("PriceOfRegistration") . '</td><td>';
+		print '<input size="5" type="text" name="price_registration" value="'.(GETPOSTISSET('price_registration') ? GETPOST('price_registration') : (strcmp($object->price_registration, '') ? price2num($object->price_registration) : '')).'">';
+		print "</td></tr>";
+
+		//Price of registration
+		print '<tr><td class="valignmiddle">' . $langs->trans("PriceOfBooth") . '</td><td>';
+		print '<input size="5" type="text" name="price_booth" value="'.(GETPOSTISSET('price_booth') ? GETPOST('price_booth') : (strcmp($object->price_booth, '') ? price2num($object->price_booth) : '')).'">';
+		print "</td></tr>";
+	} else {
+		//Allow unknown people to suggest conferences
+		print '<tr><td class="valignmiddle">' . $langs->trans("AllowUnknownPeopleSuggestConf") . $form->textwithpicto('', $langs->trans("AllowUnknownPeopleSuggestConfHelp")) . '</td><td>';
+		print '<input type="checkbox" disabled name="accept_conference_suggestions"' . (GETPOSTISSET('accept_conference_suggestions') ? (GETPOST('accept_conference_suggestions', 'alpha') != '' ? ' checked="checked"' : '') : ($object->accept_conference_suggestions ? ' checked="checked"' : '')) . '"> ';
+		print "</td></tr>";
+
+		//Allow unknown people to suggest booth
+		print '<tr><td class="valignmiddle">' . $langs->trans("AllowUnknownPeopleSuggestBooth") . $form->textwithpicto('', $langs->trans("AllowUnknownPeopleSuggestBoothHelp")) . '</td><td>';
+		print '<input type="checkbox" disabled name="accept_booth_suggestions"' . (GETPOSTISSET('accept_booth_suggestions') ? (GETPOST('accept_booth_suggestions', 'alpha') != '' ? ' checked="checked"' : '') : ($object->accept_booth_suggestions ? ' checked="checked"' : '')) . '"> ';
+		print "</td></tr>";
+
+		//Price of registration
+		print '<tr><td class="valignmiddle">' . $langs->trans("PriceOfRegistration") . '</td><td>';
+		if (strcmp($object->price_registration, '')) print price($object->price_registration, 0, $langs, 1, 0, 0, $conf->currency);
+		print "</td></tr>";
+
+		//Price of registration
+		print '<tr><td class="valignmiddle">' . $langs->trans("PriceOfBooth") . '</td><td>';
+		if (strcmp($object->price_booth, '')) print price($object->price_booth, 0, $langs, 1, 0, 0, $conf->currency);
+		print "</td></tr>";
+	}
+
+	//ICS Link
+	print '<tr><td class="valignmiddle">'.$langs->trans("EventOrganizationICSLink").'</td><td>';
+	//TODO ICS Link
+	//print '<a href="ICSLink">ICS</a>';
+	print "</td></tr>";
+
+	print '</table>';
+
+	print '</table>';
+
+	print '</div>';
+	print '</div>';
+	print '</div>';
+
+	print '<div class="clearboth"></div>';
+}
+
+print dol_get_fiche_end();
+
+if ($action == 'edit' && $permissiontoadd > 0)
+{
+	print '<div class="center">';
+	print '<input name="update" class="button" type="submit" value="'.$langs->trans("Save").'">&nbsp; &nbsp; &nbsp;';
+	print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
+	print '</div>';
+
+	print '</form>';
+}
+
+
+/*
+     * Actions Buttons
+     */
+print '<div class="tabsAction">';
+$parameters = array();
+$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
+// modified by hook
+if (empty($reshook))
+{
+	// Modify
+	if ($object->statut != Project::STATUS_CLOSED && $action=='')
+	{
+		if ($permissiontoadd > 0)
+		{
+			print '<a class="butAction" href="event.php?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>';
+		} else {
+			print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotOwnerOfProject").'">'.$langs->trans('Modify').'</a>';
+		}
+	}
+}
+
+// End of page
+llxFooter();
+$db->close();

+ 96 - 0
htdocs/projet/list.php

@@ -43,6 +43,9 @@ if (!empty($conf->categorie->enabled))
 
 // Load translation files required by the page
 $langs->loadLangs(array('projects', 'companies', 'commercial'));
+if ($conf->eventorganization->enabled) {
+	$langs->loadLangs(array('eventorganization'));
+}
 
 $action = GETPOST('action', 'aZ09');
 $massaction = GETPOST('massaction', 'alpha');
@@ -93,6 +96,10 @@ $search_usage_opportunity = GETPOST('search_usage_opportunity', 'int');
 $search_usage_task = GETPOST('search_usage_task', 'int');
 $search_usage_bill_time = GETPOST('search_usage_bill_time', 'int');
 $search_usage_event_organization = GETPOST('search_usage_event_organization', 'int');
+$search_accept_conference_suggestions = GETPOST('search_accept_conference_suggestions', 'int');
+$search_accept_booth_suggestions = GETPOST('search_accept_booth_suggestions', 'int');
+$search_price_registration = GETPOST("search_price_registration", 'alpha');
+$search_price_booth = GETPOST("search_price_booth", 'alpha');
 $optioncss = GETPOST('optioncss', 'alpha');
 
 $mine = $_REQUEST['mode'] == 'mine' ? 1 : 0;
@@ -209,6 +216,10 @@ if (empty($reshook))
 		$search_usage_task = '';
 		$search_usage_bill_time = '';
 		$search_usage_event_organization = '';
+		$search_accept_conference_suggestions = '';
+		$search_accept_booth_suggestions = '';
+		$search_price_registration = '';
+		$search_price_booth = '';
 		$toselect = '';
 		$search_array_options = array();
 		$search_category_array = array();
@@ -304,6 +315,7 @@ $distinct = 'DISTINCT'; // We add distinct until we are added a protection to be
 $sql = "SELECT ".$distinct." p.rowid as id, p.ref, p.title, p.fk_statut as status, p.fk_opp_status, p.public, p.fk_user_creat";
 $sql .= ", p.datec as date_creation, p.dateo as date_start, p.datee as date_end, p.opp_amount, p.opp_percent, (p.opp_amount*p.opp_percent/100) as opp_weighted_amount, p.tms as date_update, p.budget_amount ";
 $sql .= ",  p.usage_opportunity, p.usage_task, p.usage_bill_time, p.usage_organize_event";
+$sql .= ", accept_conference_suggestions, accept_booth_suggestions, price_registration, price_booth";
 $sql .= ", s.rowid as socid, s.nom as name, s.email";
 $sql .= ", cls.code as opp_status_code";
 // Add fields from extrafields
@@ -373,6 +385,10 @@ if ($search_usage_opportunity != '' && $search_usage_opportunity >= 0) $sql .= n
 if ($search_usage_task != '' && $search_usage_task >= 0)               $sql .= natural_search('p.usage_task', $search_usage_task, 2);
 if ($search_usage_bill_time != '' && $search_usage_bill_time >= 0)     $sql .= natural_search('p.usage_bill_time', $search_usage_bill_time, 2);
 if ($search_usage_event_organization != '' && $search_usage_event_organization >= 0)     $sql .= natural_search('p.usage_organize_event', $search_usage_event_organization, 2);
+if ($search_accept_conference_suggestions != '' && $search_accept_conference_suggestions >= 0)     $sql .= natural_search('p.accept_conference_suggestions', $search_accept_conference_suggestions, 2);
+if ($search_accept_booth_suggestions != '' && $search_accept_booth_suggestions >= 0)     $sql .= natural_search('p.accept_booth_suggestions', $search_accept_booth_suggestions, 2);
+if ($search_price_registration != '') $sql .= natural_search('p.price_registration', $search_price_registration, 1);
+if ($search_price_booth != '') $sql .= natural_search('p.price_booth', $search_price_booth, 1);
 // Add where from extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
 // Add where from hooks
@@ -450,6 +466,10 @@ if ($search_budget_amount != '') $param .= '&search_budget_amount='.urlencode($s
 if ($search_usage_task != '') $param .= '&search_usage_task='.urlencode($search_usage_task);
 if ($search_usage_bill_time != '') $param .= '&search_usage_opportunity='.urlencode($search_usage_bill_time);
 if ($search_usage_event_organization != '') $param .= '&search_usage_event_organization='.urlencode($search_usage_event_organization);
+if ($search_accept_conference_suggestions != '') $param .= '&search_accept_conference_suggestions='.urlencode($search_accept_conference_suggestions);
+if ($search_accept_booth_suggestions != '') $param .= '&search_accept_booth_suggestions='.urlencode($search_accept_booth_suggestions);
+if ($search_price_registration != '') $param .= '&search_price_registration='.urlencode($search_price_registration);
+if ($search_price_booth != '') $param .= '&search_price_booth='.urlencode($search_price_booth);
 if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
 // Add $param from extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@@ -663,6 +683,30 @@ if (!empty($arrayfields['p.usage_organize_event']['checked']))
 	print $form->selectyesno('search_usage_event_organization', $search_usage_event_organization, 1, false, 1);
 	print '</td>';
 }
+if (!empty($arrayfields['p.accept_conference_suggestions']['checked']))
+{
+	print '<td class="liste_titre nowrap right">';
+	print $form->selectyesno('search_accept_conference_suggestions', $search_accept_conference_suggestions, 1, false, 1);
+	print '</td>';
+}
+if (!empty($arrayfields['p.accept_booth_suggestions']['checked']))
+{
+	print '<td class="liste_titre nowrap right">';
+	print $form->selectyesno('search_accept_booth_suggestions', $search_accept_booth_suggestions, 1, false, 1);
+	print '</td>';
+}
+if (!empty($arrayfields['p.price_registration']['checked']))
+{
+	print '<td class="liste_titre nowrap right">';
+	print '<input type="text" class="flat" name="search_price_registration" size="4" value="'.$search_price_registration.'">';
+	print '</td>';
+}
+if (!empty($arrayfields['p.price_booth']['checked']))
+{
+	print '<td class="liste_titre nowrap right">';
+	print '<input type="text" class="flat" name="search_price_booth" size="4" value="'.$search_price_booth.'">';
+	print '</td>';
+}
 // Extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
 
@@ -717,6 +761,10 @@ if (!empty($arrayfields['p.usage_opportunity']['checked'])) print_liste_field_ti
 if (!empty($arrayfields['p.usage_task']['checked']))        print_liste_field_titre($arrayfields['p.usage_task']['label'], $_SERVER["PHP_SELF"], 'p.usage_task', "", $param, '', $sortfield, $sortorder, 'right ');
 if (!empty($arrayfields['p.usage_bill_time']['checked']))   print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right ');
 if (!empty($arrayfields['p.usage_organize_event']['checked']))   print_liste_field_titre($arrayfields['p.usage_organize_event']['label'], $_SERVER["PHP_SELF"], 'p.usage_organize_event', "", $param, '', $sortfield, $sortorder, 'right ');
+if (!empty($arrayfields['p.accept_conference_suggestions']['checked']))   print_liste_field_titre($arrayfields['p.accept_conference_suggestions']['label'], $_SERVER["PHP_SELF"], 'p.accept_conference_suggestions', "", $param, '', $sortfield, $sortorder, 'right ');
+if (!empty($arrayfields['p.accept_booth_suggestions']['checked']))   print_liste_field_titre($arrayfields['p.accept_booth_suggestions']['label'], $_SERVER["PHP_SELF"], 'p.accept_booth_suggestions', "", $param, '', $sortfield, $sortorder, 'right ');
+if (!empty($arrayfields['p.price_registration']['checked'])) print_liste_field_titre($arrayfields['p.price_registration']['label'], $_SERVER["PHP_SELF"], 'p.price_registration', "", $param, '', $sortfield, $sortorder, 'right ');
+if (!empty($arrayfields['p.price_booth']['checked'])) print_liste_field_titre($arrayfields['p.price_booth']['label'], $_SERVER["PHP_SELF"], 'p.price_booth', "", $param, '', $sortfield, $sortorder, 'right ');
 // Extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
 // Hook fields
@@ -952,6 +1000,54 @@ while ($i < min($num, $limit))
 			print '</td>';
 			if (!$i) $totalarray['nbfield']++;
 		}
+		// Allow unknown people to suggest conferences
+		if (!empty($arrayfields['p.accept_conference_suggestions']['checked']))
+		{
+			print '<td class="right">';
+			if ($obj->accept_conference_suggestions)
+			{
+				print yn($obj->accept_conference_suggestions);
+			}
+			print '</td>';
+			if (!$i) $totalarray['nbfield']++;
+		}
+		// Allow unknown people to suggest booth
+		if (!empty($arrayfields['p.accept_booth_suggestions']['checked']))
+		{
+			print '<td class="right">';
+			if ($obj->accept_booth_suggestions)
+			{
+				print yn($obj->accept_booth_suggestions);
+			}
+			print '</td>';
+			if (!$i) $totalarray['nbfield']++;
+		}
+		// Price of registration
+		if (!empty($arrayfields['p.price_registration']['checked']))
+		{
+			print '<td class="right">';
+			if ($obj->price_registration != '')
+			{
+				print price($obj->price_registration, 1, $langs, 1, -1, -1);
+				$totalarray['val']['p.price_registration'] += $obj->price_registration;
+			}
+			print '</td>';
+			if (!$i) $totalarray['nbfield']++;
+			if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.price_registration';
+		}
+		// PriceOfBooth
+		if (!empty($arrayfields['p.price_booth']['checked']))
+		{
+			print '<td class="right">';
+			if ($obj->price_booth != '')
+			{
+				print price($obj->price_booth, 1, $langs, 1, -1, -1);
+				$totalarray['val']['p.price_booth'] += $obj->price_booth;
+			}
+			print '</td>';
+			if (!$i) $totalarray['nbfield']++;
+			if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.price_booth';
+		}
 		// Extra fields
 		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
 		// Fields from hook

+ 120 - 108
htdocs/workstation/class/workstation.class.php

@@ -184,8 +184,12 @@ class Workstation extends CommonObject
 
 		$this->fields['ref']['default'] = $this->getNextNumRef();
 
-		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
-		if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0;
+		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
+			$this->fields['rowid']['visible'] = 0;
+		}
+		if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
+			$this->fields['entity']['enabled'] = 0;
+		}
 
 		// Example to show how to set values of fields definition dynamically
 		/*if ($user->rights->workstation->workstation->read) {
@@ -194,23 +198,17 @@ class Workstation extends CommonObject
 		}*/
 
 		// Unset fields that are disabled
-		foreach ($this->fields as $key => $val)
-		{
-			if (isset($val['enabled']) && empty($val['enabled']))
-			{
+		foreach ($this->fields as $key => $val) {
+			if (isset($val['enabled']) && empty($val['enabled'])) {
 				unset($this->fields[$key]);
 			}
 		}
 
 		// Translate some data of arrayofkeyval
-		if (is_object($langs))
-		{
-			foreach ($this->fields as $key => $val)
-			{
-				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
-				{
-					foreach ($val['arrayofkeyval'] as $key2 => $val2)
-					{
+		if (is_object($langs)) {
+			foreach ($this->fields as $key => $val) {
+				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+					foreach ($val['arrayofkeyval'] as $key2 => $val2) {
 						$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
 					}
 				}
@@ -233,7 +231,9 @@ class Workstation extends CommonObject
 
 		// Usergroups
 		$groups = GETPOST('groups');
-		if (empty($groups)) $groups = $this->usergroups; // createFromClone
+		if (empty($groups)) {
+			$groups = $this->usergroups; // createFromClone
+		}
 		if (!empty($groups)) {
 			foreach ($groups as $id_group) {
 				$ws_usergroup = new WorkstationUserGroup($db);
@@ -246,7 +246,9 @@ class Workstation extends CommonObject
 
 		// Resources
 		$resources = GETPOST('resources');
-		if (empty($resources)) $resources = $this->resources; // createFromClone
+		if (empty($resources)) {
+			$resources = $this->resources; // createFromClone
+		}
 		if (!empty($resources)) {
 			foreach ($resources as $id_resource) {
 				$ws_resource = new WorkstationResource($db);
@@ -280,7 +282,9 @@ class Workstation extends CommonObject
 
 		// Load source object
 		$result = $object->fetch($fromid);
-		if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines();
+		if ($result > 0 && !empty($object->table_element_line)) {
+			$object->fetchLines();
+		}
 
 		// get lines so they will be clone
 		//foreach($this->lines as $line)
@@ -292,21 +296,28 @@ class Workstation extends CommonObject
 		unset($object->import_key);
 
 		// Clear fields
-		if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
-		if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
-		if (property_exists($object, 'status')) { $object->status = self::STATUS_DISABLED; }
-		if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); }
-		if (property_exists($object, 'date_modification')) { $object->date_modification = null; }
+		if (property_exists($object, 'ref')) {
+			$object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
+		}
+		if (property_exists($object, 'label')) {
+			$object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
+		}
+		if (property_exists($object, 'status')) {
+			$object->status = self::STATUS_DISABLED;
+		}
+		if (property_exists($object, 'date_creation')) {
+			$object->date_creation = dol_now();
+		}
+		if (property_exists($object, 'date_modification')) {
+			$object->date_modification = null;
+		}
 		// ...
 		// Clear extrafields that are unique
-		if (is_array($object->array_options) && count($object->array_options) > 0)
-		{
+		if (is_array($object->array_options) && count($object->array_options) > 0) {
 			$extrafields->fetch_name_optionals_label($this->table_element);
-			foreach ($object->array_options as $key => $option)
-			{
+			foreach ($object->array_options as $key => $option) {
 				$shortkey = preg_replace('/options_/', '', $key);
-				if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey]))
-				{
+				if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
 					//var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
 					unset($object->array_options[$key]);
 				}
@@ -322,22 +333,19 @@ class Workstation extends CommonObject
 			$this->errors = $object->errors;
 		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			// copy internal contacts
-			if ($this->copy_linked_contact($object, 'internal') < 0)
-			{
+			if ($this->copy_linked_contact($object, 'internal') < 0) {
 				$error++;
 			}
 		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			// copy external contacts if same company
-			if (property_exists($this, 'socid') && $this->socid == $object->socid)
-			{
-				if ($this->copy_linked_contact($object, 'external') < 0)
+			if (property_exists($this, 'socid') && $this->socid == $object->socid) {
+				if ($this->copy_linked_contact($object, 'external') < 0) {
 					$error++;
+				}
 			}
 		}
 
@@ -367,7 +375,9 @@ class Workstation extends CommonObject
 		$this->usergroups = WorkstationUserGroup::getAllGroupsOfWorkstation($this->id);
 		$this->resources = WorkstationResource::getAllResourcesOfWorkstation($this->id);
 
-		if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
+		if ($result > 0 && !empty($this->table_element_line)) {
+			$this->fetchLines();
+		}
 		return $result;
 	}
 
@@ -407,8 +417,11 @@ class Workstation extends CommonObject
 		$sql = 'SELECT ';
 		$sql .= $this->getFieldList();
 		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
-		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
-		else $sql .= ' WHERE 1 = 1';
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
+			$sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
+		} else {
+			$sql .= ' WHERE 1 = 1';
+		}
 		// Manage filter
 		$sqlwhere = array();
 		if (count($filter) > 0) {
@@ -441,8 +454,7 @@ class Workstation extends CommonObject
 		if ($resql) {
 			$num = $this->db->num_rows($resql);
 			$i = 0;
-			while ($i < ($limit ? min($limit, $num) : $num))
-			{
+			while ($i < ($limit ? min($limit, $num) : $num)) {
 				$obj = $this->db->fetch_object($resql);
 
 				$record = new self($this->db);
@@ -526,8 +538,7 @@ class Workstation extends CommonObject
 	 */
 	public function deleteLine(User $user, $idline, $notrigger = false)
 	{
-		if ($this->status < 0)
-		{
+		if ($this->status < 0) {
 			$this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
 			return -2;
 		}
@@ -552,8 +563,7 @@ class Workstation extends CommonObject
 		$error = 0;
 
 		// Protection
-		if ($this->status == self::STATUS_VALIDATED)
-		{
+		if ($this->status == self::STATUS_VALIDATED) {
 			dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
 			return 0;
 		}
@@ -571,8 +581,7 @@ class Workstation extends CommonObject
 		$this->db->begin();
 
 		// Define new ref
-		if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
-		{
+		if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
 			$num = $this->getNextNumRef();
 		} else {
 			$num = $this->ref;
@@ -584,57 +593,58 @@ class Workstation extends CommonObject
 			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
 			$sql .= " SET ref = '".$this->db->escape($num)."',";
 			$sql .= " status = ".self::STATUS_VALIDATED;
-			if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."'";
-			if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id;
+			if (!empty($this->fields['date_validation'])) {
+				$sql .= ", date_validation = '".$this->db->idate($now)."'";
+			}
+			if (!empty($this->fields['fk_user_valid'])) {
+				$sql .= ", fk_user_valid = ".$user->id;
+			}
 			$sql .= " WHERE rowid = ".$this->id;
 
 			dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
 			$resql = $this->db->query($sql);
-			if (!$resql)
-			{
+			if (!$resql) {
 				dol_print_error($this->db);
 				$this->error = $this->db->lasterror();
 				$error++;
 			}
 
-			if (!$error && !$notrigger)
-			{
+			if (!$error && !$notrigger) {
 				// Call trigger
 				$result = $this->call_trigger('WORKSTATION_VALIDATE', $user);
-				if ($result < 0) $error++;
+				if ($result < 0) {
+					$error++;
+				}
 				// End call triggers
 			}
 		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			$this->oldref = $this->ref;
 
 			// Rename directory if dir was a temporary ref
-			if (preg_match('/^[\(]?PROV/i', $this->ref))
-			{
+			if (preg_match('/^[\(]?PROV/i', $this->ref)) {
 				// Now we rename also files into index
 				$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'workstation/".$this->db->escape($this->newref)."'";
 				$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'workstation/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
 				$resql = $this->db->query($sql);
-				if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
+				if (!$resql) {
+					$error++; $this->error = $this->db->lasterror();
+				}
 
 				// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
 				$oldref = dol_sanitizeFileName($this->ref);
 				$newref = dol_sanitizeFileName($num);
 				$dirsource = $conf->workstation->dir_output.'/workstation/'.$oldref;
 				$dirdest = $conf->workstation->dir_output.'/workstation/'.$newref;
-				if (!$error && file_exists($dirsource))
-				{
+				if (!$error && file_exists($dirsource)) {
 					dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
 
-					if (@rename($dirsource, $dirdest))
-					{
+					if (@rename($dirsource, $dirdest)) {
 						dol_syslog("Rename ok");
 						// Rename docs starting with $oldref with $newref
 						$listoffiles = dol_dir_list($conf->workstation->dir_output.'/workstation/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
-						foreach ($listoffiles as $fileentry)
-						{
+						foreach ($listoffiles as $fileentry) {
 							$dirsource = $fileentry['name'];
 							$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
 							$dirsource = $fileentry['path'].'/'.$dirsource;
@@ -647,14 +657,12 @@ class Workstation extends CommonObject
 		}
 
 		// Set new ref and current status
-		if (!$error)
-		{
+		if (!$error) {
 			$this->ref = $num;
 			$this->status = self::STATUS_VALIDATED;
 		}
 
-		if (!$error)
-		{
+		if (!$error) {
 			$this->db->commit();
 			return 1;
 		} else {
@@ -677,8 +685,11 @@ class Workstation extends CommonObject
 
 		$this->status = $status;
 
-		if (empty($status)) return $this->setDisabled($user, $notrigger);
-		else return $this->setEnabled($user, $notrigger);
+		if (empty($status)) {
+			return $this->setDisabled($user, $notrigger);
+		} else {
+			return $this->setEnabled($user, $notrigger);
+		}
 	}
 
 
@@ -721,7 +732,9 @@ class Workstation extends CommonObject
 	{
 		global $conf, $langs, $hookmanager;
 
-		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
+		if (!empty($conf->dol_no_mouse_hover)) {
+			$notooltip = 1; // Force disable tooltips
+		}
 
 		$result = '';
 
@@ -734,25 +747,28 @@ class Workstation extends CommonObject
 
 		$url = dol_buildpath('/workstation/workstation_card.php', 1).'?id='.$this->id;
 
-		if ($option != 'nolink')
-		{
+		if ($option != 'nolink') {
 			// Add param to save lastsearch_values or not
 			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
-			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
-			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+				$add_save_lastsearch_values = 1;
+			}
+			if ($add_save_lastsearch_values) {
+				$url .= '&save_lastsearch_values=1';
+			}
 		}
 
 		$linkclose = '';
-		if (empty($notooltip))
-		{
-			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
-			{
+		if (empty($notooltip)) {
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
 				$label = $langs->trans("ShowWorkstation");
 				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
 			}
 			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
 			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
-		} else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+		} else {
+			$linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+		}
 
 		$linkstart = '<a href="'.$url.'"';
 		$linkstart .= $linkclose.'>';
@@ -761,7 +777,9 @@ class Workstation extends CommonObject
 		$result .= $linkstart;
 
 		if (empty($this->showphoto_on_popup)) {
-			if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'mrp'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+			if ($withpicto) {
+				$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'mrp'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+			}
 		} else {
 			if ($withpicto) {
 				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
@@ -787,7 +805,9 @@ class Workstation extends CommonObject
 			}
 		}
 
-		if ($withpicto != 2) $result .= $this->ref;
+		if ($withpicto != 2) {
+			$result .= $this->ref;
+		}
 
 		$result .= $linkend;
 		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
@@ -796,8 +816,11 @@ class Workstation extends CommonObject
 		$hookmanager->initHooks(array('workstationdao'));
 		$parameters = array('id'=>$this->id, 'getnomurl'=>$result);
 		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
-		if ($reshook > 0) $result = $hookmanager->resPrint;
-		else $result .= $hookmanager->resPrint;
+		if ($reshook > 0) {
+			$result = $hookmanager->resPrint;
+		} else {
+			$result .= $hookmanager->resPrint;
+		}
 
 		return $result;
 	}
@@ -824,8 +847,7 @@ class Workstation extends CommonObject
 	public function LibStatut($status, $mode = 0)
 	{
 		// phpcs:enable
-		if (empty($this->labelStatus) || empty($this->labelStatusShort))
-		{
+		if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
 			global $langs;
 			//$langs->load("workstation@workstation");
 			$this->labelStatus[self::STATUS_DISABLED] = $langs->trans('Disabled');
@@ -852,28 +874,23 @@ class Workstation extends CommonObject
 		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
 		$sql .= ' WHERE t.rowid = '.$id;
 		$result = $this->db->query($sql);
-		if ($result)
-		{
-			if ($this->db->num_rows($result))
-			{
+		if ($result) {
+			if ($this->db->num_rows($result)) {
 				$obj = $this->db->fetch_object($result);
 				$this->id = $obj->rowid;
-				if ($obj->fk_user_author)
-				{
+				if ($obj->fk_user_author) {
 					$cuser = new User($this->db);
 					$cuser->fetch($obj->fk_user_author);
 					$this->user_creation = $cuser;
 				}
 
-				if ($obj->fk_user_valid)
-				{
+				if ($obj->fk_user_valid) {
 					$vuser = new User($this->db);
 					$vuser->fetch($obj->fk_user_valid);
 					$this->user_validation = $vuser;
 				}
 
-				if ($obj->fk_user_cloture)
-				{
+				if ($obj->fk_user_cloture) {
 					$cluser = new User($this->db);
 					$cluser->fetch($obj->fk_user_cloture);
 					$this->user_cloture = $cluser;
@@ -913,8 +930,7 @@ class Workstation extends CommonObject
 		$objectline = new WorkstationLine($this->db);
 		$result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_workstation = '.$this->id));
 
-		if (is_numeric($result))
-		{
+		if (is_numeric($result)) {
 			$this->error = $this->error;
 			$this->errors = $this->errors;
 			return $result;
@@ -938,8 +954,7 @@ class Workstation extends CommonObject
 			$conf->global->WORKSTATION_WORKSTATION_ADDON = 'mod_workstation_standard';
 		}
 
-		if (!empty($conf->global->WORKSTATION_WORKSTATION_ADDON))
-		{
+		if (!empty($conf->global->WORKSTATION_WORKSTATION_ADDON)) {
 			$mybool = false;
 
 			$file = $conf->global->WORKSTATION_WORKSTATION_ADDON.".php";
@@ -947,16 +962,14 @@ class Workstation extends CommonObject
 
 			// Include file with class
 			$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
-			foreach ($dirmodels as $reldir)
-			{
+			foreach ($dirmodels as $reldir) {
 				$dir = dol_buildpath($reldir."core/modules/workstation/");
 
 				// Load file with numbering class (if found)
 				$mybool |= @include_once $dir.$file;
 			}
 
-			if ($mybool === false)
-			{
+			if ($mybool === false) {
 				dol_print_error('', "Failed to include file ".$file);
 				return '';
 			}
@@ -965,8 +978,7 @@ class Workstation extends CommonObject
 				$obj = new $classname();
 				$numref = $obj->getNextValue($this);
 
-				if ($numref != '' && $numref != '-1')
-				{
+				if ($numref != '' && $numref != '-1') {
 					return $numref;
 				} else {
 					$this->error = $obj->error;

+ 8 - 14
htdocs/workstation/class/workstationresource.class.php

@@ -65,23 +65,17 @@ class WorkstationResource extends CommonObject
 		$this->db = $db;
 
 		// Unset fields that are disabled
-		foreach ($this->fields as $key => $val)
-		{
-			if (isset($val['enabled']) && empty($val['enabled']))
-			{
+		foreach ($this->fields as $key => $val) {
+			if (isset($val['enabled']) && empty($val['enabled'])) {
 				unset($this->fields[$key]);
 			}
 		}
 
 		// Translate some data of arrayofkeyval
-		if (is_object($langs))
-		{
-			foreach ($this->fields as $key => $val)
-			{
-				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
-				{
-					foreach ($val['arrayofkeyval'] as $key2 => $val2)
-					{
+		if (is_object($langs)) {
+			foreach ($this->fields as $key => $val) {
+				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+					foreach ($val['arrayofkeyval'] as $key2 => $val2) {
 						$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
 					}
 				}
@@ -95,7 +89,7 @@ class WorkstationResource extends CommonObject
 	 * @param	int		$fk_workstation		Id of workstation we need to get linked resources
 	 * @return 	array						Array of record
 	 */
-	static public function getAllResourcesOfWorkstation($fk_workstation)
+	public static function getAllResourcesOfWorkstation($fk_workstation)
 	{
 		global $db;
 		$obj = new self($db);
@@ -108,7 +102,7 @@ class WorkstationResource extends CommonObject
 	 * @param	int		$fk_workstation		Id of workstation we need to remove linked resources
 	 * @return 	int							<0 if KO, 0 if nothing done, >0 if OK and something done
 	 */
-	static public function deleteAllResourcesOfWorkstation($fk_workstation)
+	public static function deleteAllResourcesOfWorkstation($fk_workstation)
 	{
 		global $db;
 		$obj = new self($db);

+ 8 - 14
htdocs/workstation/class/workstationusergroup.class.php

@@ -64,23 +64,17 @@ class WorkstationUserGroup extends CommonObject
 		$this->db = $db;
 
 		// Unset fields that are disabled
-		foreach ($this->fields as $key => $val)
-		{
-			if (isset($val['enabled']) && empty($val['enabled']))
-			{
+		foreach ($this->fields as $key => $val) {
+			if (isset($val['enabled']) && empty($val['enabled'])) {
 				unset($this->fields[$key]);
 			}
 		}
 
 		// Translate some data of arrayofkeyval
-		if (is_object($langs))
-		{
-			foreach ($this->fields as $key => $val)
-			{
-				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
-				{
-					foreach ($val['arrayofkeyval'] as $key2 => $val2)
-					{
+		if (is_object($langs)) {
+			foreach ($this->fields as $key => $val) {
+				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+					foreach ($val['arrayofkeyval'] as $key2 => $val2) {
 						$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
 					}
 				}
@@ -94,7 +88,7 @@ class WorkstationUserGroup extends CommonObject
 	 * @param	int		$fk_workstation		id of workstation we need to get linked usergroups
 	 * @return 	array						Array of record
 	 */
-	static public function getAllGroupsOfWorkstation($fk_workstation)
+	public static function getAllGroupsOfWorkstation($fk_workstation)
 	{
 		global $db;
 
@@ -108,7 +102,7 @@ class WorkstationUserGroup extends CommonObject
 	 * @param	int		$fk_workstation		Id of workstation we need to remove linked usergroups
 	 * @return 	int							<0 if KO, 0 if nothing done, >0 if OK and something done
 	 */
-	static public function deleteAllGroupsOfWorkstation($fk_workstation)
+	public static function deleteAllGroupsOfWorkstation($fk_workstation)
 	{
 		global $db;
 

+ 13 - 6
htdocs/workstation/lib/workstation_workstation.lib.php

@@ -41,14 +41,19 @@ function workstationPrepareHead($object)
 	$head[$h][2] = 'card';
 	$h++;
 
-	if (isset($object->fields['note_public']) || isset($object->fields['note_private']))
-	{
+	if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) {
 		$nbNote = 0;
-		if (!empty($object->note_private)) $nbNote++;
-		if (!empty($object->note_public)) $nbNote++;
+		if (!empty($object->note_private)) {
+			$nbNote++;
+		}
+		if (!empty($object->note_public)) {
+			$nbNote++;
+		}
 		$head[$h][0] = dol_buildpath('/workstation/workstation_note.php', 1).'?id='.$object->id;
 		$head[$h][1] = $langs->trans('Notes');
-		if ($nbNote > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : '');
+		if ($nbNote > 0) {
+			$head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '<span class="badge marginleftonlyshort">'.$nbNote.'</span>' : '');
+		}
 		$head[$h][2] = 'note';
 		$h++;
 	}
@@ -60,7 +65,9 @@ function workstationPrepareHead($object)
 	$nbLinks = Link::count($db, $object->element, $object->id);
 	$head[$h][0] = dol_buildpath("/workstation/workstation_document.php", 1).'?id='.$object->id;
 	$head[$h][1] = $langs->trans('Documents');
-	if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';
+	if (($nbFiles + $nbLinks) > 0) {
+		$head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';
+	}
 	$head[$h][2] = 'document';
 	$h++;
 

+ 41 - 63
htdocs/workstation/workstation_agenda.php

@@ -22,47 +22,13 @@
  *  \brief      Tab of events on Workstation
  */
 
-//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
-//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
-//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
-//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
-//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
-//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
-//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');				// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
-//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
-//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
-//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
-//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
-//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
-//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
-//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
-//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
-//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', 1);		// The main.inc.php does not make a redirect if not logged, instead show simple error message
-//if (! defined("FORCECSP"))                 define('FORCECSP', 'none');				// Disable all Content Security Policies
-//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
-//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
-
 // Load Dolibarr environment
-$res = 0;
-// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
-if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
-// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
-$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
-while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
-if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
-if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
-// Try main.inc.php using relative path
-if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
-if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
-if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
-if (!$res) die("Include of main fails");
-
+require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
-dol_include_once('/workstation/class/workstation.class.php');
-dol_include_once('/workstation/lib/workstation_workstation.lib.php');
+require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php';
+require_once DOL_DOCUMENT_ROOT.'/workstation/lib/workstation_workstation.lib.php';
 
 
 // Load translation files required by the page
@@ -77,7 +43,9 @@ $backtopage = GETPOST('backtopage', 'alpha');
 
 if (GETPOST('actioncode', 'array')) {
 	$actioncode = GETPOST('actioncode', 'array', 3);
-	if (!count($actioncode)) $actioncode = '0';
+	if (!count($actioncode)) {
+		$actioncode = '0';
+	}
 } else {
 	$actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT));
 }
@@ -87,12 +55,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortfield) $sortfield = 'a.datep,a.id';
-if (!$sortorder) $sortorder = 'DESC,DESC';
+if (!$sortfield) {
+	$sortfield = 'a.datep,a.id';
+}
+if (!$sortorder) {
+	$sortorder = 'DESC,DESC';
+}
 
 // Initialize technical objects
 $object = new Workstation($db);
@@ -104,7 +78,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Load object
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
-if ($id > 0 || !empty($ref)) $upload_dir = $conf->workstation->multidir_output[$object->entity]."/".$object->id;
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->workstation->multidir_output[$object->entity]."/".$object->id;
+}
 
 // Security check - Protection if external user
 //if ($user->socid > 0) accessforbidden();
@@ -120,20 +96,19 @@ $permissiontoadd = $user->rights->workstation->workstation->write; // Used by th
 
 $parameters = array('id'=>$id);
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	// Cancel
-	if (GETPOST('cancel', 'alpha') && !empty($backtopage))
-	{
+	if (GETPOST('cancel', 'alpha') && !empty($backtopage)) {
 		header("Location: ".$backtopage);
 		exit;
 	}
 
 	// Purge search criteria
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-	{
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
 		$actioncode = '';
 		$search_agenda_label = '';
 	}
@@ -147,14 +122,15 @@ if (empty($reshook))
 
 $form = new Form($db);
 
-if ($object->id > 0)
-{
+if ($object->id > 0) {
 	$title = $langs->trans("Agenda");
 	//if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title;
 	$help_url = '';
 	llxHeader('', $title, $help_url);
 
-	if (!empty($conf->notification->enabled)) $langs->load("mails");
+	if (!empty($conf->notification->enabled)) {
+		$langs->load("mails");
+	}
 	$head = workstationPrepareHead($object);
 
 
@@ -228,10 +204,11 @@ if ($object->id > 0)
 	$urlbacktopage = $_SERVER['PHP_SELF'].'?id='.$object->id;
 	$out .= '&backtopage='.urlencode($urlbacktopage);
 	$permok = $user->rights->agenda->myactions->create;
-	if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok)
-	{
+	if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) {
 		//$out.='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create';
-		if (get_class($objthirdparty) == 'Societe') $out .= '&socid='.urlencode($objthirdparty->id);
+		if (get_class($objthirdparty) == 'Societe') {
+			$out .= '&socid='.urlencode($objthirdparty->id);
+		}
 		$out .= (!empty($objcon->id) ? '&contactid='.urlencode($objcon->id) : '').'&percentage=-1';
 		//$out.=$langs->trans("AddAnAction").' ';
 		//$out.=img_picto($langs->trans("AddAnAction"),'filenew');
@@ -241,10 +218,8 @@ if ($object->id > 0)
 
 	print '<div class="tabsAction">';
 
-	if (!empty($conf->agenda->enabled))
-	{
-		if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create))
-		{
+	if (!empty($conf->agenda->enabled)) {
+		if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) {
 			print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'">'.$langs->trans("AddAction").'</a>';
 		} else {
 			print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>';
@@ -253,11 +228,14 @@ if ($object->id > 0)
 
 	print '</div>';
 
-	if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read)))
-	{
+	if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
 		$param = '&id='.$object->id.'&socid='.$socid;
-		if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-		if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+		if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+			$param .= '&contextpage='.urlencode($contextpage);
+		}
+		if ($limit > 0 && $limit != $conf->liste_limit) {
+			$param .= '&limit='.urlencode($limit);
+		}
 
 
 		//print load_fiche_titre($langs->trans("ActionsOnWorkstation"), '', '');

+ 63 - 77
htdocs/workstation/workstation_card.php

@@ -22,49 +22,15 @@
  *		\brief      Page to create/edit/view workstation
  */
 
-//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
-//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
-//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
-//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
-//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
-//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
-//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');				// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
-//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
-//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
-//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
-//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
-//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
-//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
-//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
-//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
-//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', 1);		// The main.inc.php does not make a redirect if not logged, instead show simple error message
-//if (! defined("FORCECSP"))                 define('FORCECSP', 'none');				// Disable all Content Security Policies
-//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
-//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
-
 // Load Dolibarr environment
-$res = 0;
-// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
-if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
-// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
-$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
-while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
-if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
-if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
-// Try main.inc.php using relative path
-if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
-if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
-if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
-if (!$res) die("Include of main fails");
-
+require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
 require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
 require_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php';
-dol_include_once('/workstation/class/workstation.class.php');
-dol_include_once('/workstation/lib/workstation_workstation.lib.php');
-dol_include_once('/workstation/class/workstationusergroup.class.php');
+require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php';
+require_once DOL_DOCUMENT_ROOT.'/workstation/lib/workstation_workstation.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstationusergroup.class.php';
 
 // Load translation files required by the page
 $langs->loadLangs(array("workstation@workstation", "other"));
@@ -96,12 +62,15 @@ $hookmanager->initHooks(array('workstationcard', 'globalcard')); // Note that co
 // Initialize array of search criterias
 $search_all = GETPOST("search_all", 'alpha');
 $search = array();
-foreach ($object->fields as $key => $val)
-{
-	if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha');
+foreach ($object->fields as $key => $val) {
+	if (GETPOST('search_'.$key, 'alpha')) {
+		$search[$key] = GETPOST('search_'.$key, 'alpha');
+	}
 }
 
-if (empty($action) && empty($id) && empty($ref)) $action = 'view';
+if (empty($action) && empty($id) && empty($ref)) {
+	$action = 'view';
+}
 
 // Load object
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
@@ -119,7 +88,9 @@ $upload_dir = $conf->workstation->multidir_output[isset($object->entity) ? $obje
 //$isdraft = (($object->statut == $object::STATUS_DRAFT) ? 1 : 0);
 //$result = restrictedArea($user, 'workstation', $object->id, '', '', 'fk_soc', 'rowid', $isdraft);
 
-if (!$permissiontoread) accessforbidden();
+if (!$permissiontoread) {
+	accessforbidden();
+}
 
 
 /*
@@ -128,18 +99,22 @@ if (!$permissiontoread) accessforbidden();
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	$error = 0;
 
 	$backurlforlist = dol_buildpath('/workstation/workstation_list.php', 1);
 
 	if (empty($backtopage) || ($cancel && empty($id))) {
 		if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
-			if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist;
-			else $backtopage = dol_buildpath('/workstation/workstation_card.php', 1).'?id='.($id > 0 ? $id : '__ID__');
+			if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
+				$backtopage = $backurlforlist;
+			} else {
+				$backtopage = dol_buildpath('/workstation/workstation_card.php', 1).'?id='.($id > 0 ? $id : '__ID__');
+			}
 		}
 	}
 
@@ -161,9 +136,13 @@ if (empty($reshook))
 	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
 
 	if ($action == 'confirm_enable' && $confirm == "yes" && $permissiontoadd) {
-		if (!empty($object->id)) $object->setStatus(1);
+		if (!empty($object->id)) {
+			$object->setStatus(1);
+		}
 	} elseif ($action == 'confirm_disable' && $confirm == "yes" && $permissiontoadd) {
-		if (!empty($object->id)) $object->setStatus(0);
+		if (!empty($object->id)) {
+			$object->setStatus(0);
+		}
 	}
 }
 
@@ -191,10 +170,10 @@ llxHeader('', $title, $help_url);
 		jQuery(document).ready(function() {
 			jQuery("#type").change(function() {
 				if($(this).val() === 'MACHINE') {
-                    $('#usergroups').hide();
-                    $('#nb_operators_required').parent('td').parent('tr').hide();
+					$('#usergroups').hide();
+					$('#nb_operators_required').parent('td').parent('tr').hide();
 					$('#wsresources').show();
-                } else if($(this).val() === 'HUMAN') {
+				} else if($(this).val() === 'HUMAN') {
 					$('#wsresources').hide();
 					$('#nb_operators_required').parent('td').parent('tr').show();
 					$('#usergroups').show();
@@ -212,15 +191,18 @@ llxHeader('', $title, $help_url);
 <?php
 
 // Part to create
-if ($action == 'create')
-{
+if ($action == 'create') {
 	print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("Workstation")), '', 'object_'.$object->picto);
 
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="add">';
-	if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
-	if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	if ($backtopage) {
+		print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
+	}
+	if ($backtopageforcancel) {
+		print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	}
 
 	print dol_get_fiche_head(array(), '');
 
@@ -268,16 +250,19 @@ if ($action == 'create')
 }
 
 // Part to edit record
-if (($id || $ref) && $action == 'edit')
-{
+if (($id || $ref) && $action == 'edit') {
 	print load_fiche_titre($langs->trans("Workstation"), '', 'object_'.$object->picto);
 
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="update">';
 	print '<input type="hidden" name="id" value="'.$object->id.'">';
-	if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
-	if ($backtopageforcancel) print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	if ($backtopage) {
+		print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
+	}
+	if ($backtopageforcancel) {
+		print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
+	}
 
 	print dol_get_fiche_head();
 
@@ -318,8 +303,7 @@ if (($id || $ref) && $action == 'edit')
 }
 
 // Part to show record
-if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create')))
-{
+if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
 	$res = $object->fetch_optionals();
 
 	$head = workstationPrepareHead($object);
@@ -339,19 +323,20 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	}
 
 	// Confirmation of action xxxx
-	if ($action == 'enable')
-	{
+	if ($action == 'enable') {
 		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('EnableAWorkstation'), $langs->trans("ConfirmEnableWorkstation", $object->ref), 'confirm_enable', $formquestion, 0, 1, 220);
-	} elseif ($action == 'disable')
-	{
+	} elseif ($action == 'disable') {
 		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DisableAWorkstation'), $langs->trans("ConfirmDisableWorkstation", $object->ref), 'confirm_disable', $formquestion, 0, 1, 220);
 	}
 
 	// Call Hook formConfirm
 	$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
 	$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-	if (empty($reshook)) $formconfirm .= $hookmanager->resPrint;
-	elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint;
+	if (empty($reshook)) {
+		$formconfirm .= $hookmanager->resPrint;
+	} elseif ($reshook > 0) {
+		$formconfirm = $hookmanager->resPrint;
+	}
 
 	// Print form confirm
 	print $formconfirm;
@@ -413,7 +398,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	//$keyforbreak='fieldkeytoswitchonsecondcolumn';	// We change column just before this field
 	//unset($object->fields['fk_project']);				// Hide field already shown in banner
 	//unset($object->fields['fk_soc']);					// Hide field already shown in banner
-	if ($object->type === 'MACHINE') $object->fields['nb_operators_required']['visible'] = 0;
+	if ($object->type === 'MACHINE') {
+		$object->fields['nb_operators_required']['visible'] = 0;
+	}
 	include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
 
 	// Groups
@@ -460,10 +447,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 		print '<div class="tabsAction">'."\n";
 		$parameters = array();
 		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-		if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+		if ($reshook < 0) {
+			setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+		}
 
-		if (empty($reshook))
-		{
+		if (empty($reshook)) {
 			// Modify
 			if ($permissiontoadd) {
 				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit">'.$langs->trans("Modify").'</a>'."\n";
@@ -477,8 +465,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 			}
 
 
-			if ($permissiontoadd)
-			{
+			if ($permissiontoadd) {
 				if ($object->status == $object::STATUS_ENABLED) {
 					print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=disable">'.$langs->trans("Disable").'</a>'."\n";
 				} else {
@@ -488,8 +475,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 
 
 			// Delete (need delete permission, or if draft, just need create/modify permission)
-			if ($permissiontodelete)
-			{
+			if ($permissiontodelete) {
 				print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n";
 			} else {
 				print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";

+ 17 - 45
htdocs/workstation/workstation_document.php

@@ -22,48 +22,14 @@
  *  \brief      Tab for documents linked to Workstation
  */
 
-//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
-//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
-//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
-//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
-//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
-//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
-//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');				// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
-//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
-//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
-//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
-//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
-//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
-//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
-//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
-//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
-//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', 1);		// The main.inc.php does not make a redirect if not logged, instead show simple error message
-//if (! defined("FORCECSP"))                 define('FORCECSP', 'none');				// Disable all Content Security Policies
-//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
-//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
-
 // Load Dolibarr environment
-$res = 0;
-// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
-if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
-// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
-$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
-while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
-if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
-if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
-// Try main.inc.php using relative path
-if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
-if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
-if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
-if (!$res) die("Include of main fails");
-
+require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
-dol_include_once('/workstation/class/workstation.class.php');
-dol_include_once('/workstation/lib/workstation_workstation.lib.php');
+require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php';
+require_once DOL_DOCUMENT_ROOT.'/workstation/lib/workstation_workstation.lib.php';
 
 // Load translation files required by the page
 $langs->loadLangs(array("workstation@workstation", "companies", "other", "mails"));
@@ -79,12 +45,18 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
+if (empty($page) || $page == -1) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1
 $offset = $liste_limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (!$sortorder) $sortorder = "ASC";
-if (!$sortfield) $sortfield = "name";
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
+if (!$sortfield) {
+	$sortfield = "name";
+}
 //if (! $sortfield) $sortfield="position_name";
 
 // Initialize technical objects
@@ -98,7 +70,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 // Load object
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
 
-if ($id > 0 || !empty($ref)) $upload_dir = $conf->workstation->multidir_output[$object->entity ? $object->entity : $conf->entity]."/workstation/".get_exdir(0, 0, 0, 1, $object);
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->workstation->multidir_output[$object->entity ? $object->entity : $conf->entity]."/workstation/".get_exdir(0, 0, 0, 1, $object);
+}
 
 // Security check - Protection if external user
 //if ($user->socid > 0) accessforbidden();
@@ -127,8 +101,7 @@ $help_url = '';
 //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
 llxHeader('', $title, $help_url);
 
-if ($object->id)
-{
+if ($object->id) {
 	/*
 	 * Show tabs
 	 */
@@ -140,8 +113,7 @@ if ($object->id)
 	// Build file list
 	$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
 	$totalsize = 0;
-	foreach ($filearray as $key => $file)
-	{
+	foreach ($filearray as $key => $file) {
 		$totalsize += $file['size'];
 	}
 

+ 203 - 161
htdocs/workstation/workstation_list.php

@@ -22,42 +22,8 @@
  *		\brief      List page for workstation
  */
 
-//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
-//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
-//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
-//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
-//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
-//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
-//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');				// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
-//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
-//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
-//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
-//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
-//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
-//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
-//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
-//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
-//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', 1);		// The main.inc.php does not make a redirect if not logged, instead show simple error message
-//if (! defined("FORCECSP"))                 define('FORCECSP', 'none');				// Disable all Content Security Policies
-//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
-//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
-
 // Load Dolibarr environment
-$res = 0;
-// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
-if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
-// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
-$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
-while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
-if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
-if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
-// Try main.inc.php using relative path
-if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
-if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
-if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
-if (!$res) die("Include of main fails");
-
+require '../main.inc.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';
@@ -66,11 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php';
 // load workstation libraries
 require_once __DIR__.'/class/workstation.class.php';
 
-// for other modules
-//dol_include_once('/othermodule/class/otherobject.class.php');
-
 // Load translation files required by the page
-$langs->loadLangs(array("workstation@workstation", "other"));
+$langs->loadLangs(array("workstation", "other"));
 
 $action     = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
 $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
@@ -89,7 +52,9 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'aZ09comma');
 $sortorder = GETPOST('sortorder', 'aZ09comma');
 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
-if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; }     // If $page is not defined, or '' or -1 or if we click on clear filters
+if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
+	$page = 0;
+}     // If $page is not defined, or '' or -1 or if we click on clear filters
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
@@ -107,17 +72,24 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
 
 // Default sort order (if not yet defined by previous GETPOST)
-if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
-if (!$sortorder) $sortorder = "ASC";
+if (!$sortfield) {
+	$sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
+}
+if (!$sortorder) {
+	$sortorder = "ASC";
+}
 
 // Initialize array of search criterias
 $search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml');
 $search = array();
 
-foreach ($object->fields as $key => $val)
-{
-	if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha');
-	if (in_array($key, array('type', 'status')) && GETPOST('search_'.$key, 'alpha') == -1) $search[$key] = '';
+foreach ($object->fields as $key => $val) {
+	if (GETPOST('search_'.$key, 'alpha') !== '') {
+		$search[$key] = GETPOST('search_'.$key, 'alpha');
+	}
+	if (in_array($key, array('type', 'status')) && GETPOST('search_'.$key, 'alpha') == -1) {
+		$search[$key] = '';
+	}
 }
 
 $groups = GETPOST('groups');
@@ -125,15 +97,15 @@ $resources = GETPOST('resources');
 
 // List of fields to search into when doing a "search in all"
 $fieldstosearchall = array();
-foreach ($object->fields as $key => $val)
-{
-	if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label'];
+foreach ($object->fields as $key => $val) {
+	if ($val['searchall']) {
+		$fieldstosearchall['t.'.$key] = $val['label'];
+	}
 }
 
 // Definition of array of fields for columns
 $arrayfields = array();
-foreach ($object->fields as $key => $val)
-{
+foreach ($object->fields as $key => $val) {
 	// If $val['visible']==0, then we never show the field
 	if (!empty($val['visible'])) {
 		$visible = dol_eval($val['visible'], 1);
@@ -174,10 +146,12 @@ $permissiontoadd = $user->rights->workstation->workstation->write;
 $permissiontodelete = $user->rights->workstation->workstation->delete;
 
 // Security check
-if (empty($conf->workstation->enabled)) accessforbidden('Module not enabled');
+if (empty($conf->workstation->enabled)) {
+	accessforbidden('Module not enabled');
+}
 $socid = 0;
-if ($user->socid > 0)	// Protection if external user
-{
+if ($user->socid > 0) {
+	// Protection if external user
 	//$socid = $user->socid;
 	accessforbidden();
 }
@@ -190,23 +164,26 @@ if ($user->socid > 0)	// Protection if external user
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
+if (GETPOST('cancel', 'alpha')) {
+	$action = 'list'; $massaction = '';
+}
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
+	$massaction = '';
+}
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+if ($reshook < 0) {
+	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+}
 
-if (empty($reshook))
-{
+if (empty($reshook)) {
 	// Selection of new fields
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
 	// Purge search criteria
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-	{
-		foreach ($object->fields as $key => $val)
-		{
+	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
+		foreach ($object->fields as $key => $val) {
 			$search[$key] = '';
 		}
 		$groups=$resources=array();
@@ -214,8 +191,7 @@ if (empty($reshook))
 		$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'))
-	{
+		|| 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
 	}
 
@@ -245,13 +221,14 @@ $title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Workstations"));
 // Build and execute select
 // --------------------------------------------------------------------
 $sql = 'SELECT ';
-foreach ($object->fields as $key => $val)
-{
+foreach ($object->fields as $key => $val) {
 	$sql .= 't.'.$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.', ' : '');
+	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();
@@ -259,34 +236,54 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje
 $sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
 $sql = preg_replace('/,\s*$/', '', $sql);
 $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
-if (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 (t.rowid = ef.fk_object)";
-if (!empty($groups)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'workstation_workstation_usergroup wug ON (wug.fk_workstation = t.rowid)';
-if (!empty($resources)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'workstation_workstation_resource wr ON (wr.fk_workstation = t.rowid)';
+if (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 (t.rowid = ef.fk_object)";
+}
+if (!empty($groups)) {
+	$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'workstation_workstation_usergroup wug ON (wug.fk_workstation = t.rowid)';
+}
+if (!empty($resources)) {
+	$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'workstation_workstation_resource wr ON (wr.fk_workstation = t.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;
-if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
-else $sql .= " WHERE 1 = 1";
-foreach ($search as $key => $val)
-{
-	if ($key == 'status' && $search[$key] == -1) continue;
+if ($object->ismultientitymanaged == 1) {
+	$sql .= " WHERE t.entity IN (".getEntity($object->element).")";
+} else {
+	$sql .= " WHERE 1 = 1";
+}
+foreach ($search as $key => $val) {
+	if ($key == 'status' && $search[$key] == -1) {
+		continue;
+	}
 	$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
 	if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
-		if ($search[$key] == '-1') $search[$key] = '';
+		if ($search[$key] == '-1') {
+			$search[$key] = '';
+		}
 		$mode_search = 2;
 	}
-	if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
+	if ($search[$key] != '') {
+		$sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
+	}
+}
+if ($search_all) {
+	$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
 }
-if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
 //$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
 // Add where from extra fields
 
 // usergroups
-if (!empty($groups)) $sql.= ' AND wug.fk_usergroup IN('.implode(',', $groups).')';
+if (!empty($groups)) {
+	$sql.= ' AND wug.fk_usergroup IN('.implode(',', $groups).')';
+}
 
 // resources
-if (!empty($resources)) $sql.= ' AND wr.fk_resource IN('.implode(',', $resources).')';
+if (!empty($resources)) {
+	$sql.= ' AND wr.fk_resource IN('.implode(',', $resources).')';
+}
 
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
 // Add where from hooks
@@ -315,26 +312,24 @@ $sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
-if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-{
+if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
 	$resql = $db->query($sql);
 	$nbtotalofrecords = $db->num_rows($resql);
-	if (($page * $limit) > $nbtotalofrecords)	// if total of record found is smaller than page * limit, goto and load page 0
-	{
+	if (($page * $limit) > $nbtotalofrecords) {	// if total of record found is smaller than page * limit, goto and load page 0
 		$page = 0;
 		$offset = 0;
 	}
 }
 // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
-if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit)))
-{
+if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) {
 	$num = $nbtotalofrecords;
 } else {
-	if ($limit) $sql .= $db->plimit($limit + 1, $offset);
+	if ($limit) {
+		$sql .= $db->plimit($limit + 1, $offset);
+	}
 
 	$resql = $db->query($sql);
-	if (!$resql)
-	{
+	if (!$resql) {
 		dol_print_error($db);
 		exit;
 	}
@@ -343,8 +338,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit
 }
 
 // Direct jump if only one record found
-if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page)
-{
+if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
 	$obj = $db->fetch_object($resql);
 	$id = $obj->rowid;
 	header("Location: ".dol_buildpath('/workstation/workstation_card.php', 1).'?id='.$id);
@@ -375,14 +369,24 @@ jQuery(document).ready(function() {
 $arrayofselected = is_array($toselect) ? $toselect : array();
 
 $param = '';
-if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
-if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
-foreach ($search as $key => $val)
-{
-	if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey);
-	else $param .= '&search_'.$key.'='.urlencode($search[$key]);
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
+	$param .= '&contextpage='.urlencode($contextpage);
+}
+if ($limit > 0 && $limit != $conf->liste_limit) {
+	$param .= '&limit='.urlencode($limit);
+}
+foreach ($search as $key => $val) {
+	if (is_array($search[$key]) && count($search[$key])) {
+		foreach ($search[$key] as $skey) {
+			$param .= '&search_'.$key.'[]='.urlencode($skey);
+		}
+	} else {
+		$param .= '&search_'.$key.'='.urlencode($search[$key]);
+	}
+}
+if ($optioncss != '') {
+	$param .= '&optioncss='.urlencode($optioncss);
 }
-if ($optioncss != '')     $param .= '&optioncss='.urlencode($optioncss);
 // Add $param from extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 // Add $param from hooks
@@ -397,12 +401,18 @@ $arrayofmassactions = array(
 	//'builddoc'=>$langs->trans("PDFMerge"),
 	//'presend'=>$langs->trans("SendByMail"),
 );
-if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
-if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
+if ($permissiontodelete) {
+	$arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
+}
+if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
+	$arrayofmassactions = array();
+}
 $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
 
 print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
-if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+if ($optioncss != '') {
+	print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+}
 print '<input type="hidden" name="token" value="'.newToken().'">';
 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
 print '<input type="hidden" name="action" value="list">';
@@ -421,9 +431,10 @@ $objecttmp = new Workstation($db);
 $trackid = 'xxxx'.$object->id;
 include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
 
-if ($search_all)
-{
-	foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
+if ($search_all) {
+	foreach ($fieldstosearchall as $key => $val) {
+		$fieldstosearchall[$key] = $langs->trans($val);
+	}
 	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>';
 }
 
@@ -434,11 +445,13 @@ $moreforfilter.= '</div>';*/
 
 $parameters = array();
 $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
-if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
-else $moreforfilter = $hookmanager->resPrint;
+if (empty($reshook)) {
+	$moreforfilter .= $hookmanager->resPrint;
+} else {
+	$moreforfilter = $hookmanager->resPrint;
+}
 
-if (!empty($moreforfilter))
-{
+if (!empty($moreforfilter)) {
 	print '<div class="liste_titre liste_titre_bydiv centpercent">';
 	print $moreforfilter;
 	print '</div>';
@@ -456,20 +469,26 @@ print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwit
 // --------------------------------------------------------------------
 
 print '<tr class="liste_titre">';
-foreach ($object->fields as $key => $val)
-{
+foreach ($object->fields as $key => $val) {
 	$cssforfield = (empty($val['css']) ? '' : $val['css']);
-	if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center';
-	elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
-	elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
-	elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right';
-	if (!empty($arrayfields['t.'.$key]['checked']))
-	{
+	if ($key == 'status') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+	} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'right';
+	}
+	if (!empty($arrayfields['t.'.$key]['checked'])) {
 		print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
-		if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
-		elseif (strpos($val['type'], 'integer:') === 0) {
+		if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
+			print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
+		} elseif (strpos($val['type'], 'integer:') === 0) {
 			print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth125', 1);
-		} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
+		} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) {
+			print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
+		}
 		print '</td>';
 	}
 }
@@ -506,15 +525,18 @@ print '</tr>'."\n";
 // Fields title label
 // --------------------------------------------------------------------
 print '<tr class="liste_titre">';
-foreach ($object->fields as $key => $val)
-{
+foreach ($object->fields as $key => $val) {
 	$cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
-	if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center';
-	elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
-	elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
-	elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right';
-	if (!empty($arrayfields['t.'.$key]['checked']))
-	{
+	if ($key == 'status') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'center';
+	} elseif (in_array($val['type'], array('timestamp'))) {
+		$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+	} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') {
+		$cssforfield .= ($cssforfield ? ' ' : '').'right';
+	}
+	if (!empty($arrayfields['t.'.$key]['checked'])) {
 		print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
 	}
 }
@@ -542,11 +564,11 @@ print '</tr>'."\n";
 
 // Detect if we need a fetch on each output line
 $needToFetchEachLine = 0;
-if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0)
-{
-	foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val)
-	{
-		if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object
+if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
+	foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
+		if (preg_match('/\$object/', $val)) {
+			$needToFetchEachLine++; // There is at least one compute field that use $object
+		}
 	}
 }
 
@@ -555,10 +577,11 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co
 // --------------------------------------------------------------------
 $i = 0;
 $totalarray = array();
-while ($i < ($limit ? min($num, $limit) : $num))
-{
+while ($i < ($limit ? min($num, $limit) : $num)) {
 	$obj = $db->fetch_object($resql);
-	if (empty($obj)) break; // Should not happen
+	if (empty($obj)) {
+		break; // Should not happen
+	}
 
 	// Store properties in $object
 	$object->setVarsFromFetchObj($obj);
@@ -567,28 +590,40 @@ while ($i < ($limit ? min($num, $limit) : $num))
 
 	// Show here line of result
 	print '<tr class="oddeven">';
-	foreach ($object->fields as $key => $val)
-	{
+	foreach ($object->fields as $key => $val) {
 		$cssforfield = (empty($val['css']) ? '' : $val['css']);
-		if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
-		elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center';
+		if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
+			$cssforfield .= ($cssforfield ? ' ' : '').'center';
+		} elseif ($key == 'status') {
+			$cssforfield .= ($cssforfield ? ' ' : '').'center';
+		}
 
-		if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
-		elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+		if (in_array($val['type'], array('timestamp'))) {
+			$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+		} elseif ($key == 'ref') {
+			$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
+		}
 
-		if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) $cssforfield .= ($cssforfield ? ' ' : '').'right';
+		if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) {
+			$cssforfield .= ($cssforfield ? ' ' : '').'right';
+		}
 		//if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100';
 
-		if (!empty($arrayfields['t.'.$key]['checked']))
-		{
+		if (!empty($arrayfields['t.'.$key]['checked'])) {
 			print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
-			if ($key == 'status') print $object->getLibStatut(5);
-			else print $object->showOutputField($val, $key, $object->$key, '');
+			if ($key == 'status') {
+				print $object->getLibStatut(5);
+			} else {
+				print $object->showOutputField($val, $key, $object->$key, '');
+			}
 			print '</td>';
-			if (!$i) $totalarray['nbfield']++;
-			if (!empty($val['isameasure']))
-			{
-				if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
+			if (!$i) {
+				$totalarray['nbfield']++;
+			}
+			if (!empty($val['isameasure'])) {
+				if (!$i) {
+					$totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
+				}
 				$totalarray['val']['t.'.$key] += $object->$key;
 			}
 		}
@@ -626,14 +661,17 @@ while ($i < ($limit ? min($num, $limit) : $num))
 	print $hookmanager->resPrint;
 	// Action column
 	print '<td class="nowrap center">';
-	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
-	{
+	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;
+		if (in_array($object->id, $arrayofselected)) {
+			$selected = 1;
+		}
 		print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->id.'"'.($selected ? ' checked="checked"' : '').'>';
 	}
 	print '</td>';
-	if (!$i) $totalarray['nbfield']++;
+	if (!$i) {
+		$totalarray['nbfield']++;
+	}
 
 	print '</tr>'."\n";
 
@@ -644,10 +682,13 @@ while ($i < ($limit ? min($num, $limit) : $num))
 include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
 
 // If no record found
-if ($num == 0)
-{
+if ($num == 0) {
 	$colspan = 1;
-	foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; }
+	foreach ($arrayfields as $key => $val) {
+		if (!empty($val['checked'])) {
+			$colspan++;
+		}
+	}
 	print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
 }
 
@@ -663,10 +704,11 @@ print '</div>'."\n";
 
 print '</form>'."\n";
 
-if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords))
-{
+if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
 	$hidegeneratedfilelistifempty = 1;
-	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0;
+	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
+		$hidegeneratedfilelistifempty = 0;
+	}
 
 	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
 	$formfile = new FormFile($db);

+ 9 - 41
htdocs/workstation/workstation_note.php

@@ -22,47 +22,14 @@
  *  \brief      Tab for notes on Workstation
  */
 
-//if (! defined('NOREQUIREDB'))              define('NOREQUIREDB', '1');				// Do not create database handler $db
-//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');				// Do not load object $user
-//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');				// Do not load object $mysoc
-//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');				// Do not load object $langs
-//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');		// Do not check injection attack on GET parameters
-//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');		// Do not check injection attack on POST parameters
-//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');				// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
-//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');				// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
-//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');				// Do not check style html tag into posted data
-//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');				// If there is no need to load and show top and left menu
-//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');				// If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       	  	// Do not load ajax.lib.php library
-//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');					// If this page is public (can be called outside logged session). This include the NOIPCHECK too.
-//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');					// Do not check IP defined into conf $dolibarr_main_restrict_ip
-//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');					// Force lang to a particular value
-//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');	// Force authentication handler
-//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', 1);		// The main.inc.php does not make a redirect if not logged, instead show simple error message
-//if (! defined("FORCECSP"))                 define('FORCECSP', 'none');				// Disable all Content Security Policies
-//if (! defined('CSRFCHECK_WITH_TOKEN'))     define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
-//if (! defined('NOBROWSERNOTIF'))     		 define('NOBROWSERNOTIF', '1');				// Disable browser notification
-
 // Load Dolibarr environment
-$res = 0;
-// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined)
-if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
-// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME
-$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1;
-while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; }
-if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
-if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
-// Try main.inc.php using relative path
-if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php";
-if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
-if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
-if (!$res) die("Include of main fails");
-
-dol_include_once('/workstation/class/workstation.class.php');
-dol_include_once('/workstation/lib/workstation_workstation.lib.php');
+require '../main.inc.php';
+
+require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php';
+require_once DOL_DOCUMENT_ROOT.'/workstation/lib/workstation_workstation.lib.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("workstation@workstation", "companies"));
+$langs->loadLangs(array("workstation", "companies"));
 
 // Get parameters
 $id = GETPOST('id', 'int');
@@ -86,7 +53,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Load object
 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
-if ($id > 0 || !empty($ref)) $upload_dir = $conf->workstation->multidir_output[$object->entity]."/".$object->id;
+if ($id > 0 || !empty($ref)) {
+	$upload_dir = $conf->workstation->multidir_output[$object->entity]."/".$object->id;
+}
 
 $permissionnote = $user->rights->workstation->workstation->write; // Used by the include of actions_setnotes.inc.php
 $permissiontoadd = $user->rights->workstation->workstation->write; // Used by the include of actions_addupdatedelete.inc.php
@@ -110,8 +79,7 @@ $form = new Form($db);
 $help_url = '';
 llxHeader('', $langs->trans('Workstation'), $help_url);
 
-if ($id > 0 || !empty($ref))
-{
+if ($id > 0 || !empty($ref)) {
 	$object->fetch_thirdparty();
 
 	$head = workstationPrepareHead($object);