Browse Source

Scrutinizer Auto-Fixes

This commit consists of patches automatically generated for this project on https://scrutinizer-ci.com
Scrutinizer Auto-Fixer 5 years ago
parent
commit
ac40dd8bbe
100 changed files with 7330 additions and 7330 deletions
  1. 82 82
      htdocs/accountancy/admin/account.php
  2. 44 44
      htdocs/accountancy/admin/index.php
  3. 47 47
      htdocs/accountancy/bookkeeping/balance.php
  4. 90 90
      htdocs/accountancy/bookkeeping/card.php
  5. 46 46
      htdocs/accountancy/class/accountingjournal.class.php
  6. 279 279
      htdocs/accountancy/class/bookkeeping.class.php
  7. 33 33
      htdocs/accountancy/index.php
  8. 35 35
      htdocs/adherents/admin/website.php
  9. 215 215
      htdocs/adherents/subscription.php
  10. 178 178
      htdocs/adherents/subscription/list.php
  11. 48 48
      htdocs/adherents/type.php
  12. 35 35
      htdocs/admin/agenda_xcal.php
  13. 80 80
      htdocs/admin/boxes.php
  14. 18 18
      htdocs/admin/dav.php
  15. 39 39
      htdocs/admin/security.php
  16. 23 23
      htdocs/admin/ticket_public.php
  17. 23 23
      htdocs/api/admin/explorer.php
  18. 15 15
      htdocs/api/admin/index.php
  19. 23 23
      htdocs/asset/document.php
  20. 16 16
      htdocs/asset/note.php
  21. 61 61
      htdocs/asset/type.php
  22. 32 32
      htdocs/bom/bom_agenda.php
  23. 22 22
      htdocs/bom/bom_document.php
  24. 16 16
      htdocs/bom/bom_note.php
  25. 4 4
      htdocs/bom/tpl/objectline_create.tpl.php
  26. 5 5
      htdocs/bom/tpl/objectline_edit.tpl.php
  27. 7 7
      htdocs/bom/tpl/objectline_view.tpl.php
  28. 18 18
      htdocs/categories/card.php
  29. 19 19
      htdocs/categories/edit.php
  30. 83 83
      htdocs/categories/viewcat.php
  31. 212 212
      htdocs/comm/action/card.php
  32. 239 239
      htdocs/comm/card.php
  33. 222 222
      htdocs/comm/mailing/card.php
  34. 139 139
      htdocs/comm/mailing/class/advtargetemailing.class.php
  35. 47 47
      htdocs/comm/mailing/list.php
  36. 6 6
      htdocs/comm/propal/contact.php
  37. 5 5
      htdocs/comm/propal/document.php
  38. 4 4
      htdocs/comm/propal/note.php
  39. 7 7
      htdocs/commande/contact.php
  40. 9 9
      htdocs/commande/document.php
  41. 2 2
      htdocs/commande/info.php
  42. 2 2
      htdocs/commande/note.php
  43. 106 106
      htdocs/commande/orderstoinvoice.php
  44. 105 105
      htdocs/compta/bank/card.php
  45. 89 89
      htdocs/compta/bank/list.php
  46. 63 63
      htdocs/compta/bank/various_payment/card.php
  47. 10 10
      htdocs/compta/bank/various_payment/document.php
  48. 115 115
      htdocs/compta/cashcontrol/cashcontrol_card.php
  49. 8 8
      htdocs/compta/facture/contact.php
  50. 34 34
      htdocs/compta/facture/document.php
  51. 26 26
      htdocs/compta/facture/info.php
  52. 73 73
      htdocs/compta/facture/invoicetemplate_list.php
  53. 25 25
      htdocs/compta/facture/note.php
  54. 65 65
      htdocs/compta/facture/prelevement.php
  55. 127 127
      htdocs/compta/paiement.php
  56. 49 49
      htdocs/contact/agenda.php
  57. 151 151
      htdocs/contact/card.php
  58. 28 28
      htdocs/contrat/agenda.php
  59. 193 193
      htdocs/contrat/card.php
  60. 32 32
      htdocs/contrat/contact.php
  61. 40 40
      htdocs/contrat/document.php
  62. 29 29
      htdocs/contrat/note.php
  63. 170 170
      htdocs/contrat/services_list.php
  64. 5 5
      htdocs/core/boxes/box_accountancy_last_manual_entries.php
  65. 4 4
      htdocs/core/boxes/box_accountancy_suspense_account.php
  66. 19 19
      htdocs/core/boxes/box_bookmarks.php
  67. 74 74
      htdocs/core/class/commondocgenerator.class.php
  68. 247 247
      htdocs/core/class/commonobject.class.php
  69. 73 73
      htdocs/core/class/cunits.class.php
  70. 117 117
      htdocs/core/class/discount.class.php
  71. 151 151
      htdocs/core/class/dolgraph.class.php
  72. 308 308
      htdocs/core/class/extrafields.class.php
  73. 70 70
      htdocs/core/class/html.formactions.class.php
  74. 162 162
      htdocs/core/class/html.formcompany.class.php
  75. 121 121
      htdocs/core/class/html.formticket.class.php
  76. 62 62
      htdocs/core/class/infobox.class.php
  77. 246 246
      htdocs/core/lib/company.lib.php
  78. 9 9
      htdocs/core/lib/cron.lib.php
  79. 31 31
      htdocs/core/lib/payments.lib.php
  80. 36 36
      htdocs/core/lib/product.lib.php
  81. 117 117
      htdocs/core/lib/project.lib.php
  82. 16 16
      htdocs/core/lib/signature.lib.php
  83. 188 188
      htdocs/core/lib/ticket.lib.php
  84. 189 189
      htdocs/core/modules/import/import_csv.modules.php
  85. 175 175
      htdocs/core/modules/import/import_xlsx.modules.php
  86. 112 112
      htdocs/core/modules/modProduct.class.php
  87. 112 112
      htdocs/core/modules/modService.class.php
  88. 254 254
      htdocs/core/modules/project/doc/doc_generic_project_odt.modules.php
  89. 14 14
      htdocs/core/modules/security/generate/modGeneratePassPerso.class.php
  90. 169 169
      htdocs/core/modules/stock/doc/pdf_stdmovement.modules.php
  91. 3 3
      htdocs/core/tpl/extrafields_add.tpl.php
  92. 11 11
      htdocs/core/tpl/extrafields_view.tpl.php
  93. 13 13
      htdocs/core/tpl/objectline_create.tpl.php
  94. 29 29
      htdocs/core/tpl/objectline_edit.tpl.php
  95. 9 9
      htdocs/core/tpl/objectline_view.tpl.php
  96. 17 17
      htdocs/core/tpl/onlinepaymentlinks.tpl.php
  97. 82 82
      htdocs/don/card.php
  98. 11 11
      htdocs/don/document.php
  99. 3 3
      htdocs/don/info.php
  100. 3 3
      htdocs/don/note.php

+ 82 - 82
htdocs/accountancy/admin/account.php

@@ -24,12 +24,12 @@
  */
 
 require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("compta","bills","admin","accountancy","salaries"));
+$langs->loadLangs(array("compta", "bills", "admin", "accountancy", "salaries"));
 
 $mesg = '';
 $action = GETPOST('action', 'aZ09');
@@ -37,7 +37,7 @@ $cancel = GETPOST('cancel', 'alpha');
 $id = GETPOST('id', 'int');
 $rowid = GETPOST('rowid', 'int');
 $massaction = GETPOST('massaction', 'aZ09');
-$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'accountingaccountlist';   // To manage different context of search
+$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'accountingaccountlist'; // To manage different context of search
 
 $search_account = GETPOST('search_account', 'alpha');
 $search_label = GETPOST('search_label', 'alpha');
@@ -58,10 +58,10 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $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(
+$arrayfields = array(
     'aa.account_number'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1),
     'aa.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1),
 	'aa.account_parent'=>array('label'=>$langs->trans("Accountparent"), 'checked'=>1),
@@ -78,27 +78,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
+$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))
 {
-    if (! empty($cancel)) $action = '';
+    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_accountparent = "";
     	$search_pcgtype = "";
     	$search_pcgsubtype = "";
-		$search_array_options=array();
+		$search_array_options = array();
     }
 
     if (GETPOST('change_chart', 'alpha') && (GETPOST('valid_change_chart', 'int') || empty($conf->use_javascript_ajax)))
@@ -108,8 +108,8 @@ if (empty($reshook))
         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;
+			$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)
 			{
@@ -132,7 +132,7 @@ if (empty($reshook))
 				{
 					$offsetforchartofaccount += $reg[1];
 				}
-				$offsetforchartofaccount+=($conf->entity  * 100000000);
+				$offsetforchartofaccount += ($conf->entity * 100000000);
 
 				$result = run_sql($sqlfile, 1, $conf->entity, 1, '', 'default', 32768, 0, $offsetforchartofaccount);
 
@@ -146,7 +146,7 @@ if (empty($reshook))
 				}
 			}
 
-            if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) {
+            if (!dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) {
                 $error++;
             }
         } else {
@@ -179,12 +179,12 @@ if (empty($reshook))
  * View
  */
 
-$form=new Form($db);
+$form = new Form($db);
 
 llxHeader('', $langs->trans("ListAccounts"));
 
 if ($action == 'delete') {
-	$formconfirm = $html->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $id, $langs->trans('DeleteAccount'), $langs->trans('ConfirmDeleteAccount'), 'confirm_delete', '', 0, 1);
+	$formconfirm = $html->formconfirm($_SERVER["PHP_SELF"].'?id='.$id, $langs->trans('DeleteAccount'), $langs->trans('ConfirmDeleteAccount'), 'confirm_delete', '', 0, 1);
 	print $formconfirm;
 }
 
@@ -192,11 +192,11 @@ $pcgver = $conf->global->CHARTOFACCOUNTS;
 
 $sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.pcg_subtype, aa.account_number, aa.account_parent , aa.label, aa.active, ";
 $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;
-$sql .= " WHERE asy.rowid = " . $pcgver;
+$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;
+$sql .= " WHERE asy.rowid = ".$pcgver;
 //print $sql;
 if (strlen(trim($search_account)))			$sql .= natural_search("aa.account_number", $search_account);
 if (strlen(trim($search_label)))			$sql .= natural_search("aa.label", $search_label);
@@ -220,24 +220,24 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
 
 $sql .= $db->plimit($limit + 1, $offset);
 
-dol_syslog('accountancy/admin/account.php:: $sql=' . $sql);
+dol_syslog('accountancy/admin/account.php:: $sql='.$sql);
 $resql = $db->query($sql);
 
 if ($resql)
 {
 	$num = $db->num_rows($resql);
 
-    $param='';
-	if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
-	if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
-	if ($search_account) $param.= '&search_account='.urlencode($search_account);
-	if ($search_label) $param.= '&search_label='.urlencode($search_label);
-	if ($search_accountparent) $param.= '&search_accountparent='.urlencode($search_accountparent);
-	if ($search_pcgtype) $param.= '&search_pcgtype='.urlencode($search_pcgtype);
-	if ($search_pcgsubtype) $param.= '&search_pcgsubtype='.urlencode($search_pcgsubtype);
-    if ($optioncss != '') $param.='&optioncss='.$optioncss;
-
-    if (! empty($conf->use_javascript_ajax))
+    $param = '';
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
+	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
+	if ($search_account) $param .= '&search_account='.urlencode($search_account);
+	if ($search_label) $param .= '&search_label='.urlencode($search_label);
+	if ($search_accountparent) $param .= '&search_accountparent='.urlencode($search_accountparent);
+	if ($search_pcgtype) $param .= '&search_pcgtype='.urlencode($search_pcgtype);
+	if ($search_pcgsubtype) $param .= '&search_pcgsubtype='.urlencode($search_pcgsubtype);
+    if ($optioncss != '') $param .= '&optioncss='.$optioncss;
+
+    if (!empty($conf->use_javascript_ajax))
     {
 	    print '<!-- Add javascript to update a flag when we select "Change plan" -->
 			<script type="text/javascript">
@@ -256,7 +256,7 @@ if ($resql)
 	    	</script>';
     }
 
-	print '<form method="POST" id="searchFormList" action="' . $_SERVER["PHP_SELF"] . '">';
+	print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
 	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
 	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
@@ -266,17 +266,17 @@ if ($resql)
 	print '<input type="hidden" name="page" value="'.$page.'">';
 	print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
 
-    $newcardbutton.= dolGetButtonTitle($langs->trans("New"), $langs->trans("Addanaccount"), 'fa fa-plus-circle', './card.php?action=create');
+    $newcardbutton .= dolGetButtonTitle($langs->trans("New"), $langs->trans("Addanaccount"), 'fa fa-plus-circle', './card.php?action=create');
 
 
     print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit);
 
 	// Box to select active chart of account
-    print $langs->trans("Selectchartofaccounts") . " : ";
+    print $langs->trans("Selectchartofaccounts")." : ";
     print '<select class="flat" name="chartofaccounts" id="chartofaccounts">';
     $sql = "SELECT a.rowid, a.pcg_version, a.label, a.active, c.code as country_code";
-    $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_system as a";
-    $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as c ON a.fk_country = c.rowid AND c.active = 1";
+    $sql .= " FROM ".MAIN_DB_PREFIX."accounting_system as a";
+    $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON a.fk_country = c.rowid AND c.active = 1";
     $sql .= " WHERE a.active = 1";
     dol_syslog('accountancy/admin/account.php $sql='.$sql);
     print $sql;
@@ -287,9 +287,9 @@ if ($resql)
         while ($i < $numbis) {
             $obj = $db->fetch_object($resqlchart);
 
-            print '<option value="' . $obj->rowid . '"';
+            print '<option value="'.$obj->rowid.'"';
             print ($pcgver == $obj->rowid) ? ' selected' : '';
-            print '>' . $obj->pcg_version . ' - ' . $obj->label . ' - (' . $obj->country_code . ')</option>';
+            print '>'.$obj->pcg_version.' - '.$obj->label.' - ('.$obj->country_code.')</option>';
 
             $i++;
         }
@@ -303,43 +303,43 @@ if ($resql)
     print '<br>';
 	print '<br>';
 
-	$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
-    $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage);	// This also change content of $arrayfields
+	$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
+    $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
 
     $moreforfilter = '';
     $massactionbutton = '';
 
     print '<div class="div-table-responsive">';
-    print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
+    print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
 
 	// 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" size="10" name="search_account" value="' . $search_account . '"></td>';
-	if (! empty($arrayfields['aa.label']['checked']))			print '<td class="liste_titre"><input type="text" class="flat" size="20" name="search_label" value="' . $search_label . '"></td>';
-	if (! empty($arrayfields['aa.account_parent']['checked']))	print '<td class="liste_titre"><input type="text" class="flat" size="10" name="search_accountparent" value="' . $search_accountparent . '"></td>';
-	if (! empty($arrayfields['aa.pcg_type']['checked']))		print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_pcgtype" value="' . $search_pcgtype . '"></td>';
-	if (! empty($arrayfields['aa.pcg_subtype']['checked']))		print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_pcgsubtype" value="' . $search_pcgsubtype . '"></td>';
-	if (! empty($arrayfields['aa.active']['checked']))			print '<td class="liste_titre">&nbsp;</td>';
+	if (!empty($arrayfields['aa.account_number']['checked']))	print '<td class="liste_titre"><input type="text" class="flat" size="10" name="search_account" value="'.$search_account.'"></td>';
+	if (!empty($arrayfields['aa.label']['checked']))			print '<td class="liste_titre"><input type="text" class="flat" size="20" name="search_label" value="'.$search_label.'"></td>';
+	if (!empty($arrayfields['aa.account_parent']['checked']))	print '<td class="liste_titre"><input type="text" class="flat" size="10" name="search_accountparent" value="'.$search_accountparent.'"></td>';
+	if (!empty($arrayfields['aa.pcg_type']['checked']))		print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_pcgtype" value="'.$search_pcgtype.'"></td>';
+	if (!empty($arrayfields['aa.pcg_subtype']['checked']))		print '<td class="liste_titre"><input type="text" class="flat" size="6" name="search_pcgsubtype" value="'.$search_pcgsubtype.'"></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);
+	$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
 	print $searchpicto;
 	print '</td>';
 	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.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 (! empty($arrayfields['aa.pcg_subtype']['checked']))		print_liste_field_titre($arrayfields['aa.pcg_subtype']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_subtype', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_subtype']['help']);
-	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.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 (!empty($arrayfields['aa.pcg_subtype']['checked']))		print_liste_field_titre($arrayfields['aa.pcg_subtype']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_subtype', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_subtype']['help']);
+	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";
 
 	$accountstatic = new AccountingAccount($db);
 	$accountparent = new AccountingAccount($db);
 
-	$i=0;
+	$i = 0;
 	while ($i < min($num, $limit))
 	{
 		$obj = $db->fetch_object($resql);
@@ -351,27 +351,27 @@ 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);
 			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 parent
-		if (! empty($arrayfields['aa.account_parent']['checked']))
+		if (!empty($arrayfields['aa.account_parent']['checked']))
 		{
-			if (! empty($obj->account_parent))
+			if (!empty($obj->account_parent))
 			{
 				$accountparent->id = $obj->rowid2;
 				$accountparent->label = $obj->label2;
@@ -380,63 +380,63 @@ if ($resql)
 				print "<td>";
 				print $accountparent->getNomUrl(1);
 				print "</td>\n";
-				if (! $i) $totalarray['nbfield']++;
+				if (!$i) $totalarray['nbfield']++;
 			}
 			else
 			{
 				print '<td>&nbsp;</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']++;
 		}
 
 		// Chart of accounts subtype
-		if (! empty($arrayfields['aa.pcg_subtype']['checked']))
+		if (!empty($arrayfields['aa.pcg_subtype']['checked']))
 		{
 			print "<td>";
 			print $obj->pcg_subtype;
 			print "</td>\n";
-			if (! $i) $totalarray['nbfield']++;
+			if (!$i) $totalarray['nbfield']++;
 		}
 
 		// Activated or not
-		if (! empty($arrayfields['aa.active']['checked']))
+		if (!empty($arrayfields['aa.active']['checked']))
 		{
 			print '<td>';
 			if (empty($obj->active)) {
-				print '<a class="reposition" href="' . $_SERVER["PHP_SELF"] . '?id=' . $obj->rowid . '&action=enable">';
+				print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$obj->rowid.'&action=enable">';
 				print img_picto($langs->trans("Disabled"), 'switch_off');
 				print '</a>';
 			} else {
-				print '<a class="reposition" href="' . $_SERVER["PHP_SELF"] . '?id=' . $obj->rowid . '&action=disable">';
+				print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$obj->rowid.'&action=disable">';
 				print img_picto($langs->trans("Activated"), 'switch_on');
 				print '</a>';
 			}
 			print '</td>';
-			if (! $i) $totalarray['nbfield']++;
+			if (!$i) $totalarray['nbfield']++;
 		}
 
 		// Action
 		print '<td class="center">';
 		if ($user->rights->accounting->chartofaccount) {
-			print '<a href="./card.php?action=update&id=' . $obj->rowid . '&backtopage='.urlencode($_SERVER["PHP_SELF"].'?chartofaccounts='.$object->id).'">';
+			print '<a href="./card.php?action=update&id='.$obj->rowid.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?chartofaccounts='.$object->id).'">';
 			print img_edit();
 			print '</a>';
 			print '&nbsp;';
-			print '<a href="./card.php?action=delete&id=' . $obj->rowid . '&backtopage='.urlencode($_SERVER["PHP_SELF"].'?chartofaccounts='.$object->id). '">';
+			print '<a href="./card.php?action=delete&id='.$obj->rowid.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?chartofaccounts='.$object->id).'">';
 			print img_delete();
 			print '</a>';
 		}
-		print '</td>' . "\n";
-		if (! $i) $totalarray['nbfield']++;
+		print '</td>'."\n";
+		if (!$i) $totalarray['nbfield']++;
 
 		print "</tr>\n";
 		$i++;

+ 44 - 44
htdocs/accountancy/admin/index.php

@@ -29,11 +29,11 @@
  */
 
 require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("compta","bills","admin","accountancy"));
+$langs->loadLangs(array("compta", "bills", "admin", "accountancy"));
 
 // Security access
 if (empty($user->rights->accounting->chartofaccount))
@@ -44,9 +44,9 @@ if (empty($user->rights->accounting->chartofaccount))
 $action = GETPOST('action', 'aZ09');
 
 // Parameters ACCOUNTING_* and others
-$list = array (
+$list = array(
     'ACCOUNTING_LENGTH_GACCOUNT',
-    'ACCOUNTING_LENGTH_AACCOUNT' ,
+    'ACCOUNTING_LENGTH_AACCOUNT',
 //    'ACCOUNTING_LENGTH_DESCRIPTION',         // adjust size displayed for lines description for dol_trunc
 //    'ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT', // adjust size displayed for select account description for dol_trunc
 );
@@ -62,13 +62,13 @@ $accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' :
 if ($action == 'update') {
 	$error = 0;
 
-	if (! $error)
+	if (!$error)
 	{
 	    foreach ($list as $constname)
 	    {
 	        $constvalue = GETPOST($constname, 'alpha');
 
-	        if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) {
+	        if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) {
 	            $error++;
 	        }
 	    }
@@ -77,7 +77,7 @@ if ($action == 'update') {
 	    }
 	}
 
-    if (! $error) {
+    if (!$error) {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
 }
@@ -146,9 +146,9 @@ if ($action == 'setenabledraftexport') {
 if ($action == 'setenablesubsidiarylist') {
     $setenablesubsidiarylist = GETPOST('value', 'int');
     $res = dolibarr_set_const($db, "ACCOUNTANCY_COMBO_FOR_AUX", $setenablesubsidiarylist, 'yesno', 0, '', $conf->entity);
-    if (! $res > 0)
-        $error ++;
-    if (! $error) {
+    if (!$res > 0)
+        $error++;
+    if (!$error) {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     } else {
         setEventMessages($langs->trans("Error"), null, 'mesgs');
@@ -159,15 +159,15 @@ if ($action == 'setenablesubsidiarylist') {
  * View
  */
 
-$title= $langs->trans('ConfigAccountingExpert');
+$title = $langs->trans('ConfigAccountingExpert');
 llxHeader('', $title);
 
-$linkback='';
+$linkback = '';
 //$linkback = '<a href="' . DOL_URL_ROOT . '/admin/modules.php?restore_lastsearch_values=1">' . $langs->trans("BackToModuleList") . '</a>';
 print load_fiche_titre($langs->trans('ConfigAccountingExpert'), $linkback, 'accountancy');
 
-print '<form action="' . $_SERVER["PHP_SELF"] . '" method="post">';
-print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
+print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
+print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 print '<input type="hidden" name="action" value="update">';
 
 // Default mode for calculating turnover (parameter ACCOUNTING_MODE)
@@ -204,85 +204,85 @@ print '<br>';
 
 print '<table class="noborder centpercent">';
 print '<tr class="liste_titre">';
-print '<td colspan="2">' . $langs->trans('OtherOptions') . '</td>';
+print '<td colspan="2">'.$langs->trans('OtherOptions').'</td>';
 print "</tr>\n";
 
-if (! empty($user->admin))
+if (!empty($user->admin))
 {
     // TO DO Mutualize code for yes/no constants
     print '<tr class="oddeven">';
-	print '<td>' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_TODO") . '</td>';
-    if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO)) {
-        print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setlistsorttodo&value=0">';
+	print '<td>'.$langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_TODO").'</td>';
+    if (!empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO)) {
+        print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setlistsorttodo&value=0">';
         print img_picto($langs->trans("Activated"), 'switch_on');
         print '</a></td>';
     } else {
-        print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setlistsorttodo&value=1">';
+        print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setlistsorttodo&value=1">';
         print img_picto($langs->trans("Disabled"), 'switch_off');
         print '</a></td>';
     }
     print '</tr>';
 
     print '<tr>';
-    print '<td>' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_DONE") . '</td>';
-    if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE)) {
-        print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setlistsortdone&value=0">';
+    print '<td>'.$langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_DONE").'</td>';
+    if (!empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE)) {
+        print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setlistsortdone&value=0">';
         print img_picto($langs->trans("Activated"), 'switch_on');
         print '</a></td>';
     } else {
-        print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setlistsortdone&value=1">';
+        print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setlistsortdone&value=1">';
         print img_picto($langs->trans("Disabled"), 'switch_off');
         print '</a></td>';
     }
     print '</tr>';
 
 	print '<tr>';
-	print '<td>' . $langs->trans("ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL") . '</td>';
-	if (! empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) {
-		print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setenabledraftexport&value=0">';
+	print '<td>'.$langs->trans("ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL").'</td>';
+	if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) {
+		print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setenabledraftexport&value=0">';
 		print img_picto($langs->trans("Activated"), 'switch_on');
 		print '</a></td>';
 	} else {
-		print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setenabledraftexport&value=1">';
+		print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setenabledraftexport&value=1">';
 		print img_picto($langs->trans("Disabled"), 'switch_off');
 		print '</a></td>';
 	}
 	print '</tr>';
 
 	print '<tr>';
-	print '<td>' . $langs->trans("BANK_DISABLE_DIRECT_INPUT") . '</td>';
-	if (! empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) {
-		print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setdisabledirectinput&value=0">';
+	print '<td>'.$langs->trans("BANK_DISABLE_DIRECT_INPUT").'</td>';
+	if (!empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) {
+		print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setdisabledirectinput&value=0">';
 		print img_picto($langs->trans("Activated"), 'switch_on');
 		print '</a></td>';
 	} else {
-		print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setdisabledirectinput&value=1">';
+		print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setdisabledirectinput&value=1">';
 		print img_picto($langs->trans("Disabled"), 'switch_off');
 		print '</a></td>';
 	}
 	print '</tr>';
 
     print '<tr>';
-    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'] . '?action=setenablesubsidiarylist&value=0">';
+    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'].'?action=setenablesubsidiarylist&value=0">';
         print img_picto($langs->trans("Activated"), 'switch_on');
         print '</a></td>';
     } else {
-        print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setenablesubsidiarylist&value=1">';
+        print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setenablesubsidiarylist&value=1">';
         print img_picto($langs->trans("Disabled"), 'switch_off');
         print '</a></td>';
     }
     print '</tr>';
 
     print '<tr>';
-    print '<td>' . $langs->trans("ACCOUNTING_MANAGE_ZERO") . '</td>';
-    if (! empty($conf->global->ACCOUNTING_MANAGE_ZERO)) {
-        print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setmanagezero&value=0">';
+    print '<td>'.$langs->trans("ACCOUNTING_MANAGE_ZERO").'</td>';
+    if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO)) {
+        print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setmanagezero&value=0">';
         print img_picto($langs->trans("Activated"), 'switch_on');
         print '</a></td>';
     } else {
-        print '<td class="right"><a class="reposition" href="' . $_SERVER['PHP_SELF'] . '?action=setmanagezero&value=1">';
+        print '<td class="right"><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setmanagezero&value=1">';
         print img_picto($langs->trans("Disabled"), 'switch_off');
         print '</a></td>';
     }
@@ -295,14 +295,14 @@ foreach ($list as $key)
 {
     print '<tr class="oddeven value">';
 
-    if (! empty($conf->global->ACCOUNTING_MANAGE_ZERO) && ($key == 'ACCOUNTING_LENGTH_GACCOUNT' || $key == 'ACCOUNTING_LENGTH_AACCOUNT')) continue;
+    if (!empty($conf->global->ACCOUNTING_MANAGE_ZERO) && ($key == 'ACCOUNTING_LENGTH_GACCOUNT' || $key == 'ACCOUNTING_LENGTH_AACCOUNT')) continue;
 
     // Param
     $label = $langs->trans($key);
     print '<td>'.$label.'</td>';
     // Value
     print '<td class="right">';
-    print '<input type="text" class="maxwidth100" id="' . $key . '" name="' . $key . '" value="' . $conf->global->$key . '">';
+    print '<input type="text" class="maxwidth100" id="'.$key.'" name="'.$key.'" value="'.$conf->global->$key.'">';
     print '</td>';
 
     print '</tr>';
@@ -311,7 +311,7 @@ foreach ($list as $key)
 
 print '</table>';
 
-print '<div class="center"><input type="submit" class="button" value="' . $langs->trans('Modify') . '" name="button"></div>';
+print '<div class="center"><input type="submit" class="button" value="'.$langs->trans('Modify').'" name="button"></div>';
 
 print '<br>';
 print '<br>';

+ 47 - 47
htdocs/accountancy/bookkeeping/balance.php

@@ -28,12 +28,12 @@
 require '../../main.inc.php';
 
 // Class
-require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
-require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountancyexport.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
+require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancyexport.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
 
 // Load translation files required by the page
 $langs->loadLangs(array("accountancy"));
@@ -45,7 +45,7 @@ $action = GETPOST('action', 'aZ09');
 if (GETPOST("exportcsv", 'alpha')) $action = 'export_csv';
 
 // Load variable for pagination
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'alpha');
 $sortorder = GETPOST('sortorder', 'alpha');
 $page = GETPOST('page', 'int');
@@ -75,18 +75,18 @@ $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);
+	$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);
 	$res = $db->query($sql);
 	if ($res->num_rows > 0) {
 		$fiscalYear = $db->fetch_object($res);
 		$search_date_start = strtotime($fiscalYear->date_start);
 		$search_date_end = strtotime($fiscalYear->date_end);
 	} else {
-		$month_start= ($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1);
+		$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
 		$year_start = dol_print_date(dol_now(), '%Y');
 		$year_end = $year_start + 1;
 		$month_end = $month_start - 1;
@@ -105,26 +105,26 @@ 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);
+$param = '';
+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)) {
+$filter = array();
+if (!empty($search_date_start)) {
 	$filter['t.doc_date>='] = $search_date_start;
-	$param .= '&amp;date_startmonth=' . GETPOST('date_startmonth', 'int') . '&amp;date_startday=' . GETPOST('date_startday', 'int') . '&amp;date_startyear=' . GETPOST('date_startyear', 'int');
+	$param .= '&amp;date_startmonth='.GETPOST('date_startmonth', 'int').'&amp;date_startday='.GETPOST('date_startday', 'int').'&amp;date_startyear='.GETPOST('date_startyear', 'int');
 }
-if (! empty($search_date_end)) {
+if (!empty($search_date_end)) {
 	$filter['t.doc_date<='] = $search_date_end;
-	$param .= '&amp;date_endmonth=' . GETPOST('date_endmonth', 'int') . '&amp;date_endday=' . GETPOST('date_endday', 'int') . '&amp;date_endyear=' . GETPOST('date_endyear', 'int');
+	$param .= '&amp;date_endmonth='.GETPOST('date_endmonth', 'int').'&amp;date_endday='.GETPOST('date_endday', 'int').'&amp;date_endyear='.GETPOST('date_endyear', 'int');
 }
-if (! empty($search_accountancy_code_start)) {
+if (!empty($search_accountancy_code_start)) {
 	$filter['t.numero_compte>='] = $search_accountancy_code_start;
-	$param .= '&amp;search_accountancy_code_start=' . $search_accountancy_code_start;
+	$param .= '&amp;search_accountancy_code_start='.$search_accountancy_code_start;
 }
-if (! empty($search_accountancy_code_end)) {
+if (!empty($search_accountancy_code_end)) {
 	$filter['t.numero_compte<='] = $search_accountancy_code_end;
-	$param .= '&amp;search_accountancy_code_end=' . $search_accountancy_code_end;
+	$param .= '&amp;search_accountancy_code_end='.$search_accountancy_code_end;
 }
 
 /*
@@ -151,7 +151,7 @@ if ($action == 'export_csv')
 
 	$filename = 'balance';
 	$type_export = 'balance';
-	include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php';
+	include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
 
 	$result = $object->fetchAllBalance($sortorder, $sortfield, $limit, 0, $filter);
 	if ($result < 0) {
@@ -160,11 +160,11 @@ if ($action == 'export_csv')
 
 	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;
-		print price($line->credit) . $sep;
-		print price($line->debit - $line->credit) . $sep;
+		print length_accountg($line->numero_compte).$sep;
+		print $object->get_compte_desc($line->numero_compte).$sep;
+		print price($line->debit).$sep;
+		print price($line->credit).$sep;
+		print price($line->debit - $line->credit).$sep;
 		print "\n";
 	}
 
@@ -203,20 +203,20 @@ if ($action != 'export_csv')
 	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
 	print '<input type="hidden" name="page" value="'.$page.'">';
 
-	$button = '<input type="submit" name="exportcsv" class="butAction" value="' . $langs->trans("Export") . ' ('.$conf->global->ACCOUNTING_EXPORT_FORMAT.')" />';
+	$button = '<input type="submit" name="exportcsv" class="butAction" value="'.$langs->trans("Export").' ('.$conf->global->ACCOUNTING_EXPORT_FORMAT.')" />';
 
 	print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $button, $result, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit);
 
 	$moreforfilter = '';
 
 	$moreforfilter .= '<div class="divsearchfield">';
-	$moreforfilter .= $langs->trans('DateStart') . ': ';
-	$moreforfilter .= $form->selectDate($search_date_start?$search_date_start:-1, 'date_start', 0, 0, 1, '', 1, 0);
-	$moreforfilter .= $langs->trans('DateEnd') . ': ';
-	$moreforfilter .= $form->selectDate($search_date_end?$search_date_end:-1, 'date_end', 0, 0, 1, '', 1, 0);
+	$moreforfilter .= $langs->trans('DateStart').': ';
+	$moreforfilter .= $form->selectDate($search_date_start ? $search_date_start : -1, 'date_start', 0, 0, 1, '', 1, 0);
+	$moreforfilter .= $langs->trans('DateEnd').': ';
+	$moreforfilter .= $form->selectDate($search_date_end ? $search_date_end : -1, 'date_end', 0, 0, 1, '', 1, 0);
 	$moreforfilter .= '</div>';
 
-	if (! empty($moreforfilter)) {
+	if (!empty($moreforfilter)) {
 		print '<div class="liste_titre liste_titre_bydiv centpercent">';
 		print $moreforfilter;
 		$parameters = array();
@@ -225,7 +225,7 @@ if ($action != 'export_csv')
 		print '</div>';
 	}
 
-	print '<table class="liste ' . ($moreforfilter ? "listwithfilterbefore" : "") . '">';
+	print '<table class="liste '.($moreforfilter ? "listwithfilterbefore" : "").'">';
 
 	print '<tr class="liste_titre_filter">';
 	print '<td class="liste_titre" colspan="5">';
@@ -236,7 +236,7 @@ if ($action != 'export_csv')
 	print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array(), 1, 1, '');
 	print '</td>';
 	print '<td class="liste_titre right">';
-	$searchpicto=$form->showFilterAndCheckAddButtons(0);
+	$searchpicto = $form->showFilterAndCheckAddButtons(0);
 	print $searchpicto;
 	print '</td>';
 
@@ -265,7 +265,7 @@ if ($action != 'export_csv')
 		$description = $object->get_compte_desc($line->numero_compte); // Search description of the account
 		$root_account_description = $object->get_compte_racine($line->numero_compte);
 		if (empty($description)) {
-			$link = '<a href="'.DOL_URL_ROOT.'/accountancy/admin/card.php?action=create&accountingaccount=' . length_accountg($line->numero_compte) . '">' . img_edit_add() . '</a>';
+			$link = '<a href="'.DOL_URL_ROOT.'/accountancy/admin/card.php?action=create&accountingaccount='.length_accountg($line->numero_compte).'">'.img_edit_add().'</a>';
 		}
 		print '<tr class="oddeven">';
 
@@ -291,12 +291,12 @@ if ($action != 'export_csv')
 
 		// $object->get_compte_racine($line->numero_compte);
 
-		print '<td>' . length_accountg($line->numero_compte) . '</td>';
-		print '<td>' . $description . '</td>';
-		print '<td class="nowraponall right">' . price($line->debit) . '</td>';
-		print '<td class="nowraponall right">' . price($line->credit) . '</td>';
-		print '<td class="nowraponall right">' . price($line->debit - $line->credit) . '</td>';
-		print '<td class="center">' . $link;
+		print '<td>'.length_accountg($line->numero_compte).'</td>';
+		print '<td>'.$description.'</td>';
+		print '<td class="nowraponall right">'.price($line->debit).'</td>';
+		print '<td class="nowraponall right">'.price($line->credit).'</td>';
+		print '<td class="nowraponall right">'.price($line->debit - $line->credit).'</td>';
+		print '<td class="center">'.$link;
 		print '</td>';
 		print "</tr>\n";
 
@@ -305,11 +305,11 @@ if ($action != 'export_csv')
 		$sous_total_credit += $line->credit;
 	}
 
-	print '<tr class="liste_total"><td class="right" colspan="2">' . $langs->trans("SubTotal") . ':</td><td class="nowrap right">' . price($sous_total_debit) . '</td><td class="nowrap right">' . price($sous_total_credit) . '</td><td class="nowrap right">' . price(price2num($sous_total_debit - $sous_total_credit)) . '</td>';
+	print '<tr class="liste_total"><td class="right" colspan="2">'.$langs->trans("SubTotal").':</td><td class="nowrap right">'.price($sous_total_debit).'</td><td class="nowrap right">'.price($sous_total_credit).'</td><td class="nowrap right">'.price(price2num($sous_total_debit - $sous_total_credit)).'</td>';
 	print "<td>&nbsp;</td>\n";
 	print '</tr>';
 
-	print '<tr class="liste_total"><td class="right" colspan="2">' . $langs->trans("AccountBalance") . ':</td><td class="nowrap right">' . price($total_debit) . '</td><td class="nowrap right">' . price($total_credit) . '</td><td class="nowrap right">' . price(price2num($total_debit - $total_credit)) . '</td>';
+	print '<tr class="liste_total"><td class="right" colspan="2">'.$langs->trans("AccountBalance").':</td><td class="nowrap right">'.price($total_debit).'</td><td class="nowrap right">'.price($total_credit).'</td><td class="nowrap right">'.price(price2num($total_debit - $total_credit)).'</td>';
 	print "<td>&nbsp;</td>\n";
 	print '</tr>';
 

+ 90 - 90
htdocs/accountancy/bookkeeping/card.php

@@ -26,23 +26,23 @@
  */
 
 require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php';
-require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
-require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
-require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
-require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
+require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
+require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
+require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
 
 // Load translation files required by the page
 $langs->loadLangs(array("accountancy", "bills", "compta"));
 
 $action = GETPOST('action', 'aZ09');
-$optioncss  = GETPOST('optioncss', 'aZ');												// Option for the css output (always '' except when 'print')
+$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
 
-$id = GETPOST('id', 'int');					// id of record
-$mode = GETPOST('mode', 'aZ09');		 		// '' or 'tmp'
-$piece_num = GETPOST("piece_num", 'int');	// id of transaction (several lines share the same transaction id)
+$id = GETPOST('id', 'int'); // id of record
+$mode = GETPOST('mode', 'aZ09'); // '' or 'tmp'
+$piece_num = GETPOST("piece_num", 'int'); // id of transaction (several lines share the same transaction id)
 
 // Security check
 if ($user->socid > 0) {
@@ -66,14 +66,14 @@ $subledger_account = GETPOST('subledger_account', 'alphanohtml');
 if ($subledger_account == - 1) {
 	$subledger_account = null;
 }
-$label_operation= GETPOST('label_operation', 'alphanohtml');
+$label_operation = GETPOST('label_operation', 'alphanohtml');
 $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);
 
@@ -88,16 +88,16 @@ if ($action == "confirm_update") {
 	if ((floatval($debit) != 0.0) && (floatval($credit) != 0.0)) {
 		$error++;
 		setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors');
-		$action='update';
+		$action = 'update';
 	}
 	if (empty($accountingaccount_number) || $accountingaccount_number == '-1')
 	{
 		$error++;
 		setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("AccountAccountingShort")), null, 'errors');
-		$action='update';
+		$action = 'update';
 	}
 
-	if (! $error)
+	if (!$error)
 	{
 		$object = new BookKeeping($db);
 
@@ -109,7 +109,7 @@ if ($action == "confirm_update") {
 			$object->numero_compte = $accountingaccount_number;
 			$object->subledger_account = $subledger_account;
 			$object->label_compte = $accountingaccount_label;
-			$object->label_operation= $label_operation;
+			$object->label_operation = $label_operation;
 			$object->debit = $debit;
 			$object->credit = $credit;
 
@@ -147,22 +147,22 @@ elseif ($action == "add") {
 	{
 		$error++;
 		setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors');
-		$action='';
+		$action = '';
 	}
 	if (empty($accountingaccount_number) || $accountingaccount_number == '-1')
 	{
 		$error++;
 		setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("AccountAccountingShort")), null, 'errors');
-		$action='';
+		$action = '';
 	}
 
-	if (! $error) {
+	if (!$error) {
 		$object = new BookKeeping($db);
 
 		$object->numero_compte = $accountingaccount_number;
 		$object->subledger_account = $subledger_account;
 		$object->label_compte = $accountingaccount_label;
-		$object->label_operation= $label_operation;
+		$object->label_operation = $label_operation;
 		$object->debit = $debit;
 		$object->credit = $credit;
 		$object->doc_date = GETPOST('doc_date', 'alpha');
@@ -223,18 +223,18 @@ elseif ($action == "confirm_create") {
 
 	$object = new BookKeeping($db);
 
-	if (! $journal_code || $journal_code == '-1') {
+	if (!$journal_code || $journal_code == '-1') {
 		setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Journal")), null, 'errors');
-		$action='create';
+		$action = 'create';
 		$error++;
 	}
-	if (! GETPOST('next_num_mvt', 'alpha'))
+	if (!GETPOST('next_num_mvt', 'alpha'))
 	{
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumPiece")), null, 'errors');
 		$error++;
 	}
 
-	if (! $error)
+	if (!$error)
 	{
 		$object->label_compte = '';
 		$object->debit = 0;
@@ -258,7 +258,7 @@ elseif ($action == "confirm_create") {
 				setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
 			}
 			$action = 'update';
-			$id=$object->id;
+			$id = $object->id;
 			$piece_num = $object->piece_num;
 		}
 	}
@@ -329,7 +329,7 @@ llxHeader('', $langs->trans("CreateMvts"));
 
 // Confirmation to delete the command
 if ($action == 'delete') {
-	$formconfirm = $html->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $id.'&mode='. $mode, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'confirm_delete', '', 0, 1);
+	$formconfirm = $html->formconfirm($_SERVER["PHP_SELF"].'?id='.$id.'&mode='.$mode, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'confirm_delete', '', 0, 1);
 	print $formconfirm;
 }
 
@@ -345,12 +345,12 @@ if ($action == 'create')
 		dol_print_error('', 'Failed to get next piece number');
 	}
 
-	print '<form action="' . $_SERVER["PHP_SELF"] . '" name="create_mvt" method="POST">';
+	print '<form action="'.$_SERVER["PHP_SELF"].'" name="create_mvt" method="POST">';
 	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
 	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-	print '<input type="hidden" name="action" value="confirm_create">' . "\n";
-	print '<input type="hidden" name="next_num_mvt" value="' . $next_num_mvt . '">' . "\n";
-	print '<input type="hidden" name="mode" value="_tmp">' . "\n";
+	print '<input type="hidden" name="action" value="confirm_create">'."\n";
+	print '<input type="hidden" name="next_num_mvt" value="'.$next_num_mvt.'">'."\n";
+	print '<input type="hidden" name="mode" value="_tmp">'."\n";
 
 	dol_fiche_head();
 
@@ -362,19 +362,19 @@ if ($action == 'create')
 	print '</tr>';*/
 
 	print '<tr>';
-	print '<td class="titlefieldcreate fieldrequired">' . $langs->trans("Docdate") . '</td>';
+	print '<td class="titlefieldcreate fieldrequired">'.$langs->trans("Docdate").'</td>';
 	print '<td>';
 	print $html->selectDate('', 'doc_date', '', '', '', "create_mvt", 1, 1);
 	print '</td>';
 	print '</tr>';
 
 	print '<tr>';
-	print '<td class="fieldrequired">' . $langs->trans("Codejournal") . '</td>';
-	print '<td>' . $formaccounting->select_journal($journal_code, 'code_journal', 0, 0, 1, 1) . '</td>';
+	print '<td class="fieldrequired">'.$langs->trans("Codejournal").'</td>';
+	print '<td>'.$formaccounting->select_journal($journal_code, 'code_journal', 0, 0, 1, 1).'</td>';
 	print '</tr>';
 
 	print '<tr>';
-	print '<td>' . $langs->trans("Piece") . '</td>';
+	print '<td>'.$langs->trans("Piece").'</td>';
 	print '<td><input type="text" class="minwidth200" name="doc_ref" value="'.GETPOST('doc_ref', 'alpha').'"></td>';
 	print '</tr>';
 
@@ -390,9 +390,9 @@ if ($action == 'create')
 	dol_fiche_end();
 
 	print '<div class="center">';
-	print '<input type="submit" class="button" value="' . $langs->trans("Create") . '">';
+	print '<input type="submit" class="button" value="'.$langs->trans("Create").'">';
 	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-	print '<input type="button" value="' . $langs->trans("Cancel") . '" class="button" onclick="history.go(-1)" />';
+	print '<input type="button" value="'.$langs->trans("Cancel").'" class="button" onclick="history.go(-1)" />';
 	print '</div>';
 
 	print '</form>';
@@ -403,15 +403,15 @@ 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>';
+		$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);
 
-		$head=array();
-		$h=0;
-		$head[$h][0] = $_SERVER['PHP_SELF'].'?piece_num='.$object->piece_num.($mode?'&mode='.$mode:'');
+		$head = array();
+		$h = 0;
+		$head[$h][0] = $_SERVER['PHP_SELF'].'?piece_num='.$object->piece_num.($mode ? '&mode='.$mode : '');
 		$head[$h][1] = $langs->trans("Transaction");
 		$head[$h][2] = 'transaction';
 		$h++;
@@ -428,8 +428,8 @@ if ($action == 'create')
 
 		// Account movement
 		print '<tr>';
-		print '<td class="titlefield">' . $langs->trans("NumMvts") . '</td>';
-		print '<td>' . $object->piece_num . '</td>';
+		print '<td class="titlefield">'.$langs->trans("NumMvts").'</td>';
+		print '<td>'.$object->piece_num.'</td>';
 		print '</tr>';
 
 		// Date
@@ -438,17 +438,17 @@ if ($action == 'create')
 		print $langs->trans('Docdate');
 		print '</td>';
 		if ($action != 'editdate')
-		print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate&amp;piece_num='. $object->piece_num .'&amp;mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('SetDate'), 1).'</a></td>';
+		print '<td class="right"><a class="editfielda" 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">';
+			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.'">';
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 			print '<input type="hidden" name="action" value="setdate">';
 			print '<input type="hidden" name="mode" value="'.$mode.'">';
 			print $form->selectDate($object->doc_date ? $object->doc_date : - 1, 'doc_date', '', '', '', "setdate");
-			print '<input type="submit" class="button" value="' . $langs->trans('Modify') . '">';
+			print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
 			print '</form>';
 		} else {
 			print $object->doc_date ? dol_print_date($object->doc_date, 'day') : '&nbsp;';
@@ -462,20 +462,20 @@ if ($action == 'create')
 		print $langs->trans('Codejournal');
 		print '</td>';
 		if ($action != 'editjournal')
-		print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editjournal&amp;piece_num='.$object->piece_num.'&amp;mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'</a></td>';
+		print '<td class="right"><a class="editfielda" 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">';
+			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.'">';
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 			print '<input type="hidden" name="action" value="setjournal">';
 			print '<input type="hidden" name="mode" value="'.$mode.'">';
 			print $formaccounting->select_journal($object->code_journal, 'code_journal', 0, 0, array(), 1, 1);
-			print '<input type="submit" class="button" value="' . $langs->trans('Modify') . '">';
+			print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
 			print '</form>';
 		} else {
-			print $object->code_journal ;
+			print $object->code_journal;
 		}
 		print '</td>';
 		print '</tr>';
@@ -486,20 +486,20 @@ if ($action == 'create')
 		print $langs->trans('Piece');
 		print '</td>';
 		if ($action != 'editdocref')
-		print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdocref&amp;piece_num='.$object->piece_num.'&amp;mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('Edit'), 1).'</a></td>';
+		print '<td class="right"><a class="editfielda" 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">';
+			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.'">';
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 			print '<input type="hidden" name="action" value="setdocref">';
 			print '<input type="hidden" name="mode" value="'.$mode.'">';
 			print '<input type="text" size="20" name="doc_ref" value="'.dol_escape_htmltag($object->doc_ref).'">';
-			print '<input type="submit" class="button" value="' . $langs->trans('Modify') . '">';
+			print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
 			print '</form>';
 		} else {
-			print $object->doc_ref ;
+			print $object->doc_ref;
 		}
 		print '</td>';
 		print '</tr>';
@@ -514,17 +514,17 @@ 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>';
+			print '<td class="titlefield">'.$langs->trans("Doctype").'</td>';
+			print '<td>'.$object->doc_type.'</td>';
 			print '</tr>';
 		}
 
 		// Date document creation
 		print '<tr>';
-		print '<td class="titlefield">' . $langs->trans("DateCreation") . '</td>';
+		print '<td class="titlefield">'.$langs->trans("DateCreation").'</td>';
 		print '<td>';
 		print $object->date_creation ? dol_print_date($object->date_creation, 'day') : '&nbsp;';
 		print '</td>';
@@ -586,16 +586,16 @@ if ($action == 'create')
 		} else {
 			print load_fiche_titre($langs->trans("ListeMvts"), '', '');
 
-			print '<form action="' . $_SERVER["PHP_SELF"] . '?piece_num=' . $object->piece_num . '" method="post">';
+			print '<form action="'.$_SERVER["PHP_SELF"].'?piece_num='.$object->piece_num.'" method="post">';
 			if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
 			print '<input type="hidden" name="token" value="'.$_SESSION['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";
-			print '<input type="hidden" name="doc_ref" value="' . $object->doc_ref . '">' . "\n";
-			print '<input type="hidden" name="code_journal" value="' . $object->code_journal . '">' . "\n";
-			print '<input type="hidden" name="fk_doc" value="' . $object->fk_doc . '">' . "\n";
-			print '<input type="hidden" name="fk_docdet" value="' . $object->fk_docdet . '">' . "\n";
-			print '<input type="hidden" name="mode" value="' . $mode . '">' . "\n";
+			print '<input type="hidden" name="doc_date" value="'.$object->doc_date.'">'."\n";
+			print '<input type="hidden" name="doc_type" value="'.$object->doc_type.'">'."\n";
+			print '<input type="hidden" name="doc_ref" value="'.$object->doc_ref.'">'."\n";
+			print '<input type="hidden" name="code_journal" value="'.$object->code_journal.'">'."\n";
+			print '<input type="hidden" name="fk_doc" value="'.$object->fk_doc.'">'."\n";
+			print '<input type="hidden" name="fk_docdet" value="'.$object->fk_docdet.'">'."\n";
+			print '<input type="hidden" name="mode" value="'.$mode.'">'."\n";
 
 			print "<table class=\"noborder\" width=\"100%\">";
 			if (count($object->linesmvt) > 0) {
@@ -620,12 +620,12 @@ if ($action == 'create')
 
 					if ($action == 'update' && $line->id == $id) {
 						print '<td>';
-						print $formaccounting->select_account((GETPOSTISSET("accountingaccount_number") ? GETPOST("accountingaccount_number", "alpha") : $line->numero_compte), 'accountingaccount_number', 1, array (), 1, 1, '');
+						print $formaccounting->select_account((GETPOSTISSET("accountingaccount_number") ? GETPOST("accountingaccount_number", "alpha") : $line->numero_compte), 'accountingaccount_number', 1, array(), 1, 1, '');
 						print '</td>';
 						print '<td>';
 						// 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 $formaccounting->select_auxaccount((GETPOSTISSET("subledger_account") ? GETPOST("subledger_account", "alpha") : $line->subledger_account), 'subledger_account', 1);
 						}
@@ -634,30 +634,30 @@ if ($action == 'create')
 							print '<input type="text" class="maxwidth150" name="subledger_account" value="'.(GETPOSTISSET("subledger_account") ? GETPOST("subledger_account", "alpha") : $line->subledger_account).'">';
 						}
 						print '</td>';
-						print '<td><input type="text" class="minwidth200" name="label_operation" value="' . (GETPOSTISSET("label_operation") ? GETPOST("label_operation", "alpha") : $line->label_operation). '"></td>';
-						print '<td class="right"><input type="text" size="6" class="right" name="debit" value="' . (GETPOSTISSET("debit") ? GETPOST("debit", "alpha") : price($line->debit)) . '"></td>';
-						print '<td class="right"><input type="text" size="6" class="right" name="credit" value="' . (GETPOSTISSET("credit") ? GETPOST("credit", "alpha") : price($line->credit)) . '"></td>';
+						print '<td><input type="text" class="minwidth200" name="label_operation" value="'.(GETPOSTISSET("label_operation") ? GETPOST("label_operation", "alpha") : $line->label_operation).'"></td>';
+						print '<td class="right"><input type="text" size="6" class="right" name="debit" value="'.(GETPOSTISSET("debit") ? GETPOST("debit", "alpha") : price($line->debit)).'"></td>';
+						print '<td class="right"><input type="text" size="6" class="right" name="credit" value="'.(GETPOSTISSET("credit") ? GETPOST("credit", "alpha") : price($line->credit)).'"></td>';
 						print '<td>';
-						print '<input type="hidden" name="id" value="' . $line->id . '">' . "\n";
-						print '<input type="submit" class="button" name="update" value="' . $langs->trans("Update") . '">';
+						print '<input type="hidden" name="id" value="'.$line->id.'">'."\n";
+						print '<input type="submit" class="button" name="update" value="'.$langs->trans("Update").'">';
 						print '</td>';
 					} else {
 						$accountingaccount->fetch(null, $line->numero_compte, true);
-						print '<td>' . $accountingaccount->getNomUrl(0, 1, 1, '', 0) . '</td>';
-						print '<td>' . length_accounta($line->subledger_account) . '</td>';
-						print '<td>' . $line->label_operation. '</td>';
-						print '<td class="nowrap right">' . price($line->debit) . '</td>';
-						print '<td class="nowrap right">' . price($line->credit) . '</td>';
+						print '<td>'.$accountingaccount->getNomUrl(0, 1, 1, '', 0).'</td>';
+						print '<td>'.length_accounta($line->subledger_account).'</td>';
+						print '<td>'.$line->label_operation.'</td>';
+						print '<td class="nowrap right">'.price($line->debit).'</td>';
+						print '<td class="nowrap right">'.price($line->credit).'</td>';
 
 						print '<td class="center">';
-						print '<a href="' . $_SERVER["PHP_SELF"] . '?action=update&id=' . $line->id . '&piece_num=' . $line->piece_num . '&mode='.$mode.'">';
+						print '<a href="'.$_SERVER["PHP_SELF"].'?action=update&id='.$line->id.'&piece_num='.$line->piece_num.'&mode='.$mode.'">';
 						print img_edit();
 						print '</a> &nbsp;';
 
-						$actiontodelete='delete';
-						if ($mode == '_tmp' || $action != 'delmouv') $actiontodelete='confirm_delete';
+						$actiontodelete = 'delete';
+						if ($mode == '_tmp' || $action != 'delmouv') $actiontodelete = 'confirm_delete';
 
-						print '<a href="' . $_SERVER["PHP_SELF"] . '?action='.$actiontodelete.'&id=' . $line->id . '&piece_num=' . $line->piece_num . '&mode='.$mode.'">';
+						print '<a href="'.$_SERVER["PHP_SELF"].'?action='.$actiontodelete.'&id='.$line->id.'&piece_num='.$line->piece_num.'&mode='.$mode.'">';
 						print img_delete();
 
 						print '</a>';
@@ -677,12 +677,12 @@ if ($action == 'create')
 				if ($action == "" || $action == 'add') {
 					print '<tr class="oddeven">';
 					print '<td>';
-					print $formaccounting->select_account('', 'accountingaccount_number', 1, array (), 1, 1, '');
+					print $formaccounting->select_account('', 'accountingaccount_number', 1, array(), 1, 1, '');
 					print '</td>';
 					print '<td>';
 					// 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 $formaccounting->select_auxaccount('', 'subledger_account', 1);
 					}
@@ -694,19 +694,19 @@ if ($action == 'create')
 					print '<td><input type="text" class="minwidth200" name="label_operation" value="'.$label_operation.'"/></td>';
 					print '<td class="right"><input type="text" size="6" class="right" name="debit" value=""/></td>';
 					print '<td class="right"><input type="text" size="6" class="right" name="credit" value=""/></td>';
-					print '<td><input type="submit" class="button" name="save" value="' . $langs->trans("Add") . '"></td>';
+					print '<td><input type="submit" class="button" name="save" value="'.$langs->trans("Add").'"></td>';
 					print '</tr>';
 				}
 				print '</table>';
 
 
-				if ($mode=='_tmp' && $action=='')
+				if ($mode == '_tmp' && $action == '')
 				{
 					print '<br>';
 					print '<div class="center">';
 					if ($total_debit == $total_credit)
 					{
-						print '<a class="button" href="' . $_SERVER["PHP_SELF"] . '?piece_num=' . $object->piece_num . '&action=valid">'.$langs->trans("ValidTransaction").'</a>';
+						print '<a class="button" href="'.$_SERVER["PHP_SELF"].'?piece_num='.$object->piece_num.'&action=valid">'.$langs->trans("ValidTransaction").'</a>';
 					}
 					else
 					{
@@ -714,7 +714,7 @@ if ($action == 'create')
 					}
 
 					print ' &nbsp; ';
-					print '<a class="button" href="' . DOL_URL_ROOT.'/accountancy/bookkeeping/list.php">'.$langs->trans("Cancel").'</a>';
+					print '<a class="button" href="'.DOL_URL_ROOT.'/accountancy/bookkeeping/list.php">'.$langs->trans("Cancel").'</a>';
 
 					print "</div>";
 				}

+ 46 - 46
htdocs/accountancy/class/accountingjournal.class.php

@@ -29,12 +29,12 @@ class AccountingJournal extends CommonObject
 	/**
 	 * @var string ID to identify managed object
 	 */
-	public $element='accounting_journal';
+	public $element = 'accounting_journal';
 
 	/**
 	 * @var string Name of table without prefix where object is stored
 	 */
-	public $table_element='accounting_journal';
+	public $table_element = 'accounting_journal';
 
 	/**
 	 * @var int Field with ID of parent key if this field has a parent
@@ -64,7 +64,7 @@ class AccountingJournal extends CommonObject
      */
     public $label;
 
-	public $nature;		// 1:various operations, 2:sale, 3:purchase, 4:bank, 5:expense-report, 8:inventory, 9: has-new
+	public $nature; // 1:various operations, 2:sale, 3:purchase, 4:bank, 5:expense-report, 8:inventory, 9: has-new
 	public $active;
 
 	public $lines;
@@ -93,29 +93,29 @@ class AccountingJournal extends CommonObject
 		if ($rowid || $journal_code)
 		{
 			$sql = "SELECT rowid, code, label, nature, active";
-			$sql.= " FROM ".MAIN_DB_PREFIX."accounting_journal";
+			$sql .= " FROM ".MAIN_DB_PREFIX."accounting_journal";
 			$sql .= " WHERE";
 			if ($rowid) {
-				$sql .= " rowid = " . (int) $rowid;
+				$sql .= " rowid = ".(int) $rowid;
 			}
 			elseif ($journal_code)
 			{
-				$sql .= " code = '" . $this->db->escape($journal_code) . "'";
-				$sql .= " AND entity  = " . $conf->entity;
+				$sql .= " code = '".$this->db->escape($journal_code)."'";
+				$sql .= " AND entity  = ".$conf->entity;
 			}
 
-			dol_syslog(get_class($this)."::fetch sql=" . $sql, LOG_DEBUG);
+			dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
 			$result = $this->db->query($sql);
 			if ($result)
 			{
 				$obj = $this->db->fetch_object($result);
 
 				if ($obj) {
-					$this->id			= $obj->rowid;
+					$this->id = $obj->rowid;
 					$this->rowid		= $obj->rowid;
 
 					$this->code			= $obj->code;
-					$this->ref			= $obj->code;
+					$this->ref = $obj->code;
 					$this->label		= $obj->label;
 					$this->nature		= $obj->nature;
 					$this->active		= $obj->active;
@@ -127,8 +127,8 @@ class AccountingJournal extends CommonObject
 			}
 			else
 			{
-				$this->error = "Error " . $this->db->lasterror();
-				$this->errors[] = "Error " . $this->db->lasterror();
+				$this->error = "Error ".$this->db->lasterror();
+				$this->errors[] = "Error ".$this->db->lasterror();
 			}
 		}
 		return -1;
@@ -149,38 +149,38 @@ class AccountingJournal extends CommonObject
     public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
     {
 		$sql = "SELECT rowid, code, label, nature, active";
-		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
 		// Manage filter
 		$sqlwhere = array();
 		if (count($filter) > 0) {
 			foreach ($filter as $key => $value) {
 				if ($key == 't.code' || $key == 't.label' || $key == 't.nature') {
-					$sqlwhere[] = $key . '\'' . $this->db->escape($value) . '\'';
+					$sqlwhere[] = $key.'\''.$this->db->escape($value).'\'';
 				} elseif ($key == 't.rowid' || $key == 't.active') {
-					$sqlwhere[] = $key . '=' . $value;
+					$sqlwhere[] = $key.'='.$value;
 				}
 			}
 		}
 		$sql .= ' WHERE 1 = 1';
-		$sql .= " AND entity IN (" . getEntity('accountancy') . ")";
+		$sql .= " AND entity IN (".getEntity('accountancy').")";
 		if (count($sqlwhere) > 0) {
-			$sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere);
+			$sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere);
 		}
 
-		if (! empty($sortfield)) {
+		if (!empty($sortfield)) {
 			$sql .= $this->db->order($sortfield, $sortorder);
 		}
-		if (! empty($limit)) {
-			$sql .= ' ' . $this->db->plimit($limit + 1, $offset);
+		if (!empty($limit)) {
+			$sql .= ' '.$this->db->plimit($limit + 1, $offset);
 		}
 		$this->lines = array();
 
-		dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG);
+		dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
 		$resql = $this->db->query($sql);
 		if ($resql) {
 			$num = $this->db->num_rows($resql);
 
-			while ( $obj = $this->db->fetch_object($resql) ) {
+			while ($obj = $this->db->fetch_object($resql)) {
 				$line = new self($this->db);
 
 				$line->id = $obj->rowid;
@@ -196,10 +196,10 @@ class AccountingJournal extends CommonObject
 
 			return $num;
 		} else {
-			$this->errors[] = 'Error ' . $this->db->lasterror();
-			dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
+			$this->errors[] = 'Error '.$this->db->lasterror();
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
 
-			return - 1;
+			return -1;
 		}
 	}
 
@@ -217,34 +217,34 @@ 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';
+		$url = DOL_URL_ROOT.'/accountancy/admin/journals_list.php?id=35';
 
-		$label = '<u>' . $langs->trans("ShowAccountingJournal") . '</u>';
-		if (! empty($this->code))
-			$label .= '<br><b>'.$langs->trans('Code') . ':</b> ' . $this->code;
-		if (! empty($this->label))
-			$label .= '<br><b>'.$langs->trans('Label') . ':</b> ' . $langs->transnoentities($this->label);
-		if ($moretitle) $label.=' - '.$moretitle;
+		$label = '<u>'.$langs->trans("ShowAccountingJournal").'</u>';
+		if (!empty($this->code))
+			$label .= '<br><b>'.$langs->trans('Code').':</b> '.$this->code;
+		if (!empty($this->label))
+			$label .= '<br><b>'.$langs->trans('Label').':</b> '.$langs->transnoentities($this->label);
+		if ($moretitle) $label .= ' - '.$moretitle;
 
-		$linkclose='';
+		$linkclose = '';
 		if (empty($notooltip))
 		{
-			if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
 			{
-				$label=$langs->trans("ShowAccountingJournal");
-				$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
+				$label = $langs->trans("ShowAccountingJournal");
+				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
 			}
-			$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
-			$linkclose.=' class="classfortooltip"';
+			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+			$linkclose .= ' class="classfortooltip"';
 		}
 
-		$linkstart='<a href="'.$url.'"';
-		$linkstart.=$linkclose.'>';
-		$linkend='</a>';
+		$linkstart = '<a href="'.$url.'"';
+		$linkstart .= $linkclose.'>';
+		$linkend = '</a>';
 
 		if ($nourl)
 		{
@@ -254,11 +254,11 @@ class AccountingJournal extends CommonObject
 		}
 
 		$label_link = $this->code;
-		if ($withlabel) $label_link .= ' - ' . $langs->transnoentities($this->label);
+		if ($withlabel) $label_link .= ' - '.$langs->transnoentities($this->label);
 
 		$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;
@@ -292,7 +292,7 @@ class AccountingJournal extends CommonObject
 
 		if ($mode == 0)
 		{
-			$prefix='';
+			$prefix = '';
 			if ($nature == 9) return $langs->trans('AccountingJournalType9');
 			elseif ($nature == 5) return $langs->trans('AccountingJournalType5');
 			elseif ($nature == 4) return $langs->trans('AccountingJournalType4');

File diff suppressed because it is too large
+ 279 - 279
htdocs/accountancy/class/bookkeeping.class.php


+ 33 - 33
htdocs/accountancy/index.php

@@ -24,12 +24,12 @@
  */
 
 require '../main.inc.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("compta","bills","other","accountancy","loans","banks","admin","dict"));
+$langs->loadLangs(array("compta", "bills", "other", "accountancy", "loans", "banks", "admin", "dict"));
 
 // Security check
 if ($user->socid > 0)
@@ -45,12 +45,12 @@ $hookmanager->initHooks(array('accountancyindex'));
 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');
-    $boxorder=GETPOST('boxorder', 'aZ09');
-    $boxorder.=GETPOST('boxcombo', 'aZ09');
+    $zone = GETPOST('areacode', 'aZ09');
+    $userid = GETPOST('userid', 'int');
+    $boxorder = GETPOST('boxorder', 'aZ09');
+    $boxorder .= GETPOST('boxcombo', 'aZ09');
 
-    $result=InfoBox::saveboxorder($db, $zone, $boxorder, $userid);
+    $result = InfoBox::saveboxorder($db, $zone, $boxorder, $userid);
     if ($result > 0) setEventMessages($langs->trans("BoxAdded"), null);
 }
 
@@ -64,16 +64,16 @@ if ($conf->accounting->enabled)
 {
     $step = 0;
 
-    $resultboxes=FormOther::getBoxesArea($user, "27");    	// Load $resultboxes (selectboxlist + boxactivated + boxlista + boxlistb)
+    $resultboxes = FormOther::getBoxesArea($user, "27"); // Load $resultboxes (selectboxlist + boxactivated + boxlista + boxlistb)
 
-	$helpisexpanded = empty($resultboxes['boxactivated']);	// If there is no widget, the tooltip help is expanded by default.
+	$helpisexpanded = empty($resultboxes['boxactivated']); // 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");
+		$showtutorial .= ' '.$langs->trans("ShowTutorial");
 		$showtutorial .= '</a></div>';
 
 		$showtutorial .= '<script type="text/javascript" language="javascript">
@@ -127,7 +127,7 @@ if ($conf->accounting->enabled)
 	$textlink = '<a href="'.DOL_URL_ROOT.'/admin/dict.php?id=10&from=accountancy">'.'<strong>'.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuVatAccounts").'</strong>'.'</a>';
 	print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescVat", $step, $textlink);
 	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++;
@@ -142,7 +142,7 @@ if ($conf->accounting->enabled)
 	    print "<br>\n";
 	    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++;
 	    print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescExpenseReport", $step, '<a href="'.DOL_URL_ROOT.'/admin/dict.php?id=17&from=accountancy">'.'<strong>'.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuExpenseReportAccounts").'</strong>'.'</a>');
@@ -186,26 +186,26 @@ if ($conf->accounting->enabled)
 	$langs->loadLangs(array('bills', 'trips'));
 
 	$step++;
-	print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64+$step), $langs->transnoentitiesnoconv("BillsCustomers"), '<a href="'.DOL_URL_ROOT.'/accountancy/customer/index.php">'.'<strong>'.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("CustomersVentilation").'</strong>'.'</a>')."\n";
+	print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64 + $step), $langs->transnoentitiesnoconv("BillsCustomers"), '<a href="'.DOL_URL_ROOT.'/accountancy/customer/index.php">'.'<strong>'.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("CustomersVentilation").'</strong>'.'</a>')."\n";
 	print "<br>\n";
 
 	$step++;
-	print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64+$step), $langs->transnoentitiesnoconv("BillsSuppliers"), '<a href="'.DOL_URL_ROOT.'/accountancy/supplier/index.php">'.'<strong>'.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("SuppliersVentilation").'</strong>'.'</a>')."\n";
+	print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64 + $step), $langs->transnoentitiesnoconv("BillsSuppliers"), '<a href="'.DOL_URL_ROOT.'/accountancy/supplier/index.php">'.'<strong>'.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("SuppliersVentilation").'</strong>'.'</a>')."\n";
 	print "<br>\n";
 
-	if (! empty($conf->expensereport->enabled) || ! empty($conf->deplacement->enabled))
+	if (!empty($conf->expensereport->enabled) || !empty($conf->deplacement->enabled))
 	{
 		$step++;
-		print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64+$step), $langs->transnoentitiesnoconv("ExpenseReports"), '<a href="'.DOL_URL_ROOT.'/accountancy/expensereport/index.php">'.'<strong>'.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("ExpenseReportsVentilation").'</strong>'.'</a>')."\n";
+		print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64 + $step), $langs->transnoentitiesnoconv("ExpenseReports"), '<a href="'.DOL_URL_ROOT.'/accountancy/expensereport/index.php">'.'<strong>'.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("ExpenseReportsVentilation").'</strong>'.'</a>')."\n";
 	    print "<br>\n";
 	}
 
 	$step++;
-	print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescWriteRecords", chr(64+$step), $langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("RegistrationInAccounting"), $langs->transnoentitiesnoconv("WriteBookKeeping"))."\n";
+	print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescWriteRecords", chr(64 + $step), $langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("RegistrationInAccounting"), $langs->transnoentitiesnoconv("WriteBookKeeping"))."\n";
 	print "<br>\n";
 
 	$step++;
-	print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescAnalyze", chr(64+$step))."<br>\n";
+	print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescAnalyze", chr(64 + $step))."<br>\n";
 	print "<br>\n";
 
 	print '<br>';
@@ -219,27 +219,27 @@ if ($conf->accounting->enabled)
     /*
      * Show boxes
      */
-    $boxlist.='<div class="twocolumns">';
+    $boxlist .= '<div class="twocolumns">';
 
-    $boxlist.='<div class="firstcolumn fichehalfleft boxhalfleft" id="boxhalfleft">';
-    if(!empty($nbworkboardcount))
+    $boxlist .= '<div class="firstcolumn fichehalfleft boxhalfleft" id="boxhalfleft">';
+    if (!empty($nbworkboardcount))
     {
-        $boxlist.=$boxwork;
+        $boxlist .= $boxwork;
     }
 
-    $boxlist.=$resultboxes['boxlista'];
+    $boxlist .= $resultboxes['boxlista'];
 
-    $boxlist.= '</div>';
+    $boxlist .= '</div>';
 
-    $boxlist.= '<div class="secondcolumn fichehalfright boxhalfright" id="boxhalfright">';
+    $boxlist .= '<div class="secondcolumn fichehalfright boxhalfright" id="boxhalfright">';
 
-    $boxlist.=$boxstat;
-    $boxlist.=$resultboxes['boxlistb'];
+    $boxlist .= $boxstat;
+    $boxlist .= $resultboxes['boxlistb'];
 
-    $boxlist.= '</div>';
-    $boxlist.= "\n";
+    $boxlist .= '</div>';
+    $boxlist .= "\n";
 
-    $boxlist.='</div>';
+    $boxlist .= '</div>';
 
 
     print $boxlist;

+ 35 - 35
htdocs/adherents/admin/website.php

@@ -31,11 +31,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("admin","members"));
+$langs->loadLangs(array("admin", "members"));
 
-$action=GETPOST('action', 'alpha');
+$action = GETPOST('action', 'alpha');
 
-if (! $user->admin) accessforbidden();
+if (!$user->admin) accessforbidden();
 
 
 /*
@@ -50,22 +50,22 @@ if ($action == 'setMEMBER_ENABLE_PUBLIC')
 
 if ($action == 'update')
 {
-	$public=GETPOST('MEMBER_ENABLE_PUBLIC');
-	$amount=GETPOST('MEMBER_NEWFORM_AMOUNT');
-	$editamount=GETPOST('MEMBER_NEWFORM_EDITAMOUNT');
-	$payonline=GETPOST('MEMBER_NEWFORM_PAYONLINE');
-	$forcetype=GETPOST('MEMBER_NEWFORM_FORCETYPE');
-
-    $res=dolibarr_set_const($db, "MEMBER_ENABLE_PUBLIC", $public, 'chaine', 0, '', $conf->entity);
-    $res=dolibarr_set_const($db, "MEMBER_NEWFORM_AMOUNT", $amount, 'chaine', 0, '', $conf->entity);
-    $res=dolibarr_set_const($db, "MEMBER_NEWFORM_EDITAMOUNT", $editamount, 'chaine', 0, '', $conf->entity);
-    $res=dolibarr_set_const($db, "MEMBER_NEWFORM_PAYONLINE", $payonline, 'chaine', 0, '', $conf->entity);
-    if ($forcetype < 0) $res=dolibarr_del_const($db, "MEMBER_NEWFORM_FORCETYPE", $conf->entity);
-    else                $res=dolibarr_set_const($db, "MEMBER_NEWFORM_FORCETYPE", $forcetype, 'chaine', 0, '', $conf->entity);
-
-    if (! $res > 0) $error++;
-
- 	if (! $error)
+	$public = GETPOST('MEMBER_ENABLE_PUBLIC');
+	$amount = GETPOST('MEMBER_NEWFORM_AMOUNT');
+	$editamount = GETPOST('MEMBER_NEWFORM_EDITAMOUNT');
+	$payonline = GETPOST('MEMBER_NEWFORM_PAYONLINE');
+	$forcetype = GETPOST('MEMBER_NEWFORM_FORCETYPE');
+
+    $res = dolibarr_set_const($db, "MEMBER_ENABLE_PUBLIC", $public, 'chaine', 0, '', $conf->entity);
+    $res = dolibarr_set_const($db, "MEMBER_NEWFORM_AMOUNT", $amount, 'chaine', 0, '', $conf->entity);
+    $res = dolibarr_set_const($db, "MEMBER_NEWFORM_EDITAMOUNT", $editamount, 'chaine', 0, '', $conf->entity);
+    $res = dolibarr_set_const($db, "MEMBER_NEWFORM_PAYONLINE", $payonline, 'chaine', 0, '', $conf->entity);
+    if ($forcetype < 0) $res = dolibarr_del_const($db, "MEMBER_NEWFORM_FORCETYPE", $conf->entity);
+    else                $res = dolibarr_set_const($db, "MEMBER_NEWFORM_FORCETYPE", $forcetype, 'chaine', 0, '', $conf->entity);
+
+    if (!$res > 0) $error++;
+
+ 	if (!$error)
     {
 	    setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
@@ -80,13 +80,13 @@ if ($action == 'update')
  * View
  */
 
-$form=new Form($db);
+$form = new Form($db);
 
-$help_url='EN:Module_Foundations|FR:Module_Adh&eacute;rents|ES:M&oacute;dulo_Miembros';
+$help_url = 'EN:Module_Foundations|FR:Module_Adh&eacute;rents|ES:M&oacute;dulo_Miembros';
 llxHeader('', $langs->trans("MembersSetup"), $help_url);
 
 
-$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
+$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
 print load_fiche_titre($langs->trans("MembersSetup"), $linkback, 'title_setup');
 
 $head = member_admin_prepare_head();
@@ -142,24 +142,24 @@ $enabledisablehtml = $langs->trans("EnablePublicSubscriptionForm").' ';
 if (empty($conf->global->MEMBER_ENABLE_PUBLIC))
 {
 	// Button off, click to enable
-	$enabledisablehtml.='<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setMEMBER_ENABLE_PUBLIC&value=1'.$param.'">';
-	$enabledisablehtml.=img_picto($langs->trans("Disabled"), 'switch_off');
-	$enabledisablehtml.='</a>';
+	$enabledisablehtml .= '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setMEMBER_ENABLE_PUBLIC&value=1'.$param.'">';
+	$enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off');
+	$enabledisablehtml .= '</a>';
 }
 else
 {
 	// Button on, click to disable
-	$enabledisablehtml.='<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setMEMBER_ENABLE_PUBLIC&value=0'.$param.'">';
-	$enabledisablehtml.=img_picto($langs->trans("Activated"), 'switch_on');
-	$enabledisablehtml.='</a>';
+	$enabledisablehtml .= '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=setMEMBER_ENABLE_PUBLIC&value=0'.$param.'">';
+	$enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on');
+	$enabledisablehtml .= '</a>';
 }
 print $enabledisablehtml;
-print '<input type="hidden" id="MEMBER_ENABLE_PUBLIC" name="MEMBER_ENABLE_PUBLIC" value="'.(empty($conf->global->MEMBER_ENABLE_PUBLIC)?0:1).'">';
+print '<input type="hidden" id="MEMBER_ENABLE_PUBLIC" name="MEMBER_ENABLE_PUBLIC" value="'.(empty($conf->global->MEMBER_ENABLE_PUBLIC) ? 0 : 1).'">';
 
 
 print '<br>';
 
-if (! empty($conf->global->MEMBER_ENABLE_PUBLIC))
+if (!empty($conf->global->MEMBER_ENABLE_PUBLIC))
 {
 	print '<br>';
 
@@ -221,20 +221,20 @@ dol_fiche_end();
 print '</form>';
 
 
-if (! empty($conf->global->MEMBER_ENABLE_PUBLIC))
+if (!empty($conf->global->MEMBER_ENABLE_PUBLIC))
 {
 	print '<br>';
 	//print $langs->trans('FollowingLinksArePublic').'<br>';
 	print img_picto('', 'globe').' '.$langs->trans('BlankSubscriptionForm').':<br>';
 	if ($conf->multicompany->enabled) {
-		$entity_qr='?entity='.$conf->entity;
+		$entity_qr = '?entity='.$conf->entity;
 	} else {
-		$entity_qr='';
+		$entity_qr = '';
 	}
 
 	// Define $urlwithroot
-	$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
-	$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+	$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
+	$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
 	//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
 
 	print '<a target="_blank" href="'.$urlwithroot.'/public/members/new.php'.$entity_qr.'">'.$urlwithroot.'/public/members/new.php'.$entity_qr.'</a>';

+ 215 - 215
htdocs/adherents/subscription.php

@@ -38,15 +38,15 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
 
-$langs->loadLangs(array("companies","bills","members","users","mails",'other'));
+$langs->loadLangs(array("companies", "bills", "members", "users", "mails", 'other'));
 
-$action=GETPOST('action', 'alpha');
-$confirm=GETPOST('confirm', 'alpha');
-$rowid=GETPOST('rowid', 'int')?GETPOST('rowid', 'int'):GETPOST('id', 'int');
-$typeid=GETPOST('typeid', 'int');
+$action = GETPOST('action', 'alpha');
+$confirm = GETPOST('confirm', 'alpha');
+$rowid = GETPOST('rowid', 'int') ?GETPOST('rowid', 'int') : GETPOST('id', 'int');
+$typeid = GETPOST('typeid', 'int');
 
 // Load variable for pagination
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'alpha');
 $sortorder = GETPOST('sortorder', 'alpha');
 $page = GETPOST('page', 'int');
@@ -56,12 +56,12 @@ $pageprev = $page - 1;
 $pagenext = $page + 1;
 
 // Default sort order (if not yet defined by previous GETPOST)
-if (! $sortfield) $sortfield="c.rowid";
-if (! $sortorder) $sortorder="DESC";
+if (!$sortfield) $sortfield = "c.rowid";
+if (!$sortorder) $sortorder = "DESC";
 
 
 // Security check
-$result=restrictedArea($user, 'adherent', $rowid, '', 'cotisation');
+$result = restrictedArea($user, 'adherent', $rowid, '', 'cotisation');
 
 $object = new Adherent($db);
 $extrafields = new ExtraFields($db);
@@ -70,11 +70,11 @@ $adht = new AdherentType($db);
 // fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label($object->table_element);
 
-$errmsg='';
-$errmsgs=array();
+$errmsg = '';
+$errmsgs = array();
 
-$defaultdelay=1;
-$defaultdelayunit='y';
+$defaultdelay = 1;
+$defaultdelayunit = 'y';
 
 if ($rowid)
 {
@@ -122,7 +122,7 @@ if ($action == 'confirm_create_thirdparty' && $confirm == 'yes' && $user->rights
 	{
 		// Creation of thirdparty
 		$company = new Societe($db);
-		$result=$company->create_from_member($object, GETPOST('companyname', 'alpha'), GETPOST('companyalias', 'alpha'), GETPOST('customercode', 'alpha'));
+		$result = $company->create_from_member($object, GETPOST('companyname', 'alpha'), GETPOST('companyalias', 'alpha'), GETPOST('customercode', 'alpha'));
 
 		if ($result < 0)
 		{
@@ -131,7 +131,7 @@ if ($action == 'confirm_create_thirdparty' && $confirm == 'yes' && $user->rights
 		}
 		else
 		{
-			$action='addsubscription';
+			$action = 'addsubscription';
 		}
 	}
 	else
@@ -142,7 +142,7 @@ if ($action == 'confirm_create_thirdparty' && $confirm == 'yes' && $user->rights
 
 if ($action == 'setuserid' && ($user->rights->user->self->creer || $user->rights->user->user->creer))
 {
-    $error=0;
+    $error = 0;
     if (empty($user->rights->user->user->creer))    // If can edit only itself user, we can link to itself only
     {
         if ($_POST["userid"] != $user->id && $_POST["userid"] != $object->user_id)
@@ -152,56 +152,56 @@ if ($action == 'setuserid' && ($user->rights->user->self->creer || $user->rights
         }
     }
 
-    if (! $error)
+    if (!$error)
     {
         if ($_POST["userid"] != $object->user_id)  // If link differs from currently in database
         {
-            $result=$object->setUserId($_POST["userid"]);
+            $result = $object->setUserId($_POST["userid"]);
             if ($result < 0) dol_print_error('', $object->error);
-            $_POST['action']='';
-            $action='';
+            $_POST['action'] = '';
+            $action = '';
         }
     }
 }
 
 if ($action == 'setsocid')
 {
-    $error=0;
-    if (! $error)
+    $error = 0;
+    if (!$error)
     {
         if (GETPOST('socid', 'int') != $object->fk_soc)    // If link differs from currently in database
         {
-            $sql ="SELECT rowid FROM ".MAIN_DB_PREFIX."adherent";
-            $sql.=" WHERE fk_soc = '".GETPOST('socid', 'int')."'";
+            $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent";
+            $sql .= " WHERE fk_soc = '".GETPOST('socid', 'int')."'";
             $resql = $db->query($sql);
             if ($resql)
             {
                 $obj = $db->fetch_object($resql);
                 if ($obj && $obj->rowid > 0)
                 {
-                    $othermember=new Adherent($db);
+                    $othermember = new Adherent($db);
                     $othermember->fetch($obj->rowid);
-                    $thirdparty=new Societe($db);
+                    $thirdparty = new Societe($db);
                     $thirdparty->fetch(GETPOST('socid', 'int'));
                     $error++;
 	                setEventMessages($langs->trans("ErrorMemberIsAlreadyLinkedToThisThirdParty", $othermember->getFullName($langs), $othermember->login, $thirdparty->name), null, 'errors');
                 }
             }
 
-            if (! $error)
+            if (!$error)
             {
-                $result=$object->setThirdPartyId(GETPOST('socid', 'int'));
+                $result = $object->setThirdPartyId(GETPOST('socid', 'int'));
                 if ($result < 0) dol_print_error('', $object->error);
-                $_POST['action']='';
-                $action='';
+                $_POST['action'] = '';
+                $action = '';
             }
         }
     }
 }
 
-if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && ! $_POST["cancel"])
+if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && !$_POST["cancel"])
 {
-    $error=0;
+    $error = 0;
 
     $langs->load("banks");
 
@@ -209,114 +209,114 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && !
     $result = $adht->fetch($object->typeid);
 
     // Subscription informations
-    $datesubscription=0;
-    $datesubend=0;
-    $paymentdate=0;
+    $datesubscription = 0;
+    $datesubend = 0;
+    $paymentdate = 0;
     if ($_POST["reyear"] && $_POST["remonth"] && $_POST["reday"])
     {
-        $datesubscription=dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]);
+        $datesubscription = dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]);
     }
     if ($_POST["endyear"] && $_POST["endmonth"] && $_POST["endday"])
     {
-        $datesubend=dol_mktime(0, 0, 0, $_POST["endmonth"], $_POST["endday"], $_POST["endyear"]);
+        $datesubend = dol_mktime(0, 0, 0, $_POST["endmonth"], $_POST["endday"], $_POST["endyear"]);
     }
     if ($_POST["paymentyear"] && $_POST["paymentmonth"] && $_POST["paymentday"])
     {
-        $paymentdate=dol_mktime(0, 0, 0, $_POST["paymentmonth"], $_POST["paymentday"], $_POST["paymentyear"]);
+        $paymentdate = dol_mktime(0, 0, 0, $_POST["paymentmonth"], $_POST["paymentday"], $_POST["paymentyear"]);
     }
-    $amount=price2num(GETPOST("subscription", 'alpha'));	// Amount of subscription
-    $label=$_POST["label"];
+    $amount = price2num(GETPOST("subscription", 'alpha')); // Amount of subscription
+    $label = $_POST["label"];
 
     // Payment informations
-    $accountid=$_POST["accountid"];
-    $operation=$_POST["operation"]; // Payment mode
-    $num_chq=$_POST["num_chq"];
-    $emetteur_nom=$_POST["chqemetteur"];
-    $emetteur_banque=$_POST["chqbank"];
-    $option=$_POST["paymentsave"];
-    if (empty($option)) $option='none';
-    $sendalsoemail=GETPOST("sendmail", 'alpha');
+    $accountid = $_POST["accountid"];
+    $operation = $_POST["operation"]; // Payment mode
+    $num_chq = $_POST["num_chq"];
+    $emetteur_nom = $_POST["chqemetteur"];
+    $emetteur_banque = $_POST["chqbank"];
+    $option = $_POST["paymentsave"];
+    if (empty($option)) $option = 'none';
+    $sendalsoemail = GETPOST("sendmail", 'alpha');
 
     // Check parameters
-    if (! $datesubscription)
+    if (!$datesubscription)
     {
         $error++;
         $langs->load("errors");
-        $errmsg=$langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateSubscription"));
+        $errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateSubscription"));
         setEventMessages($errmsg, null, 'errors');
-        $action='addsubscription';
+        $action = 'addsubscription';
     }
-    if (GETPOST('end') && ! $datesubend)
+    if (GETPOST('end') && !$datesubend)
     {
         $error++;
         $langs->load("errors");
-        $errmsg=$langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateEndSubscription"));
+        $errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateEndSubscription"));
         setEventMessages($errmsg, null, 'errors');
-        $action='addsubscription';
+        $action = 'addsubscription';
     }
-    if (! $datesubend)
+    if (!$datesubend)
     {
-        $datesubend=dol_time_plus_duree(dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit), -1, 'd');
+        $datesubend = dol_time_plus_duree(dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit), -1, 'd');
     }
-    if (($option == 'bankviainvoice' || $option == 'bankdirect') && ! $paymentdate)
+    if (($option == 'bankviainvoice' || $option == 'bankdirect') && !$paymentdate)
     {
         $error++;
-        $errmsg=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePayment"));
+        $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePayment"));
         setEventMessages($errmsg, null, 'errors');
-        $action='addsubscription';
+        $action = 'addsubscription';
     }
 
     // Check if a payment is mandatory or not
-    if (! $error && $adht->subscription)	// Member type need subscriptions
+    if (!$error && $adht->subscription)	// Member type need subscriptions
     {
-        if (! is_numeric($amount))
+        if (!is_numeric($amount))
         {
             // If field is '' or not a numeric value
-            $errmsg=$langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount"));
+            $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount"));
         	setEventMessages($errmsg, null, 'errors');
             $error++;
-            $action='addsubscription';
+            $action = 'addsubscription';
         }
         else
         {
-            if (! empty($conf->banque->enabled) && $_POST["paymentsave"] != 'none')
+            if (!empty($conf->banque->enabled) && $_POST["paymentsave"] != 'none')
             {
                 if ($_POST["subscription"])
                 {
-                    if (! $_POST["label"])     $errmsg=$langs->trans("ErrorFieldRequired", $langs->transnoentities("Label"));
-                    if ($_POST["paymentsave"] != 'invoiceonly' && ! $_POST["operation"]) $errmsg=$langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode"));
-                    if ($_POST["paymentsave"] != 'invoiceonly' && ! ($_POST["accountid"] > 0)) $errmsg=$langs->trans("ErrorFieldRequired", $langs->transnoentities("FinancialAccount"));
+                    if (!$_POST["label"])     $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label"));
+                    if ($_POST["paymentsave"] != 'invoiceonly' && !$_POST["operation"]) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode"));
+                    if ($_POST["paymentsave"] != 'invoiceonly' && !($_POST["accountid"] > 0)) $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("FinancialAccount"));
                 }
                 else
                 {
-                    if ($_POST["accountid"])   $errmsg=$langs->trans("ErrorDoNotProvideAccountsIfNullAmount");
+                    if ($_POST["accountid"])   $errmsg = $langs->trans("ErrorDoNotProvideAccountsIfNullAmount");
                 }
                 if ($errmsg)
                 {
                 	$error++;
         			setEventMessages($errmsg, null, 'errors');
         			$error++;
-                	$action='addsubscription';
+                	$action = 'addsubscription';
                 }
             }
         }
     }
 
     // Record the subscription then complementary actions
-    if (! $error && $action=='subscription')
+    if (!$error && $action == 'subscription')
     {
         $db->begin();
 
         // Create subscription
-        $crowid=$object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend);
+        $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend);
         if ($crowid <= 0)
         {
             $error++;
-            $errmsg=$object->error;
+            $errmsg = $object->error;
 	        setEventMessages($object->error, $object->errors, 'errors');
         }
 
-        if (! $error)
+        if (!$error)
         {
         	$result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque);
 			if ($result < 0)
@@ -330,7 +330,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && !
 			}
         }
 
-        if (! $error)
+        if (!$error)
         {
             $db->commit();
         }
@@ -340,23 +340,23 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && !
             $action = 'addsubscription';
         }
 
-        if (! $error)
+        if (!$error)
         {
         	setEventMessages("SubscriptionRecorded", null, 'mesgs');
         }
 
         // Send email
-        if (! $error)
+        if (!$error)
         {
             // Send confirmation Email
             if ($object->email && $sendalsoemail)   // $object is 'Adherent'
             {
             	$subject = '';
-            	$msg= '';
+            	$msg = '';
 
             	// Send subscription email
             	include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
-            	$formmail=new FormMail($db);
+            	$formmail = new FormMail($db);
             	// Set output language
             	$outputlangs = new Translate('', $conf);
             	$outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
@@ -364,44 +364,44 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && !
             	$outputlangs->loadLangs(array("main", "members"));
 
             	// Get email content from template
-            	$arraydefaultmessage=null;
+            	$arraydefaultmessage = null;
             	$labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION;
 
-            	if (! empty($labeltouse)) $arraydefaultmessage=$formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
+            	if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
 
-            	if (! empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0)
+            	if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0)
             	{
             		$subject = $arraydefaultmessage->topic;
             		$msg     = $arraydefaultmessage->content;
             	}
 
-            	$substitutionarray=getCommonSubstitutionArray($outputlangs, 0, null, $object);
+            	$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
             	complete_substitutions_array($substitutionarray, $outputlangs, $object);
             	$subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
             	$texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
 
                 // Attach a file ?
-                $file='';
-                $listofpaths=array();
-                $listofnames=array();
-                $listofmimes=array();
+                $file = '';
+                $listofpaths = array();
+                $listofnames = array();
+                $listofmimes = array();
                 if (is_object($object->invoice))
                 {
                 	$invoicediroutput = $conf->facture->dir_output;
-                	$fileparams = dol_most_recent_file($invoicediroutput . '/' . $object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
+                	$fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
                 	$file = $fileparams['fullname'];
 
-                	$listofpaths=array($file);
-                	$listofnames=array(basename($file));
-                	$listofmimes=array(dol_mimetype($file));
+                	$listofpaths = array($file);
+                	$listofnames = array(basename($file));
+                	$listofmimes = array(dol_mimetype($file));
                 }
 
-                $moreinheader='X-Dolibarr-Info: send_an_email by adherents/subscription.php'."\r\n";
+                $moreinheader = 'X-Dolibarr-Info: send_an_email by adherents/subscription.php'."\r\n";
 
-                $result=$object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofnames, $listofmimes, "", "", 0, -1, '', $moreinheader);
+                $result = $object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofnames, $listofmimes, "", "", 0, -1, '', $moreinheader);
                 if ($result < 0)
                 {
-                	$errmsg=$object->error;
+                	$errmsg = $object->error;
                 	setEventMessages($object->error, $object->errors, 'errors');
                 }
                 else
@@ -416,13 +416,13 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && !
         }
 
         // Clean some POST vars
-        if (! $error)
+        if (!$error)
         {
-            $_POST["subscription"]='';
-            $_POST["accountid"]='';
-            $_POST["operation"]='';
-            $_POST["label"]='';
-            $_POST["num_chq"]='';
+            $_POST["subscription"] = '';
+            $_POST["accountid"] = '';
+            $_POST["operation"] = '';
+            $_POST["label"] = '';
+            $_POST["num_chq"] = '';
         }
     }
 }
@@ -435,34 +435,34 @@ if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && !
 
 $form = new Form($db);
 
-$now=dol_now();
+$now = dol_now();
 
-$title=$langs->trans("Member") . " - " . $langs->trans("Subscriptions");
-$helpurl="EN:Module_Foundations|FR:Module_Adh&eacute;rents|ES:M&oacute;dulo_Miembros";
+$title = $langs->trans("Member")." - ".$langs->trans("Subscriptions");
+$helpurl = "EN:Module_Foundations|FR:Module_Adh&eacute;rents|ES:M&oacute;dulo_Miembros";
 llxHeader("", $title, $helpurl);
 
 
-$param='';
-if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
-if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
-$param.= '&id='.$rowid;
-if ($optioncss != '')     $param.='&optioncss='.urlencode($optioncss);
+$param = '';
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
+if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+$param .= '&id='.$rowid;
+if ($optioncss != '')     $param .= '&optioncss='.urlencode($optioncss);
 // Add $param from extra fields
 //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 
 
 if ($rowid > 0)
 {
-    $res=$object->fetch($rowid);
+    $res = $object->fetch($rowid);
     if ($res < 0) { dol_print_error($db, $object->error); exit; }
 
     $adht->fetch($object->typeid);
 
     $head = member_prepare_head($object);
 
-    $rowspan=10;
+    $rowspan = 10;
     if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++;
-    if (! empty($conf->societe->enabled)) $rowspan++;
+    if (!empty($conf->societe->enabled)) $rowspan++;
 
     print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
     print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
@@ -504,10 +504,10 @@ if ($rowid > 0)
 	if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED))
 	{
 		print '<tr><td>'.$langs->trans("Password").'</td><td>'.preg_replace('/./i', '*', $object->pass);
-		if ((! empty($object->pass) || ! empty($object->pass_crypted)) && empty($object->user_id))
+		if ((!empty($object->pass) || !empty($object->pass_crypted)) && empty($object->user_id))
 		{
 		    $langs->load("errors");
-		    $htmltext=$langs->trans("WarningPasswordSetWithNoAccount");
+		    $htmltext = $langs->trans("WarningPasswordSetWithNoAccount");
 		    print ' '.$form->textwithpicto('', $htmltext, 1, 'warning');
 		}
 		print '</td></tr>';
@@ -528,17 +528,17 @@ if ($rowid > 0)
 	print '<tr><td>'.$langs->trans("Public").'</td><td class="valeur">'.yn($object->public).'</td></tr>';
 
 	// Categories
-	if (! empty($conf->categorie->enabled)  && ! empty($user->rights->categorie->lire))
+	if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire))
 	{
-		print '<tr><td>' . $langs->trans("Categories") . '</td>';
+		print '<tr><td>'.$langs->trans("Categories").'</td>';
 		print '<td colspan="2">';
 		print $form->showCategories($object->id, 'member', 1);
 		print '</td></tr>';
 	}
 
     // Other attributes
-    $cols=2;
-    include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+    $cols = 2;
+    include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
 	// Date end subscription
 	print '<tr><td>'.$langs->trans("SubscriptionEndDate").'</td><td class="valeur">';
@@ -551,7 +551,7 @@ if ($rowid > 0)
 	}
 	else
 	{
-	    if (! $adht->subscription)
+	    if (!$adht->subscription)
 	    {
 	        print $langs->trans("SubscriptionNotRecorded");
 	        if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled
@@ -565,7 +565,7 @@ if ($rowid > 0)
 	print '</td></tr>';
 
 	// Third party Dolibarr
-	if (! empty($conf->societe->enabled))
+	if (!empty($conf->societe->enabled))
 	{
 		print '<tr><td>';
 		print '<table class="nobordernopadding" width="100%"><tr><td>';
@@ -576,7 +576,7 @@ if ($rowid > 0)
 		print '</td><td colspan="2" class="valeur">';
 		if ($action == 'editthirdparty')
 		{
-			$htmlname='socid';
+			$htmlname = 'socid';
 			print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" name="form'.$htmlname.'">';
 			print '<input type="hidden" name="rowid" value="'.$object->id.'">';
 			print '<input type="hidden" name="action" value="set'.$htmlname.'">';
@@ -592,8 +592,8 @@ if ($rowid > 0)
 		{
 			if ($object->fk_soc)
 			{
-				$company=new Societe($db);
-				$result=$company->fetch($object->fk_soc);
+				$company = new Societe($db);
+				$result = $company->fetch($object->fk_soc);
 				print $company->getNomUrl(1);
 			}
 			else
@@ -668,23 +668,23 @@ if ($rowid > 0)
     if ($action != 'addsubscription' && $action != 'create_thirdparty')
     {
         $sql = "SELECT d.rowid, d.firstname, d.lastname, d.societe, d.fk_adherent_type as type,";
-        $sql.= " c.rowid as crowid, c.subscription,";
-        $sql.= " c.datec, c.fk_type as cfk_type,";
-        $sql.= " c.dateadh as dateh,";
-        $sql.= " c.datef,";
-        $sql.= " c.fk_bank,";
-        $sql.= " b.rowid as bid,";
-        $sql.= " ba.rowid as baid, ba.label, ba.bank, ba.ref, ba.account_number, ba.fk_accountancy_journal, ba.number, ba.currency_code";
-        $sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."subscription as c";
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON c.fk_bank = b.rowid";
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid";
-        $sql.= " WHERE d.rowid = c.fk_adherent AND d.rowid=".$rowid;
-		$sql.= $db->order($sortfield, $sortorder);
+        $sql .= " c.rowid as crowid, c.subscription,";
+        $sql .= " c.datec, c.fk_type as cfk_type,";
+        $sql .= " c.dateadh as dateh,";
+        $sql .= " c.datef,";
+        $sql .= " c.fk_bank,";
+        $sql .= " b.rowid as bid,";
+        $sql .= " ba.rowid as baid, ba.label, ba.bank, ba.ref, ba.account_number, ba.fk_accountancy_journal, ba.number, ba.currency_code";
+        $sql .= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."subscription as c";
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON c.fk_bank = b.rowid";
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid";
+        $sql .= " WHERE d.rowid = c.fk_adherent AND d.rowid=".$rowid;
+		$sql .= $db->order($sortfield, $sortorder);
 
         $result = $db->query($sql);
         if ($result)
         {
-            $subscriptionstatic=new Subscription($db);
+            $subscriptionstatic = new Subscription($db);
 
             $num = $db->num_rows($result);
             $i = 0;
@@ -698,13 +698,13 @@ if ($rowid > 0)
             print '<td class="center">'.$langs->trans("DateStart").'</td>';
             print '<td class="center">'.$langs->trans("DateEnd").'</td>';
             print '<td class="right">'.$langs->trans("Amount").'</td>';
-            if (! empty($conf->banque->enabled))
+            if (!empty($conf->banque->enabled))
             {
                 print '<td class="right">'.$langs->trans("Account").'</td>';
             }
             print "</tr>\n";
 
-            $accountstatic=new Account($db);
+            $accountstatic = new Account($db);
             $adh = new Adherent($db);
             $adht = new AdherentType($db);
 
@@ -715,8 +715,8 @@ if ($rowid > 0)
                 $adh->id = $objp->rowid;
                 $adh->typeid = $objp->type;
 
-                $subscriptionstatic->ref=$objp->crowid;
-                $subscriptionstatic->id=$objp->crowid;
+                $subscriptionstatic->ref = $objp->crowid;
+                $subscriptionstatic->id = $objp->crowid;
 
                 $typeid = ($objp->cfk_type > 0 ? $objp->cfk_type : $adh->typeid);
                 if ($typeid > 0)
@@ -735,18 +735,18 @@ if ($rowid > 0)
                 print '<td class="center">'.dol_print_date($db->jdate($objp->dateh), 'day')."</td>\n";
                 print '<td class="center">'.dol_print_date($db->jdate($objp->datef), 'day')."</td>\n";
                 print '<td class="right">'.price($objp->subscription).'</td>';
-				if (! empty($conf->banque->enabled))
+				if (!empty($conf->banque->enabled))
 				{
 					print '<td class="right">';
 					if ($objp->bid)
 					{
-						$accountstatic->label=$objp->label;
-						$accountstatic->id=$objp->baid;
-						$accountstatic->number=$objp->number;
-						$accountstatic->account_number=$objp->account_number;
-						$accountstatic->currency_code=$objp->currency_code;
+						$accountstatic->label = $objp->label;
+						$accountstatic->id = $objp->baid;
+						$accountstatic->number = $objp->number;
+						$accountstatic->account_number = $objp->account_number;
+						$accountstatic->currency_code = $objp->currency_code;
 
-						if (! empty($conf->accounting->enabled) && $objp->fk_accountancy_journal > 0)
+						if (!empty($conf->accounting->enabled) && $objp->fk_accountancy_journal > 0)
 						{
 							$accountingjournal = new AccountingJournal($db);
 							$accountingjournal->fetch($objp->fk_accountancy_journal);
@@ -754,7 +754,7 @@ if ($rowid > 0)
 							$accountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
 						}
 
-                        $accountstatic->ref=$objp->ref;
+                        $accountstatic->ref = $objp->ref;
                         print $accountstatic->getNomUrl(1);
                     }
                     else
@@ -778,7 +778,7 @@ if ($rowid > 0)
     if (($action != 'addsubscription' && $action != 'create_thirdparty'))
     {
 	    // Shon online payment link
-	    $useonlinepayment = (! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled));
+	    $useonlinepayment = (!empty($conf->paypal->enabled) || !empty($conf->stripe->enabled) || !empty($conf->paybox->enabled));
 
 	    if ($useonlinepayment)
 	    {
@@ -800,20 +800,20 @@ if ($rowid > 0)
         print load_fiche_titre($langs->trans("NewCotisation"));
 
         // Define default choice for complementary actions
-        $bankdirect=0;        // 1 means option by default is write to bank direct with no invoice
-        $invoiceonly=0;		  // 1 means option by default is invoice only
-        $bankviainvoice=0;    // 1 means option by default is write to bank via invoice
+        $bankdirect = 0; // 1 means option by default is write to bank direct with no invoice
+        $invoiceonly = 0; // 1 means option by default is invoice only
+        $bankviainvoice = 0; // 1 means option by default is write to bank via invoice
         if (GETPOST('paymentsave'))
         {
-        	if (GETPOST('paymentsave') == 'bankdirect')     $bankdirect=1;
-        	if (GETPOST('paymentsave') == 'invoiceonly')    $invoiceonly=1;
-        	if (GETPOST('paymentsave') == 'bankviainvoice') $bankviainvoice=1;
+        	if (GETPOST('paymentsave') == 'bankdirect')     $bankdirect = 1;
+        	if (GETPOST('paymentsave') == 'invoiceonly')    $invoiceonly = 1;
+        	if (GETPOST('paymentsave') == 'bankviainvoice') $bankviainvoice = 1;
         }
         else
         {
-        	if (! empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && ! empty($conf->banque->enabled) && ! empty($conf->societe->enabled) && ! empty($conf->facture->enabled)) $bankviainvoice=1;
-        	elseif (! empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && ! empty($conf->banque->enabled)) $bankdirect=1;
-        	elseif (! empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && ! empty($conf->banque->enabled) && ! empty($conf->societe->enabled) && ! empty($conf->facture->enabled)) $invoiceonly=1;
+        	if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $bankviainvoice = 1;
+        	elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) $bankdirect = 1;
+        	elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $invoiceonly = 1;
         }
 
         print "\n\n<!-- Form add subscription -->\n";
@@ -823,7 +823,7 @@ if ($rowid > 0)
         	//var_dump($bankdirect.'-'.$bankviainvoice.'-'.$invoiceonly.'-'.empty($conf->global->ADHERENT_BANK_USE));
             print "\n".'<script type="text/javascript" language="javascript">';
             print '$(document).ready(function () {
-                        $(".bankswitchclass, .bankswitchclass2").'.(($bankdirect||$bankviainvoice)?'show()':'hide()').';
+                        $(".bankswitchclass, .bankswitchclass2").'.(($bankdirect || $bankviainvoice) ? 'show()' : 'hide()').';
                         $("#none, #invoiceonly").click(function() {
                             $(".bankswitchclass").hide();
                             $(".bankswitchclass2").hide();
@@ -857,33 +857,33 @@ if ($rowid > 0)
 		// Confirm create third party
 		if ($action == 'create_thirdparty')
 		{
-			$companyalias='';
+			$companyalias = '';
 			$fullname = $object->getFullName($langs);
 
 			if ($object->morphy == 'mor')
 			{
-				$companyname=$object->company;
-				if (! empty($fullname)) $companyalias=$fullname;
+				$companyname = $object->company;
+				if (!empty($fullname)) $companyalias = $fullname;
 			}
 			else
 			{
-				$companyname=$fullname;
-				if (! empty($object->company)) $companyalias=$object->company;
+				$companyname = $fullname;
+				if (!empty($object->company)) $companyalias = $object->company;
 			}
 
 			// Create a form array
-			$formquestion=array(
+			$formquestion = array(
 				array('label' => $langs->trans("NameToCreate"), 'type' => 'text', 'name' => 'companyname', 'value' => $companyname, 'morecss' => 'minwidth300', 'moreattr' => 'maxlength="128"'),
 				array('label' => $langs->trans("AliasNames"), 'type' => 'text', 'name' => 'companyalias', 'value' => $companyalias, 'morecss' => 'minwidth300', 'moreattr' => 'maxlength="128"')
 			);
 			// If customer code was forced to "required", we ask it at creation to avoid error later
-			if (! empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED))
+			if (!empty($conf->global->MAIN_COMPANY_CODE_ALWAYS_REQUIRED))
 			{
 				$tmpcompany = new Societe($db);
-				$tmpcompany->name=$companyname;
+				$tmpcompany->name = $companyname;
                 $tmpcompany->get_codeclient($tmpcompany, 0);
 				$customercode = $tmpcompany->code_client;
-				$formquestion[]=array(
+				$formquestion[] = array(
                     'label' => $langs->trans("CustomerCode"),
                     'type' => 'text',
                     'name' => 'customercode',
@@ -910,15 +910,15 @@ if ($rowid > 0)
 		print "<table class=\"border\" width=\"100%\">\n";
         print '<tbody>';
 
-		$today=dol_now();
-        $datefrom=0;
-        $dateto=0;
-        $paymentdate=-1;
+		$today = dol_now();
+        $datefrom = 0;
+        $dateto = 0;
+        $paymentdate = -1;
 
         // Date payment
         if (GETPOST('paymentyear') && GETPOST('paymentmonth') && GETPOST('paymentday'))
         {
-            $paymentdate=dol_mktime(0, 0, 0, GETPOST('paymentmonth'), GETPOST('paymentday'), GETPOST('paymentyear'));
+            $paymentdate = dol_mktime(0, 0, 0, GETPOST('paymentmonth'), GETPOST('paymentday'), GETPOST('paymentyear'));
         }
 
         print '<tr>';
@@ -926,14 +926,14 @@ if ($rowid > 0)
         print '<td class="fieldrequired">'.$langs->trans("DateSubscription").'</td><td>';
         if (GETPOST('reday'))
         {
-            $datefrom=dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
+            $datefrom = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
         }
-        if (! $datefrom)
+        if (!$datefrom)
         {
-        	$datefrom=$object->datevalid;
+        	$datefrom = $object->datevalid;
         	if ($object->datefin > 0)
             {
-                $datefrom=dol_time_plus_duree($object->datefin, 1, 'd');
+                $datefrom = dol_time_plus_duree($object->datefin, 1, 'd');
             }
         }
         print $form->selectDate($datefrom, '', '', '', '', "subscription", 1, 1);
@@ -942,11 +942,11 @@ if ($rowid > 0)
         // Date end subscription
         if (GETPOST('endday'))
         {
-            $dateto=dol_mktime(0, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
+            $dateto = dol_mktime(0, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
         }
-        if (! $dateto)
+        if (!$dateto)
         {
-            $dateto=-1;		// By default, no date is suggested
+            $dateto = -1; // By default, no date is suggested
         }
         print '<tr><td>'.$langs->trans("DateEndSubscription").'</td><td>';
         print $form->selectDate($dateto, 'end', '', '', '', "subscription", 1, 0);
@@ -960,16 +960,16 @@ if ($rowid > 0)
             // Label
             print '<tr><td>'.$langs->trans("Label").'</td>';
             print '<td><input name="label" type="text" size="32" value="';
-            if (empty($conf->global->MEMBER_NO_DEFAULT_LABEL)) print $langs->trans("Subscription").' '.dol_print_date(($datefrom?$datefrom:time()), "%Y");
+            if (empty($conf->global->MEMBER_NO_DEFAULT_LABEL)) print $langs->trans("Subscription").' '.dol_print_date(($datefrom ? $datefrom : time()), "%Y");
             print '"></td></tr>';
 
             // Complementary action
-            if (! empty($conf->banque->enabled) || ! empty($conf->facture->enabled))
+            if (!empty($conf->banque->enabled) || !empty($conf->facture->enabled))
             {
-                $company=new Societe($db);
+                $company = new Societe($db);
                 if ($object->fk_soc)
                 {
-                    $result=$company->fetch($object->fk_soc);
+                    $result = $company->fetch($object->fk_soc);
                 }
 
                 // Title payments
@@ -979,17 +979,17 @@ if ($rowid > 0)
                 print '<tr><td class="tdtop fieldrequired">'.$langs->trans('MoreActions');
                 print '</td>';
                 print '<td>';
-                print '<input type="radio" class="moreaction" id="none" name="paymentsave" value="none"'.(empty($bankdirect) && empty($invoiceonly) && empty($bankviainvoice)?' checked':'').'> '.$langs->trans("None").'<br>';
+                print '<input type="radio" class="moreaction" id="none" name="paymentsave" value="none"'.(empty($bankdirect) && empty($invoiceonly) && empty($bankviainvoice) ? ' checked' : '').'> '.$langs->trans("None").'<br>';
                 // Add entry into bank accoun
-                if (! empty($conf->banque->enabled))
+                if (!empty($conf->banque->enabled))
                 {
-                    print '<input type="radio" class="moreaction" id="bankdirect" name="paymentsave" value="bankdirect"'.(! empty($bankdirect)?' checked':'');
+                    print '<input type="radio" class="moreaction" id="bankdirect" name="paymentsave" value="bankdirect"'.(!empty($bankdirect) ? ' checked' : '');
                     print '> '.$langs->trans("MoreActionBankDirect").'<br>';
                 }
                 // Add invoice with no payments
-                if (! empty($conf->societe->enabled) && ! empty($conf->facture->enabled))
+                if (!empty($conf->societe->enabled) && !empty($conf->facture->enabled))
                 {
-                    print '<input type="radio" class="moreaction" id="invoiceonly" name="paymentsave" value="invoiceonly"'.(! empty($invoiceonly)?' checked':'');
+                    print '<input type="radio" class="moreaction" id="invoiceonly" name="paymentsave" value="invoiceonly"'.(!empty($invoiceonly) ? ' checked' : '');
                     //if (empty($object->fk_soc)) print ' disabled';
                     print '> '.$langs->trans("MoreActionInvoiceOnly");
                     if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
@@ -1003,18 +1003,18 @@ if ($rowid > 0)
                     	print '</a>)';
                     }
                     if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. '.$langs->trans("NoVatOnSubscription", 0);
-					if (! empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (! empty($conf->product->enabled) || ! empty($conf->service->enabled)))
+					if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled)))
 					{
-						$prodtmp=new Product($db);
+						$prodtmp = new Product($db);
 						$prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS);
-						print '. '.$langs->transnoentitiesnoconv("ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS", $prodtmp->getNomUrl(1));	// must use noentitiesnoconv to avoid to encode html into getNomUrl of product
+						print '. '.$langs->transnoentitiesnoconv("ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS", $prodtmp->getNomUrl(1)); // must use noentitiesnoconv to avoid to encode html into getNomUrl of product
 					}
                     print '<br>';
                 }
                 // Add invoice with payments
-                if (! empty($conf->banque->enabled) && ! empty($conf->societe->enabled) && ! empty($conf->facture->enabled))
+                if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled))
                 {
-                    print '<input type="radio" class="moreaction" id="bankviainvoice" name="paymentsave" value="bankviainvoice"'.(! empty($bankviainvoice)?' checked':'');
+                    print '<input type="radio" class="moreaction" id="bankviainvoice" name="paymentsave" value="bankviainvoice"'.(!empty($bankviainvoice) ? ' checked' : '');
                     //if (empty($object->fk_soc)) print ' disabled';
                     print '> '.$langs->trans("MoreActionBankViaInvoice");
                     if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')';
@@ -1028,11 +1028,11 @@ if ($rowid > 0)
                     	print '</a>)';
                     }
                     if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. '.$langs->trans("NoVatOnSubscription", 0);
-					if (! empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (! empty($conf->product->enabled) || ! empty($conf->service->enabled)))
+					if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled)))
 					{
-						$prodtmp=new Product($db);
+						$prodtmp = new Product($db);
 						$prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS);
-						print '. '.$langs->transnoentitiesnoconv("ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS", $prodtmp->getNomUrl(1));	// must use noentitiesnoconv to avoid to encode html into getNomUrl of product
+						print '. '.$langs->transnoentitiesnoconv("ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS", $prodtmp->getNomUrl(1)); // must use noentitiesnoconv to avoid to encode html into getNomUrl of product
 					}
                     print '<br>';
                 }
@@ -1050,23 +1050,23 @@ if ($rowid > 0)
 
                 // Date of payment
                 print '<tr class="bankswitchclass"><td class="fieldrequired">'.$langs->trans("DatePayment").'</td><td>';
-                print $form->selectDate(isset($paymentdate)?$paymentdate:-1, 'payment', 0, 0, 1, 'subscription', 1, 1);
+                print $form->selectDate(isset($paymentdate) ? $paymentdate : -1, 'payment', 0, 0, 1, 'subscription', 1, 1);
                 print "</td></tr>\n";
 
                 print '<tr class="bankswitchclass2"><td>'.$langs->trans('Numero');
                 print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
                 print '</td>';
-                print '<td><input id="fieldnum_chq" name="num_chq" type="text" size="8" value="'.(! GETPOST('num_chq')?'':GETPOST('num_chq')).'"></td></tr>';
+                print '<td><input id="fieldnum_chq" name="num_chq" type="text" size="8" value="'.(!GETPOST('num_chq') ? '' : GETPOST('num_chq')).'"></td></tr>';
 
                 print '<tr class="bankswitchclass2 fieldrequireddyn"><td>'.$langs->trans('CheckTransmitter');
                 print ' <em>('.$langs->trans("ChequeMaker").')</em>';
                 print '</td>';
-                print '<td><input id="fieldchqemetteur" name="chqemetteur" size="32" type="text" value="'.(! GETPOST('chqemetteur')?'':GETPOST('chqemetteur')).'"></td></tr>';
+                print '<td><input id="fieldchqemetteur" name="chqemetteur" size="32" type="text" value="'.(!GETPOST('chqemetteur') ? '' : GETPOST('chqemetteur')).'"></td></tr>';
 
                 print '<tr class="bankswitchclass2"><td>'.$langs->trans('Bank');
                 print ' <em>('.$langs->trans("ChequeBank").')</em>';
                 print '</td>';
-                print '<td><input id="chqbank" name="chqbank" size="32" type="text" value="'.(! GETPOST('chqbank')?'':GETPOST('chqbank')).'"></td></tr>';
+                print '<td><input id="chqbank" name="chqbank" size="32" type="text" value="'.(!GETPOST('chqbank') ? '' : GETPOST('chqbank')).'"></td></tr>';
             }
         }
 
@@ -1074,7 +1074,7 @@ if ($rowid > 0)
 
         print '<tr><td width="30%">'.$langs->trans("SendAcknowledgementByMail").'</td>';
         print '<td>';
-        if (! $object->email)
+        if (!$object->email)
         {
             print $langs->trans("NoEMail");
         }
@@ -1085,42 +1085,42 @@ if ($rowid > 0)
 
             // Send subscription email
             $subject = '';
-            $msg= '';
+            $msg = '';
 
             // Send subscription email
             include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
-            $formmail=new FormMail($db);
+            $formmail = new FormMail($db);
             // Set output language
             $outputlangs = new Translate('', $conf);
             $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
             // Load traductions files required by page
             $outputlangs->loadLangs(array("main", "members"));
             // Get email content from template
-            $arraydefaultmessage=null;
+            $arraydefaultmessage = null;
             $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION;
 
-            if (! empty($labeltouse)) $arraydefaultmessage=$formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
+            if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
 
-            if (! empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0)
+            if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0)
             {
             	$subject = $arraydefaultmessage->topic;
             	$msg     = $arraydefaultmessage->content;
             }
 
-            $substitutionarray=getCommonSubstitutionArray($outputlangs, 0, null, $object);
+            $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
             complete_substitutions_array($substitutionarray, $outputlangs, $object);
             $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
             $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
 
-            $tmp='<input name="sendmail" type="checkbox"'.(GETPOST('sendmail', 'alpha')?' checked':(! empty($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL)?' checked':'')).'>';
-            $helpcontent='';
-            $helpcontent.='<b>'.$langs->trans("MailFrom").'</b>: '.$conf->global->ADHERENT_MAIL_FROM.'<br>'."\n";
-            $helpcontent.='<b>'.$langs->trans("MailRecipient").'</b>: '.$object->email.'<br>'."\n";
-            $helpcontent.='<b>'.$langs->trans("MailTopic").'</b>:<br>'."\n";
-            $helpcontent.=$subjecttosend."\n";
-            $helpcontent.="<br>";
-            $helpcontent.='<b>'.$langs->trans("MailText").'</b>:<br>';
-            $helpcontent.=dol_htmlentitiesbr($texttosend)."\n";
+            $tmp = '<input name="sendmail" type="checkbox"'.(GETPOST('sendmail', 'alpha') ? ' checked' : (!empty($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL) ? ' checked' : '')).'>';
+            $helpcontent = '';
+            $helpcontent .= '<b>'.$langs->trans("MailFrom").'</b>: '.$conf->global->ADHERENT_MAIL_FROM.'<br>'."\n";
+            $helpcontent .= '<b>'.$langs->trans("MailRecipient").'</b>: '.$object->email.'<br>'."\n";
+            $helpcontent .= '<b>'.$langs->trans("MailTopic").'</b>:<br>'."\n";
+            $helpcontent .= $subjecttosend."\n";
+            $helpcontent .= "<br>";
+            $helpcontent .= '<b>'.$langs->trans("MailText").'</b>:<br>';
+            $helpcontent .= dol_htmlentitiesbr($texttosend)."\n";
 
             print $form->textwithpicto($tmp, $helpcontent, 1, 'help', '', 0, 2, 'helpemailtosend');
         }

+ 178 - 178
htdocs/adherents/subscription/list.php

@@ -29,37 +29,37 @@ require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
 require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 
-$langs->loadLangs(array("members","companies"));
+$langs->loadLangs(array("members", "companies"));
 
-$action=GETPOST('action', 'aZ09');
-$massaction=GETPOST('massaction', 'alpha');
-$confirm=GETPOST('confirm', 'alpha');
+$action = GETPOST('action', 'aZ09');
+$massaction = GETPOST('massaction', 'alpha');
+$confirm = GETPOST('confirm', 'alpha');
 $toselect = GETPOST('toselect', 'array');
 
-$filter=GETPOST("filter", "alpha");
-$statut=(GETPOSTISSET("statut")?GETPOST("statut", "alpha"):1);
-$search_ref=GETPOST('search_ref', 'alpha');
-$search_type=GETPOST('search_type', 'alpha');
-$search_lastname=GETPOST('search_lastname', 'alpha');
-$search_firstname=GETPOST('search_firstname', 'alpha');
-$search_login=GETPOST('search_login', 'alpha');
-$search_note=GETPOST('search_note', 'alpha');
-$search_account=GETPOST('search_account', 'int');
-$search_amount=GETPOST('search_amount', 'alpha');
+$filter = GETPOST("filter", "alpha");
+$statut = (GETPOSTISSET("statut") ?GETPOST("statut", "alpha") : 1);
+$search_ref = GETPOST('search_ref', 'alpha');
+$search_type = GETPOST('search_type', 'alpha');
+$search_lastname = GETPOST('search_lastname', 'alpha');
+$search_firstname = GETPOST('search_firstname', 'alpha');
+$search_login = GETPOST('search_login', 'alpha');
+$search_note = GETPOST('search_note', 'alpha');
+$search_account = GETPOST('search_account', 'int');
+$search_amount = GETPOST('search_amount', 'alpha');
 $optioncss = GETPOST('optioncss', 'alpha');
 
-$date_select=GETPOST("date_select", 'alpha');
+$date_select = GETPOST("date_select", 'alpha');
 
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOST("page", 'int');
 if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
-$offset = $limit * $page ;
+$offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (! $sortorder) {  $sortorder="DESC"; }
-if (! $sortfield) {  $sortfield="c.dateadh"; }
+if (!$sortorder) {  $sortorder = "DESC"; }
+if (!$sortfield) {  $sortfield = "c.dateadh"; }
 
 $object = new Subscription($db);
 
@@ -70,19 +70,19 @@ $extrafields = new ExtraFields($db);
 // fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label($object->table_element);
 
-$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
 
 // List of fields to search into when doing a "search in all"
 $fieldstosearchall = array(
 );
-$arrayfields=array(
+$arrayfields = array(
 	'd.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1),
 	'd.fk_type'=>array('label'=>$langs->trans("Type"), 'checked'=>1),
 	'd.lastname'=>array('label'=>$langs->trans("Lastname"), 'checked'=>1),
 	'd.firstname'=>array('label'=>$langs->trans("Firstname"), 'checked'=>1),
 	'd.login'=>array('label'=>$langs->trans("Login"), 'checked'=>1),
 	't.libelle'=>array('label'=>$langs->trans("Label"), 'checked'=>1),
-	'd.bank'=>array('label'=>$langs->trans("BankAccount"), 'checked'=>1, 'enabled'=>(! empty($conf->banque->enabled))),
+	'd.bank'=>array('label'=>$langs->trans("BankAccount"), 'checked'=>1, 'enabled'=>(!empty($conf->banque->enabled))),
 	/*'d.note_public'=>array('label'=>$langs->trans("NotePublic"), 'checked'=>0),
 	 'd.note_private'=>array('label'=>$langs->trans("NotePrivate"), 'checked'=>0),*/
 	'c.dateadh'=>array('label'=>$langs->trans("DateSubscription"), 'checked'=>1, 'position'=>100),
@@ -94,18 +94,18 @@ $arrayfields=array(
 );
 
 // Security check
-$result=restrictedArea($user, 'adherent', '', '', 'cotisation');
+$result = restrictedArea($user, 'adherent', '', '', 'cotisation');
 
 
 /*
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; }
-if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; }
+if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; }
 
-$parameters=array('socid'=>$socid);
-$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
+$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 (empty($reshook))
@@ -116,17 +116,17 @@ if (empty($reshook))
     // 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
     {
-	    $search="";
-	    $search_type="";
-	    $search_ref="";
-	    $search_lastname="";
-	    $search_firstname="";
-	    $search_login="";
-	    $search_note="";
-	    $search_amount="";
-	    $search_account="";
-	    $toselect='';
-	    $search_array_options=array();
+	    $search = "";
+	    $search_type = "";
+	    $search_ref = "";
+	    $search_lastname = "";
+	    $search_firstname = "";
+	    $search_login = "";
+	    $search_note = "";
+	    $search_amount = "";
+	    $search_account = "";
+	    $toselect = '';
+	    $search_array_options = array();
     }
 }
 
@@ -135,50 +135,50 @@ if (empty($reshook))
  * View
  */
 
-$form=new Form($db);
-$subscription=new Subscription($db);
-$adherent=new Adherent($db);
-$accountstatic=new Account($db);
+$form = new Form($db);
+$subscription = new Subscription($db);
+$adherent = new Adherent($db);
+$accountstatic = new Account($db);
 
-$now=dol_now();
+$now = dol_now();
 
 // List of subscriptions
 $sql = "SELECT d.rowid, d.login, d.firstname, d.lastname, d.societe, d.photo, d.statut,";
-$sql.= " c.rowid as crowid, c.fk_type, c.subscription,";
-$sql.= " c.dateadh, c.datef, c.datec as date_creation, c.tms as date_update,";
-$sql.= " c.fk_bank as bank, c.note,";
-$sql.= " b.fk_account";
-$sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."subscription as c";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON c.fk_bank=b.rowid";
-$sql.= " WHERE d.rowid = c.fk_adherent";
-$sql.= " AND d.entity IN (".getEntity('adherent').")";
+$sql .= " c.rowid as crowid, c.fk_type, c.subscription,";
+$sql .= " c.dateadh, c.datef, c.datec as date_creation, c.tms as date_update,";
+$sql .= " c.fk_bank as bank, c.note,";
+$sql .= " b.fk_account";
+$sql .= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."subscription as c";
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON c.fk_bank=b.rowid";
+$sql .= " WHERE d.rowid = c.fk_adherent";
+$sql .= " AND d.entity IN (".getEntity('adherent').")";
 if (isset($date_select) && $date_select != '')
 {
-    $sql.= " AND c.dateadh >= '".$date_select."-01-01 00:00:00'";
-    $sql.= " AND c.dateadh < '".($date_select+1)."-01-01 00:00:00'";
+    $sql .= " AND c.dateadh >= '".$date_select."-01-01 00:00:00'";
+    $sql .= " AND c.dateadh < '".($date_select + 1)."-01-01 00:00:00'";
 }
 if ($search_ref)
 {
-	if (is_numeric($search_ref)) $sql.= " AND (c.rowid = ".$db->escape($search_ref).")";
-	else $sql.=" AND 1 = 2";    // Always wrong
+	if (is_numeric($search_ref)) $sql .= " AND (c.rowid = ".$db->escape($search_ref).")";
+	else $sql .= " AND 1 = 2"; // Always wrong
 }
-if ($search_type) $sql.= natural_search(array('c.fk_type'), $search_type);
-if ($search_lastname) $sql.= natural_search(array('d.lastname','d.societe'), $search_lastname);
-if ($search_firstname) $sql.= natural_search(array('d.firstname'), $search_firstname);
-if ($search_login) $sql.= natural_search('d.login', $search_login);
-if ($search_note)  $sql.= natural_search('c.note', $search_note);
-if ($search_account > 0) $sql.= " AND b.fk_account = ".urldecode($search_account);
-if ($search_amount) $sql.= natural_search('c.subscription', $search_amount, 1);
+if ($search_type) $sql .= natural_search(array('c.fk_type'), $search_type);
+if ($search_lastname) $sql .= natural_search(array('d.lastname', 'd.societe'), $search_lastname);
+if ($search_firstname) $sql .= natural_search(array('d.firstname'), $search_firstname);
+if ($search_login) $sql .= natural_search('d.login', $search_login);
+if ($search_note)  $sql .= natural_search('c.note', $search_note);
+if ($search_account > 0) $sql .= " AND b.fk_account = ".urldecode($search_account);
+if ($search_amount) $sql .= natural_search('c.subscription', $search_amount, 1);
 
 // 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);    // Note that $action and $object may have been modified by hook
-$sql.=$hookmanager->resPrint;
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
+$sql .= $hookmanager->resPrint;
 
-$sql.= $db->order($sortfield, $sortorder);
+$sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records with no order and no limits
 $nbtotalofrecords = '';
@@ -194,10 +194,10 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
     }
 }
 // Add limit
-$sql.= $db->plimit($limit+1, $offset);
+$sql .= $db->plimit($limit + 1, $offset);
 
 $result = $db->query($sql);
-if (! $result)
+if (!$result)
 {
 	dol_print_error($db);
 	exit;
@@ -205,9 +205,9 @@ if (! $result)
 
 $num = $db->num_rows($result);
 
-$arrayofselected=is_array($toselect)?$toselect:array();
+$arrayofselected = is_array($toselect) ? $toselect : array();
 
-if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall)
+if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall)
 {
 	$obj = $db->fetch_object($resql);
 	$id = $obj->rowid;
@@ -219,36 +219,36 @@ llxHeader('', $langs->trans("ListOfSubscriptions"), 'EN:Module_Foundations|FR:Mo
 
 $i = 0;
 
-$title=$langs->trans("ListOfSubscriptions");
-if (! empty($date_select)) $title.=' ('.$langs->trans("Year").' '.$date_select.')';
-
-$param='';
-if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
-if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
-if ($statut != '')    $param.="&statut=".urlencode($statut);
-if ($search_type)     $param.="&search_type=".urlencode($search_type);
-if ($date_select)     $param.="&date_select=".urlencode($date_select);
-if ($search_lastname) $param.="&search_lastname=".urlencode($search_lastname);
-if ($search_login)    $param.="&search_login=".urlencode($search_login);
-if ($search_account)  $param.="&search_account=".urlencode($search_account);
-if ($search_amount)   $param.="&search_amount=".urlencode($search_amount);
-if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss);
+$title = $langs->trans("ListOfSubscriptions");
+if (!empty($date_select)) $title .= ' ('.$langs->trans("Year").' '.$date_select.')';
+
+$param = '';
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
+if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+if ($statut != '')    $param .= "&statut=".urlencode($statut);
+if ($search_type)     $param .= "&search_type=".urlencode($search_type);
+if ($date_select)     $param .= "&date_select=".urlencode($date_select);
+if ($search_lastname) $param .= "&search_lastname=".urlencode($search_lastname);
+if ($search_login)    $param .= "&search_login=".urlencode($search_login);
+if ($search_account)  $param .= "&search_account=".urlencode($search_account);
+if ($search_amount)   $param .= "&search_amount=".urlencode($search_amount);
+if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
 // Add $param from extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 
 // List of mass actions available
-$arrayofmassactions =  array(
+$arrayofmassactions = array(
 	//'presend'=>$langs->trans("SendByMail"),
 	//'builddoc'=>$langs->trans("PDFMerge"),
 );
 //if ($user->rights->adherent->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
-if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
-$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
+if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
+$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
 
-$newcardbutton='';
+$newcardbutton = '';
 if ($user->rights->adherent->cotisation->creer)
 {
-    $newcardbutton.= dolGetButtonTitle($langs->trans('NewSubscription'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/adherents/list.php?status=-1,1');
+    $newcardbutton .= dolGetButtonTitle($langs->trans('NewSubscription'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/adherents/list.php?status=-1,1');
 }
 
 print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
@@ -264,95 +264,95 @@ print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
 
 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'members', 0, $newcardbutton, '', $limit);
 
-$topicmail="Information";
-$modelmail="subscription";
-$objecttmp=new Subscription($db);
-$trackid='sub'.$object->id;
+$topicmail = "Information";
+$modelmail = "subscription";
+$objecttmp = new Subscription($db);
+$trackid = 'sub'.$object->id;
 include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
 
 if ($sall)
 {
-	foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
-	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'</div>';
+	foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
+	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
 }
 
 $moreforfilter = '';
 
-$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);
+$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);
 
 print '<div class="div-table-responsive">';
-print '<table class="tagtable nobottomiftotal liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
+print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
 
 
 // Line for filters fields
 print '<tr class="liste_titre_filter">';
 
 // Line numbering
-if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID))
+if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID))
 {
 	print '<td class="liste_titre">&nbsp;</td>';
 }
 
 // Ref
-if (! empty($arrayfields['d.ref']['checked']))
+if (!empty($arrayfields['d.ref']['checked']))
 {
 	print '<td class="liste_titre left">';
 	print '<input class="flat maxwidth50" type="text" name="search_ref" value="'.dol_escape_htmltag($search_ref).'"></td>';
 }
 
 // Type
-if (! empty($arrayfields['d.fk_type']['checked']))
+if (!empty($arrayfields['d.fk_type']['checked']))
 {
 	print '<td class="liste_titre left">';
 	print '<input class="flat maxwidth50" type="text" name="search_type" value="'.dol_escape_htmltag($search_type).'">';
 	print'</td>';
 }
 
-if (! empty($arrayfields['d.lastname']['checked']))
+if (!empty($arrayfields['d.lastname']['checked']))
 {
 	print '<td class="liste_titre left">';
 	print '<input class="flat maxwidth75" type="text" name="search_lastname" value="'.dol_escape_htmltag($search_lastname).'"></td>';
 }
 
-if (! empty($arrayfields['d.firstname']['checked']))
+if (!empty($arrayfields['d.firstname']['checked']))
 {
 	print '<td class="liste_titre left">';
 	print '<input class="flat maxwidth75" type="text" name="search_firstname" value="'.dol_escape_htmltag($search_firstname).'"></td>';
 }
 
-if (! empty($arrayfields['d.login']['checked']))
+if (!empty($arrayfields['d.login']['checked']))
 {
 	print '<td class="liste_titre left">';
 	print '<input class="flat maxwidth75" type="text" name="search_login" value="'.dol_escape_htmltag($search_login).'"></td>';
 }
 
-if (! empty($arrayfields['t.libelle']['checked']))
+if (!empty($arrayfields['t.libelle']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '';
 	print '</td>';
 }
 
-if (! empty($arrayfields['d.bank']['checked']))
+if (!empty($arrayfields['d.bank']['checked']))
 {
 	print '<td class="liste_titre">';
 	$form->select_comptes($search_account, 'search_account', 0, '', 1);
 	print '</td>';
 }
 
-if (! empty($arrayfields['c.dateadh']['checked']))
+if (!empty($arrayfields['c.dateadh']['checked']))
 {
 	print '<td class="liste_titre">&nbsp;</td>';
 }
 
-if (! empty($arrayfields['c.datef']['checked']))
+if (!empty($arrayfields['c.datef']['checked']))
 {
 	print '<td class="liste_titre">&nbsp;</td>';
 }
 
-if (! empty($arrayfields['d.amount']['checked']))
+if (!empty($arrayfields['d.amount']['checked']))
 {
 	print '<td class="liste_titre right">';
 	print '<input class="flat" type="text" name="search_amount" value="'.dol_escape_htmltag($search_amount).'" size="4">';
@@ -362,17 +362,17 @@ if (! empty($arrayfields['d.amount']['checked']))
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
 
 // Fields from hook
-$parameters=array('arrayfields'=>$arrayfields);
-$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters);    // Note that $action and $object may have been modified by hook
+$parameters = array('arrayfields'=>$arrayfields);
+$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
 print $hookmanager->resPrint;
 // Date creation
-if (! empty($arrayfields['c.datec']['checked']))
+if (!empty($arrayfields['c.datec']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '</td>';
 }
 // Date modification
-if (! empty($arrayfields['c.tms']['checked']))
+if (!empty($arrayfields['c.tms']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '</td>';
@@ -380,7 +380,7 @@ if (! empty($arrayfields['c.tms']['checked']))
 
 // Action column
 print '<td class="liste_titre right">';
-$searchpicto=$form->showFilterButtons();
+$searchpicto = $form->showFilterButtons();
 print $searchpicto;
 print '</td>';
 
@@ -388,43 +388,43 @@ print "</tr>\n";
 
 
 print '<tr class="liste_titre">';
-if (! empty($arrayfields['d.ref']['checked']))
+if (!empty($arrayfields['d.ref']['checked']))
 {
 	print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "c.rowid", $param, "", "", $sortfield, $sortorder);
 }
-if (! empty($arrayfields['d.fk_type']['checked']))
+if (!empty($arrayfields['d.fk_type']['checked']))
 {
 	print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "c.fk_type", $param, "", "", $sortfield, $sortorder);
 }
-if (! empty($arrayfields['d.lastname']['checked']))
+if (!empty($arrayfields['d.lastname']['checked']))
 {
 	print_liste_field_titre("LastName", $_SERVER["PHP_SELF"], "d.lastname", $param, "", "", $sortfield, $sortorder);
 }
-if (! empty($arrayfields['d.firstname']['checked']))
+if (!empty($arrayfields['d.firstname']['checked']))
 {
 	print_liste_field_titre("FirstName", $_SERVER["PHP_SELF"], "d.firstname", $param, "", "", $sortfield, $sortorder);
 }
-if (! empty($arrayfields['d.login']['checked']))
+if (!empty($arrayfields['d.login']['checked']))
 {
 	print_liste_field_titre("Login", $_SERVER["PHP_SELF"], "d.login", $param, "", "", $sortfield, $sortorder);
 }
-if (! empty($arrayfields['t.libelle']['checked']))
+if (!empty($arrayfields['t.libelle']['checked']))
 {
 	print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "c.note", $param, "", '', $sortfield, $sortorder);
 }
-if (! empty($arrayfields['d.bank']['checked']))
+if (!empty($arrayfields['d.bank']['checked']))
 {
 	print_liste_field_titre("Account", $_SERVER["PHP_SELF"], "b.fk_account", $param, "", "", $sortfield, $sortorder);
 }
-if (! empty($arrayfields['c.dateadh']['checked']))
+if (!empty($arrayfields['c.dateadh']['checked']))
 {
 	print_liste_field_titre("DateStart", $_SERVER["PHP_SELF"], "c.dateadh", $param, "", '', $sortfield, $sortorder, 'center nowraponall ');
 }
-if (! empty($arrayfields['c.datef']['checked']))
+if (!empty($arrayfields['c.datef']['checked']))
 {
 	print_liste_field_titre("DateEnd", $_SERVER["PHP_SELF"], "c.datef", $param, "", '', $sortfield, $sortorder, 'center nowraponall ');
 }
-if (! empty($arrayfields['d.amount']['checked']))
+if (!empty($arrayfields['d.amount']['checked']))
 {
 	print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "c.subscription", $param, "", '', $sortfield, $sortorder, 'right ');
 }
@@ -432,33 +432,33 @@ if (! empty($arrayfields['d.amount']['checked']))
 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);    // Note that $action and $object may have been modified by hook
+$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['c.datec']['checked']))     print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
-if (! empty($arrayfields['c.tms']['checked']))       print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
+if (!empty($arrayfields['c.datec']['checked']))     print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
+if (!empty($arrayfields['c.tms']['checked']))       print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder);
 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ');
 print "</tr>\n";
 
 
-$total=0;
-$totalarray=array();
+$total = 0;
+$totalarray = array();
 while ($i < min($num, $limit))
 {
 	$obj = $db->fetch_object($result);
-	$total+=$obj->subscription;
+	$total += $obj->subscription;
 
-	$subscription->ref=$obj->crowid;
-	$subscription->id=$obj->crowid;
+	$subscription->ref = $obj->crowid;
+	$subscription->id = $obj->crowid;
 
-	$adherent->lastname=$obj->lastname;
-	$adherent->firstname=$obj->firstname;
-	$adherent->ref=$obj->rowid;
-	$adherent->id=$obj->rowid;
-	$adherent->statut=$obj->statut;
-	$adherent->login=$obj->login;
-	$adherent->photo=$obj->photo;
-	$adherent->typeid=$obj->type;
+	$adherent->lastname = $obj->lastname;
+	$adherent->firstname = $obj->firstname;
+	$adherent->ref = $obj->rowid;
+	$adherent->id = $obj->rowid;
+	$adherent->statut = $obj->statut;
+	$adherent->login = $obj->login;
+	$adherent->photo = $obj->photo;
+	$adherent->typeid = $obj->type;
 
 	$typeid = ($obj->fk_type > 0 ? $obj->fk_type : $adherent->typeid);
     $adht = new AdherentType($db);
@@ -467,13 +467,13 @@ while ($i < min($num, $limit))
 	print '<tr class="oddeven">';
 
 	// Ref
-	if (! empty($arrayfields['d.ref']['checked']))
+	if (!empty($arrayfields['d.ref']['checked']))
 	{
 		print '<td>'.$subscription->getNomUrl(1).'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
     // Type
-    if (! empty($arrayfields['d.fk_type']['checked']))
+    if (!empty($arrayfields['d.fk_type']['checked']))
 	{
         print '<td>';
         if ($typeid > 0)
@@ -481,107 +481,107 @@ while ($i < min($num, $limit))
         	print $adht->getNomUrl(1);
         }
         print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
 
 	// Lastname
-	if (! empty($arrayfields['d.lastname']['checked']))
+	if (!empty($arrayfields['d.lastname']['checked']))
 	{
 		$adherent->firstname = '';
 		print '<td>'.$adherent->getNomUrl(-1).'</td>';
 		$adherent->firstname = $obj->firstname;
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 	// Firstname
-	if (! empty($arrayfields['d.firstname']['checked']))
+	if (!empty($arrayfields['d.firstname']['checked']))
 	{
 		print '<td>'.$adherent->firstname.'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 
 	// Login
-	if (! empty($arrayfields['d.login']['checked']))
+	if (!empty($arrayfields['d.login']['checked']))
 	{
 		print '<td>'.$adherent->login.'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 
 	// Label
-	if (! empty($arrayfields['t.libelle']['checked']))
+	if (!empty($arrayfields['t.libelle']['checked']))
 	{
 		print '<td>';
 		print dol_trunc($obj->note, 128);
 		print '</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 
 	// Banque
-	if (! empty($arrayfields['d.bank']['checked']))
+	if (!empty($arrayfields['d.bank']['checked']))
 	{
 		print "<td>";
 		if ($obj->fk_account > 0)
 		{
-			$accountstatic->id=$obj->fk_account;
+			$accountstatic->id = $obj->fk_account;
 			$accountstatic->fetch($obj->fk_account);
 			//$accountstatic->label=$obj->label;
 			print $accountstatic->getNomUrl(1);
 		}
 		print "</td>\n";
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 
 	// Date start
-	if (! empty($arrayfields['c.dateadh']['checked']))
+	if (!empty($arrayfields['c.dateadh']['checked']))
 	{
 		print '<td class="center">'.dol_print_date($db->jdate($obj->dateadh), 'day')."</td>\n";
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 	// Date end
-	if (! empty($arrayfields['c.datef']['checked']))
+	if (!empty($arrayfields['c.datef']['checked']))
 	{
 		print '<td class="center">'.dol_print_date($db->jdate($obj->datef), 'day')."</td>\n";
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 	// Price
-	if (! empty($arrayfields['d.amount']['checked']))
+	if (!empty($arrayfields['d.amount']['checked']))
 	{
 		print '<td class="right">'.price($obj->subscription).'</td>';
-		if (! $i) $totalarray['nbfield']++;
-		if (! $i) $totalarray['pos'][$totalarray['nbfield']]='d.amount';
+		if (!$i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'd.amount';
 		$totalarray['val']['d.amount'] += $obj->subscription;
 	}
 	// Extra fields
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
 	// Fields from hook
-	$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
-	$reshook=$hookmanager->executeHooks('printFieldListValue', $parameters);    // Note that $action and $object may have been modified by hook
+	$parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj);
+	$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
 	print $hookmanager->resPrint;
 	// Date creation
-	if (! empty($arrayfields['c.datec']['checked']))
+	if (!empty($arrayfields['c.datec']['checked']))
 	{
 		print '<td class="nowrap center">';
 		print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser');
 		print '</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 	// Date modification
-	if (! empty($arrayfields['c.tms']['checked']))
+	if (!empty($arrayfields['c.tms']['checked']))
 	{
 		print '<td class="nowrap center">';
 		print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
 		print '</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 	// Action column
 	print '<td class="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($obj->rowid, $arrayofselected)) $selected=1;
-		print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected?' checked="checked"':'').'>';
+		$selected = 0;
+		if (in_array($obj->rowid, $arrayofselected)) $selected = 1;
+		print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
 	}
 	print '</td>';
-	if (! $i) $totalarray['nbfield']++;
+	if (!$i) $totalarray['nbfield']++;
 
 	print "</tr>\n";
 	$i++;
@@ -594,15 +594,15 @@ 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++; }
+	$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('sql' => $sql);
-$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters);    // Note that $action and $object may have been modified by hook
+$parameters = array('sql' => $sql);
+$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook
 print $hookmanager->resPrint;
 
 print "</table>";

+ 48 - 48
htdocs/adherents/type.php

@@ -80,16 +80,16 @@ $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
 {
-    $search_lastname="";
-    $search_login="";
-    $search_email="";
-    $type="";
-    $sall="";
+    $search_lastname = "";
+    $search_login = "";
+    $search_email = "";
+    $type = "";
+    $sall = "";
 }
 
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('membertypecard','globalcard'));
+$hookmanager->initHooks(array('membertypecard', 'globalcard'));
 
 
 /*
@@ -137,9 +137,9 @@ if ($action == 'add' && $user->rights->adherent->configurer) {
 		}
 	}
 
-	if (! $error)
+	if (!$error)
 	{
-		$id=$object->create($user);
+		$id = $object->create($user);
 		if ($id > 0)
 		{
 			header("Location: ".$_SERVER["PHP_SELF"]);
@@ -195,7 +195,7 @@ if ($action == 'update' && $user->rights->adherent->configurer)
 if ($action == 'confirm_delete' && $user->rights->adherent->configurer)
 {
 	$object->fetch($rowid);
-	$res=$object->delete();
+	$res = $object->delete();
 
 	if ($res > 0)
 	{
@@ -206,7 +206,7 @@ if ($action == 'confirm_delete' && $user->rights->adherent->configurer)
 	else
 	{
 		setEventMessages($langs->trans("MemberTypeCanNotBeDeleted"), null, 'errors');
-		$action='';
+		$action = '';
 	}
 }
 
@@ -240,10 +240,10 @@ if (! $rowid && $action != 'create' && $action != 'edit')
 
 		$param = '';
 
-		$newcardbutton='';
+		$newcardbutton = '';
 		if ($user->rights->adherent->configurer)
 		{
-            $newcardbutton.= dolGetButtonTitle($langs->trans('NewMemberType'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/adherents/type.php?action=create');
+            $newcardbutton .= dolGetButtonTitle($langs->trans('NewMemberType'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/adherents/type.php?action=create');
         }
 
 		print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@@ -260,7 +260,7 @@ if (! $rowid && $action != 'create' && $action != 'edit')
 		$moreforfilter = '';
 
 		print '<div class="div-table-responsive">';
-		print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
+		print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
 
 		print '<tr class="liste_titre">';
 		print '<th>'.$langs->trans("Ref").'</th>';
@@ -295,7 +295,7 @@ if (! $rowid && $action != 'create' && $action != 'edit')
 			print '<td class="center">'.yn($objp->subscription).'</td>';
 			print '<td class="center">'.yn($objp->vote).'</td>';
 			print '<td class="center">';
-            if ( !empty($objp->statut) ) {
+            if (!empty($objp->statut)) {
                 print img_picto($langs->trans("InActivity"), 'statut4');
             } else {
                 print img_picto($langs->trans("ActivityCeased"), 'statut5');
@@ -343,7 +343,7 @@ if ($action == 'create')
 	print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Label").'</td><td><input type="text" class="minwidth200" name="label" autofocus="autofocus"></td></tr>';
 
 	print '<tr><td>'.$langs->trans("Status").'</td><td>';
-  	print $form->selectarray('statut', array('0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')), 1);
+  	print $form->selectarray('statut', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), 1);
   	print '</td></tr>';
 
     // Morphy
@@ -351,7 +351,7 @@ if ($action == 'create')
     $morphys["phy"] = $langs->trans("Physical");
 	$morphys["mor"] = $langs->trans("Moral");
 	print '<tr><td><span>'.$langs->trans("MemberNature").'</span></td><td>';
-	print $form->selectarray("morphy", $morphys, isset($_POST["morphy"])?$_POST["morphy"]:$object->morphy);
+	print $form->selectarray("morphy", $morphys, isset($_POST["morphy"]) ? $_POST["morphy"] : $object->morphy);
 	print "</td></tr>";
 
   	print '<tr><td>'.$langs->trans("SubscriptionRequired").'</td><td>';
@@ -372,13 +372,13 @@ if ($action == 'create')
 
 	print '<tr><td class="tdtop">'.$langs->trans("WelcomeEMail").'</td><td>';
 	require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-	$doleditor=new DolEditor('mail_valid', $object->mail_valid, '', 280, 'dolibarr_notes', '', false, true, $conf->fckeditor->enabled, 15, '90%');
+	$doleditor = new DolEditor('mail_valid', $object->mail_valid, '', 280, 'dolibarr_notes', '', false, true, $conf->fckeditor->enabled, 15, '90%');
 	$doleditor->Create();
 	print '</td></tr>';
 
 	// Other attributes
-	$parameters=array();
-	$reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $act, $action);    // Note that $action and $object may have been modified by hook
+	$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))
 	{
@@ -433,7 +433,7 @@ if ($rowid > 0)
 		print '<table class="border centpercent">';
 
    		print '<tr><td class="titlefield">'.$langs->trans("Status").'</td><td>';
-        if ( !empty($object->statut) ) {
+        if (!empty($object->statut)) {
             print img_picto($langs->trans('TypeStatusActive'), 'statut4').' '.$langs->trans("InActivity");
         } else {
             print img_picto($langs->trans('TypeStatusInactive'), 'statut5').' '.$langs->trans("ActivityCeased");
@@ -471,7 +471,7 @@ if ($rowid > 0)
 		print nl2br($object->mail_valid)."</td></tr>";
 
 		// Other attributes
-		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
 		print '</table>';
 		print '</div>';
@@ -491,7 +491,7 @@ if ($rowid > 0)
 		}
 
 		// Add
-        if ( $user->rights->adherent->configurer && !empty($object->statut) )
+        if ($user->rights->adherent->configurer && !empty($object->statut))
 		{
             print '<div class="inline-block divButAction"><a class="butAction" href="card.php?action=create&typeid='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?rowid='.$object->id).'">'.$langs->trans("AddMember").'</a></div>';
         } else {
@@ -573,7 +573,7 @@ if ($rowid > 0)
 		    }
 		}
 
-		$sql.= " ".$db->plimit($conf->liste_limit+1, $offset);
+		$sql .= " ".$db->plimit($conf->liste_limit + 1, $offset);
 
 		$resql = $db->query($sql);
 		if ($resql)
@@ -581,35 +581,35 @@ if ($rowid > 0)
 		    $num = $db->num_rows($resql);
 		    $i = 0;
 
-		    $titre=$langs->trans("MembersList");
+		    $titre = $langs->trans("MembersList");
 		    if ($status != '')
 		    {
-		        if ($status == '-1,1')								{ $titre=$langs->trans("MembersListQualified"); }
-		        elseif ($status == '-1')							{ $titre=$langs->trans("MembersListToValid"); }
-		        elseif ($status == '1' && ! $filter)				{ $titre=$langs->trans("MembersListValid"); }
-		        elseif ($status == '1' && $filter=='uptodate')		{ $titre=$langs->trans("MembersListUpToDate"); }
-		        elseif ($status == '1' && $filter=='outofdate')	{ $titre=$langs->trans("MembersListNotUpToDate"); }
-		        elseif ($status == '0')							{ $titre=$langs->trans("MembersListResiliated"); }
+		        if ($status == '-1,1') { $titre = $langs->trans("MembersListQualified"); }
+		        elseif ($status == '-1') { $titre = $langs->trans("MembersListToValid"); }
+		        elseif ($status == '1' && !$filter) { $titre = $langs->trans("MembersListValid"); }
+		        elseif ($status == '1' && $filter == 'uptodate') { $titre = $langs->trans("MembersListUpToDate"); }
+		        elseif ($status == '1' && $filter == 'outofdate') { $titre = $langs->trans("MembersListNotUpToDate"); }
+		        elseif ($status == '0') { $titre = $langs->trans("MembersListResiliated"); }
 		    }
 		    elseif ($action == 'search')
 		    {
-		        $titre=$langs->trans("MembersListQualified");
+		        $titre = $langs->trans("MembersListQualified");
 		    }
 
 		    if ($type > 0)
 		    {
-				$membertype=new AdherentType($db);
-		        $result=$membertype->fetch($type);
-				$titre.=" (".$membertype->label.")";
+				$membertype = new AdherentType($db);
+		        $result = $membertype->fetch($type);
+				$titre .= " (".$membertype->label.")";
 		    }
 
-		    $param="&rowid=".$object->id;
-		    if (! empty($status))			$param.="&status=".$status;
-		    if (! empty($search_lastname))	$param.="&search_lastname=".$search_lastname;
-		    if (! empty($search_firstname))	$param.="&search_firstname=".$search_firstname;
-		    if (! empty($search_login))		$param.="&search_login=".$search_login;
-		    if (! empty($search_email))		$param.="&search_email=".$search_email;
-		    if (! empty($filter))			$param.="&filter=".$filter;
+		    $param = "&rowid=".$object->id;
+		    if (!empty($status))			$param .= "&status=".$status;
+		    if (!empty($search_lastname))	$param .= "&search_lastname=".$search_lastname;
+		    if (!empty($search_firstname))	$param .= "&search_firstname=".$search_firstname;
+		    if (!empty($search_login))		$param .= "&search_login=".$search_login;
+		    if (!empty($search_email))		$param .= "&search_email=".$search_email;
+		    if (!empty($filter))			$param .= "&filter=".$filter;
 
 		    if ($sall)
 		    {
@@ -626,7 +626,7 @@ if ($rowid > 0)
             $moreforfilter = '';
 
             print '<div class="div-table-responsive">';
-            print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
+            print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
 
             // Fields title search
 			print '<tr class="liste_titre_filter">';
@@ -666,11 +666,11 @@ if ($rowid > 0)
 		    {
 		        $objp = $db->fetch_object($resql);
 
-		        $datefin=$db->jdate($objp->datefin);
+		        $datefin = $db->jdate($objp->datefin);
 
-		        $adh=new Adherent($db);
-		        $adh->lastname=$objp->lastname;
-		        $adh->firstname=$objp->firstname;
+		        $adh = new Adherent($db);
+		        $adh->lastname = $objp->lastname;
+		        $adh->firstname = $objp->firstname;
 
 		        // Lastname
 		        print '<tr class="oddeven">';
@@ -794,7 +794,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>';
 
 		print '<tr><td>'.$langs->trans("Status").'</td><td>';
-    	print $form->selectarray('statut', array('0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')), $object->statut);
+    	print $form->selectarray('statut', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), $object->statut);
     	print '</td></tr>';
 
         // Morphy
@@ -802,7 +802,7 @@ if ($rowid > 0)
         $morphys["phy"] = $langs->trans("Physical");
         $morphys["mor"] = $langs->trans("Moral");
         print '<tr><td><span>'.$langs->trans("MemberNature").'</span></td><td>';
-        print $form->selectarray("morphy", $morphys, isset($_POST["morphy"])?$_POST["morphy"]:$object->morphy);
+        print $form->selectarray("morphy", $morphys, isset($_POST["morphy"]) ? $_POST["morphy"] : $object->morphy);
         print "</td></tr>";
 
     	print '<tr><td>'.$langs->trans("SubscriptionRequired").'</td><td>';

+ 35 - 35
htdocs/admin/agenda_xcal.php

@@ -33,22 +33,22 @@ if (!$user->admin)
     accessforbidden();
 
 // Load translation files required by the page
-$langs->loadLangs(array("admin","other","agenda"));
+$langs->loadLangs(array("admin", "other", "agenda"));
 
 $def = array();
-$actionsave=GETPOST('save', 'alpha');
+$actionsave = GETPOST('save', 'alpha');
 
 // Sauvegardes parametres
 if ($actionsave)
 {
-    $i=0;
+    $i = 0;
 
     $db->begin();
 
-    $i+=dolibarr_set_const($db, 'MAIN_AGENDA_XCAL_EXPORTKEY', trim(GETPOST('MAIN_AGENDA_XCAL_EXPORTKEY', 'alpha')), 'chaine', 0, '', $conf->entity);
-    $i+=dolibarr_set_const($db, 'MAIN_AGENDA_EXPORT_PAST_DELAY', trim(GETPOST('MAIN_AGENDA_EXPORT_PAST_DELAY', 'alpha')), 'chaine', 0, '', $conf->entity);
-    $i+=dolibarr_set_const($db, 'MAIN_AGENDA_EXPORT_CACHE', trim(GETPOST('MAIN_AGENDA_EXPORT_CACHE', 'alpha')), 'chaine', 0, '', $conf->entity);
-    $i+=dolibarr_set_const($db, 'AGENDA_EXPORT_FIX_TZ', trim(GETPOST('AGENDA_EXPORT_FIX_TZ', 'alpha')), 'chaine', 0, '', $conf->entity);
+    $i += dolibarr_set_const($db, 'MAIN_AGENDA_XCAL_EXPORTKEY', trim(GETPOST('MAIN_AGENDA_XCAL_EXPORTKEY', 'alpha')), 'chaine', 0, '', $conf->entity);
+    $i += dolibarr_set_const($db, 'MAIN_AGENDA_EXPORT_PAST_DELAY', trim(GETPOST('MAIN_AGENDA_EXPORT_PAST_DELAY', 'alpha')), 'chaine', 0, '', $conf->entity);
+    $i += dolibarr_set_const($db, 'MAIN_AGENDA_EXPORT_CACHE', trim(GETPOST('MAIN_AGENDA_EXPORT_CACHE', 'alpha')), 'chaine', 0, '', $conf->entity);
+    $i += dolibarr_set_const($db, 'AGENDA_EXPORT_FIX_TZ', trim(GETPOST('AGENDA_EXPORT_FIX_TZ', 'alpha')), 'chaine', 0, '', $conf->entity);
 
     if ($i >= 4)
     {
@@ -68,19 +68,19 @@ if ($actionsave)
  * View
  */
 
-if (! isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY=100;
+if (!isset($conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)) $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY = 100;
 
-$wikihelp='EN:Module_Agenda_En|FR:Module_Agenda|ES:Módulo_Agenda';
+$wikihelp = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:Módulo_Agenda';
 llxHeader('', $langs->trans("AgendaSetup"), $wikihelp);
 
-$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
+$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
 print load_fiche_titre($langs->trans("AgendaSetup"), $linkback, 'title_setup');
 
 
 print '<form name="agendasetupform" action="'.$_SERVER["PHP_SELF"].'" method="post">';
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 
-$head=agenda_prepare_head();
+$head = agenda_prepare_head();
 
 dol_fiche_head($head, 'xcal', $langs->trans("Agenda"), -1, 'action');
 
@@ -98,8 +98,8 @@ print "</tr>";
 
 print '<tr class="oddeven">';
 print '<td class="fieldrequired">'.$langs->trans("PasswordTogetVCalExport")."</td>";
-print '<td><input required="required" type="text" class="flat" id="MAIN_AGENDA_XCAL_EXPORTKEY" name="MAIN_AGENDA_XCAL_EXPORTKEY" value="' . (GETPOST('MAIN_AGENDA_XCAL_EXPORTKEY', 'alpha')?GETPOST('MAIN_AGENDA_XCAL_EXPORTKEY', 'alpha'):$conf->global->MAIN_AGENDA_XCAL_EXPORTKEY) . '" size="40">';
-if (! empty($conf->use_javascript_ajax))
+print '<td><input required="required" type="text" class="flat" id="MAIN_AGENDA_XCAL_EXPORTKEY" name="MAIN_AGENDA_XCAL_EXPORTKEY" value="'.(GETPOST('MAIN_AGENDA_XCAL_EXPORTKEY', 'alpha') ?GETPOST('MAIN_AGENDA_XCAL_EXPORTKEY', 'alpha') : $conf->global->MAIN_AGENDA_XCAL_EXPORTKEY).'" size="40">';
+if (!empty($conf->use_javascript_ajax))
 	print '&nbsp;'.img_picto($langs->trans('Generate'), 'refresh', 'id="generate_token" class="linkobject"');
 print '</td>';
 print "<td>&nbsp;</td>";
@@ -107,13 +107,13 @@ print "</tr>";
 
 print '<tr class="oddeven">';
 print "<td>".$langs->trans("PastDelayVCalExport")."</td>";
-print "<td><input type=\"text\" class=\"flat\" name=\"MAIN_AGENDA_EXPORT_PAST_DELAY\" value=\"". (GETPOST('MAIN_AGENDA_EXPORT_PAST_DELAY', 'alpha')?GETPOST('MAIN_AGENDA_EXPORT_PAST_DELAY', 'alpha'):$conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY) . "\" size=\"10\"> ".$langs->trans("days")."</td>";
+print "<td><input type=\"text\" class=\"flat\" name=\"MAIN_AGENDA_EXPORT_PAST_DELAY\" value=\"".(GETPOST('MAIN_AGENDA_EXPORT_PAST_DELAY', 'alpha') ?GETPOST('MAIN_AGENDA_EXPORT_PAST_DELAY', 'alpha') : $conf->global->MAIN_AGENDA_EXPORT_PAST_DELAY)."\" size=\"10\"> ".$langs->trans("days")."</td>";
 print "<td>&nbsp;</td>";
 print "</tr>";
 
 print '<tr class="oddeven">';
 print "<td>".$langs->trans("UseACacheDelay")."</td>";
-print "<td><input type=\"text\" class=\"flat\" name=\"MAIN_AGENDA_EXPORT_CACHE\" value=\"". (GETPOST('MAIN_AGENDA_EXPORT_CACHE', 'alpha')?GETPOST('MAIN_AGENDA_EXPORT_CACHE', 'alpha'):$conf->global->MAIN_AGENDA_EXPORT_CACHE) . "\" size=\"10\"></td>";
+print "<td><input type=\"text\" class=\"flat\" name=\"MAIN_AGENDA_EXPORT_CACHE\" value=\"".(GETPOST('MAIN_AGENDA_EXPORT_CACHE', 'alpha') ?GETPOST('MAIN_AGENDA_EXPORT_CACHE', 'alpha') : $conf->global->MAIN_AGENDA_EXPORT_CACHE)."\" size=\"10\"></td>";
 print "<td>&nbsp;</td>";
 print "</tr>";
 
@@ -153,35 +153,35 @@ print "<br>";
 
 
 // Define $urlwithroot
-$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
-$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
+$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
 //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
 
 
 // Show message
-$message='';
-$urlvcal='<a href="'.$urlwithroot.'/public/agenda/agendaexport.php?format=vcal&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY):'...').'" target="_blank">'.$urlwithroot.'/public/agenda/agendaexport.php?format=vcal&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY):'KEYNOTDEFINED').'</a>';
-$message.=img_picto('', 'globe').' '.$langs->trans("WebCalUrlForVCalExport", 'vcal', $urlvcal);
-$message.='<br>';
-$urlical='<a href="'.$urlwithroot.'/public/agenda/agendaexport.php?format=ical&type=event&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY):'...').'" target="_blank">'.$urlwithroot.'/public/agenda/agendaexport.php?format=ical&type=event&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY):'KEYNOTDEFINED').'</a>';
-$message.=img_picto('', 'globe').' '.$langs->trans("WebCalUrlForVCalExport", 'ical/ics', $urlical);
-$message.='<br>';
-$urlrss='<a href="'.$urlwithroot.'/public/agenda/agendaexport.php?format=rss&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY):'...').'" target="_blank">'.$urlwithroot.'/public/agenda/agendaexport.php?format=rss&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY):'KEYNOTDEFINED').'</a>';
-$message.=img_picto('', 'globe').' '.$langs->trans("WebCalUrlForVCalExport", 'rss', $urlrss);
-$message.='<br>';
-$message.='<br>';
+$message = '';
+$urlvcal = '<a href="'.$urlwithroot.'/public/agenda/agendaexport.php?format=vcal&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY ?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY) : '...').'" target="_blank">'.$urlwithroot.'/public/agenda/agendaexport.php?format=vcal&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY ?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY) : 'KEYNOTDEFINED').'</a>';
+$message .= img_picto('', 'globe').' '.$langs->trans("WebCalUrlForVCalExport", 'vcal', $urlvcal);
+$message .= '<br>';
+$urlical = '<a href="'.$urlwithroot.'/public/agenda/agendaexport.php?format=ical&type=event&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY ?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY) : '...').'" target="_blank">'.$urlwithroot.'/public/agenda/agendaexport.php?format=ical&type=event&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY ?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY) : 'KEYNOTDEFINED').'</a>';
+$message .= img_picto('', 'globe').' '.$langs->trans("WebCalUrlForVCalExport", 'ical/ics', $urlical);
+$message .= '<br>';
+$urlrss = '<a href="'.$urlwithroot.'/public/agenda/agendaexport.php?format=rss&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY ?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY) : '...').'" target="_blank">'.$urlwithroot.'/public/agenda/agendaexport.php?format=rss&exportkey='.($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY ?urlencode($conf->global->MAIN_AGENDA_XCAL_EXPORTKEY) : 'KEYNOTDEFINED').'</a>';
+$message .= img_picto('', 'globe').' '.$langs->trans("WebCalUrlForVCalExport", 'rss', $urlrss);
+$message .= '<br>';
+$message .= '<br>';
 print $message;
 
-$message =$langs->trans("AgendaUrlOptions1", $user->login, $user->login).'<br>';
-$message.=$langs->trans("AgendaUrlOptions3", $user->login, $user->login).'<br>';
-$message.=$langs->trans("AgendaUrlOptionsNotAdmin", $user->login, $user->login).'<br>';
-$message.=$langs->trans("AgendaUrlOptions4", $user->login, $user->login).'<br>';
-$message.=$langs->trans("AgendaUrlOptionsProject", $user->login, $user->login).'<br>';
-$message.=$langs->trans("AgendaUrlOptionsNotAutoEvent", 'systemauto', 'systemauto').'<br>';
+$message = $langs->trans("AgendaUrlOptions1", $user->login, $user->login).'<br>';
+$message .= $langs->trans("AgendaUrlOptions3", $user->login, $user->login).'<br>';
+$message .= $langs->trans("AgendaUrlOptionsNotAdmin", $user->login, $user->login).'<br>';
+$message .= $langs->trans("AgendaUrlOptions4", $user->login, $user->login).'<br>';
+$message .= $langs->trans("AgendaUrlOptionsProject", $user->login, $user->login).'<br>';
+$message .= $langs->trans("AgendaUrlOptionsNotAutoEvent", 'systemauto', 'systemauto').'<br>';
 
 print info_admin($message);
 
-if (! empty($conf->use_javascript_ajax))
+if (!empty($conf->use_javascript_ajax))
 {
 	print "\n".'<script type="text/javascript">';
 	print '$(document).ready(function () {

+ 80 - 80
htdocs/admin/boxes.php

@@ -31,7 +31,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
 // Load translation files required by the page
 $langs->loadLangs(array('admin', 'boxes', 'accountancy'));
 
-if (! $user->admin) accessforbidden();
+if (!$user->admin) accessforbidden();
 
 $rowid = GETPOST('rowid', 'int');
 $action = GETPOST('action', 'alpha');
@@ -53,34 +53,34 @@ if ($action == 'addconst')
 }
 
 if ($action == 'add') {
-    $error=0;
+    $error = 0;
     $db->begin();
     if (isset($_POST['boxid']) && is_array($_POST['boxid']))
     {
-        foreach($_POST['boxid'] as $boxid)
+        foreach ($_POST['boxid'] as $boxid)
         {
             if (is_numeric($boxid['pos']) && $boxid['pos'] >= 0)	// 0=Home, 1=...
             {
                 $pos = $boxid['pos'];
 
                 // Initialize distinct fk_user with all already existing values of fk_user (user that use a personalized view of boxes for page "pos")
-                $distinctfkuser=array();
-                if (! $error)
+                $distinctfkuser = array();
+                if (!$error)
                 {
                     $sql = "SELECT fk_user";
-                    $sql.= " FROM ".MAIN_DB_PREFIX."user_param";
-                    $sql.= " WHERE param = 'MAIN_BOXES_".$db->escape($pos)."' AND value = '1'";
-                    $sql.= " AND entity = ".$conf->entity;
+                    $sql .= " FROM ".MAIN_DB_PREFIX."user_param";
+                    $sql .= " WHERE param = 'MAIN_BOXES_".$db->escape($pos)."' AND value = '1'";
+                    $sql .= " AND entity = ".$conf->entity;
                     dol_syslog("boxes.php search fk_user to activate box for", LOG_DEBUG);
                     $resql = $db->query($sql);
                     if ($resql)
                     {
                         $num = $db->num_rows($resql);
-                        $i=0;
+                        $i = 0;
                         while ($i < $num)
                         {
-                            $obj=$db->fetch_object($resql);
-                            $distinctfkuser[$obj->fk_user]=$obj->fk_user;
+                            $obj = $db->fetch_object($resql);
+                            $distinctfkuser[$obj->fk_user] = $obj->fk_user;
                             $i++;
                         }
                     }
@@ -91,21 +91,21 @@ if ($action == 'add') {
                     }
                 }
 
-                $distinctfkuser['0']='0';	// Add entry for fk_user = 0. We must use string as key and val
+                $distinctfkuser['0'] = '0'; // Add entry for fk_user = 0. We must use string as key and val
 
-                foreach($distinctfkuser as $fk_user)
+                foreach ($distinctfkuser as $fk_user)
                 {
-                    if (! $error && $fk_user != '')
+                    if (!$error && $fk_user != '')
                     {
-                        $nbboxonleft=$nbboxonright=0;
+                        $nbboxonleft = $nbboxonright = 0;
                         $sql = "SELECT box_order FROM ".MAIN_DB_PREFIX."boxes WHERE position = ".$pos." AND fk_user = ".$fk_user." AND entity = ".$conf->entity;
                         dol_syslog("boxes.php activate box", LOG_DEBUG);
                         $resql = $db->query($sql);
                         if ($resql)
                         {
-                            while($obj = $db->fetch_object($resql))
+                            while ($obj = $db->fetch_object($resql))
                             {
-                                $boxorder=$obj->box_order;
+                                $boxorder = $obj->box_order;
                                 if (preg_match('/A/', $boxorder)) $nbboxonleft++;
                                 if (preg_match('/B/', $boxorder)) $nbboxonright++;
                             }
@@ -113,14 +113,14 @@ if ($action == 'add') {
                         else dol_print_error($db);
 
                         $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes (";
-                        $sql.= "box_id, position, box_order, fk_user, entity";
-                        $sql.= ") values (";
-                        $sql.= $boxid['value'].", ".$pos.", '".(($nbboxonleft > $nbboxonright) ? 'B01' : 'A01')."', ".$fk_user.", ".$conf->entity;
-                        $sql.= ")";
+                        $sql .= "box_id, position, box_order, fk_user, entity";
+                        $sql .= ") values (";
+                        $sql .= $boxid['value'].", ".$pos.", '".(($nbboxonleft > $nbboxonright) ? 'B01' : 'A01')."', ".$fk_user.", ".$conf->entity;
+                        $sql .= ")";
 
                         dol_syslog("boxes.php activate box", LOG_DEBUG);
                         $resql = $db->query($sql);
-                        if (! $resql)
+                        if (!$resql)
                         {
                             setEventMessages($db->lasterror(), null, 'errors');
                             $error++;
@@ -130,10 +130,10 @@ if ($action == 'add') {
             }
         }
     }
-    if (! $error)
+    if (!$error)
     {
         $db->commit();
-        $action='';
+        $action = '';
     }
     else
     {
@@ -144,11 +144,11 @@ if ($action == 'add') {
 if ($action == 'delete')
 {
 	$sql = "SELECT box_id FROM ".MAIN_DB_PREFIX."boxes";
-	$sql.= " WHERE rowid=".$rowid;
+	$sql .= " WHERE rowid=".$rowid;
 
 	$resql = $db->query($sql);
-	$obj=$db->fetch_object($resql);
-    if (! empty($obj->box_id))
+	$obj = $db->fetch_object($resql);
+    if (!empty($obj->box_id))
     {
 	    $db->begin();
 
@@ -158,8 +158,8 @@ if ($action == 'delete')
         //	$resql = $db->query($sql);
 
 	    $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes";
-	    $sql.= " WHERE entity = ".$conf->entity;
-    	$sql.= " AND box_id=".$obj->box_id;
+	    $sql .= " WHERE entity = ".$conf->entity;
+    	$sql .= " AND box_id=".$obj->box_id;
 
     	$resql = $db->query($sql);
 
@@ -172,33 +172,33 @@ if ($action == 'switch')
 	// We switch values of field box_order for the 2 lines of table boxes
 	$db->begin();
 
-	$objfrom=new ModeleBoxes($db);
+	$objfrom = new ModeleBoxes($db);
 	$objfrom->fetch($_GET["switchfrom"]);
 
-	$objto=new ModeleBoxes($db);
+	$objto = new ModeleBoxes($db);
 	$objto->fetch($_GET["switchto"]);
 
-	$resultupdatefrom=0;
-	$resultupdateto=0;
+	$resultupdatefrom = 0;
+	$resultupdateto = 0;
 	if (is_object($objfrom) && is_object($objto))
 	{
-	    $newfirst=$objto->box_order;
-		$newsecond=$objfrom->box_order;
+	    $newfirst = $objto->box_order;
+		$newsecond = $objfrom->box_order;
 	    if ($newfirst == $newsecond)
 	    {
-	         $newsecondchar=preg_replace('/[0-9]+/', '', $newsecond);
-	         $newsecondnum=preg_replace('/[a-zA-Z]+/', '', $newsecond);
-	         $newsecond=sprintf("%s%02d", $newsecondchar?$newsecondchar:'A', $newsecondnum+1);
+	         $newsecondchar = preg_replace('/[0-9]+/', '', $newsecond);
+	         $newsecondnum = preg_replace('/[a-zA-Z]+/', '', $newsecond);
+	         $newsecond = sprintf("%s%02d", $newsecondchar ? $newsecondchar : 'A', $newsecondnum + 1);
 	    }
-		$sql="UPDATE ".MAIN_DB_PREFIX."boxes SET box_order='".$newfirst."' WHERE rowid=".$objfrom->rowid;
+		$sql = "UPDATE ".MAIN_DB_PREFIX."boxes SET box_order='".$newfirst."' WHERE rowid=".$objfrom->rowid;
 		dol_syslog($sql);
 		$resultupdatefrom = $db->query($sql);
-		if (! $resultupdatefrom) { dol_print_error($db); }
+		if (!$resultupdatefrom) { dol_print_error($db); }
 
-		$sql="UPDATE ".MAIN_DB_PREFIX."boxes SET box_order='".$newsecond."' WHERE rowid=".$objto->rowid;
+		$sql = "UPDATE ".MAIN_DB_PREFIX."boxes SET box_order='".$newsecond."' WHERE rowid=".$objto->rowid;
 		dol_syslog($sql);
 		$resultupdateto = $db->query($sql);
-		if (! $resultupdateto) { dol_print_error($db); }
+		if (!$resultupdateto) { dol_print_error($db); }
 	}
 
 	if ($resultupdatefrom && $resultupdateto)
@@ -216,7 +216,7 @@ if ($action == 'switch')
  * View
  */
 
-$form=new Form($db);
+$form = new Form($db);
 
 llxHeader('', $langs->trans("Boxes"));
 
@@ -232,12 +232,12 @@ print '<span class="opacitymedium">'.$langs->trans("BoxesDesc")." ".$langs->tran
 $actives = array();
 
 $sql = "SELECT b.rowid, b.box_id, b.position, b.box_order,";
-$sql.= " bd.rowid as boxid";
-$sql.= " FROM ".MAIN_DB_PREFIX."boxes as b, ".MAIN_DB_PREFIX."boxes_def as bd";
-$sql.= " WHERE b.box_id = bd.rowid";
-$sql.= " AND b.entity IN (0,".$conf->entity.")";
-$sql.= " AND b.fk_user=0";
-$sql.= " ORDER by b.position, b.box_order";
+$sql .= " bd.rowid as boxid";
+$sql .= " FROM ".MAIN_DB_PREFIX."boxes as b, ".MAIN_DB_PREFIX."boxes_def as bd";
+$sql .= " WHERE b.box_id = bd.rowid";
+$sql .= " AND b.entity IN (0,".$conf->entity.")";
+$sql .= " AND b.fk_user=0";
+$sql .= " ORDER by b.position, b.box_order";
 
 dol_syslog("Search available boxes", LOG_DEBUG);
 $resql = $db->query($sql);
@@ -247,11 +247,11 @@ if ($resql)
 
 	// Check record to know if we must recalculate sort order
 	$i = 0;
-	$decalage=0;
+	$decalage = 0;
 	while ($i < $num)
 	{
 		$obj = $db->fetch_object($resql);
-		$boxes[$obj->position][$obj->box_id]=1;
+		$boxes[$obj->position][$obj->box_id] = 1;
 		$i++;
 
 		array_push($actives, $obj->box_id);
@@ -261,7 +261,7 @@ if ($resql)
 		// This occurs just after an insert.
 		if ($decalage)
 		{
-			$sql="UPDATE ".MAIN_DB_PREFIX."boxes SET box_order='".$decalage."' WHERE rowid=".$obj->rowid;
+			$sql = "UPDATE ".MAIN_DB_PREFIX."boxes SET box_order='".$decalage."' WHERE rowid=".$obj->rowid;
 			$db->query($sql);
 		}
 	}
@@ -271,9 +271,9 @@ if ($resql)
 	    // If we have renumbered, we correct the field box_order
 		// This occurs just after an insert.
 		$sql = "SELECT box_order";
-		$sql.= " FROM ".MAIN_DB_PREFIX."boxes";
-		$sql.= " WHERE entity = ".$conf->entity;
-		$sql.= " AND LENGTH(box_order) <= 2";
+		$sql .= " FROM ".MAIN_DB_PREFIX."boxes";
+		$sql .= " WHERE entity = ".$conf->entity;
+		$sql .= " AND LENGTH(box_order) <= 2";
 
 		dol_syslog("Execute requests to renumber box order", LOG_DEBUG);
 		$result = $db->query($sql);
@@ -286,13 +286,13 @@ if ($resql)
 					if (preg_match("/[13579]{1}/", substr($record['box_order'], -1)))
 					{
 						$box_order = "A0".$record['box_order'];
-						$sql="UPDATE ".MAIN_DB_PREFIX."boxes SET box_order = '".$box_order."' WHERE entity = ".$conf->entity." AND box_order = '".$record['box_order']."'";
+						$sql = "UPDATE ".MAIN_DB_PREFIX."boxes SET box_order = '".$box_order."' WHERE entity = ".$conf->entity." AND box_order = '".$record['box_order']."'";
 						$resql = $db->query($sql);
 					}
 					elseif (preg_match("/[02468]{1}/", substr($record['box_order'], -1)))
 					{
 						$box_order = "B0".$record['box_order'];
-						$sql="UPDATE ".MAIN_DB_PREFIX."boxes SET box_order = '".$box_order."' WHERE entity = ".$conf->entity." AND box_order = '".$record['box_order']."'";
+						$sql = "UPDATE ".MAIN_DB_PREFIX."boxes SET box_order = '".$box_order."' WHERE entity = ".$conf->entity." AND box_order = '".$record['box_order']."'";
 						$resql = $db->query($sql);
 					}
 				}
@@ -301,13 +301,13 @@ if ($resql)
 					if (preg_match("/[13579]{1}/", substr($record['box_order'], -1)))
 					{
 						$box_order = "A".$record['box_order'];
-						$sql="UPDATE ".MAIN_DB_PREFIX."boxes SET box_order = '".$box_order."' WHERE entity = ".$conf->entity." AND box_order = '".$record['box_order']."'";
+						$sql = "UPDATE ".MAIN_DB_PREFIX."boxes SET box_order = '".$box_order."' WHERE entity = ".$conf->entity." AND box_order = '".$record['box_order']."'";
 						$resql = $db->query($sql);
 					}
 					elseif (preg_match("/[02468]{1}/", substr($record['box_order'], -1)))
 					{
 						$box_order = "B".$record['box_order'];
-						$sql="UPDATE ".MAIN_DB_PREFIX."boxes SET box_order = '".$box_order."' WHERE entity = ".$conf->entity." AND box_order = '".$record['box_order']."'";
+						$sql = "UPDATE ".MAIN_DB_PREFIX."boxes SET box_order = '".$box_order."' WHERE entity = ".$conf->entity." AND box_order = '".$record['box_order']."'";
 						$resql = $db->query($sql);
 					}
 				}
@@ -318,9 +318,9 @@ if ($resql)
 }
 
 // Available boxes to activate
-$boxtoadd=InfoBox::listBoxes($db, 'available', -1, null, $actives);
+$boxtoadd = InfoBox::listBoxes($db, 'available', -1, null, $actives);
 // Activated boxes
-$boxactivated=InfoBox::listBoxes($db, 'activated', -1, null);
+$boxactivated = InfoBox::listBoxes($db, 'activated', -1, null);
 
 print "<br>\n";
 print "\n\n".'<!-- Boxes Available -->'."\n";
@@ -340,7 +340,7 @@ print '<td>'.$langs->trans("SourceFile").'</td>';
 print '<td width="160" class="center">'.$langs->trans("ActivateOn").'</td>';
 print "</tr>\n";
 
-foreach($boxtoadd as $box)
+foreach ($boxtoadd as $box)
 {
     if (preg_match('/^([^@]+)@([^@]+)$/i', $box->boximg))
     {
@@ -348,13 +348,13 @@ foreach($boxtoadd as $box)
     }
     else
     {
-        $logo=preg_replace("/^object_/i", "", $box->boximg);
+        $logo = preg_replace("/^object_/i", "", $box->boximg);
     }
 
     print "\n".'<!-- Box '.$box->boxcode.' -->'."\n";
     print '<tr class="oddeven">'."\n";
     print '<td>'.img_object("", $logo).' '.$langs->transnoentitiesnoconv($box->boxlabel);
-    if (! empty($box->class) && preg_match('/graph_/', $box->class)) print ' ('.$langs->trans("Graph").')';
+    if (!empty($box->class) && preg_match('/graph_/', $box->class)) print ' ('.$langs->trans("Graph").')';
     print '</td>'."\n";
     print '<td>';
     if ($box->note == '(WarningUsingThisBoxSlowDown)')
@@ -362,9 +362,9 @@ foreach($boxtoadd as $box)
     	$langs->load("errors");
     	print $langs->trans("WarningUsingThisBoxSlowDown");
     }
-	else print ($box->note?$box->note:'&nbsp;');
+	else print ($box->note ? $box->note : '&nbsp;');
     print '</td>'."\n";
-    print '<td>' . $box->sourcefile . '</td>'."\n";
+    print '<td>'.$box->sourcefile.'</td>'."\n";
 
     // For each possible position, an activation link is displayed if the box is not already active for that position
     print '<td class="center">';
@@ -374,7 +374,7 @@ foreach($boxtoadd as $box)
 
     print '</tr>'."\n";
 }
-if (! count($boxtoadd) && count($boxactivated))
+if (!count($boxtoadd) && count($boxactivated))
 {
 	print '<tr><td class="opacitymedium" colspan="4">'.$langs->trans("AllWidgetsWereEnabled").'</td></tr>';
 }
@@ -382,7 +382,7 @@ print '</table>'."\n";
 print '</div>';
 
 print '<div class="right">';
-print '<input type="submit" class="button"'.(count($boxtoadd)?'':' disabled').' value="'.$langs->trans("Activate").'">';
+print '<input type="submit" class="button"'.(count($boxtoadd) ? '' : ' disabled').' value="'.$langs->trans("Activate").'">';
 print '</div>'."\n";
 print '</form>';
 print "\n".'<!-- End Boxes Available -->'."\n";
@@ -403,9 +403,9 @@ print '<td class="center" width="60" colspan="2">'.$langs->trans("PositionByDefa
 print '<td class="center" width="80">'.$langs->trans("Disable").'</td>';
 print '</tr>'."\n";
 
-$box_order=1;
-$foundrupture=1;
-foreach($boxactivated as $key => $box)
+$box_order = 1;
+$foundrupture = 1;
+foreach ($boxactivated as $key => $box)
 {
 	if (preg_match('/^([^@]+)@([^@]+)$/i', $box->boximg))
 	{
@@ -413,13 +413,13 @@ foreach($boxactivated as $key => $box)
 	}
 	else
 	{
-		$logo=preg_replace("/^object_/i", "", $box->boximg);
+		$logo = preg_replace("/^object_/i", "", $box->boximg);
 	}
 
     print "\n".'<!-- Box '.$box->boxcode.' -->'."\n";
 	print '<tr class="oddeven">';
 	print '<td>'.img_object("", $logo).' '.$langs->transnoentitiesnoconv($box->boxlabel);
-	if (! empty($box->class) && preg_match('/graph_/', $box->class)) print ' ('.$langs->trans("Graph").')';
+	if (!empty($box->class) && preg_match('/graph_/', $box->class)) print ' ('.$langs->trans("Graph").')';
 	print '</td>';
 	print '<td>';
 	if ($box->note == '(WarningUsingThisBoxSlowDown)')
@@ -427,15 +427,15 @@ foreach($boxactivated as $key => $box)
 		$langs->load("errors");
 		print img_warning('', 0).' '.$langs->trans("WarningUsingThisBoxSlowDown");
 	}
-	else print ($box->note?$box->note:'&nbsp;');
+	else print ($box->note ? $box->note : '&nbsp;');
 	print '</td>';
-	print '<td class="center">' . (empty($pos_name[$box->position])?'':$langs->trans($pos_name[$box->position])) . '</td>';
-	$hasnext=($key < (count($boxactivated)-1));
-	$hasprevious=($key != 0);
-	print '<td class="center">'.($key+1).'</td>';
+	print '<td class="center">'.(empty($pos_name[$box->position]) ? '' : $langs->trans($pos_name[$box->position])).'</td>';
+	$hasnext = ($key < (count($boxactivated) - 1));
+	$hasprevious = ($key != 0);
+	print '<td class="center">'.($key + 1).'</td>';
 	print '<td class="center">';
-	print ($hasnext?'<a href="boxes.php?action=switch&amp;switchfrom='.$box->rowid.'&amp;switchto='.$boxactivated[$key+1]->rowid.'">'.img_down().'</a>&nbsp;':'');
-	print ($hasprevious?'<a href="boxes.php?action=switch&amp;switchfrom='.$box->rowid.'&amp;switchto='.$boxactivated[$key-1]->rowid.'">'.img_up().'</a>':'');
+	print ($hasnext ? '<a href="boxes.php?action=switch&amp;switchfrom='.$box->rowid.'&amp;switchto='.$boxactivated[$key + 1]->rowid.'">'.img_down().'</a>&nbsp;' : '');
+	print ($hasprevious ? '<a href="boxes.php?action=switch&amp;switchfrom='.$box->rowid.'&amp;switchto='.$boxactivated[$key - 1]->rowid.'">'.img_up().'</a>' : '');
 	print '</td>';
 	print '<td class="center">';
 	print '<a href="boxes.php?rowid='.$box->rowid.'&amp;action=delete">'.img_delete().'</a>';

+ 18 - 18
htdocs/admin/dav.php

@@ -26,7 +26,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/dav/dav.lib.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("admin","other","agenda"));
+$langs->loadLangs(array("admin", "other", "agenda"));
 
 if (!$user->admin)
     accessforbidden();
@@ -37,7 +37,7 @@ $backtopage = GETPOST('backtopage', 'alpha');
 
 
 
-$arrayofparameters=array(
+$arrayofparameters = array(
 	'DAV_RESTICT_ON_IP'=>array('css'=>'minwidth200', 'enabled'=>1),
     'DAV_ALLOW_PRIVATE_DIR'=>array('css'=>'minwidth200', 'enabled'=>2),
     'DAV_ALLOW_PUBLIC_DIR'=>array('css'=>'minwidth200', 'enabled'=>1),
@@ -60,14 +60,14 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
 
 llxHeader('', $langs->trans("DAVSetup"), $wikihelp);
 
-$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
+$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
 print load_fiche_titre($langs->trans("DAVSetup"), $linkback, 'title_setup');
 
 
 print '<form name="agendasetupform" action="'.$_SERVER["PHP_SELF"].'" method="post">';
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 
-$head=dav_admin_prepare_head();
+$head = dav_admin_prepare_head();
 
 dol_fiche_head($head, 'webdav', '', -1, 'action');
 
@@ -80,7 +80,7 @@ if ($action == 'edit')
 	print '<table class="noborder centpercent">';
 	print '<tr class="liste_titre"><td>'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
 
-	foreach($arrayofparameters as $key => $val)
+	foreach ($arrayofparameters as $key => $val)
 	{
 		if (isset($val['enabled']) && empty($val['enabled'])) continue;
 
@@ -100,7 +100,7 @@ if ($action == 'edit')
 		}
 		else
 		{
-			print '<input name="'.$key.'"  class="flat '.(empty($val['css'])?'minwidth200':$val['css']).'" value="' . $conf->global->$key . '">';
+			print '<input name="'.$key.'"  class="flat '.(empty($val['css']) ? 'minwidth200' : $val['css']).'" value="'.$conf->global->$key.'">';
 		}
 		print '</td></tr>';
 	}
@@ -119,7 +119,7 @@ else
 	print '<table class="noborder centpercent">';
 	print '<tr class="liste_titre"><td>'.$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') : '');
@@ -166,22 +166,22 @@ print "<br>";
 
 
 // Define $urlwithroot
-$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
-$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
+$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
 //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
 
 
 // Show message
-$message='';
-$url='<a href="'.$urlwithroot.'/dav/fileserver.php" target="_blank">'.$urlwithroot.'/dav/fileserver.php</a>';
-$message.=img_picto('', 'globe').' '.$langs->trans("WebDavServer", 'WebDAV', $url);
-$message.='<br>';
-if (! empty($conf->global->DAV_ALLOW_PUBLIC_DIR))
+$message = '';
+$url = '<a href="'.$urlwithroot.'/dav/fileserver.php" target="_blank">'.$urlwithroot.'/dav/fileserver.php</a>';
+$message .= img_picto('', 'globe').' '.$langs->trans("WebDavServer", 'WebDAV', $url);
+$message .= '<br>';
+if (!empty($conf->global->DAV_ALLOW_PUBLIC_DIR))
 {
-	$urlEntity = (! empty($conf->multicompany->enabled)?'?entity='.$conf->entity:'');
-	$url='<a href="'.$urlwithroot.'/dav/fileserver.php/public/'.$urlEntity.'" target="_blank">'.$urlwithroot.'/dav/fileserver.php/public/'.$urlEntity.'</a>';
-	$message.=img_picto('', 'globe').' '.$langs->trans("WebDavServer", 'WebDAV public', $url);
-	$message.='<br>';
+	$urlEntity = (!empty($conf->multicompany->enabled) ? '?entity='.$conf->entity : '');
+	$url = '<a href="'.$urlwithroot.'/dav/fileserver.php/public/'.$urlEntity.'" target="_blank">'.$urlwithroot.'/dav/fileserver.php/public/'.$urlEntity.'</a>';
+	$message .= img_picto('', 'globe').' '.$langs->trans("WebDavServer", 'WebDAV public', $url);
+	$message .= '<br>';
 }
 print $message;
 

+ 39 - 39
htdocs/admin/security.php

@@ -27,22 +27,22 @@ require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
 
-$action=GETPOST('action', 'aZ09');
+$action = GETPOST('action', 'aZ09');
 
 // Load translation files required by the page
-$langs->loadLangs(array("users","admin","other"));
+$langs->loadLangs(array("users", "admin", "other"));
 
 if (!$user->admin) accessforbidden();
 
 // Allow/Disallow change to clear passwords once passwords are crypted
-$allow_disable_encryption=true;
+$allow_disable_encryption = true;
 
 /*
  * Actions
  */
 if ($action == 'setgeneraterule')
 {
-	if (! dolibarr_set_const($db, 'USER_PASSWORD_GENERATED', $_GET["value"], 'chaine', 0, '', $conf->entity))
+	if (!dolibarr_set_const($db, 'USER_PASSWORD_GENERATED', $_GET["value"], 'chaine', 0, '', $conf->entity))
 	{
 		dol_print_error($db);
 	}
@@ -55,33 +55,33 @@ if ($action == 'setgeneraterule')
 
 if ($action == 'activate_encrypt')
 {
-    $error=0;
+    $error = 0;
 
 	$db->begin();
 
     dolibarr_set_const($db, "DATABASE_PWD_ENCRYPTED", "1", 'chaine', 0, '', $conf->entity);
 
     $sql = "SELECT u.rowid, u.pass, u.pass_crypted";
-    $sql.= " FROM ".MAIN_DB_PREFIX."user as u";
-    $sql.= " WHERE u.pass IS NOT NULL AND LENGTH(u.pass) < 32"; // Not a MD5 value
+    $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
+    $sql .= " WHERE u.pass IS NOT NULL AND LENGTH(u.pass) < 32"; // Not a MD5 value
 
-    $resql=$db->query($sql);
+    $resql = $db->query($sql);
     if ($resql)
     {
-        $numrows=$db->num_rows($resql);
-        $i=0;
+        $numrows = $db->num_rows($resql);
+        $i = 0;
         while ($i < $numrows)
         {
-            $obj=$db->fetch_object($resql);
+            $obj = $db->fetch_object($resql);
             if (dol_hash($obj->pass))
             {
                 $sql = "UPDATE ".MAIN_DB_PREFIX."user";
-                $sql.= " SET pass_crypted = '".dol_hash($obj->pass)."', pass = NULL";
-                $sql.= " WHERE rowid=".$obj->rowid;
+                $sql .= " SET pass_crypted = '".dol_hash($obj->pass)."', pass = NULL";
+                $sql .= " WHERE rowid=".$obj->rowid;
                 //print $sql;
 
                 $resql2 = $db->query($sql);
-                if (! $resql2)
+                if (!$resql2)
                 {
                     dol_print_error($db);
                     $error++;
@@ -96,7 +96,7 @@ if ($action == 'activate_encrypt')
 
 	//print $error." ".$sql;
     //exit;
-    if (! $error)
+    if (!$error)
 	{
 		$db->commit();
 		header("Location: security.php");
@@ -125,7 +125,7 @@ if ($action == 'activate_encryptdbpassconf')
 	$result = encodedecode_dbpassconf(1);
 	if ($result > 0)
 	{
-	    sleep(3);  // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait.
+	    sleep(3); // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait.
 
 	    // database value not required
 		//dolibarr_set_const($db, "MAIN_DATABASE_PWD_CONFIG_ENCRYPTED", "1");
@@ -142,7 +142,7 @@ elseif ($action == 'disable_encryptdbpassconf')
 	$result = encodedecode_dbpassconf(0);
 	if ($result > 0)
 	{
-	    sleep(3);  // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait.
+	    sleep(3); // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait.
 
 		// database value not required
 		//dolibarr_del_const($db, "MAIN_DATABASE_PWD_CONFIG_ENCRYPTED",$conf->entity);
@@ -196,7 +196,7 @@ if ($action == 'maj_pattern')
  */
 $form = new Form($db);
 
-$wikihelp='EN:Setup_Security|FR:Paramétrage_Sécurité|ES:Configuración_Seguridad';
+$wikihelp = 'EN:Setup_Security|FR:Paramétrage_Sécurité|ES:Configuración_Seguridad';
 llxHeader('', $langs->trans("Passwords"), $wikihelp);
 
 print load_fiche_titre($langs->trans("SecuritySetup"), '', 'title_setup');
@@ -205,7 +205,7 @@ print $langs->trans("GeneratedPasswordDesc")."<br>\n";
 print "<br>\n";
 
 
-$head=security_prepare_head();
+$head = security_prepare_head();
 
 dol_fiche_head($head, 'passwords', $langs->trans("Security"), -1);
 
@@ -220,11 +220,11 @@ print '<input type="hidden" name="consttype" value="yesno">';
 // Charge tableau des modules generation
 $dir = "../core/modules/security/generate";
 clearstatcache();
-$handle=opendir($dir);
-$i=1;
+$handle = opendir($dir);
+$i = 1;
 if (is_resource($handle))
 {
-    while (($file = readdir($handle))!==false)
+    while (($file = readdir($handle)) !== false)
     {
         if (preg_match('/(modGeneratePass[a-z]+)\.class\.php$/i', $file, $reg))
         {
@@ -233,7 +233,7 @@ if (is_resource($handle))
             require_once $dir.'/'.$file;
 
             $obj = new $classname($db, $conf, $langs, $user);
-            $arrayhandler[$obj->id]=$obj;
+            $arrayhandler[$obj->id] = $obj;
     		$i++;
         }
     }
@@ -251,7 +251,7 @@ print '</tr>';
 foreach ($arrayhandler as $key => $module)
 {
 	// Show modules according to features level
-    if ($module->version == 'development'  && $conf->global->MAIN_FEATURES_LEVEL < 2) 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())
@@ -265,9 +265,9 @@ foreach ($arrayhandler as $key => $module)
 
         // Show example of numbering module
         print '<td class="nowrap">';
-        $tmp=$module->getExample();
+        $tmp = $module->getExample();
         if (preg_match('/^Error/', $tmp)) { $langs->load("errors"); print '<div class="error">'.$langs->trans($tmp).'</div>'; }
-        elseif ($tmp=='NotConfigured') print $langs->trans($tmp);
+        elseif ($tmp == 'NotConfigured') print $langs->trans($tmp);
         else print $tmp;
         print '</td>'."\n";
 
@@ -298,37 +298,37 @@ if ($conf->global->USER_PASSWORD_GENERATED == "Perso"){
 
 
 	print '<tr class="oddeven">';
-	print '<td>' . $langs->trans("MinLength")."</td>";
+	print '<td>'.$langs->trans("MinLength")."</td>";
 	print '<td colspan="2"><input type="number" value="'.$tabConf[0].'" id="minlenght" min="1"></td>';
 	print '</tr>';
 
 
 	print '<tr class="oddeven">';
-	print '<td>' . $langs->trans("NbMajMin")."</td>";
+	print '<td>'.$langs->trans("NbMajMin")."</td>";
 	print '<td colspan="2"><input type="number" value="'.$tabConf[1].'" id="NbMajMin" min="0"></td>';
 	print '</tr>';
 
 
 	print '<tr class="oddeven">';
-	print '<td>' . $langs->trans("NbNumMin")."</td>";
+	print '<td>'.$langs->trans("NbNumMin")."</td>";
 	print '<td colspan="2"><input type="number" value="'.$tabConf[2].'" id="NbNumMin" min="0"></td>';
 	print '</tr>';
 
 
 	print '<tr class="oddeven">';
-	print '<td>' . $langs->trans("NbSpeMin")."</td>";
+	print '<td>'.$langs->trans("NbSpeMin")."</td>";
 	print '<td colspan="2"><input type="number" value="'.$tabConf[3].'" id="NbSpeMin" min="0"></td>';
 	print '</tr>';
 
 
 	print '<tr class="oddeven">';
-	print '<td>' . $langs->trans("NbIteConsecutive")."</td>";
+	print '<td>'.$langs->trans("NbIteConsecutive")."</td>";
 	print '<td colspan="2"><input type="number" value="'.$tabConf[4].'" id="NbIteConsecutive" min="0"></td>';
 	print '</tr>';
 
 
 	print '<tr class="oddeven">';
-	print '<td>' . $langs->trans("NoAmbiCaracAutoGeneration")."</td>";
+	print '<td>'.$langs->trans("NoAmbiCaracAutoGeneration")."</td>";
 	print '<td colspan="2"><input type="checkbox" id="NoAmbiCaracAutoGeneration" '.($tabConf[5] ? "checked" : "").' min="0"> <span id="textcheckbox">'.($tabConf[5] ? $langs->trans("Activated") : $langs->trans("Disabled")).'</span></td>';
 	print '</tr>';
 
@@ -398,7 +398,7 @@ if ($conf->global->USER_PASSWORD_GENERATED == "Perso"){
 
 // Cryptage mot de passe
 print '<br>';
-print "<form method=\"post\" action=\"" . $_SERVER["PHP_SELF"] . "\">";
+print "<form method=\"post\" action=\"".$_SERVER["PHP_SELF"]."\">";
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 print "<input type=\"hidden\" name=\"action\" value=\"encrypt\">";
 
@@ -413,12 +413,12 @@ print '</tr>';
 print '<tr class="oddeven">';
 print '<td colspan="3">'.$langs->trans("DoNotStoreClearPassword").'</td>';
 print '<td align="center" width="60">';
-if (! empty($conf->global->DATABASE_PWD_ENCRYPTED))
+if (!empty($conf->global->DATABASE_PWD_ENCRYPTED))
 {
 	print img_picto($langs->trans("Active"), 'tick');
 }
 print '</td>';
-if (! $conf->global->DATABASE_PWD_ENCRYPTED)
+if (!$conf->global->DATABASE_PWD_ENCRYPTED)
 {
 	print '<td align="center" width="100">';
 	print '<a href="security.php?action=activate_encrypt">'.$langs->trans("Activate").'</a>';
@@ -426,7 +426,7 @@ if (! $conf->global->DATABASE_PWD_ENCRYPTED)
 }
 
 // Database conf file encryption
-if (! empty($conf->global->DATABASE_PWD_ENCRYPTED))
+if (!empty($conf->global->DATABASE_PWD_ENCRYPTED))
 {
 	print '<td align="center" width="100">';
 	if ($allow_disable_encryption)
@@ -449,7 +449,7 @@ print '</tr>';
 print '<tr class="oddeven">';
 print '<td colspan="3">'.$langs->trans("MainDbPasswordFileConfEncrypted").'</td>';
 print '<td align="center" width="60">';
-if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || ! empty($dolibarr_main_db_encrypted_pass))
+if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass))
 {
 	print img_picto($langs->trans("Active"), 'tick');
 }
@@ -468,7 +468,7 @@ else
 	{
 		print '<a href="security.php?action=activate_encryptdbpassconf">'.$langs->trans("Activate").'</a>';
 	}
-	if (! empty($dolibarr_main_db_encrypted_pass))
+	if (!empty($dolibarr_main_db_encrypted_pass))
 	{
 		print '<a href="security.php?action=disable_encryptdbpassconf">'.$langs->trans("Disable").'</a>';
 	}
@@ -484,7 +484,7 @@ print '</tr>';
 print '<tr class="oddeven">';
 print '<td colspan="3">'.$langs->trans("DisableForgetPasswordLinkOnLogonPage").'</td>';
 print '<td align="center" width="60">';
-if(! empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK))
+if (!empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK))
 {
 	print img_picto($langs->trans("Active"), 'tick');
 }

+ 23 - 23
htdocs/admin/ticket_public.php

@@ -55,7 +55,7 @@ if ($action == 'setTICKET_ENABLE_PUBLIC_INTERFACE')
 }
 
 if ($action == 'setvar') {
-    include_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php";
+    include_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
 
     $topic_interface = GETPOST('TICKET_PUBLIC_INTERFACE_TOPIC', 'nohtml');
     if (!empty($topic_interface)) {
@@ -158,7 +158,7 @@ $page_name = "TicketSetup";
 llxHeader('', $langs->trans($page_name), $help_url);
 
 // Subheader
-$linkback = '<a href="' . DOL_URL_ROOT . '/admin/modules.php?restore_lastsearch_values=1">' . $langs->trans("BackToModuleList") . '</a>';
+$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
 
 print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup');
 
@@ -167,7 +167,7 @@ $head = ticketAdminPrepareHead();
 
 dol_fiche_head($head, 'public', $langs->trans("Module56000Name"), -1, "ticket");
 
-print '<span class="opacitymedium">'.$langs->trans("TicketPublicAccess") . '</span> : <a href="' . dol_buildpath('/public/ticket/index.php', 1) . '" target="_blank" >' . dol_buildpath('/public/ticket/index.php', 2) . '</a>';
+print '<span class="opacitymedium">'.$langs->trans("TicketPublicAccess").'</span> : <a href="'.dol_buildpath('/public/ticket/index.php', 1).'" target="_blank" >'.dol_buildpath('/public/ticket/index.php', 2).'</a>';
 
 dol_fiche_end();
 
@@ -209,7 +209,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
     print '</tr>';
 
     // Check if email exists
-    print '<tr class="oddeven"><td>' . $langs->trans("TicketsEmailMustExist") . '</td>';
+    print '<tr class="oddeven"><td>'.$langs->trans("TicketsEmailMustExist").'</td>';
     print '<td class="left">';
     if ($conf->use_javascript_ajax) {
         print ajax_constantonoff('TICKET_EMAIL_MUST_EXISTS');
@@ -242,7 +242,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
     }*/
 
     // Show logo for company
-    print '<tr class="oddeven"><td>' . $langs->trans("TicketsShowCompanyLogo") . '</td>';
+    print '<tr class="oddeven"><td>'.$langs->trans("TicketsShowCompanyLogo").'</td>';
     print '<td class="left">';
     if ($conf->use_javascript_ajax) {
     	print ajax_constantonoff('TICKET_SHOW_COMPANY_LOGO');
@@ -259,7 +259,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
     // Also send to main email address
     if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
     {
-    	print '<tr class="oddeven"><td>' . $langs->trans("TicketsEmailAlsoSendToMainAddress") . '</td>';
+    	print '<tr class="oddeven"><td>'.$langs->trans("TicketsEmailAlsoSendToMainAddress").'</td>';
     	print '<td class="left">';
     	if ($conf->use_javascript_ajax) {
     	    print ajax_constantonoff('TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS');
@@ -275,7 +275,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
     }
 
     if (!$conf->use_javascript_ajax) {
-        print '<tr class="impair"><td colspan="3" align="center"><input type="submit" class="button" value="' . $langs->trans("Save") . '"></td>';
+        print '<tr class="impair"><td colspan="3" align="center"><input type="submit" class="button" value="'.$langs->trans("Save").'"></td>';
         print '</tr>';
     }
 
@@ -290,25 +290,25 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
 
     print '<table class="noborder centpercent">';
 
-    print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '" enctype="multipart/form-data" >';
-    print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
+    print '<form method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" >';
+    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
     print '<input type="hidden" name="action" value="setvar">';
 
     print '<tr class="liste_titre">';
-    print '<td colspan="3">' . $langs->trans("Parameter") . '</td>';
+    print '<td colspan="3">'.$langs->trans("Parameter").'</td>';
     print "</tr>\n";
 
     if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) {
         print '<tr>';
-        print '<td colspan="3"><div class="info">' . $langs->trans("TicketCkEditorEmailNotActivated") . '</div></td>';
+        print '<td colspan="3"><div class="info">'.$langs->trans("TicketCkEditorEmailNotActivated").'</div></td>';
         print "</tr>\n";
     }
 
     // Interface topic
     $url_interface = $conf->global->TICKET_PUBLIC_INTERFACE_TOPIC;
-    print '<tr><td>' . $langs->trans("TicketPublicInterfaceTopicLabelAdmin") . '</label>';
+    print '<tr><td>'.$langs->trans("TicketPublicInterfaceTopicLabelAdmin").'</label>';
     print '</td><td>';
-    print '<input type="text"   name="TICKET_PUBLIC_INTERFACE_TOPIC" value="' . $conf->global->TICKET_PUBLIC_INTERFACE_TOPIC . '" size="40" ></td>';
+    print '<input type="text"   name="TICKET_PUBLIC_INTERFACE_TOPIC" value="'.$conf->global->TICKET_PUBLIC_INTERFACE_TOPIC.'" size="40" ></td>';
     print '</td>';
     print '<td align="center">';
     print $form->textwithpicto('', $langs->trans("TicketPublicInterfaceTopicHelp"), 1, 'help');
@@ -316,9 +316,9 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
 
     // Texte d'accueil homepage
     $public_text_home = $conf->global->TICKET_PUBLIC_TEXT_HOME ? $conf->global->TICKET_PUBLIC_TEXT_HOME : $langs->trans('TicketPublicInterfaceTextHome');
-    print '<tr><td>' . $langs->trans("TicketPublicInterfaceTextHomeLabelAdmin") . '</label>';
+    print '<tr><td>'.$langs->trans("TicketPublicInterfaceTextHomeLabelAdmin").'</label>';
     print '</td><td>';
-    require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
+    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
     $doleditor = new DolEditor('TICKET_PUBLIC_TEXT_HOME', $public_text_home, '100%', 180, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70);
     $doleditor->Create();
     print '</td>';
@@ -328,9 +328,9 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
 
     // Texte d'aide à la saisie du message
     $public_text_help_message = $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe');
-    print '<tr><td>' . $langs->trans("TicketPublicInterfaceTextHelpMessageLabelAdmin") . '</label>';
+    print '<tr><td>'.$langs->trans("TicketPublicInterfaceTextHelpMessageLabelAdmin").'</label>';
     print '</td><td>';
-    require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
+    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
     $doleditor = new DolEditor('TICKET_PUBLIC_TEXT_HELP_MESSAGE', $public_text_help_message, '100%', 180, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70);
     $doleditor->Create();
     print '</td>';
@@ -339,7 +339,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
     print '</td></tr>';
 
     // Activate email creation to user
-    print '<tr class="pair"><td>' . $langs->trans("TicketsDisableCustomerEmail") . '</td>';
+    print '<tr class="pair"><td>'.$langs->trans("TicketsDisableCustomerEmail").'</td>';
     print '<td class="left">';
     if ($conf->use_javascript_ajax) {
         print ajax_constantonoff('TICKET_DISABLE_CUSTOMER_MAILS');
@@ -355,9 +355,9 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
 
     // Texte de création d'un ticket
     $mail_mesg_new = $conf->global->TICKET_MESSAGE_MAIL_NEW ? $conf->global->TICKET_MESSAGE_MAIL_NEW : $langs->trans('TicketNewEmailBody');
-    print '<tr><td>' . $langs->trans("TicketNewEmailBodyLabel") . '</label>';
+    print '<tr><td>'.$langs->trans("TicketNewEmailBodyLabel").'</label>';
     print '</td><td>';
-    require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
+    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
     $doleditor = new DolEditor('TICKET_MESSAGE_MAIL_NEW', $mail_mesg_new, '100%', 120, 'dolibarr_mailings', '', false, true, $conf->global->FCKEDITOR_ENABLE_MAIL, ROWS_2, 70);
     $doleditor->Create();
     print '</td>';
@@ -367,9 +367,9 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
 
     // Url public interface
     $url_interface = $conf->global->TICKET_URL_PUBLIC_INTERFACE;
-    print '<tr><td>' . $langs->trans("TicketUrlPublicInterfaceLabelAdmin") . '</label>';
+    print '<tr><td>'.$langs->trans("TicketUrlPublicInterfaceLabelAdmin").'</label>';
     print '</td><td>';
-    print '<input type="text" name="TICKET_URL_PUBLIC_INTERFACE" value="' . $conf->global->TICKET_URL_PUBLIC_INTERFACE . '" size="40" ></td>';
+    print '<input type="text" name="TICKET_URL_PUBLIC_INTERFACE" value="'.$conf->global->TICKET_URL_PUBLIC_INTERFACE.'" size="40" ></td>';
     print '</td>';
     print '<td align="center">';
     print $form->textwithpicto('', $langs->trans("TicketUrlPublicInterfaceHelpAdmin"), 1, 'help');
@@ -377,7 +377,7 @@ if (! empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
 
     print '</table>';
 
-    print '<div class="center"><input type="submit" class="button" value="' . $langs->trans("Save") . '"></div>';
+    print '<div class="center"><input type="submit" class="button" value="'.$langs->trans("Save").'"></div>';
 
     print '</form>';
 }

+ 23 - 23
htdocs/api/admin/explorer.php

@@ -64,18 +64,18 @@ foreach ($modulesdir as $dir)
      */
     //dol_syslog("Scan directory ".$dir." for API modules");
 
-    $handle=@opendir(dol_osencode($dir));
+    $handle = @opendir(dol_osencode($dir));
     if (is_resource($handle))
     {
-        while (($file = readdir($handle))!==false)
+        while (($file = readdir($handle)) !== false)
         {
             if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg))
             {
-                $modulename=$reg[1];
+                $modulename = $reg[1];
 
                 // Defined if module is enabled
-                $enabled=true;
-                $module=$part=$obj=strtolower(preg_replace('/^mod/i', '', $modulename));
+                $enabled = true;
+                $module = $part = $obj = strtolower(preg_replace('/^mod/i', '', $modulename));
                 //if ($part == 'propale') $part='propal';
                 if ($module == 'societe') {
 					$obj = 'thirdparty';
@@ -91,10 +91,10 @@ foreach ($modulesdir as $dir)
                 if ($module == 'ficheinter') {
                     $obj = 'fichinter';
                     $part = 'fichinter';
-                    $module='fichinter';
+                    $module = 'fichinter';
                 }
 
-                if (empty($conf->$module->enabled)) $enabled=false;
+                if (empty($conf->$module->enabled)) $enabled = false;
 
                 if ($enabled) {
                     /*
@@ -107,10 +107,10 @@ foreach ($modulesdir as $dir)
                      */
                     $dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/';
 
-                    $handle_part=@opendir(dol_osencode($dir_part));
+                    $handle_part = @opendir(dol_osencode($dir_part));
                     if (is_resource($handle_part))
                     {
-                        while (($file_searched = readdir($handle_part))!==false)
+                        while (($file_searched = readdir($handle_part)) !== false)
                         {
                             if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg))
                             {
@@ -160,43 +160,43 @@ foreach ($modulesdir as $dir)
 }
 
 //var_dump($listofapis);
-$listofapis=Routes::toArray();          // TODO api for "status" is lost here
+$listofapis = Routes::toArray(); // TODO api for "status" is lost here
 //var_dump($listofapis);
 
 
 llxHeader();
 
-$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
+$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
 print load_fiche_titre($langs->trans("ApiSetup"), $linkback, 'title_setup');
 
 // Define $urlwithroot
-$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
-$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
+$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
 //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
 
 // Show message
 print '<br>';
-$message='';
-$url='<a href="'.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword" target="_blank">'.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword[&reset=1]</a>';
-$message.=$langs->trans("UrlToGetKeyToUseAPIs").':<br>';
-$message.=img_picto('', 'globe').' '.$url;
+$message = '';
+$url = '<a href="'.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword" target="_blank">'.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword[&reset=1]</a>';
+$message .= $langs->trans("UrlToGetKeyToUseAPIs").':<br>';
+$message .= img_picto('', 'globe').' '.$url;
 print $message;
 print '<br>';
 print '<br>';
 
-$oldclass='';
+$oldclass = '';
 
 print $langs->trans("ListOfAvailableAPIs").':<br>';
-foreach($listofapis['v1'] as $key => $val)
+foreach ($listofapis['v1'] as $key => $val)
 {
     if ($key == 'login') continue;
     if ($key == 'index') continue;
 
     if ($key)
     {
-        foreach($val as $method => $val2)
+        foreach ($val as $method => $val2)
         {
-            $newclass=$val2['className'];
+            $newclass = $val2['className'];
 
             if (preg_match('/restler/i', $newclass)) continue;
 
@@ -206,8 +206,8 @@ foreach($listofapis['v1'] as $key => $val)
                 $oldclass = $newclass;
             }
             //print $key.' - '.$val['classname'].' - '.$val['fullpath']." - ".DOL_MAIN_URL_ROOT.'/api/index.php/'.strtolower(preg_replace('/Api$/','',$val['classname']))."/xxx<br>\n";
-            $url=$urlwithroot.'/api/index.php/'.$key;
-            $url.='?api_key=token';
+            $url = $urlwithroot.'/api/index.php/'.$key;
+            $url .= '?api_key=token';
             print img_picto('', 'globe').' '.$method.' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
         }
     }

+ 15 - 15
htdocs/api/admin/index.php

@@ -32,10 +32,10 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 // Load translation files required by the page
 $langs->load("admin");
 
-if (! $user->admin)
+if (!$user->admin)
 	accessforbidden();
 
-$action=GETPOST('action', 'aZ09');
+$action = GETPOST('action', 'aZ09');
 
 //Activate ProfId
 if ($action == 'setproductionmode')
@@ -44,7 +44,7 @@ if ($action == 'setproductionmode')
 
 	if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', 0) > 0)
 	{
-		$error=0;
+		$error = 0;
 
 		if ($status == 1)
 		{
@@ -84,7 +84,7 @@ if ($action == 'save')
 }
 
 
-dol_mkdir(DOL_DATA_ROOT.'/api/temp');		// May have been deleted by a purge
+dol_mkdir(DOL_DATA_ROOT.'/api/temp'); // May have been deleted by a purge
 
 
 /*
@@ -93,7 +93,7 @@ dol_mkdir(DOL_DATA_ROOT.'/api/temp');		// May have been deleted by a purge
 
 llxHeader();
 
-$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
+$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
 print load_fiche_titre($langs->trans("ApiSetup"), $linkback, 'title_setup');
 
 print $langs->trans("ApiDesc")."<br>\n";
@@ -113,16 +113,16 @@ print "</tr>";
 
 print '<tr class="oddeven">';
 print '<td>'.$langs->trans("ApiProductionMode").'</td>';
-$production_mode=(empty($conf->global->API_PRODUCTION_MODE)?false:true);
+$production_mode = (empty($conf->global->API_PRODUCTION_MODE) ?false:true);
 if ($production_mode)
 {
-    print '<td><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setproductionmode&value='.($i+1).'&status=0">';
+    print '<td><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setproductionmode&value='.($i + 1).'&status=0">';
     print img_picto($langs->trans("Activated"), 'switch_on');
     print '</a></td>';
 }
 else
 {
-    print '<td><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setproductionmode&value='.($i+1).'&status=1">';
+    print '<td><a class="reposition" href="'.$_SERVER['PHP_SELF'].'?action=setproductionmode&value='.($i + 1).'&status=1">';
     print img_picto($langs->trans("Disabled"), 'switch_off');
     print '</a></td>';
 }
@@ -144,15 +144,15 @@ print '</form>';
 
 
 // Define $urlwithroot
-$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
-$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
+$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
 //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
 
 // Show message
-$message='';
-$url=$urlwithroot.'/api/index.php/login?login=<strong>auserlogin</strong>&password=<strong>thepassword</strong>[&reset=1]';
-$message.=$langs->trans("UrlToGetKeyToUseAPIs").':<br>';
-$message.=img_picto('', 'globe').' '.$url;
+$message = '';
+$url = $urlwithroot.'/api/index.php/login?login=<strong>auserlogin</strong>&password=<strong>thepassword</strong>[&reset=1]';
+$message .= $langs->trans("UrlToGetKeyToUseAPIs").':<br>';
+$message .= img_picto('', 'globe').' '.$url;
 print $message;
 print '<br>';
 print '<br>';
@@ -161,7 +161,7 @@ print '<br>';
 print '<u>'.$langs->trans("ApiExporerIs").':</u><br>';
 if (dol_is_dir(DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/explorer'))
 {
-    $url=DOL_MAIN_URL_ROOT.'/api/index.php/explorer';
+    $url = DOL_MAIN_URL_ROOT.'/api/index.php/explorer';
     print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
 }
 else

+ 23 - 23
htdocs/asset/document.php

@@ -31,12 +31,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("assets","companies"));
+$langs->loadLangs(array("assets", "companies"));
 
 
-$action=GETPOST('action', 'aZ09');
-$confirm=GETPOST('confirm');
-$id=(GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int'));
+$action = GETPOST('action', 'aZ09');
+$confirm = GETPOST('confirm');
+$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int'));
 $ref = GETPOST('ref', 'alpha');
 
 // Security check - Protection if external user
@@ -52,23 +52,23 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $conf->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";
 
 // Initialize technical objects
-$object=new Asset($db);
+$object = new Asset($db);
 $extrafields = new ExtraFields($db);
-$diroutputmassaction=$conf->assets->dir_output . '/temp/massgeneration/'.$user->id;
-$hookmanager->initHooks(array('assetdocument'));     // Note that conf->hooks_modules contains array
+$diroutputmassaction = $conf->assets->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('assetdocument')); // 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
+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->sellyoursaas->multidir_output[$object->entity] . "/packages/" . dol_sanitizeFileName($object->id);
-if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/packages/" . dol_sanitizeFileName($object->ref);
+if ($id > 0 || !empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity]."/packages/".dol_sanitizeFileName($object->ref);
 
 
 
@@ -76,7 +76,7 @@ if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output
  * Actions
  */
 
-include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
+include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
 
 
 /*
@@ -85,8 +85,8 @@ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
 
 $form = new Form($db);
 
-$title=$langs->trans("Assets").' - '.$langs->trans("Files");
-$help_url='';
+$title = $langs->trans("Assets").' - '.$langs->trans("Files");
+$help_url = '';
 //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
 llxHeader('', $title, $help_url);
 
@@ -95,23 +95,23 @@ if ($object->id)
 	/*
 	 * Show tabs
 	 */
-	if (! empty($conf->notification->enabled)) $langs->load("mails");
+	if (!empty($conf->notification->enabled)) $langs->load("mails");
 	$head = asset_prepare_head($object);
 
 	dol_fiche_head($head, 'document', $langs->trans("Asset"), -1, 'generic');
 
 
 	// 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)
+	$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'];
+		$totalsize += $file['size'];
 	}
 
 	// Object card
 	// ------------------------------------------------------------
-	$linkback = '<a href="' .dol_buildpath('/asset/list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
+	$linkback = '<a href="'.dol_buildpath('/asset/list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
 	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
 
@@ -137,12 +137,12 @@ if ($object->id)
 	$permission = 1;
 	//$permtoedit = $user->rights->asset->create;
 	$permtoedit = 1;
-	$param = '&id=' . $object->id;
+	$param = '&id='.$object->id;
 
 	//$relativepathwithnofile='asset/' . dol_sanitizeFileName($object->id).'/';
-	$relativepathwithnofile='asset/' . dol_sanitizeFileName($object->ref).'/';
+	$relativepathwithnofile = 'asset/'.dol_sanitizeFileName($object->ref).'/';
 
-	include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
+	include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
 }
 else
 {

+ 16 - 16
htdocs/asset/note.php

@@ -27,20 +27,20 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("asset","companies"));
+$langs->loadLangs(array("asset", "companies"));
 
 // Get parameters
-$id			= GETPOST('id', 'int');
+$id = GETPOST('id', 'int');
 $ref        = GETPOST('ref', 'alpha');
-$action		= GETPOST('action', 'alpha');
+$action = GETPOST('action', 'alpha');
 $cancel     = GETPOST('cancel', 'aZ09');
 $backtopage = GETPOST('backtopage', 'alpha');
 
 // Initialize technical objects
-$object=new Asset($db);
+$object = new Asset($db);
 $extrafields = new ExtraFields($db);
-$diroutputmassaction=$conf->asset->dir_output . '/temp/massgeneration/'.$user->id;
-$hookmanager->initHooks(array('assetnote'));     // Note that conf->hooks_modules contains array
+$diroutputmassaction = $conf->asset->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('assetnote')); // Note that conf->hooks_modules contains array
 
 // Fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label($object->table_element);
@@ -51,10 +51,10 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 //$result = restrictedArea($user, 'asset', $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->asset->multidir_output[$object->entity] . "/" . $object->id;
+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;
 
-$permissionnote=1;
+$permissionnote = 1;
 //$permissionnote=$user->rights->asset->creer;	// Used by the include of actions_setnotes.inc.php
 
 
@@ -62,7 +62,7 @@ $permissionnote=1;
  * Actions
  */
 
-include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include, not include_once
+include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
 
 
 /*
@@ -72,10 +72,10 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include,
 $form = new Form($db);
 
 //$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes';
-$help_url='';
+$help_url = '';
 llxHeader('', $langs->trans('Assets'), $help_url);
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	$object->fetch_thirdparty();
 
@@ -85,9 +85,9 @@ if ($id > 0 || ! empty($ref))
 
 	// Object card
 	// ------------------------------------------------------------
-	$linkback = '<a href="' .dol_buildpath('/asset/list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
+	$linkback = '<a href="'.dol_buildpath('/asset/list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
-	$morehtmlref='<div class="refidno">';
+	$morehtmlref = '<div class="refidno">';
 	/*
 	// Ref customer
 	$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
@@ -127,7 +127,7 @@ if ($id > 0 || ! empty($ref))
 	        }
 	    }
 	}*/
-	$morehtmlref.='</div>';
+	$morehtmlref .= '</div>';
 
 
 	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
@@ -137,7 +137,7 @@ if ($id > 0 || ! empty($ref))
 	print '<div class="underbanner clearboth"></div>';
 
 
-	$cssclass="titlefield";
+	$cssclass = "titlefield";
 	include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
 
 	print '</div>';

+ 61 - 61
htdocs/asset/type.php

@@ -26,9 +26,9 @@ 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");
@@ -40,25 +40,25 @@ $backtopage = GETPOST('backtopage', 'alpha');
 
 $type = GETPOST('type', 'alpha');
 
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOST("page", 'int');
 if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
-$offset = $limit * $page ;
+$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');
-$accountancy_code_depreciation_asset=GETPOST('accountancy_code_depreciation_asset', 'string');
-$accountancy_code_depreciation_expense=GETPOST('accountancy_code_depreciation_expense', 'string');
-$comment=GETPOST('comment', 'string');
+$label = GETPOST("label", "alpha");
+$accountancy_code_asset = GETPOST('accountancy_code_asset', 'string');
+$accountancy_code_depreciation_asset = GETPOST('accountancy_code_depreciation_asset', 'string');
+$accountancy_code_depreciation_expense = GETPOST('accountancy_code_depreciation_expense', 'string');
+$comment = GETPOST('comment', 'string');
 
 // Security check
-$result=restrictedArea($user, 'asset', $rowid, 'asset_type');
+$result = restrictedArea($user, 'asset', $rowid, 'asset_type');
 
 $object = new AssetType($db);
 
@@ -69,13 +69,13 @@ $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
 {
-	$type="";
-	$sall="";
+	$type = "";
+	$sall = "";
 }
 
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('assettypecard','globalcard'));
+$hookmanager->initHooks(array('assettypecard', 'globalcard'));
 
 
 /*
@@ -94,11 +94,11 @@ if ($cancel) {
 
 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);
-	$object->accountancy_code_depreciation_expense	= trim($accountancy_code_depreciation_expense);
-	$object->note									= trim($comment);
+	$object->label = trim($label);
+	$object->accountancy_code_asset = trim($accountancy_code_asset);
+	$object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset);
+	$object->accountancy_code_depreciation_expense = trim($accountancy_code_depreciation_expense);
+	$object->note = trim($comment);
 
 	// Fill array 'array_options' with data from add form
 	$ret = $extrafields->setOptionalsFromPost(null, $object);
@@ -121,9 +121,9 @@ if ($action == 'add' && $user->rights->asset->write)
 		}
 	}
 
-	if (! $error)
+	if (!$error)
 	{
-		$id=$object->create($user);
+		$id = $object->create($user);
 		if ($id > 0)
 		{
 			header("Location: ".$_SERVER["PHP_SELF"]);
@@ -147,19 +147,19 @@ if ($action == 'update' && $user->rights->asset->write)
 
 	$object->oldcopy = clone $object;
 
-	$object->label									= trim($label);
-	$object->accountancy_code_asset					= trim($accountancy_code_asset);
-	$object->accountancy_code_depreciation_asset	= trim($accountancy_code_depreciation_asset);
-	$object->accountancy_code_depreciation_expense	= trim($accountancy_code_depreciation_expense);
-	$object->note									= trim($comment);
+	$object->label = trim($label);
+	$object->accountancy_code_asset = trim($accountancy_code_asset);
+	$object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset);
+	$object->accountancy_code_depreciation_expense = trim($accountancy_code_depreciation_expense);
+	$object->note = trim($comment);
 
 	// Fill array 'array_options' with data from add form
 	$ret = $extrafields->setOptionalsFromPost(null, $object);
 	if ($ret < 0) $error++;
 
-	$ret=$object->update($user);
+	$ret = $object->update($user);
 
-	if ($ret >= 0 && ! count($object->errors))
+	if ($ret >= 0 && !count($object->errors))
 	{
 		setEventMessages($langs->trans("AssetsTypeModified"), null, 'mesgs');
 	}
@@ -175,7 +175,7 @@ if ($action == 'update' && $user->rights->asset->write)
 if ($action == 'confirm_delete' && $user->rights->asset->write)
 {
 	$object->fetch($rowid);
-	$res=$object->delete();
+	$res = $object->delete();
 
 	if ($res > 0)
 	{
@@ -186,7 +186,7 @@ if ($action == 'confirm_delete' && $user->rights->asset->write)
 	else
 	{
 		setEventMessages($langs->trans("AssetsTypeCanNotBeDeleted"), null, 'errors');
-		$action='';
+		$action = '';
 	}
 }
 
@@ -195,20 +195,20 @@ if ($action == 'confirm_delete' && $user->rights->asset->write)
  * View
  */
 
-$form=new Form($db);
+$form = new Form($db);
 
-$helpurl='';
+$helpurl = '';
 llxHeader('', $langs->trans("AssetsTypeSetup"), $helpurl);
 
 
 // List of asset type
-if (! $rowid && $action != 'create' && $action != 'edit')
+if (!$rowid && $action != 'create' && $action != 'edit')
 {
 	//dol_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";
-	$sql.= " FROM ".MAIN_DB_PREFIX."asset_type as d";
-	$sql.= " WHERE d.entity IN (".getEntity('asset_type').")";
+	$sql .= " FROM ".MAIN_DB_PREFIX."asset_type as d";
+	$sql .= " WHERE d.entity IN (".getEntity('asset_type').")";
 
 	$result = $db->query($sql);
 	if ($result)
@@ -220,12 +220,12 @@ if (! $rowid && $action != 'create' && $action != 'edit')
 
 		$param = '';
 
-        $newcardbutton='';
+        $newcardbutton = '';
         if ($user->rights->asset->configurer)
         {
-            $newcardbutton='<a class="butActionNew" href="'.DOL_URL_ROOT.'/asset/type.php?action=create"><span class="valignmiddle text-plus-circle">'.$langs->trans('NewAssetType').'</span>';
-            $newcardbutton.= '<span class="fa fa-plus-circle valignmiddle"></span>';
-            $newcardbutton.= '</a>';
+            $newcardbutton = '<a class="butActionNew" href="'.DOL_URL_ROOT.'/asset/type.php?action=create"><span class="valignmiddle text-plus-circle">'.$langs->trans('NewAssetType').'</span>';
+            $newcardbutton .= '<span class="fa fa-plus-circle valignmiddle"></span>';
+            $newcardbutton .= '</a>';
         }
 
 		print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@@ -242,7 +242,7 @@ if (! $rowid && $action != 'create' && $action != 'edit')
 		$moreforfilter = '';
 
 		print '<div class="div-table-responsive">';
-		print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
+		print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
 
 		print '<tr class="liste_titre">';
 		print '<th>'.$langs->trans("Ref").'</th>';
@@ -271,7 +271,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);
@@ -283,7 +283,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);
@@ -295,7 +295,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);
@@ -333,7 +333,7 @@ if (! $rowid && $action != 'create' && $action != 'edit')
 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"));
 
@@ -348,7 +348,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>';
@@ -390,8 +390,8 @@ if ($action == 'create')
 	print '<textarea name="comment" wrap="soft" class="centpercent" rows="3"></textarea></td></tr>';
 
 	// Other attributes
-	$parameters=array();
-	$reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $act, $action);    // Note that $action and $object may have been modified by hook
+	$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))
 	{
@@ -438,11 +438,11 @@ if ($rowid > 0)
 
 		$linkback = '<a href="'.DOL_URL_ROOT.'/asset/type.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-		$morehtmlref='<div class="refidno">';
+		$morehtmlref = '<div class="refidno">';
 		// Ref asset type
-		$morehtmlref.=$form->editfieldkey("Label", 'label', $object->label, $object, $user->rights->asset->write, 'string', '', 0, 1);
-		$morehtmlref.=$form->editfieldval("Label", 'label', $object->label, $object, $user->rights->asset->write, 'string', '', null, null, '', 1);
-		$morehtmlref.='</div>';
+		$morehtmlref .= $form->editfieldkey("Label", 'label', $object->label, $object, $user->rights->asset->write, 'string', '', 0, 1);
+		$morehtmlref .= $form->editfieldval("Label", 'label', $object->label, $object, $user->rights->asset->write, 'string', '', null, null, '', 1);
+		$morehtmlref .= '</div>';
 
 		dol_banner_tab($object, 'rowid', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright);
 
@@ -455,7 +455,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);
@@ -471,7 +471,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);
@@ -487,7 +487,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);
@@ -503,7 +503,7 @@ if ($rowid > 0)
 		print nl2br($object->note)."</td></tr>";
 
 		// Other attributes
-		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
 		print '</table>';
 		print '</div>';
@@ -542,7 +542,7 @@ if ($rowid > 0)
 		$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);
 
@@ -559,7 +559,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>';
@@ -601,8 +601,8 @@ if ($rowid > 0)
 		print '<textarea name="comment" wrap="soft" class="centpercent" rows="3">'.$object->note.'</textarea></td></tr>';
 
 		// Other attributes
-		$parameters=array();
-		$reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $act, $action);    // Note that $action and $object may have been modified by hook
+		$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))
 		{

+ 32 - 32
htdocs/bom/bom_agenda.php

@@ -65,20 +65,20 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (! $sortfield) $sortfield='a.datep,a.id';
-if (! $sortorder) $sortorder='DESC';
+if (!$sortfield) $sortfield = 'a.datep,a.id';
+if (!$sortorder) $sortorder = 'DESC';
 
 // Initialize technical objects
-$object=new BOM($db);
+$object = new BOM($db);
 $extrafields = new ExtraFields($db);
-$diroutputmassaction=$conf->bom->dir_output . '/temp/massgeneration/'.$user->id;
-$hookmanager->initHooks(array('bomagenda','globalcard'));     // Note that conf->hooks_modules contains array
+$diroutputmassaction = $conf->bom->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('bomagenda', '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->bom->multidir_output[$object->entity] . "/" . $object->id;
+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->bom->multidir_output[$object->entity]."/".$object->id;
 
 
 
@@ -86,14 +86,14 @@ if ($id > 0 || ! empty($ref)) $upload_dir = $conf->bom->multidir_output[$object-
  *	Actions
  */
 
-$parameters=array('id'=>$socid);
-$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
+$parameters = array('id'=>$socid);
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
 
 if (empty($reshook))
 {
     // Cancel
-    if (GETPOST('cancel', 'alpha') && ! empty($backtopage))
+    if (GETPOST('cancel', 'alpha') && !empty($backtopage))
     {
         header("Location: ".$backtopage);
         exit;
@@ -102,8 +102,8 @@ if (empty($reshook))
     // 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='';
+        $actioncode = '';
+        $search_agenda_label = '';
     }
 }
 
@@ -119,12 +119,12 @@ $form = new Form($db);
 
 if ($object->id > 0)
 {
-	$title=$langs->trans("Agenda");
+	$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 = bomPrepareHead($object);
 
 
@@ -132,9 +132,9 @@ if ($object->id > 0)
 
 	// Object card
 	// ------------------------------------------------------------
-	$linkback = '<a href="' .dol_buildpath('/bom/myobject_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
+	$linkback = '<a href="'.dol_buildpath('/bom/myobject_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
-	$morehtmlref='<div class="refidno">';
+	$morehtmlref = '<div class="refidno">';
 	/*
 	 // Ref customer
 	 $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
@@ -174,7 +174,7 @@ if ($object->id > 0)
 	 	}
 	 	}
 	 	}*/
-	$morehtmlref.='</div>';
+	$morehtmlref .= '</div>';
 
 
 	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
@@ -193,16 +193,16 @@ if ($object->id > 0)
 
 	// Actions buttons
 
-    $objthirdparty=$object;
-    $objcon=new stdClass();
+    $objthirdparty = $object;
+    $objcon = new stdClass();
 
-    $out='&origin='.$object->element.'&originid='.$object->id;
-    $permok=$user->rights->agenda->myactions->create;
-    if ((! empty($objthirdparty->id) || ! empty($objcon->id)) && $permok)
+    $out = '&origin='.$object->element.'&originid='.$object->id;
+    $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.='&amp;socid='.$objthirdparty->id;
-        $out.=(! empty($objcon->id)?'&amp;contactid='.$objcon->id:'').'&amp;backtopage=1&amp;percentage=-1';
+        if (get_class($objthirdparty) == 'Societe') $out .= '&amp;socid='.$objthirdparty->id;
+        $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1';
     	//$out.=$langs->trans("AddAnAction").' ';
     	//$out.=img_picto($langs->trans("AddAnAction"),'filenew');
     	//$out.="</a>";
@@ -211,9 +211,9 @@ if ($object->id > 0)
 
 	print '<div class="tabsAction">';
 
-    if (! empty($conf->agenda->enabled))
+    if (!empty($conf->agenda->enabled))
     {
-    	if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create))
+    	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>';
     	}
@@ -225,18 +225,18 @@ 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);
+    	$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("ActionsOnBom"), '', '');
 
         // List of all actions
-		$filters=array();
-        $filters['search_agenda_label']=$search_agenda_label;
+		$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);

+ 22 - 22
htdocs/bom/bom_document.php

@@ -32,12 +32,12 @@ require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
 require_once DOL_DOCUMENT_ROOT.'/bom/lib/bom.lib.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("mrp","companies","other","mails"));
+$langs->loadLangs(array("mrp", "companies", "other", "mails"));
 
 
-$action=GETPOST('action', 'aZ09');
-$confirm=GETPOST('confirm', 'alpha');
-$id=(GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int'));
+$action = GETPOST('action', 'aZ09');
+$confirm = GETPOST('confirm', 'alpha');
+$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int'));
 $ref = GETPOST('ref', 'alpha');
 
 // Security check - Protection if external user
@@ -53,30 +53,30 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $conf->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
-$object=new BOM($db);
+$object = new BOM($db);
 $extrafields = new ExtraFields($db);
-$diroutputmassaction=$conf->bom->dir_output . '/temp/massgeneration/'.$user->id;
-$hookmanager->initHooks(array('bomdocument', 'globalcard'));     // Note that conf->hooks_modules contains array
+$diroutputmassaction = $conf->bom->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('bomdocument', '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
+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->bom->multidir_output[$object->entity?$object->entity:1] . "/bom/" . dol_sanitizeFileName($object->id);
-if ($id > 0 || ! empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity?$object->entity:1] . "/bom/" . dol_sanitizeFileName($object->ref);
+if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".dol_sanitizeFileName($object->ref);
 
 
 /*
  * Actions
  */
 
-include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
+include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
 
 
 /*
@@ -85,8 +85,8 @@ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
 
 $form = new Form($db);
 
-$title=$langs->trans("BillOfMaterials").' - '.$langs->trans("Files");
-$help_url='';
+$title = $langs->trans("BillOfMaterials").' - '.$langs->trans("Files");
+$help_url = '';
 //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
 llxHeader('', $title, $help_url);
 
@@ -101,16 +101,16 @@ 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)
+	$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'];
+		$totalsize += $file['size'];
 	}
 
 	// Object card
 	// ------------------------------------------------------------
-	$linkback = '<a href="' .dol_buildpath('/bom/bom_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
+	$linkback = '<a href="'.dol_buildpath('/bom/bom_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
 	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
 
@@ -134,12 +134,12 @@ if ($object->id)
 	$modulepart = 'bom';
 	$permission = $user->rights->bom->write;
 	$permtoedit = $user->rights->bom->write;
-	$param = '&id=' . $object->id;
+	$param = '&id='.$object->id;
 
 	//$relativepathwithnofile='bom/' . dol_sanitizeFileName($object->id).'/';
-	$relativepathwithnofile='bom/' . dol_sanitizeFileName($object->ref).'/';
+	$relativepathwithnofile = 'bom/'.dol_sanitizeFileName($object->ref).'/';
 
-	include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
+	include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
 }
 else
 {

+ 16 - 16
htdocs/bom/bom_note.php

@@ -28,20 +28,20 @@ require_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
 require_once DOL_DOCUMENT_ROOT.'/bom/lib/bom.lib.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("mrp","companies"));
+$langs->loadLangs(array("mrp", "companies"));
 
 // Get parameters
-$id			= GETPOST('id', 'int');
+$id = GETPOST('id', 'int');
 $ref        = GETPOST('ref', 'alpha');
-$action		= GETPOST('action', 'alpha');
+$action = GETPOST('action', 'alpha');
 $cancel     = GETPOST('cancel', 'aZ09');
 $backtopage = GETPOST('backtopage', 'alpha');
 
 // Initialize technical objects
-$object=new BOM($db);
+$object = new BOM($db);
 $extrafields = new ExtraFields($db);
-$diroutputmassaction=$conf->bom->dir_output . '/temp/massgeneration/'.$user->id;
-$hookmanager->initHooks(array('bomnote','globalcard'));     // Note that conf->hooks_modules contains array
+$diroutputmassaction = $conf->bom->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('bomnote', 'globalcard')); // Note that conf->hooks_modules contains array
 
 // Fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label($object->table_element);
@@ -52,10 +52,10 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 //$result = restrictedArea($user, 'bom', $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->bom->multidir_output[$object->entity] . "/" . $object->id;
+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->bom->multidir_output[$object->entity]."/".$object->id;
 
-$permissionnote=1;
+$permissionnote = 1;
 //$permissionnote=$user->rights->bom->creer;	// Used by the include of actions_setnotes.inc.php
 
 
@@ -64,7 +64,7 @@ $permissionnote=1;
  * Actions
  */
 
-include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include, not include_once
+include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
 
 
 /*
@@ -74,10 +74,10 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include,
 $form = new Form($db);
 
 //$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes';
-$help_url='';
+$help_url = '';
 llxHeader('', $langs->trans('BillOfMaterials'), $help_url);
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	$object->fetch_thirdparty();
 
@@ -87,9 +87,9 @@ if ($id > 0 || ! empty($ref))
 
 	// Object card
 	// ------------------------------------------------------------
-	$linkback = '<a href="' .dol_buildpath('/bom/bom_list.php', 1) . '?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
+	$linkback = '<a href="'.dol_buildpath('/bom/bom_list.php', 1).'?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
-	$morehtmlref='<div class="refidno">';
+	$morehtmlref = '<div class="refidno">';
 	/*
 	// Ref customer
 	$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1);
@@ -129,7 +129,7 @@ if ($id > 0 || ! empty($ref))
 	        }
 	    }
 	}*/
-	$morehtmlref.='</div>';
+	$morehtmlref .= '</div>';
 
 
 	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
@@ -139,7 +139,7 @@ if ($id > 0 || ! empty($ref))
 	print '<div class="underbanner clearboth"></div>';
 
 
-	$cssclass="titlefield";
+	$cssclass = "titlefield";
 	include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
 
 	print '</div>';

+ 4 - 4
htdocs/bom/tpl/objectline_create.tpl.php

@@ -30,7 +30,7 @@
  */
 
 // Protection to avoid direct call of template
-if (empty($object) || ! is_object($object)) {
+if (empty($object) || !is_object($object)) {
     print "Error: this template page cannot be called directly as an URL";
     exit;
 }
@@ -38,11 +38,11 @@ if (empty($object) || ! is_object($object)) {
 
 global $forceall, $forcetoshowtitlelines;
 
-if (empty($forceall)) $forceall=0;
+if (empty($forceall)) $forceall = 0;
 
 
 // Define colspan for the button 'Add'
-$colspan = 3;	// Columns: total ht + col edit + col delete
+$colspan = 3; // Columns: total ht + col edit + col delete
 //print $object->element;
 
 // Lines for extrafield
@@ -141,7 +141,7 @@ print '</td>';
 print '</tr>';
 
 if (is_object($objectline)) {
-	print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
+	print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1);
 }
 ?>
 

+ 5 - 5
htdocs/bom/tpl/objectline_edit.tpl.php

@@ -32,7 +32,7 @@
  */
 
 // Protection to avoid direct call of template
-if (empty($object) || ! is_object($object))
+if (empty($object) || !is_object($object))
 {
 	print "Error, template page can't be called as URL";
 	exit;
@@ -41,11 +41,11 @@ if (empty($object) || ! is_object($object))
 
 global $forceall;
 
-if (empty($forceall)) $forceall=0;
+if (empty($forceall)) $forceall = 0;
 
 
 // Define colspan for the button 'Add'
-$colspan = 3;	// Columns: total ht + col edit + col delete
+$colspan = 3; // Columns: total ht + col edit + col delete
 
 // Lines for extrafield
 $objectline = new BOMLine($this->db);
@@ -67,7 +67,7 @@ $coldisplay++;
 
 	<input type="hidden" name="lineid" value="<?php echo $line->id; ?>">
 	<input type="hidden" id="product_type" name="type" value="<?php echo $line->product_type; ?>">
-	<input type="hidden" id="product_id" name="productid" value="<?php echo (! empty($line->fk_product)?$line->fk_product:0); ?>" />
+	<input type="hidden" id="product_id" name="productid" value="<?php echo (!empty($line->fk_product) ? $line->fk_product : 0); ?>" />
 	<input type="hidden" id="special_code" name="special_code" value="<?php echo $line->special_code; ?>">
 	<input type="hidden" id="fk_parent_line" name="fk_parent_line" value="<?php echo $line->fk_parent_line; ?>">
 
@@ -138,7 +138,7 @@ print '</td>';
 print '</tr>';
 
 if (is_object($objectline)) {
-	print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
+	print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1);
 }
 
 print "<!-- END PHP TEMPLATE objectline_edit.tpl.php -->\n";

+ 7 - 7
htdocs/bom/tpl/objectline_view.tpl.php

@@ -35,7 +35,7 @@
  */
 
 // Protection to avoid direct call of template
-if (empty($object) || ! is_object($object))
+if (empty($object) || !is_object($object))
 {
 	print "Error, template page can't be called as URL";
 	exit;
@@ -44,11 +44,11 @@ if (empty($object) || ! is_object($object))
 
 global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax;
 
-if (empty($dateSelector)) $dateSelector=0;
-if (empty($forceall)) $forceall=0;
-if (empty($senderissupplier)) $senderissupplier=0;
-if (empty($inputalsopricewithtax)) $inputalsopricewithtax=0;
-if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0;
+if (empty($dateSelector)) $dateSelector = 0;
+if (empty($forceall)) $forceall = 0;
+if (empty($senderissupplier)) $senderissupplier = 0;
+if (empty($inputalsopricewithtax)) $inputalsopricewithtax = 0;
+if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax = 0;
 
 // add html5 elements
 $domData  = ' data-element="'.$line->element.'"';
@@ -155,7 +155,7 @@ print '</tr>';
 //Line extrafield
 if (!empty($extrafields))
 {
-	print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"','colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
+	print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1);
 }
 
 print "<!-- END PHP TEMPLATE objectline_view.tpl.php -->\n";

+ 18 - 18
htdocs/categories/card.php

@@ -35,23 +35,23 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
 $langs->load("categories");
 
 // Security check
-$socid=GETPOST('socid', 'int');
+$socid = GETPOST('socid', 'int');
 if (!$user->rights->categorie->lire) accessforbidden();
 
 $action		= GETPOST('action', 'alpha');
 $cancel		= GETPOST('cancel', 'alpha');
 $origin		= GETPOST('origin', 'alpha');
-$catorigin	= GETPOST('catorigin', 'int');
-$type 		= GETPOST('type', 'alpha');
+$catorigin = GETPOST('catorigin', 'int');
+$type = GETPOST('type', 'alpha');
 $urlfrom	= GETPOST('urlfrom', 'alpha');
 $backtopage = GETPOST('backtopage', 'alpha');
 
-$socid=GETPOST('socid', 'int');
-$label=GETPOST('label');
-$description=GETPOST('description');
-$color=GETPOST('color');
-$visible=GETPOST('visible');
-$parent=GETPOST('parent');
+$socid = GETPOST('socid', 'int');
+$label = GETPOST('label');
+$description = GETPOST('description');
+$color = GETPOST('color');
+$visible = GETPOST('visible');
+$parent = GETPOST('parent');
 
 if ($origin)
 {
@@ -130,17 +130,17 @@ if ($action == 'add' && $user->rights->categorie->creer)
 
 	$object->label			= $label;
 	$object->color			= $color;
-	$object->description	= dol_htmlcleanlastbr($description);
+	$object->description = dol_htmlcleanlastbr($description);
 	$object->socid			= ($socid ? $socid : 'null');
-	$object->visible		= $visible;
-	$object->type			= $type;
+	$object->visible = $visible;
+	$object->type = $type;
 
 	if ($parent != "-1") $object->fk_parent = $parent;
 
 	$ret = $extrafields->setOptionalsFromPost(null, $object);
 	if ($ret < 0) $error++;
 
-	if (! $object->label)
+	if (!$object->label)
 	{
 		$error++;
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors');
@@ -148,7 +148,7 @@ if ($action == 'add' && $user->rights->categorie->creer)
 	}
 
 	// Create category in database
-	if (! $error)
+	if (!$error)
 	{
 		$result = $object->create($user);
 		if ($result > 0)
@@ -223,7 +223,7 @@ if (($action == 'add' || $action == 'confirmed') && $user->rights->categorie->cr
 $form = new Form($db);
 $formother = new FormOther($db);
 
-$helpurl='';
+$helpurl = '';
 llxHeader("", $langs->trans("Categories"), $helpurl);
 
 if ($user->rights->categorie->creer)
@@ -258,7 +258,7 @@ if ($user->rights->categorie->creer)
 		// Description
 		print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td>';
 		require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-		$doleditor=new DolEditor('description', $description, '', 200, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_6, '90%');
+		$doleditor = new DolEditor('description', $description, '', 200, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_6, '90%');
 		$doleditor->Create();
 		print '</td></tr>';
 
@@ -273,8 +273,8 @@ if ($user->rights->categorie->creer)
 		print ajax_combobox('parent');
 		print '</td></tr>';
 
-		$parameters=array();
-		$reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+		$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))
 		{

+ 19 - 19
htdocs/categories/edit.php

@@ -32,19 +32,19 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
 // Load translation files required by the page
 $langs->load("categories");
 
-$id=GETPOST('id', 'int');
-$ref=GETPOST('ref');
-$type=GETPOST('type');
-$action=(GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'edit');
-$confirm=GETPOST('confirm');
-$cancel=GETPOST('cancel', 'alpha');
-
-$socid=GETPOST('socid', 'int');
-$label=GETPOST('label');
-$description=GETPOST('description');
-$color=GETPOST('color', 'alpha');
-$visible=GETPOST('visible');
-$parent=GETPOST('parent');
+$id = GETPOST('id', 'int');
+$ref = GETPOST('ref');
+$type = GETPOST('type');
+$action = (GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'edit');
+$confirm = GETPOST('confirm');
+$cancel = GETPOST('cancel', 'alpha');
+
+$socid = GETPOST('socid', 'int');
+$label = GETPOST('label');
+$description = GETPOST('description');
+$color = GETPOST('color', 'alpha');
+$visible = GETPOST('visible');
+$parent = GETPOST('parent');
 
 if ($id == "")
 {
@@ -58,7 +58,7 @@ $result = restrictedArea($user, 'categorie', $id, '&category');
 $object = new Categorie($db);
 if ($id > 0)
 {
-    $result=$object->fetch($id);
+    $result = $object->fetch($id);
 }
 
 $extrafields = new ExtraFields($db);
@@ -100,12 +100,12 @@ if ($action == 'update' && $user->rights->categorie->creer)
 		$action = 'edit';
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors');
 	}
-	if (! $error && empty($object->error))
+	if (!$error && empty($object->error))
 	{
 		$ret = $extrafields->setOptionalsFromPost(null, $object);
 		if ($ret < 0) $error++;
 
-		if (! $error && $object->update($user) > 0)
+		if (!$error && $object->update($user) > 0)
 		{
 			header('Location: '.DOL_URL_ROOT.'/categories/viewcat.php?id='.$object->id.'&type='.$type);
 			exit;
@@ -159,7 +159,7 @@ print '<tr>';
 print '<td>'.$langs->trans("Description").'</td>';
 print '<td >';
 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-$doleditor=new DolEditor('description', $object->description, '', 200, 'dolibarr_notes', '', false, true, $conf->fckeditor->enabled, ROWS_6, '90%');
+$doleditor = new DolEditor('description', $object->description, '', 200, 'dolibarr_notes', '', false, true, $conf->fckeditor->enabled, ROWS_6, '90%');
 $doleditor->Create();
 print '</td></tr>';
 
@@ -175,8 +175,8 @@ print '<tr><td>'.$langs->trans("In").'</td><td>';
 print $form->select_all_categories($type, $object->fk_parent, 'parent', 64, $object->id);
 print '</td></tr>';
 
-$parameters=array();
-$reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+$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))
 {

+ 83 - 83
htdocs/categories/viewcat.php

@@ -40,19 +40,19 @@ $type       = GETPOST('type', 'aZ09');
 $removeelem = GETPOST('removeelem', 'int');
 $elemid     = GETPOST('elemid', 'int');
 
-$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'):'myobjectlist';   // 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')
+$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') : 'myobjectlist'; // 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')
 
 
 // Load variable for pagination
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST('sortfield', 'alpha');
 $sortorder = GETPOST('sortorder', 'alpha');
 $page = GETPOST('page', 'int');
@@ -71,7 +71,7 @@ if ($id == "" && $label == "")
 $result = restrictedArea($user, 'categorie', $id, '&category');
 
 $object = new Categorie($db);
-$result=$object->fetch($id, $label);
+$result = $object->fetch($id, $label);
 if ($result <= 0) {
 	dol_print_error($db, $object->error); exit;
 }
@@ -80,21 +80,21 @@ if ($result <= 0) {
 	dol_print_error($db, $object->error); exit;
 }
 
-$type=$object->type;
-if (is_numeric($type)) $type=Categorie::$MAP_ID_TO_CODE[$type];	// For backward compatibility
+$type = $object->type;
+if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility
 
 $extrafields = new ExtraFields($db);
 $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array array
-$hookmanager->initHooks(array('categorycard','globalcard'));
+$hookmanager->initHooks(array('categorycard', 'globalcard'));
 
 
 /*
  *	Actions
  */
-$parameters=array();
-$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
+$parameters = array();
+$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
 // Remove element from category
 if ($id > 0 && $removeelem > 0)
 {
@@ -145,7 +145,7 @@ if ($id > 0 && $removeelem > 0)
         $elementtype = 'project';
     }
 
-	$result=$object->del_type($tmpobject, $elementtype);
+	$result = $object->del_type($tmpobject, $elementtype);
 	if ($result < 0) dol_print_error('', $object->error);
 }
 
@@ -170,7 +170,7 @@ if ($type == Categorie::TYPE_PRODUCT && $elemid && $action == 'addintocategory'
 	$elementtype = 'product';
 
 	// TODO Add into categ
-	$result=$object->add_type($newobject, $elementtype);
+	$result = $object->add_type($newobject, $elementtype);
 	if ($result >= 0)
 	{
 		setEventMessages($langs->trans("WasAddedSuccessfully", $newobject->ref), null, 'mesgs');
@@ -197,18 +197,18 @@ if ($type == Categorie::TYPE_PRODUCT && $elemid && $action == 'addintocategory'
 $form = new Form($db);
 $formother = new FormOther($db);
 
-$helpurl='';
+$helpurl = '';
 llxHeader("", $langs->trans("Categories"), $helpurl);
 
-if ($type == Categorie::TYPE_PRODUCT)       $title=$langs->trans("ProductsCategoryShort");
-elseif ($type == Categorie::TYPE_SUPPLIER)  $title=$langs->trans("SuppliersCategoryShort");
-elseif ($type == Categorie::TYPE_CUSTOMER)  $title=$langs->trans("CustomersCategoryShort");
-elseif ($type == Categorie::TYPE_MEMBER)    $title=$langs->trans("MembersCategoryShort");
-elseif ($type == Categorie::TYPE_CONTACT)   $title=$langs->trans("ContactCategoriesShort");
-elseif ($type == Categorie::TYPE_ACCOUNT)   $title=$langs->trans("AccountsCategoriesShort");
-elseif ($type == Categorie::TYPE_PROJECT)   $title=$langs->trans("ProjectsCategoriesShort");
-elseif ($type == Categorie::TYPE_USER)      $title=$langs->trans("ProjectsCategoriesShort");
-else                                        $title=$langs->trans("Category");
+if ($type == Categorie::TYPE_PRODUCT)       $title = $langs->trans("ProductsCategoryShort");
+elseif ($type == Categorie::TYPE_SUPPLIER)  $title = $langs->trans("SuppliersCategoryShort");
+elseif ($type == Categorie::TYPE_CUSTOMER)  $title = $langs->trans("CustomersCategoryShort");
+elseif ($type == Categorie::TYPE_MEMBER)    $title = $langs->trans("MembersCategoryShort");
+elseif ($type == Categorie::TYPE_CONTACT)   $title = $langs->trans("ContactCategoriesShort");
+elseif ($type == Categorie::TYPE_ACCOUNT)   $title = $langs->trans("AccountsCategoriesShort");
+elseif ($type == Categorie::TYPE_PROJECT)   $title = $langs->trans("ProjectsCategoriesShort");
+elseif ($type == Categorie::TYPE_USER)      $title = $langs->trans("ProjectsCategoriesShort");
+else                                        $title = $langs->trans("Category");
 
 $head = categories_prepare_head($object, $type);
 
@@ -257,7 +257,7 @@ print $formother->showColor($object->color);
 print '</td></tr>';
 
 // Other attributes
-include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
 print '</table>';
 print '</div>';
@@ -338,13 +338,13 @@ else
 
 
 // List of mass actions available
-$arrayofmassactions =  array(
+$arrayofmassactions = array(
 	//'validate'=>$langs->trans("Validate"),
 	//'generate_doc'=>$langs->trans("ReGeneratePDF"),
 	//'builddoc'=>$langs->trans("PDFMerge"),
 	//'presend'=>$langs->trans("SendByMail"),
 );
-$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
+$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
 
 
 // List of products or services (type is type of category)
@@ -357,7 +357,7 @@ if ($type == Categorie::TYPE_PRODUCT)
 	}
 	else
 	{
-		$showclassifyform=1; $typeid=Categorie::TYPE_PRODUCT;
+		$showclassifyform = 1; $typeid = Categorie::TYPE_PRODUCT;
 
 		// Form to add record into a category
 		if ($showclassifyform)
@@ -408,15 +408,15 @@ if ($type == Categorie::TYPE_PRODUCT)
 				print '<td class="tdtop">'.$prod->label."</td>\n";
 				// Link to delete from category
 				print '<td class="right">';
-				$permission=0;
-				if ($type == Categorie::TYPE_PRODUCT)     $permission=($user->rights->produit->creer || $user->rights->service->creer);
-				if ($type == Categorie::TYPE_SUPPLIER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_CUSTOMER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_MEMBER)      $permission=$user->rights->adherent->creer;
-				if ($type == Categorie::TYPE_PROJECT)     $permission=$user->rights->projet->creer;
+				$permission = 0;
+				if ($type == Categorie::TYPE_PRODUCT)     $permission = ($user->rights->produit->creer || $user->rights->service->creer);
+				if ($type == Categorie::TYPE_SUPPLIER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_CUSTOMER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_MEMBER)      $permission = $user->rights->adherent->creer;
+				if ($type == Categorie::TYPE_PROJECT)     $permission = $user->rights->projet->creer;
 				if ($permission)
 				{
-					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid)?'id':'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$prod->id."'>";
+					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$prod->id."'>";
 					print $langs->trans("DeleteFromCat");
 					print img_picto($langs->trans("DeleteFromCat"), 'unlink');
 					print "</a>";
@@ -472,15 +472,15 @@ if ($type == Categorie::TYPE_SUPPLIER)
 				print "</td>\n";
 				// Link to delete from category
 				print '<td class="right">';
-				$permission=0;
-				if ($type == Categorie::TYPE_PRODUCT)     $permission=($user->rights->produit->creer || $user->rights->service->creer);
-				if ($type == Categorie::TYPE_SUPPLIER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_CUSTOMER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_MEMBER)      $permission=$user->rights->adherent->creer;
-				if ($type == Categorie::TYPE_PROJECT)     $permission=$user->rights->projet->creer;
+				$permission = 0;
+				if ($type == Categorie::TYPE_PRODUCT)     $permission = ($user->rights->produit->creer || $user->rights->service->creer);
+				if ($type == Categorie::TYPE_SUPPLIER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_CUSTOMER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_MEMBER)      $permission = $user->rights->adherent->creer;
+				if ($type == Categorie::TYPE_PROJECT)     $permission = $user->rights->projet->creer;
 				if ($permission)
 				{
-					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid)?'id':'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$soc->id."'>";
+					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$soc->id."'>";
 					print $langs->trans("DeleteFromCat");
 					print img_picto($langs->trans("DeleteFromCat"), 'unlink');
 					print "</a>";
@@ -500,7 +500,7 @@ if ($type == Categorie::TYPE_SUPPLIER)
 	}
 }
 
-if($type == Categorie::TYPE_CUSTOMER)
+if ($type == Categorie::TYPE_CUSTOMER)
 {
 	$socs = $object->getObjectsInCateg("customer", 0, $limit, $offset);
 	if ($socs < 0)
@@ -537,15 +537,15 @@ if($type == Categorie::TYPE_CUSTOMER)
 				print "</td>\n";
 				// Link to delete from category
 				print '<td class="right">';
-				$permission=0;
-				if ($type == Categorie::TYPE_PRODUCT)     $permission=($user->rights->produit->creer || $user->rights->service->creer);
-				if ($type == Categorie::TYPE_SUPPLIER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_CUSTOMER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_MEMBER)      $permission=$user->rights->adherent->creer;
-				if ($type == Categorie::TYPE_PROJECT)     $permission=$user->rights->projet->creer;
+				$permission = 0;
+				if ($type == Categorie::TYPE_PRODUCT)     $permission = ($user->rights->produit->creer || $user->rights->service->creer);
+				if ($type == Categorie::TYPE_SUPPLIER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_CUSTOMER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_MEMBER)      $permission = $user->rights->adherent->creer;
+				if ($type == Categorie::TYPE_PROJECT)     $permission = $user->rights->projet->creer;
 				if ($permission)
 				{
-					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid)?'id':'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$soc->id."'>";
+					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$soc->id."'>";
 					print $langs->trans("DeleteFromCat");
 					print img_picto($langs->trans("DeleteFromCat"), 'unlink');
 					print "</a>";
@@ -600,22 +600,22 @@ if ($type == Categorie::TYPE_MEMBER)
 
 				print "\t".'<tr class="oddeven">'."\n";
 				print '<td class="nowrap" valign="top">';
-				$member->ref=$member->login;
+				$member->ref = $member->login;
 				print $member->getNomUrl(1, 0);
 				print "</td>\n";
 				print '<td class="tdtop">'.$member->lastname."</td>\n";
 				print '<td class="tdtop">'.$member->firstname."</td>\n";
 				// Link to delete from category
 				print '<td class="right">';
-				$permission=0;
-				if ($type == Categorie::TYPE_PRODUCT)     $permission=($user->rights->produit->creer || $user->rights->service->creer);
-				if ($type == Categorie::TYPE_SUPPLIER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_CUSTOMER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_MEMBER)      $permission=$user->rights->adherent->creer;
-				if ($type == Categorie::TYPE_PROJECT)     $permission=$user->rights->projet->creer;
+				$permission = 0;
+				if ($type == Categorie::TYPE_PRODUCT)     $permission = ($user->rights->produit->creer || $user->rights->service->creer);
+				if ($type == Categorie::TYPE_SUPPLIER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_CUSTOMER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_MEMBER)      $permission = $user->rights->adherent->creer;
+				if ($type == Categorie::TYPE_PROJECT)     $permission = $user->rights->projet->creer;
 				if ($permission)
 				{
-					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid)?'id':'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$member->id."'>";
+					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$member->id."'>";
 					print $langs->trans("DeleteFromCat");
 					print img_picto($langs->trans("DeleteFromCat"), 'unlink');
 					print "</a>";
@@ -671,15 +671,15 @@ if ($type == Categorie::TYPE_CONTACT)
 				print "</td>\n";
 				// Link to delete from category
 				print '<td class="right">';
-				$permission=0;
-				if ($type == Categorie::TYPE_PRODUCT)     $permission=($user->rights->produit->creer || $user->rights->service->creer);
-				if ($type == Categorie::TYPE_SUPPLIER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_CUSTOMER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_MEMBER)      $permission=$user->rights->adherent->creer;
-				if ($type == Categorie::TYPE_PROJECT)     $permission=$user->rights->projet->creer;
+				$permission = 0;
+				if ($type == Categorie::TYPE_PRODUCT)     $permission = ($user->rights->produit->creer || $user->rights->service->creer);
+				if ($type == Categorie::TYPE_SUPPLIER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_CUSTOMER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_MEMBER)      $permission = $user->rights->adherent->creer;
+				if ($type == Categorie::TYPE_PROJECT)     $permission = $user->rights->projet->creer;
 				if ($permission)
 				{
-					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid)?'id':'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$contact->id."'>";
+					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$contact->id."'>";
 					print $langs->trans("DeleteFromCat");
 					print img_picto($langs->trans("DeleteFromCat"), 'unlink');
 					print "</a>";
@@ -740,15 +740,15 @@ if ($type == Categorie::TYPE_ACCOUNT)
                 print '<td class="tdtop">'.$account->number."</td>\n";
                 // Link to delete from category
                 print '<td class="right">';
-                $permission=0;
-                if ($type == Categorie::TYPE_PRODUCT)     $permission=($user->rights->produit->creer || $user->rights->service->creer);
-                if ($type == Categorie::TYPE_SUPPLIER)    $permission=$user->rights->societe->creer;
-                if ($type == Categorie::TYPE_CUSTOMER)    $permission=$user->rights->societe->creer;
-                if ($type == Categorie::TYPE_MEMBER)      $permission=$user->rights->adherent->creer;
-                if ($type == Categorie::TYPE_PROJECT)     $permission=$user->rights->projet->creer;
+                $permission = 0;
+                if ($type == Categorie::TYPE_PRODUCT)     $permission = ($user->rights->produit->creer || $user->rights->service->creer);
+                if ($type == Categorie::TYPE_SUPPLIER)    $permission = $user->rights->societe->creer;
+                if ($type == Categorie::TYPE_CUSTOMER)    $permission = $user->rights->societe->creer;
+                if ($type == Categorie::TYPE_MEMBER)      $permission = $user->rights->adherent->creer;
+                if ($type == Categorie::TYPE_PROJECT)     $permission = $user->rights->projet->creer;
                 if ($permission)
                 {
-                    print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid)?'id':'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$account->id."'>";
+                    print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$account->id."'>";
                     print $langs->trans("DeleteFromCat");
                     print img_picto($langs->trans("DeleteFromCat"), 'unlink');
                     print "</a>";
@@ -808,15 +808,15 @@ if ($type == Categorie::TYPE_PROJECT)
 				print '<td class="tdtop">'.$project->title."</td>\n";
 				// Link to delete from category
 				print '<td class="right">';
-				$permission=0;
-				if ($type == Categorie::TYPE_PRODUCT)     $permission=($user->rights->produit->creer || $user->rights->service->creer);
-				if ($type == Categorie::TYPE_SUPPLIER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_CUSTOMER)    $permission=$user->rights->societe->creer;
-				if ($type == Categorie::TYPE_MEMBER)      $permission=$user->rights->adherent->creer;
-				if ($type == Categorie::TYPE_PROJECT)     $permission=$user->rights->projet->creer;
+				$permission = 0;
+				if ($type == Categorie::TYPE_PRODUCT)     $permission = ($user->rights->produit->creer || $user->rights->service->creer);
+				if ($type == Categorie::TYPE_SUPPLIER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_CUSTOMER)    $permission = $user->rights->societe->creer;
+				if ($type == Categorie::TYPE_MEMBER)      $permission = $user->rights->adherent->creer;
+				if ($type == Categorie::TYPE_PROJECT)     $permission = $user->rights->projet->creer;
 				if ($permission)
 				{
-					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid)?'id':'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$project->id."'>";
+					print "<a href= '".$_SERVER['PHP_SELF']."?".(empty($socid) ? 'id' : 'socid')."=".$object->id."&amp;type=".$typeid."&amp;removeelem=".$project->id."'>";
 					print $langs->trans("DeleteFromCat");
 					print img_picto($langs->trans("DeleteFromCat"), 'unlink');
 					print "</a>";

File diff suppressed because it is too large
+ 212 - 212
htdocs/comm/action/card.php


+ 239 - 239
htdocs/comm/card.php

@@ -72,8 +72,8 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $conf->liste_limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (! $sortorder) $sortorder="ASC";
-if (! $sortfield) $sortfield="nom";
+if (!$sortorder) $sortorder = "ASC";
+if (!$sortfield) $sortfield = "nom";
 $cancelbutton = GETPOST('cancel', 'alpha');
 
 $object = new Client($db);
@@ -83,7 +83,7 @@ $extrafields = new ExtraFields($db);
 $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('thirdpartycomm','globalcard'));
+$hookmanager->initHooks(array('thirdpartycomm', 'globalcard'));
 
 
 
@@ -99,15 +99,15 @@ if (empty($reshook))
 {
 	if ($cancelbutton)
 	{
-		$action="";
+		$action = "";
 	}
 
 	// set accountancy code
 	if ($action == 'setcustomeraccountancycode')
 	{
-		$result=$object->fetch($id);
-		$object->code_compta=$_POST["customeraccountancycode"];
-		$result=$object->update($object->id, $user, 1, 1, 0);
+		$result = $object->fetch($id);
+		$object->code_compta = $_POST["customeraccountancycode"];
+		$result = $object->update($object->id, $user, 1, 1, 0);
 		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
 	}
 
@@ -115,7 +115,7 @@ if (empty($reshook))
 	if ($action == 'setconditions' && $user->rights->societe->creer)
 	{
 		$object->fetch($id);
-		$result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
+		$result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
 		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
 	}
 
@@ -123,7 +123,7 @@ if (empty($reshook))
 	if ($action == 'setmode' && $user->rights->societe->creer)
 	{
 		$object->fetch($id);
-		$result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
+		$result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
 		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
 	}
 
@@ -131,7 +131,7 @@ if (empty($reshook))
 	if ($action == 'setbankaccount' && $user->rights->societe->creer)
 	{
 		$object->fetch($id);
-		$result=$object->setBankAccount(GETPOST('fk_account', 'int'));
+		$result = $object->setBankAccount(GETPOST('fk_account', 'int'));
 		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
 	}
 
@@ -147,8 +147,8 @@ if (empty($reshook))
 	if ($action == 'setassujtva' && $user->rights->societe->creer)
 	{
 		$object->fetch($id);
-		$object->tva_assuj=$_POST['assujtva_value'];
-		$result=$object->update($object->id);
+		$object->tva_assuj = $_POST['assujtva_value'];
+		$result = $object->update($object->id);
 		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
 	}
 
@@ -156,8 +156,8 @@ if (empty($reshook))
 	if ($action == 'setprospectlevel' && $user->rights->societe->creer)
 	{
 		$object->fetch($id);
-		$object->fk_prospectlevel=GETPOST('prospect_level_id', 'alpha');
-		$result=$object->update($object->id, $user);
+		$object->fk_prospectlevel = GETPOST('prospect_level_id', 'alpha');
+		$result = $object->update($object->id, $user);
 		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
 	}
 
@@ -165,8 +165,8 @@ if (empty($reshook))
 	if ($action == 'setstcomm')
 	{
 		$object->fetch($id);
-		$object->stcomm_id=dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcomm');
-		$result=$object->update($object->id, $user);
+		$object->stcomm_id = dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcomm');
+		$result = $object->update($object->id, $user);
 		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
 	}
 
@@ -174,8 +174,8 @@ if (empty($reshook))
 	if ($action == 'setoutstanding_limit')
 	{
 		$object->fetch($id);
-		$object->outstanding_limit=GETPOST('outstanding_limit');
-		$result=$object->update($object->id, $user);
+		$object->outstanding_limit = GETPOST('outstanding_limit');
+		$result = $object->update($object->id, $user);
 		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
 	}
 
@@ -183,8 +183,8 @@ if (empty($reshook))
 	if ($action == 'setorder_min_amount')
 	{
 		$object->fetch($id);
-		$object->order_min_amount=price2num(GETPOST('order_min_amount', 'alpha'));
-		$result=$object->update($object->id, $user);
+		$object->order_min_amount = price2num(GETPOST('order_min_amount', 'alpha'));
+		$result = $object->update($object->id, $user);
 		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
 	}
 
@@ -196,7 +196,7 @@ if (empty($reshook))
         // Fill array 'array_options' with data from update form
         $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none'));
         if ($ret < 0) $error++;
-        if (! $error)
+        if (!$error)
         {
         	$result = $object->insertExtraFields('COMPANY_MODIFY');
 			if ($result < 0)
@@ -215,20 +215,20 @@ if (empty($reshook))
  */
 
 $contactstatic = new Contact($db);
-$userstatic=new User($db);
+$userstatic = new User($db);
 $form = new Form($db);
-$formcompany=new FormCompany($db);
+$formcompany = new FormCompany($db);
 
 if ($id > 0 && empty($object->id))
 {
 	// Load data of third party
-	$res=$object->fetch($id);
+	$res = $object->fetch($id);
 	if ($object->id < 0) dol_print_error($db, $object->error, $object->errors);
 }
 
-$title=$langs->trans("CustomerCard");
-if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name;
-$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
+$title = $langs->trans("CustomerCard");
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name;
+$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
 llxHeader('', $title, $help_url);
 
 
@@ -253,10 +253,10 @@ if ($object->id > 0)
 	print '</td></tr>';
 
 	// Prefix
-    if (! empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
+    if (!empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
     {
         print '<tr><td>'.$langs->trans("Prefix").'</td><td>';
-	    print ($object->prefix_comm?$object->prefix_comm:'&nbsp;');
+	    print ($object->prefix_comm ? $object->prefix_comm : '&nbsp;');
 	    print '</td></tr>';
     }
 
@@ -298,13 +298,13 @@ if ($object->id > 0)
 	if ($mysoc->country_code == 'ES')
 	{
 		// Local Taxes
-		if ($mysoc->localtax1_assuj=="1")
+		if ($mysoc->localtax1_assuj == "1")
 		{
 			print '<tr><td class="nowrap">'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td>';
 			print yn($object->localtax1_assuj);
 			print '</td></tr>';
 		}
-		if ($mysoc->localtax1_assuj=="1")
+		if ($mysoc->localtax1_assuj == "1")
 		{
 			print '<tr><td class="nowrap">'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td>';
 			print yn($object->localtax2_assuj);
@@ -356,7 +356,7 @@ if ($object->id > 0)
 	print "</td>";
 	print '</tr>';
 
-	if (! empty($conf->banque->enabled))
+	if (!empty($conf->banque->enabled))
 	{
 		// Compte bancaire par défaut
 		print '<tr><td class="nowrap">';
@@ -392,7 +392,7 @@ if ($object->id > 0)
     		print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$object->id.'">'.img_edit($langs->trans("Modify")).'</a>';
     	}
     	print '</td></tr></table>';
-    	print '</td><td>'.($object->remise_percent?'<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$object->id.'">'.$object->remise_percent.'%</a>':'').'</td>';
+    	print '</td><td>'.($object->remise_percent ? '<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$object->id.'">'.$object->remise_percent.'%</a>' : '').'</td>';
     	print '</tr>';
 
     	// Absolute discounts (Discounts-Drawbacks-Rebates)
@@ -408,7 +408,7 @@ if ($object->id > 0)
     	print '</td></tr></table>';
     	print '</td>';
     	print '<td>';
-    	$amount_discount=$object->getAvailableDiscounts();
+    	$amount_discount = $object->getAvailableDiscounts();
     	if ($amount_discount < 0) dol_print_error($db, $object->error);
     	if ($amount_discount > 0) print '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).'</a>';
     	//else print $langs->trans("DiscountNone");
@@ -423,7 +423,7 @@ if ($object->id > 0)
 	    print '<td>';
 	    print $form->editfieldkey("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer);
 	    print '</td><td>';
-	    $limit_field_type = (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount';
+	    $limit_field_type = (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount';
 	    print $form->editfieldval("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer, $limit_field_type, ($object->outstanding_limit != '' ? price($object->outstanding_limit) : ''));
 	    print '</td>';
 	    print '</tr>';
@@ -431,7 +431,7 @@ if ($object->id > 0)
 
 	if ($object->client)
 	{
-		if (! empty($conf->commande->enabled) && ! empty($conf->global->ORDER_MANAGE_MIN_AMOUNT))
+		if (!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT))
 		{
 		    print '<!-- Minimim amount for orders -->'."\n";
 		    print '<tr class="nowrap">';
@@ -446,7 +446,7 @@ if ($object->id > 0)
 
 
 	// Multiprice level
-	if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
+	if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
 	{
 		print '<tr><td class="nowrap">';
 		print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
@@ -459,14 +459,14 @@ if ($object->id > 0)
 		print '</td></tr></table>';
 		print '</td><td>';
 		print $object->price_level;
-		$keyforlabel='PRODUIT_MULTIPRICES_LABEL'.$object->price_level;
-		if (! empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel);
+		$keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$object->price_level;
+		if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel);
 		print "</td>";
 		print '</tr>';
 	}
 
     // Preferred shipping Method
-    if (! empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) {
+    if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) {
         print '<tr><td class="nowrap">';
         print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
         print $langs->trans('SendingMethod');
@@ -489,32 +489,32 @@ if ($object->id > 0)
 	// Categories
 	if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) {
 		$langs->load("categories");
-		print '<tr><td>' . $langs->trans("CustomersCategoriesShort") . '</td>';
+		print '<tr><td>'.$langs->trans("CustomersCategoriesShort").'</td>';
 		print '<td>';
 		print $form->showCategories($object->id, 'customer', 1);
 		print "</td></tr>";
 	}
 
 	// Other attributes
-	$parameters=array('socid'=>$object->id);
-	include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+	$parameters = array('socid'=>$object->id);
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
     // Sales representative
 	include DOL_DOCUMENT_ROOT.'/societe/tpl/linesalesrepresentative.tpl.php';
 
     // Module Adherent
-    if (! empty($conf->adherent->enabled))
+    if (!empty($conf->adherent->enabled))
     {
         $langs->load("members");
         $langs->load("users");
 
         print '<tr><td class="titlefield">'.$langs->trans("LinkedToDolibarrMember").'</td>';
         print '<td>';
-        $adh=new Adherent($db);
-        $result=$adh->fetch('', '', $object->id);
+        $adh = new Adherent($db);
+        $result = $adh->fetch('', '', $object->id);
         if ($result > 0)
         {
-            $adh->ref=$adh->getFullName($langs);
+            $adh->ref = $adh->getFullName($langs);
             print $adh->getNomUrl(1);
         }
         else
@@ -558,10 +558,10 @@ if ($object->id > 0)
         print '<tr><td>'.$langs->trans("StatusProsp").'</td><td>'.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']);
         print ' &nbsp; &nbsp; ';
         print '<div class="floatright">';
-        foreach($object->cacheprospectstatus as $key => $val)
+        foreach ($object->cacheprospectstatus as $key => $val)
         {
-            $titlealt='default';
-            if (! empty($val['code']) && ! in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt=$val['label'];
+            $titlealt = 'default';
+            if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label'];
             if ($object->stcomm_id != $val['id']) print '<a class="pictosubstatus" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&stcomm='.$val['code'].'&action=setstcomm">'.img_action($titlealt, $val['code']).'</a>';
         }
         print '</div></td></tr>';
@@ -574,65 +574,65 @@ if ($object->id > 0)
 	$boxstat = '';
 
 	// Nbre max d'elements des petites listes
-	$MAXLIST=$conf->global->MAIN_SIZE_SHORTLIST_LIMIT;
+	$MAXLIST = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT;
 
 	// Lien recap
-	$boxstat.='<div class="box">';
-	$boxstat.='<table summary="'.dol_escape_htmltag($langs->trans("DolibarrStateBoard")).'" class="border boxtable boxtablenobottom boxtablenotop" width="100%">';
-	$boxstat.='<tr class="impair"><td colspan="2" class="tdboxstats nohover">';
+	$boxstat .= '<div class="box">';
+	$boxstat .= '<table summary="'.dol_escape_htmltag($langs->trans("DolibarrStateBoard")).'" class="border boxtable boxtablenobottom boxtablenotop" width="100%">';
+	$boxstat .= '<tr class="impair"><td colspan="2" class="tdboxstats nohover">';
 
-	if (! empty($conf->propal->enabled))
+	if (!empty($conf->propal->enabled))
 	{
 		// Box proposals
 		$tmp = $object->getOutstandingProposals();
-		$outstandingOpened=$tmp['opened'];
-		$outstandingTotal=$tmp['total_ht'];
-		$outstandingTotalIncTax=$tmp['total_ttc'];
-		$text=$langs->trans("OverAllProposals");
-		$link=DOL_URL_ROOT.'/comm/propal/list.php?socid='.$object->id;
-		$icon='bill';
-		if ($link) $boxstat.='<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">';
-		$boxstat.='<div class="boxstats" title="'.dol_escape_htmltag($text).'">';
-		$boxstat.='<span class="boxstatstext">'.img_object("", $icon).' '.$text.'</span><br>';
-		$boxstat.='<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>';
-		$boxstat.='</div>';
-		if ($link) $boxstat.='</a>';
+		$outstandingOpened = $tmp['opened'];
+		$outstandingTotal = $tmp['total_ht'];
+		$outstandingTotalIncTax = $tmp['total_ttc'];
+		$text = $langs->trans("OverAllProposals");
+		$link = DOL_URL_ROOT.'/comm/propal/list.php?socid='.$object->id;
+		$icon = 'bill';
+		if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">';
+		$boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">';
+		$boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' '.$text.'</span><br>';
+		$boxstat .= '<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>';
+		$boxstat .= '</div>';
+		if ($link) $boxstat .= '</a>';
 	}
 
-	if (! empty($conf->commande->enabled))
+	if (!empty($conf->commande->enabled))
 	{
 		// Box commandes
 		$tmp = $object->getOutstandingOrders();
-		$outstandingOpened=$tmp['opened'];
-		$outstandingTotal=$tmp['total_ht'];
-		$outstandingTotalIncTax=$tmp['total_ttc'];
-		$text=$langs->trans("OverAllOrders");
-		$link=DOL_URL_ROOT.'/commande/list.php?socid='.$object->id;
-		$icon='bill';
-		if ($link) $boxstat.='<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">';
-		$boxstat.='<div class="boxstats" title="'.dol_escape_htmltag($text).'">';
-		$boxstat.='<span class="boxstatstext">'.img_object("", $icon).' '.$text.'</span><br>';
-		$boxstat.='<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>';
-		$boxstat.='</div>';
-		if ($link) $boxstat.='</a>';
+		$outstandingOpened = $tmp['opened'];
+		$outstandingTotal = $tmp['total_ht'];
+		$outstandingTotalIncTax = $tmp['total_ttc'];
+		$text = $langs->trans("OverAllOrders");
+		$link = DOL_URL_ROOT.'/commande/list.php?socid='.$object->id;
+		$icon = 'bill';
+		if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">';
+		$boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">';
+		$boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' '.$text.'</span><br>';
+		$boxstat .= '<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>';
+		$boxstat .= '</div>';
+		if ($link) $boxstat .= '</a>';
 	}
 
-	if (! empty($conf->facture->enabled))
+	if (!empty($conf->facture->enabled))
 	{
 		// Box factures
 		$tmp = $object->getOutstandingBills();
-		$outstandingOpened=$tmp['opened'];
-		$outstandingTotal=$tmp['total_ht'];
-		$outstandingTotalIncTax=$tmp['total_ttc'];
-		$text=$langs->trans("OverAllInvoices");
-		$link=DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id;
-		$icon='bill';
-		if ($link) $boxstat.='<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">';
-		$boxstat.='<div class="boxstats" title="'.dol_escape_htmltag($text).'">';
-		$boxstat.='<span class="boxstatstext">'.img_object("", $icon).' '.$text.'</span><br>';
-		$boxstat.='<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>';
-		$boxstat.='</div>';
-		if ($link) $boxstat.='</a>';
+		$outstandingOpened = $tmp['opened'];
+		$outstandingTotal = $tmp['total_ht'];
+		$outstandingTotalIncTax = $tmp['total_ttc'];
+		$text = $langs->trans("OverAllInvoices");
+		$link = DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id;
+		$icon = 'bill';
+		if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">';
+		$boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">';
+		$boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' '.$text.'</span><br>';
+		$boxstat .= '<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>';
+		$boxstat .= '</div>';
+		if ($link) $boxstat .= '</a>';
 
 		// Box outstanding bill
 		$warn = '';
@@ -640,50 +640,50 @@ if ($object->id > 0)
 		{
 			$warn = ' '.img_warning($langs->trans("OutstandingBillReached"));
 		}
-		$text=$langs->trans("CurrentOutstandingBill");
-		$link=DOL_URL_ROOT.'/compta/recap-compta.php?socid='.$object->id;
-		$icon='bill';
-		if ($link) $boxstat.='<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">';
-		$boxstat.='<div class="boxstats" title="'.dol_escape_htmltag($text).'">';
-		$boxstat.='<span class="boxstatstext">'.img_object("", $icon).' '.$text.'</span><br>';
-		$boxstat.='<span class="boxstatsindicator'.($outstandingOpened>0?' amountremaintopay':'').'">'.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.'</span>';
-		$boxstat.='</div>';
-		if ($link) $boxstat.='</a>';
+		$text = $langs->trans("CurrentOutstandingBill");
+		$link = DOL_URL_ROOT.'/compta/recap-compta.php?socid='.$object->id;
+		$icon = 'bill';
+		if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">';
+		$boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">';
+		$boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' '.$text.'</span><br>';
+		$boxstat .= '<span class="boxstatsindicator'.($outstandingOpened > 0 ? ' amountremaintopay' : '').'">'.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.'</span>';
+		$boxstat .= '</div>';
+		if ($link) $boxstat .= '</a>';
 	}
 
 	$parameters = array();
 	$reshook = $hookmanager->executeHooks('addMoreBoxStatsCustomer', $parameters, $object, $action);
-	if(empty($reshook)){
-		$boxstat.= $hookmanager->resPrint;
+	if (empty($reshook)) {
+		$boxstat .= $hookmanager->resPrint;
 	}
 
-	$boxstat.='</td></tr>';
-	$boxstat.='</table>';
-	$boxstat.='</div>';
+	$boxstat .= '</td></tr>';
+	$boxstat .= '</table>';
+	$boxstat .= '</div>';
 
 	print $boxstat;
 
-	$now=dol_now();
+	$now = dol_now();
 
 	/*
 	 * Last proposals
 	 */
-	if (! empty($conf->propal->enabled) && $user->rights->propal->lire)
+	if (!empty($conf->propal->enabled) && $user->rights->propal->lire)
 	{
 		$langs->load("propal");
 
 		$sql = "SELECT s.nom, s.rowid, p.rowid as propalid, p.fk_statut, p.total_ht";
-        $sql.= ", p.tva as total_tva";
-        $sql.= ", p.total as total_ttc";
-        $sql.= ", p.ref, p.ref_client, p.remise";
-		$sql.= ", p.datep as dp, p.fin_validite as datelimite";
-		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
-		$sql.= " WHERE p.fk_soc = s.rowid AND p.fk_statut = c.id";
-		$sql.= " AND s.rowid = ".$object->id;
-		$sql.= " AND p.entity IN (".getEntity('propal').")";
-		$sql.= " ORDER BY p.datep DESC";
-
-		$resql=$db->query($sql);
+        $sql .= ", p.tva as total_tva";
+        $sql .= ", p.total as total_ttc";
+        $sql .= ", p.ref, p.ref_client, p.remise";
+		$sql .= ", p.datep as dp, p.fin_validite as datelimite";
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
+		$sql .= " WHERE p.fk_soc = s.rowid AND p.fk_statut = c.id";
+		$sql .= " AND s.rowid = ".$object->id;
+		$sql .= " AND p.entity IN (".getEntity('propal').")";
+		$sql .= " ORDER BY p.datep DESC";
+
+		$resql = $db->query($sql);
 		if ($resql)
 		{
 			$propal_static = new Propal($db);
@@ -695,7 +695,7 @@ if ($object->id > 0)
             	print '<table class="noborder centpercent lastrecordtable">';
 
                 print '<tr class="liste_titre">';
-    			print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastPropals", ($num<=$MAXLIST?"":$MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/comm/propal/list.php?socid='.$object->id.'">'.$langs->trans("AllPropals").' <span class="badge">'.$num.'</span></a></td>';
+    			print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastPropals", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/comm/propal/list.php?socid='.$object->id.'">'.$langs->trans("AllPropals").' <span class="badge">'.$num.'</span></a></td>';
                 print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/comm/propal/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
     			print '</tr></table></td>';
     			print '</tr>';
@@ -715,7 +715,7 @@ if ($object->id > 0)
                 $propal_static->total_tva = $objp->total_tva;
                 $propal_static->total_ttc = $objp->total_ttc;
                 print $propal_static->getNomUrl(1);
-                if ( ($db->jdate($objp->datelimite) < ($now - $conf->propal->cloture->warning_delay)) && $objp->fk_statut == 1 ) {
+                if (($db->jdate($objp->datelimite) < ($now - $conf->propal->cloture->warning_delay)) && $objp->fk_statut == 1) {
                     print " ".img_warning();
                 }
 				print '</td><td class="right" width="80px">'.dol_print_date($db->jdate($objp->dp), 'day')."</td>\n";
@@ -740,39 +740,39 @@ if ($object->id > 0)
 	/*
 	 * Last orders
 	 */
-	if (! empty($conf->commande->enabled) && $user->rights->commande->lire)
+	if (!empty($conf->commande->enabled) && $user->rights->commande->lire)
 	{
         $sql = "SELECT s.nom, s.rowid";
-        $sql.= ", c.rowid as cid, c.total_ht";
-        $sql.= ", c.tva as total_tva";
-        $sql.= ", c.total_ttc";
-        $sql.= ", c.ref, c.ref_client, c.fk_statut, c.facture";
-        $sql.= ", c.date_commande as dc";
-		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
-		$sql.= " WHERE c.fk_soc = s.rowid ";
-		$sql.= " AND s.rowid = ".$object->id;
-		$sql.= " AND c.entity = ".$conf->entity;
-		$sql.= " ORDER BY c.date_commande DESC";
-
-		$resql=$db->query($sql);
+        $sql .= ", c.rowid as cid, c.total_ht";
+        $sql .= ", c.tva as total_tva";
+        $sql .= ", c.total_ttc";
+        $sql .= ", c.ref, c.ref_client, c.fk_statut, c.facture";
+        $sql .= ", c.date_commande as dc";
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
+		$sql .= " WHERE c.fk_soc = s.rowid ";
+		$sql .= " AND s.rowid = ".$object->id;
+		$sql .= " AND c.entity = ".$conf->entity;
+		$sql .= " ORDER BY c.date_commande DESC";
+
+		$resql = $db->query($sql);
 		if ($resql)
 		{
-			$commande_static=new Commande($db);
+			$commande_static = new Commande($db);
 
 			$num = $db->num_rows($resql);
 			if ($num > 0)
 			{
 				// Check if there are orders billable
 				$sql2 = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_client,';
-				$sql2.= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as billed';
-				$sql2.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
-				$sql2.= ', '.MAIN_DB_PREFIX.'commande as c';
-				$sql2.= ' WHERE c.fk_soc = s.rowid';
-				$sql2.= ' AND s.rowid = '.$object->id;
+				$sql2 .= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as billed';
+				$sql2 .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
+				$sql2 .= ', '.MAIN_DB_PREFIX.'commande as c';
+				$sql2 .= ' WHERE c.fk_soc = s.rowid';
+				$sql2 .= ' AND s.rowid = '.$object->id;
 				// Show orders with status validated, shipping started and delivered (well any order we can bill)
-				$sql2.= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))";
+				$sql2 .= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))";
 
-				$resql2=$db->query($sql2);
+				$resql2 = $db->query($sql2);
 				$orders2invoice = $db->num_rows($resql2);
 				$db->free($resql2);
 
@@ -780,7 +780,7 @@ if ($object->id > 0)
 				print '<table class="noborder centpercent lastrecordtable">';
 
 				print '<tr class="liste_titre">';
-				print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastCustomerOrders", ($num<=$MAXLIST?"":$MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$object->id.'">'.$langs->trans("AllOrders").' <span class="badge">'.$num.'</span></a></td>';
+				print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastCustomerOrders", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$object->id.'">'.$langs->trans("AllOrders").' <span class="badge">'.$num.'</span></a></td>';
 				print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/commande/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
 				//if($num2 > 0) print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/commande/orderstoinvoice.php?socid='.$object->id.'">'.img_picto($langs->trans("CreateInvoiceForThisCustomer"),'object_bill').'</a></td>';
 				//else print '<td width="20px" class="right"><a href="#">'.img_picto($langs->trans("NoOrdersToInvoice"),'object_bill').'</a></td>';
@@ -795,7 +795,7 @@ if ($object->id > 0)
 
 				$commande_static->id = $objp->cid;
 				$commande_static->ref = $objp->ref;
-				$commande_static->ref_client=$objp->ref_client;
+				$commande_static->ref_client = $objp->ref_client;
 				$commande_static->total_ht = $objp->total_ht;
 				$commande_static->total_tva = $objp->total_tva;
 				$commande_static->total_ttc = $objp->total_ttc;
@@ -811,7 +811,7 @@ if ($object->id > 0)
 			}
 			$db->free($resql);
 
-			if ($num >0)
+			if ($num > 0)
 			{
 				print "</table>";
 				print '</div>';
@@ -826,24 +826,24 @@ if ($object->id > 0)
     /*
      *   Last shipments
      */
-    if (! empty($conf->expedition->enabled) && $user->rights->expedition->lire)
+    if (!empty($conf->expedition->enabled) && $user->rights->expedition->lire)
     {
         $sql = 'SELECT e.rowid as id';
-        $sql.= ', e.ref';
-        $sql.= ', e.date_creation';
-        $sql.= ', e.fk_statut as statut';
-        $sql.= ', s.nom';
-        $sql.= ', s.rowid as socid';
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."expedition as e";
-        $sql.= " WHERE e.fk_soc = s.rowid AND s.rowid = ".$object->id;
-        $sql.= " AND e.entity IN (".getEntity('expedition').")";
-        $sql.= ' GROUP BY e.rowid';
-        $sql.= ', e.ref';
-        $sql.= ', e.date_creation';
-        $sql.= ', e.fk_statut';
-        $sql.= ', s.nom';
-        $sql.= ', s.rowid';
-        $sql.= " ORDER BY e.date_creation DESC";
+        $sql .= ', e.ref';
+        $sql .= ', e.date_creation';
+        $sql .= ', e.fk_statut as statut';
+        $sql .= ', s.nom';
+        $sql .= ', s.rowid as socid';
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."expedition as e";
+        $sql .= " WHERE e.fk_soc = s.rowid AND s.rowid = ".$object->id;
+        $sql .= " AND e.entity IN (".getEntity('expedition').")";
+        $sql .= ' GROUP BY e.rowid';
+        $sql .= ', e.ref';
+        $sql .= ', e.date_creation';
+        $sql .= ', e.fk_statut';
+        $sql .= ', s.nom';
+        $sql .= ', s.rowid';
+        $sql .= " ORDER BY e.date_creation DESC";
 
         $resql = $db->query($sql);
         if ($resql)
@@ -856,7 +856,7 @@ if ($object->id > 0)
             	print '<table class="noborder centpercent lastrecordtable">';
 
                 print '<tr class="liste_titre">';
-                print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastSendings", ($num<=$MAXLIST?"":$MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/expedition/list.php?socid='.$object->id.'">'.$langs->trans("AllSendings").' <span class="badge">'.$num.'</span></a></td>';
+                print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastSendings", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/expedition/list.php?socid='.$object->id.'">'.$langs->trans("AllSendings").' <span class="badge">'.$num.'</span></a></td>';
                 print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/expedition/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
                 print '</tr></table></td>';
                 print '</tr>';
@@ -880,7 +880,7 @@ if ($object->id > 0)
                     print '<td class="right"><b>!!!</b></td>';
                 }
 
-                print '<td class="nowrap right" width="100" >' . $sendingstatic->LibStatut($objp->statut, 5) . '</td>';
+                print '<td class="nowrap right" width="100" >'.$sendingstatic->LibStatut($objp->statut, 5).'</td>';
                 print "</tr>\n";
                 $i++;
             }
@@ -899,28 +899,28 @@ if ($object->id > 0)
 	/*
 	 * Last linked contracts
 	 */
-	if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire)
+	if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire)
 	{
 		$sql = "SELECT s.nom, s.rowid, c.rowid as id, c.ref as ref, c.statut, c.datec as dc, c.date_contrat as dcon, c.ref_customer as refcus, c.ref_supplier as refsup";
-		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as c";
-		$sql.= " WHERE c.fk_soc = s.rowid ";
-		$sql.= " AND s.rowid = ".$object->id;
-		$sql.= " AND c.entity = ".$conf->entity;
-		$sql.= " ORDER BY c.datec DESC";
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as c";
+		$sql .= " WHERE c.fk_soc = s.rowid ";
+		$sql .= " AND s.rowid = ".$object->id;
+		$sql .= " AND c.entity = ".$conf->entity;
+		$sql .= " ORDER BY c.datec DESC";
 
-		$resql=$db->query($sql);
+		$resql = $db->query($sql);
 		if ($resql)
 		{
-			$contrat=new Contrat($db);
+			$contrat = new Contrat($db);
 
 			$num = $db->num_rows($resql);
-			if ($num >0)
+			if ($num > 0)
 			{
 				print '<div class="div-table-responsive-no-min">';
 				print '<table class="noborder centpercent lastrecordtable">';
 
 			    print '<tr class="liste_titre">';
-				print '<td colspan="6"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastContracts", ($num<=$MAXLIST?"":$MAXLIST)).'</td>';
+				print '<td colspan="6"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastContracts", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td>';
 				print '<td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->id.'">'.$langs->trans("AllContracts").' <span class="badge">'.$num.'</span></a></td>';
 				//print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/contract/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"),'stats').'</a></td>';
 				print '</tr></table></td>';
@@ -932,10 +932,10 @@ if ($object->id > 0)
 			{
 				$objp = $db->fetch_object($resql);
 
-				$contrat->id=$objp->id;
-				$contrat->ref=$objp->ref?$objp->ref:$objp->id;
-				$contrat->ref_customer=$objp->refcus;
-				$contrat->ref_supplier=$objp->refsup;
+				$contrat->id = $objp->id;
+				$contrat->ref = $objp->ref ? $objp->ref : $objp->id;
+				$contrat->ref_customer = $objp->refcus;
+				$contrat->ref_supplier = $objp->refsup;
 				$contrat->fetch_lines();
 
 				print '<tr class="oddeven">';
@@ -969,19 +969,19 @@ if ($object->id > 0)
 	/*
 	 * Last interventions
 	 */
-	if (! empty($conf->ficheinter->enabled) && $user->rights->ficheinter->lire)
+	if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->lire)
 	{
 		$sql = "SELECT s.nom, s.rowid, f.rowid as id, f.ref, f.fk_statut, f.duree as duration, f.datei as startdate";
-		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as f";
-		$sql.= " WHERE f.fk_soc = s.rowid";
-		$sql.= " AND s.rowid = ".$object->id;
-		$sql.= " AND f.entity = ".$conf->entity;
-		$sql.= " ORDER BY f.tms DESC";
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as f";
+		$sql .= " WHERE f.fk_soc = s.rowid";
+		$sql .= " AND s.rowid = ".$object->id;
+		$sql .= " AND f.entity = ".$conf->entity;
+		$sql .= " ORDER BY f.tms DESC";
 
-		$resql=$db->query($sql);
+		$resql = $db->query($sql);
 		if ($resql)
 		{
-			$fichinter_static=new Fichinter($db);
+			$fichinter_static = new Fichinter($db);
 
 			$num = $db->num_rows($resql);
 			if ($num > 0)
@@ -990,7 +990,7 @@ if ($object->id > 0)
 				print '<table class="noborder centpercent lastrecordtable">';
 
 			    print '<tr class="liste_titre">';
-				print '<td colspan="3"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastInterventions", ($num<=$MAXLIST?"":$MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/fichinter/list.php?socid='.$object->id.'">'.$langs->trans("AllInterventions").' <span class="badge">'.$num.'</span></td>';
+				print '<td colspan="3"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastInterventions", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/fichinter/list.php?socid='.$object->id.'">'.$langs->trans("AllInterventions").' <span class="badge">'.$num.'</span></td>';
 				print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/fichinter/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
 				print '</tr></table></td>';
 				print '</tr>';
@@ -1001,8 +1001,8 @@ if ($object->id > 0)
 			{
 				$objp = $db->fetch_object($resql);
 
-				$fichinter_static->id=$objp->id;
-                $fichinter_static->statut=$objp->fk_statut;
+				$fichinter_static->id = $objp->id;
+                $fichinter_static->statut = $objp->fk_statut;
 
 				print '<tr class="oddeven">';
 				print '<td class="nowrap"><a href="'.DOL_URL_ROOT.'/fichinter/card.php?id='.$objp->id.'">'.img_object($langs->trans("ShowPropal"), "propal").' '.$objp->ref.'</a></td>'."\n";
@@ -1030,28 +1030,28 @@ if ($object->id > 0)
 	/*
 	 *   Last invoices templates
 	 */
-	if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
+	if (!empty($conf->facture->enabled) && $user->rights->facture->lire)
 	{
 		$sql = 'SELECT f.rowid as id, f.titre as ref, f.amount';
-		$sql.= ', f.total as total_ht';
-		$sql.= ', f.tva as total_tva';
-		$sql.= ', f.total_ttc';
-		$sql.= ', f.datec as dc';
-		$sql.= ', f.date_last_gen, f.date_when';
-		$sql.= ', f.frequency';
-		$sql.= ', f.unit_frequency';
-		$sql.= ', f.suspended as suspended';
-		$sql.= ', s.nom, s.rowid as socid';
-		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f";
-		$sql.= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id;
-		$sql.= " AND f.entity = ".$conf->entity;
-		$sql.= ' GROUP BY f.rowid, f.titre, f.amount, f.total, f.tva, f.total_ttc,';
-		$sql.= ' f.date_last_gen, f.datec, f.frequency, f.unit_frequency,';
-		$sql.= ' f.suspended,';
-		$sql.= ' s.nom, s.rowid';
-		$sql.= " ORDER BY f.date_last_gen, f.datec DESC";
-
-		$resql=$db->query($sql);
+		$sql .= ', f.total as total_ht';
+		$sql .= ', f.tva as total_tva';
+		$sql .= ', f.total_ttc';
+		$sql .= ', f.datec as dc';
+		$sql .= ', f.date_last_gen, f.date_when';
+		$sql .= ', f.frequency';
+		$sql .= ', f.unit_frequency';
+		$sql .= ', f.suspended as suspended';
+		$sql .= ', s.nom, s.rowid as socid';
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f";
+		$sql .= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id;
+		$sql .= " AND f.entity = ".$conf->entity;
+		$sql .= ' GROUP BY f.rowid, f.titre, f.amount, f.total, f.tva, f.total_ttc,';
+		$sql .= ' f.date_last_gen, f.datec, f.frequency, f.unit_frequency,';
+		$sql .= ' f.suspended,';
+		$sql .= ' s.nom, s.rowid';
+		$sql .= " ORDER BY f.date_last_gen, f.datec DESC";
+
+		$resql = $db->query($sql);
 		if ($resql)
 		{
 			$invoicetemplate = new FactureRec($db);
@@ -1063,7 +1063,7 @@ if ($object->id > 0)
 				print '<table class="noborder centpercent lastrecordtable">';
 
 				print '<tr class="liste_titre">';
-				print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LatestCustomerTemplateInvoices", ($num<=$MAXLIST?"":$MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id.'">'.$langs->trans("AllCustomerTemplateInvoices").' <span class="badge">'.$num.'</span></a></td>';
+				print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LatestCustomerTemplateInvoices", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id.'">'.$langs->trans("AllCustomerTemplateInvoices").' <span class="badge">'.$num.'</span></a></td>';
 				print '</tr></table></td>';
 				print '</tr>';
 			}
@@ -1107,7 +1107,7 @@ if ($object->id > 0)
 				print price($objp->total_ht);
 				print '</td>';
 
-				if (! empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES))
+				if (!empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES))
 				{
 					print '<td class="right" style="min-width: 60px">';
 					print price($objp->total_ttc);
@@ -1138,25 +1138,25 @@ if ($object->id > 0)
 	/*
 	 *   Last invoices
 	 */
-	if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
+	if (!empty($conf->facture->enabled) && $user->rights->facture->lire)
 	{
         $sql = 'SELECT f.rowid as facid, f.ref, f.type, f.amount';
-        $sql.= ', f.total as total_ht';
-        $sql.= ', f.tva as total_tva';
-        $sql.= ', f.total_ttc';
-		$sql.= ', f.datef as df, f.datec as dc, f.paye as paye, f.fk_statut as statut';
-		$sql.= ', s.nom, s.rowid as socid';
-		$sql.= ', SUM(pf.amount) as am';
-		$sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f";
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON f.rowid=pf.fk_facture';
-		$sql.= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id;
-		$sql.= " AND f.entity IN (".getEntity('invoice').")";
-		$sql.= ' GROUP BY f.rowid, f.ref, f.type, f.amount, f.total, f.tva, f.total_ttc,';
-		$sql.= ' f.datef, f.datec, f.paye, f.fk_statut,';
-		$sql.= ' s.nom, s.rowid';
-		$sql.= " ORDER BY f.datef DESC, f.datec DESC";
-
-		$resql=$db->query($sql);
+        $sql .= ', f.total as total_ht';
+        $sql .= ', f.tva as total_tva';
+        $sql .= ', f.total_ttc';
+		$sql .= ', f.datef as df, f.datec as dc, f.paye as paye, f.fk_statut as statut';
+		$sql .= ', s.nom, s.rowid as socid';
+		$sql .= ', SUM(pf.amount) as am';
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f";
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON f.rowid=pf.fk_facture';
+		$sql .= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id;
+		$sql .= " AND f.entity IN (".getEntity('invoice').")";
+		$sql .= ' GROUP BY f.rowid, f.ref, f.type, f.amount, f.total, f.tva, f.total_ttc,';
+		$sql .= ' f.datef, f.datec, f.paye, f.fk_statut,';
+		$sql .= ' s.nom, s.rowid';
+		$sql .= " ORDER BY f.datef DESC, f.datec DESC";
+
+		$resql = $db->query($sql);
 		if ($resql)
 		{
 			$facturestatic = new Facture($db);
@@ -1168,7 +1168,7 @@ if ($object->id > 0)
 				print '<table class="noborder centpercent lastrecordtable">';
 
 				print '<tr class="liste_titre">';
-				print '<td colspan="5"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastCustomersBills", ($num<=$MAXLIST?"":$MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id.'">'.$langs->trans("AllBills").' <span class="badge">'.$num.'</span></a></td>';
+				print '<td colspan="5"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastCustomersBills", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id.'">'.$langs->trans("AllBills").' <span class="badge">'.$num.'</span></a></td>';
                 print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/compta/facture/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
 				print '</tr></table></td>';
 				print '</tr>';
@@ -1202,7 +1202,7 @@ if ($object->id > 0)
 				print price($objp->total_ht);
 				print '</td>';
 
-				if (! empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES))
+				if (!empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES))
 				{
     				print '<td class="right" style="min-width: 60px">';
     				print price($objp->total_ttc);
@@ -1249,25 +1249,25 @@ if ($object->id > 0)
             print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("ThirdPartyIsClosed")).'" href="#">'.$langs->trans("ThirdPartyIsClosed").'</a></div>';
         }
 
-    	if (! empty($conf->propal->enabled) && $user->rights->propal->creer && $object->status==1)
+    	if (!empty($conf->propal->enabled) && $user->rights->propal->creer && $object->status == 1)
     	{
     		$langs->load("propal");
     		print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/comm/propal/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddProp").'</a></div>';
     	}
 
-    	if (! empty($conf->commande->enabled) && $user->rights->commande->creer && $object->status==1)
+    	if (!empty($conf->commande->enabled) && $user->rights->commande->creer && $object->status == 1)
     	{
     		$langs->load("orders");
     		print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddOrder").'</a></div>';
     	}
 
-    	if ($user->rights->contrat->creer && $object->status==1)
+    	if ($user->rights->contrat->creer && $object->status == 1)
     	{
     		$langs->load("contracts");
     		print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/contrat/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddContract").'</a></div>';
     	}
 
-    	if (! empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer && $object->status==1)
+    	if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer && $object->status == 1)
     	{
     		$langs->load("fichinter");
     		print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/fichinter/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddIntervention").'</a></div>';
@@ -1276,13 +1276,13 @@ if ($object->id > 0)
     	// Add invoice
     	if ($user->socid == 0)
     	{
-    		if (! empty($conf->deplacement->enabled) && $object->status==1)
+    		if (!empty($conf->deplacement->enabled) && $object->status == 1)
     		{
     			$langs->load("trips");
     			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/deplacement/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddTrip").'</a></div>';
     		}
 
-    		if (! empty($conf->facture->enabled) && $object->status==1)
+    		if (!empty($conf->facture->enabled) && $object->status == 1)
     		{
     			if (empty($user->rights->facture->creer))
     			{
@@ -1310,7 +1310,7 @@ if ($object->id > 0)
     	}
 
     	// Add action
-    	if (! empty($conf->agenda->enabled) && ! empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status==1)
+    	if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1)
     	{
     		if ($user->rights->agenda->myactions->create)
     		{
@@ -1325,13 +1325,13 @@ if ($object->id > 0)
 
 	print '</div>';
 
-	if (! empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_CUSTOMER_CARD))
+	if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_CUSTOMER_CARD))
 	{
 		// List of contacts
 		show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id);
 	}
 
-    if (! empty($conf->global->MAIN_REPEATTASKONEACHTAB))
+    if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB))
     {
         print load_fiche_titre($langs->trans("ActionsOnCompany"), '', '');
 

File diff suppressed because it is too large
+ 222 - 222
htdocs/comm/mailing/card.php


+ 139 - 139
htdocs/comm/mailing/class/advtargetemailing.class.php

@@ -36,7 +36,7 @@ class AdvanceTargetingMailing extends CommonObject
 	/**
 	 * @var string Error code (or message)
 	 */
-	public $error='';
+	public $error = '';
 
 	/**
 	 * @var string[] Error codes (or messages)
@@ -46,12 +46,12 @@ class AdvanceTargetingMailing extends CommonObject
 	/**
 	 * @var string ID to identify managed object
 	 */
-	public $element='advtargetemailing';
+	public $element = 'advtargetemailing';
 
 	/**
 	 * @var string Name of table without prefix where object is stored
 	 */
-	public $table_element='advtargetemailing';
+	public $table_element = 'advtargetemailing';
 
 	/**
 	 * @var int ID
@@ -64,12 +64,12 @@ class AdvanceTargetingMailing extends CommonObject
     public $type_element;
     public $filtervalue;
     public $fk_user_author;
-    public $datec='';
+    public $datec = '';
     public $fk_user_mod;
-    public $tms='';
+    public $tms = '';
 
     public $select_target_type = array();
-    public $type_statuscommprospect=array();
+    public $type_statuscommprospect = array();
     public $thirdparty_lines;
     public $contact_lines;
 
@@ -88,12 +88,12 @@ class AdvanceTargetingMailing extends CommonObject
 
 		$this->select_target_type = array(
 				'2' => $langs->trans('Contacts'),
-				'1' => $langs->trans('Contacts') . '+' . $langs->trans('ThirdParty'),
+				'1' => $langs->trans('Contacts').'+'.$langs->trans('ThirdParty'),
 				'3' => $langs->trans('ThirdParty'),
 				'4' => $langs->trans('ContactsWithThirdpartyFilter')
 		);
 		$this->type_statuscommprospect = array(
-				- 1 => $langs->trans("StatusProspect-1"),
+				-1 => $langs->trans("StatusProspect-1"),
 				0 => $langs->trans("StatusProspect0"),
 				1 => $langs->trans("StatusProspect1"),
 				2 => $langs->trans("StatusProspect2"),
@@ -111,50 +111,50 @@ class AdvanceTargetingMailing extends CommonObject
     public function create($user, $notrigger = 0)
 	{
 		global $conf, $langs;
-		$error=0;
+		$error = 0;
 
 		// Clean parameters
-		if (isset($this->fk_element)) $this->fk_element=(int) $this->fk_element;
-		if (isset($this->type_element)) $this->type_element=trim($this->type_element);
+		if (isset($this->fk_element)) $this->fk_element = (int) $this->fk_element;
+		if (isset($this->type_element)) $this->type_element = trim($this->type_element);
 
-		if (isset($this->name)) $this->name=trim($this->name);
-		if (isset($this->filtervalue)) $this->filtervalue=trim($this->filtervalue);
+		if (isset($this->name)) $this->name = trim($this->name);
+		if (isset($this->filtervalue)) $this->filtervalue = trim($this->filtervalue);
 
 		// Check parameters
 		// Put here code to add control on parameters values
 
 		// Insert request
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."advtargetemailing(";
-		$sql.= "name,";
-		$sql.= "entity,";
-		$sql.= "fk_element,";
-		$sql.= "type_element,";
-		$sql.= "filtervalue,";
-		$sql.= "fk_user_author,";
-		$sql.= "datec,";
-		$sql.= "fk_user_mod";
-		$sql.= ") VALUES (";
-		$sql.= " ".(! isset($this->name)?'NULL':"'".$this->db->escape($this->name)."'").",";
-		$sql.= " ".$conf->entity.",";
-		$sql.= " ".(! isset($this->fk_element)?'NULL':"'".$this->db->escape($this->fk_element)."'").",";
-		$sql.= " ".(! isset($this->type_element)?'NULL':"'".$this->db->escape($this->type_element)."'").",";
-		$sql.= " ".(! isset($this->filtervalue)?'NULL':"'".$this->db->escape($this->filtervalue)."'").",";
-		$sql.= " ".$user->id.",";
-		$sql.= " '".$this->db->idate(dol_now())."',";
-		$sql.= " null";
-		$sql.= ")";
+		$sql .= "name,";
+		$sql .= "entity,";
+		$sql .= "fk_element,";
+		$sql .= "type_element,";
+		$sql .= "filtervalue,";
+		$sql .= "fk_user_author,";
+		$sql .= "datec,";
+		$sql .= "fk_user_mod";
+		$sql .= ") VALUES (";
+		$sql .= " ".(!isset($this->name) ? 'NULL' : "'".$this->db->escape($this->name)."'").",";
+		$sql .= " ".$conf->entity.",";
+		$sql .= " ".(!isset($this->fk_element) ? 'NULL' : "'".$this->db->escape($this->fk_element)."'").",";
+		$sql .= " ".(!isset($this->type_element) ? 'NULL' : "'".$this->db->escape($this->type_element)."'").",";
+		$sql .= " ".(!isset($this->filtervalue) ? 'NULL' : "'".$this->db->escape($this->filtervalue)."'").",";
+		$sql .= " ".$user->id.",";
+		$sql .= " '".$this->db->idate(dol_now())."',";
+		$sql .= " null";
+		$sql .= ")";
 
 		$this->db->begin();
 
 		dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG);
-		$resql=$this->db->query($sql);
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
+		$resql = $this->db->query($sql);
+		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
 
-		if (! $error)
+		if (!$error)
 		{
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."advtargetemailing");
 
-			if (! $notrigger)
+			if (!$notrigger)
 			{
 				// Uncomment this and change MYOBJECT to your own tag if you
 				// want this action calls a trigger.
@@ -171,13 +171,13 @@ class AdvanceTargetingMailing extends CommonObject
 		// Commit or rollback
 		if ($error)
 		{
-			foreach($this->errors as $errmsg)
+			foreach ($this->errors as $errmsg)
 			{
 				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
 			}
 			$this->db->rollback();
-			return -1*$error;
+			return -1 * $error;
 		}
 		else
 		{
@@ -196,30 +196,30 @@ class AdvanceTargetingMailing extends CommonObject
 	{
 		global $langs;
 		$sql = "SELECT";
-		$sql.= " t.rowid,";
+		$sql .= " t.rowid,";
 
-		$sql.= " t.name,";
-		$sql.= " t.entity,";
-		$sql.= " t.fk_element,";
-		$sql.= " t.type_element,";
-		$sql.= " t.filtervalue,";
-		$sql.= " t.fk_user_author,";
-		$sql.= " t.datec,";
-		$sql.= " t.fk_user_mod,";
-		$sql.= " t.tms";
+		$sql .= " t.name,";
+		$sql .= " t.entity,";
+		$sql .= " t.fk_element,";
+		$sql .= " t.type_element,";
+		$sql .= " t.filtervalue,";
+		$sql .= " t.fk_user_author,";
+		$sql .= " t.datec,";
+		$sql .= " t.fk_user_mod,";
+		$sql .= " t.tms";
 
-		$sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t";
-		$sql.= " WHERE t.rowid = ".$id;
+		$sql .= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t";
+		$sql .= " WHERE t.rowid = ".$id;
 
 		dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
 			if ($this->db->num_rows($resql))
 			{
 				$obj = $this->db->fetch_object($resql);
 
-				$this->id    = $obj->rowid;
+				$this->id = $obj->rowid;
 
 				$this->name = $obj->name;
 				$this->entity = $obj->entity;
@@ -237,7 +237,7 @@ class AdvanceTargetingMailing extends CommonObject
 		}
 		else
 		{
-			$this->error="Error ".$this->db->lasterror();
+			$this->error = "Error ".$this->db->lasterror();
 			dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
 			return -1;
 		}
@@ -255,34 +255,34 @@ class AdvanceTargetingMailing extends CommonObject
         // phpcs:enable
 		global $langs;
 		$sql = "SELECT";
-		$sql.= " t.rowid,";
-
-		$sql.= " t.name,";
-		$sql.= " t.entity,";
-		$sql.= " t.fk_element,";
-		$sql.= " t.type_element,";
-		$sql.= " t.filtervalue,";
-		$sql.= " t.fk_user_author,";
-		$sql.= " t.datec,";
-		$sql.= " t.fk_user_mod,";
-		$sql.= " t.tms";
-
-		$sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t";
+		$sql .= " t.rowid,";
+
+		$sql .= " t.name,";
+		$sql .= " t.entity,";
+		$sql .= " t.fk_element,";
+		$sql .= " t.type_element,";
+		$sql .= " t.filtervalue,";
+		$sql .= " t.fk_user_author,";
+		$sql .= " t.datec,";
+		$sql .= " t.fk_user_mod,";
+		$sql .= " t.tms";
+
+		$sql .= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t";
 		if (!empty($id)) {
-			$sql.= " WHERE t.fk_element = ".$id." AND type_element='mailing'";
-		}else {
-			$sql.= " WHERE t.fk_element = ".$this->fk_element."  AND type_element='mailing'";
+			$sql .= " WHERE t.fk_element = ".$id." AND type_element='mailing'";
+		} else {
+			$sql .= " WHERE t.fk_element = ".$this->fk_element."  AND type_element='mailing'";
 		}
 
 		dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
 			if ($this->db->num_rows($resql))
 			{
 				$obj = $this->db->fetch_object($resql);
 
-				$this->id    = $obj->rowid;
+				$this->id = $obj->rowid;
 
 				$this->name = $obj->name;
 				$this->entity = $obj->entity;
@@ -300,7 +300,7 @@ class AdvanceTargetingMailing extends CommonObject
 		}
 		else
 		{
-			$this->error="Error ".$this->db->lasterror();
+			$this->error = "Error ".$this->db->lasterror();
 			dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
 			return -1;
 		}
@@ -322,34 +322,34 @@ class AdvanceTargetingMailing extends CommonObject
         // phpcs:enable
 		global $langs;
 		$sql = "SELECT";
-		$sql.= " t.rowid,";
-
-		$sql.= " t.name,";
-		$sql.= " t.entity,";
-		$sql.= " t.fk_element,";
-		$sql.= " t.type_element,";
-		$sql.= " t.filtervalue,";
-		$sql.= " t.fk_user_author,";
-		$sql.= " t.datec,";
-		$sql.= " t.fk_user_mod,";
-		$sql.= " t.tms";
-
-		$sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t";
+		$sql .= " t.rowid,";
+
+		$sql .= " t.name,";
+		$sql .= " t.entity,";
+		$sql .= " t.fk_element,";
+		$sql .= " t.type_element,";
+		$sql .= " t.filtervalue,";
+		$sql .= " t.fk_user_author,";
+		$sql .= " t.datec,";
+		$sql .= " t.fk_user_mod,";
+		$sql .= " t.tms";
+
+		$sql .= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t";
 		if (!empty($id)) {
-			$sql.= " WHERE t.fk_element = ".$id." AND type_element='$type_element'";
-		}else {
-			$sql.= " WHERE t.fk_element = ".$this->fk_element."  AND type_element='$type_element'";
+			$sql .= " WHERE t.fk_element = ".$id." AND type_element='$type_element'";
+		} else {
+			$sql .= " WHERE t.fk_element = ".$this->fk_element."  AND type_element='$type_element'";
 		}
 
 		dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
 			if ($this->db->num_rows($resql))
 			{
 				$obj = $this->db->fetch_object($resql);
 
-				$this->id    = $obj->rowid;
+				$this->id = $obj->rowid;
 
 				$this->name = $obj->name;
 				$this->entity = $obj->entity;
@@ -367,7 +367,7 @@ class AdvanceTargetingMailing extends CommonObject
 		}
 		else
 		{
-			$this->error="Error ".$this->db->lasterror();
+			$this->error = "Error ".$this->db->lasterror();
 			dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
 			return -1;
 		}
@@ -383,13 +383,13 @@ class AdvanceTargetingMailing extends CommonObject
     public function update($user, $notrigger = 0)
 	{
 		global $conf, $langs;
-		$error=0;
+		$error = 0;
 
 		// Clean parameters
-		if (isset($this->fk_element)) $this->fk_element=(int) $this->fk_element;
-		if (isset($this->type_element)) $this->type_element=trim($this->type_element);
-		if (isset($this->name)) $this->name=trim($this->name);
-		if (isset($this->filtervalue)) $this->filtervalue=trim($this->filtervalue);
+		if (isset($this->fk_element)) $this->fk_element = (int) $this->fk_element;
+		if (isset($this->type_element)) $this->type_element = trim($this->type_element);
+		if (isset($this->name)) $this->name = trim($this->name);
+		if (isset($this->filtervalue)) $this->filtervalue = trim($this->filtervalue);
 
 		// Check parameters
 		// Put here code to add a control on parameters values
@@ -397,21 +397,21 @@ class AdvanceTargetingMailing extends CommonObject
 		// Update request
 		$sql = "UPDATE ".MAIN_DB_PREFIX."advtargetemailing SET";
 
-		$sql.= " name=".(isset($this->name)?"'".$this->db->escape($this->name)."'":"''").",";
-		$sql.= " entity=".$conf->entity.",";
-		$sql.= " fk_element=".(isset($this->fk_element)?$this->fk_element:"null").",";
-		$sql.= " type_element=".(isset($this->type_element)?"'".$this->db->escape($this->type_element)."'":"null").",";
-		$sql.= " filtervalue=".(isset($this->filtervalue)?"'".$this->db->escape($this->filtervalue)."'":"null").",";
-		$sql.= " fk_user_mod=".$user->id;
+		$sql .= " name=".(isset($this->name) ? "'".$this->db->escape($this->name)."'" : "''").",";
+		$sql .= " entity=".$conf->entity.",";
+		$sql .= " fk_element=".(isset($this->fk_element) ? $this->fk_element : "null").",";
+		$sql .= " type_element=".(isset($this->type_element) ? "'".$this->db->escape($this->type_element)."'" : "null").",";
+		$sql .= " filtervalue=".(isset($this->filtervalue) ? "'".$this->db->escape($this->filtervalue)."'" : "null").",";
+		$sql .= " fk_user_mod=".$user->id;
 
-		$sql.= " WHERE rowid=".$this->id;
+		$sql .= " WHERE rowid=".$this->id;
 
 		$this->db->begin();
 		dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
 		$resql = $this->db->query($sql);
-		if (! $resql) {
+		if (!$resql) {
             $error++;
-            $this->errors[]="Error ".$this->db->lasterror();
+            $this->errors[] = "Error ".$this->db->lasterror();
         }
 
 		//if (! $error)
@@ -433,13 +433,13 @@ class AdvanceTargetingMailing extends CommonObject
 		// Commit or rollback
 		if ($error)
 		{
-			foreach($this->errors as $errmsg)
+			foreach ($this->errors as $errmsg)
 			{
 				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
 			}
 			$this->db->rollback();
-			return -1*$error;
+			return -1 * $error;
 		}
 		else
 		{
@@ -458,13 +458,13 @@ class AdvanceTargetingMailing extends CommonObject
     public function delete($user, $notrigger = 0)
 	{
 		global $conf, $langs;
-		$error=0;
+		$error = 0;
 
 		$this->db->begin();
 
-		if (! $error)
+		if (!$error)
 		{
-			if (! $notrigger)
+			if (!$notrigger)
 			{
 				// Uncomment this and change MYOBJECT to your own tag if you
 				// want this action calls a trigger.
@@ -478,26 +478,26 @@ class AdvanceTargetingMailing extends CommonObject
 			}
 		}
 
-		if (! $error)
+		if (!$error)
 		{
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."advtargetemailing";
-			$sql.= " WHERE rowid=".$this->id;
+			$sql .= " WHERE rowid=".$this->id;
 
 			dol_syslog(get_class($this)."::delete sql=".$sql);
 			$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)
+			foreach ($this->errors as $errmsg)
 			{
 				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
 			}
 			$this->db->rollback();
-			return -1*$error;
+			return -1 * $error;
 		}
 		else
 		{
@@ -516,17 +516,17 @@ class AdvanceTargetingMailing extends CommonObject
 	 */
     public function savequery($user, $arrayquery)
 	{
-		global $langs,$conf;
+		global $langs, $conf;
 
 		if (!empty($arrayquery)) {
-			$result=$this->fetch_by_mailing($this->fk_element);
-			$this->filtervalue=json_encode($arrayquery);
-			if ($result<0) {
+			$result = $this->fetch_by_mailing($this->fk_element);
+			$this->filtervalue = json_encode($arrayquery);
+			if ($result < 0) {
 				return -1;
 			}
 			if (!empty($this->id)) {
 				$this->update($user);
-			}else {
+			} else {
 				$this->create($user);
 			}
 		}
@@ -662,7 +662,7 @@ class AdvanceTargetingMailing extends CommonObject
 
 			if ($num)
 			{
-				while( $i < $num)
+				while ($i < $num)
 				{
 					$obj = $this->db->fetch_object($resql);
 
@@ -675,8 +675,8 @@ class AdvanceTargetingMailing extends CommonObject
 
 			return $num;
 		} else {
-			$this->error = "Error " . $this->db->lasterror();
-			dol_syslog(get_class($this) . "::query_thirdparty " . $this->error, LOG_ERR);
+			$this->error = "Error ".$this->db->lasterror();
+			dol_syslog(get_class($this)."::query_thirdparty ".$this->error, LOG_ERR);
 			return -1;
 		}
 	}
@@ -905,7 +905,7 @@ class AdvanceTargetingMailing extends CommonObject
 
 			if ($num)
 			{
-				while( $i < $num)
+				while ($i < $num)
 				{
 					$obj = $this->db->fetch_object($resql);
 
@@ -918,8 +918,8 @@ class AdvanceTargetingMailing extends CommonObject
 
 			return $num;
 		} else {
-			$this->error = "Error " . $this->db->lasterror();
-			dol_syslog(get_class($this) . "::query_contact " . $this->error, LOG_ERR);
+			$this->error = "Error ".$this->db->lasterror();
+			dol_syslog(get_class($this)."::query_contact ".$this->error, LOG_ERR);
 			return -1;
 		}
 	}
@@ -940,26 +940,26 @@ class AdvanceTargetingMailing extends CommonObject
 
 		//This is a multiple value test
 		if (preg_match('/;/', $criteria)) {
-			$return_sql_not_like=array();
-			$return_sql_like=array();
+			$return_sql_not_like = array();
+			$return_sql_like = array();
 
-			$criteria_array=explode(';', $criteria);
-			foreach($criteria_array as $inter_criteria) {
+			$criteria_array = explode(';', $criteria);
+			foreach ($criteria_array as $inter_criteria) {
 				if (preg_match('/!/', $inter_criteria)) {
-					$return_sql_not_like[]= '('.$column_to_test.' NOT LIKE \''.str_replace('!', '', $inter_criteria).'\')';
+					$return_sql_not_like[] = '('.$column_to_test.' NOT LIKE \''.str_replace('!', '', $inter_criteria).'\')';
 				} else {
-					$return_sql_like[]= '('.$column_to_test.' LIKE \''.$inter_criteria.'\')';
+					$return_sql_like[] = '('.$column_to_test.' LIKE \''.$inter_criteria.'\')';
 				}
 			}
 
-			if (count($return_sql_like)>0) {
-				$return_sql_criteria .= '(' . implode(' OR ', $return_sql_like) .')';
+			if (count($return_sql_like) > 0) {
+				$return_sql_criteria .= '('.implode(' OR ', $return_sql_like).')';
 			}
-			if (count($return_sql_not_like)>0) {
-				$return_sql_criteria .= ' AND (' . implode(' AND ', $return_sql_not_like).')';
+			if (count($return_sql_not_like) > 0) {
+				$return_sql_criteria .= ' AND ('.implode(' AND ', $return_sql_not_like).')';
 			}
 		} else {
-			$return_sql_criteria .= $column_to_test . ' LIKE \''.$this->db->escape($criteria).'\'';
+			$return_sql_criteria .= $column_to_test.' LIKE \''.$this->db->escape($criteria).'\'';
 		}
 
 		$return_sql_criteria .= ')';

+ 47 - 47
htdocs/comm/mailing/list.php

@@ -29,22 +29,22 @@ require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php';
 $langs->load("mails");
 
 // Security check
-$result=restrictedArea($user, 'mailing');
+$result = restrictedArea($user, 'mailing');
 
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $page = 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
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (! $sortorder) $sortorder="DESC";
-if (! $sortfield) $sortfield="m.date_creat";
+if (!$sortorder) $sortorder = "DESC";
+if (!$sortfield) $sortfield = "m.date_creat";
 
-$search_all=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml'));
-$search_ref=GETPOST("search_ref", "alpha") ? GETPOST("search_ref", "alpha") : GETPOST("sref", "alpha");
-$filteremail=GETPOST('filteremail', 'alpha');
+$search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
+$search_ref = GETPOST("search_ref", "alpha") ? GETPOST("search_ref", "alpha") : GETPOST("sref", "alpha");
+$filteremail = GETPOST('filteremail', 'alpha');
 
 $object = new Mailing($db);
 
@@ -55,7 +55,7 @@ $extrafields = new ExtraFields($db);
 // fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label($object->table_element);
 
-$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
 
 // List of fields to search into when doing a "search in all"
 $fieldstosearchall = array(
@@ -69,11 +69,11 @@ $fieldstosearchall = 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
+$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))
@@ -82,7 +82,7 @@ if (empty($reshook))
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
 	// Purge search criteria
-	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') ||GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
 	{
 		/*foreach($object->fields as $key => $val)
 		{
@@ -90,13 +90,13 @@ if (empty($reshook))
 		}*/
 		$search_ref = '';
 		$search_all = '';
-		$toselect='';
-		$search_array_options=array();
+		$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
+		$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
 	}
 
 	// Mass actions
@@ -121,28 +121,28 @@ $form = new Form($db);
 if ($filteremail)
 {
 	$sql = "SELECT m.rowid, m.titre, m.nbemail, m.statut, m.date_creat as datec, m.date_envoi as date_envoi,";
-	$sql.= " mc.statut as sendstatut";
-	$sql.= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc";
-	$sql.= " WHERE m.rowid = mc.fk_mailing AND m.entity = ".$conf->entity;
-	$sql.= " AND mc.email = '".$db->escape($filteremail)."'";
-	if ($search_ref) $sql.= " AND m.rowid = '".$db->escape($search_ref)."'";
-	if ($search_all) $sql.= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')";
-	if (! $sortorder) $sortorder="ASC";
-	if (! $sortfield) $sortfield="m.rowid";
-	$sql.= $db->order($sortfield, $sortorder);
-	$sql.= $db->plimit($conf->liste_limit +1, $offset);
+	$sql .= " mc.statut as sendstatut";
+	$sql .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc";
+	$sql .= " WHERE m.rowid = mc.fk_mailing AND m.entity = ".$conf->entity;
+	$sql .= " AND mc.email = '".$db->escape($filteremail)."'";
+	if ($search_ref) $sql .= " AND m.rowid = '".$db->escape($search_ref)."'";
+	if ($search_all) $sql .= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')";
+	if (!$sortorder) $sortorder = "ASC";
+	if (!$sortfield) $sortfield = "m.rowid";
+	$sql .= $db->order($sortfield, $sortorder);
+	$sql .= $db->plimit($conf->liste_limit + 1, $offset);
 }
 else
 {
 	$sql = "SELECT m.rowid, m.titre, m.nbemail, m.statut, m.date_creat as datec, m.date_envoi as date_envoi";
-	$sql.= " FROM ".MAIN_DB_PREFIX."mailing as m";
-	$sql.= " WHERE m.entity = ".$conf->entity;
-	if ($search_ref) $sql.= " AND m.rowid = '".$db->escape($search_ref)."'";
-	if ($search_all) $sql.= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')";
-	if (! $sortorder) $sortorder="ASC";
-	if (! $sortfield) $sortfield="m.rowid";
-	$sql.= $db->order($sortfield, $sortorder);
-	$sql.= $db->plimit($conf->liste_limit +1, $offset);
+	$sql .= " FROM ".MAIN_DB_PREFIX."mailing as m";
+	$sql .= " WHERE m.entity = ".$conf->entity;
+	if ($search_ref) $sql .= " AND m.rowid = '".$db->escape($search_ref)."'";
+	if ($search_all) $sql .= " AND (m.titre like '%".$db->escape($search_all)."%' OR m.sujet like '%".$db->escape($search_all)."%' OR m.body like '%".$db->escape($search_all)."%')";
+	if (!$sortorder) $sortorder = "ASC";
+	if (!$sortfield) $sortfield = "m.rowid";
+	$sql .= $db->order($sortfield, $sortorder);
+	$sql .= $db->plimit($conf->liste_limit + 1, $offset);
 }
 
 //print $sql;
@@ -151,19 +151,19 @@ if ($result)
 {
 	$num = $db->num_rows($result);
 
-	$title=$langs->trans("ListOfEMailings");
-	if ($filteremail) $title.=' ('.$langs->trans("SentTo", $filteremail).')';
+	$title = $langs->trans("ListOfEMailings");
+	if ($filteremail) $title .= ' ('.$langs->trans("SentTo", $filteremail).')';
 
-	$newcardbutton='';
+	$newcardbutton = '';
 	if ($user->rights->mailing->creer)
 	{
-        $newcardbutton.= dolGetButtonTitle($langs->trans('NewMailing'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/mailing/card.php?action=create');
+        $newcardbutton .= dolGetButtonTitle($langs->trans('NewMailing'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/mailing/card.php?action=create');
 	}
 
 	$i = 0;
 
 	$param = "&search_all=".urlencode($search_all);
-	if ($filteremail) $param.='&filteremail='.urlencode($filteremail);
+	if ($filteremail) $param .= '&filteremail='.urlencode($filteremail);
 
 	print '<form method="GET" action="'.$_SERVER["PHP_SELF"].'">';
 	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
@@ -178,7 +178,7 @@ if ($result)
 	$moreforfilter = '';
 
     print '<div class="div-table-responsive">';
-    print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
+    print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
 
 	print '<tr class="liste_titre_filter">';
 	print '<td class="liste_titre">';
@@ -189,11 +189,11 @@ if ($result)
 	print '<input type="text" class="flat maxwidth100 maxwidth50onsmartphone" name="search_all" value="'.dol_escape_htmltag($search_all).'">';
 	print '</td>';
 	print '<td class="liste_titre">&nbsp;</td>';
-	if (! $filteremail) print '<td class="liste_titre">&nbsp;</td>';
+	if (!$filteremail) print '<td class="liste_titre">&nbsp;</td>';
 	print '<td class="liste_titre">&nbsp;</td>';
 	print '<td class="liste_titre">&nbsp;</td>';
 	print '<td class="liste_titre maxwidthsearch">';
-	$searchpicto=$form->showFilterAndCheckAddButtons(0);
+	$searchpicto = $form->showFilterAndCheckAddButtons(0);
 	print $searchpicto;
 	print '</td>';
 	print "</tr>\n";
@@ -202,15 +202,15 @@ if ($result)
 	print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "m.rowid", $param, "", "", $sortfield, $sortorder);
 	print_liste_field_titre("Title", $_SERVER["PHP_SELF"], "m.titre", $param, "", "", $sortfield, $sortorder);
 	print_liste_field_titre("DateCreation", $_SERVER["PHP_SELF"], "m.date_creat", $param, "", 'align="center"', $sortfield, $sortorder);
-	if (! $filteremail) print_liste_field_titre("NbOfEMails", $_SERVER["PHP_SELF"], "m.nbemail", $param, "", 'align="center"', $sortfield, $sortorder);
-	if (! $filteremail) print_liste_field_titre("DateLastSend", $_SERVER["PHP_SELF"], "m.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder);
+	if (!$filteremail) print_liste_field_titre("NbOfEMails", $_SERVER["PHP_SELF"], "m.nbemail", $param, "", 'align="center"', $sortfield, $sortorder);
+	if (!$filteremail) print_liste_field_titre("DateLastSend", $_SERVER["PHP_SELF"], "m.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder);
 	else print_liste_field_titre("DateSending", $_SERVER["PHP_SELF"], "mc.date_envoi", $param, "", 'align="center"', $sortfield, $sortorder);
-	print_liste_field_titre("Status", $_SERVER["PHP_SELF"], ($filteremail?"mc.statut":"m.statut"), $param, "", 'class="right"', $sortfield, $sortorder);
+	print_liste_field_titre("Status", $_SERVER["PHP_SELF"], ($filteremail ? "mc.statut" : "m.statut"), $param, "", 'class="right"', $sortfield, $sortorder);
 	print_liste_field_titre('', $_SERVER["PHP_SELF"], "", '', '', 'class="right"', $sortfield, $sortorder, 'maxwidthsearch ');
 	print "</tr>\n";
 
 
-	$email=new Mailing($db);
+	$email = new Mailing($db);
 
 	while ($i < min($num, $limit))
 	{
@@ -233,7 +233,7 @@ if ($result)
 		print '</td>';
 
 		// Nb of email
-		if (! $filteremail)
+		if (!$filteremail)
 		{
 			print '<td align="center">';
 			$nbemail = $obj->nbemail;

+ 6 - 6
htdocs/comm/propal/contact.php

@@ -62,7 +62,7 @@ if ($id > 0 || ! empty($ref))
 		$error++;
 	}
 }
-if (! $error)
+if (!$error)
 {
 	$object->fetch_thirdparty();
 }
@@ -109,7 +109,7 @@ elseif ($action == 'swapstatut' && $user->rights->propale->creer)
 {
 	if ($object->id > 0)
 	{
-	    $result=$object->swapContactStatus(GETPOST('ligne'));
+	    $result = $object->swapContactStatus(GETPOST('ligne'));
 	}
 }
 
@@ -143,7 +143,7 @@ elseif ($action == 'setaddress' && $user->rights->propale->creer)
 llxHeader('', $langs->trans('Proposal'), 'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos');
 
 $form = new Form($db);
-$formcompany= new FormCompany($db);
+$formcompany = new FormCompany($db);
 $formother = new FormOther($db);
 
 if ($object->id > 0)
@@ -205,10 +205,10 @@ if ($object->id > 0)
 
 
 	// 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)
+	$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
+	foreach ($dirtpls as $reldir)
 	{
-		$res=@include dol_buildpath($reldir.'/contacts.tpl.php');
+		$res = @include dol_buildpath($reldir.'/contacts.tpl.php');
 		if ($res) break;
 	}
 }

+ 5 - 5
htdocs/comm/propal/document.php

@@ -32,8 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/propal.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';
-if (! empty($conf->projet->enabled)) {
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+if (!empty($conf->projet->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 }
 
 // Load translation files required by the page
@@ -79,7 +79,7 @@ if ($object->id > 0)
 {
     $object->fetch_thirdparty();
     $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
-    include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
+    include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
 }
 
 
@@ -176,8 +176,8 @@ if ($object->id > 0)
 	$modulepart = 'propal';
 	$permission = $user->rights->propal->creer;
 	$permtoedit = $user->rights->propal->creer;
-	$param = '&id=' . $object->id;
-	include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
+	$param = '&id='.$object->id;
+	include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
 }
 else
 {

+ 4 - 4
htdocs/comm/propal/note.php

@@ -51,9 +51,9 @@ $object = new Propal($db);
  * Actions
  */
 
-$permissionnote=$user->rights->propale->creer;	// Used by the include of actions_setnotes.inc.php
+$permissionnote = $user->rights->propale->creer; // Used by the include of actions_setnotes.inc.php
 
-include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include, not includ_once
+include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once
 
 
 
@@ -65,11 +65,11 @@ llxHeader('', $langs->trans('Proposal'), 'EN:Commercial_Proposals|FR:Proposition
 
 $form = new Form($db);
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	if ($mesg) print $mesg;
 
-	$now=dol_now();
+	$now = dol_now();
 
 	if ($object->fetch($id, $ref) > 0)
 	{

+ 7 - 7
htdocs/commande/contact.php

@@ -83,7 +83,7 @@ elseif ($action == 'swapstatut' && $user->rights->commande->creer)
 {
 	if ($object->fetch($id))
 	{
-	    $result=$object->swapContactStatus(GETPOST('ligne'));
+	    $result = $object->swapContactStatus(GETPOST('ligne'));
 	}
 	else
 	{
@@ -124,8 +124,8 @@ llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients|
 $form = new Form($db);
 $formcompany = new FormCompany($db);
 $formother = new FormOther($db);
-$contactstatic=new Contact($db);
-$userstatic=new User($db);
+$contactstatic = new Contact($db);
+$userstatic = new User($db);
 
 
 /* *************************************************************************** */
@@ -134,7 +134,7 @@ $userstatic=new User($db);
 /*                                                                             */
 /* *************************************************************************** */
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	$langs->trans("OrderCard");
 
@@ -200,10 +200,10 @@ if ($id > 0 || ! empty($ref))
 		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)
+		$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
+		foreach ($dirtpls as $reldir)
 		{
-		    $res=@include dol_buildpath($reldir.'/contacts.tpl.php');
+		    $res = @include dol_buildpath($reldir.'/contacts.tpl.php');
 		    if ($res) break;
 		}
 	}

+ 9 - 9
htdocs/commande/document.php

@@ -31,9 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/order.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';
-require_once DOL_DOCUMENT_ROOT .'/commande/class/commande.class.php';
-if (! empty($conf->projet->enabled)) {
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
+if (!empty($conf->projet->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 }
 
 // Load translation files required by the page
@@ -49,7 +49,7 @@ if ($user->socid)
 {
 	$socid = $user->socid;
 }
-$result=restrictedArea($user, 'commande', $id, '');
+$result = restrictedArea($user, 'commande', $id, '');
 
 // Get parameters
 $sortfield = GETPOST("sortfield", 'alpha');
@@ -76,10 +76,10 @@ $object = new Commande($db);
 if ($object->fetch($id))
 {
 	$object->fetch_thirdparty();
-	$upload_dir = $conf->commande->multidir_output[$object->entity] . "/" . dol_sanitizeFileName($object->ref);
+	$upload_dir = $conf->commande->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref);
 }
 
-include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
+include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
 
 
 /*
@@ -90,7 +90,7 @@ llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients|
 
 $form = new Form($db);
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	if ($object->fetch($id, $ref))
 	{
@@ -179,8 +179,8 @@ if ($id > 0 || ! empty($ref))
 		$modulepart = 'commande';
 		$permission = $user->rights->commande->creer;
 		$permtoedit = $user->rights->commande->creer;
-		$param = '&id=' . $object->id.'&entity=' . (! empty($object->entity)?$object->entity:$conf->entity);
-		include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
+		$param = '&id='.$object->id.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity);
+		include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
 	}
 	else
 	{

+ 2 - 2
htdocs/commande/info.php

@@ -27,8 +27,8 @@ require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/order.lib.php';
-if (! empty($conf->projet->enabled)) {
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+if (!empty($conf->projet->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 }
 
 if (!$user->rights->commande->lire)	accessforbidden();

+ 2 - 2
htdocs/commande/note.php

@@ -71,7 +71,7 @@ llxHeader('', $langs->trans('Order'), 'EN:Customers_Orders|FR:Commandes_Clients|
 
 $form = new Form($db);
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	$object->fetch_thirdparty();
 
@@ -134,7 +134,7 @@ if ($id > 0 || ! empty($ref))
 	print '<div class="underbanner clearboth"></div>';
 
 
-	$cssclass="titlefield";
+	$cssclass = "titlefield";
 	include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
 
 	print '</div>';

+ 106 - 106
htdocs/commande/orderstoinvoice.php

@@ -36,50 +36,50 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
-if (! empty($conf->projet->enabled)) {
+if (!empty($conf->projet->enabled)) {
 	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
 }
 
 // Load translation files required by the page
 $langs->loadLangs(array("orders", "deliveries", "companies"));
 
-if (! $user->rights->facture->creer)
+if (!$user->rights->facture->creer)
 	accessforbidden();
 
-$id				= (GETPOST('id')?GETPOST('id', 'int'):GETPOST("facid", "int"));  // For backward compatibility
+$id				= (GETPOST('id') ?GETPOST('id', 'int') : GETPOST("facid", "int")); // For backward compatibility
 $ref			= GETPOST('ref', 'alpha');
 $action			= GETPOST('action', 'alpha');
 $confirm		= GETPOST('confirm', 'alpha');
 $sref			= GETPOST('sref', 'alpha');
-$sref_client	= GETPOST('sref_client', 'alpha');
-$sall			= trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml'));
-$socid			= GETPOST('socid', 'int');
-$selected		= GETPOST('orders_to_invoice');
+$sref_client = GETPOST('sref_client', 'alpha');
+$sall			= trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
+$socid = GETPOST('socid', 'int');
+$selected = GETPOST('orders_to_invoice');
 $sortfield		= GETPOST("sortfield", 'alpha');
 $sortorder		= GETPOST("sortorder", 'alpha');
-$viewstatut		= GETPOST('viewstatut', 'alpha');
+$viewstatut = GETPOST('viewstatut', 'alpha');
 
 $error = 0;
 
-if (! $sortfield) $sortfield='c.rowid';
-if (! $sortorder) $sortorder='DESC';
+if (!$sortfield) $sortfield = 'c.rowid';
+if (!$sortorder) $sortorder = 'DESC';
 
 $now = dol_now();
-$date_start = dol_mktime(0, 0, 0, $_REQUEST["date_startmonth"], $_REQUEST["date_startday"], $_REQUEST["date_startyear"]);	// Date for local PHP server
+$date_start = dol_mktime(0, 0, 0, $_REQUEST["date_startmonth"], $_REQUEST["date_startday"], $_REQUEST["date_startyear"]); // Date for local PHP server
 $date_end = dol_mktime(23, 59, 59, $_REQUEST["date_endmonth"], $_REQUEST["date_endday"], $_REQUEST["date_endyear"]);
-$date_starty = dol_mktime(0, 0, 0, $_REQUEST["date_start_delymonth"], $_REQUEST["date_start_delyday"], $_REQUEST["date_start_delyyear"]);	// Date for local PHP server
+$date_starty = dol_mktime(0, 0, 0, $_REQUEST["date_start_delymonth"], $_REQUEST["date_start_delyday"], $_REQUEST["date_start_delyyear"]); // Date for local PHP server
 $date_endy = dol_mktime(23, 59, 59, $_REQUEST["date_end_delymonth"], $_REQUEST["date_end_delyday"], $_REQUEST["date_end_delyyear"]);
 
 $extrafields = new ExtraFields($db);
 
-$object=new Facture($db);
+$object = new Facture($db);
 
 // fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label($object->table_element);
 
 if ($action == 'create')
 {
-	if (! is_array($selected))
+	if (!is_array($selected))
 	{
 		$error++;
 		setEventMessages($langs->trans('Error_OrderNotChecked'), null, 'errors');
@@ -93,7 +93,7 @@ if ($action == 'create')
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
-$hookmanager=new HookManager($db);
+$hookmanager = new HookManager($db);
 $hookmanager->initHooks(array('orderstoinvoice'));
 
 
@@ -107,7 +107,7 @@ if (($action == 'create' || $action == 'add') && !$error)
 	require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
-	if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
+	if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 
 	$langs->load('bills');
 	$langs->load('products');
@@ -118,8 +118,8 @@ if (($action == 'create' || $action == 'add') && !$error)
 		$n        = count($orders_id);
 		$i        = 0;
 
-		$originid=$orders_id[0];
-		$_GET['originid']=$orders_id[0];
+		$originid = $orders_id[0];
+		$_GET['originid'] = $orders_id[0];
 	}
 	if (isset($_POST['orders_to_invoice']))
 	{
@@ -189,23 +189,23 @@ if (($action == 'create' || $action == 'add') && !$error)
 					$id = $object->create($user);
 					$object->fetch_thirdparty();
 
-					if ($id>0)
+					if ($id > 0)
 					{
-						foreach($orders_id as $origin => $origin_id)
+						foreach ($orders_id as $origin => $origin_id)
 						{
-							$origin_id = (! empty($origin_id) ? $origin_id : $object->origin_id);
+							$origin_id = (!empty($origin_id) ? $origin_id : $object->origin_id);
 							$db->begin();
 							$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
-							$sql.= "fk_source";
-							$sql.= ", sourcetype";
-							$sql.= ", fk_target";
-							$sql.= ", targettype";
-							$sql.= ") VALUES (";
-							$sql.= $origin_id;
-							$sql.= ", '".$object->origin."'";
-							$sql.= ", ".$id;
-							$sql.= ", '".$object->element."'";
-							$sql.= ")";
+							$sql .= "fk_source";
+							$sql .= ", sourcetype";
+							$sql .= ", fk_target";
+							$sql .= ", targettype";
+							$sql .= ") VALUES (";
+							$sql .= $origin_id;
+							$sql .= ", '".$object->origin."'";
+							$sql .= ", ".$id;
+							$sql .= ", '".$object->element."'";
+							$sql .= ")";
 
 							if ($db->query($sql))
 							{
@@ -222,7 +222,7 @@ if (($action == 'create' || $action == 'add') && !$error)
 							include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
 							$objectsrc = new Commande($db);
 							dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
-							$result=$objectsrc->fetch($orders_id[$ii]);
+							$result = $objectsrc->fetch($orders_id[$ii]);
 							if ($result > 0)
 							{
 								if ($closeOrders)
@@ -236,26 +236,26 @@ if (($action == 'create' || $action == 'add') && !$error)
 									$objectsrc->fetch_lines();
 									$lines = $objectsrc->lines;
 								}
-								$fk_parent_line=0;
-								$num=count($lines);
-								for ($i=0;$i<$num;$i++)
+								$fk_parent_line = 0;
+								$num = count($lines);
+								for ($i = 0; $i < $num; $i++)
 								{
-									$desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
+									$desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle);
 									if ($lines[$i]->subprice < 0)
 									{
 										// Negative line, we create a discount line
 										$discount = new DiscountAbsolute($db);
-										$discount->fk_soc=$object->socid;
-										$discount->amount_ht=abs($lines[$i]->total_ht);
-										$discount->amount_tva=abs($lines[$i]->total_tva);
-										$discount->amount_ttc=abs($lines[$i]->total_ttc);
-										$discount->tva_tx=$lines[$i]->tva_tx;
-										$discount->fk_user=$user->id;
-										$discount->description=$desc;
-										$discountid=$discount->create($user);
+										$discount->fk_soc = $object->socid;
+										$discount->amount_ht = abs($lines[$i]->total_ht);
+										$discount->amount_tva = abs($lines[$i]->total_tva);
+										$discount->amount_ttc = abs($lines[$i]->total_ttc);
+										$discount->tva_tx = $lines[$i]->tva_tx;
+										$discount->fk_user = $user->id;
+										$discount->description = $desc;
+										$discountid = $discount->create($user);
 										if ($discountid > 0)
 										{
-											$result=$object->insert_discount($discountid);
+											$result = $object->insert_discount($discountid);
 											//$result=$discount->link_to_invoice($lineid,$id);
 										}
 										else
@@ -268,17 +268,17 @@ if (($action == 'create' || $action == 'add') && !$error)
 									else
 									{
 										// Positive line
-										$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
+										$product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
 										// Date start
-										$date_start=false;
-										if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
-										if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
-										if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
+										$date_start = false;
+										if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue;
+										if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel;
+										if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start;
 										//Date end
-										$date_end=false;
-										if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
-										if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
-										if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
+										$date_end = false;
+										if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue;
+										if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel;
+										if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end;
 										// Reset fk_parent_line for no child products and special product
 										if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
 										{
@@ -320,11 +320,11 @@ if (($action == 'create' || $action == 'add') && !$error)
 										);
 										if ($result > 0)
 										{
-											$lineid=$result;
+											$lineid = $result;
 										}
 										else
 										{
-											$lineid=0;
+											$lineid = 0;
 											$error++;
 											break;
 										}
@@ -354,7 +354,7 @@ if (($action == 'create' || $action == 'add') && !$error)
 		}
 
 		// End of object creation, we show it
-		if ($id > 0 && ! $error)
+		if ($id > 0 && !$error)
 		{
 			$db->commit();
 			header('Location: '.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$id);
@@ -363,9 +363,9 @@ if (($action == 'create' || $action == 'add') && !$error)
 		else
 		{
 			$db->rollback();
-			$action='create';
-			$_GET["origin"]=$_POST["origin"];
-			$_GET["originid"]=$_POST["originid"];
+			$action = 'create';
+			$_GET["origin"] = $_POST["origin"];
+			$_GET["originid"] = $_POST["originid"];
 			setEventMessages($object->error, $object->errors, 'errors');
 			$error++;
 		}
@@ -385,27 +385,27 @@ $companystatic = new Societe($db);
 // Mode creation
 if ($action == 'create' && !$error)
 {
-	$facturestatic=new Facture($db);
+	$facturestatic = new Facture($db);
 
 	llxHeader();
 	print load_fiche_titre($langs->trans('NewBill'));
 
 	$soc = new Societe($db);
-	if ($socid) $res=$soc->fetch($socid);
+	if ($socid) $res = $soc->fetch($socid);
 	if ($res)
 	{
 		$cond_reglement_id 	= $soc->cond_reglement_id;
 		$mode_reglement_id 	= $soc->mode_reglement_id;
-		$remise_percent 	= $soc->remise_percent;
+		$remise_percent = $soc->remise_percent;
 	}
-	$remise_absolue 	= 0;
-	$dateinvoice		= empty($conf->global->MAIN_AUTOFILL_DATE)?-1:'';
+	$remise_absolue = 0;
+	$dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '';
 
-	$absolute_discount=$soc->getAvailableDiscounts();
+	$absolute_discount = $soc->getAvailableDiscounts();
 	print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
 	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 	print '<input type="hidden" name="action" value="add">';
-	print '<input type="hidden" name="socid" value="'.$soc->id.'">' ."\n";
+	print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
 	print '<input name="ref" type="hidden" value="provisoire">';
 	print '<input name="ref_client" type="hidden" value="'.$ref_client.'">';
 	print '<input name="ref_int" type="hidden" value="'.$ref_int.'">';
@@ -433,9 +433,9 @@ if ($action == 'create' && !$error)
 
 	// Standard invoice
 	print '<tr height="18"><td width="16px" valign="middle">';
-	print '<input type="radio" name="type" value="0"'.(GETPOST('type')==0?' checked':'').'>';
+	print '<input type="radio" name="type" value="0"'.(GETPOST('type') == 0 ? ' checked' : '').'>';
 	print '</td><td valign="middle">';
-	$desc=$html->textwithpicto($langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1);
+	$desc = $html->textwithpicto($langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1);
 	print $desc;
 	print '</td></tr>'."\n";
 	print '</table>';
@@ -446,16 +446,16 @@ if ($action == 'create' && !$error)
 	print '</td></tr>';
 	// Payment term
 	print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
-	$html->select_conditions_paiements(isset($_POST['cond_reglement_id'])?$_POST['cond_reglement_id']:$cond_reglement_id, 'cond_reglement_id');
+	$html->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id');
 	print '</td></tr>';
 	// Payment mode
 	print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>';
-	$html->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id, 'mode_reglement_id');
+	$html->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id');
 	print '</td></tr>';
 	// Project
-	if (! empty($conf->projet->enabled))
+	if (!empty($conf->projet->enabled))
 	{
-		$formproject=new FormProjets($db);
+		$formproject = new FormProjets($db);
 
 		$langs->load('projects');
 		print '<tr><td>'.$langs->trans('Project').'</td><td>';
@@ -468,7 +468,7 @@ if ($action == 'create' && !$error)
 	$listoforders = array();
 	foreach ($selected as $sel)
 	{
-		$result=$objectsrc->fetch($sel);
+		$result = $objectsrc->fetch($sel);
 		if ($result > 0)
 		{
 			$listoforders[] = $objectsrc->ref;
@@ -476,12 +476,12 @@ if ($action == 'create' && !$error)
 	}
 
 	// Other attributes
-	$parameters=array('objectsrc' => $objectsrc, 'idsrc' => $listoforders);
-	$reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+	$parameters = array('objectsrc' => $objectsrc, 'idsrc' => $listoforders);
+	$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
     print $hookmanager->resPrint;
 	if (empty($reshook))
 	{
-		$object=new Facture($db);
+		$object = new Facture($db);
 		print $object->showOptionals($extrafields, 'edit');
 	}
 
@@ -489,7 +489,7 @@ if ($action == 'create' && !$error)
 	print '<tr><td>'.$langs->trans('Model').'</td>';
 	print '<td>';
 	include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
-	$liste=ModelePDFFactures::liste_modeles($db);
+	$liste = ModelePDFFactures::liste_modeles($db);
 	print $html->selectarray('model', $liste, $conf->global->FACTURE_ADDON_PDF);
 	print "</td></tr>";
 
@@ -550,36 +550,36 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
 	<?php
 
 	$sql = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.entity, c.ref, c.total_ht, c.ref_client,';
-	$sql.= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as billed';
-	$sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
-	$sql.= ', '.MAIN_DB_PREFIX.'commande as c';
-	if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-	$sql.= ' WHERE c.entity IN ('.getEntity('commande').')';
-	$sql.= ' AND c.fk_soc = s.rowid';
+	$sql .= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as billed';
+	$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
+	$sql .= ', '.MAIN_DB_PREFIX.'commande as c';
+	if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+	$sql .= ' WHERE c.entity IN ('.getEntity('commande').')';
+	$sql .= ' AND c.fk_soc = s.rowid';
 
 	// Show orders with status validated, shipping started and delivered (well any order we can bill)
-	$sql.= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))";
+	$sql .= " AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))";
 
-	if ($socid)	$sql.= ' AND s.rowid = '.$socid;
-	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;
+	if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
 	if ($sref)
 	{
-		$sql.= " AND c.ref LIKE '%".$db->escape($sref)."%'";
+		$sql .= " AND c.ref LIKE '%".$db->escape($sref)."%'";
 	}
 	if ($sall)
 	{
-		$sql.= " AND (c.ref LIKE '%".$db->escape($sall)."%' OR c.note LIKE '%".$db->escape($sall)."%')";
+		$sql .= " AND (c.ref LIKE '%".$db->escape($sall)."%' OR c.note LIKE '%".$db->escape($sall)."%')";
 	}
 
 	//Date filter
-	if ($date_start && $date_end) $sql.= " AND c.date_commande >= '".$db->idate($date_start)."' AND c.date_commande <= '".$db->idate($date_end)."'";
-	if ($date_starty && $date_endy) $sql.= " AND c.date_livraison >= '".$db->idate($date_starty)."' AND c.date_livraison <= '".$db->idate($date_endy)."'";
+	if ($date_start && $date_end) $sql .= " AND c.date_commande >= '".$db->idate($date_start)."' AND c.date_commande <= '".$db->idate($date_end)."'";
+	if ($date_starty && $date_endy) $sql .= " AND c.date_livraison >= '".$db->idate($date_starty)."' AND c.date_livraison <= '".$db->idate($date_endy)."'";
 
 	if (!empty($sref_client))
 	{
-		$sql.= ' AND c.ref_client LIKE \'%'.$db->escape($sref_client).'%\'';
+		$sql .= ' AND c.ref_client LIKE \'%'.$db->escape($sref_client).'%\'';
 	}
-	$sql.= $db->order($sortfield, $sortorder);
+	$sql .= $db->order($sortfield, $sortorder);
 
 	$resql = $db->query($sql);
 	if ($resql)
@@ -590,18 +590,18 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
 			$soc->fetch($socid);
 		}
 		$title = $langs->trans('ListOfOrders');
-		$title.=' - '.$langs->trans('StatusOrderValidated').', '.$langs->trans("StatusOrderSent").', '.$langs->trans('StatusOrderToBill');
+		$title .= ' - '.$langs->trans('StatusOrderValidated').', '.$langs->trans("StatusOrderSent").', '.$langs->trans('StatusOrderToBill');
 		$num = $db->num_rows($resql);
 		print load_fiche_titre($title);
 		$i = 0;
-		$period=$html->selectDate($date_start, 'date_start', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_end, 'date_end', 0, 0, 1, '', 1, 0);
-		$periodely=$html->selectDate($date_starty, 'date_start_dely', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_endy, 'date_end_dely', 0, 0, 1, '', 1, 0);
+		$period = $html->selectDate($date_start, 'date_start', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_end, 'date_end', 0, 0, 1, '', 1, 0);
+		$periodely = $html->selectDate($date_starty, 'date_start_dely', 0, 0, 1, '', 1, 0).' - '.$html->selectDate($date_endy, 'date_end_dely', 0, 0, 1, '', 1, 0);
 
-		if (! empty($socid))
+		if (!empty($socid))
 		{
 			// Company
-			$companystatic->id=$socid;
-			$companystatic->name=$soc->name;
+			$companystatic->id = $socid;
+			$companystatic->name = $soc->name;
 			print '<h3>'.$companystatic->getNomUrl(1, 'customer').'</h3>';
 		}
 
@@ -664,8 +664,8 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
 			print '<tr class="oddeven">';
 			print '<td class="nowrap">';
 
-			$generic_commande->id=$objp->rowid;
-			$generic_commande->ref=$objp->ref;
+			$generic_commande->id = $objp->rowid;
+			$generic_commande->ref = $objp->ref;
 			$generic_commande->statut = $objp->fk_statut;
 			$generic_commande->date_commande = $db->jdate($objp->date_commande);
 			$generic_commande->date_livraison = $db->jdate($objp->date_livraison);
@@ -682,9 +682,9 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
 			print '</td>';
 
 			print '<td width="16" class="nobordernopadding hideonsmartphone right">';
-			$filename=dol_sanitizeFileName($objp->ref);
-			$filedir=$conf->commande->multidir_output[$objp->entity] . '/' . dol_sanitizeFileName($objp->ref);
-			$urlsource=$_SERVER['PHP_SELF'].'?id='.$objp->rowid;
+			$filename = dol_sanitizeFileName($objp->ref);
+			$filedir = $conf->commande->multidir_output[$objp->entity].'/'.dol_sanitizeFileName($objp->ref);
+			$urlsource = $_SERVER['PHP_SELF'].'?id='.$objp->rowid;
 			print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir);
 			print '</td></tr></table>';
 			print '</td>';
@@ -707,7 +707,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
 			// Checkbox
 			print '<td align="center">';
 			print '<input class="flat checkformerge" type="checkbox" name="orders_to_invoice[]" value="'.$objp->rowid.'">';
-			print '</td>' ;
+			print '</td>';
 
 			print '</tr>';
 
@@ -719,7 +719,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
         print '</div>';
 
 		// Buttons actions
-		print '<br><div class="center"><input type="checkbox" '.(empty($conf->global->INVOICE_CLOSE_ORDERS_OFF_BY_DEFAULT_FORMASSINVOICE)?' checked="checked"':'').' name="autocloseorders"> '.$langs->trans("CloseProcessedOrdersAutomatically");
+		print '<br><div class="center"><input type="checkbox" '.(empty($conf->global->INVOICE_CLOSE_ORDERS_OFF_BY_DEFAULT_FORMASSINVOICE) ? ' checked="checked"' : '').' name="autocloseorders"> '.$langs->trans("CloseProcessedOrdersAutomatically");
 		print '<div class="right">';
 		print '<input type="hidden" name="socid" value="'.$socid.'">';
 		print '<input type="hidden" name="action" value="create">';

+ 105 - 105
htdocs/compta/bank/card.php

@@ -29,19 +29,19 @@
  */
 
 require '../../main.inc.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formbank.class.php';
-require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
-if (! empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.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 . '/accountancy/class/accountingjournal.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbank.class.php';
+require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.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.'/accountancy/class/accountingjournal.class.php';
 
 // Load translation files required by the page
-$langs->loadLangs(array("banks","bills","categories","companies","compta"));
+$langs->loadLangs(array("banks", "bills", "categories", "companies", "compta"));
 
 $action = GETPOST('action', 'aZ09');
 $cancel = GETPOST('cancel', 'alpha');
@@ -59,17 +59,17 @@ $extrafields = new ExtraFields($db);
 $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('bankcard','globalcard'));
+$hookmanager->initHooks(array('bankcard', 'globalcard'));
 
 /*
  * Actions
  */
 
-if ($cancel) $action='';
+if ($cancel) $action = '';
 
 if ($action == 'add')
 {
-	$error=0;
+	$error = 0;
 
 	$db->begin();
 
@@ -124,26 +124,26 @@ if ($action == 'add')
 	if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number))
 	{
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountancyCode")), null, 'errors');
-		$action='create';       // Force chargement page en mode creation
+		$action = 'create'; // Force chargement page en mode creation
 		$error++;
 	}
 	if (empty($object->ref))
 	{
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors');
-		$action='create';       // Force chargement page en mode creation
+		$action = 'create'; // Force chargement page en mode creation
 		$error++;
 	}
 	if (empty($object->label))
 	{
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors');
-		$action='create';       // Force chargement page en mode creation
+		$action = 'create'; // Force chargement page en mode creation
 		$error++;
 	}
 
 	// Fill array 'array_options' with data from add form
 	$ret = $extrafields->setOptionalsFromPost(null, $object);
 
-	if (! $error)
+	if (!$error)
 	{
 		$id = $object->create($user);
 		if ($id > 0)
@@ -152,19 +152,19 @@ if ($action == 'add')
 			$categories = GETPOST('categories', 'array');
 			$object->setCategories($categories);
 
-			$_GET["id"]=$id;            // Force chargement page en mode visu
+			$_GET["id"] = $id; // Force chargement page en mode visu
 
-			$action='';
+			$action = '';
 		}
 		else {
 			$error++;
 			setEventMessages($object->error, $object->errors, 'errors');
 
-			$action='create';   // Force chargement page en mode creation
+			$action = 'create'; // Force chargement page en mode creation
 		}
 	}
 
-	if (! $error)
+	if (!$error)
 	{
 		$db->commit();
 	}
@@ -176,7 +176,7 @@ if ($action == 'add')
 
 if ($action == 'update')
 {
-	$error=0;
+	$error = 0;
 
 	// Update account
 	$object = new Account($db);
@@ -225,31 +225,31 @@ if ($action == 'update')
 	if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number))
 	{
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountancyCode")), null, 'errors');
-		$action='edit';       // Force chargement page en mode creation
+		$action = 'edit'; // Force chargement page en mode creation
 		$error++;
 	}
 	if (empty($object->ref))
 	{
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors');
-		$action='edit';       // Force chargement page en mode creation
+		$action = 'edit'; // Force chargement page en mode creation
 		$error++;
 	}
 	if (empty($object->label))
 	{
 		setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors');
-		$action='edit';       // Force chargement page en mode creation
+		$action = 'edit'; // Force chargement page en mode creation
 		$error++;
 	}
 
 	$db->begin();
 
-	if (! $error)
+	if (!$error)
 	{
 		// Fill array 'array_options' with data from add form
 		$ret = $extrafields->setOptionalsFromPost(null, $object);
 	}
 
-	if (! $error)
+	if (!$error)
 	{
 		$result = $object->update($user);
 		if ($result >= 0)
@@ -258,17 +258,17 @@ if ($action == 'update')
 			$categories = GETPOST('categories', 'array');
 			$object->setCategories($categories);
 
-			$_GET["id"]=$_POST["id"];   // Force chargement page en mode visu
+			$_GET["id"] = $_POST["id"]; // Force chargement page en mode visu
 		}
 		else
 		{
 			$error++;
 			setEventMessages($object->error, $object->errors, 'errors');
-			$action='edit';     // Force chargement page edition
+			$action = 'edit'; // Force chargement page edition
 		}
 	}
 
-	if (! $error)
+	if (!$error)
 	{
 		$db->commit();
 	}
@@ -306,11 +306,11 @@ if ($action == 'confirm_delete' && $_POST["confirm"] == "yes" && $user->rights->
 $form = new Form($db);
 $formbank = new FormBank($db);
 $formcompany = new FormCompany($db);
-if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db);
+if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db);
 
-$countrynotdefined=$langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')';
+$countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')';
 
-$title = $langs->trans("FinancialAccount") . " - " . $langs->trans("Card");
+$title = $langs->trans("FinancialAccount")." - ".$langs->trans("Card");
 $helpurl = "";
 llxHeader("", $title, $helpurl);
 
@@ -319,7 +319,7 @@ llxHeader("", $title, $helpurl);
 
 if ($action == 'create')
 {
-	$object=new Account($db);
+	$object = new Account($db);
 
 	print load_fiche_titre($langs->trans("NewFinancialAccount"), '', 'title_bank.png');
 
@@ -350,7 +350,7 @@ if ($action == 'create')
 
 	// Ref
 	print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans("Ref").'</td>';
-	print '<td><input size="8" type="text" class="flat" name="ref" value="'.dol_escape_htmltag(GETPOST("ref")?GETPOST("ref", 'alpha'):$object->ref).'" maxlength="12" autofocus></td></tr>';
+	print '<td><input size="8" type="text" class="flat" name="ref" value="'.dol_escape_htmltag(GETPOST("ref") ?GETPOST("ref", 'alpha') : $object->ref).'" maxlength="12" autofocus></td></tr>';
 
 	// Label
 	print '<tr><td class="fieldrequired">'.$langs->trans("LabelBankCashAccount").'</td>';
@@ -359,15 +359,15 @@ if ($action == 'create')
 	// Type
 	print '<tr><td class="fieldrequired">'.$langs->trans("AccountType").'</td>';
 	print '<td>';
-	$formbank->selectTypeOfBankAccount(isset($_POST["type"])?$_POST["type"]: Account::TYPE_CURRENT, "type");
+	$formbank->selectTypeOfBankAccount(isset($_POST["type"]) ? $_POST["type"] : Account::TYPE_CURRENT, "type");
 	print '</td></tr>';
 
 	// Currency
 	print '<tr><td class="fieldrequired">'.$langs->trans("Currency").'</td>';
 	print '<td>';
-	$selectedcode=$object->currency_code;
-	if (! $selectedcode) $selectedcode=$conf->currency;
-	print $form->selectCurrency((isset($_POST["account_currency_code"])?$_POST["account_currency_code"]:$selectedcode), 'account_currency_code');
+	$selectedcode = $object->currency_code;
+	if (!$selectedcode) $selectedcode = $conf->currency;
+	print $form->selectCurrency((isset($_POST["account_currency_code"]) ? $_POST["account_currency_code"] : $selectedcode), 'account_currency_code');
 	//print $langs->trans("Currency".$conf->currency);
 	//print '<input type="hidden" name="account_currency_code" value="'.$conf->currency.'">';
 	print '</td></tr>';
@@ -375,17 +375,17 @@ if ($action == 'create')
 	// Status
 	print '<tr><td class="fieldrequired">'.$langs->trans("Status").'</td>';
 	print '<td>';
-	print $form->selectarray("clos", $object->status, (GETPOST("clos", 'int')!=''?GETPOST("clos", 'int'):$object->clos));
+	print $form->selectarray("clos", $object->status, (GETPOST("clos", 'int') != '' ?GETPOST("clos", 'int') : $object->clos));
 	print '</td></tr>';
 
 	// Country
-	$selectedcode='';
+	$selectedcode = '';
 	if (isset($_POST["account_country_id"]))
 	{
-		$selectedcode=$_POST["account_country_id"]?$_POST["account_country_id"]:$object->country_code;
+		$selectedcode = $_POST["account_country_id"] ? $_POST["account_country_id"] : $object->country_code;
 	}
-	elseif (empty($selectedcode)) $selectedcode=$mysoc->country_code;
-	$object->country_code = getCountry($selectedcode, 2);	// Force country code on account to have following field on bank fields matching country rules
+	elseif (empty($selectedcode)) $selectedcode = $mysoc->country_code;
+	$object->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules
 
 	print '<tr><td class="fieldrequired">'.$langs->trans("BankAccountCountry").'</td>';
 	print '<td>';
@@ -397,7 +397,7 @@ if ($action == 'create')
 	print '<tr><td>'.$langs->trans('State').'</td><td>';
 	if ($selectedcode)
 	{
-		$formcompany->select_departement(isset($_POST["account_state_id"])?$_POST["account_state_id"]:'', $selectedcode, 'account_state_id');
+		$formcompany->select_departement(isset($_POST["account_state_id"]) ? $_POST["account_state_id"] : '', $selectedcode, 'account_state_id');
 	}
 	else
 	{
@@ -433,13 +433,13 @@ if ($action == 'create')
 	print '<td>';
 	// Editor wysiwyg
 	require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-	$doleditor=new DolEditor('account_comment', (GETPOST("account_comment")?GETPOST("account_comment"):$object->comment), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_4, '90%');
+	$doleditor = new DolEditor('account_comment', (GETPOST("account_comment") ?GETPOST("account_comment") : $object->comment), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_4, '90%');
 	$doleditor->Create();
 	print '</td></tr>';
 
 	// Other attributes
-	$parameters=array();
-	$reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+	$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))
 	{
@@ -454,7 +454,7 @@ if ($action == 'create')
 
 	// Sold
 	print '<tr><td class="titlefieldcreate">'.$langs->trans("InitialBankBalance").'</td>';
-	print '<td><input size="12" type="text" class="flat" name="solde" value="'.(GETPOST("solde")?GETPOST("solde"):price2num($object->solde)).'"></td></tr>';
+	print '<td><input size="12" type="text" class="flat" name="solde" value="'.(GETPOST("solde") ?GETPOST("solde") : price2num($object->solde)).'"></td></tr>';
 
 	print '<tr><td>'.$langs->trans("Date").'</td>';
 	print '<td>';
@@ -462,10 +462,10 @@ if ($action == 'create')
 	print '</td></tr>';
 
 	print '<tr><td>'.$langs->trans("BalanceMinimalAllowed").'</td>';
-	print '<td><input size="12" type="text" class="flat" name="account_min_allowed" value="'.(GETPOST("account_min_allowed")?GETPOST("account_min_allowed"):$object->min_allowed).'"></td></tr>';
+	print '<td><input size="12" type="text" class="flat" name="account_min_allowed" value="'.(GETPOST("account_min_allowed") ?GETPOST("account_min_allowed") : $object->min_allowed).'"></td></tr>';
 
 	print '<tr><td>'.$langs->trans("BalanceMinimalDesired").'</td>';
-	print '<td><input size="12" type="text" class="flat" name="account_min_desired" value="'.(GETPOST("account_min_desired")?GETPOST("account_min_desired"):$object->min_desired).'"></td></tr>';
+	print '<td><input size="12" type="text" class="flat" name="account_min_desired" value="'.(GETPOST("account_min_desired") ?GETPOST("account_min_desired") : $object->min_desired).'"></td></tr>';
 
 	print '</table>';
 	print '<br>';
@@ -476,7 +476,7 @@ if ($action == 'create')
 
 		// If bank account
 		print '<tr><td class="titlefieldcreate">'.$langs->trans("BankName").'</td>';
-		print '<td><input size="30" type="text" class="flat" name="bank" value="'.(GETPOST('bank')?GETPOST('bank', 'alpha'):$object->bank).'"></td>';
+		print '<td><input size="30" type="text" class="flat" name="bank" value="'.(GETPOST('bank') ?GETPOST('bank', 'alpha') : $object->bank).'"></td>';
 		print '</tr>';
 
 		// Show fields of bank account
@@ -500,32 +500,32 @@ if ($action == 'create')
 			}
 
 			print '<td>'.$langs->trans($val).'</td>';
-			print '<td><input size="'.$size.'" type="text" class="flat" name="'.$name.'" value="'.(GETPOST($name)?GETPOST($name, 'alpha'):$content).'"></td>';
+			print '<td><input size="'.$size.'" type="text" class="flat" name="'.$name.'" value="'.(GETPOST($name) ?GETPOST($name, 'alpha') : $content).'"></td>';
 			print '</tr>';
 		}
 		$ibankey = FormBank::getIBANLabel($object);
-		$bickey="BICNumber";
-		if ($object->getCountryCode() == 'IN') $bickey="SWIFT";
+		$bickey = "BICNumber";
+		if ($object->getCountryCode() == 'IN') $bickey = "SWIFT";
 
 		// IBAN
 		print '<tr><td>'.$langs->trans($ibankey).'</td>';
-		print '<td><input size="34" maxlength="34" type="text" class="flat" name="iban" value="'.(GETPOST('iban')?GETPOST('iban', 'alpha'):$object->iban).'"></td></tr>';
+		print '<td><input size="34" maxlength="34" type="text" class="flat" name="iban" value="'.(GETPOST('iban') ?GETPOST('iban', 'alpha') : $object->iban).'"></td></tr>';
 
 		print '<tr><td>'.$langs->trans($bickey).'</td>';
-		print '<td><input size="11" maxlength="11" type="text" class="flat" name="bic" value="'.(GETPOST('bic')?GETPOST('bic', 'alpha'):$object->bic).'"></td></tr>';
+		print '<td><input size="11" maxlength="11" type="text" class="flat" name="bic" value="'.(GETPOST('bic') ?GETPOST('bic', 'alpha') : $object->bic).'"></td></tr>';
 
 		print '<tr><td>'.$langs->trans("BankAccountDomiciliation").'</td><td>';
 		print "<textarea class=\"flat\" name=\"domiciliation\" rows=\"2\" cols=\"40\">";
-		print (GETPOST('domiciliation')?GETPOST('domiciliation'):$object->domiciliation);
+		print (GETPOST('domiciliation') ?GETPOST('domiciliation') : $object->domiciliation);
 		print "</textarea></td></tr>";
 
 		print '<tr><td>'.$langs->trans("BankAccountOwner").'</td>';
-		print '<td><input size="30" type="text" class="flat" name="proprio" value="'.(GETPOST('proprio')?GETPOST('proprio', 'alpha'):$object->proprio).'">';
+		print '<td><input size="30" type="text" class="flat" name="proprio" value="'.(GETPOST('proprio') ?GETPOST('proprio', 'alpha') : $object->proprio).'">';
 		print '</td></tr>';
 
 		print '<tr><td class="tdtop">'.$langs->trans("BankAccountOwnerAddress").'</td><td>';
 		print "<textarea class=\"flat\" name=\"owner_address\" rows=\"2\" cols=\"40\">";
-		print (GETPOST('owner_address')?GETPOST('owner_address', 'alpha'):$object->owner_address);
+		print (GETPOST('owner_address') ?GETPOST('owner_address', 'alpha') : $object->owner_address);
 		print "</textarea></td></tr>";
 
 		print '</table>';
@@ -534,10 +534,10 @@ if ($action == 'create')
 
 	print '<table class="border centpercent">';
 	// Accountancy code
-	$fieldrequired='';
-	if (! empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) $fieldrequired='fieldrequired ';
+	$fieldrequired = '';
+	if (!empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) $fieldrequired = 'fieldrequired ';
 
-	if (! empty($conf->accounting->enabled))
+	if (!empty($conf->accounting->enabled))
 	{
 		print '<tr><td class="'.$fieldrequired.'titlefieldcreate">'.$langs->trans("AccountancyCode").'</td>';
 		print '<td>';
@@ -547,11 +547,11 @@ if ($action == 'create')
 	else
 	{
 		print '<tr><td class="'.$fieldrequired.'titlefieldcreate">'.$langs->trans("AccountancyCode").'</td>';
-		print '<td><input type="text" name="account_number" value="'.(GETPOST("account_number")?GETPOST('account_number', 'alpha'):$object->account_number).'"></td></tr>';
+		print '<td><input type="text" name="account_number" value="'.(GETPOST("account_number") ?GETPOST('account_number', 'alpha') : $object->account_number).'"></td></tr>';
 	}
 
 	// Accountancy journal
-	if (! empty($conf->accounting->enabled))
+	if (!empty($conf->accounting->enabled))
 	{
 		print '<tr><td>'.$langs->trans("AccountancyJournal").'</td>';
 		print '<td>';
@@ -564,9 +564,9 @@ if ($action == 'create')
 	dol_fiche_end();
 
 	print '<div class="center">';
-	print '<input type="submit" class="button" value="' . $langs->trans("CreateAccount") . '">';
+	print '<input type="submit" class="button" value="'.$langs->trans("CreateAccount").'">';
 	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-	print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
+	print '<input type="button" class="button" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
 	print '</div>';
 
 	print '</form>';
@@ -588,11 +588,11 @@ else
 		if ($_GET["ref"])
 		{
 			$object->fetch(0, $_GET["ref"]);
-			$_GET["id"]=$object->id;
+			$_GET["id"] = $object->id;
 		}
 
 		// Show tabs
-		$head=bank_prepare_head($object);
+		$head = bank_prepare_head($object);
 		dol_fiche_head($head, 'bankname', $langs->trans("FinancialAccount"), -1, 'account');
 
 		$formconfirm = '';
@@ -608,7 +608,7 @@ else
 
 		$linkback = '<a href="'.DOL_URL_ROOT.'/compta/bank/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-		$morehtmlref='';
+		$morehtmlref = '';
 		dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
 
 
@@ -648,7 +648,7 @@ else
 		// Accountancy code
 		print '<tr class="liste_titre_add"><td class="titlefield">'.$langs->trans("AccountancyCode").'</td>';
 		print '<td>';
-		if (! empty($conf->accounting->enabled)) {
+		if (!empty($conf->accounting->enabled)) {
 			$accountingaccount = new AccountingAccount($db);
 			$accountingaccount->fetch('', $object->account_number, 1);
 
@@ -659,7 +659,7 @@ else
 		print '</td></tr>';
 
 		// Accountancy journal
-		if (! empty($conf->accounting->enabled))
+		if (!empty($conf->accounting->enabled))
 		{
 			print '<tr><td>'.$langs->trans("AccountancyJournal").'</td>';
 			print '<td>';
@@ -675,7 +675,7 @@ else
 
 		// Other attributes
 		$cols = 2;
-		include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
 		print '</table>';
 
@@ -725,13 +725,13 @@ else
 			}
 
 			$ibankey = FormBank::getIBANLabel($object);
-			$bickey="BICNumber";
-			if ($object->getCountryCode() == 'IN') $bickey="SWIFT";
+			$bickey = "BICNumber";
+			if ($object->getCountryCode() == 'IN') $bickey = "SWIFT";
 
 			print '<tr><td>'.$langs->trans($ibankey).'</td>';
 			print '<td>'.$object->iban.'&nbsp;';
-			if (! empty($object->iban)) {
-				if (! checkIbanForAccount($object)) {
+			if (!empty($object->iban)) {
+				if (!checkIbanForAccount($object)) {
 					print img_picto($langs->trans("IbanNotValid"), 'warning');
 				} else {
 					print img_picto($langs->trans("IbanValid"), 'info');
@@ -741,8 +741,8 @@ else
 
 			print '<tr><td>'.$langs->trans($bickey).'</td>';
 			print '<td>'.$object->bic.'&nbsp;';
-			if (! empty($object->bic)) {
-				if (! checkSwiftForAccount($object)) {
+			if (!empty($object->bic)) {
+				if (!checkSwiftForAccount($object)) {
 					print img_picto($langs->trans("SwiftNotValid"), 'warning');
 				} else {
 					print img_picto($langs->trans("SwiftValid"), 'info');
@@ -783,7 +783,7 @@ else
 			print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$object->id.'">'.$langs->trans("Modify").'</a>';
 		}
 
-		$canbedeleted=$object->can_be_deleted();   // Renvoi vrai si compte sans mouvements
+		$canbedeleted = $object->can_be_deleted(); // Renvoi vrai si compte sans mouvements
 		if ($user->rights->banque->configurer && $canbedeleted)
 		{
 			print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&id='.$object->id.'">'.$langs->trans("Delete").'</a>';
@@ -837,16 +837,16 @@ else
 
 		// Ref
 		print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans("Ref").'</td>';
-		print '<td><input type="text" class="flat maxwidth200" name="ref" value="'.dol_escape_htmltag(isset($_POST["ref"])?GETPOST("ref"):$object->ref).'"></td></tr>';
+		print '<td><input type="text" class="flat maxwidth200" name="ref" value="'.dol_escape_htmltag(isset($_POST["ref"]) ?GETPOST("ref") : $object->ref).'"></td></tr>';
 
 		// Label
 		print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td>';
-		print '<td><input type="text" class="flat minwidth300" name="label" value="'.dol_escape_htmltag(isset($_POST["label"])?GETPOST("label"):$object->label).'"></td></tr>';
+		print '<td><input type="text" class="flat minwidth300" name="label" value="'.dol_escape_htmltag(isset($_POST["label"]) ?GETPOST("label") : $object->label).'"></td></tr>';
 
 		// Type
 		print '<tr><td class="fieldrequired">'.$langs->trans("AccountType").'</td>';
 		print '<td class="maxwidth200onsmartphone">';
-		$formbank->selectTypeOfBankAccount((isset($_POST["type"])?$_POST["type"]:$object->type), "type");
+		$formbank->selectTypeOfBankAccount((isset($_POST["type"]) ? $_POST["type"] : $object->type), "type");
 		print '</td></tr>';
 
 		// Currency
@@ -854,9 +854,9 @@ else
 		print '<input type="hidden" value="'.$object->currency_code.'">';
 		print '</td>';
 		print '<td class="maxwidth200onsmartphone">';
-		$selectedcode=$object->currency_code;
-		if (! $selectedcode) $selectedcode=$conf->currency;
-		print $form->selectCurrency((isset($_POST["account_currency_code"])?$_POST["account_currency_code"]:$selectedcode), 'account_currency_code');
+		$selectedcode = $object->currency_code;
+		if (!$selectedcode) $selectedcode = $conf->currency;
+		print $form->selectCurrency((isset($_POST["account_currency_code"]) ? $_POST["account_currency_code"] : $selectedcode), 'account_currency_code');
 		//print $langs->trans("Currency".$conf->currency);
 		//print '<input type="hidden" name="account_currency_code" value="'.$conf->currency.'">';
 		print '</td></tr>';
@@ -864,15 +864,15 @@ else
 		// Status
 		print '<tr><td class="fieldrequired">'.$langs->trans("Status").'</td>';
 		print '<td class="maxwidth200onsmartphone">';
-		print $form->selectarray("clos", $object->status, (isset($_POST["clos"])?$_POST["clos"]:$object->clos));
+		print $form->selectarray("clos", $object->status, (isset($_POST["clos"]) ? $_POST["clos"] : $object->clos));
 		print '</td></tr>';
 
 		// Country
-		$object->country_id=$object->country_id?$object->country_id:$mysoc->country_id;
-		$selectedcode=$object->country_code;
-		if (isset($_POST["account_country_id"])) $selectedcode=$_POST["account_country_id"];
-		elseif (empty($selectedcode)) $selectedcode=$mysoc->country_code;
-		$object->country_code = getCountry($selectedcode, 2);	// Force country code on account to have following field on bank fields matching country rules
+		$object->country_id = $object->country_id ? $object->country_id : $mysoc->country_id;
+		$selectedcode = $object->country_code;
+		if (isset($_POST["account_country_id"])) $selectedcode = $_POST["account_country_id"];
+		elseif (empty($selectedcode)) $selectedcode = $mysoc->country_code;
+		$object->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules
 
 		print '<tr><td class="fieldrequired">'.$langs->trans("Country").'</td>';
 		print '<td class="maxwidth200onsmartphone">';
@@ -884,7 +884,7 @@ else
 		print '<tr><td>'.$langs->trans('State').'</td><td class="maxwidth200onsmartphone">';
 		if ($selectedcode)
 		{
-			print $formcompany->select_state(isset($_POST["account_state_id"])?$_POST["account_state_id"]:$object->state_id, $selectedcode, 'account_state_id');
+			print $formcompany->select_state(isset($_POST["account_state_id"]) ? $_POST["account_state_id"] : $object->state_id, $selectedcode, 'account_state_id');
 		}
 		else
 		{
@@ -895,22 +895,22 @@ else
 		// Conciliable
 		print '<tr><td>'.$langs->trans("Conciliable").'</td>';
 		print '<td>';
-		$conciliate=$object->canBeConciliated();
+		$conciliate = $object->canBeConciliated();
 		if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')';
 		elseif ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')';
-		else print '<input type="checkbox" class="flat" name="norappro"'.(($conciliate > 0)?'':' checked="checked"').'"> '.$langs->trans("DisableConciliation");
+		else print '<input type="checkbox" class="flat" name="norappro"'.(($conciliate > 0) ? '' : ' checked="checked"').'"> '.$langs->trans("DisableConciliation");
 		print '</td></tr>';
 
 		// Balance
 		print '<tr><td>'.$langs->trans("BalanceMinimalAllowed").'</td>';
-		print '<td><input size="12" type="text" class="flat" name="account_min_allowed" value="'.(isset($_POST["account_min_allowed"])?GETPOST("account_min_allowed"):$object->min_allowed).'"></td></tr>';
+		print '<td><input size="12" type="text" class="flat" name="account_min_allowed" value="'.(isset($_POST["account_min_allowed"]) ?GETPOST("account_min_allowed") : $object->min_allowed).'"></td></tr>';
 
 		print '<tr><td>'.$langs->trans("BalanceMinimalDesired").'</td>';
-		print '<td ><input size="12" type="text" class="flat" name="account_min_desired" value="'.(isset($_POST["account_min_desired"])?GETPOST("account_min_desired"):$object->min_desired).'"></td></tr>';
+		print '<td ><input size="12" type="text" class="flat" name="account_min_desired" value="'.(isset($_POST["account_min_desired"]) ?GETPOST("account_min_desired") : $object->min_desired).'"></td></tr>';
 
 		// Web
 		print '<tr><td>'.$langs->trans("Web").'</td>';
-		print '<td><input class="maxwidth200onsmartphone" type="text" class="flat" name="url" value="'.(isset($_POST["url"])?GETPOST("url"):$object->url).'">';
+		print '<td><input class="maxwidth200onsmartphone" type="text" class="flat" name="url" value="'.(isset($_POST["url"]) ?GETPOST("url") : $object->url).'">';
 		print '</td></tr>';
 
 		// Tags-Categories
@@ -935,13 +935,13 @@ else
 		print '<td>';
 		// Editor wysiwyg
 		require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-		$doleditor=new DolEditor('account_comment', (GETPOST("account_comment")?GETPOST("account_comment"):$object->comment), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_4, '95%');
+		$doleditor = new DolEditor('account_comment', (GETPOST("account_comment") ?GETPOST("account_comment") : $object->comment), '', 90, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_4, '95%');
 		$doleditor->Create();
 		print '</td></tr>';
 
 		// Other attributes
-		$parameters=array();
-		$reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+		$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))
 		{
@@ -973,7 +973,7 @@ else
 		print '</td></tr>';
 
 		// Accountancy journal
-		if (! empty($conf->accounting->enabled))
+		if (!empty($conf->accounting->enabled))
 		{
 			print '<tr><td class="fieldrequired">'.$langs->trans("AccountancyJournal").'</td>';
 			print '<td>';
@@ -1022,8 +1022,8 @@ else
 			}
 
 			$ibankey = FormBank::getIBANLabel($object);
-			$bickey="BICNumber";
-			if ($object->getCountryCode() == 'IN') $bickey="SWIFT";
+			$bickey = "BICNumber";
+			if ($object->getCountryCode() == 'IN') $bickey = "SWIFT";
 
 			// IBAN
 			print '<tr><td>'.$langs->trans($ibankey).'</td>';

+ 89 - 89
htdocs/compta/bank/list.php

@@ -64,8 +64,8 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (! $sortfield) $sortfield='b.label';
-if (! $sortorder) $sortorder='ASC';
+if (!$sortfield) $sortfield = 'b.label';
+if (!$sortorder) $sortorder = 'ASC';
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 $object = new Account($db);
@@ -82,14 +82,14 @@ $fieldstosearchall = array(
     'b.label'=>'Label',
 );
 
-$checkedtypetiers=0;
-$arrayfields=array(
+$checkedtypetiers = 0;
+$arrayfields = array(
     'b.ref'=>array('label'=>$langs->trans("BankAccounts"), 'checked'=>1),
     'accountype'=>array('label'=>$langs->trans("Type"), 'checked'=>1),
     'b.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1),
     'b.number'=>array('label'=>$langs->trans("AccountIdShort"), 'checked'=>1),
-    'b.account_number'=>array('label'=>$langs->trans("AccountAccounting"), 'checked'=>(! empty($conf->accounting->enabled) || ! empty($conf->accounting->enabled))),
-    'b.fk_accountancy_journal'=>array('label'=>$langs->trans("AccountancyJournal"), 'checked'=>(! empty($conf->accounting->enabled) || ! empty($conf->accounting->enabled))),
+    'b.account_number'=>array('label'=>$langs->trans("AccountAccounting"), 'checked'=>(!empty($conf->accounting->enabled) || !empty($conf->accounting->enabled))),
+    'b.fk_accountancy_journal'=>array('label'=>$langs->trans("AccountancyJournal"), 'checked'=>(!empty($conf->accounting->enabled) || !empty($conf->accounting->enabled))),
     'toreconcile'=>array('label'=>$langs->trans("TransactionsToConciliate"), 'checked'=>1),
     'b.currency_code'=>array('label'=>$langs->trans("Currency"), 'checked'=>0),
 	'b.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500),
@@ -114,11 +114,11 @@ $arrayfields = dol_sort_array($arrayfields, 'position');
  * 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
+$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');
 
 include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
@@ -126,10 +126,10 @@ 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
 {
-    $search_ref='';
-    $search_label='';
-    $search_number='';
-    $search_status='';
+    $search_ref = '';
+    $search_label = '';
+    $search_number = '';
+    $search_status = '';
 }
 
 
@@ -179,7 +179,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
     $nbtotalofrecords = $db->num_rows($result);
 }
 
-$sql.= $db->plimit($limit + 1, $offset);
+$sql .= $db->plimit($limit + 1, $offset);
 
 $resql = $db->query($sql);
 if ($resql)
@@ -198,41 +198,41 @@ else dol_print_error($db);
 
 
 
-$help_url='EN:Module_Banks_and_Cash|FR:Module_Banques_et_Caisses|ES:M&oacute;dulo_Bancos_y_Cajas';
+$help_url = 'EN:Module_Banks_and_Cash|FR:Module_Banques_et_Caisses|ES:M&oacute;dulo_Bancos_y_Cajas';
 llxHeader('', $title, $help_url);
 
-$link='';
+$link = '';
 
 
 $num_rows = count($accounts);
 
-$arrayofselected=is_array($toselect)?$toselect:array();
-
-$param='';
-if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
-if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
-if ($search_ref != '')      $param.='&search_ref='.$search_ref;
-if ($search_label != '')    $param.='&search_label='.$search_label;
-if ($search_number != '')   $param.='&search_number='.$search_number;
-if ($search_status != '')   $param.='&search_status='.$search_status;
-if ($show_files)            $param.='&show_files=' .$show_files;
-if ($optioncss != '')       $param.='&optioncss='.$optioncss;
+$arrayofselected = is_array($toselect) ? $toselect : array();
+
+$param = '';
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
+if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
+if ($search_ref != '')      $param .= '&search_ref='.$search_ref;
+if ($search_label != '')    $param .= '&search_label='.$search_label;
+if ($search_number != '')   $param .= '&search_number='.$search_number;
+if ($search_status != '')   $param .= '&search_status='.$search_status;
+if ($show_files)            $param .= '&show_files='.$show_files;
+if ($optioncss != '')       $param .= '&optioncss='.$optioncss;
 // Add $param from extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 
 // List of mass actions available
-$arrayofmassactions =  array(
+$arrayofmassactions = array(
 //    'presend'=>$langs->trans("SendByMail"),
 //    'builddoc'=>$langs->trans("PDFMerge"),
 );
-if ($user->rights->banque->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
-if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
-$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
+if ($user->rights->banque->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
+if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
+$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
 
-$newcardbutton='';
+$newcardbutton = '';
 if ($user->rights->banque->configurer)
 {
-    $newcardbutton.= dolGetButtonTitle($langs->trans('NewFinancialAccount'), '', 'fa fa-plus-circle', 'card.php?action=create');
+    $newcardbutton .= dolGetButtonTitle($langs->trans('NewFinancialAccount'), '', 'fa fa-plus-circle', 'card.php?action=create');
 }
 
 
@@ -249,89 +249,89 @@ print '<input type="hidden" name="viewstatut" value="'.$viewstatut.'">';
 
 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'bank', 0, $newcardbutton, '', $limit, 1);
 
-$topicmail="Information";
+$topicmail = "Information";
 //$modelmail="subscription";
-$objecttmp=new Account($db);
+$objecttmp = new Account($db);
 //$trackid='sub'.$object->id;
 include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
 
 if ($sall)
 {
-    foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
-    print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'</div>';
+    foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
+    print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
 }
 
-$moreforfilter='';
+$moreforfilter = '';
 
 
 // Bank accounts
-$parameters=array();
-$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters);    // Note that $action and $object may have been modified by hook
+$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($moreforfilter))
+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
+$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
+$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
 
 print '<div class="div-table-responsive">';
-print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
+print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
 
 print '<tr class="liste_titre_filter">';
 
 // Ref
-if (! empty($arrayfields['b.ref']['checked']))
+if (!empty($arrayfields['b.ref']['checked']))
 {
     print '<td class="liste_titre">';
     print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">';
     print '</td>';
 }
 // Label
-if (! empty($arrayfields['b.label']['checked']))
+if (!empty($arrayfields['b.label']['checked']))
 {
     print '<td class="liste_titre">';
     print '<input class="flat" size="6" type="text" name="search_label" value="'.$search_label.'">';
     print '</td>';
 }
 // Account type
-if (! empty($arrayfields['accountype']['checked']))
+if (!empty($arrayfields['accountype']['checked']))
 {
     print '<td class="liste_titre">';
     print '</td>';
 }
 // Bank number
-if (! empty($arrayfields['b.number']['checked']))
+if (!empty($arrayfields['b.number']['checked']))
 {
     print '<td class="liste_titre">';
     print '<input class="flat" size="6" type="text" name="search_number" value="'.$search_number.'">';
     print '</td>';
 }
 // Account number
-if (! empty($arrayfields['b.account_number']['checked']))
+if (!empty($arrayfields['b.account_number']['checked']))
 {
     print '<td class="liste_titre">';
     print '</td>';
 }
 // Accountancy journal
-if (! empty($arrayfields['b.fk_accountancy_journal']['checked']))
+if (!empty($arrayfields['b.fk_accountancy_journal']['checked']))
 {
     print '<td class="liste_titre">';
     print '</td>';
 }
 // Transactions to reconcile
-if (! empty($arrayfields['toreconcile']['checked']))
+if (!empty($arrayfields['toreconcile']['checked']))
 {
     print '<td class="liste_titre">';
     print '</td>';
 }
 // Currency
-if (! empty($arrayfields['b.currency_code']['checked']))
+if (!empty($arrayfields['b.currency_code']['checked']))
 {
     print '<td class="liste_titre">';
     print '</td>';
@@ -340,26 +340,26 @@ if (! empty($arrayfields['b.currency_code']['checked']))
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
 
 // Fields from hook
-$parameters=array('arrayfields'=>$arrayfields);
-$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters);    // Note that $action and $object may have been modified by hook
+$parameters = array('arrayfields'=>$arrayfields);
+$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
 print $hookmanager->resPrint;
 // Date creation
-if (! empty($arrayfields['b.datec']['checked']))
+if (!empty($arrayfields['b.datec']['checked']))
 {
     print '<td class="liste_titre">';
     print '</td>';
 }
 // Date modification
-if (! empty($arrayfields['b.tms']['checked']))
+if (!empty($arrayfields['b.tms']['checked']))
 {
     print '<td class="liste_titre">';
     print '</td>';
 }
 // Status
-if (! empty($arrayfields['b.clos']['checked']))
+if (!empty($arrayfields['b.clos']['checked']))
 {
     print '<td class="liste_titre center">';
-    $array=array(
+    $array = array(
         'opened'=>$langs->trans("Opened"),
         'closed'=>$langs->trans("Closed")
     );
@@ -367,42 +367,42 @@ if (! empty($arrayfields['b.clos']['checked']))
     print '</td>';
 }
 // Balance
-if (! empty($arrayfields['balance']['checked']))
+if (!empty($arrayfields['balance']['checked']))
 {
     print '<td class="liste_titre"></td>';
 }
 // Action column
 print '<td class="liste_titre valignmiddle">';
-$searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1);
+$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
 print $searchpicto;
 print '</td>';
 print '</tr>';
 
 // Fields title
 print '<tr class="liste_titre">';
-if (! empty($arrayfields['b.ref']['checked']))            print_liste_field_titre($arrayfields['b.ref']['label'], $_SERVER["PHP_SELF"], 'b.ref', '', $param, '', $sortfield, $sortorder);
-if (! empty($arrayfields['b.label']['checked']))          print_liste_field_titre($arrayfields['b.label']['label'], $_SERVER["PHP_SELF"], 'b.label', '', $param, '', $sortfield, $sortorder);
-if (! empty($arrayfields['accountype']['checked']))       print_liste_field_titre($arrayfields['accountype']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
-if (! empty($arrayfields['b.number']['checked']))         print_liste_field_titre($arrayfields['b.number']['label'], $_SERVER["PHP_SELF"], 'b.number', '', $param, '', $sortfield, $sortorder);
-if (! empty($arrayfields['b.account_number']['checked'])) print_liste_field_titre($arrayfields['b.account_number']['label'], $_SERVER["PHP_SELF"], 'b.account_number', '', $param, '', $sortfield, $sortorder);
-if (! empty($arrayfields['b.fk_accountancy_journal']['checked'])) print_liste_field_titre($arrayfields['b.fk_accountancy_journal']['label'], $_SERVER["PHP_SELF"], 'b.fk_accountancy_journal', '', $param, '', $sortfield, $sortorder);
-if (! empty($arrayfields['b.currency_code']['checked']))  print_liste_field_titre($arrayfields['b.currency_code']['label'], $_SERVER["PHP_SELF"], 'b.currency_code', '', $param, '', $sortfield, $sortorder, 'center ');
-if (! empty($arrayfields['toreconcile']['checked']))      print_liste_field_titre($arrayfields['toreconcile']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['b.ref']['checked']))            print_liste_field_titre($arrayfields['b.ref']['label'], $_SERVER["PHP_SELF"], 'b.ref', '', $param, '', $sortfield, $sortorder);
+if (!empty($arrayfields['b.label']['checked']))          print_liste_field_titre($arrayfields['b.label']['label'], $_SERVER["PHP_SELF"], 'b.label', '', $param, '', $sortfield, $sortorder);
+if (!empty($arrayfields['accountype']['checked']))       print_liste_field_titre($arrayfields['accountype']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
+if (!empty($arrayfields['b.number']['checked']))         print_liste_field_titre($arrayfields['b.number']['label'], $_SERVER["PHP_SELF"], 'b.number', '', $param, '', $sortfield, $sortorder);
+if (!empty($arrayfields['b.account_number']['checked'])) print_liste_field_titre($arrayfields['b.account_number']['label'], $_SERVER["PHP_SELF"], 'b.account_number', '', $param, '', $sortfield, $sortorder);
+if (!empty($arrayfields['b.fk_accountancy_journal']['checked'])) print_liste_field_titre($arrayfields['b.fk_accountancy_journal']['label'], $_SERVER["PHP_SELF"], 'b.fk_accountancy_journal', '', $param, '', $sortfield, $sortorder);
+if (!empty($arrayfields['b.currency_code']['checked']))  print_liste_field_titre($arrayfields['b.currency_code']['label'], $_SERVER["PHP_SELF"], 'b.currency_code', '', $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['toreconcile']['checked']))      print_liste_field_titre($arrayfields['toreconcile']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'center ');
 // 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);    // Note that $action and $object may have been modified by hook
+$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['b.datec']['checked']))          print_liste_field_titre($arrayfields['b.datec']['label'], $_SERVER["PHP_SELF"], "b.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['b.tms']['checked']))            print_liste_field_titre($arrayfields['b.tms']['label'], $_SERVER["PHP_SELF"], "b.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['b.clos']['checked']))           print_liste_field_titre($arrayfields['b.clos']['label'], $_SERVER["PHP_SELF"], 'b.clos', '', $param, '', $sortfield, $sortorder, 'center ');
-if (! empty($arrayfields['balance']['checked']))          print_liste_field_titre($arrayfields['balance']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right ');
+if (!empty($arrayfields['b.datec']['checked']))          print_liste_field_titre($arrayfields['b.datec']['label'], $_SERVER["PHP_SELF"], "b.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['b.tms']['checked']))            print_liste_field_titre($arrayfields['b.tms']['label'], $_SERVER["PHP_SELF"], "b.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['b.clos']['checked']))           print_liste_field_titre($arrayfields['b.clos']['label'], $_SERVER["PHP_SELF"], 'b.clos', '', $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['balance']['checked']))          print_liste_field_titre($arrayfields['balance']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right ');
 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
 print "</tr>\n";
 
 
-$total = array(); $found = 0; $i=0; $lastcurrencycode='';
+$total = array(); $found = 0; $i = 0; $lastcurrencycode = '';
 
 foreach ($accounts as $key=>$type)
 {
@@ -488,26 +488,26 @@ foreach ($accounts as $key=>$type)
     		print '';
     	}
     	print '</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
     }
 
     // Currency
-    if (! empty($arrayfields['b.currency_code']['checked']))
+    if (!empty($arrayfields['b.currency_code']['checked']))
     {
     	print '<td class="center">';
    		print $objecttmp->currency_code;
     	print '</td>';
-    	if (! $i) $totalarray['nbfield']++;
+    	if (!$i) $totalarray['nbfield']++;
     }
 
     // Transactions to reconcile
-    if (! empty($arrayfields['toreconcile']['checked']))
+    if (!empty($arrayfields['toreconcile']['checked']))
     {
         print '<td class="center">';
 		if ($objecttmp->rappro)
 		{
-			$result=$objecttmp->load_board($user, $objecttmp->id);
-            if ($result<0) {
+			$result = $objecttmp->load_board($user, $objecttmp->id);
+            if ($result < 0) {
                 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
             } else {
                 print '<span class="badge badge-info classfortooltip" title="'.dol_htmlentities($langs->trans("TransactionsToConciliate")).'">'.$result->nbtodo.'</span>';
@@ -571,12 +571,12 @@ foreach ($accounts as $key=>$type)
 	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($objecttmp->id, $arrayofselected)) $selected=1;
-	    print '<input id="cb'.$objecttmp->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$objecttmp->id.'"'.($selected?' checked="checked"':'').'>';
+	    $selected = 0;
+	    if (in_array($objecttmp->id, $arrayofselected)) $selected = 1;
+	    print '<input id="cb'.$objecttmp->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$objecttmp->id.'"'.($selected ? ' checked="checked"' : '').'>';
 	}
 	print '</td>';
-	if (! $i) $totalarray['nbfield']++;
+	if (!$i) $totalarray['nbfield']++;
 
 	print '</tr>';
 
@@ -586,10 +586,10 @@ foreach ($accounts as $key=>$type)
 }
 
 // If no record found
-if (! $found)
+if (!$found)
 {
-    $colspan=1;
-    foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; }
+    $colspan = 1;
+    foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; }
     print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
 }
 

+ 63 - 63
htdocs/compta/bank/various_payment/card.php

@@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
-if (! empty($conf->projet->enabled))
+if (!empty($conf->projet->enabled))
 {
 	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
@@ -85,39 +85,39 @@ if (empty($reshook))
 	{
 		if ($action != 'addlink')
 		{
-			$urltogo=$backtopage?$backtopage:dol_buildpath('/compta/bank/various_payment/list.php', 1);
+			$urltogo = $backtopage ? $backtopage : dol_buildpath('/compta/bank/various_payment/list.php', 1);
 			header("Location: ".$urltogo);
 			exit;
 		}
-		if ($id > 0 || ! empty($ref)) $ret = $object->fetch($id, $ref);
-		$action='';
+		if ($id > 0 || !empty($ref)) $ret = $object->fetch($id, $ref);
+		$action = '';
 	}
 
 	if ($action == 'add')
 	{
-		$error=0;
-
-		$datep=dol_mktime(12, 0, 0, GETPOST("datepmonth", 'int'), GETPOST("datepday", 'int'), GETPOST("datepyear", 'int'));
-		$datev=dol_mktime(12, 0, 0, GETPOST("datevmonth", 'int'), GETPOST("datevday", 'int'), GETPOST("datevyear", 'int'));
-		if (empty($datev)) $datev=$datep;
-
-		$object->ref='';	// TODO
-		$object->accountid=GETPOST("accountid", 'int') > 0 ? GETPOST("accountid", "int") : 0;
-		$object->datev=$datev;
-		$object->datep=$datep;
-		$object->amount=price2num(GETPOST("amount", 'alpha'));
-		$object->label=GETPOST("label", 'none');
-		$object->note=GETPOST("note", 'none');
-		$object->type_payment=GETPOST("paymenttype", 'int') > 0 ? GETPOST("paymenttype", "int") : 0;
-		$object->num_payment=GETPOST("num_payment", 'alpha');
-		$object->fk_user_author=$user->id;
-		$object->category_transaction=GETPOST("category_transaction", 'alpha');
-
-		$object->accountancy_code=GETPOST("accountancy_code") > 0 ? GETPOST("accountancy_code", "alpha") : "";
-        $object->subledger_account=GETPOST("subledger_account") > 0 ? GETPOST("subledger_account", "alpha") : "";
-
-		$object->sens=GETPOST('sens');
-		$object->fk_project= GETPOST('fk_project', 'int');
+		$error = 0;
+
+		$datep = dol_mktime(12, 0, 0, GETPOST("datepmonth", 'int'), GETPOST("datepday", 'int'), GETPOST("datepyear", 'int'));
+		$datev = dol_mktime(12, 0, 0, GETPOST("datevmonth", 'int'), GETPOST("datevday", 'int'), GETPOST("datevyear", 'int'));
+		if (empty($datev)) $datev = $datep;
+
+		$object->ref = ''; // TODO
+		$object->accountid = GETPOST("accountid", 'int') > 0 ? GETPOST("accountid", "int") : 0;
+		$object->datev = $datev;
+		$object->datep = $datep;
+		$object->amount = price2num(GETPOST("amount", 'alpha'));
+		$object->label = GETPOST("label", 'none');
+		$object->note = GETPOST("note", 'none');
+		$object->type_payment = GETPOST("paymenttype", 'int') > 0 ? GETPOST("paymenttype", "int") : 0;
+		$object->num_payment = GETPOST("num_payment", 'alpha');
+		$object->fk_user_author = $user->id;
+		$object->category_transaction = GETPOST("category_transaction", 'alpha');
+
+		$object->accountancy_code = GETPOST("accountancy_code") > 0 ? GETPOST("accountancy_code", "alpha") : "";
+        $object->subledger_account = GETPOST("subledger_account") > 0 ? GETPOST("subledger_account", "alpha") : "";
+
+		$object->sens = GETPOST('sens');
+		$object->fk_project = GETPOST('fk_project', 'int');
 
 		if (empty($datep) || empty($datev))
 		{
@@ -137,29 +137,29 @@ if (empty($reshook))
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors');
 			$error++;
 		}
-		if (! empty($conf->banque->enabled) && ! $object->accountid > 0)
+		if (!empty($conf->banque->enabled) && !$object->accountid > 0)
 		{
 			$langs->load('errors');
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount")), null, 'errors');
 			$error++;
 		}
 		// TODO Remove this and allow instead to edit a various payment to enter accounting code
-		if (! empty($conf->accounting->enabled) && ! $object->accountancy_code)
+		if (!empty($conf->accounting->enabled) && !$object->accountancy_code)
 		{
 			$langs->load('errors');
 			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountAccounting")), null, 'errors');
 			$error++;
 		}
 
-		if (! $error)
+		if (!$error)
 		{
 			$db->begin();
 
-			$ret=$object->create($user);
+			$ret = $object->create($user);
 			if ($ret > 0)
 			{
 				$db->commit();
-				$urltogo=($backtopage ? $backtopage : DOL_URL_ROOT.'/compta/bank/various_payment/list.php');
+				$urltogo = ($backtopage ? $backtopage : DOL_URL_ROOT.'/compta/bank/various_payment/list.php');
 				header("Location: ".$urltogo);
 				exit;
 			}
@@ -167,29 +167,29 @@ if (empty($reshook))
 			{
 				$db->rollback();
 				setEventMessages($object->error, $object->errors, 'errors');
-				$action="create";
+				$action = "create";
 			}
 		}
 
-		$action='create';
+		$action = 'create';
 	}
 
 	if ($action == 'delete')
 	{
-		$result=$object->fetch($id);
+		$result = $object->fetch($id);
 
 		if ($object->rappro == 0)
 		{
 			$db->begin();
 
-			$ret=$object->delete($user);
+			$ret = $object->delete($user);
 			if ($ret > 0)
 			{
 				if ($object->fk_bank)
 				{
-					$accountline=new AccountLine($db);
-					$result=$accountline->fetch($object->fk_bank);
-					if ($result > 0) $result=$accountline->delete($user);	// $result may be 0 if not found (when bank entry was deleted manually and fk_bank point to nothing)
+					$accountline = new AccountLine($db);
+					$result = $accountline->fetch($object->fk_bank);
+					if ($result > 0) $result = $accountline->delete($user); // $result may be 0 if not found (when bank entry was deleted manually and fk_bank point to nothing)
 				}
 
 				if ($result >= 0)
@@ -200,7 +200,7 @@ if (empty($reshook))
 				}
 				else
 				{
-					$object->error=$accountline->error;
+					$object->error = $accountline->error;
 					$db->rollback();
 					setEventMessages($object->error, $object->errors, 'errors');
 				}
@@ -226,8 +226,8 @@ if (empty($reshook))
 llxHeader("", $langs->trans("VariousPayment"));
 
 $form = new Form($db);
-if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db);
-if (! empty($conf->projet->enabled)) $formproject = new FormProjets($db);
+if (!empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db);
+if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db);
 
 if ($id)
 {
@@ -271,25 +271,25 @@ if ($action == 'create')
 	// Date payment
 	print '<tr><td class="titlefieldcreate">';
 	print $form->editfieldkey('DatePayment', 'datep', '', $object, 0, 'string', '', 1).'</td><td>';
-	print $form->selectDate((empty($datep)?-1:$datep), "datep", '', '', '', 'add', 1, 1);
+	print $form->selectDate((empty($datep) ?-1 : $datep), "datep", '', '', '', 'add', 1, 1);
 	print '</td></tr>';
 
 	// Date value for bank
 	print '<tr><td>';
 	print $form->editfieldkey('DateValue', 'datev', '', $object, 0).'</td><td>';
-	print $form->selectDate((empty($datev)?-1:$datev), "datev", '', '', '', 'add', 1, 1);
+	print $form->selectDate((empty($datev) ?-1 : $datev), "datev", '', '', '', 'add', 1, 1);
 	print '</td></tr>';
 
 	// Label
 	print '<tr><td>';
 	print $form->editfieldkey('Label', 'label', '', $object, 0, 'string', '', 1).'</td><td>';
-	print '<input name="label" id="label" class="minwidth300" value="'.($label?$label:$langs->trans("VariousPayment")).'">';
+	print '<input name="label" id="label" class="minwidth300" value="'.($label ? $label : $langs->trans("VariousPayment")).'">';
 	print '</td></tr>';
 
 	// Sens
 	print '<tr><td>';
 	print $form->editfieldkey('Sens', 'sens', '', $object, 0, 'string', '', 1).'</td><td>';
-    $sensarray=array( '0' => $langs->trans("Debit"), '1' => $langs->trans("Credit"));
+    $sensarray = array('0' => $langs->trans("Debit"), '1' => $langs->trans("Credit"));
     print $form->selectarray('sens', $sensarray, $sens);
 	print '</td></tr>';
 
@@ -300,11 +300,11 @@ if ($action == 'create')
 	print '</td></tr>';
 
 	// Bank
-	if (! empty($conf->banque->enabled))
+	if (!empty($conf->banque->enabled))
 	{
 		print '<tr><td>';
 		print $form->editfieldkey('BankAccount', 'selectaccountid', '', $object, 0, 'string', '', 1).'</td><td>';
-		$form->select_comptes($accountid, "accountid", 0, '', 1);  // Affiche liste des comptes courant
+		$form->select_comptes($accountid, "accountid", 0, '', 1); // Affiche liste des comptes courant
 		print '</td></tr>';
 	}
 
@@ -315,7 +315,7 @@ if ($action == 'create')
 	print '</td></tr>';
 
 	// Number
-	if (! empty($conf->banque->enabled))
+	if (!empty($conf->banque->enabled))
 	{
 		// Number
 		print '<tr><td><label for="num_payment">'.$langs->trans('Numero');
@@ -325,23 +325,23 @@ if ($action == 'create')
 	}
 
     // Project
-    if (! empty($conf->projet->enabled))
+    if (!empty($conf->projet->enabled))
     {
-        $formproject=new FormProjets($db);
+        $formproject = new FormProjets($db);
 
         // Associated project
         $langs->load("projects");
 
         print '<tr><td>'.$langs->trans("Project").'</td><td>';
 
-        $numproject=$formproject->select_projects(-1, $projectid, 'fk_project', 0, 0, 1, 1);
+        $numproject = $formproject->select_projects(-1, $projectid, 'fk_project', 0, 0, 1, 1);
 
         print '</td></tr>';
     }
 
     // Other attributes
-    $parameters=array();
-    $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+    $parameters = array();
+    $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
     print $hookmanager->resPrint;
 
     print '</td></tr>';
@@ -355,7 +355,7 @@ if ($action == 'create')
     }
 
 	// Accountancy account
-	if (! empty($conf->accounting->enabled))
+	if (!empty($conf->accounting->enabled))
 	{
 		// TODO Remove the fieldrequired and allow instead to edit a various payment to enter accounting code
 		print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("AccountAccounting").'</td>';
@@ -371,11 +371,11 @@ if ($action == 'create')
 	}
 
     // Subledger account
-    if (! empty($conf->accounting->enabled))
+    if (!empty($conf->accounting->enabled))
     {
         print '<tr><td>'.$langs->trans("SubledgerAccount").'</td>';
         print '<td>';
-        if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX))
+        if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX))
         {
             print $formaccounting->select_auxaccount($subledger_account, 'subledger_account', 1, '');
         }
@@ -484,7 +484,7 @@ if ($id)
 	print '<tr><td class="nowrap">';
 	print $langs->trans("AccountAccounting");
 	print '</td><td>';
-	if (! empty($conf->accounting->enabled))
+	if (!empty($conf->accounting->enabled))
 	{
 		$accountingaccount = new AccountingAccount($db);
 		$accountingaccount->fetch('', $object->accountancy_code, 1);
@@ -502,11 +502,11 @@ if ($id)
     print $object->subledger_account;
     print '</td></tr>';
 
-	if (! empty($conf->banque->enabled))
+	if (!empty($conf->banque->enabled))
 	{
 		if ($object->fk_account > 0)
 		{
-			$bankline=new AccountLine($db);
+			$bankline = new AccountLine($db);
 			$bankline->fetch($object->fk_bank);
 
 			print '<tr>';
@@ -519,8 +519,8 @@ if ($id)
 	}
 
 	// Other attributes
-	$parameters=array('socid'=>$object->id);
-	include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+	$parameters = array('socid'=>$object->id);
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
 	print '</table>';
 
@@ -542,7 +542,7 @@ if ($id)
 	// Delete
 	if (empty($object->rappro))
 	{
-		if (! empty($user->rights->banque->modifier))
+		if (!empty($user->rights->banque->modifier))
 		{
 			print '<div class="inline-block divButAction"><a class="butActionDelete" href="card.php?id='.$object->id.'&action=delete">'.$langs->trans("Delete").'</a></div>';
 		}

+ 10 - 10
htdocs/compta/bank/various_payment/document.php

@@ -50,22 +50,22 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $conf->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";
 
 
 $object = new PaymentVarious($db);
 $object->fetch($id, $ref);
 
 $upload_dir = $conf->bank->dir_output.'/'.dol_sanitizeFileName($object->id);
-$modulepart='banque';
+$modulepart = 'banque';
 
 
 /*
  * Actions
  */
 
-include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
+include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
 
 
 /*
@@ -125,11 +125,11 @@ if ($object->id)
 	print '<div class="underbanner clearboth"></div>';
 
 	// 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)
+	$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'];
+		$totalsize += $file['size'];
 	}
 
 	print '<table class="border tableforfield centpercent">';
@@ -146,8 +146,8 @@ if ($object->id)
 
 	$modulepart = 'banque';
 	$permission = $user->rights->banque->modifier;
-	$param = '&id=' . $object->id;
-	include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
+	$param = '&id='.$object->id;
+	include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
 }
 else
 {

+ 115 - 115
htdocs/compta/cashcontrol/cashcontrol_card.php

@@ -31,20 +31,20 @@ require '../../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/cashcontrol/class/cashcontrol.class.php';
 
-$langs->loadLangs(array("install","cashdesk","admin","banks"));
+$langs->loadLangs(array("install", "cashdesk", "admin", "banks"));
 
-$id=GETPOST('id', 'int');
+$id = GETPOST('id', 'int');
 $ref = GETPOST('ref', 'alpha');
-$action=GETPOST('action', 'aZ09');
+$action = GETPOST('action', 'aZ09');
 $categid = GETPOST('categid');
 $label = GETPOST("label");
 
-$now=dol_now();
-$syear = (GETPOSTISSET('closeyear')?GETPOST('closeyear', 'int'):dol_print_date($now, "%Y"));
-$smonth = (GETPOSTISSET('closemonth')?GETPOST('closemonth', 'int'):dol_print_date($now, "%m"));
-$sday = (GETPOSTISSET('closeday')?GETPOST('closeday', 'int'):dol_print_date($now, "%d"));
+$now = dol_now();
+$syear = (GETPOSTISSET('closeyear') ?GETPOST('closeyear', 'int') : dol_print_date($now, "%Y"));
+$smonth = (GETPOSTISSET('closemonth') ?GETPOST('closemonth', 'int') : dol_print_date($now, "%m"));
+$sday = (GETPOSTISSET('closeday') ?GETPOST('closeday', 'int') : dol_print_date($now, "%d"));
 
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOST("page", 'int');
@@ -52,30 +52,30 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (! $sortfield) $sortfield='rowid';
-if (! $sortorder) $sortorder='ASC';
+if (!$sortfield) $sortfield = 'rowid';
+if (!$sortorder) $sortorder = 'ASC';
 
 // Security check
-if (! $user->rights->cashdesk->use && ! $user->rights->takepos->use)
+if (!$user->rights->cashdesk->use && !$user->rights->takepos->use)
 {
 	accessforbidden();
 }
 
-$arrayofpaymentmode=array('cash'=>'Cash', 'cheque'=>'Cheque', 'card'=>'CreditCard');
+$arrayofpaymentmode = array('cash'=>'Cash', 'cheque'=>'Cheque', 'card'=>'CreditCard');
 
-$arrayofposavailable=array();
-if (! empty($conf->cashdesk->enabled)) $arrayofposavailable['cashdesk']=$langs->trans('CashDesk').' (cashdesk)';
-if (! empty($conf->takepos->enabled))  $arrayofposavailable['takepos']=$langs->trans('TakePOS').' (takepos)';
+$arrayofposavailable = array();
+if (!empty($conf->cashdesk->enabled)) $arrayofposavailable['cashdesk'] = $langs->trans('CashDesk').' (cashdesk)';
+if (!empty($conf->takepos->enabled))  $arrayofposavailable['takepos'] = $langs->trans('TakePOS').' (takepos)';
 // TODO Add hook here to allow other POS to add themself
 
-$object= new CashControl($db);
+$object = new CashControl($db);
 $extrafields = new ExtraFields($db);
 
 // fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('cashcontrolcard','globalcard'));
+$hookmanager->initHooks(array('cashcontrolcard', 'globalcard'));
 
 
 /*
@@ -86,7 +86,7 @@ $permissiontoadd = ($user->rights->cashdesk->use || $user->rights->takepos->use)
 $permissiontodelete = ($user->rights->cashdesk->use || $user->rights->takepos->use) || ($permissiontoadd && $object->status == 0);
 if (empty($backtopage)) $backtopage = dol_buildpath('/compta/cashcontrol/cashcontrol_card.php', 1).'?id='.($id > 0 ? $id : '__ID__');
 $backurlforlist = dol_buildpath('/compta/cashcontrol/cashcontrol_list.php', 1);
-$triggermodname = 'CACHCONTROL_MODIFY';	// Name of trigger action code to execute when we modify record
+$triggermodname = 'CACHCONTROL_MODIFY'; // Name of trigger action code to execute when we modify record
 
 if (empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH) && empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH1))
 {
@@ -99,70 +99,70 @@ if (GETPOST('cancel', 'alpha'))
 	$action = 'create';
 }
 
-if ($action=="start")
+if ($action == "start")
 {
-	$error=0;
-	if (! GETPOST('posmodule', 'alpha') || GETPOST('posmodule', 'alpha') == '-1')
+	$error = 0;
+	if (!GETPOST('posmodule', 'alpha') || GETPOST('posmodule', 'alpha') == '-1')
 	{
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Module")), null, 'errors');
-		$action='create';
+		$action = 'create';
 		$error++;
 	}
 	if (GETPOST('posnumber', 'alpha') == '')
 	{
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CashDesk")), null, 'errors');
-		$action='create';
+		$action = 'create';
 		$error++;
 	}
-	if (! GETPOST('closeyear', 'alpha') || GETPOST('closeyear', 'alpha') == '-1')
+	if (!GETPOST('closeyear', 'alpha') || GETPOST('closeyear', 'alpha') == '-1')
 	{
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Year")), null, 'errors');
-		$action='create';
+		$action = 'create';
 		$error++;
 	}
 }
-elseif ($action=="add")
+elseif ($action == "add")
 {
 	if (GETPOST('opening', 'alpha') == '')
 	{
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InitialBankBalance")), null, 'errors');
-		$action='start';
+		$action = 'start';
 		$error++;
 	}
-	$error=0;
-	foreach($arrayofpaymentmode as $key=>$val)
+	$error = 0;
+	foreach ($arrayofpaymentmode as $key=>$val)
 	{
 		$object->$key = price2num(GETPOST($key.'_amount', 'alpha'));
 	}
 
-	if (! $error)
+	if (!$error)
 	{
 		$object->day_close = GETPOST('closeday', 'int');
 		$object->month_close = GETPOST('closemonth', 'int');
 		$object->year_close = GETPOST('closeyear', 'int');
 
-	    $object->opening=price2num(GETPOST('opening', 'alpha'));
-	    $object->posmodule=GETPOST('posmodule', 'alpha');
-		$object->posnumber=GETPOST('posnumber', 'alpha');
+	    $object->opening = price2num(GETPOST('opening', 'alpha'));
+	    $object->posmodule = GETPOST('posmodule', 'alpha');
+		$object->posnumber = GETPOST('posnumber', 'alpha');
 
 		$db->begin();
 
-		$id=$object->create($user);
+		$id = $object->create($user);
 
 		if ($id > 0)
 		{
 			$db->commit();
-			$action="view";
+			$action = "view";
 		}
 		else
 		{
 			$db->rollback;
-			$action="view";
+			$action = "view";
 		}
 	}
 }
 
-if ($action=="close")
+if ($action == "close")
 {
 	$object->fetch($id);
 
@@ -176,21 +176,21 @@ if ($action=="close")
 		setEventMessages($langs->trans("CashFenceDone"), null);
 	}
 
-    $action="view";
+    $action = "view";
 }
 
 // Action to delete
-if ($action == 'confirm_delete' && ! empty($permissiontodelete))
+if ($action == 'confirm_delete' && !empty($permissiontodelete))
 {
     $object->fetch($id);
 
-    if (! ($object->id > 0))
+    if (!($object->id > 0))
     {
         dol_print_error('', 'Error, object must be fetched before being deleted');
         exit;
     }
 
-    $result=$object->delete($user);
+    $result = $object->delete($user);
     //var_dump($result);
     if ($result > 0)
     {
@@ -201,7 +201,7 @@ if ($action == 'confirm_delete' && ! empty($permissiontodelete))
     }
     else
     {
-        if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors');
+        if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors');
         else setEventMessages($object->error, null, 'errors');
     }
 }
@@ -211,15 +211,15 @@ if ($action == 'confirm_delete' && ! empty($permissiontodelete))
  * View
  */
 
-$form=new Form($db);
+$form = new Form($db);
 
-if ($action=="create" || $action=="start")
+if ($action == "create" || $action == "start")
 {
 	llxHeader();
 
-	$initialbalanceforterminal=array();
-	$theoricalamountforterminal=array();
-	$theoricalnbofinvoiceforterminal=array();
+	$initialbalanceforterminal = array();
+	$theoricalamountforterminal = array();
+	$theoricalnbofinvoiceforterminal = array();
 
 	if (GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '-1')
 	{
@@ -227,16 +227,16 @@ if ($action=="create" || $action=="start")
 		$terminalid = GETPOST('posnumber', 'alpha');
 		$terminaltouse = $terminalid;
 
-		if ($terminaltouse == '1' && $posmodule=='cashdesk') $terminaltouse = '';
+		if ($terminaltouse == '1' && $posmodule == 'cashdesk') $terminaltouse = '';
 
-		if ($posmodule=='cashdesk' && $terminaltouse != '' && $terminaltouse != '1') {
+		if ($posmodule == 'cashdesk' && $terminaltouse != '' && $terminaltouse != '1') {
 			$terminaltouse = '';
 			setEventMessages($langs->trans("OnlyTerminal1IsAvailableForCashDeskModule"), null, 'errors');
 			$error++;
 		}
 
 		// Calculate $initialbalanceforterminal for terminal 0
-		foreach($arrayofpaymentmode as $key => $val)
+		foreach ($arrayofpaymentmode as $key => $val)
 		{
 			if ($key != 'cash')
 			{
@@ -245,18 +245,18 @@ if ($action=="create" || $action=="start")
 			}
 
 			// Get the bank account dedicated to this point of sale module/terminal
-			$vartouse='CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse;
-			$bankid = $conf->global->$vartouse;			// This value is ok for 'Terminal 0' for module 'CashDesk' and 'TakePos' (they manage only 1 terminal)
+			$vartouse = 'CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse;
+			$bankid = $conf->global->$vartouse; // This value is ok for 'Terminal 0' for module 'CashDesk' and 'TakePos' (they manage only 1 terminal)
 			// Hook to get the good bank id according to posmodule and posnumber.
 			// @TODO add hook here
 
 			if ($bankid > 0)
 			{
     			$sql = "SELECT SUM(amount) as total FROM ".MAIN_DB_PREFIX."bank";
-    			$sql.= " WHERE fk_account = ".$bankid;
-    			if ($syear && ! $smonth)              $sql.= " AND dateo < '".$db->idate(dol_get_first_day($syear, 1))."'";
-    			elseif ($syear && $smonth && ! $sday) $sql.= " AND dateo < '".$db->idate(dol_get_first_day($syear, $smonth))."'";
-    			elseif ($syear && $smonth && $sday)   $sql.= " AND dateo < '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."'";
+    			$sql .= " WHERE fk_account = ".$bankid;
+    			if ($syear && !$smonth)              $sql .= " AND dateo < '".$db->idate(dol_get_first_day($syear, 1))."'";
+    			elseif ($syear && $smonth && !$sday) $sql .= " AND dateo < '".$db->idate(dol_get_first_day($syear, $smonth))."'";
+    			elseif ($syear && $smonth && $sday)   $sql .= " AND dateo < '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."'";
     			else dol_print_error('', 'Year not defined');
 
     			$resql = $db->query($sql);
@@ -275,28 +275,28 @@ if ($action=="create" || $action=="start")
 		}
 
 		// Calculate $theoricalamountforterminal for terminal 0
-		foreach($arrayofpaymentmode as $key => $val)
+		foreach ($arrayofpaymentmode as $key => $val)
 		{
 			/*$sql = "SELECT SUM(amount) as total FROM ".MAIN_DB_PREFIX."bank";
 			$sql.= " WHERE fk_account = ".$bankid;*/
 			$sql = "SELECT SUM(pf.amount) as total, COUNT(*) as nb";
-			$sql.= " FROM ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."c_paiement as cp";
-			$sql.= " WHERE pf.fk_facture = f.rowid AND p.rowid = pf.fk_paiement AND cp.id = p.fk_paiement";
-			$sql.= " AND f.module_source = '".$db->escape($posmodule)."'";
-			$sql.= " AND f.pos_source = '".$db->escape($terminalid)."'";
-			$sql.= " AND f.paye = 1";
-			$sql.= " AND p.entity IN (".getEntity('facture').")";
-			if ($key == 'cash')       $sql.=" AND cp.code = 'LIQ'";
-			elseif ($key == 'cheque') $sql.=" AND cp.code = 'CHQ'";
-			elseif ($key == 'card')   $sql.=" AND cp.code = 'CB'";
+			$sql .= " FROM ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."c_paiement as cp";
+			$sql .= " WHERE pf.fk_facture = f.rowid AND p.rowid = pf.fk_paiement AND cp.id = p.fk_paiement";
+			$sql .= " AND f.module_source = '".$db->escape($posmodule)."'";
+			$sql .= " AND f.pos_source = '".$db->escape($terminalid)."'";
+			$sql .= " AND f.paye = 1";
+			$sql .= " AND p.entity IN (".getEntity('facture').")";
+			if ($key == 'cash')       $sql .= " AND cp.code = 'LIQ'";
+			elseif ($key == 'cheque') $sql .= " AND cp.code = 'CHQ'";
+			elseif ($key == 'card')   $sql .= " AND cp.code = 'CB'";
 			else
 			{
 				dol_print_error('Value for key = '.$key.' not supported');
 				exit;
 			}
-			if ($syear && ! $smonth)              $sql.= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, 1))."' AND '".$db->idate(dol_get_last_day($syear, 12))."'";
-			elseif ($syear && $smonth && ! $sday) $sql.= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, $smonth))."' AND '".$db->idate(dol_get_last_day($syear, $smonth))."'";
-			elseif ($syear && $smonth && $sday)   $sql.= " AND datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $smonth, $sday, $syear))."'";
+			if ($syear && !$smonth)              $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, 1))."' AND '".$db->idate(dol_get_last_day($syear, 12))."'";
+			elseif ($syear && $smonth && !$sday) $sql .= " AND datef BETWEEN '".$db->idate(dol_get_first_day($syear, $smonth))."' AND '".$db->idate(dol_get_last_day($syear, $smonth))."'";
+			elseif ($syear && $smonth && $sday)   $sql .= " AND datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $smonth, $sday, $syear))."' AND '".$db->idate(dol_mktime(23, 59, 59, $smonth, $sday, $syear))."'";
 			else dol_print_error('', 'Year not defined');
 
 			$resql = $db->query($sql);
@@ -337,53 +337,53 @@ if ($action=="create" || $action=="start")
     print '<td></td>';
     print "</tr>\n";
 
-	$disabled=0;
-	$prefix='close';
+	$disabled = 0;
+	$prefix = 'close';
 
     print '<tr class="oddeven">';
-    print '<td>'.$form->selectarray('posmodule', $arrayofposavailable, GETPOST('posmodule', 'alpha'), (count($arrayofposavailable)>1?1:0)).'</td>';
+    print '<td>'.$form->selectarray('posmodule', $arrayofposavailable, GETPOST('posmodule', 'alpha'), (count($arrayofposavailable) > 1 ? 1 : 0)).'</td>';
     print '<td>';
-    $array=array(1=>"1", 2=>"2", 3=>"3", 4=>"4", 5=>"5", 6=>"6", 7=>"7", 8=>"8", 9=>"9");
-    $selectedposnumber=0; $showempty=1;
+    $array = array(1=>"1", 2=>"2", 3=>"3", 4=>"4", 5=>"5", 6=>"6", 7=>"7", 8=>"8", 9=>"9");
+    $selectedposnumber = 0; $showempty = 1;
     if ($conf->global->TAKEPOS_NUM_TERMINALS == '1')
     {
-        $selectedposnumber=1; $showempty=0;
+        $selectedposnumber = 1; $showempty = 0;
     }
-    print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber')?GETPOST('posnumber', 'int'):$selectedposnumber, $showempty);
+    print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber') ?GETPOST('posnumber', 'int') : $selectedposnumber, $showempty);
     //print '<input name="posnumber" type="text" class="maxwidth50" value="'.(GETPOSTISSET('posnumber')?GETPOST('posnumber', 'alpha'):'0').'">';
     print '</td>';
 	// Year
 	print '<td>';
-	$retstring='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
-	for ($year = $syear - 10; $year < $syear + 10 ; $year++)
+	$retstring = '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
+	for ($year = $syear - 10; $year < $syear + 10; $year++)
 	{
-		$retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
+		$retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
 	}
-	$retstring.="</select>\n";
+	$retstring .= "</select>\n";
 	print $retstring;
 	print '</td>';
 	// Month
 	print '<td>';
-	$retstring='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
-	$retstring.='<option value="0"></option>';
-	for ($month = 1 ; $month <= 12 ; $month++)
+	$retstring = '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
+	$retstring .= '<option value="0"></option>';
+	for ($month = 1; $month <= 12; $month++)
 	{
-		$retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
-		$retstring.=dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
-		$retstring.="</option>";
+		$retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
+		$retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
+		$retstring .= "</option>";
 	}
-	$retstring.="</select>";
+	$retstring .= "</select>";
 	print $retstring;
 	print '</td>';
 	// Day
 	print '<td>';
-	$retstring='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
-	$retstring.='<option value="0" selected>&nbsp;</option>';
-	for ($day = 1 ; $day <= 31; $day++)
+	$retstring = '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
+	$retstring .= '<option value="0" selected>&nbsp;</option>';
+	for ($day = 1; $day <= 31; $day++)
 	{
-		$retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
+		$retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
 	}
-	$retstring.="</select>";
+	$retstring .= "</select>";
 	print $retstring;
 	print '</td>';
 	// Button Start
@@ -425,10 +425,10 @@ if ($action=="create" || $action=="start")
 		print '<td align="center">'.$langs->trans("Cash");
 		//print '<br>'.$langs->trans("TheoricalAmount").'<br>'.$langs->trans("RealAmount");
 		print '</td>';
-		$i=0;
-		foreach($arrayofpaymentmode as $key => $val)
+		$i = 0;
+		foreach ($arrayofpaymentmode as $key => $val)
 		{
-			print '<td align="center"'.($i == 0 ? ' class="hide0"':'').'>'.$langs->trans($val);
+			print '<td align="center"'.($i == 0 ? ' class="hide0"' : '').'>'.$langs->trans($val);
 			//print '<br>'.$langs->trans("TheoricalAmount").'<br>'.$langs->trans("RealAmount");
 			print '</td>';
 			$i++;
@@ -442,10 +442,10 @@ if ($action=="create" || $action=="start")
 		print '<td align="center">';
 		print '</td>';
 		// Amount per payment type
-		$i=0;
-		foreach($arrayofpaymentmode as $key => $val)
+		$i = 0;
+		foreach ($arrayofpaymentmode as $key => $val)
 		{
-		    print '<td align="center"'.($i == 0 ? ' class="hide0"':'').'>';
+		    print '<td align="center"'.($i == 0 ? ' class="hide0"' : '').'>';
 		    print $theoricalnbofinvoiceforterminal[$terminalid][$key];
 		    print '</td>';
 		    $i++;
@@ -461,10 +461,10 @@ if ($action=="create" || $action=="start")
 		print price($initialbalanceforterminal[$terminalid]['cash']).'<br>';
 		print '</td>';
 		// Amount per payment type
-		$i=0;
-		foreach($arrayofpaymentmode as $key => $val)
+		$i = 0;
+		foreach ($arrayofpaymentmode as $key => $val)
 		{
-			print '<td align="center"'.($i == 0 ? ' class="hide0"':'').'>';
+			print '<td align="center"'.($i == 0 ? ' class="hide0"' : '').'>';
 			print price($theoricalamountforterminal[$terminalid][$key]).'<br>';
 			print '</td>';
 			$i++;
@@ -477,14 +477,14 @@ if ($action=="create" || $action=="start")
 		print '<td>'.$langs->trans("RealAmount").'</td>';
 		// Initial amount
 		print '<td align="center">';
-		print '<input name="opening" type="text" class="maxwidth100 center" value="'.(GETPOSTISSET('opening')?price2num(GETPOST('opening', 'alpha')):price($initialbalanceforterminal[$terminalid]['cash'])).'">';
+		print '<input name="opening" type="text" class="maxwidth100 center" value="'.(GETPOSTISSET('opening') ?price2num(GETPOST('opening', 'alpha')) : price($initialbalanceforterminal[$terminalid]['cash'])).'">';
 		print '</td>';
 		// Amount per payment type
-		$i=0;
-		foreach($arrayofpaymentmode as $key => $val)
+		$i = 0;
+		foreach ($arrayofpaymentmode as $key => $val)
 		{
-			print '<td align="center"'.($i == 0 ? ' class="hide0"':'').'>';
-			print '<input name="'.$key.'_amount" type="text"'.($key == 'cash'?' autofocus':'').' class="maxwidth100 center" value="'.GETPOST($key.'_amount', 'alpha').'">';
+			print '<td align="center"'.($i == 0 ? ' class="hide0"' : '').'>';
+			print '<input name="'.$key.'_amount" type="text"'.($key == 'cash' ? ' autofocus' : '').' class="maxwidth100 center" value="'.GETPOST($key.'_amount', 'alpha').'">';
 			print '</td>';
 			$i++;
 		}
@@ -500,23 +500,23 @@ if ($action=="create" || $action=="start")
     print '</form>';
 }
 
-if (empty($action) || $action=="view")
+if (empty($action) || $action == "view")
 {
     $object->fetch($id);
 
     llxHeader('', $langs->trans("CashControl"));
 
-    $head=array();
+    $head = array();
     $head[0][0] = DOL_URL_ROOT.'/compta/cashcontrol/cashcontrol_card.php?id='.$object->id;
     $head[0][1] = $langs->trans("Card");
     $head[0][2] = 'cashcontrol';
 
     dol_fiche_head($head, 'cashcontrol', $langs->trans("CashControl"), -1, 'cashcontrol');
 
-    $linkback = '<a href="' . DOL_URL_ROOT . '/compta/cashcontrol/cashcontrol_list.php?restore_lastsearch_values=1">' . $langs->trans("BackToList") . '</a>';
+    $linkback = '<a href="'.DOL_URL_ROOT.'/compta/cashcontrol/cashcontrol_list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-    $morehtmlref='<div class="refidno">';
-    $morehtmlref.='</div>';
+    $morehtmlref = '<div class="refidno">';
+    $morehtmlref .= '</div>';
 
 
     dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'rowid', $morehtmlref);
@@ -563,7 +563,7 @@ if (empty($action) || $action=="view")
     print price($object->opening, 0, $langs, 1, -1, -1, $conf->currency);
     print "</td></tr>";
 
-    foreach($arrayofpaymentmode as $key => $val)
+    foreach ($arrayofpaymentmode as $key => $val)
     {
         print '<tr><td valign="middle">'.$langs->trans($val).'</td><td>';
     	print price($object->$key, 0, $langs, 1, -1, -1, $conf->currency);
@@ -578,12 +578,12 @@ if (empty($action) || $action=="view")
     dol_fiche_end();
 
 	print '<div class="tabsAction">';
-	print '<div class="inline-block divButAction"><a target="_blank" class="butAction" href="report.php?id='.$id.'">' . $langs->trans('PrintTicket') . '</a></div>';
+	print '<div class="inline-block divButAction"><a target="_blank" class="butAction" href="report.php?id='.$id.'">'.$langs->trans('PrintTicket').'</a></div>';
 	if ($object->status == CashControl::STATUS_DRAFT)
 	{
-		print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $id . '&amp;action=close">' . $langs->trans('ValidateAndClose') . '</a></div>';
+		print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&amp;action=close">'.$langs->trans('ValidateAndClose').'</a></div>';
 
-		print '<div class="inline-block divButAction"><a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?id=' . $id . '&amp;action=confirm_delete">' . $langs->trans('Delete') . '</a></div>';
+		print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&amp;action=confirm_delete">'.$langs->trans('Delete').'</a></div>';
 	}
 	print '</div>';
 

+ 8 - 8
htdocs/compta/facture/contact.php

@@ -89,7 +89,7 @@ elseif ($action == 'swapstatut' && $user->rights->facture->creer)
 {
 	if ($object->fetch($id))
 	{
-	    $result=$object->swapContactStatus(GETPOST('ligne'));
+	    $result = $object->swapContactStatus(GETPOST('ligne'));
 	}
 	else
 	{
@@ -118,14 +118,14 @@ elseif ($action == 'deletecontact' && $user->rights->facture->creer)
  * View
  */
 
-$title = $langs->trans('InvoiceCustomer') . " - " . $langs->trans('ContactsAddresses');
+$title = $langs->trans('InvoiceCustomer')." - ".$langs->trans('ContactsAddresses');
 $helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
 llxHeader('', $title, $helpurl);
 
 $form = new Form($db);
 $formcompany = new FormCompany($db);
-$contactstatic=new Contact($db);
-$userstatic=new User($db);
+$contactstatic = new Contact($db);
+$userstatic = new User($db);
 
 
 /* *************************************************************************** */
@@ -134,7 +134,7 @@ $userstatic=new User($db);
 /*                                                                             */
 /* *************************************************************************** */
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	if ($object->fetch($id, $ref) > 0)
 	{
@@ -201,10 +201,10 @@ if ($id > 0 || ! empty($ref))
 		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)
+		$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
+		foreach ($dirtpls as $reldir)
 		{
-		    $res=@include dol_buildpath($reldir.'/contacts.tpl.php');
+		    $res = @include dol_buildpath($reldir.'/contacts.tpl.php');
 		    if ($res) break;
 		}
 	}

+ 34 - 34
htdocs/compta/facture/document.php

@@ -63,14 +63,14 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $conf->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";
 
 $object = new Facture($db);
 if ($object->fetch($id))
 {
 	$object->fetch_thirdparty();
-	$upload_dir = $conf->facture->dir_output . "/" . dol_sanitizeFileName($object->ref);
+	$upload_dir = $conf->facture->dir_output."/".dol_sanitizeFileName($object->ref);
 }
 
 
@@ -78,20 +78,20 @@ if ($object->fetch($id))
  * Actions
  */
 
-require_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
+require_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
 
 
 /*
  * View
  */
 
-$title = $langs->trans('InvoiceCustomer') . " - " . $langs->trans('Documents');
+$title = $langs->trans('InvoiceCustomer')." - ".$langs->trans('Documents');
 $helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
 llxHeader('', $title, $helpurl);
 
 $form = new Form($db);
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	if ($object->fetch($id, $ref) > 0)
 	{
@@ -105,60 +105,60 @@ if ($id > 0 || ! empty($ref))
     	$totalpaye = $object->getSommePaiement();
 
 		// 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)
+		$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'];
+			$totalsize += $file['size'];
 		}
 
 
 	    // Invoice content
 
-	    $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
+	    $linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
-	    $morehtmlref='<div class="refidno">';
+	    $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);
+	    $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') . ' : ' . $object->thirdparty->getNomUrl(1, 'customer');
+	    $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer');
 	    // Project
-	    if (! empty($conf->projet->enabled))
+	    if (!empty($conf->projet->enabled))
 	    {
 	    	$langs->load("projects");
-	    	$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+	    	$morehtmlref .= '<br>'.$langs->trans('Project').' ';
 	    	if ($user->rights->facture->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.=' : ';
+	    			$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="'.$_SESSION['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>';
+	    			$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="'.$_SESSION['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);
+	    			$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)) {
+	    		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>';
+	    			$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 .= '';
 	    		}
 	    	}
 	    }
-	    $morehtmlref.='</div>';
+	    $morehtmlref .= '</div>';
 
-	    $object->totalpaye = $totalpaye;   // To give a chance to dol_banner_tab to use already paid amount to show correct status
+	    $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
 
 	    dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0);
 
@@ -178,8 +178,8 @@ if ($id > 0 || ! empty($ref))
 		$modulepart = 'facture';
 		$permission = $user->rights->facture->creer;
 		$permtoedit = $user->rights->facture->creer;
-		$param = '&id=' . $object->id;
-		include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
+		$param = '&id='.$object->id;
+		include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
 	}
 	else
 	{

+ 26 - 26
htdocs/compta/facture/info.php

@@ -28,15 +28,15 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
-if (! empty($conf->projet->enabled)) {
-	include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+if (!empty($conf->projet->enabled)) {
+	include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 }
 
 // Load translation files required by the page
 $langs->loadLangs(array('companies', 'bills'));
 
 $id = GETPOST("facid", "int");
-$ref=GETPOST("ref", 'alpha');
+$ref = GETPOST("ref", 'alpha');
 
 
 /*
@@ -45,7 +45,7 @@ $ref=GETPOST("ref", 'alpha');
 
 $form = new Form($db);
 
-$title = $langs->trans('InvoiceCustomer') . " - " . $langs->trans('Info');
+$title = $langs->trans('InvoiceCustomer')." - ".$langs->trans('Info');
 $helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
 llxHeader('', $title, $helpurl);
 
@@ -62,50 +62,50 @@ $totalpaye = $object->getSommePaiement();
 
 // Invoice content
 
-$linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
+$linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
-$morehtmlref='<div class="refidno">';
+$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);
+$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') . ' : ' . $object->thirdparty->getNomUrl(1, 'customer');
+$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer');
 // Project
-if (! empty($conf->projet->enabled))
+if (!empty($conf->projet->enabled))
 {
 	$langs->load("projects");
-	$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+	$morehtmlref .= '<br>'.$langs->trans('Project').' ';
 	if ($user->rights->facture->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.=' : ';
+			$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="'.$_SESSION['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>';
+			$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="'.$_SESSION['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);
+			$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)) {
+		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>';
+			$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 .= '';
 		}
 	}
 }
-$morehtmlref.='</div>';
+$morehtmlref .= '</div>';
 
-$object->totalpaye = $totalpaye;   // To give a chance to dol_banner_tab to use already paid amount to show correct status
+$object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
 
 dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0);
 

+ 73 - 73
htdocs/compta/facture/invoicetemplate_list.php

@@ -33,15 +33,15 @@ require '../../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
-if (! empty($conf->projet->enabled)) {
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+if (!empty($conf->projet->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 	//require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
 }
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
 
 // Load translation files required by the page
 $langs->loadLangs(array('bills', 'compta', 'admin', 'other'));
@@ -104,19 +104,19 @@ if (($id > 0 || $ref) && $action != 'create' && $action != 'add')
 }
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('invoicereccard','globalcard'));
+$hookmanager->initHooks(array('invoicereccard', 'globalcard'));
 $extrafields = new ExtraFields($db);
 
 // fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label('facture_rec');
 
-$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
 
 $permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php
-$permissiondellink=$user->rights->facture->creer;	// Used by the include of actions_dellink.inc.php
+$permissiondellink = $user->rights->facture->creer; // Used by the include of actions_dellink.inc.php
 $permissiontoedit = $user->rights->facture->creer; // Used by the include of actions_lineupdonw.inc.php
 
-$arrayfields=array(
+$arrayfields = array(
 	'f.titre'=>array('label'=>$langs->trans("Ref"), 'checked'=>1),
 	's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1),
 	'f.total'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1),
@@ -137,10 +137,10 @@ $arrayfields=array(
 // 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)
+	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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key]));
+		if (!empty($extrafields->attributes[$object->table_element]['list'][$key]))
+			$arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key]));
 	}
 }
 $object->fields = dol_sort_array($object->fields, 'position');
@@ -151,8 +151,8 @@ $arrayfields = dol_sort_array($arrayfields, 'position');
  * 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
@@ -160,7 +160,7 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
 
 if (empty($reshook))
 {
-	if (GETPOST('cancel', 'alpha')) $action='';
+	if (GETPOST('cancel', 'alpha')) $action = '';
 
 	// Selection of new fields
 	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
@@ -168,24 +168,24 @@ if (empty($reshook))
 	// Do we click on 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
 	{
-		$search_ref='';
-		$search_societe='';
-		$search_montant_ht='';
-		$search_montant_vat='';
-		$search_montant_ttc='';
-		$search_payment_mode='';
-		$search_payment_term='';
-		$search_day='';
-		$search_year='';
-		$search_month='';
-		$search_day_date_when='';
-		$search_year_date_when='';
-		$search_month_date_when='';
-		$search_recurring='';
-		$search_frequency='';
-		$search_unit_frequency='';
-		$search_status='';
-		$search_array_options=array();
+		$search_ref = '';
+		$search_societe = '';
+		$search_montant_ht = '';
+		$search_montant_vat = '';
+		$search_montant_ttc = '';
+		$search_payment_mode = '';
+		$search_payment_term = '';
+		$search_day = '';
+		$search_year = '';
+		$search_month = '';
+		$search_day_date_when = '';
+		$search_year_date_when = '';
+		$search_month_date_when = '';
+		$search_recurring = '';
+		$search_frequency = '';
+		$search_unit_frequency = '';
+		$search_status = '';
+		$search_array_options = array();
 	}
 
 	// Mass actions
@@ -247,22 +247,22 @@ if ($search_societe)              $sql .= natural_search('s.nom', $search_societ
 if ($search_montant_ht != '')     $sql .= natural_search('f.total', $search_montant_ht, 1);
 if ($search_montant_vat != '')    $sql .= natural_search('f.tva', $search_montant_vat, 1);
 if ($search_montant_ttc != '')    $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1);
-if (! empty($search_payment_mode) && $search_payment_mode != '-1')   $sql .= natural_search('f.fk_mode_reglement', $search_payment_mode, 1);
-if (! empty($search_payment_term) && $search_payment_term != '-1')   $sql .= natural_search('f.fk_cond_reglement', $search_payment_term, 1);
+if (!empty($search_payment_mode) && $search_payment_mode != '-1')   $sql .= natural_search('f.fk_mode_reglement', $search_payment_mode, 1);
+if (!empty($search_payment_term) && $search_payment_term != '-1')   $sql .= natural_search('f.fk_cond_reglement', $search_payment_term, 1);
 if ($search_recurring == '1')     $sql .= ' AND f.frequency > 0';
 if ($search_recurring == '0')     $sql .= ' AND (f.frequency IS NULL or f.frequency = 0)';
 if ($search_frequency != '')      $sql .= natural_search('f.frequency', $search_frequency, 1);
 if ($search_unit_frequency != '') $sql .= ' AND f.frequency > 0'.natural_search('f.unit_frequency', $search_unit_frequency);
 if ($search_status != '' && $search_status >= -1)
 {
-	if ($search_status == 0) $sql.= ' AND frequency = 0 AND suspended = 0';
-	if ($search_status == 1) $sql.= ' AND frequency != 0 AND suspended = 0';
-	if ($search_status == -1) $sql.= ' AND suspended = 1';
+	if ($search_status == 0) $sql .= ' AND frequency = 0 AND suspended = 0';
+	if ($search_status == 1) $sql .= ' AND frequency != 0 AND suspended = 0';
+	if ($search_status == -1) $sql .= ' AND suspended = 1';
 }
-$sql.=dolSqlDateFilter('f.date_last_gen', $search_day, $search_month, $search_year);
-$sql.=dolSqlDateFilter('f.date_last_gen', $search_day_date_when, $search_month_date_when, $search_year_date_when);
+$sql .= dolSqlDateFilter('f.date_last_gen', $search_day, $search_month, $search_year);
+$sql .= dolSqlDateFilter('f.date_last_gen', $search_day_date_when, $search_month_date_when, $search_year_date_when);
 
-$sql.= $db->order($sortfield, $sortorder);
+$sql .= $db->order($sortfield, $sortorder);
 
 $nbtotalofrecords = '';
 if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
@@ -276,43 +276,43 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
 	}
 }
 
-$sql.= $db->plimit($limit+1, $offset);
+$sql .= $db->plimit($limit + 1, $offset);
 
 $resql = $db->query($sql);
 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 ($socid)                     $param.='&socid='.urlencode($socid);
-	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_day_date_when)      $param.='&search_day_date_when='.urlencode($search_day_date_when);
-	if ($search_month_date_when)    $param.='&search_month_date_when='.urlencode($search_month_date_when);
-	if ($search_year_date_when)     $param.='&search_year_date_when=' .urlencode($search_year_date_when);
-	if ($search_ref)                $param.='&search_ref=' .urlencode($search_ref);
-	if ($search_societe)            $param.='&search_societe=' .urlencode($search_societe);
-	if ($search_montant_ht != '')   $param.='&search_montant_ht=' .urlencode($search_montant_ht);
-	if ($search_montant_vat != '')  $param.='&search_montant_vat='.urlencode($search_montant_vat);
-	if ($search_montant_ttc != '')  $param.='&search_montant_ttc='.urlencode($search_montant_ttc);
-	if ($search_payment_mode != '') $param.='&search_payment_mode='.urlencode($search_payment_mode);
-	if ($search_payment_type != '') $param.='&search_payment_type='.urlencode($search_payment_type);
-	if ($search_recurring != '' && $search_recurrning != '-1')    $param.='&search_recurring='  .urlencode($search_recurring);
-	if ($search_frequency > 0)        $param.='&search_frequency='  .urlencode($search_frequency);
-	if ($search_unit_frequency != '') $param.='&search_unit_frequency='.urlencode($search_unit_frequency);
-	if ($search_status != '')		$param.='&search_status='.urlencode($search_status);
-	if ($option)                    $param.="&option=".urlencode($option);
-	if ($optioncss != '')           $param.='&optioncss='.urlencode($optioncss);
+	$param = '';
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
+	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+	if ($socid)                     $param .= '&socid='.urlencode($socid);
+	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_day_date_when)      $param .= '&search_day_date_when='.urlencode($search_day_date_when);
+	if ($search_month_date_when)    $param .= '&search_month_date_when='.urlencode($search_month_date_when);
+	if ($search_year_date_when)     $param .= '&search_year_date_when='.urlencode($search_year_date_when);
+	if ($search_ref)                $param .= '&search_ref='.urlencode($search_ref);
+	if ($search_societe)            $param .= '&search_societe='.urlencode($search_societe);
+	if ($search_montant_ht != '')   $param .= '&search_montant_ht='.urlencode($search_montant_ht);
+	if ($search_montant_vat != '')  $param .= '&search_montant_vat='.urlencode($search_montant_vat);
+	if ($search_montant_ttc != '')  $param .= '&search_montant_ttc='.urlencode($search_montant_ttc);
+	if ($search_payment_mode != '') $param .= '&search_payment_mode='.urlencode($search_payment_mode);
+	if ($search_payment_type != '') $param .= '&search_payment_type='.urlencode($search_payment_type);
+	if ($search_recurring != '' && $search_recurrning != '-1')    $param .= '&search_recurring='.urlencode($search_recurring);
+	if ($search_frequency > 0)        $param .= '&search_frequency='.urlencode($search_frequency);
+	if ($search_unit_frequency != '') $param .= '&search_unit_frequency='.urlencode($search_unit_frequency);
+	if ($search_status != '')		$param .= '&search_status='.urlencode($search_status);
+	if ($option)                    $param .= "&option=".urlencode($option);
+	if ($optioncss != '')           $param .= '&optioncss='.urlencode($optioncss);
 	// Add $param from extra fields
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 
-	$massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge")));
+	$massactionbutton = $form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge")));
 
-	$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
-	$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage);	// This also change content of $arrayfields
+	$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
+	$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
 	//$selectedfields.=$form->showCheckAddButtons('checkforselect', 1);
 
 	print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
@@ -661,7 +661,7 @@ if ($resql)
 			{
 				print "&nbsp;";
 			}
-			if (! $i) $totalarray['nbfield']++;
+			if (!$i) $totalarray['nbfield']++;
 			print "</td>";
 
 			print "</tr>\n";
@@ -671,8 +671,8 @@ if ($resql)
 	}
 	else
 	{
-		$colspan=1;
-		foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; }
+		$colspan = 1;
+		foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; }
 		print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
 	}
 

+ 25 - 25
htdocs/compta/facture/note.php

@@ -64,13 +64,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include,
  * View
  */
 
-$title = $langs->trans('InvoiceCustomer') . " - " . $langs->trans('Notes');
+$title = $langs->trans('InvoiceCustomer')." - ".$langs->trans('Notes');
 $helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
 llxHeader('', $title, $helpurl);
 
 $form = new Form($db);
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	$object = new Facture($db);
 	$object->fetch($id, $ref);
@@ -85,50 +85,50 @@ if ($id > 0 || ! empty($ref))
 
     // Invoice content
 
-    $linkback = '<a href="' . DOL_URL_ROOT . '/compta/facture/list.php?restore_lastsearch_values=1' . (! empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
+    $linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
-    $morehtmlref='<div class="refidno">';
+    $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);
+    $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') . ' : ' . $object->thirdparty->getNomUrl(1, 'customer');
+    $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer');
     // Project
-    if (! empty($conf->projet->enabled))
+    if (!empty($conf->projet->enabled))
     {
     	$langs->load("projects");
-    	$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+    	$morehtmlref .= '<br>'.$langs->trans('Project').' ';
     	if ($user->rights->facture->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.=' : ';
+    			$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="'.$_SESSION['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>';
+    			$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="'.$_SESSION['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);
+    			$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)) {
+    		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>';
+    			$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 .= '';
     		}
     	}
     }
-    $morehtmlref.='</div>';
+    $morehtmlref .= '</div>';
 
-    $object->totalpaye = $totalpaye;   // To give a chance to dol_banner_tab to use already paid amount to show correct status
+    $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
 
     dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0);
 
@@ -136,7 +136,7 @@ if ($id > 0 || ! empty($ref))
 	print '<div class="underbanner clearboth"></div>';
 
 
-	$cssclass="titlefield";
+	$cssclass = "titlefield";
     include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php';
 
 	dol_fiche_end();

+ 65 - 65
htdocs/compta/facture/prelevement.php

@@ -32,8 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
-if (! empty($conf->projet->enabled)) {
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+if (!empty($conf->projet->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 }
 
 if (!$user->rights->facture->lire) accessforbidden();
@@ -95,7 +95,7 @@ if (empty($reshook))
                 setEventMessages($object->error, $object->errors, 'errors');
             }
         }
-        $action='';
+        $action = '';
     }
 
     if ($action == "delete")
@@ -117,9 +117,9 @@ if (empty($reshook))
  * View
  */
 
-$now=dol_now();
+$now = dol_now();
 
-$title = $langs->trans('InvoiceCustomer') . " - " . $langs->trans('StandingOrders');
+$title = $langs->trans('InvoiceCustomer')." - ".$langs->trans('StandingOrders');
 $helpurl = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
 llxHeader('', $title, $helpurl);
 
@@ -135,7 +135,7 @@ if ($object->id > 0)
 {
 	$selleruserevenustamp = $mysoc->useRevenueStamp();
 
-	$totalpaye  = $object->getSommePaiement();
+	$totalpaye = $object->getSommePaiement();
 	$totalcreditnotes = $object->getSumCreditNotesUsed();
 	$totaldeposits = $object->getSumDepositsUsed();
 	//print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
@@ -146,10 +146,10 @@ if ($object->id > 0)
 	//$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
 	$resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
 
-	if ($object->paye) $resteapayer=0;
-	$resteapayeraffiche=$resteapayer;
+	if ($object->paye) $resteapayer = 0;
+	$resteapayeraffiche = $resteapayer;
 
-	if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
+	if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
 		$filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
 		$filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
 	} else {
@@ -157,10 +157,10 @@ if ($object->id > 0)
 		$filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
 	}
 
-	$absolute_discount=$object->thirdparty->getAvailableDiscounts('', $filterabsolutediscount);
-	$absolute_creditnote=$object->thirdparty->getAvailableDiscounts('', $filtercreditnote);
-	$absolute_discount=price2num($absolute_discount, 'MT');
-	$absolute_creditnote=price2num($absolute_creditnote, 'MT');
+	$absolute_discount = $object->thirdparty->getAvailableDiscounts('', $filterabsolutediscount);
+	$absolute_creditnote = $object->thirdparty->getAvailableDiscounts('', $filtercreditnote);
+	$absolute_discount = price2num($absolute_discount, 'MT');
+	$absolute_creditnote = price2num($absolute_creditnote, 'MT');
 
 	$author = new User($db);
 	if ($object->user_author)
@@ -233,27 +233,27 @@ if ($object->id > 0)
 	print $object->getLibType();
 	if ($object->type == Facture::TYPE_REPLACEMENT)
 	{
-		$facreplaced=new Facture($db);
+		$facreplaced = new Facture($db);
 		$facreplaced->fetch($object->fk_facture_source);
 		print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')';
 	}
 	if ($object->type == Facture::TYPE_CREDIT_NOTE)
 	{
-		$facusing=new Facture($db);
+		$facusing = new Facture($db);
 		$facusing->fetch($object->fk_facture_source);
 		print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')';
 	}
 
-	$facidavoir=$object->getListIdAvoirFromInvoice();
+	$facidavoir = $object->getListIdAvoirFromInvoice();
 	if (count($facidavoir) > 0)
 	{
 		print ' ('.$langs->transnoentities("InvoiceHasAvoir");
-		$i=0;
-		foreach($facidavoir as $id)
+		$i = 0;
+		foreach ($facidavoir as $id)
 		{
-			if ($i==0) print ' ';
+			if ($i == 0) print ' ';
 			else print ',';
-			$facavoir=new Facture($db);
+			$facavoir = new Facture($db);
 			$facavoir->fetch($id);
 			print $facavoir->getNomUrl(1);
 		}
@@ -274,7 +274,7 @@ if ($object->id > 0)
 
 	$thirdparty = $object->thirdparty;
 	$discount_type = 0;
-	$backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id);
+	$backtopage = urlencode($_SERVER["PHP_SELF"].'?facid='.$object->id);
 	$cannotApplyDiscount = 1;
 	include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
 
@@ -285,7 +285,7 @@ if ($object->id > 0)
 	print '<table class="nobordernopadding" width="100%"><tr><td>';
 	print $langs->trans('DateInvoice');
 	print '</td>';
-	if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editinvoicedate' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editinvoicedate&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
+	if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editinvoicedate' && !empty($object->brouillon) && $user->rights->facture->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editinvoicedate&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
 	print '</tr></table>';
 	print '</td><td colspan="3">';
 
@@ -312,7 +312,7 @@ if ($object->id > 0)
 	print '<table class="nobordernopadding" width="100%"><tr><td>';
 	print $langs->trans('PaymentConditionsShort');
 	print '</td>';
-	if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
+	if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && !empty($object->brouillon) && $user->rights->facture->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
 	print '</tr></table>';
 	print '</td><td colspan="3">';
 	if ($object->type != Facture::TYPE_CREDIT_NOTE)
@@ -337,7 +337,7 @@ if ($object->id > 0)
 	print '<table class="nobordernopadding" width="100%"><tr><td>';
 	print $langs->trans('DateMaxPayment');
 	print '</td>';
-	if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editpaymentterm&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
+	if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && !empty($object->brouillon) && $user->rights->facture->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editpaymentterm&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
 	print '</tr></table>';
 	print '</td><td colspan="3">';
 	if ($object->type != Facture::TYPE_CREDIT_NOTE)
@@ -365,7 +365,7 @@ if ($object->id > 0)
 	print '<table class="nobordernopadding" width="100%"><tr><td>';
 	print $langs->trans('PaymentMode');
 	print '</td>';
-	if ($action != 'editmode' && ! empty($object->brouillon) && $user->rights->facture->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
+	if ($action != 'editmode' && !empty($object->brouillon) && $user->rights->facture->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
 	print '</tr></table>';
 	print '</td><td colspan="3">';
 	if ($action == 'editmode')
@@ -383,7 +383,7 @@ if ($object->id > 0)
 	print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
 	print $langs->trans('BankAccount');
 	print '<td>';
-	if (($action != 'editbankaccount') && $user->rights->commande->creer && ! empty($object->brouillon))
+	if (($action != 'editbankaccount') && $user->rights->commande->creer && !empty($object->brouillon))
 	    print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>';
 	print '</tr></table>';
 	print '</td><td colspan="3">';
@@ -414,39 +414,39 @@ if ($object->id > 0)
 	if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency))
 	{
 	    // Multicurrency Amount HT
-	    print '<tr><td class="titlefieldmiddle">' . $form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0) . '</td>';
-	    print '<td class="nowrap">' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
+	    print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
+	    print '<td class="nowrap">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
 	    print '</tr>';
 
 	    // Multicurrency Amount VAT
-	    print '<tr><td>' . $form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0) . '</td>';
-	    print '<td class="nowrap">' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
+	    print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
+	    print '<td class="nowrap">'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
 	    print '</tr>';
 
 	    // Multicurrency Amount TTC
-	    print '<tr><td>' . $form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0) . '</td>';
-	    print '<td class="nowrap">' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
+	    print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
+	    print '<td class="nowrap">'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
 	    print '</tr>';
 	}
 
 	// Amount
-	print '<tr><td class="titlefield">' . $langs->trans('AmountHT') . '</td>';
-	print '<td class="nowrap">' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
+	print '<tr><td class="titlefield">'.$langs->trans('AmountHT').'</td>';
+	print '<td class="nowrap">'.price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
 
 	// Vat
-	print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td colspan="3" class="nowrap">' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
+	print '<tr><td>'.$langs->trans('AmountVAT').'</td><td colspan="3" class="nowrap">'.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
 	print '</tr>';
 
 	// Amount Local Taxes
 	if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) 	// Localtax1
 	{
-	    print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
-	    print '<td class="nowrap">' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
+	    print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
+	    print '<td class="nowrap">'.price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
 	}
 	if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) 	// Localtax2
 	{
-	    print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
-	    print '<td class=nowrap">' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
+	    print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
+	    print '<td class=nowrap">'.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
 	}
 
 	// Revenue stamp
@@ -456,9 +456,9 @@ if ($object->id > 0)
 	    print '<table class="nobordernopadding" width="100%"><tr><td>';
 	    print $langs->trans('RevenueStamp');
 	    print '</td>';
-	    if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer)
+	    if ($action != 'editrevenuestamp' && !empty($object->brouillon) && $user->rights->facture->creer)
 	    {
-	        print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editrevenuestamp&amp;facid=' . $object->id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '</a></td>';
+	        print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editrevenuestamp&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetRevenuStamp'), 1).'</a></td>';
 	    }
         print '</tr></table>';
         print '</td><td>';
@@ -467,7 +467,7 @@ if ($object->id > 0)
 	}
 
 	// Total with tax
-	print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td class="nowrap">' . price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency) . '</td></tr>';
+	print '<tr><td>'.$langs->trans('AmountTTC').'</td><td class="nowrap">'.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
 
     $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
 
@@ -545,10 +545,10 @@ if ($object->id > 0)
     			$remaintopaylesspendingdebit = $resteapayer - $pending;
 
     			print '<form method="POST" action="">';
-    			print '<input type="hidden" name="id" value="' . $object->id . '" />';
+    			print '<input type="hidden" name="id" value="'.$object->id.'" />';
     			print '<input type="hidden" name="action" value="new" />';
-    			print '<label for="withdraw_request_amount">' . $langs->trans('WithdrawRequestAmount') . ' </label>';
-    			print '<input type="text" id="withdraw_request_amount" name="withdraw_request_amount" value="' . $remaintopaylesspendingdebit . '" size="10" />';
+    			print '<label for="withdraw_request_amount">'.$langs->trans('WithdrawRequestAmount').' </label>';
+    			print '<input type="text" id="withdraw_request_amount" name="withdraw_request_amount" value="'.$remaintopaylesspendingdebit.'" size="10" />';
     			print '<input type="submit" class="butAction" value="'.$langs->trans("MakeWithdrawRequest").'" />';
     			print '</form>';
     		}
@@ -596,14 +596,14 @@ if ($object->id > 0)
 	print '</tr>';
 
 	$sql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande";
-	$sql.= " , pfd.date_traite as date_traite, pfd.amount,";
-	$sql.= " u.rowid as user_id, u.lastname, u.firstname, u.login";
-	$sql.= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
-	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on pfd.fk_user_demande = u.rowid";
-	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."prelevement_bons as pb ON pb.rowid = pfd.fk_prelevement_bons";
-	$sql.= " WHERE fk_facture = ".$object->id;
-	$sql.= " AND pfd.traite = 0";
-	$sql.= " ORDER BY pfd.date_demande DESC";
+	$sql .= " , pfd.date_traite as date_traite, pfd.amount,";
+	$sql .= " u.rowid as user_id, u.lastname, u.firstname, u.login";
+	$sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
+	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on pfd.fk_user_demande = u.rowid";
+	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."prelevement_bons as pb ON pb.rowid = pfd.fk_prelevement_bons";
+	$sql .= " WHERE fk_facture = ".$object->id;
+	$sql .= " AND pfd.traite = 0";
+	$sql .= " ORDER BY pfd.date_demande DESC";
 
 	$result_sql = $db->query($sql);
 
@@ -646,14 +646,14 @@ if ($object->id > 0)
 	// Past requests
 
 	$sql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande, pfd.date_traite, pfd.fk_prelevement_bons, pfd.amount,";
-	$sql.= " pb.ref,";
-	$sql.= " u.rowid as user_id, u.lastname, u.firstname, u.login";
-	$sql.= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
-	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on pfd.fk_user_demande = u.rowid";
-	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."prelevement_bons as pb ON pb.rowid = pfd.fk_prelevement_bons";
-	$sql.= " WHERE fk_facture = ".$object->id;
-	$sql.= " AND pfd.traite = 1";
-	$sql.= " ORDER BY pfd.date_demande DESC";
+	$sql .= " pb.ref,";
+	$sql .= " u.rowid as user_id, u.lastname, u.firstname, u.login";
+	$sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
+	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on pfd.fk_user_demande = u.rowid";
+	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."prelevement_bons as pb ON pb.rowid = pfd.fk_prelevement_bons";
+	$sql .= " WHERE fk_facture = ".$object->id;
+	$sql .= " AND pfd.traite = 1";
+	$sql .= " ORDER BY pfd.date_demande DESC";
 
 	$result = $db->query($sql);
 	if ($result)
@@ -677,9 +677,9 @@ if ($object->id > 0)
 			print '<td align="center">';
 			if ($obj->fk_prelevement_bons > 0)
 			{
-				$withdrawreceipt=new BonPrelevement($db);
-				$withdrawreceipt->id=$obj->fk_prelevement_bons;
-				$withdrawreceipt->ref=$obj->ref;
+				$withdrawreceipt = new BonPrelevement($db);
+				$withdrawreceipt->id = $obj->fk_prelevement_bons;
+				$withdrawreceipt->ref = $obj->ref;
 				print $withdrawreceipt->getNomUrl(1);
 			}
 			print "</td>\n";
@@ -694,7 +694,7 @@ if ($object->id > 0)
 			$i++;
 		}
 
-		if (! $numopen && ! $numclosed)
+		if (!$numopen && !$numclosed)
 			print '<tr class="oddeven"><td colspan="7" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
 
 		$db->free($result);

+ 127 - 127
htdocs/compta/paiement.php

@@ -42,21 +42,21 @@ $langs->loadLangs(array('companies', 'bills', 'banks', 'multicurrency'));
 $action		= GETPOST('action', 'alpha');
 $confirm	= GETPOST('confirm', 'alpha');
 
-$facid		= GETPOST('facid', 'int');
-$accountid	= GETPOST('accountid', 'int');
+$facid = GETPOST('facid', 'int');
+$accountid = GETPOST('accountid', 'int');
 $paymentnum	= GETPOST('num_paiement', 'alpha');
 $socid      = GETPOST('socid', 'int');
 
 $sortfield	= GETPOST('sortfield', 'alpha');
 $sortorder	= GETPOST('sortorder', 'alpha');
-$page		= GETPOST('page', 'int');
+$page = GETPOST('page', 'int');
 
-$amounts=array();
-$amountsresttopay=array();
-$addwarning=0;
+$amounts = array();
+$amountsresttopay = array();
+$addwarning = 0;
 
-$multicurrency_amounts=array();
-$multicurrency_amountsresttopay=array();
+$multicurrency_amounts = array();
+$multicurrency_amountsresttopay = array();
 
 // Security check
 if ($user->socid > 0)
@@ -64,24 +64,24 @@ if ($user->socid > 0)
     $socid = $user->socid;
 }
 
-$object=new Facture($db);
+$object = new Facture($db);
 
 // Load object
 if ($facid > 0)
 {
-	$ret=$object->fetch($facid);
+	$ret = $object->fetch($facid);
 }
 
 // Initialize technical object to manage hooks of paiements. Note that conf->hooks_modules contains array array
-$hookmanager->initHooks(array('paiementcard','globalcard'));
+$hookmanager->initHooks(array('paiementcard', 'globalcard'));
 
 
 /*
  * Actions
  */
 
-$parameters=array('socid'=>$socid);
-$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
+$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 (empty($reshook))
@@ -97,7 +97,7 @@ if (empty($reshook))
 	    $atleastonepaymentnotnull = 0;
 
 	    // Generate payment array and check if there is payment higher than invoice and payment date before invoice date
-	    $tmpinvoice=new Facture($db);
+	    $tmpinvoice = new Facture($db);
 	    foreach ($_POST as $key => $value)
 	    {
 			if (substr($key, 0, 7) == 'amount_' && GETPOST($key) != '')
@@ -105,16 +105,16 @@ if (empty($reshook))
 	            $cursorfacid = substr($key, 7);
 	            $amounts[$cursorfacid] = price2num(trim(GETPOST($key)));
 	            $totalpayment = $totalpayment + $amounts[$cursorfacid];
-	            if (! empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++;
-	            $result=$tmpinvoice->fetch($cursorfacid);
+	            if (!empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++;
+	            $result = $tmpinvoice->fetch($cursorfacid);
 	            if ($result <= 0) dol_print_error($db);
-	            $amountsresttopay[$cursorfacid]=price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement());
+	            $amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement());
 	            if ($amounts[$cursorfacid])
 	            {
 		            // Check amount
 		            if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid])))
 		            {
-		                $addwarning=1;
+		                $addwarning = 1;
 		                $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay");
 		            }
 		            // Check date
@@ -126,23 +126,23 @@ if (empty($reshook))
 		            }
 	            }
 
-	            $formquestion[$i++]=array('type' => 'hidden','name' => $key,  'value' => $_POST[$key]);
+	            $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => $_POST[$key]);
 	        }
 			elseif (substr($key, 0, 21) == 'multicurrency_amount_')
 			{
 				$cursorfacid = substr($key, 21);
 	            $multicurrency_amounts[$cursorfacid] = price2num(trim(GETPOST($key)));
 	            $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid];
-	            if (! empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++;
-	            $result=$tmpinvoice->fetch($cursorfacid);
+	            if (!empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++;
+	            $result = $tmpinvoice->fetch($cursorfacid);
 	            if ($result <= 0) dol_print_error($db);
-	            $multicurrency_amountsresttopay[$cursorfacid]=price2num($tmpinvoice->multicurrency_total_ttc - $tmpinvoice->getSommePaiement(1));
+	            $multicurrency_amountsresttopay[$cursorfacid] = price2num($tmpinvoice->multicurrency_total_ttc - $tmpinvoice->getSommePaiement(1));
 	            if ($multicurrency_amounts[$cursorfacid])
 	            {
 		            // Check amount
 		            if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid])))
 		            {
-		                $addwarning=1;
+		                $addwarning = 1;
 		                $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay");
 		            }
 		            // Check date
@@ -154,18 +154,18 @@ if (empty($reshook))
 		            }
 	            }
 
-	            $formquestion[$i++]=array('type' => 'hidden','name' => $key,  'value' => GETPOST($key, 'int'));
+	            $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => GETPOST($key, 'int'));
 			}
 	    }
 
 	    // Check parameters
-	    if (! GETPOST('paiementcode'))
+	    if (!GETPOST('paiementcode'))
 	    {
 	        setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('PaymentMode')), null, 'errors');
 	        $error++;
 	    }
 
-	    if (! empty($conf->banque->enabled))
+	    if (!empty($conf->banque->enabled))
 	    {
 	        // If bank module is on, account is required to enter a payment
 	        if (GETPOST('accountid') <= 0)
@@ -212,7 +212,7 @@ if (empty($reshook))
 	 */
 	if ($action == 'confirm_paiement' && $confirm == 'yes')
 	{
-	    $error=0;
+	    $error = 0;
 
 	    $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
 
@@ -244,7 +244,7 @@ if (empty($reshook))
 	        }
 	    }
 
-	    if (! empty($conf->banque->enabled))
+	    if (!empty($conf->banque->enabled))
 	    {
 	    	// Si module bank actif, un compte est obligatoire lors de la saisie d'un paiement
 	    	if (GETPOST('accountid', 'int') <= 0)
@@ -257,17 +257,17 @@ if (empty($reshook))
 	    // Creation of payment line
 	    $paiement = new Paiement($db);
 	    $paiement->datepaye     = $datepaye;
-	    $paiement->amounts      = $amounts;   // Array with all payments dispatching with invoice id
-	    $paiement->multicurrency_amounts = $multicurrency_amounts;   // Array with all payments dispatching
+	    $paiement->amounts      = $amounts; // Array with all payments dispatching with invoice id
+	    $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
 	    $paiement->paiementid   = dol_getIdFromCode($db, GETPOST('paiementcode'), 'c_paiement', 'code', 'id', 1);
 	    $paiement->num_paiement = GETPOST('num_paiement', 'alpha');
 	    $paiement->note         = GETPOST('comment', 'alpha');
 
-	    if (! $error)
+	    if (!$error)
 	    {
 	        // Create payment and update this->multicurrency_amounts if this->amounts filled or
 	        // this->amounts if this->multicurrency_amounts filled.
-	        $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices')=='on'?1:0), $thirdparty);    // This include closing invoices and regenerating documents
+	        $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices') == 'on' ? 1 : 0), $thirdparty); // This include closing invoices and regenerating documents
 	    	if ($paiement_id < 0)
 	        {
 	            setEventMessages($paiement->error, $paiement->errors, 'errors');
@@ -275,11 +275,11 @@ if (empty($reshook))
 	        }
 	    }
 
-	    if (! $error)
+	    if (!$error)
 	    {
-	    	$label='(CustomerInvoicePayment)';
-	    	if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) $label='(CustomerInvoicePaymentBack)';  // Refund of a credit note
-	        $result=$paiement->addPaymentToBank($user, 'payment', $label, GETPOST('accountid'), GETPOST('chqemetteur'), GETPOST('chqbank'));
+	    	$label = '(CustomerInvoicePayment)';
+	    	if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
+	        $result = $paiement->addPaymentToBank($user, 'payment', $label, GETPOST('accountid'), GETPOST('chqemetteur'), GETPOST('chqbank'));
 	        if ($result < 0)
 	        {
 	            setEventMessages($paiement->error, $paiement->errors, 'errors');
@@ -287,19 +287,19 @@ if (empty($reshook))
 	        }
 	    }
 
-	    if (! $error)
+	    if (!$error)
 	    {
 	        $db->commit();
 
 	        // If payment dispatching on more than one invoice, we stay on summary page, otherwise jump on invoice card
-	        $invoiceid=0;
+	        $invoiceid = 0;
 	        foreach ($paiement->amounts as $key => $amount)
 	        {
 	            $facid = $key;
 	            if (is_numeric($amount) && $amount <> 0)
 	            {
-	                if ($invoiceid != 0) $invoiceid=-1; // There is more than one invoice payed by this payment
-	                else $invoiceid=$facid;
+	                if ($invoiceid != 0) $invoiceid = -1; // There is more than one invoice payed by this payment
+	                else $invoiceid = $facid;
 	            }
 	        }
 	        if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$invoiceid;
@@ -319,7 +319,7 @@ if (empty($reshook))
  * View
  */
 
-$form=new Form($db);
+$form = new Form($db);
 
 
 llxHeader('', $langs->trans("Payment"));
@@ -335,31 +335,31 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 	{
 		$facture->fetch_thirdparty();
 
-		$title='';
-		if ($facture->type != Facture::TYPE_CREDIT_NOTE) $title.=$langs->trans("EnterPaymentReceivedFromCustomer");
-		if ($facture->type == Facture::TYPE_CREDIT_NOTE) $title.=$langs->trans("EnterPaymentDueToCustomer");
+		$title = '';
+		if ($facture->type != Facture::TYPE_CREDIT_NOTE) $title .= $langs->trans("EnterPaymentReceivedFromCustomer");
+		if ($facture->type == Facture::TYPE_CREDIT_NOTE) $title .= $langs->trans("EnterPaymentDueToCustomer");
 		print load_fiche_titre($title);
 
 		// Initialize data for confirmation (this is used because data can be change during confirmation)
 		if ($action == 'add_paiement')
 		{
-			$i=0;
+			$i = 0;
 
-			$formquestion[$i++]=array('type' => 'hidden','name' => 'facid', 'value' => $facture->id);
-			$formquestion[$i++]=array('type' => 'hidden','name' => 'socid', 'value' => $facture->socid);
-			$formquestion[$i++]=array('type' => 'hidden','name' => 'type',  'value' => $facture->type);
+			$formquestion[$i++] = array('type' => 'hidden', 'name' => 'facid', 'value' => $facture->id);
+			$formquestion[$i++] = array('type' => 'hidden', 'name' => 'socid', 'value' => $facture->socid);
+			$formquestion[$i++] = array('type' => 'hidden', 'name' => 'type', 'value' => $facture->type);
 		}
 
 		// Invoice with Paypal transaction
 		// TODO add hook possibility (regis)
-		if (! empty($conf->paypalplus->enabled) && $conf->global->PAYPAL_ENABLE_TRANSACTION_MANAGEMENT && ! empty($facture->ref_int))
+		if (!empty($conf->paypalplus->enabled) && $conf->global->PAYPAL_ENABLE_TRANSACTION_MANAGEMENT && !empty($facture->ref_int))
 		{
-			if (! empty($conf->global->PAYPAL_BANK_ACCOUNT)) $accountid=$conf->global->PAYPAL_BANK_ACCOUNT;
-			$paymentnum=$facture->ref_int;
+			if (!empty($conf->global->PAYPAL_BANK_ACCOUNT)) $accountid = $conf->global->PAYPAL_BANK_ACCOUNT;
+			$paymentnum = $facture->ref_int;
 		}
 
 		// Add realtime total information
-		if (! empty($conf->use_javascript_ajax))
+		if (!empty($conf->use_javascript_ajax))
 		{
 			print "\n".'<script type="text/javascript" language="javascript">';
 			print '$(document).ready(function () {
@@ -478,19 +478,19 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
         // Date payment
         print '<tr><td><span class="fieldrequired">'.$langs->trans('Date').'</span></td><td>';
         $datepayment = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
-        $datepayment= ($datepayment == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE)?-1:'') : $datepayment);
+        $datepayment = ($datepayment == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datepayment);
         print $form->selectDate($datepayment, '', '', '', 0, "add_paiement", 1, 1, 0, '', '', $facture->date);
         print '</td></tr>';
 
         // Payment mode
         print '<tr><td><span class="fieldrequired">'.$langs->trans('PaymentMode').'</span></td><td>';
-        $form->select_types_paiements((GETPOST('paiementcode')?GETPOST('paiementcode'):$facture->mode_reglement_code), 'paiementcode', '', 2);
+        $form->select_types_paiements((GETPOST('paiementcode') ?GETPOST('paiementcode') : $facture->mode_reglement_code), 'paiementcode', '', 2);
         print "</td>\n";
         print '</tr>';
 
         // Bank account
         print '<tr>';
-        if (! empty($conf->banque->enabled))
+        if (!empty($conf->banque->enabled))
         {
             if ($facture->type != 2) print '<td><span class="fieldrequired">'.$langs->trans('AccountToCredit').'</span></td>';
             if ($facture->type == 2) print '<td><span class="fieldrequired">'.$langs->trans('AccountToDebit').'</span></td>';
@@ -511,7 +511,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
         print '<td><input name="num_paiement" type="text" value="'.$paymentnum.'"></td></tr>';
 
         // Check transmitter
-        print '<tr><td class="'.(GETPOST('paiementcode')=='CHQ'?'fieldrequired ':'').'fieldrequireddyn">'.$langs->trans('CheckTransmitter');
+        print '<tr><td class="'.(GETPOST('paiementcode') == 'CHQ' ? 'fieldrequired ' : '').'fieldrequireddyn">'.$langs->trans('CheckTransmitter');
         print ' <em>('.$langs->trans("ChequeMaker").')</em>';
         print '</td>';
         print '<td><input id="fieldchqemetteur" name="chqemetteur" size="30" type="text" value="'.GETPOST('chqemetteur', 'alphanohtml').'"></td></tr>';
@@ -537,30 +537,30 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
          */
 
         $sql = 'SELECT f.rowid as facid, f.ref, f.total_ttc, f.multicurrency_code, f.multicurrency_total_ttc, f.type,';
-        $sql.= ' f.datef as df, f.fk_soc as socid, f.date_lim_reglement as dlr';
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f';
-		$sql.= ' WHERE f.entity IN ('.getEntity('facture').')';
-        $sql.= ' AND (f.fk_soc = '.$facture->socid;
+        $sql .= ' f.datef as df, f.fk_soc as socid, f.date_lim_reglement as dlr';
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
+		$sql .= ' WHERE f.entity IN ('.getEntity('facture').')';
+        $sql .= ' AND (f.fk_soc = '.$facture->socid;
 		// Can pay invoices of all child of parent company
-		if(!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS) && !empty($facture->thirdparty->parent)) {
-			$sql.= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->parent.')';
+		if (!empty($conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS) && !empty($facture->thirdparty->parent)) {
+			$sql .= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->parent.')';
 		}
 		// Can pay invoices of all child of myself
-		if(!empty($conf->global->FACTURE_PAYMENTS_ON_SUBSIDIARY_COMPANIES)){
-			$sql.= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->id.')';
+		if (!empty($conf->global->FACTURE_PAYMENTS_ON_SUBSIDIARY_COMPANIES)) {
+			$sql .= ' OR f.fk_soc IN (SELECT rowid FROM '.MAIN_DB_PREFIX.'societe WHERE parent = '.$facture->thirdparty->id.')';
 		}
-        $sql.= ') AND f.paye = 0';
-        $sql.= ' AND f.fk_statut = 1'; // Statut=0 => not validated, Statut=2 => canceled
+        $sql .= ') AND f.paye = 0';
+        $sql .= ' AND f.fk_statut = 1'; // Statut=0 => not validated, Statut=2 => canceled
         if ($facture->type != Facture::TYPE_CREDIT_NOTE)
         {
-            $sql .= ' AND type IN (0,1,3,5)';	// Standard invoice, replacement, deposit, situation
+            $sql .= ' AND type IN (0,1,3,5)'; // Standard invoice, replacement, deposit, situation
         }
         else
         {
-            $sql .= ' AND type = 2';		// If paying back a credit note, we show all credit notes
+            $sql .= ' AND type = 2'; // If paying back a credit note, we show all credit notes
         }
         // Sort invoices by date and serial number: the older one comes first
-        $sql.=' ORDER BY f.datef ASC, f.ref ASC';
+        $sql .= ' ORDER BY f.datef ASC, f.ref ASC';
 
         $resql = $db->query($sql);
         if ($resql)
@@ -568,14 +568,14 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
             $num = $db->num_rows($resql);
             if ($num > 0)
             {
-				$arraytitle=$langs->trans('Invoice');
-				if ($facture->type == 2) $arraytitle=$langs->trans("CreditNotes");
-				$alreadypayedlabel=$langs->trans('Received');
-				$multicurrencyalreadypayedlabel=$langs->trans('MulticurrencyReceived');
-				if ($facture->type == 2) { $alreadypayedlabel=$langs->trans("PaidBack"); $multicurrencyalreadypayedlabel=$langs->trans("MulticurrencyPaidBack"); }
-				$remaindertopay=$langs->trans('RemainderToTake');
-				$multicurrencyremaindertopay=$langs->trans('MulticurrencyRemainderToTake');
-				if ($facture->type == 2) { $remaindertopay=$langs->trans("RemainderToPayBack"); $multicurrencyremaindertopay=$langs->trans("MulticurrencyRemainderToPayBack"); }
+				$arraytitle = $langs->trans('Invoice');
+				if ($facture->type == 2) $arraytitle = $langs->trans("CreditNotes");
+				$alreadypayedlabel = $langs->trans('Received');
+				$multicurrencyalreadypayedlabel = $langs->trans('MulticurrencyReceived');
+				if ($facture->type == 2) { $alreadypayedlabel = $langs->trans("PaidBack"); $multicurrencyalreadypayedlabel = $langs->trans("MulticurrencyPaidBack"); }
+				$remaindertopay = $langs->trans('RemainderToTake');
+				$multicurrencyremaindertopay = $langs->trans('MulticurrencyRemainderToTake');
+				if ($facture->type == 2) { $remaindertopay = $langs->trans("RemainderToPayBack"); $multicurrencyremaindertopay = $langs->trans("MulticurrencyRemainderToPayBack"); }
 
                 $i = 0;
                 //print '<tr><td colspan="3">';
@@ -598,42 +598,42 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
                 print '<td class="right">'.$remaindertopay.'</td>';
                 print '<td class="right">'.$langs->trans('PaymentAmount').'</td>';
 
-                $parameters=array();
-                $reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $facture, $action); // Note that $action and $object may have been modified by hook
+                $parameters = array();
+                $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $facture, $action); // Note that $action and $object may have been modified by hook
 
                 print '<td align="right">&nbsp;</td>';
                 print "</tr>\n";
 
-                $total=0;
-                $totalrecu=0;
-                $totalrecucreditnote=0;
-                $totalrecudeposits=0;
+                $total = 0;
+                $totalrecu = 0;
+                $totalrecucreditnote = 0;
+                $totalrecudeposits = 0;
 
                 while ($i < $num)
                 {
                     $objp = $db->fetch_object($resql);
 
-                    $sign=1;
-                    if ($facture->type == Facture::TYPE_CREDIT_NOTE) $sign=-1;
+                    $sign = 1;
+                    if ($facture->type == Facture::TYPE_CREDIT_NOTE) $sign = -1;
 
 					$soc = new Societe($db);
 					$soc->fetch($objp->socid);
 
-                    $invoice=new Facture($db);
+                    $invoice = new Facture($db);
                     $invoice->fetch($objp->facid);
                     $paiement = $invoice->getSommePaiement();
-                    $creditnotes=$invoice->getSumCreditNotesUsed();
-                    $deposits=$invoice->getSumDepositsUsed();
-                    $alreadypayed=price2num($paiement + $creditnotes + $deposits, 'MT');
-                    $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
+                    $creditnotes = $invoice->getSumCreditNotesUsed();
+                    $deposits = $invoice->getSumDepositsUsed();
+                    $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT');
+                    $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
 
 					// Multicurrency Price
 					if (!empty($conf->multicurrency->enabled)) {
 						$multicurrency_payment = $invoice->getSommePaiement(1);
-						$multicurrency_creditnotes=$invoice->getSumCreditNotesUsed(1);
-						$multicurrency_deposits=$invoice->getSumDepositsUsed(1);
-						$multicurrency_alreadypayed=price2num($multicurrency_payment + $multicurrency_creditnotes + $multicurrency_deposits, 'MT');
-	                    $multicurrency_remaintopay=price2num($invoice->multicurrency_total_ttc - $multicurrency_payment - $multicurrency_creditnotes - $multicurrency_deposits, 'MT');
+						$multicurrency_creditnotes = $invoice->getSumCreditNotesUsed(1);
+						$multicurrency_deposits = $invoice->getSumDepositsUsed(1);
+						$multicurrency_alreadypayed = price2num($multicurrency_payment + $multicurrency_creditnotes + $multicurrency_deposits, 'MT');
+	                    $multicurrency_remaintopay = price2num($invoice->multicurrency_total_ttc - $multicurrency_payment - $multicurrency_creditnotes - $multicurrency_deposits, 'MT');
 					}
 
 
@@ -648,7 +648,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
                    	print '<td align="center">'.dol_print_date($db->jdate($objp->df), 'day')."</td>\n";
 
                     // Due date
-                    if ($objp->dlr > 0 )
+                    if ($objp->dlr > 0)
                     {
                         print '<td class="nowraponall center">';
                         print dol_print_date($db->jdate($objp->dlr), 'day');
@@ -715,7 +715,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 					}
 
 					// Price
-                    print '<td class="right" '.(($invoice->id==$facid)?' style="font-weight: bold" ':'').'>'.price($sign * $objp->total_ttc).'</td>';
+                    print '<td class="right" '.(($invoice->id == $facid) ? ' style="font-weight: bold" ' : '').'>'.price($sign * $objp->total_ttc).'</td>';
 
                     // Received or paid back
                     print '<td class="right">'.price($sign * $paiement);
@@ -748,8 +748,8 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
                     }
                     print "</td>";
 
-                    $parameters=array();
-                    $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $objp, $action); // Note that $action and $object may have been modified by hook
+                    $parameters = array();
+                    $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $objp, $action); // Note that $action and $object may have been modified by hook
 
                     // Warning
                     print '<td align="center" width="16">';
@@ -763,11 +763,11 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 
                     print "</tr>\n";
 
-                    $total+=$objp->total;
-                    $total_ttc+=$objp->total_ttc;
-                    $totalrecu+=$paiement;
-                    $totalrecucreditnote+=$creditnotes;
-                    $totalrecudeposits+=$deposits;
+                    $total += $objp->total;
+                    $total_ttc += $objp->total_ttc;
+                    $totalrecu += $paiement;
+                    $totalrecucreditnote += $creditnotes;
+                    $totalrecudeposits += $deposits;
                     $i++;
                 }
 
@@ -789,7 +789,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
                     if ($totalrecudeposits) print '+'.price($totalrecudeposits);
                     print '</b></td>';
                     print '<td class="right"><b>'.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits, 'MT')).'</b></td>';
-                    print '<td class="right" id="result" style="font-weight: bold;"></td>';		// Autofilled
+                    print '<td class="right" id="result" style="font-weight: bold;"></td>'; // Autofilled
                     print '<td align="center">&nbsp;</td>';
                     print "</tr>\n";
                 }
@@ -807,10 +807,10 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
         // Bouton Enregistrer
         if ($action != 'add_paiement')
         {
-        	$checkboxlabel=$langs->trans("ClosePaidInvoicesAutomatically");
-        	if ($facture->type == Facture::TYPE_CREDIT_NOTE) $checkboxlabel=$langs->trans("ClosePaidCreditNotesAutomatically");
-        	$buttontitle=$langs->trans('ToMakePayment');
-        	if ($facture->type == Facture::TYPE_CREDIT_NOTE) $buttontitle=$langs->trans('ToMakePaymentBack');
+        	$checkboxlabel = $langs->trans("ClosePaidInvoicesAutomatically");
+        	if ($facture->type == Facture::TYPE_CREDIT_NOTE) $checkboxlabel = $langs->trans("ClosePaidCreditNotesAutomatically");
+        	$buttontitle = $langs->trans('ToMakePayment');
+        	if ($facture->type == Facture::TYPE_CREDIT_NOTE) $buttontitle = $langs->trans('ToMakePaymentBack');
 
         	print '<br><div class="center">';
         	print '<input type="checkbox" checked name="closepaidinvoices"> '.$checkboxlabel;
@@ -826,17 +826,17 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
         // Form to confirm payment
         if ($action == 'add_paiement')
         {
-            $preselectedchoice=$addwarning?'no':'yes';
+            $preselectedchoice = $addwarning ? 'no' : 'yes';
 
             print '<br>';
-            if (!empty($totalpayment)) $text=$langs->trans('ConfirmCustomerPayment', $totalpayment, $langs->trans("Currency".$conf->currency));
+            if (!empty($totalpayment)) $text = $langs->trans('ConfirmCustomerPayment', $totalpayment, $langs->trans("Currency".$conf->currency));
 			if (!empty($multicurrency_totalpayment))
 			{
-				$text.='<br>'.$langs->trans('ConfirmCustomerPayment', $multicurrency_totalpayment, $langs->trans("paymentInInvoiceCurrency"));
+				$text .= '<br>'.$langs->trans('ConfirmCustomerPayment', $multicurrency_totalpayment, $langs->trans("paymentInInvoiceCurrency"));
 			}
             if (GETPOST('closepaidinvoices'))
             {
-                $text.='<br>'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed");
+                $text .= '<br>'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed");
                 print '<input type="hidden" name="closepaidinvoices" value="'.GETPOST('closepaidinvoices').'">';
             }
             print $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$facture->id.'&socid='.$facture->socid.'&type='.$facture->type, $langs->trans('ReceivedCustomersPayments'), $text, 'confirm_paiement', $formquestion, $preselectedchoice);
@@ -850,28 +850,28 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 /**
  *  Show list of payments
  */
-if (! GETPOST('action', 'aZ09'))
+if (!GETPOST('action', 'aZ09'))
 {
     if (empty($page) || $page == -1) $page = 0;
-    $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
-    $offset = $limit * $page ;
+    $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
+    $offset = $limit * $page;
 
-    if (! $sortorder) $sortorder='DESC';
-    if (! $sortfield) $sortfield='p.datep';
+    if (!$sortorder) $sortorder = 'DESC';
+    if (!$sortfield) $sortfield = 'p.datep';
 
     $sql = 'SELECT p.datep as dp, p.amount, f.amount as fa_amount, f.ref';
-    $sql.=', f.rowid as facid, c.libelle as paiement_type, p.num_paiement';
-    $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
-    $sql.= ', '.MAIN_DB_PREFIX.'facture as f';
-    $sql.= ' WHERE p.fk_facture = f.rowid';
-    $sql.= ' AND f.entity IN (' . getEntity('invoice').')';
+    $sql .= ', f.rowid as facid, c.libelle as paiement_type, p.num_paiement';
+    $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
+    $sql .= ', '.MAIN_DB_PREFIX.'facture as f';
+    $sql .= ' WHERE p.fk_facture = f.rowid';
+    $sql .= ' AND f.entity IN ('.getEntity('invoice').')';
     if ($socid)
     {
-        $sql.= ' AND f.fk_soc = '.$socid;
+        $sql .= ' AND f.fk_soc = '.$socid;
     }
 
-    $sql.= ' ORDER BY '.$sortfield.' '.$sortorder;
-    $sql.= $db->plimit($limit+1, $offset);
+    $sql .= ' ORDER BY '.$sortfield.' '.$sortorder;
+    $sql .= $db->plimit($limit + 1, $offset);
     $resql = $db->query($sql);
 
     if ($resql)
@@ -901,8 +901,8 @@ if (! GETPOST('action', 'aZ09'))
             print '<td>&nbsp;</td>';
             print '</tr>';
 
-            $parameters=array();
-            $reshook=$hookmanager->executeHooks('printObjectLine', $parameters, $objp, $action); // Note that $action and $object may have been modified by hook
+            $parameters = array();
+            $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $objp, $action); // Note that $action and $object may have been modified by hook
 
             $i++;
         }

+ 49 - 49
htdocs/contact/agenda.php

@@ -39,7 +39,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-require_once DOL_DOCUMENT_ROOT. '/core/class/html.form.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
@@ -47,12 +47,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 // Load translation files required by the page
 $langs->loadLangs(array('companies', 'users', 'other', 'commercial'));
 
-$mesg=''; $error=0; $errors=array();
+$mesg = ''; $error = 0; $errors = array();
 
 $action		= (GETPOST('action', 'alpha') ? GETPOST('action', 'alpha') : 'view');
 $confirm	= GETPOST('confirm', 'alpha');
 $backtopage = GETPOST('backtopage', 'alpha');
-$id			= GETPOST('id', 'int');
+$id = GETPOST('id', 'int');
 $socid		= GETPOST('socid', 'int');
 
 $object = new Contact($db);
@@ -63,9 +63,9 @@ $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Get object canvas (By default, this is not defined, so standard usage of dolibarr)
 $object->getCanvas($id);
-$objcanvas=null;
-$canvas = (! empty($object->canvas)?$object->canvas:GETPOST("canvas"));
-if (! empty($canvas))
+$objcanvas = null;
+$canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas"));
+if (!empty($canvas))
 {
     require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
     $objcanvas = new Canvas($db, $action);
@@ -95,25 +95,25 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (! $sortfield) $sortfield='a.datep, a.id';
-if (! $sortorder) $sortorder='DESC';
+if (!$sortfield) $sortfield = 'a.datep, a.id';
+if (!$sortorder) $sortorder = 'DESC';
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('contactagenda','globalcard'));
+$hookmanager->initHooks(array('contactagenda', 'globalcard'));
 
 
 /*
  *	Actions
  */
 
-$parameters=array('id'=>$id, 'objcanvas'=>$objcanvas);
-$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
+$parameters = array('id'=>$id, 'objcanvas'=>$objcanvas);
+$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))
+    if (GETPOST('cancel', 'alpha') && !empty($backtopage))
     {
         header("Location: ".$backtopage);
         exit;
@@ -122,8 +122,8 @@ 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
     {
-        $actioncode='';
-        $search_agenda_label='';
+        $actioncode = '';
+        $search_agenda_label = '';
     }
 }
 
@@ -134,9 +134,9 @@ if (empty($reshook))
 
 $form = new Form($db);
 
-$title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
-if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title=$object->lastname;
-$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
+$title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname;
+$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
 llxHeader('', $title, $help_url);
 
 
@@ -154,11 +154,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
     if (empty($object->error) && $id)
  	{
  		$object = new Contact($db);
- 		$result=$object->fetch($id);
+ 		$result = $object->fetch($id);
 		if ($result <= 0) dol_print_error('', $object->error);
  	}
-   	$objcanvas->assign_values($action, $object->id, $object->ref);	// Set value for templates
-    $objcanvas->display_canvas($action);							// Show template
+   	$objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates
+    $objcanvas->display_canvas($action); // Show template
 }
 else
 {
@@ -171,30 +171,30 @@ else
     {
         if ($action == 'delete')
         {
-            print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage?'&backtopage='.$backtopage:''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1);
+            print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage ? '&backtopage='.$backtopage : ''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1);
         }
     }
 
     /*
      * Onglets
      */
-    $head=array();
+    $head = array();
     if ($id > 0)
     {
         // Si edition contact deja existant
         $object = new Contact($db);
-        $res=$object->fetch($id, $user);
+        $res = $object->fetch($id, $user);
         if ($res < 0) { dol_print_error($db, $object->error); exit; }
-        $res=$object->fetch_optionals();
+        $res = $object->fetch_optionals();
         if ($res < 0) { dol_print_error($db, $object->error); exit; }
 
         // Show tabs
         $head = contact_prepare_head($object);
 
-        $title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
+        $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
     }
 
-    if (! empty($id) && $action != 'edit' && $action != 'create')
+    if (!empty($id) && $action != 'edit' && $action != 'create')
     {
         $objsoc = new Societe($db);
 
@@ -208,17 +208,17 @@ else
 
         $linkback = '<a href="'.DOL_URL_ROOT.'/contact/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-        $morehtmlref='<div class="refidno">';
+        $morehtmlref = '<div class="refidno">';
         if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))
         {
-            $objsoc=new Societe($db);
+            $objsoc = new Societe($db);
             $objsoc->fetch($object->socid);
             // Thirdparty
-            $morehtmlref.=$langs->trans('ThirdParty') . ' : ';
-            if ($objsoc->id > 0) $morehtmlref.=$objsoc->getNomUrl(1);
-            else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany");
+            $morehtmlref .= $langs->trans('ThirdParty').' : ';
+            if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1);
+            else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany");
         }
-        $morehtmlref.='</div>';
+        $morehtmlref .= '</div>';
 
         dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref);
 
@@ -236,17 +236,17 @@ else
 
     	// Actions buttons
 
-        $objcon=$object;
+        $objcon = $object;
         $object->fetch_thirdparty();
-        $objthirdparty=$object->thirdparty;
+        $objthirdparty = $object->thirdparty;
 
-        $out='';
-        $permok=$user->rights->agenda->myactions->create;
-        if ((! empty($objthirdparty->id) || ! empty($objcon->id)) && $permok)
+        $out = '';
+        $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 (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') $out.='&amp;socid='.$objthirdparty->id;
-            $out.=(! empty($objcon->id)?'&amp;contactid='.$objcon->id:'').'&amp;backtopage=1&amp;percentage=-1';
+            if (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') $out .= '&amp;socid='.$objthirdparty->id;
+            $out .= (!empty($objcon->id) ? '&amp;contactid='.$objcon->id : '').'&amp;backtopage=1&amp;percentage=-1';
         	//$out.=$langs->trans("AddAnAction").' ';
         	//$out.=img_picto($langs->trans("AddAnAction"),'filenew');
         	//$out.="</a>";
@@ -256,29 +256,29 @@ else
     	//print '<div class="tabsAction">';
         //print '</div>';
 
-    	$newcardbutton='';
-    	if (! empty($conf->agenda->enabled))
+    	$newcardbutton = '';
+    	if (!empty($conf->agenda->enabled))
     	{
-    		if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create))
+    		if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create))
     		{
-                $newcardbutton.= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out);
+                $newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out);
     		}
     	}
 
-        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)))
        	{
        		print '<br>';
 
-            $param='&id='.$id;
-            if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
-            if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
+            $param = '&id='.$id;
+            if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
+            if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
 
             print load_fiche_titre($langs->trans("ActionsOnContact"), $newcardbutton, '');
             //print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $morehtmlcenter, 0, -1, '', '', '', '', 0, 1, 1);
 
             // List of all actions
-    		$filters=array();
-        	$filters['search_agenda_label']=$search_agenda_label;
+    		$filters = array();
+        	$filters['search_agenda_label'] = $search_agenda_label;
 
             show_actions_done($conf, $langs, $db, $objthirdparty, $object, 0, $actioncode, '', $filters, $sortfield, $sortorder);
         }

+ 151 - 151
htdocs/contact/card.php

@@ -48,12 +48,12 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
 // Load translation files required by the page
 $langs->loadLangs(array('companies', 'users', 'other', 'commercial'));
 
-$mesg=''; $error=0; $errors=array();
+$mesg = ''; $error = 0; $errors = array();
 
-$action		= (GETPOST('action', 'alpha') ? GETPOST('action', 'alpha') : 'view');
-$confirm		= GETPOST('confirm', 'alpha');
-$backtopage	= GETPOST('backtopage', 'alpha');
-$id			= GETPOST('id', 'int');
+$action = (GETPOST('action', 'alpha') ? GETPOST('action', 'alpha') : 'view');
+$confirm = GETPOST('confirm', 'alpha');
+$backtopage = GETPOST('backtopage', 'alpha');
+$id = GETPOST('id', 'int');
 $socid		= GETPOST('socid', 'int');
 
 $object = new Contact($db);
@@ -66,9 +66,9 @@ $socialnetworks = getArrayOfSocialNetworks();
 
 // Get object canvas (By default, this is not defined, so standard usage of dolibarr)
 $object->getCanvas($id);
-$objcanvas=null;
-$canvas = (! empty($object->canvas)?$object->canvas:GETPOST("canvas"));
-if (! empty($canvas))
+$objcanvas = null;
+$canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas"));
+if (!empty($canvas))
 {
     require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
     $objcanvas = new Canvas($db, $action);
@@ -120,30 +120,30 @@ if (empty($reshook))
 
             // Creation user
             $nuser = new User($db);
-            $result=$nuser->create_from_contact($object, GETPOST("login"));	// Do not use GETPOST(alpha)
+            $result = $nuser->create_from_contact($object, GETPOST("login")); // Do not use GETPOST(alpha)
 
             if ($result > 0)
             {
-                $result2=$nuser->setPassword($user, GETPOST("password"), 0, 0, 1);	// Do not use GETPOST(alpha)
+                $result2 = $nuser->setPassword($user, GETPOST("password"), 0, 0, 1); // Do not use GETPOST(alpha)
                 if ($result2)
                 {
                     $db->commit();
                 }
                 else
                 {
-                    $error=$nuser->error; $errors=$nuser->errors;
+                    $error = $nuser->error; $errors = $nuser->errors;
                     $db->rollback();
                 }
             }
             else
             {
-                $error=$nuser->error; $errors=$nuser->errors;
+                $error = $nuser->error; $errors = $nuser->errors;
                 $db->rollback();
             }
         }
         else
         {
-            $error=$object->error; $errors=$object->errors;
+            $error = $object->error; $errors = $object->errors;
         }
     }
 
@@ -152,7 +152,7 @@ if (empty($reshook))
 	if ($action == 'disable')
 	{
 		$object->fetch($id);
-		if ($object->setstatus(0)<0)
+		if ($object->setstatus(0) < 0)
 		{
 			setEventMessages($object->error, $object->errors, 'errors');
 		}
@@ -167,7 +167,7 @@ if (empty($reshook))
 	if ($action == 'enable')
 	{
 		$object->fetch($id);
-		if ($object->setstatus(1)<0)
+		if ($object->setstatus(1) < 0)
 		{
 			setEventMessages($object->error, $object->errors, 'errors');
 		}
@@ -232,18 +232,18 @@ if (empty($reshook))
 			$action = 'create';
 		}
 
-        if (! GETPOST("lastname"))
+        if (!GETPOST("lastname"))
         {
-            $error++; $errors[]=$langs->trans("ErrorFieldRequired", $langs->transnoentities("Lastname").' / '.$langs->transnoentities("Label"));
+            $error++; $errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Lastname").' / '.$langs->transnoentities("Label"));
             $action = 'create';
         }
 
-        if (! $error)
+        if (!$error)
         {
-            $id =  $object->create($user);
+            $id = $object->create($user);
             if ($id <= 0)
             {
-                $error++; $errors=array_merge($errors, ($object->error?array($object->error):$object->errors));
+                $error++; $errors = array_merge($errors, ($object->error ? array($object->error) : $object->errors));
                 $action = 'create';
 			} else {
 				// Categories association
@@ -268,11 +268,11 @@ if (empty($reshook))
 			}
         }
 
-        if (! $error && $id > 0)
+        if (!$error && $id > 0)
         {
             $db->commit();
-            if (! empty($backtopage)) $url=$backtopage;
-            else $url='card.php?id='.$id;
+            if (!empty($backtopage)) $url = $backtopage;
+            else $url = 'card.php?id='.$id;
             header("Location: ".$url);
             exit;
         }
@@ -310,17 +310,17 @@ if (empty($reshook))
         }
     }
 
-    if ($action == 'update' && ! $_POST["cancel"] && $user->rights->societe->contact->creer)
+    if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact->creer)
     {
         if (empty($_POST["lastname"]))
         {
-            $error++; $errors=array($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name").' / '.$langs->transnoentities("Label")));
+            $error++; $errors = array($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name").' / '.$langs->transnoentities("Label")));
             $action = 'edit';
         }
 
-		if (! $error)
+		if (!$error)
 		{
-			$contactid=GETPOST("contactid", 'int');
+			$contactid = GETPOST("contactid", 'int');
 			$object->fetch($contactid);
 
 			// Photo save
@@ -328,8 +328,8 @@ if (empty($reshook))
             $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']);
             if (GETPOST('deletephoto') && $object->photo)
             {
-                $fileimg=$dir.'/'.$object->photo;
-                $dirthumbs=$dir.'/thumbs';
+                $fileimg = $dir.'/'.$object->photo;
+                $dirthumbs = $dir.'/thumbs';
                 dol_delete_file($fileimg);
                 dol_delete_dir_recursive($dirthumbs);
                 $object->photo = '';
@@ -342,10 +342,10 @@ if (empty($reshook))
 
                     if (@is_dir($dir))
                     {
-                        $newfile=$dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']);
+                        $newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']);
                         $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1);
 
-                        if (! $result > 0)
+                        if (!$result > 0)
                         {
                             $errors[] = "ErrorFailedToSaveFile";
                         }
@@ -365,7 +365,7 @@ if (empty($reshook))
             }
             else
             {
-                switch($_FILES['photo']['error'])
+                switch ($_FILES['photo']['error'])
                 {
                     case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
                     case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
@@ -459,8 +459,8 @@ if (empty($reshook))
 	    				$object->no_email = $no_email;
     				}
 
-    				$object->old_lastname='';
-    				$object->old_firstname='';
+    				$object->old_lastname = '';
+    				$object->old_firstname = '';
     				$action = 'view';
     			}
     			else
@@ -471,9 +471,9 @@ if (empty($reshook))
 			}
         }
 
-        if (! $error && empty($errors))
+        if (!$error && empty($errors))
         {
-       		if (! empty($backtopage))
+       		if (!empty($backtopage))
        		{
        			header("Location: ".$backtopage);
        			exit;
@@ -482,9 +482,9 @@ if (empty($reshook))
     }
 
     // Actions to send emails
-	$trigger_name='CONTACT_SENTBYMAIL';
-	$paramname='id';
-	$mode='emailfromcontact';
+	$trigger_name = 'CONTACT_SENTBYMAIL';
+	$paramname = 'id';
+	$mode = 'emailfromcontact';
 	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
 }
 
@@ -494,15 +494,15 @@ if (empty($reshook))
  */
 
 
-$title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
-if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title=$object->lastname;
-$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
+$title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
+if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname;
+$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
 llxHeader('', $title, $help_url);
 
 $form = new Form($db);
 $formcompany = new FormCompany($db);
 
-$countrynotdefined=$langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')';
+$countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')';
 
 if ($socid > 0)
 {
@@ -518,11 +518,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
     if (empty($object->error) && $id)
  	{
  		$object = new Contact($db);
- 		$result=$object->fetch($id);
+ 		$result = $object->fetch($id);
 		if ($result <= 0) dol_print_error('', $object->error);
  	}
-   	$objcanvas->assign_values($action, $object->id, $object->ref);	// Set value for templates
-    $objcanvas->display_canvas($action);							// Show template
+   	$objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates
+    $objcanvas->display_canvas($action); // Show template
 }
 else
 {
@@ -535,27 +535,27 @@ else
     {
         if ($action == 'delete')
         {
-            print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage?'&backtopage='.$backtopage:''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1);
+            print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage ? '&backtopage='.$backtopage : ''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1);
         }
     }
 
     /*
      * Onglets
      */
-    $head=array();
+    $head = array();
     if ($id > 0)
     {
         // Si edition contact deja existant
         $object = new Contact($db);
-        $res=$object->fetch($id, $user);
-        if ($res<0) {
+        $res = $object->fetch($id, $user);
+        if ($res < 0) {
         	setEventMessages($object->error, $object->errors, 'errors');
         }
 
         // Show tabs
         $head = contact_prepare_head($object);
 
-        $title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
+        $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses"));
     }
 
     if ($user->rights->societe->contact->creer)
@@ -565,25 +565,25 @@ else
             /*
              * Fiche en mode creation
              */
-            $object->canvas=$canvas;
+            $object->canvas = $canvas;
 
             $object->state_id = GETPOST("state_id");
 
             // We set country_id, country_code and label for the selected country
-            $object->country_id=$_POST["country_id"]?GETPOST("country_id"):(empty($objsoc->country_id)?$mysoc->country_id:$objsoc->country_id);
+            $object->country_id = $_POST["country_id"] ?GETPOST("country_id") : (empty($objsoc->country_id) ? $mysoc->country_id : $objsoc->country_id);
             if ($object->country_id)
             {
-            	$tmparray=getCountry($object->country_id, 'all');
+            	$tmparray = getCountry($object->country_id, 'all');
                 $object->country_code = $tmparray['code'];
                 $object->country      = $tmparray['label'];
             }
 
-            $title = $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
-            $linkback='';
+            $title = $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
+            $linkback = '';
             print load_fiche_titre($title, $linkback, 'address');
 
             // Show errors
-            dol_htmloutput_errors(is_numeric($error)?'':$error, $errors);
+            dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors);
 
             if ($conf->use_javascript_ajax)
             {
@@ -612,7 +612,7 @@ else
             print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
             print '<input type="hidden" name="action" value="add">';
             print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
-			if (! empty($objsoc)) {
+			if (!empty($objsoc)) {
 				print '<input type="hidden" name="entity" value="'.$objsoc->entity.'">';
             }
 
@@ -622,9 +622,9 @@ else
 
             // Name
             print '<tr><td class="titlefieldcreate fieldrequired"><label for="lastname">'.$langs->trans("Lastname").' / '.$langs->trans("Label").'</label></td>';
-            print '<td><input name="lastname" id="lastname" type="text" class="maxwidth100onsmartphone" maxlength="80" value="'.dol_escape_htmltag(GETPOST("lastname", 'alpha')?GETPOST("lastname", 'alpha'):$object->lastname).'" autofocus="autofocus"></td>';
+            print '<td><input name="lastname" id="lastname" type="text" class="maxwidth100onsmartphone" maxlength="80" value="'.dol_escape_htmltag(GETPOST("lastname", 'alpha') ?GETPOST("lastname", 'alpha') : $object->lastname).'" autofocus="autofocus"></td>';
             print '<td><label for="firstname">'.$langs->trans("Firstname").'</label></td>';
-            print '<td><input name="firstname" id="firstname"type="text" class="maxwidth100onsmartphone" maxlength="80" value="'.dol_escape_htmltag(GETPOST("firstname", 'alpha')?GETPOST("firstname", 'alpha'):$object->firstname).'"></td></tr>';
+            print '<td><input name="firstname" id="firstname"type="text" class="maxwidth100onsmartphone" maxlength="80" value="'.dol_escape_htmltag(GETPOST("firstname", 'alpha') ?GETPOST("firstname", 'alpha') : $object->firstname).'"></td></tr>';
 
             // Company
             if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))
@@ -673,23 +673,23 @@ else
             print '</tr>';
 
             // Zip / Town
-            if (($objsoc->typent_code == 'TE_PRIVATE' || ! empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->zip)) == 0) $object->zip = $objsoc->zip;			// Predefined with third party
-            if (($objsoc->typent_code == 'TE_PRIVATE' || ! empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->town)) == 0) $object->town = $objsoc->town;	// Predefined with third party
+            if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->zip)) == 0) $object->zip = $objsoc->zip; // Predefined with third party
+            if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->town)) == 0) $object->town = $objsoc->town; // Predefined with third party
             print '<tr><td><label for="zipcode">'.$langs->trans("Zip").'</label> / <label for="town">'.$langs->trans("Town").'</label></td><td colspan="'.$colspan.'" class="maxwidthonsmartphone">';
-            print $formcompany->select_ziptown((GETPOST("zipcode", 'alpha')?GETPOST("zipcode", 'alpha'):$object->zip), 'zipcode', array('town','selectcountry_id','state_id'), 6).'&nbsp;';
-            print $formcompany->select_ziptown((GETPOST("town", 'alpha')?GETPOST("town", 'alpha'):$object->town), 'town', array('zipcode','selectcountry_id','state_id'));
+            print $formcompany->select_ziptown((GETPOST("zipcode", 'alpha') ?GETPOST("zipcode", 'alpha') : $object->zip), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6).'&nbsp;';
+            print $formcompany->select_ziptown((GETPOST("town", 'alpha') ?GETPOST("town", 'alpha') : $object->town), 'town', array('zipcode', 'selectcountry_id', 'state_id'));
             print '</td></tr>';
 
             // Country
             print '<tr><td><label for="selectcountry_id">'.$langs->trans("Country").'</label></td><td colspan="'.$colspan.'" class="maxwidthonsmartphone">';
-            print $form->select_country((GETPOST("country_id", 'alpha')?GETPOST("country_id", 'alpha'):$object->country_id), 'country_id');
+            print $form->select_country((GETPOST("country_id", 'alpha') ?GETPOST("country_id", 'alpha') : $object->country_id), 'country_id');
             if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
             print '</td></tr>';
 
             // State
             if (empty($conf->global->SOCIETE_DISABLE_STATE))
             {
-                if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2))
+                if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2))
                 {
                     print '<tr><td><label for="state_id">'.$langs->trans('Region-State').'</label></td><td colspan="'.$colspan.'" class="maxwidthonsmartphone">';
                 }
@@ -700,7 +700,7 @@ else
 
                 if ($object->country_id)
                 {
-                    print $formcompany->select_state(GETPOST("state_id", 'alpha')?GETPOST("state_id", 'alpha'):$object->state_id, $object->country_code, 'state_id');
+                    print $formcompany->select_state(GETPOST("state_id", 'alpha') ?GETPOST("state_id", 'alpha') : $object->state_id, $object->country_code, 'state_id');
                 }
                 else
                 {
@@ -816,7 +816,7 @@ else
 
 	        // Contact by default
 	        if (!empty($socid)) {
-		        print '<tr><td>' . $langs->trans("ContactByDefaultFor") . '</td>';
+		        print '<tr><td>'.$langs->trans("ContactByDefaultFor").'</td>';
 		        print '<td colspan="3">';
 		        $contactType = $object->listeTypeContacts('external', '', 1);
 		        print $form->multiselectarray('roles', $contactType);
@@ -824,8 +824,8 @@ else
 	        }
 
             // Other attributes
-            $parameters=array('socid' => $socid, 'objsoc' => $objsoc, 'colspan' => ' colspan="3"', 'cols' => 3);
-            $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+            $parameters = array('socid' => $socid, 'objsoc' => $objsoc, 'colspan' => ' colspan="3"', 'cols' => 3);
+            $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
             print $hookmanager->resPrint;
             if (empty($reshook))
             {
@@ -843,7 +843,7 @@ else
 
             // Date To Birth
             print '<tr><td width="20%"><label for="birthday">'.$langs->trans("DateToBirth").'</label></td><td width="30%">';
-            $form=new Form($db);
+            $form = new Form($db);
             if ($object->birthday)
             {
                 print $form->selectDate($object->birthday, 'birthday', 0, 0, 0, "perso", 1, 0);
@@ -871,7 +871,7 @@ else
 
             print '<div class="center">';
             print '<input type="submit" class="button" name="add" value="'.$langs->trans("Add").'">';
-            if (! empty($backtopage))
+            if (!empty($backtopage))
             {
                 print ' &nbsp; &nbsp; ';
                 print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
@@ -879,13 +879,13 @@ else
             else
             {
                 print ' &nbsp; &nbsp; ';
-                print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
+                print '<input type="button" class="button" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
             }
             print '</div>';
 
             print "</form>";
         }
-        elseif ($action == 'edit' && ! empty($id))
+        elseif ($action == 'edit' && !empty($id))
         {
             /*
              * Fiche en mode edition
@@ -894,16 +894,16 @@ else
             // We set country_id, and country_code label of the chosen country
             if (isset($_POST["country_id"]) || $object->country_id)
             {
-	            $tmparray=getCountry($object->country_id, 'all');
-	            $object->country_code =	$tmparray['code'];
-	            $object->country      =	$tmparray['label'];
+	            $tmparray = getCountry($object->country_id, 'all');
+	            $object->country_code = $tmparray['code'];
+	            $object->country      = $tmparray['label'];
             }
 
 			$objsoc = new Societe($db);
 			$objsoc->fetch($object->socid);
 
 			// Show errors
-			dol_htmloutput_errors(is_numeric($error)?'':$error, $errors);
+			dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors);
 
             if ($conf->use_javascript_ajax)
             {
@@ -951,12 +951,12 @@ else
 
             // Lastname
             print '<tr><td class="titlefieldcreate fieldrequired"><label for="lastname">'.$langs->trans("Lastname").' / '.$langs->trans("Label").'</label></td>';
-            print '<td colspan="3"><input name="lastname" id="lastname" type="text" class="minwidth200" maxlength="80" value="'.(isset($_POST["lastname"])?GETPOST("lastname"):$object->lastname).'" autofocus="autofocus"></td>';
+            print '<td colspan="3"><input name="lastname" id="lastname" type="text" class="minwidth200" maxlength="80" value="'.(isset($_POST["lastname"]) ?GETPOST("lastname") : $object->lastname).'" autofocus="autofocus"></td>';
             print '</tr>';
             print '<tr>';
             // Firstname
             print '<td><label for="firstname">'.$langs->trans("Firstname").'</label></td>';
-	        print '<td colspan="3"><input name="firstname" id="firstname" type="text" class="minwidth200" maxlength="80" value="'.(isset($_POST["firstname"])?GETPOST("firstname"):$object->firstname).'"></td>';
+	        print '<td colspan="3"><input name="firstname" id="firstname" type="text" class="minwidth200" maxlength="80" value="'.(isset($_POST["firstname"]) ?GETPOST("firstname") : $object->firstname).'"></td>';
 	        print '</tr>';
 
             // Company
@@ -989,20 +989,20 @@ else
 
             // Zip / Town
             print '<tr><td><label for="zipcode">'.$langs->trans("Zip").'</label> / <label for="town">'.$langs->trans("Town").'</label></td><td colspan="3" class="maxwidthonsmartphone">';
-            print $formcompany->select_ziptown((isset($_POST["zipcode"])?GETPOST("zipcode"):$object->zip), 'zipcode', array('town','selectcountry_id','state_id'), 6).'&nbsp;';
-            print $formcompany->select_ziptown((isset($_POST["town"])?GETPOST("town"):$object->town), 'town', array('zipcode','selectcountry_id','state_id'));
+            print $formcompany->select_ziptown((isset($_POST["zipcode"]) ?GETPOST("zipcode") : $object->zip), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6).'&nbsp;';
+            print $formcompany->select_ziptown((isset($_POST["town"]) ?GETPOST("town") : $object->town), 'town', array('zipcode', 'selectcountry_id', 'state_id'));
             print '</td></tr>';
 
             // Country
             print '<tr><td><label for="selectcountry_id">'.$langs->trans("Country").'</label></td><td colspan="3" class="maxwidthonsmartphone">';
-            print $form->select_country(isset($_POST["country_id"])?GETPOST("country_id"):$object->country_id, 'country_id');
+            print $form->select_country(isset($_POST["country_id"]) ?GETPOST("country_id") : $object->country_id, 'country_id');
             if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
             print '</td></tr>';
 
             // State
             if (empty($conf->global->SOCIETE_DISABLE_STATE))
             {
-                if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2))
+                if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2))
                 {
                     print '<tr><td><label for="state_id">'.$langs->trans('Region-State').'</label></td><td colspan="3" class="maxwidthonsmartphone">';
                 }
@@ -1043,23 +1043,23 @@ else
 
             // Unsubscribe
             print '<tr>';
-            if (! empty($conf->mailing->enabled))
+            if (!empty($conf->mailing->enabled))
             {
             	$noemail = '';
-            	if (empty($noemail) && ! empty($object->email))
+            	if (empty($noemail) && !empty($object->email))
             	{
-            		$sql="SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'";
+            		$sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'";
             		//print $sql;
-            		$resql=$db->query($sql);
+            		$resql = $db->query($sql);
             		if ($resql)
             		{
-            			$obj=$db->fetch_object($resql);
+            			$obj = $db->fetch_object($resql);
             			$noemail = $obj->nb;
             		}
             	}
 
             	print '<td><label for="no_email">'.$langs->trans("No_Email").'</label></td>';
-	            print '<td>'.$form->selectyesno('no_email', (GETPOSTISSET("no_email")?GETPOST("no_email", 'alpha'):$noemail), 1).'</td>';
+	            print '<td>'.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ?GETPOST("no_email", 'alpha') : $noemail), 1).'</td>';
             }
             else
 			{
@@ -1141,7 +1141,7 @@ else
 
 			// Categories
 			if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) {
-				print '<tr><td>' . $form->editfieldkey('Categories', 'contcats', '', $object, 0) . '</td>';
+				print '<tr><td>'.$form->editfieldkey('Categories', 'contcats', '', $object, 0).'</td>';
 				print '<td colspan="3">';
 				$cate_arbo = $form->select_all_categories(Categorie::TYPE_CONTACT, null, null, null, null, 1);
 				$c = new Categorie($db);
@@ -1155,15 +1155,15 @@ else
 
 			// Contact by default
 	        if (!empty($object->socid)) {
-		        print '<tr><td>' . $langs->trans("ContactByDefaultFor") . '</td>';
+		        print '<tr><td>'.$langs->trans("ContactByDefaultFor").'</td>';
 		        print '<td colspan="3">';
 		        print $formcompany->showRoles("roles", $object, 'edit', $object->roles);
 		        print '</td></tr>';
 	        }
 
             // Other attributes
-            $parameters=array('colspan' => ' colspan="3"', 'cols'=>3);
-            $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+            $parameters = array('colspan' => ' colspan="3"', 'cols'=>3);
+            $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
             print $hookmanager->resPrint;
             if (empty($reshook))
             {
@@ -1172,31 +1172,31 @@ else
 
             $object->load_ref_elements();
 
-            if (! empty($conf->commande->enabled))
+            if (!empty($conf->commande->enabled))
             {
                 print '<tr><td>'.$langs->trans("ContactForOrders").'</td><td colspan="3">';
-                print $object->ref_commande?$object->ref_commande:$langs->trans("NoContactForAnyOrder");
+                print $object->ref_commande ? $object->ref_commande : $langs->trans("NoContactForAnyOrder");
                 print '</td></tr>';
             }
 
-            if (! empty($conf->propal->enabled))
+            if (!empty($conf->propal->enabled))
             {
                 print '<tr><td>'.$langs->trans("ContactForProposals").'</td><td colspan="3">';
-                print $object->ref_propal?$object->ref_propal:$langs->trans("NoContactForAnyProposal");
+                print $object->ref_propal ? $object->ref_propal : $langs->trans("NoContactForAnyProposal");
                 print '</td></tr>';
             }
 
-            if (! empty($conf->contrat->enabled))
+            if (!empty($conf->contrat->enabled))
             {
                 print '<tr><td>'.$langs->trans("ContactForContracts").'</td><td colspan="3">';
-                print $object->ref_contrat?$object->ref_contrat:$langs->trans("NoContactForAnyContract");
+                print $object->ref_contrat ? $object->ref_contrat : $langs->trans("NoContactForAnyContract");
                 print '</td></tr>';
             }
 
-            if (! empty($conf->facture->enabled))
+            if (!empty($conf->facture->enabled))
             {
                 print '<tr><td>'.$langs->trans("ContactForInvoices").'</td><td colspan="3">';
-                print $object->ref_facturation?$object->ref_facturation:$langs->trans("NoContactForAnyInvoice");
+                print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice");
                 print '</td></tr>';
             }
 
@@ -1204,8 +1204,8 @@ else
             print '<tr><td>'.$langs->trans("DolibarrLogin").'</td><td colspan="3">';
             if ($object->user_id)
             {
-                $dolibarr_user=new User($db);
-                $result=$dolibarr_user->fetch($object->user_id);
+                $dolibarr_user = new User($db);
+                $result = $dolibarr_user->fetch($object->user_id);
                 print $dolibarr_user->getLoginUrl(1);
             }
             else print $langs->trans("NoDolibarrAccess");
@@ -1242,14 +1242,14 @@ else
         }
     }
 
-    if (! empty($id) && $action != 'edit' && $action != 'create')
+    if (!empty($id) && $action != 'edit' && $action != 'create')
     {
         $objsoc = new Societe($db);
 
         // View mode
 
         // Show errors
-        dol_htmloutput_errors(is_numeric($error)?'':$error, $errors);
+        dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors);
 
         dol_fiche_head($head, 'card', $title, -1, 'contact');
 
@@ -1257,15 +1257,15 @@ else
         {
             // Full firstname and lastname separated with a dot : firstname.lastname
             include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
-            $login=dol_buildlogin($object->lastname, $object->firstname);
+            $login = dol_buildlogin($object->lastname, $object->firstname);
 
-            $generated_password='';
-            if (! $ldap_sid) // TODO ldap_sid ?
+            $generated_password = '';
+            if (!$ldap_sid) // TODO ldap_sid ?
             {
                 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
-                $generated_password=getRandomPassword(false);
+                $generated_password = getRandomPassword(false);
             }
-            $password=$generated_password;
+            $password = $generated_password;
 
             // Create a form array
             $formquestion = array(
@@ -1273,27 +1273,27 @@ else
                 array('label' => $langs->trans("Password"), 'type' => 'text', 'name' => 'password', 'value' => $password),
                 //array('label' => $form->textwithpicto($langs->trans("Type"),$langs->trans("InternalExternalDesc")), 'type' => 'select', 'name' => 'intern', 'default' => 1, 'values' => array(0=>$langs->trans('Internal'),1=>$langs->trans('External')))
             );
-            $text=$langs->trans("ConfirmCreateContact").'<br>';
-            if (! empty($conf->societe->enabled))
+            $text = $langs->trans("ConfirmCreateContact").'<br>';
+            if (!empty($conf->societe->enabled))
             {
-                if ($object->socid > 0) $text.=$langs->trans("UserWillBeExternalUser");
-                else $text.=$langs->trans("UserWillBeInternalUser");
+                if ($object->socid > 0) $text .= $langs->trans("UserWillBeExternalUser");
+                else $text .= $langs->trans("UserWillBeInternalUser");
             }
             print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CreateDolibarrLogin"), $text, "confirm_create_user", $formquestion, 'yes');
         }
 
         $linkback = '<a href="'.DOL_URL_ROOT.'/contact/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-        $morehtmlref='<div class="refidno">';
+        $morehtmlref = '<div class="refidno">';
         if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))
         {
             $objsoc->fetch($object->socid);
             // Thirdparty
-            $morehtmlref.=$langs->trans('ThirdParty') . ' : ';
-            if ($objsoc->id > 0) $morehtmlref.=$objsoc->getNomUrl(1, 'contact');
-            else $morehtmlref.=$langs->trans("ContactNotLinkedToCompany");
+            $morehtmlref .= $langs->trans('ThirdParty').' : ';
+            if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1, 'contact');
+            else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany");
         }
-        $morehtmlref.='</div>';
+        $morehtmlref .= '</div>';
 
         dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref);
 
@@ -1313,7 +1313,7 @@ else
         print '<tr><td>'.$langs->trans("PostOrFunction").'</td><td>'.$object->poste.'</td></tr>';
 
         // Email
-        if (! empty($conf->mailing->enabled))
+        if (!empty($conf->mailing->enabled))
         {
             $langs->load("mails");
             print '<tr><td>'.$langs->trans("NbOfEMailingsSend").'</td>';
@@ -1325,14 +1325,14 @@ else
         {
         	//print 'eee'.$object->email;
         	$noemail = $object->no_email;
-        	if (empty($noemail) && ! empty($object->email))
+        	if (empty($noemail) && !empty($object->email))
         	{
-        		$sql="SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'";
+        		$sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'";
         		//print $sql;
-        		$resql=$db->query($sql);
+        		$resql = $db->query($sql);
         		if ($resql)
         		{
-        			$obj=$db->fetch_object($resql);
+        			$obj = $db->fetch_object($resql);
         			$noemail = $obj->nb;
         		}
         	}
@@ -1352,15 +1352,15 @@ else
         print '<table class="border tableforfield" width="100%">';
 
 		// Categories
-		if (! empty($conf->categorie->enabled)  && ! empty($user->rights->categorie->lire)) {
-			print '<tr><td class="titlefield">' . $langs->trans("Categories") . '</td>';
+		if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) {
+			print '<tr><td class="titlefield">'.$langs->trans("Categories").'</td>';
 			print '<td colspan="3">';
 			print $form->showCategories($object->id, 'contact', 1);
 			print '</td></tr>';
 		}
 
 	    if (!empty($object->socid)) {
-		    print '<tr><td class="titlefield">' . $langs->trans("ContactByDefaultFor") . '</td>';
+		    print '<tr><td class="titlefield">'.$langs->trans("ContactByDefaultFor").'</td>';
 		    print '<td colspan="3">';
 		    print $formcompany->showRoles("roles", $object, 'view');
 		    print '</td></tr>';
@@ -1368,49 +1368,49 @@ else
 
     	// Other attributes
     	$cols = 3;
-    	$parameters=array('socid'=>$socid);
-    	include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+    	$parameters = array('socid'=>$socid);
+    	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
         $object->load_ref_elements();
 
-        if (! empty($conf->propal->enabled))
+        if (!empty($conf->propal->enabled))
         {
             print '<tr><td class="titlefield">'.$langs->trans("ContactForProposals").'</td><td colspan="3">';
-            print $object->ref_propal?$object->ref_propal:$langs->trans("NoContactForAnyProposal");
+            print $object->ref_propal ? $object->ref_propal : $langs->trans("NoContactForAnyProposal");
             print '</td></tr>';
         }
 
-        if (! empty($conf->commande->enabled) || ! empty($conf->expedition->enabled))
+        if (!empty($conf->commande->enabled) || !empty($conf->expedition->enabled))
         {
             print '<tr><td>';
-            if (! empty($conf->expedition->enabled)) { print $langs->trans("ContactForOrdersOrShipments"); }
+            if (!empty($conf->expedition->enabled)) { print $langs->trans("ContactForOrdersOrShipments"); }
             else print $langs->trans("ContactForOrders");
             print '</td><td colspan="3">';
-            $none=$langs->trans("NoContactForAnyOrder");
-            if  (! empty($conf->expedition->enabled)) { $none=$langs->trans("NoContactForAnyOrderOrShipments"); }
-            print $object->ref_commande?$object->ref_commande:$none;
+            $none = $langs->trans("NoContactForAnyOrder");
+            if (!empty($conf->expedition->enabled)) { $none = $langs->trans("NoContactForAnyOrderOrShipments"); }
+            print $object->ref_commande ? $object->ref_commande : $none;
             print '</td></tr>';
         }
 
-        if (! empty($conf->contrat->enabled))
+        if (!empty($conf->contrat->enabled))
         {
             print '<tr><td>'.$langs->trans("ContactForContracts").'</td><td colspan="3">';
-            print $object->ref_contrat?$object->ref_contrat:$langs->trans("NoContactForAnyContract");
+            print $object->ref_contrat ? $object->ref_contrat : $langs->trans("NoContactForAnyContract");
             print '</td></tr>';
         }
 
-        if (! empty($conf->facture->enabled))
+        if (!empty($conf->facture->enabled))
         {
             print '<tr><td>'.$langs->trans("ContactForInvoices").'</td><td colspan="3">';
-            print $object->ref_facturation?$object->ref_facturation:$langs->trans("NoContactForAnyInvoice");
+            print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice");
             print '</td></tr>';
         }
 
         print '<tr><td>'.$langs->trans("DolibarrLogin").'</td><td colspan="3">';
         if ($object->user_id)
         {
-            $dolibarr_user=new User($db);
-            $result=$dolibarr_user->fetch($object->user_id);
+            $dolibarr_user = new User($db);
+            $result = $dolibarr_user->fetch($object->user_id);
             print $dolibarr_user->getLoginUrl(1);
         }
         else print $langs->trans("NoDolibarrAccess");
@@ -1434,11 +1434,11 @@ else
         // Barre d'actions
         print '<div class="tabsAction">';
 
-		$parameters=array();
-		$reshook=$hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
-		if (empty($reshook) && $action!='presend')
+		$parameters = array();
+		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+		if (empty($reshook) && $action != 'presend')
 		{
-			if (! empty($object->email))
+			if (!empty($object->email))
 			{
 				$langs->load("mails");
 				print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=presend&amp;mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>';
@@ -1454,7 +1454,7 @@ else
                 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=edit">'.$langs->trans('Modify').'</a>';
             }
 
-            if (! $object->user_id && $user->rights->user->user->creer)
+            if (!$object->user_id && $user->rights->user->user->creer)
             {
                 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=create_user">'.$langs->trans("CreateDolibarrLogin").'</a>';
             }
@@ -1473,15 +1473,15 @@ else
 		    // Delete
 		    if ($user->rights->societe->contact->supprimer)
             {
-                print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=delete'.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.$langs->trans('Delete').'</a>';
+                print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=delete'.($backtopage ? '&backtopage='.urlencode($backtopage) : '').'">'.$langs->trans('Delete').'</a>';
             }
         }
 
         print "</div>";
 
 	    // Presend form
-	    $modelmail='contact';
-	    $defaulttopic='Information';
+	    $modelmail = 'contact';
+	    $defaulttopic = 'Information';
 	    $diroutput = $conf->contact->dir_output;
 	    $trackid = 'con'.$object->id;
 

+ 28 - 28
htdocs/contrat/agenda.php

@@ -27,8 +27,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
-if (! empty($conf->projet->enabled)) {
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+if (!empty($conf->projet->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
 }
 
@@ -37,14 +37,14 @@ $langs->loadLangs(array("companies", "contracts"));
 
 if (GETPOST('actioncode', 'array'))
 {
-	$actioncode=GETPOST('actioncode', 'array', 3);
-	if (! count($actioncode)) $actioncode='0';
+	$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));
+	$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');
+$search_agenda_label = GETPOST('search_agenda_label');
 
 $action		= GETPOST('action', 'alpha');
 $confirm	= GETPOST('confirm', 'alpha');
@@ -63,25 +63,25 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $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 object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('agendacontract','globalcard'));
+$hookmanager->initHooks(array('agendacontract', 'globalcard'));
 
 
 /*
  * Actions
  */
 
-$parameters=array('id'=>$id);
-$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
+$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))
+	if (GETPOST('cancel', 'alpha') && !empty($backtopage))
 	{
 		header("Location: ".$backtopage);
 		exit;
@@ -90,8 +90,8 @@ if (empty($reshook))
 	// 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='';
+		$actioncode = '';
+		$search_agenda_label = '';
 	}
 }
 
@@ -104,17 +104,17 @@ if (empty($reshook))
 
 $form = new Form($db);
 $formfile = new FormFile($db);
-if (! empty($conf->projet->enabled)) $formproject = new FormProjets($db);
+if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db);
 
 if ($id > 0)
 {
 	// Load object modContract
-	$module=(! empty($conf->global->CONTRACT_ADDON)?$conf->global->CONTRACT_ADDON:'mod_contract_serpis');
+	$module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
 	if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php')
 	{
-		$module = substr($module, 0, dol_strlen($module)-4);
+		$module = substr($module, 0, dol_strlen($module) - 4);
 	}
-	$result=dol_include_once('/core/modules/contract/'.$module.'.php');
+	$result = dol_include_once('/core/modules/contract/'.$module.'.php');
 	if ($result > 0)
 	{
 		$modCodeContract = new $module();
@@ -229,29 +229,29 @@ if ($id > 0)
 	//print '</div>';
 
 
-	$newcardbutton='';
-	if (! empty($conf->agenda->enabled))
+	$newcardbutton = '';
+	if (!empty($conf->agenda->enabled))
 	{
-		if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create))
+		if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create))
 		{
-			$newcardbutton.= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out);
+			$newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out);
 		}
 	}
 
-	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)))
 	{
 		print '<br>';
 
-		$param='&id='.$id;
-		if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage;
-		if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
+		$param = '&id='.$id;
+		if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
+		if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
 
 		print load_fiche_titre($langs->trans("ActionsOnContract"), $newcardbutton, '');
 		//print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $newcardbutton, '', 0, 1, 1);
 
 		// List of all actions
-		$filters=array();
-		$filters['search_agenda_label']=$search_agenda_label;
+		$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);

File diff suppressed because it is too large
+ 193 - 193
htdocs/contrat/card.php


+ 32 - 32
htdocs/contrat/contact.php

@@ -89,7 +89,7 @@ if ($action == 'swapstatut' && $user->rights->contrat->creer)
 {
 	if ($object->fetch($id))
 	{
-	    $result=$object->swapContactStatus(GETPOST('ligne'));
+	    $result = $object->swapContactStatus(GETPOST('ligne'));
 	}
 	else
 	{
@@ -118,9 +118,9 @@ if ($action == 'deletecontact' && $user->rights->contrat->creer)
 llxHeader('', $langs->trans("Contract"), "");
 
 $form = new Form($db);
-$formcompany= new FormCompany($db);
-$contactstatic=new Contact($db);
-$userstatic=new User($db);
+$formcompany = new FormCompany($db);
+$contactstatic = new Contact($db);
+$userstatic = new User($db);
 
 /* *************************************************************************** */
 /*                                                                             */
@@ -128,7 +128,7 @@ $userstatic=new User($db);
 /*                                                                             */
 /* *************************************************************************** */
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	if ($object->fetch($id, $ref) > 0)
 	{
@@ -136,66 +136,66 @@ if ($id > 0 || ! empty($ref))
 
 	    $head = contract_prepare_head($object);
 
-		$hselected=1;
+		$hselected = 1;
 
 		dol_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract');
 
 		// Contract card
 
-        $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
+        $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
 
-        $morehtmlref='';
+        $morehtmlref = '';
         //if (! empty($modCodeContract->code_auto)) {
-            $morehtmlref.=$object->ref;
+            $morehtmlref .= $object->ref;
         /*} else {
             $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3);
             $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2);
         }*/
 
-		$morehtmlref.='<div class="refidno">';
+		$morehtmlref .= '<div class="refidno">';
 		// Ref customer
-		$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
-		$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1, 'getFormatedCustomerRef');
+		$morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
+		$morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1, 'getFormatedCustomerRef');
 		// Ref supplier
-		$morehtmlref.='<br>';
-		$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
-		$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
+		$morehtmlref .= '<br>';
+		$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
+		$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
 		// Thirdparty
-	    $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+	    $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
         // Project
-        if (! empty($conf->projet->enabled)) {
+        if (!empty($conf->projet->enabled)) {
             $langs->load("projects");
-            $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+            $morehtmlref .= '<br>'.$langs->trans('Project').' ';
             if ($user->rights->contrat->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.=' : ';
+                    $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="'.$_SESSION['newtoken'].'">';
-	                $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $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>';
+	                $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="'.$_SESSION['newtoken'].'">';
+	                $morehtmlref .= $formproject->select_projects($object->thirdparty->id, $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->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
+	                $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
 	            }
 	        } else {
-	            if (! empty($object->fk_project)) {
+	            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>';
+	                $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 .= '';
 	            }
 	        }
 	    }
-	    $morehtmlref.='</div>';
+	    $morehtmlref .= '</div>';
 
 
 	    dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);

+ 40 - 40
htdocs/contrat/document.php

@@ -33,8 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.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';
-if (! empty($conf->projet->enabled)) {
-	require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
+if (!empty($conf->projet->enabled)) {
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 }
 
 // Load translation files required by the page
@@ -62,8 +62,8 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $conf->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";
 
 
 $object = new Contrat($db);
@@ -74,17 +74,17 @@ if ($object->id > 0)
 }
 
 $upload_dir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($object->ref);
-$modulepart='contract';
+$modulepart = 'contract';
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('contractcard','globalcard'));
+$hookmanager->initHooks(array('contractcard', 'globalcard'));
 
 
 /*
  * Actions
  */
 
-include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
+include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
 
 
 /*
@@ -98,77 +98,77 @@ llxHeader('', $langs->trans("Contract"), "");
 
 if ($object->id)
 {
-	$head=contract_prepare_head($object);
+	$head = contract_prepare_head($object);
 
 	dol_fiche_head($head, 'documents', $langs->trans("Contract"), -1, 'contract');
 
 
 	// 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)
+	$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'];
+		$totalsize += $file['size'];
 	}
 
 
 	// Contract card
 
-	$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
+	$linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
 
-	$morehtmlref='';
+	$morehtmlref = '';
 	//if (! empty($modCodeContract->code_auto)) {
-	$morehtmlref.=$object->ref;
+	$morehtmlref .= $object->ref;
 	/*} else {
 	 $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3);
 	$morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2);
 	}*/
 
-	$morehtmlref.='<div class="refidno">';
+	$morehtmlref .= '<div class="refidno">';
 	// Ref customer
-	$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
-	$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1, 'getFormatedCustomerRef');
+	$morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
+	$morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1, 'getFormatedCustomerRef');
 	// Ref supplier
-	$morehtmlref.='<br>';
-	$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
-	$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
+	$morehtmlref .= '<br>';
+	$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
+	$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
 	// Thirdparty
-	$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+	$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
 	// Project
-	if (! empty($conf->projet->enabled))
+	if (!empty($conf->projet->enabled))
 	{
 		$langs->load("projects");
-		$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+		$morehtmlref .= '<br>'.$langs->trans('Project').' ';
 		if ($user->rights->contrat->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.=' : ';
+				$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="'.$_SESSION['newtoken'].'">';
-				$morehtmlref.=$formproject->select_projects($object->thirdparty->id, $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>';
+				$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="'.$_SESSION['newtoken'].'">';
+				$morehtmlref .= $formproject->select_projects($object->thirdparty->id, $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->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
+				$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
 			}
 		} else {
-			if (! empty($object->fk_project)) {
+			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>';
+				$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 .= '';
 			}
 		}
 	}
-	$morehtmlref.='</div>';
+	$morehtmlref .= '</div>';
 
 
 	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
@@ -190,8 +190,8 @@ if ($object->id)
     $modulepart = 'contract';
     $permission = $user->rights->contrat->creer;
     $permtoedit = $user->rights->contrat->creer;
-    $param = '&id=' . $object->id;
-    include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
+    $param = '&id='.$object->id;
+    include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
 }
 else
 {

+ 29 - 29
htdocs/contrat/note.php

@@ -58,7 +58,7 @@ $hookmanager->initHooks(array('contractcard','globalcard'));
  * Actions
  */
 
-include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include, not includ_once
+include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once
 
 
 
@@ -70,7 +70,7 @@ llxHeader('', $langs->trans("Contract"), "");
 
 $form = new Form($db);
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
     $object->fetch_thirdparty();
 
@@ -82,61 +82,61 @@ if ($id > 0 || ! empty($ref))
 
     // Contract card
 
-    $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
+    $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
 
-    $morehtmlref='';
+    $morehtmlref = '';
     //if (! empty($modCodeContract->code_auto)) {
-    $morehtmlref.=$object->ref;
+    $morehtmlref .= $object->ref;
     /*} else {
      $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3);
     $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2);
     }*/
 
-    $morehtmlref.='<div class="refidno">';
+    $morehtmlref .= '<div class="refidno">';
     // Ref customer
-    $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
-    $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1, 'getFormatedCustomerRef');
+    $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', 0, 1);
+    $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, 0, 'string', '', null, null, '', 1, 'getFormatedCustomerRef');
     // Ref supplier
-    $morehtmlref.='<br>';
-    $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
-    $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
+    $morehtmlref .= '<br>';
+    $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
+    $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
     // Thirdparty
-    $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
+    $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
     // Project
-    if (! empty($conf->projet->enabled))
+    if (!empty($conf->projet->enabled))
     {
     	$langs->load("projects");
-    	$morehtmlref.='<br>'.$langs->trans('Project') . ' ';
+    	$morehtmlref .= '<br>'.$langs->trans('Project').' ';
     	if ($user->rights->contrat->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.=' : ';
+    			$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="'.$_SESSION['newtoken'].'">';
-    			$morehtmlref.=$formproject->select_projects($object->thirdparty->id, $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>';
+    			$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="'.$_SESSION['newtoken'].'">';
+    			$morehtmlref .= $formproject->select_projects($object->thirdparty->id, $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->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
+    			$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
     		}
     	} else {
-    		if (! empty($object->fk_project)) {
+    		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>';
+    			$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 .= '';
     		}
     	}
     }
-    $morehtmlref.='</div>';
+    $morehtmlref .= '</div>';
 
 
     dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
@@ -152,7 +152,7 @@ if ($id > 0 || ! empty($ref))
     print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">';
     if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent);
     else print $langs->trans("CompanyHasNoRelativeDiscount");
-    $absolute_discount=$object->thirdparty->getAvailableDiscounts();
+    $absolute_discount = $object->thirdparty->getAvailableDiscounts();
     print '. ';
     if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency));
     else print $langs->trans("CompanyHasNoAbsoluteDiscount");

+ 170 - 170
htdocs/contrat/services_list.php

@@ -35,7 +35,7 @@ require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
 // Load translation files required by the page
 $langs->loadLangs(array('products', 'contracts', 'companies'));
 
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOST("page", 'int');
@@ -43,39 +43,39 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (! $sortfield) $sortfield="c.rowid";
-if (! $sortorder) $sortorder="ASC";
+if (!$sortfield) $sortfield = "c.rowid";
+if (!$sortorder) $sortorder = "ASC";
 
 $mode = GETPOST("mode");
-$filter=GETPOST("filter");
-$search_name=GETPOST("search_name", 'alpha');
-$search_contract=GETPOST("search_contract", 'alpha');
-$search_service=GETPOST("search_service", 'alpha');
-$search_status=GETPOST("search_status", 'alpha');
-$statut=GETPOST('statut', 'int')?GETPOST('statut', 'int'):1;
-$search_product_category=GETPOST('search_product_category', 'int');
-$socid=GETPOST('socid', 'int');
-$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'contractservicelist'.$mode;
-
-$opouvertureprevuemonth=GETPOST('opouvertureprevuemonth');
-$opouvertureprevueday=GETPOST('opouvertureprevueday');
-$opouvertureprevueyear=GETPOST('opouvertureprevueyear');
-$filter_opouvertureprevue=GETPOST('filter_opouvertureprevue');
-
-$op1month=GETPOST('op1month', 'int');
-$op1day=GETPOST('op1day', 'int');
-$op1year=GETPOST('op1year', 'int');
-$filter_op1=GETPOST('filter_op1', 'alpha');
-
-$op2month=GETPOST('op2month', 'int');
-$op2day=GETPOST('op2day', 'int');
-$op2year=GETPOST('op2year', 'int');
-$filter_op2=GETPOST('filter_op2', 'alpha');
-
-$opcloturemonth=GETPOST('opcloturemonth', 'int');
-$opclotureday=GETPOST('opclotureday', 'int');
-$opclotureyear=GETPOST('opclotureyear', 'int');
-$filter_opcloture=GETPOST('filter_opcloture', 'alpha');
+$filter = GETPOST("filter");
+$search_name = GETPOST("search_name", 'alpha');
+$search_contract = GETPOST("search_contract", 'alpha');
+$search_service = GETPOST("search_service", 'alpha');
+$search_status = GETPOST("search_status", 'alpha');
+$statut = GETPOST('statut', 'int') ?GETPOST('statut', 'int') : 1;
+$search_product_category = GETPOST('search_product_category', 'int');
+$socid = GETPOST('socid', 'int');
+$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'contractservicelist'.$mode;
+
+$opouvertureprevuemonth = GETPOST('opouvertureprevuemonth');
+$opouvertureprevueday = GETPOST('opouvertureprevueday');
+$opouvertureprevueyear = GETPOST('opouvertureprevueyear');
+$filter_opouvertureprevue = GETPOST('filter_opouvertureprevue');
+
+$op1month = GETPOST('op1month', 'int');
+$op1day = GETPOST('op1day', 'int');
+$op1year = GETPOST('op1year', 'int');
+$filter_op1 = GETPOST('filter_op1', 'alpha');
+
+$op2month = GETPOST('op2month', 'int');
+$op2day = GETPOST('op2day', 'int');
+$op2year = GETPOST('op2year', 'int');
+$filter_op2 = GETPOST('filter_op2', 'alpha');
+
+$opcloturemonth = GETPOST('opcloturemonth', 'int');
+$opclotureday = GETPOST('opclotureday', 'int');
+$opclotureyear = GETPOST('opclotureyear', 'int');
+$filter_opcloture = GETPOST('filter_opcloture', 'alpha');
 
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@@ -135,10 +135,10 @@ $arrayfields=array(
 // 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)
+	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], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key]));
+		if (!empty($extrafields->attributes[$object->table_element]['list'][$key]))
+			$arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key]));
 	}
 }
 $object->fields = dol_sort_array($object->fields, 'position');
@@ -151,11 +151,11 @@ $arrayfields = dol_sort_array($arrayfields, 'position');
  * Actions
  */
 
-if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; }
-if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; }
+if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; }
 
-$parameters=array('socid'=>$socid);
-$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
+$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 (empty($reshook))
@@ -165,31 +165,31 @@ if (empty($reshook))
 
 	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_product_category=0;
-		$search_name="";
-		$search_contract="";
-		$search_service="";
-		$search_status=-1;
-		$opouvertureprevuemonth="";
-		$opouvertureprevueday="";
-		$opouvertureprevueyear="";
-		$filter_opouvertureprevue="";
-		$op1month="";
-		$op1day="";
-		$op1year="";
-		$filter_op1="";
-		$op2month="";
-		$op2day="";
-		$op2year="";
-		$filter_op2="";
-		$opcloturemonth="";
-		$opclotureday="";
-		$opclotureyear="";
-		$filter_opcloture="";
-		$mode='';
-		$filter='';
-		$toselect='';
-		$search_array_options=array();
+   		$search_product_category = 0;
+		$search_name = "";
+		$search_contract = "";
+		$search_service = "";
+		$search_status = -1;
+		$opouvertureprevuemonth = "";
+		$opouvertureprevueday = "";
+		$opouvertureprevueyear = "";
+		$filter_opouvertureprevue = "";
+		$op1month = "";
+		$op1day = "";
+		$op1year = "";
+		$filter_op1 = "";
+		$op2month = "";
+		$op2day = "";
+		$op2year = "";
+		$filter_op2 = "";
+		$opcloturemonth = "";
+		$opclotureday = "";
+		$opclotureyear = "";
+		$filter_opcloture = "";
+		$mode = '';
+		$filter = '';
+		$toselect = '';
+		$search_array_options = array();
 	}
 }
 
@@ -275,8 +275,8 @@ $sql .= $db->plimit($limit + 1, $offset);
 
 //print $sql;
 dol_syslog("contrat/services_list.php", LOG_DEBUG);
-$resql=$db->query($sql);
-if (! $resql)
+$resql = $db->query($sql);
+if (!$resql)
 {
 	dol_print_error($db);
 	exit;
@@ -295,36 +295,36 @@ if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) &&
 
 llxHeader(null, $langs->trans("Services"));
 
-$param='';
-if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
-if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit;
-if ($search_contract) $param.='&amp;search_contract='.urlencode($search_contract);
-if ($search_name)      $param.='&amp;search_name='.urlencode($search_name);
-if ($search_service)  $param.='&amp;search_service='.urlencode($search_service);
-if ($mode)            $param.='&amp;mode='.urlencode($mode);
-if ($filter)          $param.='&amp;filter='.urlencode($filter);
-if (! empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) $param.='&amp;filter_opouvertureprevue='.urlencode($filter_opouvertureprevue);
-if (! empty($filter_op1) && $filter_op1 != -1) $param.='&amp;filter_op1='.urlencode($filter_op1);
-if (! empty($filter_op2) && $filter_op2 != -1) $param.='&amp;filter_op2='.urlencode($filter_op2);
-if (! empty($filter_opcloture) && $filter_opcloture != -1) $param.='&amp;filter_opcloture='.urlencode($filter_opcloture);
-if ($filter_dateouvertureprevue != '') $param.='&amp;opouvertureprevueday='.$opouvertureprevueday.'&amp;opouvertureprevuemonth='.$opouvertureprevuemonth.'&amp;opouvertureprevueyear='.$opouvertureprevueyear;
-if ($filter_date1 != '') $param.='&amp;op1day='.$op1day.'&amp;op1month='.$op1month.'&amp;op1year='.$op1year;
-if ($filter_date2 != '') $param.='&amp;op2day='.$op2day.'&amp;op2month='.$op2month.'&amp;op2year='.$op2year;
-if ($filter_datecloture != '') $param.='&amp;opclotureday='.$op2day.'&amp;opcloturemonth='.$op2month.'&amp;opclotureyear='.$op2year;
-if ($optioncss != '') $param.='&optioncss='.$optioncss;
+$param = '';
+if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
+if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
+if ($search_contract) $param .= '&amp;search_contract='.urlencode($search_contract);
+if ($search_name)      $param .= '&amp;search_name='.urlencode($search_name);
+if ($search_service)  $param .= '&amp;search_service='.urlencode($search_service);
+if ($mode)            $param .= '&amp;mode='.urlencode($mode);
+if ($filter)          $param .= '&amp;filter='.urlencode($filter);
+if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) $param .= '&amp;filter_opouvertureprevue='.urlencode($filter_opouvertureprevue);
+if (!empty($filter_op1) && $filter_op1 != -1) $param .= '&amp;filter_op1='.urlencode($filter_op1);
+if (!empty($filter_op2) && $filter_op2 != -1) $param .= '&amp;filter_op2='.urlencode($filter_op2);
+if (!empty($filter_opcloture) && $filter_opcloture != -1) $param .= '&amp;filter_opcloture='.urlencode($filter_opcloture);
+if ($filter_dateouvertureprevue != '') $param .= '&amp;opouvertureprevueday='.$opouvertureprevueday.'&amp;opouvertureprevuemonth='.$opouvertureprevuemonth.'&amp;opouvertureprevueyear='.$opouvertureprevueyear;
+if ($filter_date1 != '') $param .= '&amp;op1day='.$op1day.'&amp;op1month='.$op1month.'&amp;op1year='.$op1year;
+if ($filter_date2 != '') $param .= '&amp;op2day='.$op2day.'&amp;op2month='.$op2month.'&amp;op2year='.$op2year;
+if ($filter_datecloture != '') $param .= '&amp;opclotureday='.$op2day.'&amp;opcloturemonth='.$op2month.'&amp;opclotureyear='.$op2year;
+if ($optioncss != '') $param .= '&optioncss='.$optioncss;
 // Add $param from extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 
 // List of mass actions available
-$arrayofmassactions =  array(
+$arrayofmassactions = array(
 	//'presend'=>$langs->trans("SendByMail"),
 	//'builddoc'=>$langs->trans("PDFMerge"),
 );
 //if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
 //if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
-$massactionbutton=$form->selectMassAction('', $arrayofmassactions);
+$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
 
-print '<form method="POST" action="'. $_SERVER["PHP_SELF"] .'">';
+print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
 if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
@@ -334,17 +334,17 @@ print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
 print '<input type="hidden" name="page" value="'.$page.'">';
 print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
 
-$title=$langs->trans("ListOfServices");
-if ($mode == "0") $title=$langs->trans("ListOfInactiveServices");	// Must use == "0"
-if ($mode == "4" && $filter != "expired") $title=$langs->trans("ListOfRunningServices");
-if ($mode == "4" && $filter == "expired") $title=$langs->trans("ListOfExpiredServices");
-if ($mode == "5") $title=$langs->trans("ListOfClosedServices");
+$title = $langs->trans("ListOfServices");
+if ($mode == "0") $title = $langs->trans("ListOfInactiveServices"); // Must use == "0"
+if ($mode == "4" && $filter != "expired") $title = $langs->trans("ListOfRunningServices");
+if ($mode == "4" && $filter == "expired") $title = $langs->trans("ListOfExpiredServices");
+if ($mode == "5") $title = $langs->trans("ListOfClosedServices");
 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'commercial', 0, '', '', $limit);
 
 if ($sall)
 {
-	foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
-	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'</div>';
+	foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
+	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>';
 }
 
 $morefilter = '';
@@ -353,60 +353,60 @@ $morefilter = '';
 if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire))
 {
 	include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
-	$moreforfilter.='<div class="divsearchfield">';
-	$moreforfilter.=$langs->trans('IncludingProductWithTag'). ': ';
+	$moreforfilter .= '<div class="divsearchfield">';
+	$moreforfilter .= $langs->trans('IncludingProductWithTag').': ';
 	$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1);
-	$moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
-	$moreforfilter.='</div>';
+	$moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1);
+	$moreforfilter .= '</div>';
 }
 
-$parameters=array();
-$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters);    // Note that $action and $object may have been modified by hook
+$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($moreforfilter))
+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
+$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
+$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
 
 
 print '<div class="div-table-responsive">';
-print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
+print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
 
 print '<tr class="liste_titre">';
-if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, "", $sortfield, $sortorder);
-if (! empty($arrayfields['p.description']['checked'])) print_liste_field_titre($arrayfields['p.description']['label'], $_SERVER["PHP_SELF"], "p.description", "", $param, "", $sortfield, $sortorder);
-if (! empty($arrayfields['cd.qty']['checked']))  print_liste_field_titre($arrayfields['cd.qty']['label'], $_SERVER["PHP_SELF"], "cd.qty", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['cd.total_ht']['checked']))  print_liste_field_titre($arrayfields['cd.total_ht']['label'], $_SERVER["PHP_SELF"], "cd.total_ht", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['cd.total_tva']['checked']))  print_liste_field_titre($arrayfields['cd.total_tva']['label'], $_SERVER["PHP_SELF"], "cd.total_tva", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['cd.tva_tx']['checked']))  print_liste_field_titre($arrayfields['cd.tva_tx']['label'], $_SERVER["PHP_SELF"], "cd.tva_tx", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['cd.subprice']['checked']))  print_liste_field_titre($arrayfields['cd.subprice']['label'], $_SERVER["PHP_SELF"], "cd.subprice", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder);
-if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture_prevue", "", $param, '', $sortfield, $sortorder, 'center ');
-if (! empty($arrayfields['cd.date_ouverture']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture", "", $param, '', $sortfield, $sortorder, 'center ');
-if (! empty($arrayfields['cd.date_fin_validite']['checked'])) print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'], $_SERVER["PHP_SELF"], "cd.date_fin_validite", "", $param, '', $sortfield, $sortorder, 'center ');
-if (! empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre($arrayfields['cd.date_cloture']['label'], $_SERVER["PHP_SELF"], "cd.date_cloture", "", $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, "", $sortfield, $sortorder);
+if (!empty($arrayfields['p.description']['checked'])) print_liste_field_titre($arrayfields['p.description']['label'], $_SERVER["PHP_SELF"], "p.description", "", $param, "", $sortfield, $sortorder);
+if (!empty($arrayfields['cd.qty']['checked']))  print_liste_field_titre($arrayfields['cd.qty']['label'], $_SERVER["PHP_SELF"], "cd.qty", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['cd.total_ht']['checked']))  print_liste_field_titre($arrayfields['cd.total_ht']['label'], $_SERVER["PHP_SELF"], "cd.total_ht", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['cd.total_tva']['checked']))  print_liste_field_titre($arrayfields['cd.total_tva']['label'], $_SERVER["PHP_SELF"], "cd.total_tva", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['cd.tva_tx']['checked']))  print_liste_field_titre($arrayfields['cd.tva_tx']['label'], $_SERVER["PHP_SELF"], "cd.tva_tx", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['cd.subprice']['checked']))  print_liste_field_titre($arrayfields['cd.subprice']['label'], $_SERVER["PHP_SELF"], "cd.subprice", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, "", $sortfield, $sortorder);
+if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture_prevue", "", $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['cd.date_ouverture']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture", "", $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['cd.date_fin_validite']['checked'])) print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'], $_SERVER["PHP_SELF"], "cd.date_fin_validite", "", $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre($arrayfields['cd.date_cloture']['label'], $_SERVER["PHP_SELF"], "cd.date_cloture", "", $param, '', $sortfield, $sortorder, 'center ');
 // 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);    // Note that $action and $object may have been modified by hook
+$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['cd.datec']['checked']))  print_liste_field_titre($arrayfields['cd.datec']['label'], $_SERVER["PHP_SELF"], "cd.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['cd.tms']['checked']))    print_liste_field_titre($arrayfields['cd.tms']['label'], $_SERVER["PHP_SELF"], "cd.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], "cd.statut,c.statut", "", $param, '', $sortfield, $sortorder, 'right ');
+if (!empty($arrayfields['cd.datec']['checked']))  print_liste_field_titre($arrayfields['cd.datec']['label'], $_SERVER["PHP_SELF"], "cd.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['cd.tms']['checked']))    print_liste_field_titre($arrayfields['cd.tms']['label'], $_SERVER["PHP_SELF"], "cd.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], "cd.statut,c.statut", "", $param, '', $sortfield, $sortorder, 'right ');
 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
 print "</tr>\n";
 
 print '<tr class="liste_titre">';
-if (! empty($arrayfields['c.ref']['checked']))
+if (!empty($arrayfields['c.ref']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '<input type="hidden" name="filter" value="'.$filter.'">';
@@ -415,40 +415,40 @@ if (! empty($arrayfields['c.ref']['checked']))
 	print '</td>';
 }
 // Service label
-if (! empty($arrayfields['p.description']['checked']))
+if (!empty($arrayfields['p.description']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '<input type="text" class="flat maxwidth100" name="search_service" value="'.dol_escape_htmltag($search_service).'">';
 	print '</td>';
 }
 // detail lines
-if (! empty($arrayfields['cd.qty']['checked']))
+if (!empty($arrayfields['cd.qty']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '</td>';
 }
-if (! empty($arrayfields['cd.total_ht']['checked']))
+if (!empty($arrayfields['cd.total_ht']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '</td>';
 }
-if (! empty($arrayfields['cd.total_tva']['checked']))
+if (!empty($arrayfields['cd.total_tva']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '</td>';
 }
-if (! empty($arrayfields['cd.tva_tx']['checked']))
+if (!empty($arrayfields['cd.tva_tx']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '</td>';
 }
-if (! empty($arrayfields['cd.subprice']['checked']))
+if (!empty($arrayfields['cd.subprice']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '</td>';
 }
 // Third party
-if (! empty($arrayfields['s.nom']['checked']))
+if (!empty($arrayfields['s.nom']['checked']))
 {
 	print '<td class="liste_titre">';
 	print '<input type="text" class="flat maxwidth100" name="search_name" value="'.dol_escape_htmltag($search_name).'">';
@@ -456,43 +456,43 @@ if (! empty($arrayfields['s.nom']['checked']))
 }
 
 
-if (! empty($arrayfields['cd.date_ouverture_prevue']['checked']))
+if (!empty($arrayfields['cd.date_ouverture_prevue']['checked']))
 {
 	print '<td class="liste_titre center">';
-	$arrayofoperators=array('<'=>'<','>'=>'>');
+	$arrayofoperators = array('<'=>'<', '>'=>'>');
 	print $form->selectarray('filter_opouvertureprevue', $arrayofoperators, $filter_opouvertureprevue, 1);
 	print ' ';
-	$filter_dateouvertureprevue=dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear);
+	$filter_dateouvertureprevue = dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear);
 	print $form->selectDate($filter_dateouvertureprevue, 'opouvertureprevue', 0, 0, 1, '', 1, 0);
 	print '</td>';
 }
-if (! empty($arrayfields['cd.date_ouverture']['checked']))
+if (!empty($arrayfields['cd.date_ouverture']['checked']))
 {
 	print '<td class="liste_titre center">';
-	$arrayofoperators=array('<'=>'<','>'=>'>');
+	$arrayofoperators = array('<'=>'<', '>'=>'>');
 	print $form->selectarray('filter_op1', $arrayofoperators, $filter_op1, 1);
 	print ' ';
-	$filter_date1=dol_mktime(0, 0, 0, $op1month, $op1day, $op1year);
+	$filter_date1 = dol_mktime(0, 0, 0, $op1month, $op1day, $op1year);
 	print $form->selectDate($filter_date1, 'op1', 0, 0, 1, '', 1, 0);
 	print '</td>';
 }
-if (! empty($arrayfields['cd.date_fin_validite']['checked']))
+if (!empty($arrayfields['cd.date_fin_validite']['checked']))
 {
 	print '<td class="liste_titre center">';
-	$arrayofoperators=array('<'=>'<','>'=>'>');
+	$arrayofoperators = array('<'=>'<', '>'=>'>');
 	print $form->selectarray('filter_op2', $arrayofoperators, $filter_op2, 1);
 	print ' ';
-	$filter_date2=dol_mktime(0, 0, 0, $op2month, $op2day, $op2year);
+	$filter_date2 = dol_mktime(0, 0, 0, $op2month, $op2day, $op2year);
 	print $form->selectDate($filter_date2, 'op2', 0, 0, 1, '', 1, 0);
 	print '</td>';
 }
-if (! empty($arrayfields['cd.date_cloture']['checked']))
+if (!empty($arrayfields['cd.date_cloture']['checked']))
 {
 	print '<td class="liste_titre center">';
-	$arrayofoperators=array('<'=>'<','>'=>'>');
+	$arrayofoperators = array('<'=>'<', '>'=>'>');
 	print $form->selectarray('filter_opcloture', $arrayofoperators, $filter_opcloture, 1);
 	print ' ';
-	$filter_date_cloture=dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear);
+	$filter_date_cloture = dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear);
 	print $form->selectDate($filter_date_cloture, 'opcloture', 0, 0, 1, '', 1, 0);
 	print '</td>';
 }
@@ -500,83 +500,83 @@ if (! empty($arrayfields['cd.date_cloture']['checked']))
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
 
 // Fields from hook
-$parameters=array('arrayfields'=>$arrayfields);
-$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters);    // Note that $action and $object may have been modified by hook
+$parameters = array('arrayfields'=>$arrayfields);
+$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
 print $hookmanager->resPrint;
-if (! empty($arrayfields['cd.datec']['checked']))
+if (!empty($arrayfields['cd.datec']['checked']))
 {
 	// Date creation
 	print '<td class="liste_titre">';
 	print '</td>';
 }
-if (! empty($arrayfields['cd.tms']['checked']))
+if (!empty($arrayfields['cd.tms']['checked']))
 {
 	// Date modification
 	print '<td class="liste_titre">';
 	print '</td>';
 }
-if (! empty($arrayfields['status']['checked']))
+if (!empty($arrayfields['status']['checked']))
 {
 	// Status
 	print '<td class="liste_titre right">';
-	$arrayofstatus=array(
+	$arrayofstatus = array(
 		'0'=>$langs->trans("ServiceStatusInitial"),
 		'4'=>$langs->trans("ServiceStatusRunning"),
 		'4&filter=notexpired'=>$langs->trans("ServiceStatusNotLate"),
 		'4&filter=expired'=>$langs->trans("ServiceStatusLate"),
 		'5'=>$langs->trans("ServiceStatusClosed")
 	);
-	print $form->selectarray('search_status', $arrayofstatus, (strstr($search_status, ',')?-1:$search_status), 1, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone');
+	print $form->selectarray('search_status', $arrayofstatus, (strstr($search_status, ',') ?-1 : $search_status), 1, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone');
 	print '</td>';
 }
 // Action column
 print '<td class="liste_titre maxwidthsearch">';
-$searchpicto=$form->showFilterAndCheckAddButtons(0);
+$searchpicto = $form->showFilterAndCheckAddButtons(0);
 print $searchpicto;
 print '</td>';
 print "</tr>\n";
 
-$contractstatic=new Contrat($db);
-$productstatic=new Product($db);
+$contractstatic = new Contrat($db);
+$productstatic = new Product($db);
 
-$i=0;
-$totalarray=array();
+$i = 0;
+$totalarray = array();
 while ($i < min($num, $limit))
 {
 	$obj = $db->fetch_object($resql);
 
-	$contractstatic->id=$obj->cid;
-	$contractstatic->ref=$obj->ref?$obj->ref:$obj->cid;
+	$contractstatic->id = $obj->cid;
+	$contractstatic->ref = $obj->ref ? $obj->ref : $obj->cid;
 
-	$companystatic->id=$obj->socid;
-	$companystatic->name=$obj->name;
-	$companystatic->email=$obj->email;
-	$companystatic->client=$obj->client;
-	$companystatic->fournisseur=$obj->fournisseur;
+	$companystatic->id = $obj->socid;
+	$companystatic->name = $obj->name;
+	$companystatic->email = $obj->email;
+	$companystatic->client = $obj->client;
+	$companystatic->fournisseur = $obj->fournisseur;
 
 	print '<tr class="oddeven">';
 
 	// Ref
-	if (! empty($arrayfields['c.ref']['checked']))
+	if (!empty($arrayfields['c.ref']['checked']))
 	{
 		print '<td>';
 		print $contractstatic->getNomUrl(1, 16);
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
 	// Service
-	if (! empty($arrayfields['p.description']['checked']))
+	if (!empty($arrayfields['p.description']['checked']))
 	{
 		print '<td>';
 		if ($obj->pid > 0)
 		{
-			$productstatic->id=$obj->pid;
-			$productstatic->type=$obj->ptype;
-			$productstatic->ref=$obj->pref;
-			$productstatic->entity=$obj->pentity;
+			$productstatic->id = $obj->pid;
+			$productstatic->type = $obj->ptype;
+			$productstatic->ref = $obj->pref;
+			$productstatic->entity = $obj->pentity;
 			print $productstatic->getNomUrl(1, '', 24);
-			print $obj->label?' - '.dol_trunc($obj->label, 16):'';
-			if (! empty($obj->description) && ! empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description);
+			print $obj->label ? ' - '.dol_trunc($obj->label, 16) : '';
+			if (!empty($obj->description) && !empty($conf->global->PRODUCT_DESC_IN_LIST)) print '<br>'.dol_nl2br($obj->description);
 		}
 		else
 		{
@@ -732,8 +732,8 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
 
 $db->free($resql);
 
-$parameters=array('sql' => $sql);
-$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters);    // Note that $action and $object may have been modified by hook
+$parameters = array('sql' => $sql);
+$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook
 print $hookmanager->resPrint;
 
 print '</table>';

+ 5 - 5
htdocs/core/boxes/box_accountancy_last_manual_entries.php

@@ -32,9 +32,9 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php';
  */
 class box_accountancy_last_manual_entries extends ModeleBoxes
 {
-    public $boxcode="accountancy_last_manual_entries";
-    public $boximg="object_invoice";
-    public $boxlabel="BoxLastManualEntries";
+    public $boxcode = "accountancy_last_manual_entries";
+    public $boximg = "object_invoice";
+    public $boxlabel = "BoxLastManualEntries";
     public $depends = array("accounting");
 
 	/**
@@ -60,7 +60,7 @@ class box_accountancy_last_manual_entries extends ModeleBoxes
 
         $this->db = $db;
 
-        $this->hidden = ! ($user->rights->accounting->mouvements->lire);
+        $this->hidden = !($user->rights->accounting->mouvements->lire);
     }
 
     /**
@@ -140,7 +140,7 @@ class box_accountancy_last_manual_entries extends ModeleBoxes
                     $line++;
                 }
 
-                if ($num==0) $this->info_box_contents[$line][0] = array('td' => 'class="center"','text'=>$langs->trans("NoRecordedManualEntries"));
+                if ($num == 0) $this->info_box_contents[$line][0] = array('td' => 'class="center"', 'text'=>$langs->trans("NoRecordedManualEntries"));
 
                 $this->db->free($result);
             } else {

+ 4 - 4
htdocs/core/boxes/box_accountancy_suspense_account.php

@@ -32,9 +32,9 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php';
  */
 class box_accountancy_suspense_account extends ModeleBoxes
 {
-    public $boxcode="accountancy_suspense_account";
-    public $boximg="object_invoice";
-    public $boxlabel="BoxSuspenseAccount";
+    public $boxcode = "accountancy_suspense_account";
+    public $boximg = "object_invoice";
+    public $boxlabel = "BoxSuspenseAccount";
     public $depends = array("accounting");
 
     /**
@@ -60,7 +60,7 @@ class box_accountancy_suspense_account extends ModeleBoxes
 
         $this->db = $db;
 
-        $this->hidden = ! ($user->rights->accounting->mouvements->lire);
+        $this->hidden = !($user->rights->accounting->mouvements->lire);
     }
 
     /**

+ 19 - 19
htdocs/core/boxes/box_bookmarks.php

@@ -28,9 +28,9 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php';
  */
 class box_bookmarks extends ModeleBoxes
 {
-    public $boxcode="bookmarks";
-    public $boximg="bookmark";
-    public $boxlabel="BoxMyLastBookmarks";
+    public $boxcode = "bookmarks";
+    public $boximg = "bookmark";
+    public $boxlabel = "BoxMyLastBookmarks";
     public $depends = array("bookmark");
 
 	/**
@@ -56,7 +56,7 @@ class box_bookmarks extends ModeleBoxes
 
 	    $this->db = $db;
 
-	    $this->hidden = ! ($user->rights->bookmark->lire);
+	    $this->hidden = !($user->rights->bookmark->lire);
 	}
 
 	/**
@@ -70,30 +70,30 @@ class box_bookmarks extends ModeleBoxes
 		global $user, $langs, $conf;
 		$langs->load("boxes");
 
-		$this->max=$max;
+		$this->max = $max;
 
 		$this->info_box_head = array(
             'text' => $langs->trans("BoxMyLastBookmarks", $max),
             'sublink' => DOL_URL_ROOT.'/bookmarks/list.php',
         );
         if ($user->rights->bookmark->creer) {
-			$this->info_box_head['subpicto']='bookmark';
-			$this->info_box_head['subtext']=$langs->trans("BookmarksManagement");
+			$this->info_box_head['subpicto'] = 'bookmark';
+			$this->info_box_head['subtext'] = $langs->trans("BookmarksManagement");
 		}
 		else
 		{
-			$this->info_box_head['subpicto']='bookmark';
-			$this->info_box_head['subtext']=$langs->trans("ListOfBookmark");
+			$this->info_box_head['subpicto'] = 'bookmark';
+			$this->info_box_head['subtext'] = $langs->trans("ListOfBookmark");
 		}
 
 		if ($user->rights->bookmark->lire)
 		{
 			$sql = "SELECT b.title, b.url, b.target, b.favicon";
-			$sql.= " FROM ".MAIN_DB_PREFIX."bookmark as b";
-			$sql.= " WHERE fk_user = ".$user->id;
-            $sql.= " AND b.entity = ".$conf->entity;
-			$sql.= $this->db->order("position", "ASC");
-			$sql.= $this->db->plimit($max, 0);
+			$sql .= " FROM ".MAIN_DB_PREFIX."bookmark as b";
+			$sql .= " WHERE fk_user = ".$user->id;
+            $sql .= " AND b.entity = ".$conf->entity;
+			$sql .= $this->db->order("position", "ASC");
+			$sql .= $this->db->plimit($max, 0);
 
 			$result = $this->db->query($sql);
 			if ($result)
@@ -110,22 +110,22 @@ class box_bookmarks extends ModeleBoxes
                         'logo' => $this->boximg,
                         'url' => $objp->url,
                         'tooltip' => $objp->title,
-                        'target' => $objp->target?'newtab':'',
+                        'target' => $objp->target ? 'newtab' : '',
                     );
                     $this->info_box_contents[$line][1] = array(
                         'td' => '',
                         'text' => $objp->title,
                         'url' => $objp->url,
                         'tooltip' => $objp->title,
-                        'target' => $objp->target?'newtab':'',
+                        'target' => $objp->target ? 'newtab' : '',
                     );
 
                     $line++;
                 }
 
-                if ($num==0) {
-                    $mytxt=$langs->trans("NoRecordedBookmarks");
-                    if ($user->rights->bookmark->creer) $mytxt.=' '.$langs->trans("ClickToAdd");
+                if ($num == 0) {
+                    $mytxt = $langs->trans("NoRecordedBookmarks");
+                    if ($user->rights->bookmark->creer) $mytxt .= ' '.$langs->trans("ClickToAdd");
                     $this->info_box_contents[$line][0] = array(
                         'td' => 'class="center" colspan="2"',
                         'tooltip' => $mytxt,

+ 74 - 74
htdocs/core/class/commondocgenerator.class.php

@@ -37,7 +37,7 @@ abstract class CommonDocGenerator
 	/**
 	 * @var string Error code (or message)
 	 */
-	public $error='';
+	public $error = '';
 
     /**
      * @var string[]    Array of error strings
@@ -74,7 +74,7 @@ abstract class CommonDocGenerator
         // phpcs:enable
         global $conf;
 
-        $logotouse=$conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo;
+        $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo;
 
         return array(
             'myuser_lastname'=>$user->lastname,
@@ -112,20 +112,20 @@ abstract class CommonDocGenerator
         // phpcs:enable
         global $conf;
 
-        if (empty($mysoc->forme_juridique) && ! empty($mysoc->forme_juridique_code))
+        if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code))
         {
-            $mysoc->forme_juridique=getFormeJuridiqueLabel($mysoc->forme_juridique_code);
+            $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code);
         }
-        if (empty($mysoc->country) && ! empty($mysoc->country_code))
+        if (empty($mysoc->country) && !empty($mysoc->country_code))
         {
-        	$mysoc->country=$outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
+        	$mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
         }
-        if (empty($mysoc->state) && ! empty($mysoc->state_code))
+        if (empty($mysoc->state) && !empty($mysoc->state_code))
         {
-        	$mysoc->state=getState($mysoc->state_code, 0);
+        	$mysoc->state = getState($mysoc->state_code, 0);
         }
 
-        $logotouse=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small;
+        $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small;
 
         return array(
             'mycompany_logo'=>$logotouse,
@@ -172,13 +172,13 @@ abstract class CommonDocGenerator
         // phpcs:enable
         global $conf;
 
-        if (empty($object->country) && ! empty($object->country_code))
+        if (empty($object->country) && !empty($object->country_code))
         {
-        	$object->country=$outputlangs->transnoentitiesnoconv("Country".$object->country_code);
+        	$object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code);
         }
-        if (empty($object->state) && ! empty($object->state_code))
+        if (empty($object->state) && !empty($object->state_code))
         {
-        	$object->state=getState($object->state_code, 0);
+        	$object->state = getState($object->state_code, 0);
         }
 
         $array_thirdparty = array(
@@ -326,7 +326,7 @@ abstract class CommonDocGenerator
         // phpcs:enable
     	global $conf;
 
-    	$now=dol_now('gmt');	// gmt
+    	$now = dol_now('gmt'); // gmt
     	$array_other = array(
     	    // Date in default language
     	    'current_date'=>dol_print_date($now, 'day', 'tzuser'),
@@ -341,7 +341,7 @@ abstract class CommonDocGenerator
     	);
 
 
-    	foreach($conf->global as $key => $val)
+    	foreach ($conf->global as $key => $val)
     	{
     		if (preg_match('/(_pass|password|secret|_key|key$)/i', $key)) $newval = '*****forbidden*****';
     		else $newval = $val;
@@ -366,12 +366,12 @@ abstract class CommonDocGenerator
         // phpcs:enable
 		global $conf;
 
-		$sumpayed=$sumdeposit=$sumcreditnote='';
-		$already_payed_all=0;
-		$remain_to_pay=0;
+		$sumpayed = $sumdeposit = $sumcreditnote = '';
+		$already_payed_all = 0;
+		$remain_to_pay = 0;
 		if ($object->element == 'facture')
 		{
-			$invoice_source=new Facture($this->db);
+			$invoice_source = new Facture($this->db);
 			if ($object->fk_facture_source > 0)
 			{
 				$invoice_source->fetch($object->fk_facture_source);
@@ -379,44 +379,44 @@ abstract class CommonDocGenerator
 			$sumpayed = $object->getSommePaiement();
 			$sumdeposit = $object->getSumDepositsUsed();
 			$sumcreditnote = $object->getSumCreditNotesUsed();
-			$already_payed_all=$sumpayed + $sumdeposit + $sumcreditnote;
-			$remain_to_pay=$sumpayed - $sumdeposit - $sumcreditnote;
+			$already_payed_all = $sumpayed + $sumdeposit + $sumcreditnote;
+			$remain_to_pay = $sumpayed - $sumdeposit - $sumcreditnote;
 		}
 
 		$date = ($object->element == 'contrat' ? $object->date_contrat : $object->date);
 
-		$resarray=array(
+		$resarray = array(
 		$array_key.'_id'=>$object->id,
 		$array_key.'_ref'=>$object->ref,
 		$array_key.'_ref_ext'=>$object->ref_ext,
-		$array_key.'_ref_customer'=>(! empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)),
-		$array_key.'_ref_supplier'=>(! empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)),
+		$array_key.'_ref_customer'=>(!empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)),
+		$array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)),
 		$array_key.'_source_invoice_ref'=>$invoice_source->ref,
 		// Dates
         $array_key.'_hour'=>dol_print_date($date, 'hour'),
 		$array_key.'_date'=>dol_print_date($date, 'day'),
 		$array_key.'_date_rfc'=>dol_print_date($date, 'dayrfc'),
-		$array_key.'_date_limit'=>(! empty($object->date_lim_reglement)?dol_print_date($object->date_lim_reglement, 'day'):''),
-	    $array_key.'_date_end'=>(! empty($object->fin_validite)?dol_print_date($object->fin_validite, 'day'):''),
+		$array_key.'_date_limit'=>(!empty($object->date_lim_reglement) ?dol_print_date($object->date_lim_reglement, 'day') : ''),
+	    $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''),
 		$array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
-		$array_key.'_date_modification'=>(! empty($object->date_modification)?dol_print_date($object->date_modification, 'day'):''),
-		$array_key.'_date_validation'=>(! empty($object->date_validation)?dol_print_date($object->date_validation, 'dayhour'):''),
-		$array_key.'_date_delivery_planed'=>(! empty($object->date_livraison)?dol_print_date($object->date_livraison, 'day'):''),
-		$array_key.'_date_close'=>(! empty($object->date_cloture)?dol_print_date($object->date_cloture, 'dayhour'):''),
+		$array_key.'_date_modification'=>(!empty($object->date_modification) ?dol_print_date($object->date_modification, 'day') : ''),
+		$array_key.'_date_validation'=>(!empty($object->date_validation) ?dol_print_date($object->date_validation, 'dayhour') : ''),
+		$array_key.'_date_delivery_planed'=>(!empty($object->date_livraison) ?dol_print_date($object->date_livraison, 'day') : ''),
+		$array_key.'_date_close'=>(!empty($object->date_cloture) ?dol_print_date($object->date_cloture, 'dayhour') : ''),
 
 		$array_key.'_payment_mode_code'=>$object->mode_reglement_code,
-		$array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code)!='PaymentType'.$object->mode_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code):$object->mode_reglement),
+		$array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) != 'PaymentType'.$object->mode_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) : $object->mode_reglement),
 		$array_key.'_payment_term_code'=>$object->cond_reglement_code,
-		$array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code)!='PaymentCondition'.$object->cond_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code):($object->cond_reglement_doc?$object->cond_reglement_doc:$object->cond_reglement)),
+		$array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) != 'PaymentCondition'.$object->cond_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) : ($object->cond_reglement_doc ? $object->cond_reglement_doc : $object->cond_reglement)),
 
 		$array_key.'_total_ht_locale'=>price($object->total_ht, 0, $outputlangs),
-		$array_key.'_total_vat_locale'=>(! empty($object->total_vat)?price($object->total_vat, 0, $outputlangs):price($object->total_tva, 0, $outputlangs)),
+		$array_key.'_total_vat_locale'=>(!empty($object->total_vat) ?price($object->total_vat, 0, $outputlangs) : price($object->total_tva, 0, $outputlangs)),
 		$array_key.'_total_localtax1_locale'=>price($object->total_localtax1, 0, $outputlangs),
 		$array_key.'_total_localtax2_locale'=>price($object->total_localtax2, 0, $outputlangs),
 		$array_key.'_total_ttc_locale'=>price($object->total_ttc, 0, $outputlangs),
 
 		$array_key.'_total_ht'=>price2num($object->total_ht),
-		$array_key.'_total_vat'=>(! empty($object->total_vat)?price2num($object->total_vat):price2num($object->total_tva)),
+		$array_key.'_total_vat'=>(!empty($object->total_vat) ?price2num($object->total_vat) : price2num($object->total_tva)),
 		$array_key.'_total_localtax1'=>price2num($object->total_localtax1),
 		$array_key.'_total_localtax2'=>price2num($object->total_localtax2),
 		$array_key.'_total_ttc'=>price2num($object->total_ttc),
@@ -432,7 +432,7 @@ abstract class CommonDocGenerator
 
 		$array_key.'_note_private'=>$object->note,
 		$array_key.'_note_public'=>$object->note_public,
-		$array_key.'_note'=>$object->note_public,			// For backward compatibility
+		$array_key.'_note'=>$object->note_public, // For backward compatibility
 
 		// Payments
 		$array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs),
@@ -459,9 +459,9 @@ abstract class CommonDocGenerator
 		}
 
 		// Fetch project information if there is a project assigned to this object
-		if ($object->element != "project" && ! empty($object->fk_project) && $object->fk_project > 0)
+		if ($object->element != "project" && !empty($object->fk_project) && $object->fk_project > 0)
 		{
-			if (! is_object($object->project))
+			if (!is_object($object->project))
 			{
 				$object->fetch_projet();
 			}
@@ -497,23 +497,23 @@ abstract class CommonDocGenerator
 			$resarray['object_total_up'] = $totalUp;
 			$resarray['object_total_up_locale'] = price($resarray['object_total_up'], 0, $outputlangs);
 			if (method_exists($object, 'getTotalDiscount')) {
-				$totalDiscount=$object->getTotalDiscount();
+				$totalDiscount = $object->getTotalDiscount();
 			} else {
-				$totalDiscount=0;
+				$totalDiscount = 0;
 			}
 			if (!empty($totalUp) && !empty($totalDiscount)) {
 				$resarray['object_total_discount'] = round(100 / $totalUp * $totalDiscount, 2);
 				$resarray['object_total_discount_locale'] = price($resarray['object_total_discount'], 0, $outputlangs);
 			} else {
-				$resarray['object_total_discount']='';
-				$resarray['object_total_discount_locale']='';
+				$resarray['object_total_discount'] = '';
+				$resarray['object_total_discount_locale'] = '';
 			}
 		}
 
 		// Retrieve extrafields
 		if (is_array($object->array_options) && count($object->array_options))
 		{
-			$extrafieldkey=$object->element;
+			$extrafieldkey = $object->element;
 
 			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
 			$extrafields = new ExtraFields($this->db);
@@ -539,7 +539,7 @@ abstract class CommonDocGenerator
         // phpcs:enable
 		global $conf;
 
-		$resarray= array(
+		$resarray = array(
 			'line_fulldesc'=>doc_getlinedesc($line, $outputlangs),
 			'line_product_ref'=>$line->product_ref,
 			'line_product_ref_fourn'=>$line->ref_fourn, // for supplier doc lines
@@ -554,7 +554,7 @@ abstract class CommonDocGenerator
 			'line_total_up'=>price2num($line->subprice * $line->qty),
 			'line_total_up_locale'=>price($line->subprice * $line->qty, 0, $outputlangs),
 			'line_qty'=>$line->qty,
-			'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
+			'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''),
 			'line_price_ht'=>price2num($line->total_ht),
 			'line_price_ttc'=>price2num($line->total_ttc),
 			'line_price_vat'=>price2num($line->total_tva),
@@ -625,7 +625,7 @@ abstract class CommonDocGenerator
 		{
 			$tmpproduct = new Product($this->db);
 			$result = $tmpproduct->fetch($line->fk_product);
-			foreach($tmpproduct->array_options as $key=>$label)
+			foreach ($tmpproduct->array_options as $key=>$label)
 				$resarray["line_product_".$key] = $label;
 		}
 
@@ -647,9 +647,9 @@ abstract class CommonDocGenerator
     	global $conf;
 		dol_include_once('/core/lib/product.lib.php');
 		$object->list_delivery_methods($object->shipping_method_id);
-		$calculatedVolume=($object->trueWidth * $object->trueHeight * $object->trueDepth);
+		$calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth);
 
-    	$array_shipment=array(
+    	$array_shipment = array(
 	    	$array_key.'_id'=>$object->id,
 	    	$array_key.'_ref'=>$object->ref,
 	    	$array_key.'_ref_ext'=>$object->ref_ext,
@@ -676,8 +676,8 @@ abstract class CommonDocGenerator
     	// Add vat by rates
     	foreach ($object->lines as $line)
     	{
-    		if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx]=0;
-    		$array_shipment[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva;
+    		if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0;
+    		$array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
     	}
 
     	// Retrieve extrafields
@@ -758,7 +758,7 @@ abstract class CommonDocGenerator
         // phpcs:enable
         $array_other = array();
         if (!empty($object)) {
-            foreach($object as $key => $value) {
+            foreach ($object as $key => $value) {
                 if (!empty($value)) {
                     if (!is_array($value) && !is_object($value)) {
                         $array_other['object_'.$key] = $value;
@@ -862,7 +862,7 @@ abstract class CommonDocGenerator
 				}
 			}
 
-			$array_to_fill=array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key]));
+			$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key]));
 		}
 
 		return $array_to_fill;
@@ -883,10 +883,10 @@ abstract class CommonDocGenerator
 	 */
     public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0)
     {
-        if (empty($hidetop) || $hidetop==-1) $pdf->line($x, $y, $x+$l, $y);
-        $pdf->line($x+$l, $y, $x+$l, $y+$h);
-        if (empty($hidebottom)) $pdf->line($x+$l, $y+$h, $x, $y+$h);
-        $pdf->line($x, $y+$h, $x, $y);
+        if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y);
+        $pdf->line($x + $l, $y, $x + $l, $y + $h);
+        if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h);
+        $pdf->line($x, $y + $h, $x, $y);
     }
 
 
@@ -899,8 +899,8 @@ abstract class CommonDocGenerator
      */
     public function columnSort($a, $b)
     {
-        if(empty($a['rank'])){ $a['rank'] = 0; }
-        if(empty($b['rank'])){ $b['rank'] = 0; }
+        if (empty($a['rank'])) { $a['rank'] = 0; }
+        if (empty($b['rank'])) { $b['rank'] = 0; }
         if ($a['rank'] == $b['rank']) {
             return 0;
         }
@@ -956,25 +956,25 @@ abstract class CommonDocGenerator
         foreach ($this->cols as $colKey =>& $colDef)
         {
             // setting empty conf with default
-            if(!empty($colDef['title'])){
+            if (!empty($colDef['title'])) {
                 $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']);
             }
-            else{
+            else {
                 $colDef['title'] = $this->defaultTitlesFieldsStyle;
             }
 
             // setting empty conf with default
-            if(!empty($colDef['content'])){
+            if (!empty($colDef['content'])) {
                 $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']);
             }
-            else{
+            else {
                 $colDef['content'] = $this->defaultContentsFieldsStyle;
             }
 
-            if($this->getColumnStatus($colKey))
+            if ($this->getColumnStatus($colKey))
             {
                 // In case of flexible column
-                if(empty($colDef['width'])){
+                if (empty($colDef['width'])) {
                     $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol;
                 }
 
@@ -1020,7 +1020,7 @@ abstract class CommonDocGenerator
      */
     public function getColumnRank($colKey)
     {
-        if(!isset($this->cols[$colKey]['rank'])) return -1;
+        if (!isset($this->cols[$colKey]['rank'])) return -1;
         return  $this->cols[$colKey]['rank'];
     }
 
@@ -1039,22 +1039,22 @@ abstract class CommonDocGenerator
         $rank = -1;
 
         // try to get rank from target column
-        if(!empty($targetCol)){
+        if (!empty($targetCol)) {
             $rank = $this->getColumnRank($targetCol);
-            if($rank>=0 && $insertAfterTarget){ $rank++; }
+            if ($rank >= 0 && $insertAfterTarget) { $rank++; }
         }
 
         // get rank from new column definition
-        if($rank<0 && !empty($defArray['rank'])){
+        if ($rank < 0 && !empty($defArray['rank'])) {
             $rank = $defArray['rank'];
         }
 
         // error: no rank
-        if($rank<0){ return -1; }
+        if ($rank < 0) { return -1; }
 
         foreach ($this->cols as $colKey =>& $colDef)
         {
-            if( $rank <= $colDef['rank'])
+            if ($rank <= $colDef['rank'])
             {
                 $colDef['rank'] = $colDef['rank'] + 1;
             }
@@ -1080,16 +1080,16 @@ abstract class CommonDocGenerator
     {
         global $hookmanager;
 
-        $parameters=array(
+        $parameters = array(
             'curY' => &$curY,
             'columnText' => $columnText,
             'colKey' => $colKey
         );
-        $reshook=$hookmanager->executeHooks('printStdColumnContent', $parameters, $this);    // Note that $action and $object may have been modified by hook
+        $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook
         if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
         if (!$reshook)
         {
-            if(empty($columnText)) return;
+            if (empty($columnText)) return;
             $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position
             $colDef = $this->cols[$colKey];
             $pdf->writeHTMLCell($this->getColumnContentWidth($colKey), 2, $this->getColumnContentXStart($colKey), $curY, $columnText, 0, 0, 0, true, $colDef['content']['align']);
@@ -1105,7 +1105,7 @@ abstract class CommonDocGenerator
      */
     public function getColumnStatus($colKey)
     {
-        if( !empty($this->cols[$colKey]['status'])){
+        if (!empty($this->cols[$colKey]['status'])) {
             return true;
         }
         else  return  false;
@@ -1135,7 +1135,7 @@ abstract class CommonDocGenerator
                 'hidetop' => $hidetop
             );
 
-            $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this);    // Note that $object may have been modified by hook
+            $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook
             if ($reshook < 0) {
                 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
             } elseif (empty($reshook)) {

File diff suppressed because it is too large
+ 247 - 247
htdocs/core/class/commonobject.class.php


+ 73 - 73
htdocs/core/class/cunits.class.php

@@ -35,7 +35,7 @@ class CUnits // extends CommonObject
 	/**
 	 * @var string Error code (or message)
 	 */
-	public $error='';
+	public $error = '';
 
 	/**
 	 * @var string[] Error codes (or messages)
@@ -82,45 +82,45 @@ class CUnits // extends CommonObject
     public function create($user, $notrigger = 0)
     {
     	global $conf, $langs;
-		$error=0;
+		$error = 0;
 
 		// Clean parameters
 
 		if (isset($this->id)) $this->id = (int) $this->id;
-		if (isset($this->code)) $this->code=trim($this->code);
-		if (isset($this->label)) $this->libelle=trim($this->label);
-		if (isset($this->short_label)) $this->libelle=trim($this->short_label);
-		if (isset($this->unit_type)) $this->active=trim($this->unit_type);
-		if (isset($this->active)) $this->active=trim($this->active);
-		if (isset($this->scale)) $this->scale=trim($this->scale);
+		if (isset($this->code)) $this->code = trim($this->code);
+		if (isset($this->label)) $this->libelle = trim($this->label);
+		if (isset($this->short_label)) $this->libelle = trim($this->short_label);
+		if (isset($this->unit_type)) $this->active = trim($this->unit_type);
+		if (isset($this->active)) $this->active = trim($this->active);
+		if (isset($this->scale)) $this->scale = trim($this->scale);
 
 		// Check parameters
 		// Put here code to add control on parameters values
 
         // Insert request
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_units(";
-		$sql.= "rowid,";
-		$sql.= "code,";
-		$sql.= "label,";
-		$sql.= "short_label,";
-		$sql.= "unit_type";
-		$sql.= "scale";
-        $sql.= ") VALUES (";
-		$sql.= " ".(! isset($this->id)?'NULL':"'".$this->db->escape($this->id)."'").",";
-		$sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").",";
-		$sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").",";
-		$sql.= " ".(! isset($this->short_label)?'NULL':"'".$this->db->escape($this->short_label)."'").",";
-		$sql.= " ".(! isset($this->unit_type)?'NULL':"'".$this->db->escape($this->unit_type)."'");
-		$sql.= " ".(! isset($this->scale)?'NULL':"'".$this->db->escape($this->scale)."'");
-		$sql.= ")";
+		$sql .= "rowid,";
+		$sql .= "code,";
+		$sql .= "label,";
+		$sql .= "short_label,";
+		$sql .= "unit_type";
+		$sql .= "scale";
+        $sql .= ") VALUES (";
+		$sql .= " ".(!isset($this->id) ? 'NULL' : "'".$this->db->escape($this->id)."'").",";
+		$sql .= " ".(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").",";
+		$sql .= " ".(!isset($this->label) ? 'NULL' : "'".$this->db->escape($this->label)."'").",";
+		$sql .= " ".(!isset($this->short_label) ? 'NULL' : "'".$this->db->escape($this->short_label)."'").",";
+		$sql .= " ".(!isset($this->unit_type) ? 'NULL' : "'".$this->db->escape($this->unit_type)."'");
+		$sql .= " ".(!isset($this->scale) ? 'NULL' : "'".$this->db->escape($this->scale)."'");
+		$sql .= ")";
 
 		$this->db->begin();
 
 	   	dol_syslog(get_class($this)."::create", LOG_DEBUG);
-        $resql=$this->db->query($sql);
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
+        $resql = $this->db->query($sql);
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
 
-		if (! $error)
+		if (!$error)
         {
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_units");
 
@@ -141,13 +141,13 @@ class CUnits // extends CommonObject
         // Commit or rollback
         if ($error)
 		{
-			foreach($this->errors as $errmsg)
+			foreach ($this->errors as $errmsg)
 			{
 	            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
 			}
 			$this->db->rollback();
-			return -1*$error;
+			return -1 * $error;
 		}
 		else
 		{
@@ -171,32 +171,32 @@ class CUnits // extends CommonObject
     	global $langs;
 
         $sql = "SELECT";
-		$sql.= " t.rowid,";
-		$sql.= " t.code,";
-		$sql.= " t.label,";
-		$sql.= " t.short_label,";
-		$sql.= " t.scale,";
-		$sql.= " t.unit_type,";
-		$sql.= " t.scale,";
-		$sql.= " t.active";
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_units as t";
-        $sql_where=array();
-        if ($id)   $sql_where[]= " t.id = ".$id;
-        if ($unit_type)   $sql_where[]= " t.unit_type = '".$this->db->escape($unit_type)."'";
-        if ($code) $sql_where[]= " t.code = '".$this->db->escape($code)."'";
-        if ($short_label) $sql_where[]= " t.short_label = '".$this->db->escape($short_label)."'";
-        if (count($sql_where)>0) {
-        	$sql.=' WHERE '. implode(' AND ', $sql_where);
+		$sql .= " t.rowid,";
+		$sql .= " t.code,";
+		$sql .= " t.label,";
+		$sql .= " t.short_label,";
+		$sql .= " t.scale,";
+		$sql .= " t.unit_type,";
+		$sql .= " t.scale,";
+		$sql .= " t.active";
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t";
+        $sql_where = array();
+        if ($id)   $sql_where[] = " t.id = ".$id;
+        if ($unit_type)   $sql_where[] = " t.unit_type = '".$this->db->escape($unit_type)."'";
+        if ($code) $sql_where[] = " t.code = '".$this->db->escape($code)."'";
+        if ($short_label) $sql_where[] = " t.short_label = '".$this->db->escape($short_label)."'";
+        if (count($sql_where) > 0) {
+        	$sql .= ' WHERE '.implode(' AND ', $sql_where);
         }
 
-        $resql=$this->db->query($sql);
+        $resql = $this->db->query($sql);
         if ($resql)
         {
             if ($this->db->num_rows($resql))
             {
                 $obj = $this->db->fetch_object($resql);
 
-                $this->id    = $obj->rowid;
+                $this->id = $obj->rowid;
 				$this->code = $obj->code;
 				$this->label = $obj->label;
 				$this->short_label = $obj->short_label;
@@ -211,7 +211,7 @@ class CUnits // extends CommonObject
         }
         else
         {
-      	    $this->error="Error ".$this->db->lasterror();
+      	    $this->error = "Error ".$this->db->lasterror();
             return -1;
         }
     }
@@ -295,8 +295,8 @@ class CUnits // extends CommonObject
 
     		return $this->records;
     	} else {
-    		$this->errors[] = 'Error ' . $this->db->lasterror();
-    		dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
+    		$this->errors[] = 'Error '.$this->db->lasterror();
+    		dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
 
     		return -1;
     	}
@@ -313,34 +313,34 @@ class CUnits // extends CommonObject
     public function update($user = null, $notrigger = 0)
     {
     	global $conf, $langs;
-		$error=0;
+		$error = 0;
 
 		// Clean parameters
-		if (isset($this->code)) $this->code=trim($this->code);
-		if (isset($this->label)) $this->libelle=trim($this->label);
-		if (isset($this->short_label)) $this->libelle=trim($this->short_label);
-		if (isset($this->unit_type)) $this->libelle=trim($this->unit_type);
-		if (isset($this->scale)) $this->scale=trim($this->scale);
-		if (isset($this->active)) $this->active=trim($this->active);
+		if (isset($this->code)) $this->code = trim($this->code);
+		if (isset($this->label)) $this->libelle = trim($this->label);
+		if (isset($this->short_label)) $this->libelle = trim($this->short_label);
+		if (isset($this->unit_type)) $this->libelle = trim($this->unit_type);
+		if (isset($this->scale)) $this->scale = trim($this->scale);
+		if (isset($this->active)) $this->active = trim($this->active);
 
 		// Check parameters
 		// Put here code to add control on parameters values
 
         // Update request
         $sql = "UPDATE ".MAIN_DB_PREFIX."c_units SET";
-		$sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").",";
-		$sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
-		$sql.= " short_label=".(isset($this->short_label)?"'".$this->db->escape($this->short_label)."'":"null").",";
-		$sql.= " unit_type=".(isset($this->unit_type)?"'".$this->db->escape($this->unit_type)."'":"null").",";
-		$sql.= " scale=".(isset($this->scale)?"'".$this->db->escape($this->scale)."'":"null").",";
-		$sql.= " active=".(isset($this->active)?$this->active:"null");
-        $sql.= " WHERE rowid=".$this->id;
+		$sql .= " code=".(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "null").",";
+		$sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
+		$sql .= " short_label=".(isset($this->short_label) ? "'".$this->db->escape($this->short_label)."'" : "null").",";
+		$sql .= " unit_type=".(isset($this->unit_type) ? "'".$this->db->escape($this->unit_type)."'" : "null").",";
+		$sql .= " scale=".(isset($this->scale) ? "'".$this->db->escape($this->scale)."'" : "null").",";
+		$sql .= " active=".(isset($this->active) ? $this->active : "null");
+        $sql .= " WHERE rowid=".$this->id;
 
 		$this->db->begin();
 
 		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(); }
 
 		//if (! $error)
 		//{
@@ -361,13 +361,13 @@ class CUnits // extends CommonObject
         // Commit or rollback
 		if ($error)
 		{
-			foreach($this->errors as $errmsg)
+			foreach ($this->errors as $errmsg)
 			{
 	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
 			}
 			$this->db->rollback();
-			return -1*$error;
+			return -1 * $error;
 		}
 		else
 		{
@@ -387,16 +387,16 @@ class CUnits // extends CommonObject
 	public function delete($user, $notrigger = 0)
 	{
 		global $conf, $langs;
-		$error=0;
+		$error = 0;
 
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."c_units";
-		$sql.= " WHERE rowid=".$this->id;
+		$sql .= " WHERE rowid=".$this->id;
 
 		$this->db->begin();
 
 		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(); }
 
 		//if (! $error)
 		//{
@@ -417,13 +417,13 @@ class CUnits // extends CommonObject
         // Commit or rollback
 		if ($error)
 		{
-			foreach($this->errors as $errmsg)
+			foreach ($this->errors as $errmsg)
 			{
 	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
 			}
 			$this->db->rollback();
-			return -1*$error;
+			return -1 * $error;
 		}
 		else
 		{

+ 117 - 117
htdocs/core/class/discount.class.php

@@ -41,7 +41,7 @@ class DiscountAbsolute
 	/**
 	 * @var string[]	Array of error strings
 	 */
-	public $errors=array();
+	public $errors = array();
 
 	/**
 	 * @var int ID discount
@@ -53,10 +53,10 @@ class DiscountAbsolute
 	 */
     public $fk_soc;
 
-    public $discount_type;		// 0 => customer discount, 1 => supplier discount
-    public $amount_ht;			//
-    public $amount_tva;			//
-    public $amount_ttc;			//
+    public $discount_type; // 0 => customer discount, 1 => supplier discount
+    public $amount_ht; //
+    public $amount_tva; //
+    public $amount_ttc; //
     public $multicurrency_amount_ht;
     public $multicurrency_amount_tva;
     public $multicurrency_amount_ttc;
@@ -193,7 +193,7 @@ class DiscountAbsolute
         }
         else
         {
-            $this->error=$this->db->error();
+            $this->error = $this->db->error();
             return -1;
         }
     }
@@ -210,61 +210,61 @@ class DiscountAbsolute
         global $conf, $langs;
 
         // Clean parameters
-        $this->amount_ht=price2num($this->amount_ht);
-        $this->amount_tva=price2num($this->amount_tva);
-        $this->amount_ttc=price2num($this->amount_ttc);
+        $this->amount_ht = price2num($this->amount_ht);
+        $this->amount_tva = price2num($this->amount_tva);
+        $this->amount_ttc = price2num($this->amount_ttc);
 
-        $this->tva_tx=price2num($this->tva_tx);
+        $this->tva_tx = price2num($this->tva_tx);
 
-        $this->multicurrency_amount_ht=price2num($this->multicurrency_amount_ht);
-        $this->multicurrency_amount_tva=price2num($this->multicurrency_amount_tva);
-        $this->multicurrency_amount_ttc=price2num($this->multicurrency_amount_ttc);
+        $this->multicurrency_amount_ht = price2num($this->multicurrency_amount_ht);
+        $this->multicurrency_amount_tva = price2num($this->multicurrency_amount_tva);
+        $this->multicurrency_amount_ttc = price2num($this->multicurrency_amount_ttc);
 
-        if (empty($this->multicurrency_amount_ht)) $this->multicurrency_amount_ht=0;
-        if (empty($this->multicurrency_amount_tva)) $this->multicurrency_amount_tva=0;
-        if (empty($this->multicurrency_amount_ttc)) $this->multicurrency_amount_ttc=0;
+        if (empty($this->multicurrency_amount_ht)) $this->multicurrency_amount_ht = 0;
+        if (empty($this->multicurrency_amount_tva)) $this->multicurrency_amount_tva = 0;
+        if (empty($this->multicurrency_amount_ttc)) $this->multicurrency_amount_ttc = 0;
 
         // Check parameters
         if (empty($this->description))
         {
-            $this->error='BadValueForPropertyDescription';
+            $this->error = 'BadValueForPropertyDescription';
             dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
             return -1;
         }
 
         $userid = $user->id;
-		if (! ($userid > 0))		// For example when record is saved into an anonymous context with a not loaded object $user.
+		if (!($userid > 0))		// For example when record is saved into an anonymous context with a not loaded object $user.
 		{
 			include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
 			$tmpinvoice = new Facture($this->db);
 			$tmpinvoice->fetch($this->fk_facture_source);
-			$userid = $tmpinvoice->fk_user_author;	// We use the author of invoice
+			$userid = $tmpinvoice->fk_user_author; // We use the author of invoice
 		}
 
         // Insert request
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except";
-        $sql.= " (entity, datec, fk_soc, discount_type, fk_user, description,";
-        $sql.= " amount_ht, amount_tva, amount_ttc, tva_tx,";
-        $sql.= " multicurrency_amount_ht, multicurrency_amount_tva, multicurrency_amount_ttc,";
-        $sql.= " fk_facture_source, fk_invoice_supplier_source";
-        $sql.= ")";
-        $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".(empty($this->discount_type)?0:intval($this->discount_type)).", ".$userid.", '".$this->db->escape($this->description)."',";
-        $sql.= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.",";
-        $sql.= " ".$this->multicurrency_amount_ht.", ".$this->multicurrency_amount_tva.", ".$this->multicurrency_amount_ttc.", ";
-        $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null").",";
-        $sql.= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'":"null");
-        $sql.= ")";
+        $sql .= " (entity, datec, fk_soc, discount_type, fk_user, description,";
+        $sql .= " amount_ht, amount_tva, amount_ttc, tva_tx,";
+        $sql .= " multicurrency_amount_ht, multicurrency_amount_tva, multicurrency_amount_ttc,";
+        $sql .= " fk_facture_source, fk_invoice_supplier_source";
+        $sql .= ")";
+        $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec != '' ? $this->datec : dol_now())."', ".$this->fk_soc.", ".(empty($this->discount_type) ? 0 : intval($this->discount_type)).", ".$userid.", '".$this->db->escape($this->description)."',";
+        $sql .= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.",";
+        $sql .= " ".$this->multicurrency_amount_ht.", ".$this->multicurrency_amount_tva.", ".$this->multicurrency_amount_ttc.", ";
+        $sql .= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null").",";
+        $sql .= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'" : "null");
+        $sql .= ")";
 
         dol_syslog(get_class($this)."::create", LOG_DEBUG);
-        $resql=$this->db->query($sql);
+        $resql = $this->db->query($sql);
         if ($resql)
         {
-            $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX."societe_remise_except");
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe_remise_except");
             return $this->id;
         }
         else
         {
-            $this->error=$this->db->lasterror().' - sql='.$sql;
+            $this->error = $this->db->lasterror().' - sql='.$sql;
             return -1;
         }
     }
@@ -283,21 +283,21 @@ class DiscountAbsolute
         // Check if we can remove the discount
         if ($this->fk_facture_source)
         {
-            $sql="SELECT COUNT(rowid) as nb";
-            $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except";
-            $sql.=" WHERE (fk_facture_line IS NOT NULL";	// Not used as absolute simple discount
-            $sql.=" OR fk_facture IS NOT NULL)"; 			// Not used as credit note and not used as deposit
-            $sql.=" AND fk_facture_source = ".$this->fk_facture_source;
+            $sql = "SELECT COUNT(rowid) as nb";
+            $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except";
+            $sql .= " WHERE (fk_facture_line IS NOT NULL"; // Not used as absolute simple discount
+            $sql .= " OR fk_facture IS NOT NULL)"; // Not used as credit note and not used as deposit
+            $sql .= " AND fk_facture_source = ".$this->fk_facture_source;
             //$sql.=" AND rowid != ".$this->id;
 
             dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG);
-            $resql=$this->db->query($sql);
+            $resql = $this->db->query($sql);
             if ($resql)
             {
                 $obj = $this->db->fetch_object($resql);
                 if ($obj->nb > 0)
                 {
-                    $this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
+                    $this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
                     return -2;
                 }
             }
@@ -311,21 +311,21 @@ class DiscountAbsolute
         // Check if we can remove the discount
         if ($this->fk_invoice_supplier_source)
         {
-            $sql="SELECT COUNT(rowid) as nb";
-            $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except";
-        	$sql.=" WHERE (fk_invoice_supplier_line IS NOT NULL";	// Not used as absolute simple discount
-        	$sql.=" OR fk_invoice_supplier IS NOT NULL)"; 			// Not used as credit note and not used as deposit
-        	$sql.=" AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;
+            $sql = "SELECT COUNT(rowid) as nb";
+            $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except";
+        	$sql .= " WHERE (fk_invoice_supplier_line IS NOT NULL"; // Not used as absolute simple discount
+        	$sql .= " OR fk_invoice_supplier IS NOT NULL)"; // Not used as credit note and not used as deposit
+        	$sql .= " AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;
         	//$sql.=" AND rowid != ".$this->id;
 
         	dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG);
-        	$resql=$this->db->query($sql);
+        	$resql = $this->db->query($sql);
         	if ($resql)
         	{
         		$obj = $this->db->fetch_object($resql);
         		if ($obj->nb > 0)
         		{
-        			$this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
+        			$this->error = 'ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved';
         			return -2;
         		}
         	}
@@ -340,27 +340,27 @@ class DiscountAbsolute
 
         // Delete but only if not used
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except ";
-        if ($this->fk_facture_source) $sql.= " WHERE fk_facture_source = ".$this->fk_facture_source;	// Delete all lines of same serie
-        elseif ($this->fk_invoice_supplier_source) $sql.= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source;	// Delete all lines of same serie
-        else $sql.= " WHERE rowid = ".$this->id;	// Delete only line
-        $sql.= " AND (fk_facture_line IS NULL";	// Not used as absolute simple discount
-        $sql.= " AND fk_facture IS NULL)";		// Not used as credit note and not used as deposit
-        $sql.= " AND (fk_invoice_supplier_line IS NULL";	// Not used as absolute simple discount
-        $sql.= " AND fk_invoice_supplier IS NULL)";		// Not used as credit note and not used as deposit
+        if ($this->fk_facture_source) $sql .= " WHERE fk_facture_source = ".$this->fk_facture_source; // Delete all lines of same serie
+        elseif ($this->fk_invoice_supplier_source) $sql .= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; // Delete all lines of same serie
+        else $sql .= " WHERE rowid = ".$this->id; // Delete only line
+        $sql .= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount
+        $sql .= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit
+        $sql .= " AND (fk_invoice_supplier_line IS NULL"; // Not used as absolute simple discount
+        $sql .= " AND fk_invoice_supplier IS NULL)"; // Not used as credit note and not used as deposit
 
         dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG);
-        $result=$this->db->query($sql);
+        $result = $this->db->query($sql);
         if ($result)
         {
             // If source of discount was a credit note or deposit, we change source statut.
             if ($this->fk_facture_source)
             {
                 $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
-                $sql.=" set paye=0, fk_statut=1";
-                $sql.=" WHERE (type = 2 or type = 3) AND rowid=".$this->fk_facture_source;
+                $sql .= " set paye=0, fk_statut=1";
+                $sql .= " WHERE (type = 2 or type = 3) AND rowid=".$this->fk_facture_source;
 
                 dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG);
-                $result=$this->db->query($sql);
+                $result = $this->db->query($sql);
                 if ($result)
                 {
                     $this->db->commit();
@@ -387,7 +387,7 @@ class DiscountAbsolute
             	}
             	else
             	{
-            		$this->error=$this->db->lasterror();
+            		$this->error = $this->db->lasterror();
             		$this->db->rollback();
             		return -1;
             	}
@@ -400,7 +400,7 @@ class DiscountAbsolute
         }
         else
         {
-            $this->error=$this->db->lasterror();
+            $this->error = $this->db->lasterror();
             $this->db->rollback();
             return -1;
         }
@@ -422,43 +422,43 @@ class DiscountAbsolute
     {
         // phpcs:enable
         // Check parameters
-        if (! $rowidline && ! $rowidinvoice)
+        if (!$rowidline && !$rowidinvoice)
         {
-            $this->error='ErrorBadParameters';
+            $this->error = 'ErrorBadParameters';
             return -1;
         }
         if ($rowidline && $rowidinvoice)
         {
-            $this->error='ErrorBadParameters';
+            $this->error = 'ErrorBadParameters';
             return -2;
         }
 
-        $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
-        if(! empty($this->discount_type)) {
-        	if ($rowidline)    $sql.=" SET fk_invoice_supplier_line = ".$rowidline;
-        	if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice;
+        $sql = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
+        if (!empty($this->discount_type)) {
+        	if ($rowidline)    $sql .= " SET fk_invoice_supplier_line = ".$rowidline;
+        	if ($rowidinvoice) $sql .= " SET fk_invoice_supplier = ".$rowidinvoice;
         } else {
-        	if ($rowidline)    $sql.=" SET fk_facture_line = ".$rowidline;
-        	if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice;
+        	if ($rowidline)    $sql .= " SET fk_facture_line = ".$rowidline;
+        	if ($rowidinvoice) $sql .= " SET fk_facture = ".$rowidinvoice;
         }
-        $sql.=" WHERE rowid = ".$this->id;
+        $sql .= " WHERE rowid = ".$this->id;
 
         dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG);
         $resql = $this->db->query($sql);
         if ($resql)
         {
-        	if(! empty($this->discount_type)) {
-        		$this->fk_invoice_supplier_line=$rowidline;
-        		$this->fk_invoice_supplier=$rowidinvoice;
+        	if (!empty($this->discount_type)) {
+        		$this->fk_invoice_supplier_line = $rowidline;
+        		$this->fk_invoice_supplier = $rowidinvoice;
         	} else {
-        		$this->fk_facture_line=$rowidline;
-        		$this->fk_facture=$rowidinvoice;
+        		$this->fk_facture_line = $rowidline;
+        		$this->fk_facture = $rowidinvoice;
         	}
             return 1;
         }
         else
         {
-            $this->error=$this->db->error();
+            $this->error = $this->db->error();
             return -3;
         }
     }
@@ -474,13 +474,13 @@ class DiscountAbsolute
     public function unlink_invoice()
     {
         // phpcs:enable
-        $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
-        if (! empty($this->discount_type)) {
-            $sql.=" SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL";
+        $sql = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except";
+        if (!empty($this->discount_type)) {
+            $sql .= " SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL";
         } else {
-			$sql.=" SET fk_facture_line = NULL, fk_facture = NULL";
+			$sql .= " SET fk_facture_line = NULL, fk_facture = NULL";
 		}
-        $sql.=" WHERE rowid = ".$this->id;
+        $sql .= " WHERE rowid = ".$this->id;
 
         dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG);
         $resql = $this->db->query($sql);
@@ -490,7 +490,7 @@ class DiscountAbsolute
         }
         else
         {
-            $this->error=$this->db->error();
+            $this->error = $this->db->error();
             return -3;
         }
     }
@@ -512,21 +512,21 @@ class DiscountAbsolute
 
         dol_syslog(get_class($this)."::getAvailableDiscounts discount_type=".$discount_type, LOG_DEBUG);
 
-        $sql  = "SELECT SUM(rc.amount_ttc) as amount";
-        $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc";
-        $sql.= " WHERE rc.entity = " . $conf->entity;
-        $sql.= " AND rc.discount_type=".intval($discount_type);
-        if (! empty($discount_type)) {
-        	$sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier
+        $sql = "SELECT SUM(rc.amount_ttc) as amount";
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc";
+        $sql .= " WHERE rc.entity = ".$conf->entity;
+        $sql .= " AND rc.discount_type=".intval($discount_type);
+        if (!empty($discount_type)) {
+        	$sql .= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier
         } else {
-        	$sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer
+        	$sql .= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer
         }
-        if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id;
-        if (is_object($user))    $sql.= " AND rc.fk_user = ".$user->id;
-        if ($filter)   $sql.=' AND ('.$filter.')';
-        if ($maxvalue) $sql.=' AND rc.amount_ttc <= '.price2num($maxvalue);
+        if (is_object($company)) $sql .= " AND rc.fk_soc = ".$company->id;
+        if (is_object($user))    $sql .= " AND rc.fk_user = ".$user->id;
+        if ($filter)   $sql .= ' AND ('.$filter.')';
+        if ($maxvalue) $sql .= ' AND rc.amount_ttc <= '.price2num($maxvalue);
 
-        $resql=$this->db->query($sql);
+        $resql = $this->db->query($sql);
         if ($resql)
         {
             $obj = $this->db->fetch_object($resql);
@@ -556,25 +556,25 @@ class DiscountAbsolute
         if ($invoice->element == 'facture' || $invoice->element == 'invoice')
         {
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
-            $sql.= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
-            $sql.= ' AND f.type = 3';
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
+            $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
+            $sql .= ' AND f.type = 3';
         }
         elseif ($invoice->element == 'invoice_supplier')
         {
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
-            $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
-            $sql.= ' AND f.type = 3';
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
+            $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
+            $sql .= ' AND f.type = 3';
         }
         else
         {
-            $this->error=get_class($this)."::getSumDepositsUsed was called with a bad object as a first parameter";
+            $this->error = get_class($this)."::getSumDepositsUsed was called with a bad object as a first parameter";
             dol_print_error($this->error);
             return -1;
         }
 
-        $resql=$this->db->query($sql);
+        $resql = $this->db->query($sql);
         if ($resql)
         {
             $obj = $this->db->fetch_object($resql);
@@ -602,25 +602,25 @@ class DiscountAbsolute
         if ($invoice->element == 'facture' || $invoice->element == 'invoice')
         {
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
-            $sql.= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
-            $sql.= ' AND (f.type = 2 OR f.type = 0)';	// Find discount coming from credit note or excess received
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture as f';
+            $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id;
+            $sql .= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess received
         }
         elseif ($invoice->element == 'invoice_supplier')
         {
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
-            $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
-            $sql.= ' AND (f.type = 2 OR f.type = 0)';	// Find discount coming from credit note or excess paid
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f';
+            $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id;
+            $sql .= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess paid
         }
         else
         {
-            $this->error=get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter";
+            $this->error = get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter";
             dol_print_error($this->error);
             return -1;
         }
 
-        $resql=$this->db->query($sql);
+        $resql = $this->db->query($sql);
         if ($resql)
         {
             $obj = $this->db->fetch_object($resql);
@@ -647,23 +647,23 @@ class DiscountAbsolute
         if ($invoice->element == 'facture' || $invoice->element == 'invoice')
         {
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc';
-            $sql.= ' WHERE rc.fk_facture IS NULL AND rc.fk_facture_source = '.$invoice->id;
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc';
+            $sql .= ' WHERE rc.fk_facture IS NULL AND rc.fk_facture_source = '.$invoice->id;
         }
         elseif ($invoice->element == 'invoice_supplier')
         {
             $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount';
-            $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc';
-            $sql.= ' WHERE rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_source = '.$invoice->id;
+            $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc';
+            $sql .= ' WHERE rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_source = '.$invoice->id;
         }
         else
         {
-            $this->error=get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter";
+            $this->error = get_class($this)."::getSumCreditNotesUsed was called with a bad object as a first parameter";
             dol_print_error($this->error);
             return -1;
         }
 
-        $resql=$this->db->query($sql);
+        $resql = $this->db->query($sql);
         if ($resql)
         {
             $obj = $this->db->fetch_object($resql);
@@ -724,7 +724,7 @@ class DiscountAbsolute
 	 */
 	public function initAsSpecimen()
 	{
-		global $user,$langs,$conf;
+		global $user, $langs, $conf;
 
 		$this->fk_soc         = 1;
 		$this->amount_ht      = 10;

+ 151 - 151
htdocs/core/class/dolgraph.class.php

@@ -39,54 +39,54 @@
  */
 class DolGraph
 {
-	public $type=array();			// Array with type of each series. Example: array('bars', 'lines', ...)
-	public $mode='side';		    // Mode bars graph: side, depth
-	private $_library='jflot';	// Graphic library to use (jflot, artichow)
+	public $type = array(); // Array with type of each series. Example: array('bars', 'lines', ...)
+	public $mode = 'side'; // Mode bars graph: side, depth
+	private $_library = 'jflot'; // Graphic library to use (jflot, artichow)
 
 	//! Array of data
-	public $data;				// Data of graph: array(array('abs1',valA1,valB1), array('abs2',valA2,valB2), ...)
-	public $title;				// Title of graph
-	public $cssprefix='';		// To add into css styles
+	public $data; // Data of graph: array(array('abs1',valA1,valB1), array('abs2',valA2,valB2), ...)
+	public $title; // Title of graph
+	public $cssprefix = ''; // To add into css styles
 
 	/**
 	 * @var int|string 		Width of graph. It can be a numeric for pixels or a string like '100%'
 	 */
-	public $width=380;
+	public $width = 380;
 	/**
 	 * @var int 			Height of graph
 	 */
-	public $height=200;
+	public $height = 200;
 
-	public $MaxValue=0;
-	public $MinValue=0;
-	public $SetShading=0;
+	public $MaxValue = 0;
+	public $MinValue = 0;
+	public $SetShading = 0;
 
-	public $horizTickIncrement=-1;
-	public $SetNumXTicks=-1;
-	public $labelInterval=-1;
+	public $horizTickIncrement = -1;
+	public $SetNumXTicks = -1;
+	public $labelInterval = -1;
 
-	public $hideXGrid=false;
-	public $hideYGrid=false;
+	public $hideXGrid = false;
+	public $hideYGrid = false;
 
-	public $Legend=array();
-	public $LegendWidthMin=0;
-	public $showlegend=1;
-	public $showpointvalue=1;
-	public $showpercent=0;
-	public $combine=0;				// 0.05 if you want to combine records < 5% into "other"
-	public $graph;     			// Objet Graph (Artichow, Phplot...)
+	public $Legend = array();
+	public $LegendWidthMin = 0;
+	public $showlegend = 1;
+	public $showpointvalue = 1;
+	public $showpercent = 0;
+	public $combine = 0; // 0.05 if you want to combine records < 5% into "other"
+	public $graph; // Objet Graph (Artichow, Phplot...)
 
 	/**
 	 * @var string Error code (or message)
 	 */
-	public $error='';
+	public $error = '';
 
-	public $bordercolor;			// array(R,G,B)
-	public $bgcolor;				// array(R,G,B)
-	public $bgcolorgrid=array(255,255,255);			// array(R,G,B)
-	public $datacolor;				// array(array(R,G,B),...)
+	public $bordercolor; // array(R,G,B)
+	public $bgcolor; // array(R,G,B)
+	public $bgcolorgrid = array(255, 255, 255); // array(R,G,B)
+	public $datacolor; // array(array(R,G,B),...)
 
-	private $stringtoshow;      // To store string to output graph into HTML page
+	private $stringtoshow; // To store string to output graph into HTML page
 
 
 	/**
@@ -102,24 +102,24 @@ class DolGraph
 		// To use old feature
 		if ($library == 'artichow')
 		{
-			$this->_library='artichow';
+			$this->_library = 'artichow';
 
 			// Test if module GD present
 			$modules_list = get_loaded_extensions();
-			$isgdinstalled=0;
+			$isgdinstalled = 0;
 			foreach ($modules_list as $module)
 			{
-				if ($module == 'gd') $isgdinstalled=1;
+				if ($module == 'gd') $isgdinstalled = 1;
 			}
-			if (! $isgdinstalled)
+			if (!$isgdinstalled)
 			{
-				$this->error="Error: PHP GD module is not available. It is required to build graphics.";
+				$this->error = "Error: PHP GD module is not available. It is required to build graphics.";
 			}
 		}
 
-		$this->bordercolor = array(235,235,224);
-		$this->datacolor = array(array(120,130,150), array(160,160,180), array(190,190,220));
-		$this->bgcolor = array(235,235,224);
+		$this->bordercolor = array(235, 235, 224);
+		$this->datacolor = array(array(120, 130, 150), array(160, 160, 180), array(190, 190, 220));
+		$this->bgcolor = array(235, 235, 224);
 
 		$color_file = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php';
 		if (is_readable($color_file))
@@ -453,7 +453,7 @@ class DolGraph
 	 */
     public function setShowLegend($showlegend)
 	{
-		$this->showlegend=$showlegend;
+		$this->showlegend = $showlegend;
 	}
 
 	/**
@@ -464,7 +464,7 @@ class DolGraph
 	 */
     public function setShowPointValue($showpointvalue)
 	{
-		$this->showpointvalue=$showpointvalue;
+		$this->showpointvalue = $showpointvalue;
 	}
 
 	/**
@@ -475,7 +475,7 @@ class DolGraph
 	 */
     public function setShowPercent($showpercent)
 	{
-		$this->showpercent=$showpercent;
+		$this->showpercent = $showpercent;
 	}
 
 
@@ -487,12 +487,12 @@ class DolGraph
 	 * @param	array	$bg_color		array(R,G,B) ou 'onglet' ou 'default'
 	 * @return	void
 	 */
-    public function SetBgColor($bg_color = array(255,255,255))
+    public function SetBgColor($bg_color = array(255, 255, 255))
 	{
         // phpcs:enable
-		global $theme_bgcolor,$theme_bgcoloronglet;
+		global $theme_bgcolor, $theme_bgcoloronglet;
 
-		if (! is_array($bg_color))
+		if (!is_array($bg_color))
 		{
 			if ($bg_color == 'onglet')
 			{
@@ -517,12 +517,12 @@ class DolGraph
 	 * @param	array	$bg_colorgrid		array(R,G,B) ou 'onglet' ou 'default'
 	 * @return	void
 	 */
-    public function SetBgColorGrid($bg_colorgrid = array(255,255,255))
+    public function SetBgColorGrid($bg_colorgrid = array(255, 255, 255))
 	{
         // phpcs:enable
-		global $theme_bgcolor,$theme_bgcoloronglet;
+		global $theme_bgcolor, $theme_bgcoloronglet;
 
-		if (! is_array($bg_colorgrid))
+		if (!is_array($bg_colorgrid))
 		{
 			if ($bg_colorgrid == 'onglet')
 			{
@@ -567,11 +567,11 @@ class DolGraph
 		$nblines = count($this->data);
 		$nbvalues = count($this->data[0]) - 1;
 
-		for ($j = 0 ; $j < $nblines ; $j++)
+		for ($j = 0; $j < $nblines; $j++)
 		{
-			for ($i = 0 ; $i < $nbvalues ; $i++)
+			for ($i = 0; $i < $nbvalues; $i++)
 			{
-				$vals[$k] = $this->data[$j][$i+1];
+				$vals[$k] = $this->data[$j][$i + 1];
 				$k++;
 			}
 		}
@@ -594,11 +594,11 @@ class DolGraph
 		$nblines = count($this->data);
 		$nbvalues = count($this->data[0]) - 1;
 
-		for ($j = 0 ; $j < $nblines ; $j++)
+		for ($j = 0; $j < $nblines; $j++)
 		{
-			for ($i = 0 ; $i < $nbvalues ; $i++)
+			for ($i = 0; $i < $nbvalues; $i++)
 			{
-				$vals[$k] = $this->data[$j][$i+1];
+				$vals[$k] = $this->data[$j][$i + 1];
 				$k++;
 			}
 		}
@@ -617,15 +617,15 @@ class DolGraph
         // phpcs:enable
 		$max = $this->GetMaxValueInData();
 		if ($max != 0) $max++;
-		$size=dol_strlen(abs(ceil($max)));
-		$factor=1;
-		for ($i=0; $i < ($size-1); $i++)
+		$size = dol_strlen(abs(ceil($max)));
+		$factor = 1;
+		for ($i = 0; $i < ($size - 1); $i++)
 		{
-			$factor*=10;
+			$factor *= 10;
 		}
 
-		$res=0;
-		if (is_numeric($max)) $res=ceil($max/$factor)*$factor;
+		$res = 0;
+		if (is_numeric($max)) $res = ceil($max / $factor) * $factor;
 
 		//print "max=".$max." res=".$res;
 		return $res;
@@ -641,16 +641,16 @@ class DolGraph
 	{
         // phpcs:enable
 		$min = $this->GetMinValueInData();
-		if ($min == '') $min=0;
+		if ($min == '') $min = 0;
 		if ($min != 0) $min--;
-		$size=dol_strlen(abs(floor($min)));
-		$factor=1;
-		for ($i=0; $i < ($size-1); $i++)
+		$size = dol_strlen(abs(floor($min)));
+		$factor = 1;
+		for ($i = 0; $i < ($size - 1); $i++)
 		{
-			$factor*=10;
+			$factor *= 10;
 		}
 
-		$res=floor($min/$factor)*$factor;
+		$res = floor($min / $factor) * $factor;
 
 		//print "min=".$min." res=".$res;
 		return $res;
@@ -667,23 +667,23 @@ class DolGraph
 	{
 		if (empty($file))
 		{
-			$this->error="Call to draw method was made with empty value for parameter file.";
+			$this->error = "Call to draw method was made with empty value for parameter file.";
 			dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR);
 			return -2;
 		}
-		if (! is_array($this->data))
+		if (!is_array($this->data))
 		{
-			$this->error="Call to draw method was made but SetData was not called or called with an empty dataset for parameters";
+			$this->error = "Call to draw method was made but SetData was not called or called with an empty dataset for parameters";
 			dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR);
 			return -1;
 		}
 		if (count($this->data) < 1)
 		{
-			$this->error="Call to draw method was made but SetData was is an empty dataset";
+			$this->error = "Call to draw method was made but SetData was is an empty dataset";
 			dol_syslog(get_class($this)."::draw ".$this->error, LOG_WARNING);
 		}
 		$call = "draw_".$this->_library;
-		call_user_func_array(array($this,$call), array($file,$fileurl));
+		call_user_func_array(array($this, $call), array($file, $fileurl));
 	}
 
 
@@ -702,24 +702,24 @@ class DolGraph
 
 		dol_syslog(get_class($this)."::draw_artichow this->type=".join(',', $this->type));
 
-		if (! defined('SHADOW_RIGHT_TOP'))  define('SHADOW_RIGHT_TOP', 3);
-		if (! defined('LEGEND_BACKGROUND')) define('LEGEND_BACKGROUND', 2);
-		if (! defined('LEGEND_LINE'))       define('LEGEND_LINE', 1);
+		if (!defined('SHADOW_RIGHT_TOP'))  define('SHADOW_RIGHT_TOP', 3);
+		if (!defined('LEGEND_BACKGROUND')) define('LEGEND_BACKGROUND', 2);
+		if (!defined('LEGEND_LINE'))       define('LEGEND_LINE', 1);
 
 		// Create graph
-		$classname='';
-		if (! isset($this->type[0]) || $this->type[0] == 'bars')  $classname='BarPlot';    // Only one type (first one) is supported by artichow
-		elseif ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') $classname='LinePlot';
-		else $classname='TypeUnknown';
+		$classname = '';
+		if (!isset($this->type[0]) || $this->type[0] == 'bars')  $classname = 'BarPlot'; // Only one type (first one) is supported by artichow
+		elseif ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') $classname = 'LinePlot';
+		else $classname = 'TypeUnknown';
 		include_once ARTICHOW_PATH.$classname.'.class.php';
 
 		// Definition de couleurs
-		$bgcolor=new Color($this->bgcolor[0], $this->bgcolor[1], $this->bgcolor[2]);
-		$bgcolorgrid=new Color($this->bgcolorgrid[0], $this->bgcolorgrid[1], $this->bgcolorgrid[2]);
-		$colortrans=new Color(0, 0, 0, 100);
-		$colorsemitrans=new Color(255, 255, 255, 60);
-		$colorgradient= new LinearGradient(new Color(235, 235, 235), new Color(255, 255, 255), 0);
-		$colorwhite=new Color(255, 255, 255);
+		$bgcolor = new Color($this->bgcolor[0], $this->bgcolor[1], $this->bgcolor[2]);
+		$bgcolorgrid = new Color($this->bgcolorgrid[0], $this->bgcolorgrid[1], $this->bgcolorgrid[2]);
+		$colortrans = new Color(0, 0, 0, 100);
+		$colorsemitrans = new Color(255, 255, 255, 60);
+		$colorgradient = new LinearGradient(new Color(235, 235, 235), new Color(255, 255, 255), 0);
+		$colorwhite = new Color(255, 255, 255);
 
 		// Graph
 		$graph = new Graph($this->width, $this->height);
@@ -738,11 +738,11 @@ class DolGraph
 		$group = new PlotGroup;
 		//$group->setSpace(5, 5, 0, 0);
 
-		$paddleft=50;
-		$paddright=10;
-		$strl=dol_strlen(max(abs($this->MaxValue), abs($this->MinValue)));
+		$paddleft = 50;
+		$paddright = 10;
+		$strl = dol_strlen(max(abs($this->MaxValue), abs($this->MinValue)));
 		if ($strl > 6) $paddleft += ($strl * 4);
-		$group->setPadding($paddleft, $paddright);		// Width on left and right for Y axis values
+		$group->setPadding($paddleft, $paddright); // Width on left and right for Y axis values
 		$group->legend->setSpace(0);
 		$group->legend->setPadding(2, 2, 2, 2);
 		$group->legend->setPosition(null, 0.1);
@@ -755,26 +755,26 @@ class DolGraph
 		if ($this->hideYGrid)	$group->grid->hideHorizontal(true);
 
 		// On boucle sur chaque lot de donnees
-		$legends=array();
-		$i=0;
-		$nblot=count($this->data[0])-1;
+		$legends = array();
+		$i = 0;
+		$nblot = count($this->data[0]) - 1;
 
 		while ($i < $nblot)
 		{
-			$x=0;
-			$values=array();
-			foreach($this->data as $key => $valarray)
+			$x = 0;
+			$values = array();
+			foreach ($this->data as $key => $valarray)
 			{
 				$legends[$x] = $valarray[0];
-				$values[$x]  = $valarray[$i+1];
+				$values[$x]  = $valarray[$i + 1];
 				$x++;
 			}
 
 			// We fix unknown values to null
-			$newvalues=array();
-			foreach($values as $val)
+			$newvalues = array();
+			foreach ($values as $val)
 			{
-				$newvalues[]=(is_numeric($val) ? $val : null);
+				$newvalues[] = (is_numeric($val) ? $val : null);
 			}
 
 
@@ -784,14 +784,14 @@ class DolGraph
 				//print_r($values);
 				//print '<br>';
 
-				$color=new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2], 20);
-				$colorbis=new Color(min($this->datacolor[$i][0]+50, 255), min($this->datacolor[$i][1]+50, 255), min($this->datacolor[$i][2]+50, 255), 50);
+				$color = new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2], 20);
+				$colorbis = new Color(min($this->datacolor[$i][0] + 50, 255), min($this->datacolor[$i][1] + 50, 255), min($this->datacolor[$i][2] + 50, 255), 50);
 
-				$colorgrey=new Color(100, 100, 100);
-				$colorborder=new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2]);
+				$colorgrey = new Color(100, 100, 100);
+				$colorborder = new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2]);
 
-				if ($this->mode == 'side')  $plot = new BarPlot($newvalues, $i+1, $nblot);
-				if ($this->mode == 'depth') $plot = new BarPlot($newvalues, 1, 1, ($nblot-$i-1)*5);
+				if ($this->mode == 'side')  $plot = new BarPlot($newvalues, $i + 1, $nblot);
+				if ($this->mode == 'depth') $plot = new BarPlot($newvalues, 1, 1, ($nblot - $i - 1) * 5);
 
 				$plot->barBorder->setColor($colorgrey);
 				//$plot->setBarColor($color);
@@ -816,9 +816,9 @@ class DolGraph
 
 			if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint')
 			{
-				$color=new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2], 20);
-				$colorbis=new Color(min($this->datacolor[$i][0]+20, 255), min($this->datacolor[$i][1]+20, 255), min($this->datacolor[$i][2]+20, 255), 60);
-				$colorter=new Color(min($this->datacolor[$i][0]+50, 255), min($this->datacolor[$i][1]+50, 255), min($this->datacolor[$i][2]+50, 255), 90);
+				$color = new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2], 20);
+				$colorbis = new Color(min($this->datacolor[$i][0] + 20, 255), min($this->datacolor[$i][1] + 20, 255), min($this->datacolor[$i][2] + 20, 255), 60);
+				$colorter = new Color(min($this->datacolor[$i][0] + 50, 255), min($this->datacolor[$i][1] + 50, 255), min($this->datacolor[$i][2] + 50, 255), 90);
 
 				$plot = new LinePlot($newvalues);
 				//$plot->setSize(1, 0.96);
@@ -864,7 +864,7 @@ class DolGraph
 		// Generate file
 		$graph->draw($file);
 
-		$this->stringtoshow='<!-- Build using '.$this->_library.' --><img src="'.$fileurl.'" title="'.dol_escape_htmltag($this->title?$this->title:$this->YLabel).'" alt="'.dol_escape_htmltag($this->title?$this->title:$this->YLabel).'">';
+		$this->stringtoshow = '<!-- Build using '.$this->_library.' --><img src="'.$fileurl.'" title="'.dol_escape_htmltag($this->title ? $this->title : $this->YLabel).'" alt="'.dol_escape_htmltag($this->title ? $this->title : $this->YLabel).'">';
 	}
 
 
@@ -989,7 +989,7 @@ class DolGraph
 						'.($this->combine ? '
 						combine: {
 						 	threshold: '.$this->combine.'
-						},' : '') . '
+						},' : '').'
 						label: {
 							show: true,
 							radius: 0.9,
@@ -997,15 +997,15 @@ class DolGraph
 								var percent=Math.round(series.percent);
 								var number=series.data[0][1];
 								return \'';
-								$this->stringtoshow.='<span style="font-size:8pt;text-align:center;padding:2px;color:black;">';
-								if ($urltemp) $this->stringtoshow.='<a style="color: #FFFFFF;" border="0" href="'.$urltemp.'">';
-								$this->stringtoshow.='\'+';
-								$this->stringtoshow.=($showlegend?'':'label+\' \'+');	// Hide label if already shown in legend
-								$this->stringtoshow.=($showpointvalue?'number+':'');
-								$this->stringtoshow.=($showpercent?'\'<br/>\'+percent+\'%\'+':'');
-								$this->stringtoshow.='\'';
-								if ($urltemp) $this->stringtoshow.='</a>';
-								$this->stringtoshow.='</span>\';
+								$this->stringtoshow .= '<span style="font-size:8pt;text-align:center;padding:2px;color:black;">';
+								if ($urltemp) $this->stringtoshow .= '<a style="color: #FFFFFF;" border="0" href="'.$urltemp.'">';
+								$this->stringtoshow .= '\'+';
+								$this->stringtoshow .= ($showlegend ? '' : 'label+\' \'+'); // Hide label if already shown in legend
+								$this->stringtoshow .= ($showpointvalue ? 'number+' : '');
+								$this->stringtoshow .= ($showpercent ? '\'<br/>\'+percent+\'%\'+' : '');
+								$this->stringtoshow .= '\'';
+								if ($urltemp) $this->stringtoshow .= '</a>';
+								$this->stringtoshow .= '</span>\';
 							},
 							background: {
 							opacity: 0.0,
@@ -1022,9 +1022,9 @@ class DolGraph
 			},';
 			if (count($datacolor))
 			{
-				$this->stringtoshow.='colors: '.(! empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
+				$this->stringtoshow .= 'colors: '.(!empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
 			}
-			$this->stringtoshow.='legend: {show: '.($showlegend?'true':'false').', position: \'ne\' }
+			$this->stringtoshow .= 'legend: {show: '.($showlegend ? 'true' : 'false').', position: \'ne\' }
 		});
 		}'."\n";
 		}
@@ -1033,7 +1033,7 @@ class DolGraph
 		{
 			// Add code to support tooltips
 		    // TODO: remove js css and use graph-tooltip-inner class instead by adding css in each themes
-			$this->stringtoshow.='
+			$this->stringtoshow .= '
 			function showTooltip_'.$tag.'(x, y, contents) {
 				$(\'<div class="graph-tooltip-inner" id="tooltip_'.$tag.'">\' + contents + \'</div>\').css({
 					position: \'absolute\',
@@ -1065,10 +1065,10 @@ class DolGraph
 						var y = item.datapoint[1].toFixed(2);
 						var z = item.series.xaxis.ticks[item.dataIndex].label;
 						';
-						if ($this->showpointvalue > 0) $this->stringtoshow.='
+						if ($this->showpointvalue > 0) $this->stringtoshow .= '
 							showTooltip_'.$tag.'(item.pageX, item.pageY, item.series.label + "<br>" + z + " => " + y);
 						';
-						$this->stringtoshow.='
+						$this->stringtoshow .= '
 					}
 				}
 				else {
@@ -1078,50 +1078,50 @@ class DolGraph
 			});
 			';
 
-			$this->stringtoshow.='var stack = null, steps = false;'."\n";
+			$this->stringtoshow .= 'var stack = null, steps = false;'."\n";
 
-			$this->stringtoshow.='function plotWithOptions_'.$tag.'() {'."\n";
-			$this->stringtoshow.='$.plot($("#placeholder_'.$tag.'"), [ '."\n";
-			$i=$firstlot;
+			$this->stringtoshow .= 'function plotWithOptions_'.$tag.'() {'."\n";
+			$this->stringtoshow .= '$.plot($("#placeholder_'.$tag.'"), [ '."\n";
+			$i = $firstlot;
 			while ($i < $nblot)
 			{
-				if ($i > $firstlot) $this->stringtoshow.=', '."\n";
-				$color=sprintf("%02x%02x%02x", $this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2]);
-				$this->stringtoshow.='{ ';
-				if (! isset($this->type[$i]) || $this->type[$i] == 'bars') $this->stringtoshow.='bars: { lineWidth: 1, show: true, align: "'.($i==$firstlot?'center':'left').'", barWidth: 0.5 }, ';
-				if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) $this->stringtoshow.='lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, ';
-				$this->stringtoshow.='color: "#'.$color.'", label: "'.(isset($this->Legend[$i]) ? dol_escape_js($this->Legend[$i]) : '').'", data: d'.$i.' }';
+				if ($i > $firstlot) $this->stringtoshow .= ', '."\n";
+				$color = sprintf("%02x%02x%02x", $this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2]);
+				$this->stringtoshow .= '{ ';
+				if (!isset($this->type[$i]) || $this->type[$i] == 'bars') $this->stringtoshow .= 'bars: { lineWidth: 1, show: true, align: "'.($i == $firstlot ? 'center' : 'left').'", barWidth: 0.5 }, ';
+				if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) $this->stringtoshow .= 'lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, ';
+				$this->stringtoshow .= 'color: "#'.$color.'", label: "'.(isset($this->Legend[$i]) ? dol_escape_js($this->Legend[$i]) : '').'", data: d'.$i.' }';
 				$i++;
 			}
 			// shadowSize: 0 -> Drawing is faster without shadows
-			$this->stringtoshow.="\n".' ], { series: { shadowSize: 0, stack: stack, lines: { fill: false, steps: steps }, bars: { barWidth: 0.6,  fillColor: { colors: [{opacity: 0.9 }, {opacity: 0.85}] }} }'."\n";
+			$this->stringtoshow .= "\n".' ], { series: { shadowSize: 0, stack: stack, lines: { fill: false, steps: steps }, bars: { barWidth: 0.6,  fillColor: { colors: [{opacity: 0.9 }, {opacity: 0.85}] }} }'."\n";
 
 			// Xaxis
-			$this->stringtoshow.=', xaxis: { ticks: ['."\n";
-			$x=0;
-			foreach($this->data as $key => $valarray)
+			$this->stringtoshow .= ', xaxis: { ticks: ['."\n";
+			$x = 0;
+			foreach ($this->data as $key => $valarray)
 			{
-				if ($x > 0) $this->stringtoshow.=', '."\n";
-				$this->stringtoshow.= ' ['.$x.', "'.$valarray[0].'"]';
+				if ($x > 0) $this->stringtoshow .= ', '."\n";
+				$this->stringtoshow .= ' ['.$x.', "'.$valarray[0].'"]';
 				$x++;
 			}
-			$this->stringtoshow.='] }'."\n";
+			$this->stringtoshow .= '] }'."\n";
 
 			// Yaxis
-			$this->stringtoshow.=', yaxis: { min: '.$this->MinValue.', max: '.($this->MaxValue).' }'."\n";
+			$this->stringtoshow .= ', yaxis: { min: '.$this->MinValue.', max: '.($this->MaxValue).' }'."\n";
 
 			// Background color
-			$color1=sprintf("%02x%02x%02x", $this->bgcolorgrid[0], $this->bgcolorgrid[0], $this->bgcolorgrid[2]);
-			$color2=sprintf("%02x%02x%02x", $this->bgcolorgrid[0], $this->bgcolorgrid[1], $this->bgcolorgrid[2]);
-			$this->stringtoshow.=', grid: { hoverable: true, backgroundColor: { colors: ["#'.$color1.'", "#'.$color2.'"] }, borderWidth: 1, borderColor: \'#e6e6e6\', tickColor  : \'#e6e6e6\' }'."\n";
+			$color1 = sprintf("%02x%02x%02x", $this->bgcolorgrid[0], $this->bgcolorgrid[0], $this->bgcolorgrid[2]);
+			$color2 = sprintf("%02x%02x%02x", $this->bgcolorgrid[0], $this->bgcolorgrid[1], $this->bgcolorgrid[2]);
+			$this->stringtoshow .= ', grid: { hoverable: true, backgroundColor: { colors: ["#'.$color1.'", "#'.$color2.'"] }, borderWidth: 1, borderColor: \'#e6e6e6\', tickColor  : \'#e6e6e6\' }'."\n";
 			//$this->stringtoshow.=', shadowSize: 20'."\n";    TODO Uncommet this
-			$this->stringtoshow.='});'."\n";
-			$this->stringtoshow.='}'."\n";
+			$this->stringtoshow .= '});'."\n";
+			$this->stringtoshow .= '}'."\n";
 		}
 
-		$this->stringtoshow.='plotWithOptions_'.$tag.'();'."\n";
-		$this->stringtoshow.='});'."\n";
-		$this->stringtoshow.='</script>'."\n";
+		$this->stringtoshow .= 'plotWithOptions_'.$tag.'();'."\n";
+		$this->stringtoshow .= '});'."\n";
+		$this->stringtoshow .= '</script>'."\n";
 	}
 
 
@@ -1138,8 +1138,8 @@ class DolGraph
 
 		if ($shownographyet)
 		{
-			$s= '<div class="nographyet" style="width:'.(preg_match('/%/', $this->width)?$this->width:$this->width.'px').'; height:'.(preg_match('/%/', $this->height)?$this->height:$this->height.'px').';"></div>';
-			$s.='<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
+			$s = '<div class="nographyet" style="width:'.(preg_match('/%/', $this->width) ? $this->width : $this->width.'px').'; height:'.(preg_match('/%/', $this->height) ? $this->height : $this->height.'px').';"></div>';
+			$s .= '<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
 			return $s;
 		}
 
@@ -1161,11 +1161,11 @@ class DolGraph
 		if ($direction == 'width')
 		{
 			if (empty($conf->dol_optimize_smallscreen)) return ($defaultsize ? $defaultsize : '500');
-			else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width']-40));
+			else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width'] - 40));
 		}
 		if ($direction == 'height')
 		{
-			return (empty($conf->dol_optimize_smallscreen)?($defaultsize?$defaultsize:'200'):'160');
+			return (empty($conf->dol_optimize_smallscreen) ? ($defaultsize ? $defaultsize : '200') : '160');
 		}
 		return 0;
 	}

File diff suppressed because it is too large
+ 308 - 308
htdocs/core/class/extrafields.class.php


+ 70 - 70
htdocs/core/class/html.formactions.class.php

@@ -37,7 +37,7 @@ class FormActions
     /**
 	 * @var string Error code (or message)
 	 */
-	public $error='';
+	public $error = '';
 
 
     /**
@@ -67,7 +67,7 @@ class FormActions
     public function form_select_status_action($formname, $selected, $canedit = 1, $htmlname = 'complete', $showempty = 0, $onlyselect = 0, $morecss = 'maxwidth100')
     {
         // phpcs:enable
-        global $langs,$conf;
+        global $langs, $conf;
 
         $listofstatus = array(
             '-1' => $langs->trans("ActionNotApplicable"),
@@ -77,7 +77,7 @@ class FormActions
         );
 		// +ActionUncomplete
 
-        if (! empty($conf->use_javascript_ajax))
+        if (!empty($conf->use_javascript_ajax))
         {
             print "\n";
             print "<script type=\"text/javascript\">
@@ -98,7 +98,7 @@ class FormActions
                 function select_status() {
                     var defaultvalue = $('#select' + htmlname).val();
                     var percentage = $('input[name=percentage]');
-                    var selected = '".(isset($selected)?$selected:'')."';
+                    var selected = '".(isset($selected) ? $selected : '')."';
                     var value = (selected>0?selected:(defaultvalue>=0?defaultvalue:''));
 
                     percentage.val(value);
@@ -125,13 +125,13 @@ class FormActions
                 }
                 </script>\n";
         }
-        if (! empty($conf->use_javascript_ajax) || $onlyselect)
+        if (!empty($conf->use_javascript_ajax) || $onlyselect)
         {
         	//var_dump($selected);
-        	if ($selected == 'done') $selected='100';
-            print '<select '.($canedit?'':'disabled ').'name="'.$htmlname.'" id="select'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'">';
-            if ($showempty) print '<option value=""'.($selected == ''?' selected':'').'></option>';
-            foreach($listofstatus as $key => $val)
+        	if ($selected == 'done') $selected = '100';
+            print '<select '.($canedit ? '' : 'disabled ').'name="'.$htmlname.'" id="select'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'">';
+            if ($showempty) print '<option value=""'.($selected == '' ? ' selected' : '').'></option>';
+            foreach ($listofstatus as $key => $val)
             {
                 print '<option value="'.$key.'"'.(($selected == $key && strlen($selected) == strlen($key)) || (($selected > 0 && $selected < 100) && $key == '50') ? ' selected' : '').'>'.$val.'</option>';
                 if ($key == '50' && $onlyselect == 2)
@@ -140,17 +140,17 @@ class FormActions
                 }
             }
             print '</select>';
-            if ($selected == 0 || $selected == 100) $canedit=0;
+            if ($selected == 0 || $selected == 100) $canedit = 0;
 
             if (empty($onlyselect))
             {
-	            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat hideifna" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit&&($selected>=0)?'':' disabled').'>';
+	            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat hideifna" value="'.($selected >= 0 ? $selected : '').'" size="2"'.($canedit && ($selected >= 0) ? '' : ' disabled').'>';
     	        print '<span class="hideonsmartphone hideifna">%</span>';
             }
         }
         else
 		{
-            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit?'':' disabled').'>%';
+            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat" value="'.($selected >= 0 ? $selected : '').'" size="2"'.($canedit ? '' : ' disabled').'>%';
         }
     }
 
@@ -170,79 +170,79 @@ class FormActions
      */
     public function showactions($object, $typeelement, $socid = 0, $forceshowtitle = 0, $morecss = 'listactions', $max = 0, $moreparambacktopage = '', $morehtmlright = '')
     {
-        global $langs,$conf,$user;
+        global $langs, $conf, $user;
         global $bc;
 
         require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
 
-        $sortfield='a.datep,a.id';
-        $sortorder='DESC,DESC';
+        $sortfield = 'a.datep,a.id';
+        $sortorder = 'DESC,DESC';
 
-        $listofactions=ActionComm::getActions($this->db, $socid, $object->id, $typeelement, '', $sortfield, $sortorder, ($max?($max+1):0));
-        if (! is_array($listofactions)) dol_print_error($this->db, 'FailedToGetActions');
+        $listofactions = ActionComm::getActions($this->db, $socid, $object->id, $typeelement, '', $sortfield, $sortorder, ($max ? ($max + 1) : 0));
+        if (!is_array($listofactions)) dol_print_error($this->db, 'FailedToGetActions');
 
         $num = count($listofactions);
         if ($num || $forceshowtitle)
         {
-        	if ($typeelement == 'invoice')               $title=$langs->trans('ActionsOnBill');
-        	elseif ($typeelement == 'invoice_supplier' || $typeelement == 'supplier_invoice') $title=$langs->trans('ActionsOnBill');
-        	elseif ($typeelement == 'propal')            $title=$langs->trans('ActionsOnPropal');
-        	elseif ($typeelement == 'supplier_proposal') $title=$langs->trans('ActionsOnSupplierProposal');
-        	elseif ($typeelement == 'order')             $title=$langs->trans('ActionsOnOrder');
-        	elseif ($typeelement == 'order_supplier' || $typeelement == 'supplier_order')   $title=$langs->trans('ActionsOnOrder');
-        	elseif ($typeelement == 'shipping')          $title=$langs->trans('ActionsOnShipping');
-            elseif ($typeelement == 'fichinter')         $title=$langs->trans('ActionsOnFicheInter');
-            elseif ($typeelement == 'project')           $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
-            elseif ($typeelement == 'task')              $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
-            elseif ($typeelement == 'member')            $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
-            else $title=$langs->trans("LatestLinkedEvents", $max?$max:'');
-
-            $urlbacktopage=$_SERVER['PHP_SELF'].'?id='.$object->id.($moreparambacktopage?'&'.$moreparambacktopage:'');
+        	if ($typeelement == 'invoice')               $title = $langs->trans('ActionsOnBill');
+        	elseif ($typeelement == 'invoice_supplier' || $typeelement == 'supplier_invoice') $title = $langs->trans('ActionsOnBill');
+        	elseif ($typeelement == 'propal')            $title = $langs->trans('ActionsOnPropal');
+        	elseif ($typeelement == 'supplier_proposal') $title = $langs->trans('ActionsOnSupplierProposal');
+        	elseif ($typeelement == 'order')             $title = $langs->trans('ActionsOnOrder');
+        	elseif ($typeelement == 'order_supplier' || $typeelement == 'supplier_order')   $title = $langs->trans('ActionsOnOrder');
+        	elseif ($typeelement == 'shipping')          $title = $langs->trans('ActionsOnShipping');
+            elseif ($typeelement == 'fichinter')         $title = $langs->trans('ActionsOnFicheInter');
+            elseif ($typeelement == 'project')           $title = $langs->trans('LatestLinkedEvents', $max ? $max : '');
+            elseif ($typeelement == 'task')              $title = $langs->trans('LatestLinkedEvents', $max ? $max : '');
+            elseif ($typeelement == 'member')            $title = $langs->trans('LatestLinkedEvents', $max ? $max : '');
+            else $title = $langs->trans("LatestLinkedEvents", $max ? $max : '');
+
+            $urlbacktopage = $_SERVER['PHP_SELF'].'?id='.$object->id.($moreparambacktopage ? '&'.$moreparambacktopage : '');
 
             $projectid = $object->fk_project;
             if ($typeelement == 'project') $projectid = $object->id;
 
-            $newcardbutton='';
-			if (! empty($conf->agenda->enabled))
+            $newcardbutton = '';
+			if (!empty($conf->agenda->enabled))
 			{
-                $newcardbutton.= dolGetButtonTitle($langs->trans("AddEvent"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.dol_print_date(dol_now(), 'dayhourlog').'&origin='.$typeelement.'&originid='.$object->id.($object->socid>0?'&socid='.$object->socid:($socid>0?'&socid='.$socid:'')).($projectid>0?'&projectid='.$projectid:'').'&backtopage='.urlencode($urlbacktopage));
+                $newcardbutton .= dolGetButtonTitle($langs->trans("AddEvent"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.dol_print_date(dol_now(), 'dayhourlog').'&origin='.$typeelement.'&originid='.$object->id.($object->socid > 0 ? '&socid='.$object->socid : ($socid > 0 ? '&socid='.$socid : '')).($projectid > 0 ? '&projectid='.$projectid : '').'&backtopage='.urlencode($urlbacktopage));
 			}
 
         	print '<!-- formactions->showactions -->'."\n";
         	print load_fiche_titre($title, $newcardbutton, '', 0, 0, '', $morehtmlright);
 
-        	$page=0; $param='';
+        	$page = 0; $param = '';
 
         	print '<div class="div-table-responsive-no-min">';
-        	print '<table class="centpercent noborder'.($morecss?' '.$morecss:'').'">';
+        	print '<table class="centpercent noborder'.($morecss ? ' '.$morecss : '').'">';
         	print '<tr class="liste_titre">';
-        	print getTitleFieldOfList('Ref',   0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
-        	print getTitleFieldOfList('By',    0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
-        	print getTitleFieldOfList('Type',  0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
+        	print getTitleFieldOfList('Ref', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
+        	print getTitleFieldOfList('By', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
+        	print getTitleFieldOfList('Type', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
         	print getTitleFieldOfList('Title', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
-        	print getTitleFieldOfList('Date',  0, $_SERVER["PHP_SELF"], 'a.datep', $page, $param, '', $sortfield, $sortorder, 'center ', 1);
-        	print getTitleFieldOfList('',      0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, 'right ', 1);
+        	print getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', $page, $param, '', $sortfield, $sortorder, 'center ', 1);
+        	print getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, 'right ', 1);
         	print '</tr>';
         	print "\n";
 
         	if (is_array($listofactions) && count($listofactions))
         	{
-        		$cacheusers=array();
+        		$cacheusers = array();
 
 	        	$cursorevent = 0;
-	        	foreach($listofactions as $action)
+	        	foreach ($listofactions as $action)
 	        	{
 	        		if ($max && $cursorevent >= $max) break;
 
-	        		$ref=$action->getNomUrl(1, -1);
-	        		$label=$action->getNomUrl(0, 38);
+	        		$ref = $action->getNomUrl(1, -1);
+	        		$label = $action->getNomUrl(0, 38);
 
 	        		print '<tr class="oddeven">';
 	        		// Ref
 					print '<td class="nowraponall">'.$ref.'</td>';
 					// Onwer
 	        		print '<td class="tdoverflowmax150">';
-	        		if (! empty($action->userownerid))
+	        		if (!empty($action->userownerid))
 	        		{
 	        			if (is_object($cacheusers[$action->userownerid]))
 	        			{
@@ -262,17 +262,17 @@ class FormActions
 	        		print '</td>';
 					// Type
 	        		print '<td>';
-					$imgpicto='';
-					if (! empty($conf->global->AGENDA_USE_EVENT_TYPE))
+					$imgpicto = '';
+					if (!empty($conf->global->AGENDA_USE_EVENT_TYPE))
 					{
-						if ($action->type_picto) $imgpicto=img_picto('', $action->type_picto);
+						if ($action->type_picto) $imgpicto = img_picto('', $action->type_picto);
 						else {
-							if ($action->type_code == 'AC_RDV')       $imgpicto=img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' ';
-							elseif ($action->type_code == 'AC_TEL')   $imgpicto=img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' ';
-							elseif ($action->type_code == 'AC_FAX')   $imgpicto=img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' ';
-							elseif ($action->type_code == 'AC_EMAIL') $imgpicto=img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' ';
-							elseif ($action->type_code == 'AC_INT')   $imgpicto=img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' ';
-							elseif (! preg_match('/_AUTO/', $action->type_code)) $imgpicto=img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' ';
+							if ($action->type_code == 'AC_RDV')       $imgpicto = img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' ';
+							elseif ($action->type_code == 'AC_TEL')   $imgpicto = img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' ';
+							elseif ($action->type_code == 'AC_FAX')   $imgpicto = img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' ';
+							elseif ($action->type_code == 'AC_EMAIL') $imgpicto = img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' ';
+							elseif ($action->type_code == 'AC_INT')   $imgpicto = img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' ';
+							elseif (!preg_match('/_AUTO/', $action->type_code)) $imgpicto = img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' ';
 						}
 					}
 					print $imgpicto;
@@ -284,8 +284,8 @@ class FormActions
 	        		print '<td class="center">'.dol_print_date($action->datep, 'dayhour', 'tzuserrel');
 	        		if ($action->datef)
 	        		{
-		        		$tmpa=dol_getdate($action->datep);
-		        		$tmpb=dol_getdate($action->datef);
+		        		$tmpa = dol_getdate($action->datep);
+		        		$tmpb = dol_getdate($action->datef);
 		        		if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year'])
 		        		{
 		        			if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($action->datef, 'hour', 'tzuserrel');
@@ -335,39 +335,39 @@ class FormActions
     public function select_type_actions($selected = '', $htmlname = 'actioncode', $excludetype = '', $onlyautoornot = 0, $hideinfohelp = 0, $multiselect = 0, $nooutput = 0)
     {
         // phpcs:enable
-        global $langs,$user,$form,$conf;
+        global $langs, $user, $form, $conf;
 
-        if (! is_object($form)) $form=new Form($this->db);
+        if (!is_object($form)) $form = new Form($this->db);
 
         require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
         require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
-        $caction=new CActionComm($this->db);
+        $caction = new CActionComm($this->db);
 
        	// Suggest a list with manual events or all auto events
-       	$arraylist=$caction->liste_array(1, 'code', $excludetype, $onlyautoornot);
-       	array_unshift($arraylist, '&nbsp;');     // Add empty line at start
+       	$arraylist = $caction->liste_array(1, 'code', $excludetype, $onlyautoornot);
+       	array_unshift($arraylist, '&nbsp;'); // Add empty line at start
        	//asort($arraylist);
 
-       	if ($selected == 'manual') $selected='AC_OTH';
-       	if ($selected == 'auto')   $selected='AC_OTH_AUTO';
+       	if ($selected == 'manual') $selected = 'AC_OTH';
+       	if ($selected == 'auto')   $selected = 'AC_OTH_AUTO';
 
-       	if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']);
+       	if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']);
 
-       	$out='';
+       	$out = '';
 
-		if (! empty($multiselect))
+		if (!empty($multiselect))
 		{
 	        if (!is_array($selected) && !empty($selected)) $selected = explode(',', $selected);
-			$out.=$form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0);
+			$out .= $form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0);
 		}
 		else
 		{
-			$out.=$form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
+			$out .= $form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
 		}
 
         if ($user->admin && empty($onlyautoornot) && $hideinfohelp <= 0)
         {
-            $out.=info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup").($hideinfohelp == -1 ? ". ".$langs->trans("YouCanSetDefaultValueInModuleSetup") : ''), 1);
+            $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup").($hideinfohelp == -1 ? ". ".$langs->trans("YouCanSetDefaultValueInModuleSetup") : ''), 1);
         }
 
         if ($nooutput) return $out;

+ 162 - 162
htdocs/core/class/html.formcompany.class.php

@@ -46,17 +46,17 @@ class FormCompany extends Form
 	public function typent_array($mode = 0, $filter = '')
 	{
         // phpcs:enable
-		global $langs,$mysoc;
+		global $langs, $mysoc;
 
 		$effs = array();
 
 		$sql = "SELECT id, code, libelle";
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_typent";
-		$sql.= " WHERE active = 1 AND (fk_country IS NULL OR fk_country = ".(empty($mysoc->country_id)?'0':$mysoc->country_id).")";
-		if ($filter) $sql.=" ".$filter;
-		$sql.= " ORDER by position, id";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_typent";
+		$sql .= " WHERE active = 1 AND (fk_country IS NULL OR fk_country = ".(empty($mysoc->country_id) ? '0' : $mysoc->country_id).")";
+		if ($filter) $sql .= " ".$filter;
+		$sql .= " ORDER by position, id";
 		dol_syslog(get_class($this).'::typent_array', LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
 			$num = $this->db->num_rows($resql);
@@ -65,11 +65,11 @@ class FormCompany extends Form
 			while ($i < $num)
 			{
 				$objp = $this->db->fetch_object($resql);
-				if (! $mode) $key=$objp->id;
-				else $key=$objp->code;
+				if (!$mode) $key = $objp->id;
+				else $key = $objp->code;
 				if ($langs->trans($objp->code) != $objp->code) $effs[$key] = $langs->trans($objp->code);
 				else $effs[$key] = $objp->libelle;
-				if ($effs[$key]=='-') $effs[$key]='';
+				if ($effs[$key] == '-') $effs[$key] = '';
 				$i++;
 			}
 			$this->db->free($resql);
@@ -93,11 +93,11 @@ class FormCompany extends Form
 
 		$sql = "SELECT id, code, libelle";
 		$sql .= " FROM ".MAIN_DB_PREFIX."c_effectif";
-		$sql.= " WHERE active = 1";
-		if ($filter) $sql.=" ".$filter;
+		$sql .= " WHERE active = 1";
+		if ($filter) $sql .= " ".$filter;
 		$sql .= " ORDER BY id ASC";
 		dol_syslog(get_class($this).'::effectif_array', LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
 			$num = $this->db->num_rows($resql);
@@ -106,10 +106,10 @@ class FormCompany extends Form
 			while ($i < $num)
 			{
 				$objp = $this->db->fetch_object($resql);
-				if (! $mode) $key=$objp->id;
-				else $key=$objp->code;
+				if (!$mode) $key = $objp->id;
+				else $key = $objp->code;
 
-				$effs[$key] = $objp->libelle!='-'?$objp->libelle:'';
+				$effs[$key] = $objp->libelle != '-' ? $objp->libelle : '';
 				$i++;
 			}
 			$this->db->free($resql);
@@ -139,9 +139,9 @@ class FormCompany extends Form
 
 		dol_syslog(get_class($this).'::form_prospect_level', LOG_DEBUG);
 		$sql = "SELECT code, label";
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_prospectlevel";
-		$sql.= " WHERE active > 0";
-		$sql.= " ORDER BY sortorder";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_prospectlevel";
+		$sql .= " WHERE active > 0";
+		$sql .= " ORDER BY sortorder";
 		$resql = $this->db->query($sql);
 		if ($resql)
 		{
@@ -164,7 +164,7 @@ class FormCompany extends Form
 			print Form::selectarray($htmlname, $options, $selected);
 		}
 		else dol_print_error($this->db);
-		if (! empty($htmlname) && $user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
+		if (!empty($htmlname) && $user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
 		print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
 		print '</form>';
 	}
@@ -203,88 +203,88 @@ class FormCompany extends Form
 	public function select_state($selected = 0, $country_codeid = 0, $htmlname = 'state_id')
 	{
         // phpcs:enable
-		global $conf,$langs,$user;
+		global $conf, $langs, $user;
 
 		dol_syslog(get_class($this)."::select_departement selected=".$selected.", country_codeid=".$country_codeid, LOG_DEBUG);
 
 		$langs->load("dict");
 
-		$out='';
+		$out = '';
 
 		// Serch departements/cantons/province active d'une region et pays actif
 		$sql = "SELECT d.rowid, d.code_departement as code, d.nom as name, d.active, c.label as country, c.code as country_code, r.nom as region_name FROM";
-		$sql .= " ".MAIN_DB_PREFIX ."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c";
+		$sql .= " ".MAIN_DB_PREFIX."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c";
 		$sql .= " WHERE d.fk_region=r.code_region and r.fk_pays=c.rowid";
 		$sql .= " AND d.active = 1 AND r.active = 1 AND c.active = 1";
 		if ($country_codeid && is_numeric($country_codeid))   $sql .= " AND c.rowid = '".$this->db->escape($country_codeid)."'";
-		if ($country_codeid && ! is_numeric($country_codeid)) $sql .= " AND c.code = '".$this->db->escape($country_codeid)."'";
+		if ($country_codeid && !is_numeric($country_codeid)) $sql .= " AND c.code = '".$this->db->escape($country_codeid)."'";
 		$sql .= " ORDER BY c.code, d.code_departement";
 
-		$result=$this->db->query($sql);
+		$result = $this->db->query($sql);
 		if ($result)
 		{
-			if (!empty($htmlname)) $out.= '<select id="'.$htmlname.'" class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'">';
-			if ($country_codeid) $out.= '<option value="0">&nbsp;</option>';
+			if (!empty($htmlname)) $out .= '<select id="'.$htmlname.'" class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'">';
+			if ($country_codeid) $out .= '<option value="0">&nbsp;</option>';
 			$num = $this->db->num_rows($result);
 			$i = 0;
 			dol_syslog(get_class($this)."::select_departement num=".$num, LOG_DEBUG);
 			if ($num)
 			{
-				$country='';
+				$country = '';
 				while ($i < $num)
 				{
 					$obj = $this->db->fetch_object($result);
 					if ($obj->code == '0')		// Le code peut etre une chaine
 					{
-						$out.= '<option value="0">&nbsp;</option>';
+						$out .= '<option value="0">&nbsp;</option>';
 					}
 					else {
-						if (! $country || $country != $obj->country)
+						if (!$country || $country != $obj->country)
 						{
 							// Affiche la rupture si on est en mode liste multipays
-							if (! $country_codeid && $obj->country_code)
+							if (!$country_codeid && $obj->country_code)
 							{
-								$out.= '<option value="-1" disabled>----- '.$obj->country." -----</option>\n";
-								$country=$obj->country;
+								$out .= '<option value="-1" disabled>----- '.$obj->country." -----</option>\n";
+								$country = $obj->country;
 							}
 						}
 
-						if ((! empty($selected) && $selected == $obj->rowid)
-						 || (empty($selected) && ! empty($conf->global->MAIN_FORCE_DEFAULT_STATE_ID) && $conf->global->MAIN_FORCE_DEFAULT_STATE_ID == $obj->rowid))
+						if ((!empty($selected) && $selected == $obj->rowid)
+						 || (empty($selected) && !empty($conf->global->MAIN_FORCE_DEFAULT_STATE_ID) && $conf->global->MAIN_FORCE_DEFAULT_STATE_ID == $obj->rowid))
 						{
-							$out.= '<option value="'.$obj->rowid.'" selected>';
+							$out .= '<option value="'.$obj->rowid.'" selected>';
 						}
 						else
 						{
-							$out.= '<option value="'.$obj->rowid.'">';
+							$out .= '<option value="'.$obj->rowid.'">';
 						}
 
 						// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
 						if (!empty($conf->global->MAIN_SHOW_STATE_CODE) &&
 						($conf->global->MAIN_SHOW_STATE_CODE == 1 || $conf->global->MAIN_SHOW_STATE_CODE == 2 || $conf->global->MAIN_SHOW_STATE_CODE === 'all')) {
-							if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1) {
-								$out.= $obj->region_name . ' - ' . $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:''));
+							if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1) {
+								$out .= $obj->region_name.' - '.$obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : ''));
 							}
 							else {
-								$out.= $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:''));
+								$out .= $obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : ''));
 							}
 						}
 						else {
-							if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1) {
-								$out.= $obj->region_name . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:''));
+							if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1) {
+								$out .= $obj->region_name.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : ''));
 							}
 							else {
-								$out.= ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:''));
+								$out .= ($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : ''));
 							}
 						}
 
-						$out.= '</option>';
+						$out .= '</option>';
 					}
 					$i++;
 				}
 			}
-			if (! empty($htmlname)) $out.= '</select>';
-			if (! empty($htmlname) && $user->admin) $out.= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
+			if (!empty($htmlname)) $out .= '</select>';
+			if (!empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
 		}
 		else
 		{
@@ -292,9 +292,9 @@ class FormCompany extends Form
 		}
 
 		// Make select dynamic
-		if (! empty($htmlname))
+		if (!empty($htmlname))
 		{
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
+			include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
 			$out .= ajax_combobox($htmlname);
 		}
 
@@ -316,16 +316,16 @@ class FormCompany extends Form
 	public function select_region($selected = '', $htmlname = 'region_id')
 	{
         // phpcs:enable
-		global $conf,$langs;
+		global $conf, $langs;
 		$langs->load("dict");
 
 		$sql = "SELECT r.rowid, r.code_region as code, r.nom as label, r.active, c.code as country_code, c.label as country";
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_regions as r, ".MAIN_DB_PREFIX."c_country as c";
-		$sql.= " WHERE r.fk_pays=c.rowid AND r.active = 1 and c.active = 1";
-		$sql.= " ORDER BY c.code, c.label ASC";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_regions as r, ".MAIN_DB_PREFIX."c_country as c";
+		$sql .= " WHERE r.fk_pays=c.rowid AND r.active = 1 and c.active = 1";
+		$sql .= " ORDER BY c.code, c.label ASC";
 
 		dol_syslog(get_class($this)."::select_region", LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
 			print '<select class="flat" name="'.$htmlname.'">';
@@ -333,7 +333,7 @@ class FormCompany extends Form
 			$i = 0;
 			if ($num)
 			{
-				$country='';
+				$country = '';
 				while ($i < $num)
 				{
 					$obj = $this->db->fetch_object($resql);
@@ -344,10 +344,10 @@ class FormCompany extends Form
 						if ($country == '' || $country != $obj->country)
 						{
 							// Show break
-							$key=$langs->trans("Country".strtoupper($obj->country_code));
-							$valuetoshow=($key != "Country".strtoupper($obj->country_code))?$obj->country_code." - ".$key:$obj->country;
+							$key = $langs->trans("Country".strtoupper($obj->country_code));
+							$valuetoshow = ($key != "Country".strtoupper($obj->country_code)) ? $obj->country_code." - ".$key : $obj->country;
 							print '<option value="-1" disabled>----- '.$valuetoshow." -----</option>\n";
-							$country=$obj->country;
+							$country = $obj->country;
 						}
 
 						if ($selected > 0 && $selected == $obj->code)
@@ -382,20 +382,20 @@ class FormCompany extends Form
 	public function select_civility($selected = '', $htmlname = 'civility_id', $morecss = 'maxwidth100')
 	{
         // phpcs:enable
-		global $conf,$langs,$user;
+		global $conf, $langs, $user;
 		$langs->load("dict");
 
-		$out='';
+		$out = '';
 
 		$sql = "SELECT rowid, code, label, active FROM ".MAIN_DB_PREFIX."c_civility";
-		$sql.= " WHERE active = 1";
+		$sql .= " WHERE active = 1";
 
 		dol_syslog("Form::select_civility", LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
-			$out.= '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
-			$out.= '<option value="">&nbsp;</option>';
+			$out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
+			$out .= '<option value="">&nbsp;</option>';
 			$num = $this->db->num_rows($resql);
 			$i = 0;
 			if ($num)
@@ -405,20 +405,20 @@ class FormCompany extends Form
 					$obj = $this->db->fetch_object($resql);
 					if ($selected == $obj->code)
 					{
-						$out.= '<option value="'.$obj->code.'" selected>';
+						$out .= '<option value="'.$obj->code.'" selected>';
 					}
 					else
 					{
-						$out.= '<option value="'.$obj->code.'">';
+						$out .= '<option value="'.$obj->code.'">';
 					}
 					// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
-					$out.= ($langs->trans("Civility".$obj->code)!="Civility".$obj->code ? $langs->trans("Civility".$obj->code) : ($obj->label!='-'?$obj->label:''));
-					$out.= '</option>';
+					$out .= ($langs->trans("Civility".$obj->code) != "Civility".$obj->code ? $langs->trans("Civility".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
+					$out .= '</option>';
 					$i++;
 				}
 			}
-			$out.= '</select>';
-			if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
+			$out .= '</select>';
+			if ($user->admin) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
 		}
 		else
 		{
@@ -460,10 +460,10 @@ class FormCompany extends Form
 	public function select_juridicalstatus($selected = '', $country_codeid = 0, $filter = '', $htmlname = 'forme_juridique_code')
 	{
         // phpcs:enable
-		global $conf,$langs,$user;
+		global $conf, $langs, $user;
 		$langs->load("dict");
 
-		$out='';
+		$out = '';
 
 		// On recherche les formes juridiques actives des pays actifs
 		$sql  = "SELECT f.rowid, f.code as code , f.libelle as label, f.active, c.label as country, c.code as country_code";
@@ -475,70 +475,70 @@ class FormCompany extends Form
 		$sql .= " ORDER BY c.code";
 
 		dol_syslog(get_class($this)."::select_juridicalstatus", LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
-			$out.= '<div id="particulier2" class="visible">';
-			$out.= '<select class="flat minwidth200" name="'.$htmlname.'" id="'.$htmlname.'">';
-			if ($country_codeid) $out.= '<option value="0">&nbsp;</option>';	// When country_codeid is set, we force to add an empty line because it does not appears from select. When not set, we already get the empty line from select.
+			$out .= '<div id="particulier2" class="visible">';
+			$out .= '<select class="flat minwidth200" name="'.$htmlname.'" id="'.$htmlname.'">';
+			if ($country_codeid) $out .= '<option value="0">&nbsp;</option>'; // When country_codeid is set, we force to add an empty line because it does not appears from select. When not set, we already get the empty line from select.
 
 			$num = $this->db->num_rows($resql);
 			if ($num)
 			{
 				$i = 0;
-				$country=''; $arraydata=array();
+				$country = ''; $arraydata = array();
 				while ($i < $num)
 				{
 					$obj = $this->db->fetch_object($resql);
 
 					if ($obj->code)		// We exclude empty line, we will add it later
 					{
-						$labelcountry=(($langs->trans("Country".$obj->country_code)!="Country".$obj->country_code) ? $langs->trans("Country".$obj->country_code) : $obj->country);
-						$labeljs=(($langs->trans("JuridicalStatus".$obj->code)!="JuridicalStatus".$obj->code) ? $langs->trans("JuridicalStatus".$obj->code) : ($obj->label!='-'?$obj->label:''));	// $obj->label is already in output charset (converted by database driver)
-						$arraydata[$obj->code]=array('code'=>$obj->code, 'label'=>$labeljs, 'label_sort'=>$labelcountry.'_'.$labeljs, 'country_code'=>$obj->country_code, 'country'=>$labelcountry);
+						$labelcountry = (($langs->trans("Country".$obj->country_code) != "Country".$obj->country_code) ? $langs->trans("Country".$obj->country_code) : $obj->country);
+						$labeljs = (($langs->trans("JuridicalStatus".$obj->code) != "JuridicalStatus".$obj->code) ? $langs->trans("JuridicalStatus".$obj->code) : ($obj->label != '-' ? $obj->label : '')); // $obj->label is already in output charset (converted by database driver)
+						$arraydata[$obj->code] = array('code'=>$obj->code, 'label'=>$labeljs, 'label_sort'=>$labelcountry.'_'.$labeljs, 'country_code'=>$obj->country_code, 'country'=>$labelcountry);
 					}
 					$i++;
 				}
 
-				$arraydata=dol_sort_array($arraydata, 'label_sort', 'ASC');
+				$arraydata = dol_sort_array($arraydata, 'label_sort', 'ASC');
 				if (empty($country_codeid))	// Introduce empty value (if $country_codeid not empty, empty value was already added)
 				{
-					$arraydata[0]=array('code'=>0, 'label'=>'', 'label_sort'=>'_', 'country_code'=>'', 'country'=>'');
+					$arraydata[0] = array('code'=>0, 'label'=>'', 'label_sort'=>'_', 'country_code'=>'', 'country'=>'');
 				}
 
-				foreach($arraydata as $key => $val)
+				foreach ($arraydata as $key => $val)
 				{
-					if (! $country || $country != $val['country'])
+					if (!$country || $country != $val['country'])
 					{
 						// Show break when we are in multi country mode
 						if (empty($country_codeid) && $val['country_code'])
 						{
-							$out.= '<option value="0" disabled class="selectoptiondisabledwhite">----- '.$val['country']." -----</option>\n";
-							$country=$val['country'];
+							$out .= '<option value="0" disabled class="selectoptiondisabledwhite">----- '.$val['country']." -----</option>\n";
+							$country = $val['country'];
 						}
 					}
 
 					if ($selected > 0 && $selected == $val['code'])
 					{
-						$out.= '<option value="'.$val['code'].'" selected>';
+						$out .= '<option value="'.$val['code'].'" selected>';
 					}
 					else
 					{
-						$out.= '<option value="'.$val['code'].'">';
+						$out .= '<option value="'.$val['code'].'">';
 					}
 					// If translation exists, we use it, otherwise we use default label in database
-					$out.= $val['label'];
-					$out.= '</option>';
+					$out .= $val['label'];
+					$out .= '</option>';
 				}
 			}
-			$out.= '</select>';
-			if ($user->admin) $out.= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
+			$out .= '</select>';
+			if ($user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
 
 		    // Make select dynamic
-        	include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
+        	include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
 	        $out .= ajax_combobox($htmlname);
 
-			$out.= '</div>';
+			$out .= '</div>';
 		}
 		else
 		{
@@ -566,15 +566,15 @@ class FormCompany extends Form
 	{
 		global $conf, $langs;
 
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
+		if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
 		{
 			// Use Ajax search
-			$minLength = (is_numeric($conf->global->COMPANY_USE_SEARCH_TO_SELECT)?$conf->global->COMPANY_USE_SEARCH_TO_SELECT:2);
+			$minLength = (is_numeric($conf->global->COMPANY_USE_SEARCH_TO_SELECT) ? $conf->global->COMPANY_USE_SEARCH_TO_SELECT : 2);
 
-			$socid=0; $name='';
+			$socid = 0; $name = '';
 			if ($selected > 0)
 			{
-				$tmpthirdparty=new Societe($this->db);
+				$tmpthirdparty = new Societe($this->db);
 				$result = $tmpthirdparty->fetch($selected);
 				if ($result > 0)
 				{
@@ -584,13 +584,13 @@ class FormCompany extends Form
 			}
 
 
-			$events=array();
+			$events = array();
 			// Add an entry 'method' to say 'yes, we must execute url with param action = method';
 			// Add an entry 'url' to say which url to execute
 			// Add an entry htmlname to say which element we must change once url is called
 			// Add entry params => array('cssid' => 'attr') to say to remov or add attribute attr if answer of url return  0 or >0 lines
 			// To refresh contacts list on thirdparty list change
-			$events[]=array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php', 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
+			$events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php', 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
 
 			if (count($events))	// If there is some ajax events to run once selection is done, we add code here to run events
 			{
@@ -646,29 +646,29 @@ class FormCompany extends Form
 
 			print "\n".'<!-- Input text for third party with Ajax.Autocompleter (selectCompaniesForNewContact) -->'."\n";
 			print '<input type="text" size="30" id="search_'.$htmlname.'" name="search_'.$htmlname.'" value="'.$name.'" />';
-			print ajax_autocompleter(($socid?$socid:-1), $htmlname, DOL_URL_ROOT.'/societe/ajaxcompanies.php', '', $minLength, 0);
+			print ajax_autocompleter(($socid ? $socid : -1), $htmlname, DOL_URL_ROOT.'/societe/ajaxcompanies.php', '', $minLength, 0);
 			return $socid;
 		}
 		else
 		{
 			// Search to list thirdparties
 			$sql = "SELECT s.rowid, s.nom as name FROM";
-			$sql.= " ".MAIN_DB_PREFIX."societe as s";
-			$sql.= " WHERE s.entity IN (".getEntity('societe').")";
+			$sql .= " ".MAIN_DB_PREFIX."societe as s";
+			$sql .= " WHERE s.entity IN (".getEntity('societe').")";
 			// For ajax search we limit here. For combo list, we limit later
 			if (is_array($limitto) && count($limitto))
 			{
-				$sql.= " AND s.rowid IN (".join(',', $limitto).")";
+				$sql .= " AND s.rowid IN (".join(',', $limitto).")";
 			}
-			$sql.= " ORDER BY s.nom ASC";
+			$sql .= " ORDER BY s.nom ASC";
 
 			$resql = $this->db->query($sql);
 			if ($resql)
 			{
-				print '<select class="flat'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'"';
+				print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"';
 				if ($conf->use_javascript_ajax)
 				{
-					$javaScript = "window.location='".$_SERVER['PHP_SELF']."?".$var_id."=".($forceid>0?$forceid:$object->id).$moreparam."&".$htmlname."=' + form.".$htmlname.".options[form.".$htmlname.".selectedIndex].value;";
+					$javaScript = "window.location='".$_SERVER['PHP_SELF']."?".$var_id."=".($forceid > 0 ? $forceid : $object->id).$moreparam."&".$htmlname."=' + form.".$htmlname.".options[form.".$htmlname.".selectedIndex].value;";
 					print ' onChange="'.$javaScript.'"';
 				}
 				print '>';
@@ -680,8 +680,8 @@ class FormCompany extends Form
 					{
 						$obj = $this->db->fetch_object($resql);
 						if ($i == 0) $firstCompany = $obj->rowid;
-						$disabled=0;
-						if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid, $limitto)) $disabled=1;
+						$disabled = 0;
+						if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) $disabled = 1;
 						if ($selected > 0 && $selected == $obj->rowid)
 						{
 							print '<option value="'.$obj->rowid.'"';
@@ -695,7 +695,7 @@ class FormCompany extends Form
 							if ($disabled) print ' disabled';
 							print '>'.dol_trunc($obj->name, 24).'</option>';
 						}
-						$i ++;
+						$i++;
 					}
 				}
 				print "</select>\n";
@@ -729,9 +729,9 @@ class FormCompany extends Form
 		if (is_object($object) && method_exists($object, 'liste_type_contact'))
 		{
 			$lesTypes = $object->liste_type_contact($source, $sortorder, 0, 1);
-			print '<select class="flat valignmiddle'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
+			print '<select class="flat valignmiddle'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
 			if ($showempty) print '<option value="0"></option>';
-			foreach($lesTypes as $key=>$value)
+			foreach ($lesTypes as $key=>$value)
 			{
 				print '<option value="'.$key.'"';
 				if ($key == $selected) print ' selected';
@@ -760,29 +760,29 @@ class FormCompany extends Form
 		if ($rendermode === 'view') {
 			$toprint = array();
 			foreach ($contact->roles as $key => $val) {
-				$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa;">' . $val['label'] . '</li>';
+				$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa;">'.$val['label'].'</li>';
 			}
-			return '<div class="select2-container-multi-dolibarr" style="width: 90%;" id="'.$htmlname.'"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
+			return '<div class="select2-container-multi-dolibarr" style="width: 90%;" id="'.$htmlname.'"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
 		}
 
 		if ($rendermode === 'edit')
 		{
-			$contactType=$contact->listeTypeContacts('external', '', 1);
-			if (count($selected)>0) {
-				$newselected=array();
-				foreach($selected as $key=>$val) {
+			$contactType = $contact->listeTypeContacts('external', '', 1);
+			if (count($selected) > 0) {
+				$newselected = array();
+				foreach ($selected as $key=>$val) {
 					if (is_array($val) && array_key_exists('id', $val) && in_array($val['id'], array_keys($contactType))) {
-						$newselected[]=$val['id'];
+						$newselected[] = $val['id'];
 					} else {
 						break;
 					}
 				}
-				if (count($newselected)>0) $selected=$newselected;
+				if (count($newselected) > 0) $selected = $newselected;
 			}
 			return $this->multiselectarray($htmlname, $contactType, $selected);
 		}
 
-		return 'ErrorBadValueForParameterRenderMode';	// Should not happened
+		return 'ErrorBadValueForParameterRenderMode'; // Should not happened
 	}
 
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
@@ -803,17 +803,17 @@ class FormCompany extends Form
         // phpcs:enable
 		global $conf;
 
-		$out='';
+		$out = '';
 
-		$size='';
-		if (!empty($fieldsize)) $size='size="'.$fieldsize.'"';
+		$size = '';
+		if (!empty($fieldsize)) $size = 'size="'.$fieldsize.'"';
 
 		if ($conf->use_javascript_ajax && empty($disableautocomplete))
 		{
-			$out.= ajax_multiautocompleter($htmlname, $fields, DOL_URL_ROOT.'/core/ajax/ziptown.php')."\n";
-			$moreattrib.=' autocomplete="off"';
+			$out .= ajax_multiautocompleter($htmlname, $fields, DOL_URL_ROOT.'/core/ajax/ziptown.php')."\n";
+			$moreattrib .= ' autocomplete="off"';
 		}
-		$out.= '<input id="'.$htmlname.'" class="maxwidthonsmartphone'.($morecss?' '.$morecss:'').'" type="text"'.($moreattrib?' '.$moreattrib:'').' name="'.$htmlname.'" '.$size.' value="'.$selected.'">'."\n";
+		$out .= '<input id="'.$htmlname.'" class="maxwidthonsmartphone'.($morecss ? ' '.$morecss : '').'" type="text"'.($moreattrib ? ' '.$moreattrib : '').' name="'.$htmlname.'" '.$size.' value="'.$selected.'">'."\n";
 
 		return $out;
 	}
@@ -832,40 +832,40 @@ class FormCompany extends Form
     public function get_input_id_prof($idprof, $htmlname, $preselected, $country_code, $morecss = 'maxwidth100onsmartphone quatrevingtpercent')
     {
         // phpcs:enable
-        global $conf,$langs;
+        global $conf, $langs;
 
-        $formlength=0;
+        $formlength = 0;
         if (empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
         	if ($country_code == 'FR')
         	{
         		if (isset($idprof)) {
-        			if ($idprof==1) $formlength=9;
-        			elseif ($idprof==2) $formlength=14;
-        			elseif ($idprof==3) $formlength=5;      // 4 chiffres et 1 lettre depuis janvier
-        			elseif ($idprof==4) $formlength=32;     // No maximum as we need to include a town name in this id
+        			if ($idprof == 1) $formlength = 9;
+        			elseif ($idprof == 2) $formlength = 14;
+        			elseif ($idprof == 3) $formlength = 5; // 4 chiffres et 1 lettre depuis janvier
+        			elseif ($idprof == 4) $formlength = 32; // No maximum as we need to include a town name in this id
         		}
         	}
         	elseif ($country_code == 'ES')
         	{
-        		if ($idprof==1) $formlength=9;  //CIF/NIF/NIE 9 digits
-        		if ($idprof==2) $formlength=12; //NASS 12 digits without /
-        		if ($idprof==3) $formlength=5;  //CNAE 5 digits
-        		if ($idprof==4) $formlength=32; //depend of college
+        		if ($idprof == 1) $formlength = 9; //CIF/NIF/NIE 9 digits
+        		if ($idprof == 2) $formlength = 12; //NASS 12 digits without /
+        		if ($idprof == 3) $formlength = 5; //CNAE 5 digits
+        		if ($idprof == 4) $formlength = 32; //depend of college
         	}
         }
 
-        $selected=$preselected;
-        if (! $selected && isset($idprof)) {
-        	if ($idprof==1 && ! empty($this->idprof1)) $selected=$this->idprof1;
-        	elseif ($idprof==2 && ! empty($this->idprof2)) $selected=$this->idprof2;
-        	elseif ($idprof==3 && ! empty($this->idprof3)) $selected=$this->idprof3;
-        	elseif ($idprof==4 && ! empty($this->idprof4)) $selected=$this->idprof4;
+        $selected = $preselected;
+        if (!$selected && isset($idprof)) {
+        	if ($idprof == 1 && !empty($this->idprof1)) $selected = $this->idprof1;
+        	elseif ($idprof == 2 && !empty($this->idprof2)) $selected = $this->idprof2;
+        	elseif ($idprof == 3 && !empty($this->idprof3)) $selected = $this->idprof3;
+        	elseif ($idprof == 4 && !empty($this->idprof4)) $selected = $this->idprof4;
         }
 
-        $maxlength=$formlength;
-        if (empty($formlength)) { $formlength=24; $maxlength=128; }
+        $maxlength = $formlength;
+        if (empty($formlength)) { $formlength = 24; $maxlength = 128; }
 
-        $out = '<input type="text" '.($morecss?'class="'.$morecss.'" ':'').'name="'.$htmlname.'" id="'.$htmlname.'" maxlength="'.$maxlength.'" value="'.$selected.'">';
+        $out = '<input type="text" '.($morecss ? 'class="'.$morecss.'" ' : '').'name="'.$htmlname.'" id="'.$htmlname.'" maxlength="'.$maxlength.'" value="'.$selected.'">';
 
         return $out;
     }
@@ -882,19 +882,19 @@ class FormCompany extends Form
     public function select_localtax($local, $selected, $htmlname)
     {
         // phpcs:enable
-        $tax=get_localtax_by_third($local);
+        $tax = get_localtax_by_third($local);
 
         $num = $this->db->num_rows($tax);
         $i = 0;
     	if ($num)
     	{
-    		$valors=explode(":", $tax);
+    		$valors = explode(":", $tax);
 
     		if (count($valors) > 1)
     		{
     			//montar select
     			print '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
-    			while ($i <= (count($valors))-1)
+    			while ($i <= (count($valors)) - 1)
     			{
     				if ($selected == $valors[$i])
     				{
@@ -926,37 +926,37 @@ class FormCompany extends Form
     public function selectProspectCustomerType($selected, $htmlname = 'client', $htmlidname = 'customerprospect', $typeinput = 'form', $morecss = '')
     {
 
-    	global $conf,$langs;
+    	global $conf, $langs;
 
     	$out = '<select class="flat '.$morecss.'" name="'.$htmlname.'" id="'.$htmlidname.'">';
-    	if ($typeinput=='form') {
+    	if ($typeinput == 'form') {
     		if ($selected == '' || $selected == '-1') $out .= '<option value="-1">&nbsp;</option>';
 	    	if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
-	    		$out .= '<option value="2"'.($selected==2?' selected':'').'>'.$langs->trans('Prospect').'</option>';
+	    		$out .= '<option value="2"'.($selected == 2 ? ' selected' : '').'>'.$langs->trans('Prospect').'</option>';
 	    	}
 	    	if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) {
-	    		$out .= '<option value="3"'.($selected==3?' selected':'').'>'.$langs->trans('ProspectCustomer').'</option>';
+	    		$out .= '<option value="3"'.($selected == 3 ? ' selected' : '').'>'.$langs->trans('ProspectCustomer').'</option>';
 	    	}
 	    	if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
-	    		$out .= '<option value="1"'.($selected==1?' selected':'').'>'.$langs->trans('Customer').'</option>';
+	    		$out .= '<option value="1"'.($selected == 1 ? ' selected' : '').'>'.$langs->trans('Customer').'</option>';
 	    	}
-	    	$out .= '<option value="0"'.((string) $selected == '0'?' selected':'').'>'.$langs->trans('NorProspectNorCustomer').'</option>';
-    	} elseif ($typeinput=='list') {
-    		$out .=  '<option value="-1"'.(($selected=='' || $selected == '-1')?' selected':'').'>&nbsp;</option>';
+	    	$out .= '<option value="0"'.((string) $selected == '0' ? ' selected' : '').'>'.$langs->trans('NorProspectNorCustomer').'</option>';
+    	} elseif ($typeinput == 'list') {
+    		$out .= '<option value="-1"'.(($selected == '' || $selected == '-1') ? ' selected' : '').'>&nbsp;</option>';
     		if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
-    			$out .=  '<option value="1,3"'.($selected=='1,3'?' selected':'').'>'.$langs->trans('Customer').'</option>';
+    			$out .= '<option value="1,3"'.($selected == '1,3' ? ' selected' : '').'>'.$langs->trans('Customer').'</option>';
     		}
     		if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
-    			$out .=  '<option value="2,3"'.($selected=='2,3'?' selected':'').'>'.$langs->trans('Prospect').'</option>';
+    			$out .= '<option value="2,3"'.($selected == '2,3' ? ' selected' : '').'>'.$langs->trans('Prospect').'</option>';
     		}
-    		$out .=  '<option value="4"'.($selected=='4'?' selected':'').'>'.$langs->trans('Supplier').'</option>';
-    		$out .=  '<option value="0"'.($selected=='0'?' selected':'').'>'.$langs->trans('Others').'</option>';
-    	} elseif ($typeinput=='admin') {
+    		$out .= '<option value="4"'.($selected == '4' ? ' selected' : '').'>'.$langs->trans('Supplier').'</option>';
+    		$out .= '<option value="0"'.($selected == '0' ? ' selected' : '').'>'.$langs->trans('Others').'</option>';
+    	} elseif ($typeinput == 'admin') {
     		if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && empty($conf->global->SOCIETE_DISABLE_PROSPECTSCUSTOMERS)) {
-    			$out .= '<option value="3"'.($selected==3?' selected':'').'>'.$langs->trans('ProspectCustomer').'</option>';
+    			$out .= '<option value="3"'.($selected == 3 ? ' selected' : '').'>'.$langs->trans('ProspectCustomer').'</option>';
     		}
     		if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
-    			$out .= '<option value="1"'.($selected==1?' selected':'').'>'.$langs->trans('Customer').'</option>';
+    			$out .= '<option value="1"'.($selected == 1 ? ' selected' : '').'>'.$langs->trans('Customer').'</option>';
     		}
     	}
     	$out .= '</select>';

+ 121 - 121
htdocs/core/class/html.formticket.class.php

@@ -22,12 +22,12 @@
  *       \ingroup    ticket
  *       \brief      Fichier de la classe permettant la generation du formulaire html d'envoi de mail unitaire
  */
-require_once DOL_DOCUMENT_ROOT . "/core/class/html.form.class.php";
-require_once DOL_DOCUMENT_ROOT . "/core/class/html.formmail.class.php";
-require_once DOL_DOCUMENT_ROOT . "/core/class/html.formprojet.class.php";
+require_once DOL_DOCUMENT_ROOT."/core/class/html.form.class.php";
+require_once DOL_DOCUMENT_ROOT."/core/class/html.formmail.class.php";
+require_once DOL_DOCUMENT_ROOT."/core/class/html.formprojet.class.php";
 
 if (!class_exists('FormCompany')) {
-    include DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
+    include DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
 }
 
 /**
@@ -117,7 +117,7 @@ class FormTicket
         $this->withcreatereadonly = 1;
         $this->withemail = 0;
         $this->withref = 0;
-        $this->withextrafields = 0;         // Show extrafields or not
+        $this->withextrafields = 0; // Show extrafields or not
         //$this->withtopicreadonly=0;
     }
 
@@ -152,26 +152,26 @@ class FormTicket
 
         if ($withdolfichehead) dol_fiche_head(null, 'card', '', 0, '');
 
-        print '<form method="POST" '.($withdolfichehead?'':'style="margin-bottom: 30px;" ').'name="ticket" id="form_create_ticket" enctype="multipart/form-data" action="' . $this->param["returnurl"] . '">';
-        print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
-        print '<input type="hidden" name="action" value="' . $this->action . '">';
+        print '<form method="POST" '.($withdolfichehead ? '' : 'style="margin-bottom: 30px;" ').'name="ticket" id="form_create_ticket" enctype="multipart/form-data" action="'.$this->param["returnurl"].'">';
+        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+        print '<input type="hidden" name="action" value="'.$this->action.'">';
         foreach ($this->param as $key => $value) {
-        	print '<input type="hidden" name="' . $key . '" value="' . $value . '">';
+        	print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
         }
-        print '<input type="hidden" name="fk_user_create" value="' . $this->fk_user_create . '">';
+        print '<input type="hidden" name="fk_user_create" value="'.$this->fk_user_create.'">';
 
         print '<table class="border centpercent">';
 
         if ($this->withref) {
             // Ref
             $defaultref = $ticketstat->getDefaultRef();
-            print '<tr><td class="titlefieldcreate"><span class="fieldrequired">' . $langs->trans("Ref") . '</span></td><td><input size="18" type="text" name="ref" value="' . (GETPOST("ref", 'alpha') ? GETPOST("ref", 'alpha') : $defaultref) . '"></td></tr>';
+            print '<tr><td class="titlefieldcreate"><span class="fieldrequired">'.$langs->trans("Ref").'</span></td><td><input size="18" type="text" name="ref" value="'.(GETPOST("ref", 'alpha') ? GETPOST("ref", 'alpha') : $defaultref).'"></td></tr>';
         }
 
         // TITLE
         if ($this->withemail) {
-            print '<tr><td class="titlefield"><label for="email"><span class="fieldrequired">' . $langs->trans("Email") . '</span></label></td><td>';
-            print '<input  class="text minwidth200" id="email" name="email" value="' . (GETPOST('email', 'alpha') ? GETPOST('email', 'alpha') : $subject) . '" />';
+            print '<tr><td class="titlefield"><label for="email"><span class="fieldrequired">'.$langs->trans("Email").'</span></label></td><td>';
+            print '<input  class="text minwidth200" id="email" name="email" value="'.(GETPOST('email', 'alpha') ? GETPOST('email', 'alpha') : $subject).'" />';
             print '</td></tr>';
         }
 
@@ -184,7 +184,7 @@ class FormTicket
                 $subelement = $regs[2];
             }
 
-            dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
+            dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
             $classname = ucfirst($subelement);
             $objectsrc = new $classname($this->db);
             $objectsrc->fetch(GETPOST('originid', 'int'));
@@ -195,53 +195,53 @@ class FormTicket
 
             $objectsrc->fetch_thirdparty();
             $newclassname = $classname;
-            print '<tr><td>' . $langs->trans($newclassname) . '</td><td colspan="2"><input name="' . $subelement . 'id" value="' . GETPOST('originid') . '" type="hidden" />' . $objectsrc->getNomUrl(1) . '</td></tr>';
+            print '<tr><td>'.$langs->trans($newclassname).'</td><td colspan="2"><input name="'.$subelement.'id" value="'.GETPOST('originid').'" type="hidden" />'.$objectsrc->getNomUrl(1).'</td></tr>';
         }
 
         // Type
-        print '<tr><td class="titlefield"><span class="fieldrequired"><label for="selecttype_code">' . $langs->trans("TicketTypeRequest") . '</span></label></td><td>';
+        print '<tr><td class="titlefield"><span class="fieldrequired"><label for="selecttype_code">'.$langs->trans("TicketTypeRequest").'</span></label></td><td>';
         $this->selectTypesTickets((GETPOST('type_code') ? GETPOST('type_code') : $this->type_code), 'type_code', '', '2');
         print '</td></tr>';
 
         // Severity
-        print '<tr><td><span class="fieldrequired"><label for="selectseverity_code">' . $langs->trans("TicketSeverity") . '</span></label></td><td>';
+        print '<tr><td><span class="fieldrequired"><label for="selectseverity_code">'.$langs->trans("TicketSeverity").'</span></label></td><td>';
         $this->selectSeveritiesTickets((GETPOST('severity_code') ? GETPOST('severity_code') : $this->severity_code), 'severity_code', '', '2');
         print '</td></tr>';
 
         // Group
-        print '<tr><td><span class="fieldrequired"><label for="selectcategory_code">' . $langs->trans("TicketGroup") . '</span></label></td><td>';
+        print '<tr><td><span class="fieldrequired"><label for="selectcategory_code">'.$langs->trans("TicketGroup").'</span></label></td><td>';
         $this->selectGroupTickets((GETPOST('category_code') ? GETPOST('category_code') : $this->category_code), 'category_code', '', '2');
         print '</td></tr>';
 
         // Subject
         if ($this->withtitletopic) {
-            print '<tr><td><label for="subject"><span class="fieldrequired">' . $langs->trans("Subject") . '</span></label></td><td>';
+            print '<tr><td><label for="subject"><span class="fieldrequired">'.$langs->trans("Subject").'</span></label></td><td>';
 
             // Réponse à un ticket : affichage du titre du thread en readonly
             if ($this->withtopicreadonly) {
-                print $langs->trans('SubjectAnswerToTicket') . ' ' . $this->topic_title;
+                print $langs->trans('SubjectAnswerToTicket').' '.$this->topic_title;
                 print '</td></tr>';
             } else {
                 if ($this->withthreadid > 0) {
-                    $subject = $langs->trans('SubjectAnswerToTicket') . ' ' . $this->withthreadid . ' : ' . $this->topic_title . '';
+                    $subject = $langs->trans('SubjectAnswerToTicket').' '.$this->withthreadid.' : '.$this->topic_title.'';
                 }
-                print '<input class="text" size="50" id="subject" name="subject" value="' . (GETPOST('subject', 'alpha') ? GETPOST('subject', 'alpha') : $subject) . '" />';
+                print '<input class="text" size="50" id="subject" name="subject" value="'.(GETPOST('subject', 'alpha') ? GETPOST('subject', 'alpha') : $subject).'" />';
                 print '</td></tr>';
             }
         }
 
         // MESSAGE
         $msg = GETPOSTISSET('message') ? GETPOST('message', 'none') : '';
-        print '<tr><td><label for="message"><span class="fieldrequired">' . $langs->trans("Message") . '</span></label></td><td>';
+        print '<tr><td><label for="message"><span class="fieldrequired">'.$langs->trans("Message").'</span></label></td><td>';
 
         // If public form, display more information
         $toolbarname = 'dolibarr_notes';
         if ($this->ispublic)
         {
             $toolbarname = 'dolibarr_details';
-            print '<div class="warning">' . ($conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe')) . '</div>';
+            print '<div class="warning">'.($conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE ? $conf->global->TICKET_PUBLIC_TEXT_HELP_MESSAGE : $langs->trans('TicketPublicPleaseBeAccuratelyDescribe')).'</div>';
         }
-        include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
+        include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
         $uselocalbrowser = true;
         $doleditor = new DolEditor('message', $msg, '100%', 230, $toolbarname, 'In', true, $uselocalbrowser, $conf->global->FCKEDITOR_ENABLE_TICKET, ROWS_8, '90%');
         $doleditor->Create();
@@ -249,7 +249,7 @@ class FormTicket
 
         // FK_USER_CREATE
         if ($this->withusercreate > 0 && $this->fk_user_create) {
-            print '<tr><td class="titlefield">' . $langs->trans("CreatedBy") . '</td><td>';
+            print '<tr><td class="titlefield">'.$langs->trans("CreatedBy").'</td><td>';
             $langs->load("users");
             $fuser = new User($this->db);
 
@@ -267,12 +267,12 @@ class FormTicket
             // altairis: force company and contact id for external user
             if (empty($user->socid)) {
                 // Company
-                print '<tr><td class="titlefield">' . $langs->trans("ThirdParty") . '</td><td>';
+                print '<tr><td class="titlefield">'.$langs->trans("ThirdParty").'</td><td>';
                 $events = array();
                 $events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php', 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
                 print $form->select_company($this->withfromsocid, 'socid', '', 1, 1, '', $events, 0, 'minwidth200');
                 print '</td></tr>';
-                if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
+                if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
                     $htmlname = 'socid';
                     print '<script type="text/javascript">
                     $(document).ready(function () {
@@ -327,7 +327,7 @@ class FormTicket
                 }
 
                 // Contact and type
-                print '<tr><td>' . $langs->trans("Contact") . '</td><td>';
+                print '<tr><td>'.$langs->trans("Contact").'</td><td>';
                 // If no socid, set to -1 to avoid full contacts list
                 $selectedCompany = ($this->withfromsocid > 0) ? $this->withfromsocid : -1;
                 $nbofcontacts = $form->select_contacts($selectedCompany, $this->withfromcontactid, 'contactid', 3, '', '', 0, 'minwidth200');
@@ -335,24 +335,24 @@ class FormTicket
                 $formcompany->selectTypeContact($ticketstatic, '', 'type', 'external', '', 0, 'maginleftonly');
                 print '</td></tr>';
             } else {
-                print '<tr><td class="titlefield"><input type="hidden" name="socid" value="' . $user->socid . '"/></td>';
-                print '<td><input type="hidden" name="contactid" value="' . $user->contactid . '"/></td>';
+                print '<tr><td class="titlefield"><input type="hidden" name="socid" value="'.$user->socid.'"/></td>';
+                print '<td><input type="hidden" name="contactid" value="'.$user->contactid.'"/></td>';
                 print '<td><input type="hidden" name="type" value="Z"/></td></tr>';
             }
 
             // Notify thirdparty at creation
             if (empty($this->ispublic))
             {
-                print '<tr><td><label for="notify_tiers_at_create">' . $langs->trans("TicketNotifyTiersAtCreation") . '</label></td><td>';
-                print '<input type="checkbox" id="notify_tiers_at_create" name="notify_tiers_at_create"'.($this->withnotifytiersatcreate?' checked="checked"':'').'>';
+                print '<tr><td><label for="notify_tiers_at_create">'.$langs->trans("TicketNotifyTiersAtCreation").'</label></td><td>';
+                print '<input type="checkbox" id="notify_tiers_at_create" name="notify_tiers_at_create"'.($this->withnotifytiersatcreate ? ' checked="checked"' : '').'>';
                 print '</td></tr>';
             }
         }
 
-        if (! empty($conf->projet->enabled) && ! $this->ispublic)
+        if (!empty($conf->projet->enabled) && !$this->ispublic)
         {
-            $formproject=new FormProjets($this->db);
-            print '<tr><td><label for="project"><span class="">' . $langs->trans("Project") . '</span></label></td><td>';
+            $formproject = new FormProjets($this->db);
+            print '<tr><td><label for="project"><span class="">'.$langs->trans("Project").'</span></label></td><td>';
             print $formproject->select_projects(-1, GETPOST('projectid', 'int'), 'projectid', 0, 0, 1, 1);
             print '</td></tr>';
         }
@@ -422,11 +422,11 @@ class FormTicket
         if ($withdolfichehead) dol_fiche_end();
 
         print '<br><center>';
-        print '<input class="button" type="submit" name="add" value="' . $langs->trans(($this->withthreadid > 0 ? "SendResponse" : "NewTicket")) . '" />';
+        print '<input class="button" type="submit" name="add" value="'.$langs->trans(($this->withthreadid > 0 ? "SendResponse" : "NewTicket")).'" />';
 
         if ($this->withcancel) {
             print " &nbsp; &nbsp; ";
-            print "<input class=\"button\" type=\"submit\" name=\"cancel\" value=\"" . $langs->trans("Cancel") . "\">";
+            print "<input class=\"button\" type=\"submit\" name=\"cancel\" value=\"".$langs->trans("Cancel")."\">";
         }
         print "</center>\n";
 
@@ -453,7 +453,7 @@ class FormTicket
 
         $ticketstat = new Ticket($this->db);
 
-        dol_syslog(get_class($this) . "::select_types_tickets " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
+        dol_syslog(get_class($this)."::select_types_tickets ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
 
         $filterarray = array();
 
@@ -463,7 +463,7 @@ class FormTicket
 
         $ticketstat->loadCacheTypesTickets();
 
-        print '<select id="select' . $htmlname . '" class="flat minwidth100'.($morecss?' '.$morecss:'').'" name="' . $htmlname . '">';
+        print '<select id="select'.$htmlname.'" class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
         if ($empty) {
             print '<option value="">&nbsp;</option>';
         }
@@ -481,19 +481,19 @@ class FormTicket
                 }
 
                 if ($format == 0) {
-                    print '<option value="' . $id . '"';
+                    print '<option value="'.$id.'"';
                 }
 
                 if ($format == 1) {
-                    print '<option value="' . $arraytypes['code'] . '"';
+                    print '<option value="'.$arraytypes['code'].'"';
                 }
 
                 if ($format == 2) {
-                    print '<option value="' . $arraytypes['code'] . '"';
+                    print '<option value="'.$arraytypes['code'].'"';
                 }
 
                 if ($format == 3) {
-                    print '<option value="' . $id . '"';
+                    print '<option value="'.$id.'"';
                 }
 
                 // Si selected est text, on compare avec code, sinon avec id
@@ -548,7 +548,7 @@ class FormTicket
 
         $ticketstat = new Ticket($this->db);
 
-        dol_syslog(get_class($this) . "::selectCategoryTickets " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
+        dol_syslog(get_class($this)."::selectCategoryTickets ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
 
         $filterarray = array();
 
@@ -558,7 +558,7 @@ class FormTicket
 
         $ticketstat->loadCacheCategoriesTickets();
 
-        print '<select id="select' . $htmlname . '" class="flat minwidth100'.($morecss?' '.$morecss:'').'" name="' . $htmlname . '">';
+        print '<select id="select'.$htmlname.'" class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
         if ($empty) {
             print '<option value="">&nbsp;</option>';
         }
@@ -576,19 +576,19 @@ class FormTicket
                 }
 
                 if ($format == 0) {
-                    print '<option value="' . $id . '"';
+                    print '<option value="'.$id.'"';
                 }
 
                 if ($format == 1) {
-                    print '<option value="' . $arraycategories['code'] . '"';
+                    print '<option value="'.$arraycategories['code'].'"';
                 }
 
                 if ($format == 2) {
-                    print '<option value="' . $arraycategories['code'] . '"';
+                    print '<option value="'.$arraycategories['code'].'"';
                 }
 
                 if ($format == 3) {
-                    print '<option value="' . $id . '"';
+                    print '<option value="'.$id.'"';
                 }
 
                 // Si selected est text, on compare avec code, sinon avec id
@@ -649,7 +649,7 @@ class FormTicket
 
         $ticketstat = new Ticket($this->db);
 
-        dol_syslog(get_class($this) . "::selectSeveritiesTickets " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
+        dol_syslog(get_class($this)."::selectSeveritiesTickets ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
 
         $filterarray = array();
 
@@ -659,7 +659,7 @@ class FormTicket
 
         $ticketstat->loadCacheSeveritiesTickets();
 
-        print '<select id="select' . $htmlname . '" class="flat minwidth100'.($morecss?' '.$morecss:'').'" name="' . $htmlname . '">';
+        print '<select id="select'.$htmlname.'" class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
         if ($empty) {
             print '<option value="">&nbsp;</option>';
         }
@@ -677,19 +677,19 @@ class FormTicket
                 }
 
                 if ($format == 0) {
-                    print '<option value="' . $id . '"';
+                    print '<option value="'.$id.'"';
                 }
 
                 if ($format == 1) {
-                    print '<option value="' . $arrayseverities['code'] . '"';
+                    print '<option value="'.$arrayseverities['code'].'"';
                 }
 
                 if ($format == 2) {
-                    print '<option value="' . $arrayseverities['code'] . '"';
+                    print '<option value="'.$arrayseverities['code'].'"';
                 }
 
                 if ($format == 3) {
-                    print '<option value="' . $id . '"';
+                    print '<option value="'.$id.'"';
                 }
 
                 // Si selected est text, on compare avec code, sinon avec id
@@ -739,15 +739,15 @@ class FormTicket
     public function clear_attached_files()
     {
     	// phpcs:enable
-    	global $conf,$user;
+    	global $conf, $user;
     	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 
     	// Set tmp user directory
-    	$vardir=$conf->user->dir_output."/".$user->id;
-    	$upload_dir = $vardir.'/temp/';                     // TODO Add $keytoavoidconflict in upload_dir path
+    	$vardir = $conf->user->dir_output."/".$user->id;
+    	$upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path
     	if (is_dir($upload_dir)) dol_delete_dir_recursive($upload_dir);
 
-    	$keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid;   // this->trackid must be defined
+    	$keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
     	unset($_SESSION["listofpaths".$keytoavoidconflict]);
     	unset($_SESSION["listofnames".$keytoavoidconflict]);
     	unset($_SESSION["listofmimes".$keytoavoidconflict]);
@@ -766,7 +766,7 @@ class FormTicket
         $formmail = new FormMail($this->db);
         $addfileaction = 'addfile';
 
-        if (! is_object($form)) $form=new Form($this->db);
+        if (!is_object($form)) $form = new Form($this->db);
 
         // Load translation files required by the page
         $langs->loadLangs(array('other', 'mails'));
@@ -781,7 +781,7 @@ class FormTicket
         $outputlangs = $langs;
         $newlang = '';
         if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $this->param['langsmodels'];
-        if (! empty($newlang))
+        if (!empty($newlang))
         {
         	$outputlangs = new Translate("", $conf);
         	$outputlangs->setDefaultLang($newlang);
@@ -792,35 +792,35 @@ class FormTicket
         $arraydefaultmessage = -1;
         if ($this->param['models'] != 'none')
         {
-        	$model_id=0;
+        	$model_id = 0;
         	if (array_key_exists('models_id', $this->param))
         	{
-        		$model_id=$this->param["models_id"];
+        		$model_id = $this->param["models_id"];
         	}
 
-        	$arraydefaultmessage=$formmail->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id);		// If $model_id is empty, preselect the first one
+        	$arraydefaultmessage = $formmail->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id); // If $model_id is empty, preselect the first one
         }
 
         // Define list of attached files
         $listofpaths = array();
         $listofnames = array();
         $listofmimes = array();
-        $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid;   // this->trackid must be defined
+        $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
 
         if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1'))
         {
-        	if (! empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit']))
+        	if (!empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit']))
         	{
-        		foreach($this->param['fileinit'] as $file)
+        		foreach ($this->param['fileinit'] as $file)
         		{
         			$this->add_attached_files($file, basename($file), dol_mimetype($file));
         		}
         	}
         }
 
-        if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
-        if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
-        if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
+        if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
+        if (!empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
+        if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
 
         // Define output language
         $outputlangs = $langs;
@@ -828,7 +828,7 @@ class FormTicket
         if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
             $newlang = $this->param['langsmodels'];
         }
-        if (! empty($newlang)) {
+        if (!empty($newlang)) {
             $outputlangs = new Translate("", $conf);
             $outputlangs->setDefaultLang($newlang);
             $outputlangs->load('other');
@@ -841,7 +841,7 @@ class FormTicket
         // Example 1 : Adding jquery code
         print '<script type="text/javascript" language="javascript">
 		jQuery(document).ready(function() {
-			send_email=' . $send_email . ';
+			send_email=' . $send_email.';
 			if (send_email) {
 				jQuery(".email_line").show();
 			} else {
@@ -859,31 +859,31 @@ class FormTicket
         print '});
 		</script>';
 
-        print '<form method="post" name="ticket" enctype="multipart/form-data" action="' . $this->param["returnurl"] . '">';
-        print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
-        print '<input type="hidden" name="action" value="' . $this->action . '">';
+        print '<form method="post" name="ticket" enctype="multipart/form-data" action="'.$this->param["returnurl"].'">';
+        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+        print '<input type="hidden" name="action" value="'.$this->action.'">';
         print '<input type="hidden" name="actionbis" value="add_message">';
         foreach ($this->param as $key => $value) {
-            print '<input type="hidden" name="' . $key . '" value="' . $value . '">';
+            print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
         }
 
         // Get message template
-        $model_id=0;
+        $model_id = 0;
         if (array_key_exists('models_id', $this->param)) {
-            $model_id=$this->param["models_id"];
-            $arraydefaultmessage=$formmail->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id);
+            $model_id = $this->param["models_id"];
+            $arraydefaultmessage = $formmail->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id);
         }
 
         $result = $formmail->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs);
-        if ($result<0) {
+        if ($result < 0) {
             setEventMessages($this->error, $this->errors, 'errors');
         }
-        $modelmail_array=array();
+        $modelmail_array = array();
         foreach ($formmail->lines_model as $line) {
-            $modelmail_array[$line->id]=$line->label;
+            $modelmail_array[$line->id] = $line->label;
         }
 
-        print '<table class="border"  width="' . $width . '">';
+        print '<table class="border"  width="'.$width.'">';
 
         // External users can't send message email
         if ($user->rights->ticket->write && !$user->socid)
@@ -891,11 +891,11 @@ class FormTicket
             print '<tr><td width="30%"></td><td colspan="2">';
             $checkbox_selected = (GETPOST('send_email') == "1" ? ' checked' : '');
             print '<input type="checkbox" name="send_email" value="1" id="send_msg_email" '.$checkbox_selected.'/> ';
-            print '<label for="send_msg_email">' . $langs->trans('SendMessageByEmail') . '</label>';
+            print '<label for="send_msg_email">'.$langs->trans('SendMessageByEmail').'</label>';
             print '</td></tr>';
 
             // Zone to select its email template
-            if (count($modelmail_array)>0) {
+            if (count($modelmail_array) > 0) {
                 print '<tr class="email_line"><td></td><td colspan="2"><div style="padding: 3px 0 3px 0">'."\n";
                 print $langs->trans('SelectMailModel').': '.$formmail->selectarray('modelmailselected', $modelmail_array, $this->param['models_id'], 1);
                 if ($user->admin) {
@@ -908,23 +908,23 @@ class FormTicket
             }
 
             // Private message (not visible by customer/external user)
-            if (! $user->socid) {
+            if (!$user->socid) {
                 print '<tr><td width="30%"></td><td>';
                 $checkbox_selected = (GETPOST('private_message', 'alpha') == "1" ? ' checked' : '');
                 print '<input type="checkbox" name="private_message" value="1" id="private_message" '.$checkbox_selected.'/> ';
-                print '<label for="private_message">' . $langs->trans('MarkMessageAsPrivate') . '</label>';
+                print '<label for="private_message">'.$langs->trans('MarkMessageAsPrivate').'</label>';
                 print '</td><td align="center">';
                 print $form->textwithpicto('', $langs->trans("TicketMessagePrivateHelp"), 1, 'help');
                 print '</td></tr>';
             }
 
-            print '<tr class="email_line"><td class="titlefieldcreate">' . $langs->trans('Subject') . '</td>';
+            print '<tr class="email_line"><td class="titlefieldcreate">'.$langs->trans('Subject').'</td>';
             $label_title = empty($conf->global->MAIN_APPLICATION_TITLE) ? $mysoc->name : $conf->global->MAIN_APPLICATION_TITLE;
-            print '<td colspan="2"><input type="text" class="text" size="80" name="subject" value="[' . $label_title . ' - ticket #' . $this->track_id . '] ' . $langs->trans('TicketNewMessage') . '" />';
+            print '<td colspan="2"><input type="text" class="text" size="80" name="subject" value="['.$label_title.' - ticket #'.$this->track_id.'] '.$langs->trans('TicketNewMessage').'" />';
             print '</td></tr>';
 
             // Destinataires
-            print '<tr class="email_line"><td>' . $langs->trans('MailRecipients') . '</td><td colspan="2">';
+            print '<tr class="email_line"><td>'.$langs->trans('MailRecipients').'</td><td colspan="2">';
             $ticketstat = new Ticket($this->db);
             $res = $ticketstat->fetch('', '', $this->track_id);
             if ($res) {
@@ -936,13 +936,13 @@ class FormTicket
                 if (is_array($contacts) && count($contacts) > 0) {
                     foreach ($contacts as $key => $info_sendto) {
                         if ($info_sendto['email'] != '') {
-                        	$sendto[] = dol_escape_htmltag(trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">")." <small>(" . dol_escape_htmltag($info_sendto['libelle']) . ")</small>";
+                        	$sendto[] = dol_escape_htmltag(trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">")." <small>(".dol_escape_htmltag($info_sendto['libelle']).")</small>";
                         }
                     }
                 }
 
                 if ($ticketstat->origin_email && !in_array($this->dao->origin_email, $sendto)) {
-                	$sendto[] = dol_escape_htmltag($ticketstat->origin_email) . " <small>(".$langs->trans("TicketEmailOriginIssuer").")</small>";
+                	$sendto[] = dol_escape_htmltag($ticketstat->origin_email)." <small>(".$langs->trans("TicketEmailOriginIssuer").")</small>";
                 }
 
                 if ($ticketstat->fk_soc > 0) {
@@ -950,19 +950,19 @@ class FormTicket
                     $ticketstat->fetch_thirdparty();
 
                     if (is_array($ticketstat->thirdparty->email) && !in_array($ticketstat->thirdparty->email, $sendto)) {
-                        $sendto[] = $ticketstat->thirdparty->email . ' <small>(' . $langs->trans('Customer') . ')</small>';
+                        $sendto[] = $ticketstat->thirdparty->email.' <small>('.$langs->trans('Customer').')</small>';
                     }
                 }
 
                 if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS) {
-                    $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO . ' <small>(generic email)</small>';
+                    $sendto[] = $conf->global->TICKET_NOTIFICATION_EMAIL_TO.' <small>(generic email)</small>';
                 }
 
                 // Print recipient list
                 if (is_array($sendto) && count($sendto) > 0) {
                     print implode(', ', $sendto);
                 } else {
-                    print '<div class="warning">' . $langs->trans('WarningNoEMailsAdded') . ' ' . $langs->trans('TicketGoIntoContactTab') . '</div>';
+                    print '<div class="warning">'.$langs->trans('WarningNoEMailsAdded').' '.$langs->trans('TicketGoIntoContactTab').'</div>';
                 }
             }
             print '</td></tr>';
@@ -972,10 +972,10 @@ class FormTicket
         // External users can't send message email
         if ($user->rights->ticket->write && !$user->socid) {
             $mail_intro = GETPOST('mail_intro') ? GETPOST('mail_intro') : $conf->global->TICKET_MESSAGE_MAIL_INTRO;
-            print '<tr class="email_line"><td><label for="mail_intro">' . $langs->trans("TicketMessageMailIntro") . '</label>';
+            print '<tr class="email_line"><td><label for="mail_intro">'.$langs->trans("TicketMessageMailIntro").'</label>';
 
             print '</td><td>';
-            include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
+            include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
             $uselocalbrowser = true;
 
             $doleditor = new DolEditor('mail_intro', $mail_intro, '100%', 90, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70);
@@ -987,11 +987,11 @@ class FormTicket
         }
 
         // MESSAGE
-        $defaultmessage="";
+        $defaultmessage = "";
         if (is_array($arraydefaultmessage) && count($arraydefaultmessage) > 0 && $arraydefaultmessage->content) {
-            $defaultmessage=$arraydefaultmessage->content;
+            $defaultmessage = $arraydefaultmessage->content;
         }
-        $defaultmessage=str_replace('\n', "\n", $defaultmessage);
+        $defaultmessage = str_replace('\n', "\n", $defaultmessage);
 
         // Deal with format differences between message and signature (text / HTML)
         if (dol_textishtml($defaultmessage) && !dol_textishtml($this->substit['__SIGNATURE__'])) {
@@ -999,19 +999,19 @@ class FormTicket
         } elseif (!dol_textishtml($defaultmessage) && dol_textishtml($this->substit['__SIGNATURE__'])) {
             $defaultmessage = dol_nl2br($defaultmessage);
         }
-        if (isset($_POST["message"]) &&  ! $_POST['modelselected']) {
-            $defaultmessage=GETPOST('message');
+        if (isset($_POST["message"]) && !$_POST['modelselected']) {
+            $defaultmessage = GETPOST('message');
         } else {
-            $defaultmessage=make_substitutions($defaultmessage, $this->substit);
+            $defaultmessage = make_substitutions($defaultmessage, $this->substit);
             // Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty)
-            $defaultmessage=preg_replace("/^(<br>)+/", "", $defaultmessage);
-            $defaultmessage=preg_replace("/^\n+/", "", $defaultmessage);
+            $defaultmessage = preg_replace("/^(<br>)+/", "", $defaultmessage);
+            $defaultmessage = preg_replace("/^\n+/", "", $defaultmessage);
         }
 
-        print '<tr><td class="tdtop"><label for="message"><span class="fieldrequired">' . $langs->trans("Message") . '</span></label></td><td>';
+        print '<tr><td class="tdtop"><label for="message"><span class="fieldrequired">'.$langs->trans("Message").'</span></label></td><td>';
         //$toolbarname = 'dolibarr_details';
         $toolbarname = 'dolibarr_notes';
-        include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
+        include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
         $doleditor = new DolEditor('message', $defaultmessage, '100%', 200, $toolbarname, '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, 70);
         $doleditor->Create();
         print '</td><td align="center">';
@@ -1025,10 +1025,10 @@ class FormTicket
         // External users can't send message email
         if ($user->rights->ticket->write && !$user->socid) {
             $mail_signature = GETPOST('mail_signature') ? GETPOST('mail_signature') : $conf->global->TICKET_MESSAGE_MAIL_SIGNATURE;
-            print '<tr class="email_line"><td><label for="mail_intro">' . $langs->trans("TicketMessageMailSignature") . '</label>';
+            print '<tr class="email_line"><td><label for="mail_intro">'.$langs->trans("TicketMessageMailSignature").'</label>';
 
             print '</td><td>';
-            include_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
+            include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
             $doleditor = new DolEditor('mail_signature', $mail_signature, '100%', 150, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_2, 70);
             $doleditor->Create();
             print '</td><td align="center">';
@@ -1039,33 +1039,33 @@ class FormTicket
         // Attached files
         if (!empty($this->withfile)) {
             $out = '<tr>';
-            $out .= '<td width="180">' . $langs->trans("MailFile") . '</td>';
+            $out .= '<td width="180">'.$langs->trans("MailFile").'</td>';
             $out .= '<td colspan="2">';
             // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript
-            $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">' . "\n";
+            $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
             $out .= '<script type="text/javascript" language="javascript">';
             $out .= 'jQuery(document).ready(function () {';
             $out .= '    jQuery(".removedfile").click(function() {';
             $out .= '        jQuery(".removedfilehidden").val(jQuery(this).val());';
             $out .= '    });';
             $out .= '})';
-            $out .= '</script>' . "\n";
+            $out .= '</script>'."\n";
             if (count($listofpaths)) {
                 foreach ($listofpaths as $key => $val) {
-                    $out .= '<div id="attachfile_' . $key . '">';
-                    $out .= img_mime($listofnames[$key]) . ' ' . $listofnames[$key];
+                    $out .= '<div id="attachfile_'.$key.'">';
+                    $out .= img_mime($listofnames[$key]).' '.$listofnames[$key];
                     if (!$this->withfilereadonly) {
-                        $out .= ' <input type="image" style="border: 0px;" src="' . DOL_URL_ROOT . '/theme/' . $conf->theme . '/img/delete.png" value="' . ($key + 1) . '" class="removedfile reposition" id="removedfile_' . $key . '" name="removedfile_' . $key . '" />';
+                        $out .= ' <input type="image" style="border: 0px;" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/delete.png" value="'.($key + 1).'" class="removedfile reposition" id="removedfile_'.$key.'" name="removedfile_'.$key.'" />';
                     }
                     $out .= '<br></div>';
                 }
             } else {
-                $out .= $langs->trans("NoAttachedFiles") . '<br>';
+                $out .= $langs->trans("NoAttachedFiles").'<br>';
             }
             if ($this->withfile == 2) { // Can add other files
-                $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="' . $langs->trans("Upload") . '" />';
+                $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
                 $out .= ' ';
-                $out .= '<input type="submit" class="button" id="' . $addfileaction . '" name="' . $addfileaction . '" value="' . $langs->trans("MailingAddFile") . '" />';
+                $out .= '<input type="submit" class="button" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
             }
             $out .= "</td></tr>\n";
 
@@ -1075,10 +1075,10 @@ class FormTicket
         print '</table>';
 
         print '<center><br>';
-        print '<input class="button" type="submit" name="btn_add_message" value="' . $langs->trans("AddMessage") . '" />';
+        print '<input class="button" type="submit" name="btn_add_message" value="'.$langs->trans("AddMessage").'" />';
         if ($this->withcancel) {
             print " &nbsp; &nbsp; ";
-            print "<input class=\"button\" type=\"submit\" name=\"cancel\" value=\"" . $langs->trans("Cancel") . "\">";
+            print "<input class=\"button\" type=\"submit\" name=\"cancel\" value=\"".$langs->trans("Cancel")."\">";
         }
         print "</center>\n";
 

+ 62 - 62
htdocs/core/class/infobox.class.php

@@ -94,29 +94,29 @@ class InfoBox
     {
         global $conf;
 
-        $boxes=array();
+        $boxes = array();
 
-        $confuserzone='MAIN_BOXES_'.$zone;
+        $confuserzone = 'MAIN_BOXES_'.$zone;
         if ($mode == 'activated')	// activated
         {
             $sql = "SELECT b.rowid, b.position, b.box_order, b.fk_user,";
-            $sql.= " d.rowid as box_id, d.file, d.note, d.tms";
-            $sql.= " FROM ".MAIN_DB_PREFIX."boxes as b, ".MAIN_DB_PREFIX."boxes_def as d";
-            $sql.= " WHERE b.box_id = d.rowid";
-            $sql.= " AND b.entity IN (0,".$conf->entity.")";
-            if ($zone >= 0) $sql.= " AND b.position = ".$zone;
-            if (is_object($user)) $sql.= " AND b.fk_user IN (0,".$user->id.")";
-            else $sql.= " AND b.fk_user = 0";
-            $sql.= " ORDER BY b.box_order";
+            $sql .= " d.rowid as box_id, d.file, d.note, d.tms";
+            $sql .= " FROM ".MAIN_DB_PREFIX."boxes as b, ".MAIN_DB_PREFIX."boxes_def as d";
+            $sql .= " WHERE b.box_id = d.rowid";
+            $sql .= " AND b.entity IN (0,".$conf->entity.")";
+            if ($zone >= 0) $sql .= " AND b.position = ".$zone;
+            if (is_object($user)) $sql .= " AND b.fk_user IN (0,".$user->id.")";
+            else $sql .= " AND b.fk_user = 0";
+            $sql .= " ORDER BY b.box_order";
         }
         else	// available
         {
             $sql = "SELECT d.rowid as box_id, d.file, d.note, d.tms";
-            $sql.= " FROM ".MAIN_DB_PREFIX."boxes_def as d";
-            $sql.= " WHERE d.entity IN (0,".$conf->entity.")";
+            $sql .= " FROM ".MAIN_DB_PREFIX."boxes_def as d";
+            $sql .= " WHERE d.entity IN (0,".$conf->entity.")";
         }
 
-        dol_syslog(get_class()."::listBoxes get default box list for mode=".$mode." userid=".(is_object($user)?$user->id:'')."", LOG_DEBUG);
+        dol_syslog(get_class()."::listBoxes get default box list for mode=".$mode." userid=".(is_object($user) ? $user->id : '')."", LOG_DEBUG);
         $resql = $db->query($sql);
         if ($resql)
         {
@@ -126,7 +126,7 @@ class InfoBox
             {
                 $obj = $db->fetch_object($resql);
 
-                if (! in_array($obj->box_id, $excludelist))
+                if (!in_array($obj->box_id, $excludelist))
                 {
                     if (preg_match('/^([^@]+)@([^@]+)$/i', $obj->file, $regs))
                     {
@@ -136,7 +136,7 @@ class InfoBox
                     }
                     else
                     {
-                        $boxname=preg_replace('/\.php$/i', '', $obj->file);
+                        $boxname = preg_replace('/\.php$/i', '', $obj->file);
                         $relsourcefile = "/core/boxes/".$boxname.".php";
                     }
 
@@ -148,48 +148,48 @@ class InfoBox
                     dol_include_once($relsourcefile);
                     if (class_exists($boxname))
                     {
-                        $box=new $boxname($db, $obj->note);		// Constructor may set properties like box->enabled. obj->note is note into box def, not user params.
+                        $box = new $boxname($db, $obj->note); // Constructor may set properties like box->enabled. obj->note is note into box def, not user params.
                         //$box=new stdClass();
 
                         // box properties
-                        $box->rowid		= (empty($obj->rowid) ? '' : $obj->rowid);
-                        $box->id		= (empty($obj->box_id) ? '' : $obj->box_id);
-                        $box->position	= ($obj->position == '' ? '' : $obj->position);		// '0' must stay '0'
+                        $box->rowid = (empty($obj->rowid) ? '' : $obj->rowid);
+                        $box->id = (empty($obj->box_id) ? '' : $obj->box_id);
+                        $box->position = ($obj->position == '' ? '' : $obj->position); // '0' must stay '0'
                         $box->box_order	= (empty($obj->box_order) ? '' : $obj->box_order);
-                        $box->fk_user	= (empty($obj->fk_user) ? 0 : $obj->fk_user);
-                        $box->sourcefile= $relsourcefile;
+                        $box->fk_user = (empty($obj->fk_user) ? 0 : $obj->fk_user);
+                        $box->sourcefile = $relsourcefile;
                         $box->class     = $boxname;
 
-                        if ($mode == 'activated' && ! is_object($user))	// List of activated box was not yet personalized into database
+                        if ($mode == 'activated' && !is_object($user))	// List of activated box was not yet personalized into database
                         {
                             if (is_numeric($box->box_order))
                             {
-                                if ($box->box_order % 2 == 1) $box->box_order='A'.$box->box_order;
-                                elseif ($box->box_order % 2 == 0) $box->box_order='B'.$box->box_order;
+                                if ($box->box_order % 2 == 1) $box->box_order = 'A'.$box->box_order;
+                                elseif ($box->box_order % 2 == 0) $box->box_order = 'B'.$box->box_order;
                             }
                         }
                         // box_def properties
-                        $box->box_id	= (empty($obj->box_id) ? '' : $obj->box_id);
-                        $box->note		= (empty($obj->note) ? '' : $obj->note);
+                        $box->box_id = (empty($obj->box_id) ? '' : $obj->box_id);
+                        $box->note = (empty($obj->note) ? '' : $obj->note);
 
                         // Filter on box->enabled (used for example by box_comptes)
                         // Filter also on box->depends. Example: array("product|service") or array("contrat", "service")
-                        $enabled=$box->enabled;
+                        $enabled = $box->enabled;
                         if (isset($box->depends) && count($box->depends) > 0)
                         {
-                            foreach($box->depends as $moduleelem)
+                            foreach ($box->depends as $moduleelem)
                             {
-                                $arrayelem=explode('|', $moduleelem);
-                                $tmpenabled=0;	// $tmpenabled is used for the '|' test (OR)
-                                foreach($arrayelem as $module)
+                                $arrayelem = explode('|', $moduleelem);
+                                $tmpenabled = 0; // $tmpenabled is used for the '|' test (OR)
+                                foreach ($arrayelem as $module)
                                 {
-                                    $tmpmodule=preg_replace('/@[^@]+/', '', $module);
-                                    if (! empty($conf->$tmpmodule->enabled)) $tmpenabled=1;
+                                    $tmpmodule = preg_replace('/@[^@]+/', '', $module);
+                                    if (!empty($conf->$tmpmodule->enabled)) $tmpenabled = 1;
                                     //print $boxname.'-'.$module.'-module enabled='.(empty($conf->$tmpmodule->enabled)?0:1).'<br>';
                                 }
                                 if (empty($tmpenabled))	// We found at least one module required that is disabled
                                 {
-                                    $enabled=0;
+                                    $enabled = 0;
                                     break;
                                 }
                             }
@@ -197,7 +197,7 @@ class InfoBox
                         //print '=>'.$boxname.'-enabled='.$enabled.'<br>';
 
                         //print 'xx module='.$module.' enabled='.$enabled;
-                        if ($enabled && ($includehidden || empty($box->hidden))) $boxes[]=$box;
+                        if ($enabled && ($includehidden || empty($box->hidden))) $boxes[] = $box;
                         else unset($box);
                     }
                     else
@@ -231,66 +231,66 @@ class InfoBox
     {
         global $conf;
 
-        $error=0;
+        $error = 0;
 
         require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 
         dol_syslog(get_class()."::saveboxorder zone=".$zone." userid=".$userid);
 
-        if (! $userid || $userid == 0) return 0;
+        if (!$userid || $userid == 0) return 0;
 
         $user = new User($db);
-        $user->id=$userid;
+        $user->id = $userid;
 
         $db->begin();
 
         // Save parameters to say user has a dedicated setup
-        $tab=array();
-        $confuserzone='MAIN_BOXES_'.$zone;
-        $tab[$confuserzone]=1;
+        $tab = array();
+        $confuserzone = 'MAIN_BOXES_'.$zone;
+        $tab[$confuserzone] = 1;
         if (dol_set_user_param($db, $conf, $user, $tab) < 0)
         {
-            $error=$db->lasterror();
+            $error = $db->lasterror();
             $db->rollback();
             return -3;
         }
 
         // Delete all lines
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."boxes";
-        $sql.= " WHERE entity = ".$conf->entity;
-        $sql.= " AND fk_user = ".$userid;
-        $sql.= " AND position = ".$zone;
+        $sql .= " WHERE entity = ".$conf->entity;
+        $sql .= " AND fk_user = ".$userid;
+        $sql .= " AND position = ".$zone;
 
         dol_syslog(get_class()."::saveboxorder", LOG_DEBUG);
         $result = $db->query($sql);
         if ($result)
         {
-            $colonnes=explode('-', $boxorder);
+            $colonnes = explode('-', $boxorder);
             foreach ($colonnes as $collist)
             {
-                $part=explode(':', $collist);
-                $colonne=$part[0];
-                $list=$part[1];
+                $part = explode(':', $collist);
+                $colonne = $part[0];
+                $list = $part[1];
                 dol_syslog(get_class()."::saveboxorder column=".$colonne.' list='.$list);
 
-                $i=0;
-                $listarray=explode(',', $list);
+                $i = 0;
+                $listarray = explode(',', $list);
                 foreach ($listarray as $id)
                 {
                     if (is_numeric($id))
                     {
                         //dol_syslog("aaaaa".count($listarray));
                         $i++;
-                        $ii=sprintf('%02d', $i);
+                        $ii = sprintf('%02d', $i);
                         $sql = "INSERT INTO ".MAIN_DB_PREFIX."boxes";
-                        $sql.= "(box_id, position, box_order, fk_user, entity)";
-                        $sql.= " values (";
-                        $sql.= " ".$id.",";
-                        $sql.= " ".$zone.",";
-                        $sql.= " '".$colonne.$ii."',";
-                        $sql.= " ".$userid.",";
-                        $sql.= " ".$conf->entity;
-                        $sql.= ")";
+                        $sql .= "(box_id, position, box_order, fk_user, entity)";
+                        $sql .= " values (";
+                        $sql .= " ".$id.",";
+                        $sql .= " ".$zone.",";
+                        $sql .= " '".$colonne.$ii."',";
+                        $sql .= " ".$userid.",";
+                        $sql .= " ".$conf->entity;
+                        $sql .= ")";
 
                         dol_syslog(get_class()."::saveboxorder", LOG_DEBUG);
                         $result = $db->query($sql);
@@ -304,7 +304,7 @@ class InfoBox
             }
             if ($error)
             {
-                $error=$db->error();
+                $error = $db->error();
                 $db->rollback();
                 return -2;
             }
@@ -316,7 +316,7 @@ class InfoBox
         }
         else
         {
-            $error=$db->lasterror();
+            $error = $db->lasterror();
             $db->rollback();
             dol_syslog(get_class()."::saveboxorder ".$error);
             return -1;

File diff suppressed because it is too large
+ 246 - 246
htdocs/core/lib/company.lib.php


+ 9 - 9
htdocs/core/lib/cron.lib.php

@@ -87,17 +87,17 @@ function dol_print_cron_urls()
 	global $dolibarr_main_url_root;
 
 	// Define $urlwithroot
-	$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
-	$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+	$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
+	$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
 	//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
 
 	// Cron launch
 	print '<div class="div-table-responsive-no-min">';
 	print $langs->trans("URLToLaunchCronJobs").':<br>';
-	$url=$urlwithroot.'/public/cron/cron_run_jobs.php?'.(empty($conf->global->CRON_KEY)?'':'securitykey='.$conf->global->CRON_KEY.'&').'userlogin='.$user->login;
+	$url = $urlwithroot.'/public/cron/cron_run_jobs.php?'.(empty($conf->global->CRON_KEY) ? '' : 'securitykey='.$conf->global->CRON_KEY.'&').'userlogin='.$user->login;
 	print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
 	print ' '.$langs->trans("OrToLaunchASpecificJob").'<br>';
-	$url=$urlwithroot.'/public/cron/cron_run_jobs.php?'.(empty($conf->global->CRON_KEY)?'':'securitykey='.$conf->global->CRON_KEY.'&').'userlogin='.$user->login.'&id=cronjobid';
+	$url = $urlwithroot.'/public/cron/cron_run_jobs.php?'.(empty($conf->global->CRON_KEY) ? '' : 'securitykey='.$conf->global->CRON_KEY.'&').'userlogin='.$user->login.'&id=cronjobid';
 	print img_picto('', 'globe').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
     print '</div>';
     print '<br>';
@@ -107,22 +107,22 @@ function dol_print_cron_urls()
 
 	print '<u>'.$langs->trans("FileToLaunchCronJobs").':</u><br>';
 
-	$file='/scripts/cron/cron_run_jobs.php'.' '.(empty($conf->global->CRON_KEY)?'securitykey':''.$conf->global->CRON_KEY.'').' '.$logintouse.' [cronjobid]';
+	$file = '/scripts/cron/cron_run_jobs.php'.' '.(empty($conf->global->CRON_KEY) ? 'securitykey' : ''.$conf->global->CRON_KEY.'').' '.$logintouse.' [cronjobid]';
 	print '<textarea class="quatrevingtpercent">..'.$file."</textarea><br>\n";
 	print '<br>';
 
 	// Add note
 	if (empty($conf->global->CRON_DISABLE_TUTORIAL_CRON))
 	{
-    	$linuxlike=1;
-    	if (preg_match('/^win/i', PHP_OS)) $linuxlike=0;
-    	if (preg_match('/^mac/i', PHP_OS)) $linuxlike=0;
+    	$linuxlike = 1;
+    	if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0;
+    	if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0;
     	print $langs->trans("Note").': ';
     	if ($linuxlike)
     	{
     		print $langs->trans("CronExplainHowToRunUnix");
     		print '<br>';
-    		print '<textarea class="quatrevingtpercent">*/5 * * * * pathtoscript/scripts/cron/cron_run_jobs.php '.(empty($conf->global->CRON_KEY)?'securitykey':''.$conf->global->CRON_KEY.'').' '.$logintouse.' &gt; '.DOL_DATA_ROOT.'/cron_run_jobs.php.log</textarea><br>';
+    		print '<textarea class="quatrevingtpercent">*/5 * * * * pathtoscript/scripts/cron/cron_run_jobs.php '.(empty($conf->global->CRON_KEY) ? 'securitykey' : ''.$conf->global->CRON_KEY.'').' '.$logintouse.' &gt; '.DOL_DATA_ROOT.'/cron_run_jobs.php.log</textarea><br>';
     	}
     	else
     	{

+ 31 - 31
htdocs/core/lib/payments.lib.php

@@ -136,12 +136,12 @@ function showOnlinePaymentUrl($type, $ref)
 	// Load translation files required by the page
     $langs->loadLangs(array('payment', 'paybox'));
 
-	$servicename=$langs->transnoentitiesnoconv('Online');
+	$servicename = $langs->transnoentitiesnoconv('Online');
 
 	$out = img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePayment", $servicename).'<br>';
 	$url = getOnlinePaymentUrl(0, $type, $ref);
-	$out.= '<input type="text" id="onlinepaymenturl" class="quatrevingtpercent" value="'.$url.'">';
-	$out.= ajax_autoselect("onlinepaymenturl", 0);
+	$out .= '<input type="text" id="onlinepaymenturl" class="quatrevingtpercent" value="'.$url.'">';
+	$out .= ajax_autoselect("onlinepaymenturl", 0);
 	return $out;
 }
 
@@ -160,12 +160,12 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
 {
     global $conf, $dolibarr_main_url_root;
 
-	$ref=str_replace(' ', '', $ref);
-	$out='';
+	$ref = str_replace(' ', '', $ref);
+	$out = '';
 
 	// Define $urlwithroot
-	$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
-	$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
+	$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
+	$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
 	//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
 
 	$urltouse = DOL_MAIN_URL_ROOT;
@@ -295,51 +295,51 @@ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0,
     global $conf;
 
     // Juridical status
-    $line1="";
+    $line1 = "";
     if ($fromcompany->forme_juridique_code)
     {
-        $line1.=($line1?" - ":"").getFormeJuridiqueLabel($fromcompany->forme_juridique_code);
+        $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code);
     }
     // Capital
     if ($fromcompany->capital)
     {
-        $line1.=($line1?" - ":"").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency);
+        $line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency);
     }
     // Prof Id 1
-    if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || ! $fromcompany->idprof2))
+    if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2))
     {
-        $field=$langs->transcountrynoentities("ProfId1", $fromcompany->country_code);
-        if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1];
-        $line1.=($line1?" - ":"").$field.": ".$fromcompany->idprof1;
+        $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code);
+        if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+        $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1;
     }
     // Prof Id 2
     if ($fromcompany->idprof2)
     {
-        $field=$langs->transcountrynoentities("ProfId2", $fromcompany->country_code);
-        if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1];
-        $line1.=($line1?" - ":"").$field.": ".$fromcompany->idprof2;
+        $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code);
+        if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+        $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2;
     }
 
     // Second line of company infos
-    $line2="";
+    $line2 = "";
     // Prof Id 3
     if ($fromcompany->idprof3)
     {
-        $field=$langs->transcountrynoentities("ProfId3", $fromcompany->country_code);
-        if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1];
-        $line2.=($line2?" - ":"").$field.": ".$fromcompany->idprof3;
+        $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code);
+        if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+        $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3;
     }
     // Prof Id 4
     if ($fromcompany->idprof4)
     {
-        $field=$langs->transcountrynoentities("ProfId4", $fromcompany->country_code);
-        if (preg_match('/\((.*)\)/i', $field, $reg)) $field=$reg[1];
-        $line2.=($line2?" - ":"").$field.": ".$fromcompany->idprof4;
+        $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code);
+        if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+        $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4;
     }
     // IntraCommunautary VAT
     if ($fromcompany->tva_intra != '')
     {
-        $line2.=($line2?" - ":"").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra;
+        $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra;
     }
 
     print '<br>';
@@ -350,16 +350,16 @@ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0,
     	print '<!-- object = '.$object->element.' -->';
     	print '<br>';
 
-    	$parammessageform='ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix;
-    	if (! empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
-    	elseif (! empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM);
+    	$parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix;
+    	if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
+    	elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM);
 
     	// Add other message if VAT exists
     	if ($object->total_vat != 0 || $object->total_tva != 0)
     	{
-    		$parammessageform='ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix;
-    		if (! empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
-    		elseif (! empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT);
+    		$parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix;
+    		if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
+    		elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT);
     	}
     }
 

+ 36 - 36
htdocs/core/lib/product.lib.php

@@ -45,7 +45,7 @@ function product_prepare_head($object)
 	$head[$h][2] = 'card';
 	$h++;
 
-	if (! empty($object->status))
+	if (!empty($object->status))
 	{
     	$head[$h][0] = DOL_URL_ROOT."/product/price.php?id=".$object->id;
     	$head[$h][1] = $langs->trans("SellingPrices");
@@ -53,10 +53,10 @@ function product_prepare_head($object)
     	$h++;
 	}
 
-	if (! empty($object->status_buy) || (! empty($conf->margin->enabled) && ! empty($object->status)))   // If margin is on and product on sell, we may need the cost price even if product os not on purchase
+	if (!empty($object->status_buy) || (!empty($conf->margin->enabled) && !empty($object->status)))   // If margin is on and product on sell, we may need the cost price even if product os not on purchase
 	{
-    	if ((! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire)
-    	|| (! empty($conf->margin->enabled) && $user->rights->margin->liretous)
+    	if ((!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire)
+    	|| (!empty($conf->margin->enabled) && $user->rights->margin->liretous)
     	)
     	{
     		$head[$h][0] = DOL_URL_ROOT."/product/fournisseurs.php?id=".$object->id;
@@ -67,7 +67,7 @@ function product_prepare_head($object)
 	}
 
 	// Multilangs
-	if (! empty($conf->global->MAIN_MULTILANGS))
+	if (!empty($conf->global->MAIN_MULTILANGS))
 	{
 		$head[$h][0] = DOL_URL_ROOT."/product/traduction.php?id=".$object->id;
 		$head[$h][1] = $langs->trans("Translation");
@@ -130,16 +130,16 @@ function product_prepare_head($object)
     // Tab to link resources
     if (!empty($conf->resource->enabled))
     {
-        if ($object->isProduct() && ! empty($conf->global->RESOURCE_ON_PRODUCTS))
+        if ($object->isProduct() && !empty($conf->global->RESOURCE_ON_PRODUCTS))
         {
-            $head[$h][0] = DOL_URL_ROOT . '/resource/element_resource.php?element=product&ref=' . $object->ref;
+            $head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=product&ref='.$object->ref;
             $head[$h][1] = $langs->trans("Resources");
             $head[$h][2] = 'resources';
             $h++;
         }
-        if ($object->isService() && ! empty($conf->global->RESOURCE_ON_SERVICES))
+        if ($object->isService() && !empty($conf->global->RESOURCE_ON_SERVICES))
         {
-            $head[$h][0] = DOL_URL_ROOT . '/resource/element_resource.php?element=service&ref=' . $object->ref;
+            $head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=service&ref='.$object->ref;
             $head[$h][1] = $langs->trans("Resources");
             $head[$h][2] = 'resources';
             $h++;
@@ -188,10 +188,10 @@ function product_prepare_head($object)
     // Log
     $head[$h][0] = DOL_URL_ROOT.'/product/agenda.php?id='.$object->id;
     $head[$h][1] = $langs->trans("Events");
-    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)))
     {
-    	$head[$h][1].= '/';
-    	$head[$h][1].= $langs->trans("Agenda");
+    	$head[$h][1] .= '/';
+    	$head[$h][1] .= $langs->trans("Agenda");
     }
     $head[$h][2] = 'agenda';
     $h++;
@@ -210,7 +210,7 @@ function productlot_prepare_head($object)
     global $db, $langs, $conf, $user;
 
     // Load translation files required by the page
-    $langs->loadLangs(array("products","productbatch"));
+    $langs->loadLangs(array("products", "productbatch"));
 
     $h = 0;
     $head = array();
@@ -270,7 +270,7 @@ function product_admin_prepare_head()
 	$head[$h][2] = 'general';
 	$h++;
 
-	if (!empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL))
+	if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL))
 	{
 		$head[$h] = array(
 			0 => DOL_URL_ROOT."/product/admin/price_rules.php",
@@ -342,7 +342,7 @@ function product_lot_admin_prepare_head()
  */
 function show_stats_for_company($product, $socid)
 {
-	global $conf,$langs,$user,$db;
+	global $conf, $langs, $user, $db;
 
 	$nblines = 0;
 
@@ -354,10 +354,10 @@ function show_stats_for_company($product, $socid)
 	print '</tr>';
 
 	// Customer proposals
-	if (! empty($conf->propal->enabled) && $user->rights->propale->lire)
+	if (!empty($conf->propal->enabled) && $user->rights->propale->lire)
 	{
 		$nblines++;
-		$ret=$product->load_stats_propale($socid);
+		$ret = $product->load_stats_propale($socid);
 		if ($ret < 0) dol_print_error($db);
 		$langs->load("propal");
 		print '<tr><td>';
@@ -372,10 +372,10 @@ function show_stats_for_company($product, $socid)
 		print '</tr>';
 	}
 	// Supplier proposals
-	if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire)
+	if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire)
 	{
 		$nblines++;
-		$ret=$product->load_stats_proposal_supplier($socid);
+		$ret = $product->load_stats_proposal_supplier($socid);
 		if ($ret < 0) dol_print_error($db);
 		$langs->load("propal");
 		print '<tr><td>';
@@ -390,10 +390,10 @@ function show_stats_for_company($product, $socid)
 		print '</tr>';
 	}
 	// Customer orders
-	if (! empty($conf->commande->enabled) && $user->rights->commande->lire)
+	if (!empty($conf->commande->enabled) && $user->rights->commande->lire)
 	{
 		$nblines++;
-		$ret=$product->load_stats_commande($socid);
+		$ret = $product->load_stats_commande($socid);
 		if ($ret < 0) dol_print_error($db);
 		$langs->load("orders");
 		print '<tr><td>';
@@ -408,10 +408,10 @@ function show_stats_for_company($product, $socid)
 		print '</tr>';
 	}
 	// Supplier orders
-	if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande->lire)
+	if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande->lire)
 	{
 		$nblines++;
-		$ret=$product->load_stats_commande_fournisseur($socid);
+		$ret = $product->load_stats_commande_fournisseur($socid);
 		if ($ret < 0) dol_print_error($db);
 		$langs->load("orders");
 		print '<tr><td>';
@@ -426,10 +426,10 @@ function show_stats_for_company($product, $socid)
 		print '</tr>';
 	}
 	// Customer invoices
-	if (! empty($conf->facture->enabled) && $user->rights->facture->lire)
+	if (!empty($conf->facture->enabled) && $user->rights->facture->lire)
 	{
 		$nblines++;
-		$ret=$product->load_stats_facture($socid);
+		$ret = $product->load_stats_facture($socid);
 		if ($ret < 0) dol_print_error($db);
 		$langs->load("bills");
 		print '<tr><td>';
@@ -444,10 +444,10 @@ function show_stats_for_company($product, $socid)
 		print '</tr>';
 	}
 	// Supplier invoices
-	if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire)
+	if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire)
 	{
 		$nblines++;
-		$ret=$product->load_stats_facture_fournisseur($socid);
+		$ret = $product->load_stats_facture_fournisseur($socid);
 		if ($ret < 0) dol_print_error($db);
 		$langs->load("bills");
 		print '<tr><td>';
@@ -463,10 +463,10 @@ function show_stats_for_company($product, $socid)
 	}
 
 	// Contracts
-	if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire)
+	if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire)
 	{
 		$nblines++;
-		$ret=$product->load_stats_contrat($socid);
+		$ret = $product->load_stats_contrat($socid);
 		if ($ret < 0) dol_print_error($db);
 		$langs->load("contracts");
 		print '<tr><td>';
@@ -514,7 +514,7 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho
 {
 	global $langs, $db;
 	require_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php';
-	$measuringUnits= new CUnits($db);
+	$measuringUnits = new CUnits($db);
 
 	if ($scale !== '')
 	{
@@ -534,10 +534,10 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho
 	}
 	$result = $measuringUnits->fetchAll('', '', 0, 0, $arrayforfilter);
 
-	if ($result<0) {
+	if ($result < 0) {
 		return -1;
 	} else {
-		if (is_array($measuringUnits->records) && count($measuringUnits->records)>0) {
+		if (is_array($measuringUnits->records) && count($measuringUnits->records) > 0) {
 			if ($use_short_label) return $measuringUnits->records[key($measuringUnits->records)]->short_label;
 			else return $langs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label);
 		} else {
@@ -555,8 +555,8 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho
  */
 function measuring_units_squared($unit)
 {
-	$measuring_units=array();
-	$measuring_units[0] = 0;   // m -> m3
+	$measuring_units = array();
+	$measuring_units[0] = 0; // m -> m3
 	$measuring_units[-1] = -2; // dm-> dm2
 	$measuring_units[-2] = -4; // cm -> cm2
 	$measuring_units[-3] = -6; // mm -> mm2
@@ -575,8 +575,8 @@ function measuring_units_squared($unit)
  */
 function measuring_units_cubed($unit)
 {
-	$measuring_units=array();
-	$measuring_units[0] = 0;   // m -> m2
+	$measuring_units = array();
+	$measuring_units[0] = 0; // m -> m2
 	$measuring_units[-1] = -3; // dm-> dm3
 	$measuring_units[-2] = -6; // cm -> cm3
 	$measuring_units[-3] = -9; // mm -> mm3

+ 117 - 117
htdocs/core/lib/project.lib.php

@@ -259,13 +259,13 @@ function project_timesheet_prepare_head($mode, $fuser = null)
 
 	$h = 0;
 
-	$param='';
-	$param.=($mode?'&mode='.$mode:'');
-	if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) $param.='&search_usertoprocessid='.$fuser->id;
+	$param = '';
+	$param .= ($mode ? '&mode='.$mode : '');
+	if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) $param .= '&search_usertoprocessid='.$fuser->id;
 
 	if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK))
 	{
-		$head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($param?'?'.$param:'');
+		$head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($param ? '?'.$param : '');
 		$head[$h][1] = $langs->trans("InputPerWeek");
 		$head[$h][2] = 'inputperweek';
 		$h++;
@@ -273,7 +273,7 @@ function project_timesheet_prepare_head($mode, $fuser = null)
 
 	if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME))
 	{
-		$head[$h][0] = DOL_URL_ROOT."/projet/activity/perday.php".($param?'?'.$param:'');
+		$head[$h][0] = DOL_URL_ROOT."/projet/activity/perday.php".($param ? '?'.$param : '');
 		$head[$h][1] = $langs->trans("InputPerDay");
 		$head[$h][2] = 'inputperday';
 		$h++;
@@ -353,10 +353,10 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 	global $user, $bc, $langs, $conf, $db;
 	global $projectstatic, $taskstatic;
 
-	$lastprojectid=0;
+	$lastprojectid = 0;
 
-	$projectsArrayId=explode(',', $projectsListId);
-	if ($filterprogresscalc!=='') {
+	$projectsArrayId = explode(',', $projectsListId);
+	if ($filterprogresscalc !== '') {
 		foreach ($lines as $key=>$line) {
 			if (!empty($line->planned_workload) && !empty($line->duration)) {
 				$filterprogresscalc = str_replace(' = ', ' == ', $filterprogresscalc);
@@ -365,27 +365,27 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 				}
 			}
 		}
-		$lines=array_values($lines);
+		$lines = array_values($lines);
 	}
 
-	$numlines=count($lines);
+	$numlines = count($lines);
 
 	// We declare counter as global because we want to edit them into recursive call
 	global $total_projectlinesa_spent, $total_projectlinesa_planned, $total_projectlinesa_spent_if_planned, $total_projectlinesa_declared_if_planned, $total_projectlinesa_tobill, $total_projectlinesa_billed;
 
 	if ($level == 0)
 	{
-		$total_projectlinesa_spent=0;
-		$total_projectlinesa_planned=0;
-		$total_projectlinesa_spent_if_planned=0;
-        $total_projectlinesa_declared_if_planned=0;
-		$total_projectlinesa_tobill=0;
-		$total_projectlinesa_billed=0;
+		$total_projectlinesa_spent = 0;
+		$total_projectlinesa_planned = 0;
+		$total_projectlinesa_spent_if_planned = 0;
+        $total_projectlinesa_declared_if_planned = 0;
+		$total_projectlinesa_tobill = 0;
+		$total_projectlinesa_billed = 0;
 	}
 
-	for ($i = 0 ; $i < $numlines ; $i++)
+	for ($i = 0; $i < $numlines; $i++)
 	{
-		if ($parent == 0 && $level >= 0) $level = 0;              // if $level = -1, we dont' use sublevel recursion, we show all lines
+		if ($parent == 0 && $level >= 0) $level = 0; // if $level = -1, we dont' use sublevel recursion, we show all lines
 
 		// Process line
 		// print "i:".$i."-".$lines[$i]->fk_project.'<br>';
@@ -393,26 +393,26 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 		if ($lines[$i]->fk_parent == $parent || $level < 0)       // if $level = -1, we dont' use sublevel recursion, we show all lines
 		{
 			// Show task line.
-			$showline=1;
-			$showlineingray=0;
+			$showline = 1;
+			$showlineingray = 0;
 
 			// If there is filters to use
 			if (is_array($taskrole))
 			{
 				// If task not legitimate to show, search if a legitimate task exists later in tree
-				if (! isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent)
+				if (!isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent)
 				{
 					// So search if task has a subtask legitimate to show
-					$foundtaskforuserdeeper=0;
+					$foundtaskforuserdeeper = 0;
 					searchTaskInChild($foundtaskforuserdeeper, $lines[$i]->id, $lines, $taskrole);
 					//print '$foundtaskforuserpeeper='.$foundtaskforuserdeeper.'<br>';
 					if ($foundtaskforuserdeeper > 0)
 					{
-						$showlineingray=1;		// We will show line but in gray
+						$showlineingray = 1; // We will show line but in gray
 					}
 					else
 					{
-						$showline=0;			// No reason to show line
+						$showline = 0; // No reason to show line
 					}
 				}
 			}
@@ -423,12 +423,12 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 				if (empty($user->rights->projet->all->lire))
 				{
 					// User is not allowed on this project and project is not public, so we hide line
-					if (! in_array($lines[$i]->fk_project, $projectsArrayId))
+					if (!in_array($lines[$i]->fk_project, $projectsArrayId))
 					{
 						// Note that having a user assigned to a task into a project user has no permission on, should not be possible
 						// because assignement on task can be done only on contact of project.
 						// If assignement was done and after, was removed from contact of project, then we can hide the line.
-						$showline=0;
+						$showline = 0;
 					}
 				}
 			}
@@ -439,26 +439,26 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 				if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid)
 				{
 					$var = !$var;
-					$lastprojectid=$lines[$i]->fk_project;
+					$lastprojectid = $lines[$i]->fk_project;
 				}
 
 				print '<tr '.$bc[$var].' id="row-'.$lines[$i]->id.'">'."\n";
 
-				$projectstatic->id=$lines[$i]->fk_project;
-				$projectstatic->ref=$lines[$i]->projectref;
-				$projectstatic->public=$lines[$i]->public;
-				$projectstatic->title=$lines[$i]->projectlabel;
-				$projectstatic->usage_bill_time=$lines[$i]->usage_bill_time;
+				$projectstatic->id = $lines[$i]->fk_project;
+				$projectstatic->ref = $lines[$i]->projectref;
+				$projectstatic->public = $lines[$i]->public;
+				$projectstatic->title = $lines[$i]->projectlabel;
+				$projectstatic->usage_bill_time = $lines[$i]->usage_bill_time;
 
-				$taskstatic->id=$lines[$i]->id;
-				$taskstatic->ref=$lines[$i]->ref;
-				$taskstatic->label=($taskrole[$lines[$i]->id]?$langs->trans("YourRole").': '.$taskrole[$lines[$i]->id]:'');
+				$taskstatic->id = $lines[$i]->id;
+				$taskstatic->ref = $lines[$i]->ref;
+				$taskstatic->label = ($taskrole[$lines[$i]->id] ? $langs->trans("YourRole").': '.$taskrole[$lines[$i]->id] : '');
 				$taskstatic->projectstatus = $lines[$i]->projectstatus;
 				$taskstatic->progress = $lines[$i]->progress;
 				$taskstatic->fk_statut = $lines[$i]->status;
 				$taskstatic->datee = $lines[$i]->date_end;
-                $taskstatic->planned_workload= $lines[$i]->planned_workload;
-                $taskstatic->duration_effective= $lines[$i]->duration;
+                $taskstatic->planned_workload = $lines[$i]->planned_workload;
+                $taskstatic->duration_effective = $lines[$i]->duration;
 
 
 				if ($showproject)
@@ -466,14 +466,14 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 					// Project ref
 					print "<td>";
 					//if ($showlineingray) print '<i>';
-					if ($lines[$i]->public || in_array($lines[$i]->fk_project, $projectsArrayId) || ! empty($user->rights->projet->all->lire)) print $projectstatic->getNomUrl(1);
+					if ($lines[$i]->public || in_array($lines[$i]->fk_project, $projectsArrayId) || !empty($user->rights->projet->all->lire)) print $projectstatic->getNomUrl(1);
 					else print $projectstatic->getNomUrl(1, 'nolink');
 					//if ($showlineingray) print '</i>';
 					print "</td>";
 
 					// Project status
 					print '<td>';
-					$projectstatic->statut=$lines[$i]->projectstatus;
+					$projectstatic->statut = $lines[$i]->projectstatus;
 					print $projectstatic->getLibStatut(2);
 					print "</td>";
 				}
@@ -494,12 +494,12 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 				print "<td>";
 				if ($showlineingray) print '<i>';
 				//else print '<a href="'.DOL_URL_ROOT.'/projet/tasks/task.php?id='.$lines[$i]->id.'&withproject=1">';
-				for ($k = 0 ; $k < $level ; $k++)
+				for ($k = 0; $k < $level; $k++)
 				{
 					print '<div class="marginleftonly">';
 				}
 				print $lines[$i]->label;
-				for ($k = 0 ; $k < $level ; $k++)
+				for ($k = 0; $k < $level; $k++)
 				{
 					print '</div>';
 				}
@@ -518,15 +518,15 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 				if ($taskstatic->hasDelay()) print img_warning($langs->trans("Late"));
 				print '</td>';
 
-				$plannedworkloadoutputformat='allhourmin';
-				$timespentoutputformat='allhourmin';
-				if (! empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat=$conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT;
-				if (! empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat=$conf->global->PROJECT_TIME_SPENT_FORMAT;
+				$plannedworkloadoutputformat = 'allhourmin';
+				$timespentoutputformat = 'allhourmin';
+				if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT;
+				if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT;
 
 				// Planned Workload (in working hours)
 				print '<td class="right">';
-				$fullhour=convertSecondToTime($lines[$i]->planned_workload, $plannedworkloadoutputformat);
-				$workingdelay=convertSecondToTime($lines[$i]->planned_workload, 'all', 86400, 7);	// TODO Replace 86400 and 7 to take account working hours per day and working day per weeks
+				$fullhour = convertSecondToTime($lines[$i]->planned_workload, $plannedworkloadoutputformat);
+				$workingdelay = convertSecondToTime($lines[$i]->planned_workload, 'all', 86400, 7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks
 				if ($lines[$i]->planned_workload != '')
 				{
 					print $fullhour;
@@ -539,7 +539,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 				// Time spent
 				print '<td class="right">';
 				if ($showlineingray) print '<i>';
-				else print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$lines[$i]->id.($showproject?'':'&withproject=1').'">';
+				else print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?id='.$lines[$i]->id.($showproject ? '' : '&withproject=1').'">';
 				if ($lines[$i]->duration) print convertSecondToTime($lines[$i]->duration, $timespentoutputformat);
 				else print '--:--';
 				if ($showlineingray) print '</i>';
@@ -600,20 +600,20 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 				}
 
 				// Contacts of task
-				if (! empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST))
+				if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST))
 				{
 					print '<td>';
-					foreach(array('internal','external') as $source)
+					foreach (array('internal', 'external') as $source)
 					{
 						$tab = $lines[$i]->liste_contact(-1, $source);
-						$num=count($tab);
-						if (!empty($num)){
-							foreach ($tab as $contacttask){
+						$num = count($tab);
+						if (!empty($num)) {
+							foreach ($tab as $contacttask) {
 								//var_dump($contacttask);
 								if ($source == 'internal') $c = new User($db);
 								else $c = new Contact($db);
 								$c->fetch($contacttask['id']);
-								print $c->getNomUrl(1) . ' (' . $contacttask['libelle'] . ')' . '<br>';
+								print $c->getNomUrl(1).' ('.$contacttask['libelle'].')'.'<br>';
 							}
 						}
 					}
@@ -628,7 +628,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 
 				print "</tr>\n";
 
-				if (! $showlineingray) $inc++;
+				if (!$showlineingray) $inc++;
 
 				if ($level >= 0)    // Call sublevels
 				{
@@ -662,7 +662,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 		print convertSecondToTime($total_projectlinesa_planned, 'allhourmin');
 		print '</td>';
 		print '<td class="nowrap liste_total right">';
-		if ($projectidfortotallink > 0) print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?projectid='.$projectidfortotallink.($showproject?'':'&withproject=1').'">';
+		if ($projectidfortotallink > 0) print '<a href="'.DOL_URL_ROOT.'/projet/tasks/time.php?projectid='.$projectidfortotallink.($showproject ? '' : '&withproject=1').'">';
 		print convertSecondToTime($total_projectlinesa_spent, 'allhourmin');
 		if ($projectidfortotallink > 0) print '</a>';
 		print '</td>';
@@ -680,13 +680,13 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
 
             if ($totalCalculatedProgress > $totalAverageDeclaredProgress) {
                 $progressBarClass = 'progress-bar-danger';
-                $badgeClass.= 'badge-danger';
+                $badgeClass .= 'badge-danger';
             } elseif ($totalCalculatedProgress * $warningRatio >= $totalAverageDeclaredProgress) { // warning if close at 1%
                 $progressBarClass = 'progress-bar-warning';
-                $badgeClass.= 'badge-warning';
+                $badgeClass .= 'badge-warning';
             } else {
                 $progressBarClass = 'progress-bar-success';
-                $badgeClass.= 'badge-success';
+                $badgeClass .= 'badge-success';
             }
         }
 
@@ -719,7 +719,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t
     		print '</td>';
 		}
 		// Contacts of task
-		if (! empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST))
+		if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST))
 		{
 			print '<td></td>';
 		}
@@ -1169,11 +1169,11 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
 				// Ref
 				print '<td>';
 				print '<!-- Task id = '.$lines[$i]->id.' -->';
-				for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
+				for ($k = 0; $k < $level; $k++) print "&nbsp;&nbsp;&nbsp;";
 				print $taskstatic->getNomUrl(1, 'withproject', 'time');
 				// Label task
 				print '<br>';
-				for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
+				for ($k = 0; $k < $level; $k++) print "&nbsp;&nbsp;&nbsp;";
 				print $taskstatic->label;
 				//print "<br>";
 				//for ($k = 0 ; $k < $level ; $k++) print "&nbsp;&nbsp;&nbsp;";
@@ -1221,20 +1221,20 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr
 				else print '--:--';
 				print "</td>\n";
 
-				$disabledproject=1;$disabledtask=1;
+				$disabledproject = 1; $disabledtask = 1;
 				//print "x".$lines[$i]->fk_project;
 				//var_dump($lines[$i]);
 				//var_dump($projectsrole[$lines[$i]->fk_project]);
 				// If at least one role for project
-				if ($lines[$i]->public || ! empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
+				if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
 				{
-					$disabledproject=0;
-					$disabledtask=0;
+					$disabledproject = 0;
+					$disabledtask = 0;
 				}
 				// If $restricteditformytask is on and I have no role on task, i disable edit
 				if ($restricteditformytask && empty($tasksrole[$lines[$i]->id]))
 				{
-					$disabledtask=1;
+					$disabledtask = 1;
 				}
 
 				// Form to add new time
@@ -1392,7 +1392,7 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$
             $obj = &$lines[$i]; // To display extrafields
 
 			// If we want all or we have a role on task, we show it
-			if (empty($mine) || ! empty($tasksrole[$lines[$i]->id]))
+			if (empty($mine) || !empty($tasksrole[$lines[$i]->id]))
 			{
 				//dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project);
 
@@ -1530,7 +1530,7 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$
 				*/
 
 				// Project
-				if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
+				if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
 				{
     				print '<td class="nowrap">';
     				if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]);
@@ -1538,7 +1538,7 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$
 				}
 
 				// Thirdparty
-				if (! empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
+				if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT))
 				{
 				    print '<td class="tdoverflowmax100">';
 				    if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project');
@@ -1596,25 +1596,25 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$
 
 				// Time spent by user
 				print '<td class="right">';
-				$tmptimespent=$taskstatic->getSummaryOfTimeSpent($fuser->id);
+				$tmptimespent = $taskstatic->getSummaryOfTimeSpent($fuser->id);
 				if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin');
 				else print '--:--';
 				print "</td>\n";
 
-				$disabledproject=1;$disabledtask=1;
+				$disabledproject = 1; $disabledtask = 1;
 				//print "x".$lines[$i]->fk_project;
 				//var_dump($lines[$i]);
 				//var_dump($projectsrole[$lines[$i]->fk_project]);
 				// If at least one role for project
-				if ($lines[$i]->public || ! empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
+				if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer)
 				{
-					$disabledproject=0;
-					$disabledtask=0;
+					$disabledproject = 0;
+					$disabledtask = 0;
 				}
 				// If $restricteditformytask is on and I have no role on task, i disable edit
 				if ($restricteditformytask && empty($tasksrole[$lines[$i]->id]))
 				{
-					$disabledtask=1;
+					$disabledtask = 1;
 				}
 
 				//var_dump($projectstatic->weekWorkLoadPerTask);
@@ -1686,9 +1686,9 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$
 				$ret = projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable, $oldprojectforbreak, $arrayfields, $extrafields);
 				//var_dump('ret with parent='.$lines[$i]->id.' level='.$level);
 				//var_dump($ret);
-				foreach($ret as $key => $val)
+				foreach ($ret as $key => $val)
 				{
-					$totalforeachday[$key]+=$val;
+					$totalforeachday[$key] += $val;
 				}
 				//var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks');
 				//var_dump($totalforeachday);
@@ -1717,8 +1717,8 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$
 function searchTaskInChild(&$inc, $parent, &$lines, &$taskrole)
 {
 	//print 'Search in line with parent id = '.$parent.'<br>';
-	$numlines=count($lines);
-	for ($i = 0 ; $i < $numlines ; $i++)
+	$numlines = count($lines);
+	for ($i = 0; $i < $numlines; $i++)
 	{
 		// Process line $lines[$i]
 		if ($lines[$i]->fk_parent == $parent && $lines[$i]->id != $lines[$i]->fk_parent)
@@ -1811,40 +1811,40 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks
 			{
 				$project_year_filter = date("Y");
 			}
-			$sql.= " AND (p.dateo IS NULL OR p.dateo <= ".$db->idate(dol_get_last_day($project_year_filter, 12, false)).")";
-			$sql.= " AND (p.datee IS NULL OR p.datee >= ".$db->idate(dol_get_first_day($project_year_filter, 1, false)).")";
+			$sql .= " AND (p.dateo IS NULL OR p.dateo <= ".$db->idate(dol_get_last_day($project_year_filter, 12, false)).")";
+			$sql .= " AND (p.datee IS NULL OR p.datee >= ".$db->idate(dol_get_first_day($project_year_filter, 1, false)).")";
 		}
 	}
 
 	// Get id of project we must show tasks
-	$arrayidofprojects=array();
+	$arrayidofprojects = array();
 	$sql1 = "SELECT p.rowid as projectid";
-	$sql1.= $sql;
+	$sql1 .= $sql;
 	$resql = $db->query($sql1);
 	if ($resql)
 	{
-		$i=0;
+		$i = 0;
 		$num = $db->num_rows($resql);
 		while ($i < $num)
 		{
 			$objp = $db->fetch_object($resql);
-			$arrayidofprojects[$objp->projectid]=$objp->projectid;
+			$arrayidofprojects[$objp->projectid] = $objp->projectid;
 			$i++;
 		}
 	}
 	else dol_print_error($db);
-	if (empty($arrayidofprojects)) $arrayidofprojects[0]=-1;
+	if (empty($arrayidofprojects)) $arrayidofprojects[0] = -1;
 
 	// Get list of project with calculation on tasks
 	$sql2 = "SELECT p.rowid as projectid, p.ref, p.title, p.fk_soc, s.nom as socname, p.fk_user_creat, p.public, p.fk_statut as status, p.fk_opp_status as opp_status, p.opp_amount,";
-	$sql2.= " p.dateo, p.datee,";
-	$sql2.= " COUNT(t.rowid) as nb, SUM(t.planned_workload) as planned_workload, SUM(t.planned_workload * t.progress / 100) as declared_progess_workload";
-	$sql2.= " FROM ".MAIN_DB_PREFIX."projet as p";
-	$sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc";
-	$sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t ON p.rowid = t.fk_projet";
-	$sql2.= " WHERE p.rowid IN (".join(',', $arrayidofprojects).")";
-	$sql2.= " GROUP BY p.rowid, p.ref, p.title, p.fk_soc, s.nom, p.fk_user_creat, p.public, p.fk_statut, p.fk_opp_status, p.opp_amount, p.dateo, p.datee";
-	$sql2.= " ORDER BY p.title, p.ref";
+	$sql2 .= " p.dateo, p.datee,";
+	$sql2 .= " COUNT(t.rowid) as nb, SUM(t.planned_workload) as planned_workload, SUM(t.planned_workload * t.progress / 100) as declared_progess_workload";
+	$sql2 .= " FROM ".MAIN_DB_PREFIX."projet as p";
+	$sql2 .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc";
+	$sql2 .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task as t ON p.rowid = t.fk_projet";
+	$sql2 .= " WHERE p.rowid IN (".join(',', $arrayidofprojects).")";
+	$sql2 .= " GROUP BY p.rowid, p.ref, p.title, p.fk_soc, s.nom, p.fk_user_creat, p.public, p.fk_statut, p.fk_opp_status, p.opp_amount, p.dateo, p.datee";
+	$sql2 .= " ORDER BY p.title, p.ref";
 
 	$resql = $db->query($sql2);
 	if ($resql)
@@ -1859,7 +1859,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks
 		print '<tr class="liste_titre">';
 		print_liste_field_titre($title.'<span class="badge marginleftonlyshort">'.$num.'</span>', $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder);
 		print_liste_field_titre("ThirdParty", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder);
-		if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
+		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 		{
 			print_liste_field_titre("OpportunityAmount", "", "", "", "", 'align="right"', $sortfield, $sortorder);
 			print_liste_field_titre("OpportunityStatus", "", "", "", "", 'align="right"', $sortfield, $sortorder);
@@ -1867,14 +1867,14 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks
 		if (empty($conf->global->PROJECT_HIDE_TASKS))
 		{
 			print_liste_field_titre("Tasks", "", "", "", "", 'align="right"', $sortfield, $sortorder);
-			if (! in_array('plannedworkload', $hiddenfields))  print_liste_field_titre("PlannedWorkload", "", "", "", "", 'align="right"', $sortfield, $sortorder);
-			if (! in_array('declaredprogress', $hiddenfields)) print_liste_field_titre("ProgressDeclared", "", "", "", "", 'align="right"', $sortfield, $sortorder);
+			if (!in_array('plannedworkload', $hiddenfields))  print_liste_field_titre("PlannedWorkload", "", "", "", "", 'align="right"', $sortfield, $sortorder);
+			if (!in_array('declaredprogress', $hiddenfields)) print_liste_field_titre("ProgressDeclared", "", "", "", "", 'align="right"', $sortfield, $sortorder);
 		}
 		print_liste_field_titre("Status", "", "", "", "", 'align="right"', $sortfield, $sortorder);
 		print "</tr>\n";
 
-		$total_plannedworkload=0;
-		$total_declaredprogressworkload=0;
+		$total_plannedworkload = 0;
+		$total_declaredprogressworkload = 0;
 		while ($i < $num)
 		{
 			$objp = $db->fetch_object($resql);
@@ -1887,7 +1887,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks
 			$userAccess = $projectstatic->restrictedProjectArea($user);
 			if ($userAccess >= 0)
 			{
-				$projectstatic->ref=$objp->ref;
+				$projectstatic->ref = $objp->ref;
 				$projectstatic->statut = $objp->status;
 				$projectstatic->title = $objp->title;
 				$projectstatic->datee = $db->jdate($objp->datee);
@@ -1897,18 +1897,18 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks
 				print '<tr class="oddeven">';
 				print '<td>';
 				print $projectstatic->getNomUrl(1);
-				if (! in_array('projectlabel', $hiddenfields)) print '<br>'.dol_trunc($objp->title, 24);
+				if (!in_array('projectlabel', $hiddenfields)) print '<br>'.dol_trunc($objp->title, 24);
 				print '</td>';
 				print '<td>';
 				if ($objp->fk_soc > 0)
 				{
-					$thirdpartystatic->id=$objp->fk_soc;
-					$thirdpartystatic->ref=$objp->socname;
-					$thirdpartystatic->name=$objp->socname;
+					$thirdpartystatic->id = $objp->fk_soc;
+					$thirdpartystatic->ref = $objp->socname;
+					$thirdpartystatic->name = $objp->socname;
 					print $thirdpartystatic->getNomUrl(1);
 				}
 				print '</td>';
-				if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
+				if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 				{
 					print '<td class="right">';
 					if ($objp->opp_amount) print price($objp->opp_amount, 0, '', 1, -1, -1, $conf->currency);
@@ -1922,19 +1922,19 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks
 				{
 					print '<td class="right">'.$objp->nb.'</td>';
 
-					$plannedworkload=$objp->planned_workload;
-					$total_plannedworkload+=$plannedworkload;
-					if (! in_array('plannedworkload', $hiddenfields))
+					$plannedworkload = $objp->planned_workload;
+					$total_plannedworkload += $plannedworkload;
+					if (!in_array('plannedworkload', $hiddenfields))
 					{
-						print '<td class="right">'.($plannedworkload?convertSecondToTime($plannedworkload):'').'</td>';
+						print '<td class="right">'.($plannedworkload ?convertSecondToTime($plannedworkload) : '').'</td>';
 					}
-					if (! in_array('declaredprogress', $hiddenfields))
+					if (!in_array('declaredprogress', $hiddenfields))
 					{
-						$declaredprogressworkload=$objp->declared_progess_workload;
-						$total_declaredprogressworkload+=$declaredprogressworkload;
+						$declaredprogressworkload = $objp->declared_progess_workload;
+						$total_declaredprogressworkload += $declaredprogressworkload;
 						print '<td class="right">';
 						//print $objp->planned_workload.'-'.$objp->declared_progess_workload."<br>";
-						print ($plannedworkload?round(100*$declaredprogressworkload/$plannedworkload, 0).'%':'');
+						print ($plannedworkload ?round(100 * $declaredprogressworkload / $plannedworkload, 0).'%' : '');
 						print '</td>';
 					}
 				}
@@ -1952,7 +1952,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks
 
 		print '<tr class="liste_total">';
 		print '<td colspan="2">'.$langs->trans("Total")."</td>";
-		if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES))
+		if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
 		{
 			print '<td class="liste_total right">'.price($total_opp_amount, 0, '', 1, -1, -1, $conf->currency).'</td>';
 			print '<td class="liste_total right">'.$form->textwithpicto(price($ponderated_opp_amount, 0, '', 1, -1, -1, $conf->currency), $langs->trans("OpportunityPonderatedAmountDesc"), 1).'</td>';
@@ -1960,8 +1960,8 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks
 		if (empty($conf->global->PROJECT_HIDE_TASKS))
 		{
 			print '<td class="liste_total right">'.$total_task.'</td>';
-			if (! in_array('plannedworkload', $hiddenfields))  print '<td class="liste_total right">'.($total_plannedworkload?convertSecondToTime($total_plannedworkload):'').'</td>';
-			if (! in_array('declaredprogress', $hiddenfields)) print '<td class="liste_total right">'.($total_plannedworkload?round(100*$total_declaredprogressworkload/$total_plannedworkload, 0).'%':'').'</td>';
+			if (!in_array('plannedworkload', $hiddenfields))  print '<td class="liste_total right">'.($total_plannedworkload ?convertSecondToTime($total_plannedworkload) : '').'</td>';
+			if (!in_array('declaredprogress', $hiddenfields)) print '<td class="liste_total right">'.($total_plannedworkload ?round(100 * $total_declaredprogressworkload / $total_plannedworkload, 0).'%' : '').'</td>';
 		}
 		print '<td class="liste_total"></td>';
 		print '</tr>';

+ 16 - 16
htdocs/core/lib/signature.lib.php

@@ -29,14 +29,14 @@ function showOnlineSignatureUrl($type, $ref)
 	global $conf, $langs;
 
 	// Load translation files required by the page
-    $langs->loadLangs(array("payment","paybox"));
+    $langs->loadLangs(array("payment", "paybox"));
 
-	$servicename='Online';
+	$servicename = 'Online';
 
 	$out = img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlineSignature", $servicename).'<br>';
 	$url = getOnlineSignatureUrl(0, $type, $ref);
-	$out.= '<input type="text" id="onlinesignatureurl" class="quatrevingtpercent" value="'.$url.'">';
-	$out.= ajax_autoselect("onlinesignatureurl", 0);
+	$out .= '<input type="text" id="onlinesignatureurl" class="quatrevingtpercent" value="'.$url.'">';
+	$out .= ajax_autoselect("onlinesignatureurl", 0);
 	return $out;
 }
 
@@ -53,29 +53,29 @@ function getOnlineSignatureUrl($mode, $type, $ref = '')
 {
 	global $conf, $db, $langs;
 
-	$ref=str_replace(' ', '', $ref);
-	$out='';
+	$ref = str_replace(' ', '', $ref);
+	$out = '';
 
 	if ($type == 'proposal')
 	{
-		$out=DOL_MAIN_URL_ROOT.'/public/onlinesign/newonlinesign.php?source=proposal&ref='.($mode?'<font color="#666666">':'');
-		if ($mode == 1) $out.='proposal_ref';
-		if ($mode == 0) $out.=urlencode($ref);
-		$out.=($mode?'</font>':'');
-		if ($mode == 1) $out.='&hashp=<font color="#666666">hash_of_file</font>';
+		$out = DOL_MAIN_URL_ROOT.'/public/onlinesign/newonlinesign.php?source=proposal&ref='.($mode ? '<font color="#666666">' : '');
+		if ($mode == 1) $out .= 'proposal_ref';
+		if ($mode == 0) $out .= urlencode($ref);
+		$out .= ($mode ? '</font>' : '');
+		if ($mode == 1) $out .= '&hashp=<font color="#666666">hash_of_file</font>';
 		else
 		{
 			include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
-			$propaltmp=new Propal($db);
+			$propaltmp = new Propal($db);
 			$res = $propaltmp->fetch(0, $ref);
 			if ($res <= 0) return 'FailedToGetProposal';
 
 			include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
-			$ecmfile=new EcmFiles($db);
+			$ecmfile = new EcmFiles($db);
 
 			$ecmfile->fetch(0, '', $propaltmp->last_main_doc);
 
-			$hashp=$ecmfile->share;
+			$hashp = $ecmfile->share;
 			if (empty($hashp))
 			{
 				$out = $langs->trans("FeatureOnlineSignDisabled");
@@ -83,13 +83,13 @@ function getOnlineSignatureUrl($mode, $type, $ref = '')
 			}
 			else
 			{
-				$out.='&hashp='.$hashp;
+				$out .= '&hashp='.$hashp;
 			}
 		}
 	}
 
 	// For multicompany
-	if (! empty($out)) $out.="&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities
+	if (!empty($out)) $out .= "&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities
 
 	return $out;
 }

+ 188 - 188
htdocs/core/lib/ticket.lib.php

@@ -77,7 +77,7 @@ function ticket_prepare_head($object)
 
     $h = 0;
     $head = array();
-    $head[$h][0] = DOL_URL_ROOT.'/ticket/card.php?action=view&track_id=' . $object->track_id;
+    $head[$h][0] = DOL_URL_ROOT.'/ticket/card.php?action=view&track_id='.$object->track_id;
     $head[$h][1] = $langs->trans("Card");
     $head[$h][2] = 'tabTicket';
     $h++;
@@ -110,25 +110,25 @@ function ticket_prepare_head($object)
 
     // History
 	$ticketViewType = "messaging";
-	if(empty($_SESSION['ticket-view-type'])){
+	if (empty($_SESSION['ticket-view-type'])) {
 		$_SESSION['ticket-view-type'] = $ticketViewType;
 	}
-	else{
+	else {
 		$ticketViewType = $_SESSION['ticket-view-type'];
 	}
 
-	if($ticketViewType == "messaging"){
-		$head[$h][0] = DOL_URL_ROOT.'/ticket/messaging.php?track_id=' . $object->track_id;
+	if ($ticketViewType == "messaging") {
+		$head[$h][0] = DOL_URL_ROOT.'/ticket/messaging.php?track_id='.$object->track_id;
 	}
-	else{
+	else {
 		// $ticketViewType == "list"
-		$head[$h][0] = DOL_URL_ROOT.'/ticket/agenda.php?track_id=' . $object->track_id;
+		$head[$h][0] = DOL_URL_ROOT.'/ticket/agenda.php?track_id='.$object->track_id;
 	}
     $head[$h][1] = $langs->trans('Events');
-    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)))
     {
-    	$head[$h][1].= '/';
-    	$head[$h][1].= $langs->trans("Agenda");
+    	$head[$h][1] .= '/';
+    	$head[$h][1] .= $langs->trans("Agenda");
     }
     $head[$h][2] = 'tabTicketLogs';
     $h++;
@@ -158,22 +158,22 @@ function showDirectPublicLink($object)
 		$url = dol_buildpath('/public/ticket/view.php', 3).'?track_id='.$object->track_id.'&email='.$email;
 	}
 
-	$out='';
+	$out = '';
 	if (empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE))
 	{
-		$out.= '<span class="opacitymedium">'.$langs->trans("PublicInterfaceNotEnabled").'</span>';
+		$out .= '<span class="opacitymedium">'.$langs->trans("PublicInterfaceNotEnabled").'</span>';
 	}
 	else
 	{
-		$out.= img_picto('', 'object_globe.png').' '.$langs->trans("TicketPublicAccess").':<br>';
+		$out .= img_picto('', 'object_globe.png').' '.$langs->trans("TicketPublicAccess").':<br>';
 		if ($url)
 		{
-			$out.= '<input type="text" id="directpubliclink" class="quatrevingtpercent" value="'.$url.'">';
-			$out.= ajax_autoselect("directpubliclink", 0);
+			$out .= '<input type="text" id="directpubliclink" class="quatrevingtpercent" value="'.$url.'">';
+			$out .= ajax_autoselect("directpubliclink", 0);
 		}
 		else
 		{
-			$out.= '<span class="opacitymedium">'.$langs->trans("TicketNotCreatedFromPublicInterface").'</span>';
+			$out .= '<span class="opacitymedium">'.$langs->trans("TicketNotCreatedFromPublicInterface").'</span>';
 		}
 	}
 
@@ -272,12 +272,12 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
     dol_include_once('/comm/action/class/actioncomm.class.php');
 
     // Check parameters
-    if (! is_object($filterobj) && ! is_object($objcon)) dol_print_error('', 'BadParameter');
+    if (!is_object($filterobj) && !is_object($objcon)) dol_print_error('', 'BadParameter');
 
-    $out='';
-    $histo=array();
-    $numaction = 0 ;
-    $now=dol_now('tzuser');
+    $out = '';
+    $histo = array();
+    $numaction = 0;
+    $now = dol_now('tzuser');
 
     // Open DSI -- Fix order by -- Begin
     $sortfield_list = explode(',', $sortfield);
@@ -288,7 +288,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
     }
     $sortfield_new = implode(',', $sortfield_new_list);
 
-    if (! empty($conf->agenda->enabled))
+    if (!empty($conf->agenda->enabled))
     {
         // Recherche histo sur actioncomm
         if (is_object($objcon) && $objcon->id > 0) {
@@ -298,142 +298,142 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
         {
             $sql = "SELECT a.id, a.label as label,";
         }
-        $sql.= " a.datep as dp,";
-        $sql.= " a.note as message,";
-        $sql.= " a.datep2 as dp2,";
-        $sql.= " a.percent as percent, 'action' as type,";
-        $sql.= " a.fk_element, a.elementtype,";
-        $sql.= " a.fk_contact,";
-        $sql.= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
-        $sql.= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname";
-        if (is_object($filterobj) && get_class($filterobj) == 'Societe')      $sql.= ", sp.lastname, sp.firstname";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql.= ", m.lastname, m.firstname";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur')  $sql.= ", o.ref";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Product')  $sql.= ", o.ref";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket')   $sql.= ", o.ref";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'BOM')      $sql.= ", o.ref";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat')  $sql.= ", o.ref";
-        $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
+        $sql .= " a.datep as dp,";
+        $sql .= " a.note as message,";
+        $sql .= " a.datep2 as dp2,";
+        $sql .= " a.percent as percent, 'action' as type,";
+        $sql .= " a.fk_element, a.elementtype,";
+        $sql .= " a.fk_contact,";
+        $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
+        $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname";
+        if (is_object($filterobj) && get_class($filterobj) == 'Societe')      $sql .= ", sp.lastname, sp.firstname";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", m.lastname, m.firstname";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur')  $sql .= ", o.ref";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Product')  $sql .= ", o.ref";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket')   $sql .= ", o.ref";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'BOM')      $sql .= ", o.ref";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat')  $sql .= ", o.ref";
+        $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
 
         $force_filter_contact = false;
         if (is_object($objcon) && $objcon->id > 0) {
             $force_filter_contact = true;
-            $sql.= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
-            $sql.= " AND r.element_type = '" . $db->escape($objcon->table_element) . "' AND r.fk_element = " . $objcon->id;
+            $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
+            $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".$objcon->id;
         }
 
-        if (is_object($filterobj) && get_class($filterobj) == 'Societe')  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
+        if (is_object($filterobj) && get_class($filterobj) == 'Societe')  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
         elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
-            $sql.= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
-            $sql.= " ON er.resource_type = 'dolresource'";
-            $sql.= " AND er.element_id = a.id";
-            $sql.= " AND er.resource_id = ".$filterobj->id;
+            $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
+            $sql .= " ON er.resource_type = 'dolresource'";
+            $sql .= " AND er.element_id = a.id";
+            $sql .= " AND er.resource_id = ".$filterobj->id;
         }
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql.= ", ".MAIN_DB_PREFIX."adherent as m";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql.= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql.= ", ".MAIN_DB_PREFIX."product as o";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql.= ", ".MAIN_DB_PREFIX."ticket as o";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql.= ", ".MAIN_DB_PREFIX."bom_bom as o";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql.= ", ".MAIN_DB_PREFIX."contrat as o";
-
-        $sql.= " WHERE a.entity IN (".getEntity('agenda').")";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql .= ", ".MAIN_DB_PREFIX."adherent as m";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Product') $sql .= ", ".MAIN_DB_PREFIX."product as o";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') $sql .= ", ".MAIN_DB_PREFIX."ticket as o";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') $sql .= ", ".MAIN_DB_PREFIX."contrat as o";
+
+        $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
         if ($force_filter_contact === false) {
-            if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) $sql.= " AND a.fk_soc = ".$filterobj->id;
-            elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) $sql.= " AND a.fk_project = ".$filterobj->id;
+            if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) $sql .= " AND a.fk_soc = ".$filterobj->id;
+            elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) $sql .= " AND a.fk_project = ".$filterobj->id;
             elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent')
             {
-                $sql.= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
-                if ($filterobj->id) $sql.= " AND a.fk_element = ".$filterobj->id;
+                $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
+                if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id;
             }
             elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur')
             {
-                $sql.= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
-                if ($filterobj->id) $sql.= " AND a.fk_element = ".$filterobj->id;
+                $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
+                if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id;
             }
             elseif (is_object($filterobj) && get_class($filterobj) == 'Product')
             {
-                $sql.= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
-                if ($filterobj->id) $sql.= " AND a.fk_element = ".$filterobj->id;
+                $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
+                if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id;
             }
             elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket')
             {
-                $sql.= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
-                if ($filterobj->id) $sql.= " AND a.fk_element = ".$filterobj->id;
+                $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
+                if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id;
             }
             elseif (is_object($filterobj) && get_class($filterobj) == 'BOM')
             {
-                $sql.= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
-                if ($filterobj->id) $sql.= " AND a.fk_element = ".$filterobj->id;
+                $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
+                if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id;
             }
             elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat')
             {
-                $sql.= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
-                if ($filterobj->id) $sql.= " AND a.fk_element = ".$filterobj->id;
+                $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
+                if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id;
             }
         }
 
         // Condition on actioncode
-        if (! empty($actioncode))
+        if (!empty($actioncode))
         {
             if (empty($conf->global->AGENDA_USE_EVENT_TYPE))
             {
-                if ($actioncode == 'AC_NON_AUTO') $sql.= " AND c.type != 'systemauto'";
-                elseif ($actioncode == 'AC_ALL_AUTO') $sql.= " AND c.type = 'systemauto'";
+                if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'";
+                elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'";
                 else
                 {
-                    if ($actioncode == 'AC_OTH') $sql.= " AND c.type != 'systemauto'";
-                    elseif ($actioncode == 'AC_OTH_AUTO') $sql.= " AND c.type = 'systemauto'";
+                    if ($actioncode == 'AC_OTH') $sql .= " AND c.type != 'systemauto'";
+                    elseif ($actioncode == 'AC_OTH_AUTO') $sql .= " AND c.type = 'systemauto'";
                 }
             }
             else
             {
-                if ($actioncode == 'AC_NON_AUTO') $sql.= " AND c.type != 'systemauto'";
-                elseif ($actioncode == 'AC_ALL_AUTO') $sql.= " AND c.type = 'systemauto'";
-                else $sql.= " AND c.code = '".$db->escape($actioncode)."'";
+                if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'";
+                elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'";
+                else $sql .= " AND c.code = '".$db->escape($actioncode)."'";
             }
         }
-        if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
-        elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
-        if (is_array($filters) && $filters['search_agenda_label']) $sql.= natural_search('a.label', $filters['search_agenda_label']);
+        if ($donetodo == 'todo') $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
+        elseif ($donetodo == 'done') $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
+        if (is_array($filters) && $filters['search_agenda_label']) $sql .= natural_search('a.label', $filters['search_agenda_label']);
     }
 
     // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
-    if (! empty($conf->mailing->enabled) && ! empty($objcon->email)
+    if (!empty($conf->mailing->enabled) && !empty($objcon->email)
         && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING'))
     {
         $langs->load("mails");
 
         $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type";
-        $sql2.= ", '' as fk_element, '' as elementtype, '' as contact_id";
-        $sql2.= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
-        $sql2.= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action
-        if (is_object($filterobj) && get_class($filterobj) == 'Societe')      $sql2.= ", '' as lastname, '' as firstname";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql2.= ", '' as lastname, '' as firstname";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur')  $sql2.= ", '' as ref";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Product')  $sql2.= ", '' as ref";
-        elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket')   $sql2.= ", '' as ref";
-        $sql2.= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
-        $sql2.= " WHERE mc.email = '".$db->escape($objcon->email)."'";	// Search is done on email.
-        $sql2.= " AND mc.statut = 1";
-        $sql2.= " AND u.rowid = m.fk_user_valid";
-        $sql2.= " AND mc.fk_mailing=m.rowid";
+        $sql2 .= ", '' as fk_element, '' as elementtype, '' as contact_id";
+        $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
+        $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action
+        if (is_object($filterobj) && get_class($filterobj) == 'Societe')      $sql2 .= ", '' as lastname, '' as firstname";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') $sql2 .= ", '' as lastname, '' as firstname";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur')  $sql2 .= ", '' as ref";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Product')  $sql2 .= ", '' as ref";
+        elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket')   $sql2 .= ", '' as ref";
+        $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
+        $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email.
+        $sql2 .= " AND mc.statut = 1";
+        $sql2 .= " AND u.rowid = m.fk_user_valid";
+        $sql2 .= " AND mc.fk_mailing=m.rowid";
     }
 
     if (!empty($sql) && !empty($sql2)) {
-        $sql = $sql . " UNION " . $sql2;
+        $sql = $sql." UNION ".$sql2;
     } elseif (empty($sql) && !empty($sql2)) {
         $sql = $sql2;
     }
 
     //TODO Add limit in nb of results
-    $sql.= $db->order($sortfield_new, $sortorder);
+    $sql .= $db->order($sortfield_new, $sortorder);
     dol_syslog("company.lib::show_actions_done", LOG_DEBUG);
-    $resql=$db->query($sql);
+    $resql = $db->query($sql);
     if ($resql)
     {
-        $i = 0 ;
+        $i = 0;
         $num = $db->num_rows($resql);
 
         while ($i < $num)
@@ -442,19 +442,19 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
 
             if ($obj->type == 'action') {
                 $contactaction = new ActionComm($db);
-                $contactaction->id=$obj->id;
+                $contactaction->id = $obj->id;
                 $result = $contactaction->fetchResources();
-                if ($result<0) {
+                if ($result < 0) {
                     dol_print_error($db);
                     setEventMessage("company.lib::show_actions_done Error fetch ressource", 'errors');
                 }
 
                 //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
                 //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
-                $tododone='';
-                if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone='todo';
+                $tododone = '';
+                if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone = 'todo';
 
-                $histo[$numaction]=array(
+                $histo[$numaction] = array(
                     'type'=>$obj->type,
                     'tododone'=>$tododone,
                     'id'=>$obj->id,
@@ -479,11 +479,11 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
                     // Type of event
                     'acode'=>$obj->acode,
                     'alabel'=>$obj->alabel,
-                    'libelle'=>$obj->alabel,    // deprecated
+                    'libelle'=>$obj->alabel, // deprecated
                     'apicto'=>$obj->apicto
                 );
             } else {
-                $histo[$numaction]=array(
+                $histo[$numaction] = array(
                     'type'=>$obj->type,
                     'tododone'=>'done',
                     'id'=>$obj->id,
@@ -511,85 +511,85 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
         dol_print_error($db);
     }
 
-    if (! empty($conf->agenda->enabled) || (! empty($conf->mailing->enabled) && ! empty($objcon->email)))
+    if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email)))
     {
-        $delay_warning=$conf->global->MAIN_DELAY_ACTIONS_TODO*24*60*60;
+        $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60;
 
         require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
         include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
         require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
         require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
 
-        $formactions=new FormActions($db);
+        $formactions = new FormActions($db);
 
-        $actionstatic=new ActionComm($db);
-        $userstatic=new User($db);
+        $actionstatic = new ActionComm($db);
+        $userstatic = new User($db);
         $contactstatic = new Contact($db);
         $userGetNomUrlCache = array();
 
-		$out.='<div class="filters-container" >';
-		$out.='<form name="listactionsfilter" class="listactionsfilter" action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
+		$out .= '<div class="filters-container" >';
+		$out .= '<form name="listactionsfilter" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
 		if ($objcon && get_class($objcon) == 'Contact' &&
 			(is_null($filterobj) || get_class($filterobj) == 'Societe'))
 		{
-			$out.='<input type="hidden" name="id" value="'.$objcon->id.'" />';
+			$out .= '<input type="hidden" name="id" value="'.$objcon->id.'" />';
 		}
 		else
 		{
-			$out.='<input type="hidden" name="id" value="'.$filterobj->id.'" />';
+			$out .= '<input type="hidden" name="id" value="'.$filterobj->id.'" />';
 		}
-		if ($filterobj && get_class($filterobj) == 'Societe') $out.='<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
+		if ($filterobj && get_class($filterobj) == 'Societe') $out .= '<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
 
-		$out.="\n";
+		$out .= "\n";
 
-		$out.='<div class="div-table-responsive-no-min">';
-		$out.='<table class="noborder borderbottom centpercent">';
+		$out .= '<div class="div-table-responsive-no-min">';
+		$out .= '<table class="noborder borderbottom centpercent">';
 
-		$out.='<tr class="liste_titre">';
+		$out .= '<tr class="liste_titre">';
 
 		//$out.='<td class="liste_titre">';
 		$out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, '')."\n";
 		//$out.='</td>';
 
-		$out.='<th class="liste_titre"><strong>'.$langs->trans("Search").' : </strong></th>';
+		$out .= '<th class="liste_titre"><strong>'.$langs->trans("Search").' : </strong></th>';
 		if ($donetodo)
 		{
-			$out.='<th class="liste_titre"></th>';
+			$out .= '<th class="liste_titre"></th>';
 		}
-		$out.='<th class="liste_titre">'.$langs->trans("Type").' ';
-		$out.=$formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:-1, 0, 0, 1);
-		$out.='</th>';
-		$out.='<th class="liste_titre maxwidth100onsmartphone">';
-		$out.=$langs->trans("Label").' ';
-		$out.='<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'">';
-		$out.='</th>';
+		$out .= '<th class="liste_titre">'.$langs->trans("Type").' ';
+		$out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1);
+		$out .= '</th>';
+		$out .= '<th class="liste_titre maxwidth100onsmartphone">';
+		$out .= $langs->trans("Label").' ';
+		$out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'">';
+		$out .= '</th>';
 
-		$out.='<th class="liste_titre width50 middle">';
-		$searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1);
-		$out.=$searchpicto;
-		$out.='</th>';
-		$out.='</tr>';
+		$out .= '<th class="liste_titre width50 middle">';
+		$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
+		$out .= $searchpicto;
+		$out .= '</th>';
+		$out .= '</tr>';
 
 
-		$out.='</table>';
+		$out .= '</table>';
 
-        $out.='</form>';
-		$out.='</div>';
+        $out .= '</form>';
+		$out .= '</div>';
 
-        $out.="\n";
+        $out .= "\n";
 
-        $out.='<ul class="timeline">';
+        $out .= '<ul class="timeline">';
 
         if ($donetodo)
         {
-            $tmp='';
-            if (get_class($filterobj) == 'Societe') $tmp.='<a href="'.DOL_URL_ROOT.'/comm/action/list.php?socid='.$filterobj->id.'&amp;status=done">';
-            $tmp.=($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
-            $tmp.=($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
-            $tmp.=($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
+            $tmp = '';
+            if (get_class($filterobj) == 'Societe') $tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?socid='.$filterobj->id.'&amp;status=done">';
+            $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
+            $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
+            $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
             //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
-            if (get_class($filterobj) == 'Societe') $tmp.='</a>';
-            $out.=getTitleFieldOfList($tmp);
+            if (get_class($filterobj) == 'Societe') $tmp .= '</a>';
+            $out .= getTitleFieldOfList($tmp);
         }
 
 
@@ -601,69 +601,69 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
 
         foreach ($histo as $key=>$value)
         {
-            $actionstatic->fetch($histo[$key]['id']);    // TODO Do we need this, we already have a lot of data of line into $histo
+            $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
 
-            $actionstatic->type_picto=$histo[$key]['apicto'];
-            $actionstatic->type_code=$histo[$key]['acode'];
+            $actionstatic->type_picto = $histo[$key]['apicto'];
+            $actionstatic->type_code = $histo[$key]['acode'];
 
             $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$histo[$key]['id'];
 
-            $tmpa=dol_getdate($histo[$key]['datestart'], false);
-            if($actualCycleDate !== $tmpa['year'].'-'.$tmpa['yday']){
+            $tmpa = dol_getdate($histo[$key]['datestart'], false);
+            if ($actualCycleDate !== $tmpa['year'].'-'.$tmpa['yday']) {
                 $actualCycleDate = $tmpa['year'].'-'.$tmpa['yday'];
-                $out.='<!-- timeline time label -->';
-                $out.='<li class="time-label">';
-                $out.='<span class="timeline-badge-date">';
-                $out.= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzserver', $langs);
-                $out.='</span>';
-                $out.='</li>';
-                $out.='<!-- /.timeline-label -->';
+                $out .= '<!-- timeline time label -->';
+                $out .= '<li class="time-label">';
+                $out .= '<span class="timeline-badge-date">';
+                $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzserver', $langs);
+                $out .= '</span>';
+                $out .= '</li>';
+                $out .= '<!-- /.timeline-label -->';
             }
 
 
-            $out.='<!-- timeline item -->'."\n";
-            $out.='<li class="timeline-code-'.strtolower($actionstatic->code).'">';
+            $out .= '<!-- timeline item -->'."\n";
+            $out .= '<li class="timeline-code-'.strtolower($actionstatic->code).'">';
 
 
-            $out.='<!-- timeline icon -->'."\n";
+            $out .= '<!-- timeline icon -->'."\n";
             $iconClass = 'fa fa-comments';
             $img_picto = '';
             $colorClass = '';
             $pictoTitle = '';
 
-            if ($histo[$key]['percent']==-1) {
+            if ($histo[$key]['percent'] == -1) {
                 $colorClass = 'timeline-icon-not-applicble';
                 $pictoTitle = $langs->trans('StatusNotApplicable');
             }
-            elseif ($histo[$key]['percent']==0) {
+            elseif ($histo[$key]['percent'] == 0) {
                 $colorClass = 'timeline-icon-todo';
-                $pictoTitle = $langs->trans('StatusActionToDo') . ' (0%)';
+                $pictoTitle = $langs->trans('StatusActionToDo').' (0%)';
             }
-            elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100){
+            elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
                 $colorClass = 'timeline-icon-in-progress';
                 $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)';
             }
-            elseif ($histo[$key]['percent'] >= 100){
+            elseif ($histo[$key]['percent'] >= 100) {
                 $colorClass = 'timeline-icon-done';
-                $pictoTitle =  $langs->trans('StatusActionDone').' (100%)';
+                $pictoTitle = $langs->trans('StatusActionDone').' (100%)';
             }
 
 
-            if($actionstatic->code == 'AC_TICKET_CREATE'){
+            if ($actionstatic->code == 'AC_TICKET_CREATE') {
                 $iconClass = 'fa fa-ticket';
             }
-            elseif($actionstatic->code == 'AC_TICKET_MODIFY'){
+            elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
                 $iconClass = 'fa fa-pencil';
             }
-            elseif($actionstatic->code == 'TICKET_MSG'){
+            elseif ($actionstatic->code == 'TICKET_MSG') {
                 $iconClass = 'fa fa-comments';
             }
-            elseif($actionstatic->code == 'TICKET_MSG_PRIVATE'){
+            elseif ($actionstatic->code == 'TICKET_MSG_PRIVATE') {
                 $iconClass = 'fa fa-mask';
             }
             elseif (!empty($conf->global->AGENDA_USE_EVENT_TYPE))
             {
-                if ($actionstatic->type_picto) $img_picto =  img_picto('', $actionstatic->type_picto);
+                if ($actionstatic->type_picto) $img_picto = img_picto('', $actionstatic->type_picto);
                 else {
                     if ($actionstatic->type_code == 'AC_RDV')       $iconClass = 'fa fa-handshake';
                     elseif ($actionstatic->type_code == 'AC_TEL')   $iconClass = 'fa fa-phone';
@@ -671,24 +671,24 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
                     elseif ($actionstatic->type_code == 'AC_EMAIL') $iconClass = 'fa fa-envelope';
                     elseif ($actionstatic->type_code == 'AC_INT')   $iconClass = 'fa fa-shipping-fast';
                     elseif ($actionstatic->type_code == 'AC_OTH_AUTO')   $iconClass = 'fa fa-robot';
-                    elseif (! preg_match('/_AUTO/', $actionstatic->type_code)) $iconClass = 'fa fa-robot';
+                    elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) $iconClass = 'fa fa-robot';
                 }
             }
 
 
 
-            $out.='<i class="'.$iconClass .' '.$colorClass.'" title="'.$pictoTitle .'">'.$img_picto.'</i>'."\n";
+            $out .= '<i class="'.$iconClass.' '.$colorClass.'" title="'.$pictoTitle.'">'.$img_picto.'</i>'."\n";
 
-            $out.='<div class="timeline-item">'."\n";
+            $out .= '<div class="timeline-item">'."\n";
 
-            $out.='<span class="timeline-header-action">';
+            $out .= '<span class="timeline-header-action">';
 
-			if (isset($histo[$key]['type']) && $histo[$key]['type']=='mailing') {
-				$out.='<a class="timeline-btn" href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
-				$out.=$histo[$key]['id'];
-				$out.='</a> ';
+			if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
+				$out .= '<a class="timeline-btn" href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
+				$out .= $histo[$key]['id'];
+				$out .= '</a> ';
 			} else {
-				$out.=$actionstatic->getNomUrl(1, -1).' ';
+				$out .= $actionstatic->getNomUrl(1, -1).' ';
 			}
 
             //if ($user->rights->agenda->allactions->read || $actionstatic->authorid == $user->id)
@@ -765,16 +765,16 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
 
             $out .= '</span>';
 
-            $out.='</h3>';
+            $out .= '</h3>';
 
-            if (! empty($histo[$key]['message'])
+            if (!empty($histo[$key]['message'])
                 && $actionstatic->code != 'AC_TICKET_CREATE'
                 && $actionstatic->code != 'AC_TICKET_MODIFY'
             )
             {
-                $out.='<div class="timeline-body">';
-                $out.=$histo[$key]['message'];
-                $out.='</div>';
+                $out .= '<div class="timeline-body">';
+                $out .= $histo[$key]['message'];
+                $out .= '</div>';
             }
 
 
@@ -792,11 +792,11 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no
                         dol_print_error($db, $contact->error);
 
                     if ($result > 0) {
-                        $contactList.= !empty($contactList)?', ':'';
+                        $contactList .= !empty($contactList) ? ', ' : '';
                         $contactList .= $contact->getNomUrl(1);
                         if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
-                            if (! empty($contact->phone_pro))
-                                $contactList .= '(' . dol_print_phone($contact->phone_pro) . ')';
+                            if (!empty($contact->phone_pro))
+                                $contactList .= '('.dol_print_phone($contact->phone_pro).')';
                         }
                     }
                 }

+ 189 - 189
htdocs/core/modules/import/import_csv.modules.php

@@ -25,7 +25,7 @@
  *		\brief      File to load import files with CSV format
  */
 
-require_once DOL_DOCUMENT_ROOT .'/core/modules/import/modules_import.php';
+require_once DOL_DOCUMENT_ROOT.'/core/modules/import/modules_import.php';
 
 
 /**
@@ -43,7 +43,7 @@ class ImportCsv extends ModeleImports
 	/**
 	 * @var string Error code (or message)
 	 */
-	public $error='';
+	public $error = '';
 
 	/**
 	 * @var string[] Error codes (or messages)
@@ -60,7 +60,7 @@ class ImportCsv extends ModeleImports
      */
     public $label;
 
-	public $extension;    // Extension of files imported by driver
+	public $extension; // Extension of files imported by driver
 
 	/**
      * Dolibarr version of driver
@@ -68,19 +68,19 @@ class ImportCsv extends ModeleImports
      */
 	public $version = 'dolibarr';
 
-	public $label_lib;    // Label of external lib used by driver
+	public $label_lib; // Label of external lib used by driver
 
-	public $version_lib;  // Version of external lib used by driver
+	public $version_lib; // Version of external lib used by driver
 
 	public $separator;
 
-	public $file;      // Path of file
+	public $file; // Path of file
 
-	public $handle;    // Handle fichier
+	public $handle; // Handle fichier
 
-	public $cacheconvert=array();      // Array to cache list of value found after a convertion
+	public $cacheconvert = array(); // Array to cache list of value found after a convertion
 
-	public $cachefieldtable=array();   // Array to cache list of value found into fields@tables
+	public $cachefieldtable = array(); // Array to cache list of value found into fields@tables
 
 	public $nbinsert = 0; // # of insert done during the import
 
@@ -98,23 +98,23 @@ class ImportCsv extends ModeleImports
 		global $conf, $langs;
 		$this->db = $db;
 
-		$this->separator=(GETPOST('separator')?GETPOST('separator'):(empty($conf->global->IMPORT_CSV_SEPARATOR_TO_USE)?',':$conf->global->IMPORT_CSV_SEPARATOR_TO_USE));
-		$this->enclosure='"';
-		$this->escape='"';
+		$this->separator = (GETPOST('separator') ?GETPOST('separator') : (empty($conf->global->IMPORT_CSV_SEPARATOR_TO_USE) ? ',' : $conf->global->IMPORT_CSV_SEPARATOR_TO_USE));
+		$this->enclosure = '"';
+		$this->escape = '"';
 
-		$this->id='csv';                // Same value then xxx in file name export_xxx.modules.php
-		$this->label='Csv';             // Label of driver
-		$this->desc=$langs->trans("CSVFormatDesc", $this->separator, $this->enclosure, $this->escape);
-		$this->extension='csv';         // Extension for generated file by this driver
-		$this->picto='mime/other';		// Picto
-		$this->version='1.34';         // Driver version
+		$this->id = 'csv'; // Same value then xxx in file name export_xxx.modules.php
+		$this->label = 'Csv'; // Label of driver
+		$this->desc = $langs->trans("CSVFormatDesc", $this->separator, $this->enclosure, $this->escape);
+		$this->extension = 'csv'; // Extension for generated file by this driver
+		$this->picto = 'mime/other'; // Picto
+		$this->version = '1.34'; // Driver version
 
 		// If driver use an external library, put its name here
-		$this->label_lib='Dolibarr';
-		$this->version_lib=DOL_VERSION;
+		$this->label_lib = 'Dolibarr';
+		$this->version_lib = DOL_VERSION;
 
-		$this->datatoimport=$datatoimport;
-		if (preg_match('/^societe_/', $datatoimport)) $this->thirpartyobject=new Societe($this->db);
+		$this->datatoimport = $datatoimport;
+		if (preg_match('/^societe_/', $datatoimport)) $this->thirpartyobject = new Societe($this->db);
 	}
 
 
@@ -142,7 +142,7 @@ class ImportCsv extends ModeleImports
     public function write_title_example($outputlangs, $headerlinefields)
 	{
         // phpcs:enable
-		$s=join($this->separator, array_map('cleansep', $headerlinefields));
+		$s = join($this->separator, array_map('cleansep', $headerlinefields));
 		return $s."\n";
 	}
 
@@ -157,7 +157,7 @@ class ImportCsv extends ModeleImports
     public function write_record_example($outputlangs, $contentlinevalues)
 	{
         // phpcs:enable
-		$s=join($this->separator, array_map('cleansep', $contentlinevalues));
+		$s = join($this->separator, array_map('cleansep', $contentlinevalues));
 		return $s."\n";
 	}
 
@@ -187,22 +187,22 @@ class ImportCsv extends ModeleImports
 	{
         // phpcs:enable
 		global $langs;
-		$ret=1;
+		$ret = 1;
 
 		dol_syslog(get_class($this)."::open_file file=".$file);
 
-		ini_set('auto_detect_line_endings', 1);	// For MAC compatibility
+		ini_set('auto_detect_line_endings', 1); // For MAC compatibility
 
 		$this->handle = fopen(dol_osencode($file), "r");
-		if (! $this->handle)
+		if (!$this->handle)
 		{
 			$langs->load("errors");
-			$this->error=$langs->trans("ErrorFailToOpenFile", $file);
-			$ret=-1;
+			$this->error = $langs->trans("ErrorFailToOpenFile", $file);
+			$ret = -1;
 		}
 		else
 		{
-			$this->file=$file;
+			$this->file = $file;
 		}
 
 		return $ret;
@@ -247,47 +247,47 @@ class ImportCsv extends ModeleImports
         // phpcs:enable
 		global $conf;
 
-		$arrayres=fgetcsv($this->handle, 100000, $this->separator, $this->enclosure, $this->escape);
+		$arrayres = fgetcsv($this->handle, 100000, $this->separator, $this->enclosure, $this->escape);
 
 		// End of file
 		if ($arrayres === false) return false;
 
 		//var_dump($this->handle);
 		//var_dump($arrayres);exit;
-		$newarrayres=array();
+		$newarrayres = array();
 		if ($arrayres && is_array($arrayres))
 		{
-			foreach($arrayres as $key => $val)
+			foreach ($arrayres as $key => $val)
 			{
-				if (! empty($conf->global->IMPORT_CSV_FORCE_CHARSET))	// Forced charset
+				if (!empty($conf->global->IMPORT_CSV_FORCE_CHARSET))	// Forced charset
 				{
 					if (strtolower($conf->global->IMPORT_CSV_FORCE_CHARSET) == 'utf8')
 					{
-						$newarrayres[$key]['val']=$val;
-						$newarrayres[$key]['type']=(dol_strlen($val)?1:-1);	// If empty we considere it's null
+						$newarrayres[$key]['val'] = $val;
+						$newarrayres[$key]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we considere it's null
 					}
 					else
 					{
-						$newarrayres[$key]['val']=utf8_encode($val);
-						$newarrayres[$key]['type']=(dol_strlen($val)?1:-1);	// If empty we considere it's null
+						$newarrayres[$key]['val'] = utf8_encode($val);
+						$newarrayres[$key]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we considere it's null
 					}
 				}
 				else	// Autodetect format (UTF8 or ISO)
 				{
 					if (utf8_check($val))
 					{
-						$newarrayres[$key]['val']=$val;
-						$newarrayres[$key]['type']=(dol_strlen($val)?1:-1);	// If empty we considere it's null
+						$newarrayres[$key]['val'] = $val;
+						$newarrayres[$key]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we considere it's null
 					}
 					else
 					{
-						$newarrayres[$key]['val']=utf8_encode($val);
-						$newarrayres[$key]['type']=(dol_strlen($val)?1:-1);	// If empty we considere it's null
+						$newarrayres[$key]['val'] = utf8_encode($val);
+						$newarrayres[$key]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we considere it's null
 					}
 				}
 			}
 
-			$this->col=count($newarrayres);
+			$this->col = count($newarrayres);
 		}
 
 		return $newarrayres;
@@ -322,21 +322,21 @@ class ImportCsv extends ModeleImports
     public function import_insert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys)
 	{
         // phpcs:enable
-		global $langs,$conf,$user;
-        global $thirdparty_static;    	// Specific to thirdparty import
-		global $tablewithentity_cache;	// Cache to avoid to call  desc at each rows on tables
+		global $langs, $conf, $user;
+        global $thirdparty_static; // Specific to thirdparty import
+		global $tablewithentity_cache; // Cache to avoid to call  desc at each rows on tables
 
-		$error=0;
-		$warning=0;
-		$this->errors=array();
-		$this->warnings=array();
+		$error = 0;
+		$warning = 0;
+		$this->errors = array();
+		$this->warnings = array();
 
 		//dol_syslog("import_csv.modules maxfields=".$maxfields." importid=".$importid);
 
 		//var_dump($array_match_file_to_database);
 		//var_dump($arrayrecord);
-		$array_match_database_to_file=array_flip($array_match_file_to_database);
-		$sort_array_match_file_to_database=$array_match_file_to_database;
+		$array_match_database_to_file = array_flip($array_match_file_to_database);
+		$sort_array_match_file_to_database = $array_match_file_to_database;
 		ksort($sort_array_match_file_to_database);
 
 		//var_dump($sort_array_match_file_to_database);
@@ -344,8 +344,8 @@ class ImportCsv extends ModeleImports
 		if (count($arrayrecord) == 0 || (count($arrayrecord) == 1 && empty($arrayrecord[0]['val'])))
 		{
 			//print 'W';
-			$this->warnings[$warning]['lib']=$langs->trans('EmptyLine');
-			$this->warnings[$warning]['type']='EMPTY';
+			$this->warnings[$warning]['lib'] = $langs->trans('EmptyLine');
+			$this->warnings[$warning]['type'] = 'EMPTY';
 			$warning++;
 		}
 		else
@@ -354,25 +354,25 @@ class ImportCsv extends ModeleImports
 			$updatedone = false;
 			$insertdone = false;
 			// For each table to insert, me make a separate insert
-			foreach($objimport->array_import_tables[0] as $alias => $tablename)
+			foreach ($objimport->array_import_tables[0] as $alias => $tablename)
 			{
 				// Build sql request
-				$sql='';
-				$listfields=array();
-				$listvalues=array();
-				$i=0;
-				$errorforthistable=0;
+				$sql = '';
+				$listfields = array();
+				$listvalues = array();
+				$i = 0;
+				$errorforthistable = 0;
 
 				// Define $tablewithentity_cache[$tablename] if not already defined
-				if (! isset($tablewithentity_cache[$tablename]))	// keep this test with "isset"
+				if (!isset($tablewithentity_cache[$tablename]))	// keep this test with "isset"
 				{
 					dol_syslog("Check if table ".$tablename." has an entity field");
-					$resql=$this->db->DDLDescTable($tablename, 'entity');
+					$resql = $this->db->DDLDescTable($tablename, 'entity');
 					if ($resql)
 					{
-						$obj=$this->db->fetch_object($resql);
-						if ($obj) $tablewithentity_cache[$tablename]=1;		// table contains entity field
-						else $tablewithentity_cache[$tablename]=0;			// table does not contains entity field
+						$obj = $this->db->fetch_object($resql);
+						if ($obj) $tablewithentity_cache[$tablename] = 1; // table contains entity field
+						else $tablewithentity_cache[$tablename] = 0; // table does not contains entity field
 					}
 					else dol_print_error($this->db);
 				}
@@ -388,26 +388,26 @@ class ImportCsv extends ModeleImports
                 }
 
 				// Loop on each fields in the match array: $key = 1..n, $val=alias of field (s.nom)
-				foreach($sort_array_match_file_to_database as $key => $val)
+				foreach ($sort_array_match_file_to_database as $key => $val)
 				{
-				    $fieldalias=preg_replace('/\..*$/i', '', $val);
-				    $fieldname=preg_replace('/^.*\./i', '', $val);
+				    $fieldalias = preg_replace('/\..*$/i', '', $val);
+				    $fieldname = preg_replace('/^.*\./i', '', $val);
 
-				    if ($alias != $fieldalias) continue;    // Not a field of current table
+				    if ($alias != $fieldalias) continue; // Not a field of current table
 
 					if ($key <= $maxfields)
 					{
 						// Set $newval with value to insert and set $listvalues with sql request part for insert
-						$newval='';
-						if ($arrayrecord[($key-1)]['type'] > 0) $newval=$arrayrecord[($key-1)]['val'];    // If type of field into input file is not empty string (so defined into input file), we get value
+						$newval = '';
+						if ($arrayrecord[($key - 1)]['type'] > 0) $newval = $arrayrecord[($key - 1)]['val']; // If type of field into input file is not empty string (so defined into input file), we get value
 
 						// Make some tests on $newval
 
 						// Is it a required field ?
-						if (preg_match('/\*/', $objimport->array_import_fields[0][$val]) && ((string) $newval==''))
+						if (preg_match('/\*/', $objimport->array_import_fields[0][$val]) && ((string) $newval == ''))
 						{
-							$this->errors[$error]['lib']=$langs->trans('ErrorMissingMandatoryValue', $key);
-							$this->errors[$error]['type']='NOTNULL';
+							$this->errors[$error]['lib'] = $langs->trans('ErrorMissingMandatoryValue', $key);
+							$this->errors[$error]['type'] = 'NOTNULL';
 							$errorforthistable++;
 							$error++;
 						}
@@ -415,28 +415,28 @@ class ImportCsv extends ModeleImports
 						else
 						{
 						    // We convert field if required
-						    if (! empty($objimport->array_import_convertvalue[0][$val]))
+						    if (!empty($objimport->array_import_convertvalue[0][$val]))
 						    {
                                 //print 'Must convert '.$newval.' with rule '.join(',',$objimport->array_import_convertvalue[0][$val]).'. ';
-                                if ($objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromcodeid'
-                                	|| $objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromref'
-                                	|| $objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromcodeorlabel'
+                                if ($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeid'
+                                	|| $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromref'
+                                	|| $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeorlabel'
                                 	)
                                 {
                                     // New val can be an id or ref. If it start with id: it is forced to id, if it start with ref: it is forced to ref. It not, we try to guess.
-                                    $isidorref='id';
-                                    if (! is_numeric($newval) && $newval != '' && ! preg_match('/^id:/i', $newval)) $isidorref='ref';
-                                    $newval=preg_replace('/^(id|ref):/i', '', $newval);    // Remove id: or ref: that was used to force if field is id or ref
+                                    $isidorref = 'id';
+                                    if (!is_numeric($newval) && $newval != '' && !preg_match('/^id:/i', $newval)) $isidorref = 'ref';
+                                    $newval = preg_replace('/^(id|ref):/i', '', $newval); // Remove id: or ref: that was used to force if field is id or ref
                                     //print 'Val is now '.$newval.' and is type '.$isidorref."<br>\n";
 
                                     if ($isidorref == 'ref')    // If value into input import file is a ref, we apply the function defined into descriptor
                                     {
-                                        $file=(empty($objimport->array_import_convertvalue[0][$val]['classfile'])?$objimport->array_import_convertvalue[0][$val]['file']:$objimport->array_import_convertvalue[0][$val]['classfile']);
-                                        $class=$objimport->array_import_convertvalue[0][$val]['class'];
-                                        $method=$objimport->array_import_convertvalue[0][$val]['method'];
+                                        $file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']);
+                                        $class = $objimport->array_import_convertvalue[0][$val]['class'];
+                                        $method = $objimport->array_import_convertvalue[0][$val]['method'];
                                         if ($this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval] != '')
                                         {
-                                        	$newval=$this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval];
+                                        	$newval = $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval];
                                         }
                                         else
 										{
@@ -446,7 +446,7 @@ class ImportCsv extends ModeleImports
                                                 dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method);
                                                 break;
                                             }
-                                            $classinstance=new $class($this->db);
+                                            $classinstance = new $class($this->db);
                                             // Try the fetch from code or ref
                                             $param_array = array('', $newval);
                                             if ($class == 'AccountingAccount')
@@ -550,11 +550,11 @@ class ImportCsv extends ModeleImports
                                 			dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method.', units='.$units);
                                 			break;
                                 		}
-                                		$classinstance=new $class($this->db);
+                                		$classinstance = new $class($this->db);
                                 		// Try the fetch from code or ref
                                 		call_user_func_array(array($classinstance, $method), array('', '', $newval, $units));
-                                		$scaleorid = (($objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromcodeunits') ? $classinstance->id : $classinstance->scale);
-                                		$this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval]=$scaleorid;
+                                		$scaleorid = (($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeunits') ? $classinstance->id : $classinstance->scale);
+                                		$this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval] = $scaleorid;
                                 		//print 'We have made a '.$class.'->'.$method." to get a value from key '".$newval."' and we got '".$scaleorid."'.";exit;
                                 		if ($classinstance->id > 0)	// we found record
                                 		{
@@ -562,91 +562,91 @@ class ImportCsv extends ModeleImports
                                 		}
                                 		else
                                 		{
-                                			if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) $this->errors[$error]['lib']=$langs->trans('ErrorFieldValueNotIn', $key, $newval, 'scale', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
-                                			else $this->errors[$error]['lib']='ErrorFieldValueNotIn';
-                                			$this->errors[$error]['type']='FOREIGNKEY';
+                                			if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) $this->errors[$error]['lib'] = $langs->trans('ErrorFieldValueNotIn', $key, $newval, 'scale', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
+                                			else $this->errors[$error]['lib'] = 'ErrorFieldValueNotIn';
+                                			$this->errors[$error]['type'] = 'FOREIGNKEY';
                                 			$errorforthistable++;
                                 			$error++;
                                 		}
                                 	}
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomercodeifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomercodeifauto')
                                 {
                                     if (strtolower($newval) == 'auto')
                                     {
                                         $this->thirpartyobject->get_codeclient(0, 0);
-                                        $newval=$this->thirpartyobject->code_client;
+                                        $newval = $this->thirpartyobject->code_client;
                                         //print 'code_client='.$newval;
                                     }
-                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                    if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsuppliercodeifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsuppliercodeifauto')
                                 {
                                     if (strtolower($newval) == 'auto')
                                     {
-                                        $newval=$this->thirpartyobject->get_codefournisseur(0, 1);
-                                        $newval=$this->thirpartyobject->code_fournisseur;
+                                        $newval = $this->thirpartyobject->get_codefournisseur(0, 1);
+                                        $newval = $this->thirpartyobject->code_fournisseur;
                                         //print 'code_fournisseur='.$newval;
                                     }
-                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                    if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomeraccountancycodeifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomeraccountancycodeifauto')
                                 {
                                     if (strtolower($newval) == 'auto')
                                     {
                                         $this->thirpartyobject->get_codecompta('customer');
-                                        $newval=$this->thirpartyobject->code_compta;
+                                        $newval = $this->thirpartyobject->code_compta;
                                         //print 'code_compta='.$newval;
                                     }
-                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                    if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsupplieraccountancycodeifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsupplieraccountancycodeifauto')
                                 {
                                     if (strtolower($newval) == 'auto')
                                     {
                                         $this->thirpartyobject->get_codecompta('supplier');
-                                        $newval=$this->thirpartyobject->code_compta_fournisseur;
-                                        if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                        $newval = $this->thirpartyobject->code_compta_fournisseur;
+                                        if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                         //print 'code_compta_fournisseur='.$newval;
                                     }
-                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                    if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getrefifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getrefifauto')
                                 {
-                                    $defaultref='';
+                                    $defaultref = '';
                                     // TODO provide the $modTask (module of generation of ref) as parameter of import_insert function
-                                    $obj = empty($conf->global->PROJECT_TASK_ADDON)?'mod_task_simple':$conf->global->PROJECT_TASK_ADDON;
-                                    if (! empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php"))
+                                    $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
+                                    if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php"))
                                     {
-                                        require_once DOL_DOCUMENT_ROOT ."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
+                                        require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
                                         $modTask = new $obj;
                                         $defaultref = $modTask->getNextValue(null, null);
                                     }
-                                    if (is_numeric($defaultref) && $defaultref <= 0) $defaultref='';
-                                    $newval=$defaultref;
+                                    if (is_numeric($defaultref) && $defaultref <= 0) $defaultref = '';
+                                    $newval = $defaultref;
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='compute')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'compute')
                                 {
-                                    $file=(empty($objimport->array_import_convertvalue[0][$val]['classfile'])?$objimport->array_import_convertvalue[0][$val]['file']:$objimport->array_import_convertvalue[0][$val]['classfile']);
-                                    $class=$objimport->array_import_convertvalue[0][$val]['class'];
-                                    $method=$objimport->array_import_convertvalue[0][$val]['method'];
+                                    $file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']);
+                                    $class = $objimport->array_import_convertvalue[0][$val]['class'];
+                                    $method = $objimport->array_import_convertvalue[0][$val]['method'];
                                     $resultload = dol_include_once($file);
                                     if (empty($resultload))
                                     {
                                         dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method);
                                         break;
                                     }
-                                    $classinstance=new $class($this->db);
+                                    $classinstance = new $class($this->db);
                                     $res = call_user_func_array(array($classinstance, $method), array(&$arrayrecord));
-                                    if ($res<0) {
-                                        if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) $this->errors[$error]['lib']=$langs->trans('ErrorFieldValueNotIn', $key, $newval, 'code', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
-                                        else $this->errors[$error]['lib']='ErrorFieldValueNotIn';
-                                        $this->errors[$error]['type']='FOREIGNKEY';
+                                    if ($res < 0) {
+                                        if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) $this->errors[$error]['lib'] = $langs->trans('ErrorFieldValueNotIn', $key, $newval, 'code', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
+                                        else $this->errors[$error]['lib'] = 'ErrorFieldValueNotIn';
+                                        $this->errors[$error]['type'] = 'FOREIGNKEY';
                                         $errorforthistable++;
                                         $error++;
                                     }
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='numeric')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'numeric')
                                 {
                                     $newval = price2num($newval);
                                 }
@@ -655,36 +655,36 @@ class ImportCsv extends ModeleImports
 						    }
 
 						    // Test regexp
-							if (! empty($objimport->array_import_regex[0][$val]) && ($newval != ''))
+							if (!empty($objimport->array_import_regex[0][$val]) && ($newval != ''))
 							{
 								// If test is "Must exist in a field@table or field@table:..."
 								if (preg_match('/^(.+)@([^:]+)(:.+)?$/', $objimport->array_import_regex[0][$val], $reg))
 								{
-									$field=$reg[1];
-									$table=$reg[2];
-									$filter=!empty($reg[3])?substr($reg[3], 1):'';
+									$field = $reg[1];
+									$table = $reg[2];
+									$filter = !empty($reg[3]) ?substr($reg[3], 1) : '';
 
 									$cachekey = $field.'@'.$table;
-									if(! empty($filter)) $cachekey.= ':'.$filter;
+									if (!empty($filter)) $cachekey .= ':'.$filter;
 
 									// Load content of field@table into cache array
-									if (! is_array($this->cachefieldtable[$cachekey])) // If content of field@table not already loaded into cache
+									if (!is_array($this->cachefieldtable[$cachekey])) // If content of field@table not already loaded into cache
 									{
-										$sql="SELECT ".$field." as aliasfield FROM ".$table;
-										if(! empty($filter))
+										$sql = "SELECT ".$field." as aliasfield FROM ".$table;
+										if (!empty($filter))
 										{
-											$sql.= ' WHERE ' . $filter;
+											$sql .= ' WHERE '.$filter;
 										}
 
-										$resql=$this->db->query($sql);
+										$resql = $this->db->query($sql);
 										if ($resql)
 										{
-											$num=$this->db->num_rows($resql);
-											$i=0;
+											$num = $this->db->num_rows($resql);
+											$i = 0;
 											while ($i < $num)
 											{
-												$obj=$this->db->fetch_object($resql);
-												if ($obj) $this->cachefieldtable[$cachekey][]=$obj->aliasfield;
+												$obj = $this->db->fetch_object($resql);
+												if ($obj) $this->cachefieldtable[$cachekey][] = $obj->aliasfield;
 												$i++;
 											}
 										}
@@ -695,21 +695,21 @@ class ImportCsv extends ModeleImports
 									}
 
 									// Now we check cache is not empty (should not) and key is into cache
-									if (! is_array($this->cachefieldtable[$cachekey]) || ! in_array($newval, $this->cachefieldtable[$cachekey]))
+									if (!is_array($this->cachefieldtable[$cachekey]) || !in_array($newval, $this->cachefieldtable[$cachekey]))
 									{
 										$tableforerror = $table;
-										if(! empty($filter)) $tableforerror.= ':'.$filter;
-										$this->errors[$error]['lib']=$langs->transnoentitiesnoconv('ErrorFieldValueNotIn', $key, $newval, $field, $tableforerror);
-										$this->errors[$error]['type']='FOREIGNKEY';
+										if (!empty($filter)) $tableforerror .= ':'.$filter;
+										$this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorFieldValueNotIn', $key, $newval, $field, $tableforerror);
+										$this->errors[$error]['type'] = 'FOREIGNKEY';
 									    $errorforthistable++;
 										$error++;
 									}
 								}
 								// If test is just a static regex
-								elseif (! preg_match('/'.$objimport->array_import_regex[0][$val].'/i', $newval)) {
+								elseif (!preg_match('/'.$objimport->array_import_regex[0][$val].'/i', $newval)) {
 								    //if ($key == 19) print "xxx".$newval."zzz".$objimport->array_import_regex[0][$val]."<br>";
-									$this->errors[$error]['lib']=$langs->transnoentitiesnoconv('ErrorWrongValueForField', $key, $newval, $objimport->array_import_regex[0][$val]);
-									$this->errors[$error]['type']='REGEX';
+									$this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorWrongValueForField', $key, $newval, $objimport->array_import_regex[0][$val]);
+									$this->errors[$error]['type'] = 'REGEX';
 									$errorforthistable++;
 									$error++;
 								}
@@ -723,9 +723,9 @@ class ImportCsv extends ModeleImports
 						$listfields[] = $fieldname;
 
 						// Note: arrayrecord (and 'type') is filled with ->import_read_record called by import.php page before calling import_insert
-						if (empty($newval) && $arrayrecord[($key-1)]['type'] < 0) {
-                            $listvalues[] = ($newval=='0'?$newval:"null");
-                        } elseif (empty($newval) && $arrayrecord[($key-1)]['type'] == 0) {
+						if (empty($newval) && $arrayrecord[($key - 1)]['type'] < 0) {
+                            $listvalues[] = ($newval == '0' ? $newval : "null");
+                        } elseif (empty($newval) && $arrayrecord[($key - 1)]['type'] == 0) {
                             $listvalues[] = "''";
                         } else {
                             $listvalues[] = "'".$this->db->escape($newval)."'";
@@ -738,9 +738,9 @@ class ImportCsv extends ModeleImports
 				if (!empty($listfields) && is_array($objimport->array_import_fieldshidden[0]))
 				{
     				// Loop on each hidden fields to add them into listfields/listvalues
-				    foreach($objimport->array_import_fieldshidden[0] as $key => $val)
+				    foreach ($objimport->array_import_fieldshidden[0] as $key => $val)
     				{
-    					if (! preg_match('/^'.preg_quote($alias, '/').'\./', $key)) continue;    // Not a field of current table
+    					if (!preg_match('/^'.preg_quote($alias, '/').'\./', $key)) continue; // Not a field of current table
     				    if ($val == 'user->id')
     				    {
     				        $listfields[] = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
@@ -748,8 +748,8 @@ class ImportCsv extends ModeleImports
     				    }
     				    elseif (preg_match('/^lastrowid-/', $val))
     				    {
-    				        $tmp=explode('-', $val);
-    				        $lastinsertid=(isset($last_insert_id_array[$tmp[1]]))?$last_insert_id_array[$tmp[1]]:0;
+    				        $tmp = explode('-', $val);
+    				        $lastinsertid = (isset($last_insert_id_array[$tmp[1]])) ? $last_insert_id_array[$tmp[1]] : 0;
 							$keyfield = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
     				        $listfields[] = $keyfield;
                             $listvalues[] = $lastinsertid;
@@ -757,14 +757,14 @@ class ImportCsv extends ModeleImports
     				    }
     				    elseif (preg_match('/^const-/', $val))
     				    {
-    				    	$tmp=explode('-', $val, 2);
+    				    	$tmp = explode('-', $val, 2);
     				    	$listfields[] = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
     				    	$listvalues[] = "'".$tmp[1]."'";
     				    }
     				    else
     				    {
-    				    	$this->errors[$error]['lib']='Bad value of profile setup '.$val.' for array_import_fieldshidden';
-    				    	$this->errors[$error]['type']='Import profile setup';
+    				    	$this->errors[$error]['lib'] = 'Bad value of profile setup '.$val.' for array_import_fieldshidden';
+    				    	$this->errors[$error]['type'] = 'Import profile setup';
     				    	$error++;
     				    }
     				}
@@ -773,7 +773,7 @@ class ImportCsv extends ModeleImports
 
 				// If no error for this $alias/$tablename, we have a complete $listfields and $listvalues that are defined
 				// so we can try to make the insert or update now.
-				if (! $errorforthistable)
+				if (!$errorforthistable)
 				{
 					//print "$alias/$tablename/$listfields/$listvalues<br>";
 					if (!empty($listfields))
@@ -792,21 +792,21 @@ class ImportCsv extends ModeleImports
 								$filters = array();
 								foreach ($updatekeys as $key) {
 									$col = $objimport->array_import_updatekeys[0][$key];
-									$key=preg_replace('/^.*\./i', '', $key);
+									$key = preg_replace('/^.*\./i', '', $key);
 									$where[] = $key.' = '.$data[$key];
 									$filters[] = $col.' = '.$data[$key];
 								}
-								$sqlSelect.= ' WHERE '.implode(' AND ', $where);
+								$sqlSelect .= ' WHERE '.implode(' AND ', $where);
 
-								$resql=$this->db->query($sqlSelect);
-								if($resql) {
+								$resql = $this->db->query($sqlSelect);
+								if ($resql) {
 									$res = $this->db->fetch_object($resql);
-									if($resql->num_rows == 1) {
+									if ($resql->num_rows == 1) {
 										$lastinsertid = $res->rowid;
 										$last_insert_id_array[$tablename] = $lastinsertid;
-									} elseif($resql->num_rows > 1) {
-										$this->errors[$error]['lib']=$langs->trans('MultipleRecordFoundWithTheseFilters', implode(', ', $filters));
-										$this->errors[$error]['type']='SQL';
+									} elseif ($resql->num_rows > 1) {
+										$this->errors[$error]['lib'] = $langs->trans('MultipleRecordFoundWithTheseFilters', implode(', ', $filters));
+										$this->errors[$error]['type'] = 'SQL';
 										$error++;
 									} else {
 										// No record found with filters, insert will be tried below
@@ -815,8 +815,8 @@ class ImportCsv extends ModeleImports
 								else
 								{
 									//print 'E';
-									$this->errors[$error]['lib']=$this->db->lasterror();
-									$this->errors[$error]['type']='SQL';
+									$this->errors[$error]['lib'] = $this->db->lasterror();
+									$this->errors[$error]['type'] = 'SQL';
 									$error++;
 								}
 							} else {
@@ -827,13 +827,13 @@ class ImportCsv extends ModeleImports
 								// Note: For extrafield tablename, we have in importfieldshidden_array an enty 'extra.fk_object'=>'lastrowid-tableparent' so $keyfield is 'fk_object'
 								$sqlSelect = 'SELECT rowid FROM '.$tablename;
 
-								if(empty($keyfield)) $keyfield = 'rowid';
+								if (empty($keyfield)) $keyfield = 'rowid';
 								$sqlSelect .= ' WHERE '.$keyfield.' = '.$lastinsertid;
 
-								$resql=$this->db->query($sqlSelect);
-								if($resql) {
+								$resql = $this->db->query($sqlSelect);
+								if ($resql) {
 									$res = $this->db->fetch_object($resql);
-									if($resql->num_rows == 1) {
+									if ($resql->num_rows == 1) {
 										// We have a row referencing this last foreign key, continue with UPDATE.
 									} else {
 										// No record found referencing this last foreign key,
@@ -844,8 +844,8 @@ class ImportCsv extends ModeleImports
 								else
 								{
 									//print 'E';
-									$this->errors[$error]['lib']=$this->db->lasterror();
-									$this->errors[$error]['type']='SQL';
+									$this->errors[$error]['lib'] = $this->db->lasterror();
+									$this->errors[$error]['type'] = 'SQL';
 									$error++;
 								}
 							}
@@ -859,24 +859,24 @@ class ImportCsv extends ModeleImports
 								foreach ($data as $key => $val) {
 									$set[] = $key.' = '.$val;
 								}
-								$sqlstart.= ' SET '.implode(', ', $set);
+								$sqlstart .= ' SET '.implode(', ', $set);
 
-								if(empty($keyfield)) $keyfield = 'rowid';
+								if (empty($keyfield)) $keyfield = 'rowid';
 								$sqlend = ' WHERE '.$keyfield.' = '.$lastinsertid;
 
 								$sql = $sqlstart.$sqlend;
 
 								// Run update request
-								$resql=$this->db->query($sql);
-								if($resql) {
+								$resql = $this->db->query($sql);
+								if ($resql) {
 									// No error, update has been done. $this->db->db->affected_rows can be 0 if data hasn't changed
 									$updatedone = true;
 								}
 								else
 								{
 									//print 'E';
-									$this->errors[$error]['lib']=$this->db->lasterror();
-									$this->errors[$error]['type']='SQL';
+									$this->errors[$error]['lib'] = $this->db->lasterror();
+									$this->errors[$error]['type'] = 'SQL';
 									$error++;
 								}
 							}
@@ -887,13 +887,13 @@ class ImportCsv extends ModeleImports
 							// Build SQL INSERT request
 							$sqlstart = 'INSERT INTO '.$tablename.'('.implode(', ', $listfields).', import_key';
 							$sqlend = ') VALUES('.implode(', ', $listvalues).", '".$importid."'";
-							if (! empty($tablewithentity_cache[$tablename])) {
-								$sqlstart.= ', entity';
-								$sqlend.= ', '.$conf->entity;
+							if (!empty($tablewithentity_cache[$tablename])) {
+								$sqlstart .= ', entity';
+								$sqlend .= ', '.$conf->entity;
 							}
-							if (! empty($objimport->array_import_tables_creator[0][$alias])) {
-								$sqlstart.= ', '.$objimport->array_import_tables_creator[0][$alias];
-								$sqlend.=', '.$user->id;
+							if (!empty($objimport->array_import_tables_creator[0][$alias])) {
+								$sqlstart .= ', '.$objimport->array_import_tables_creator[0][$alias];
+								$sqlend .= ', '.$user->id;
 							}
 							$sql = $sqlstart.$sqlend.')';
 							dol_syslog("import_csv.modules", LOG_DEBUG);
@@ -901,7 +901,7 @@ class ImportCsv extends ModeleImports
 							// Run insert request
 							if ($sql)
 							{
-								$resql=$this->db->query($sql);
+								$resql = $this->db->query($sql);
 								if ($resql)
 								{
 								    $last_insert_id_array[$tablename] = $this->db->last_insert_id($tablename); // store the last inserted auto_increment id for each table, so that child tables can be inserted with the appropriate id. This must be done just after the INSERT request, else we risk losing the id (because another sql query will be issued somewhere in Dolibarr).
@@ -910,8 +910,8 @@ class ImportCsv extends ModeleImports
 								else
 								{
 									//print 'E';
-									$this->errors[$error]['lib']=$this->db->lasterror();
-									$this->errors[$error]['type']='SQL';
+									$this->errors[$error]['lib'] = $this->db->lasterror();
+									$this->errors[$error]['type'] = 'SQL';
 									$error++;
 								}
 							}
@@ -926,8 +926,8 @@ class ImportCsv extends ModeleImports
 			    if ($error) break;
 			}
 
-			if($updatedone) $this->nbupdate++;
-			if($insertdone) $this->nbinsert++;
+			if ($updatedone) $this->nbupdate++;
+			if ($insertdone) $this->nbinsert++;
 		}
 
 		return 1;
@@ -942,5 +942,5 @@ class ImportCsv extends ModeleImports
  */
 function cleansep($value)
 {
-	return str_replace(array(',',';'), '/', $value);
+	return str_replace(array(',', ';'), '/', $value);
 };

+ 175 - 175
htdocs/core/modules/import/import_xlsx.modules.php

@@ -25,7 +25,7 @@
  *		\brief      File to load import files with Excel format
  */
 
-require_once DOL_DOCUMENT_ROOT .'/core/modules/import/modules_import.php';
+require_once DOL_DOCUMENT_ROOT.'/core/modules/import/modules_import.php';
 
 
 /**
@@ -43,7 +43,7 @@ class ImportXlsx extends ModeleImports
     /**
 	 * @var string Error code (or message)
 	 */
-	public $error='';
+	public $error = '';
 
 	/**
 	 * @var string[] Error codes (or messages)
@@ -60,7 +60,7 @@ class ImportXlsx extends ModeleImports
      */
     public $label;
 
-	public $extension;    // Extension of files imported by driver
+	public $extension; // Extension of files imported by driver
 
 	/**
      * Dolibarr version of driver
@@ -68,19 +68,19 @@ class ImportXlsx extends ModeleImports
      */
 	public $version = 'dolibarr';
 
-	public $label_lib;    // Label of external lib used by driver
+	public $label_lib; // Label of external lib used by driver
 
-	public $version_lib;  // Version of external lib used by driver
+	public $version_lib; // Version of external lib used by driver
 
 	public $separator;
 
-    public $file;      // Path of file
+    public $file; // Path of file
 
-	public $handle;    // Handle fichier
+	public $handle; // Handle fichier
 
-	public $cacheconvert=array();      // Array to cache list of value found after a convertion
+	public $cacheconvert = array(); // Array to cache list of value found after a convertion
 
-	public $cachefieldtable=array();   // Array to cache list of value found into fields@tables
+	public $cachefieldtable = array(); // Array to cache list of value found into fields@tables
 
 	public $workbook; // temporary import file
 
@@ -97,31 +97,31 @@ class ImportXlsx extends ModeleImports
 	 */
     public function __construct($db, $datatoimport)
 	{
-		global $conf,$langs;
+		global $conf, $langs;
 		$this->db = $db;
 
 		// this is used as an extension from the example file code, so we have to put xlsx here !!!
-		$this->id='xlsx';                // Same value as xxx in file name export_xxx.modules.php
-		$this->label='Excel 2007';             // Label of driver
-		$this->desc=$langs->trans("Excel2007FormatDesc");
-		$this->extension='xlsx';         // Extension for generated file by this driver
-		$this->picto='mime/xls';		// Picto (This is not used by the example file code as Mime type, too bad ...)
-		$this->version='1.0';         // Driver version
+		$this->id = 'xlsx'; // Same value as xxx in file name export_xxx.modules.php
+		$this->label = 'Excel 2007'; // Label of driver
+		$this->desc = $langs->trans("Excel2007FormatDesc");
+		$this->extension = 'xlsx'; // Extension for generated file by this driver
+		$this->picto = 'mime/xls'; // Picto (This is not used by the example file code as Mime type, too bad ...)
+		$this->version = '1.0'; // Driver version
 
 		// If driver use an external library, put its name here
         require_once PHPEXCEL_PATH.'PHPExcel.php';
 		require_once PHPEXCEL_PATH.'PHPExcel/Style/Alignment.php';
-        if (! class_exists('ZipArchive')) // For Excel2007, PHPExcel need ZipArchive
+        if (!class_exists('ZipArchive')) // For Excel2007, PHPExcel need ZipArchive
         {
                 $langs->load("errors");
-                $this->error=$langs->trans('ErrorPHPNeedModule', 'zip');
+                $this->error = $langs->trans('ErrorPHPNeedModule', 'zip');
                 return -1;
         }
-        $this->label_lib='PhpExcel';
-        $this->version_lib='1.8.0';
+        $this->label_lib = 'PhpExcel';
+        $this->version_lib = '1.8.0';
 
-		$this->datatoimport=$datatoimport;
-		if (preg_match('/^societe_/', $datatoimport)) $this->thirpartyobject=new Societe($this->db);
+		$this->datatoimport = $datatoimport;
+		if (preg_match('/^societe_/', $datatoimport)) $this->thirpartyobject = new Societe($this->db);
 	}
 
 
@@ -135,11 +135,11 @@ class ImportXlsx extends ModeleImports
     public function write_header_example($outputlangs)
 	{
         // phpcs:enable
-        global $user,$conf,$langs;
+        global $user, $conf, $langs;
         // create a temporary object, the final output will be generated in footer
         if (!empty($conf->global->MAIN_USE_FILECACHE_EXPORT_EXCEL_DIR)) {
             $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;
-            $cacheSettings = array (
+            $cacheSettings = array(
                 'dir' => $conf->global->MAIN_USE_FILECACHE_EXPORT_EXCEL_DIR
             );
             PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
@@ -174,7 +174,7 @@ class ImportXlsx extends ModeleImports
 		$this->workbook->getActiveSheet()->getStyle('1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
 
 		$col = 0;
-		foreach($headerlinefields as $field) {
+		foreach ($headerlinefields as $field) {
 			$this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($col, 1, $outputlangs->transnoentities($field));
 			// set autowidth
 			//$this->workbook->getActiveSheet()->getColumnDimension($this->column2Letter($col + 1))->setAutoSize(true);
@@ -197,7 +197,7 @@ class ImportXlsx extends ModeleImports
         // phpcs:enable
 		$col = 0;
 		$row = 2;
-		foreach($contentlinevalues as $cell) {
+		foreach ($contentlinevalues as $cell) {
 			$this->workbook->getActiveSheet()->SetCellValueByColumnAndRow($col, $row, $cell);
 			$col++;
 		}
@@ -240,7 +240,7 @@ class ImportXlsx extends ModeleImports
 	{
         // phpcs:enable
 		global $langs;
-		$ret=1;
+		$ret = 1;
 
 		dol_syslog(get_class($this)."::open_file file=".$file);
 
@@ -287,7 +287,7 @@ class ImportXlsx extends ModeleImports
 		// This is not called by the import code !!!
 		$this->headers = array();
 		$colcount = PHPExcel_Cell::columnIndexFromString($this->workbook->getActiveSheet()->getHighestDataColumn());
-		for($col=0;$col<$colcount;$col++) {
+		for ($col = 0; $col < $colcount; $col++) {
 			$this->headers[$col] = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, 1)->getValue();
 		}
 		return 0;
@@ -306,14 +306,14 @@ class ImportXlsx extends ModeleImports
 		global $conf;
 
 		$rowcount = $this->workbook->getActiveSheet()->getHighestDataRow();
-		if($this->record > $rowcount)
+		if ($this->record > $rowcount)
 			return false;
 		$array = array();
 		$colcount = PHPExcel_Cell::columnIndexFromString($this->workbook->getActiveSheet()->getHighestDataColumn(0));
-		for($col=0;$col<$colcount;$col++) {
+		for ($col = 0; $col < $colcount; $col++) {
 			$val = $this->workbook->getActiveSheet()->getCellByColumnAndRow($col, $this->record)->getValue();
 			$array[$col]['val'] = $val;
-			$array[$col]['type'] = (dol_strlen($val)?1:-1); // If empty we consider it null
+			$array[$col]['type'] = (dol_strlen($val) ? 1 : -1); // If empty we consider it null
 		}
 		$this->record++;
 		return $array;
@@ -349,21 +349,21 @@ class ImportXlsx extends ModeleImports
     public function import_insert($arrayrecord, $array_match_file_to_database, $objimport, $maxfields, $importid, $updatekeys)
 	{
         // phpcs:enable
-		global $langs,$conf,$user;
-        global $thirdparty_static;    	// Specific to thirdparty import
-		global $tablewithentity_cache;	// Cache to avoid to call  desc at each rows on tables
+		global $langs, $conf, $user;
+        global $thirdparty_static; // Specific to thirdparty import
+		global $tablewithentity_cache; // Cache to avoid to call  desc at each rows on tables
 
-		$error=0;
-		$warning=0;
-		$this->errors=array();
-		$this->warnings=array();
+		$error = 0;
+		$warning = 0;
+		$this->errors = array();
+		$this->warnings = array();
 
 		//dol_syslog("import_csv.modules maxfields=".$maxfields." importid=".$importid);
 
 		//var_dump($array_match_file_to_database);
 		//var_dump($arrayrecord);
-		$array_match_database_to_file=array_flip($array_match_file_to_database);
-		$sort_array_match_file_to_database=$array_match_file_to_database;
+		$array_match_database_to_file = array_flip($array_match_file_to_database);
+		$sort_array_match_file_to_database = $array_match_file_to_database;
 		ksort($sort_array_match_file_to_database);
 
 		//var_dump($sort_array_match_file_to_database);
@@ -371,8 +371,8 @@ class ImportXlsx extends ModeleImports
 		if (count($arrayrecord) == 0 || (count($arrayrecord) == 1 && empty($arrayrecord[0]['val'])))
 		{
 			//print 'W';
-			$this->warnings[$warning]['lib']=$langs->trans('EmptyLine');
-			$this->warnings[$warning]['type']='EMPTY';
+			$this->warnings[$warning]['lib'] = $langs->trans('EmptyLine');
+			$this->warnings[$warning]['type'] = 'EMPTY';
 			$warning++;
 		}
 		else
@@ -381,25 +381,25 @@ class ImportXlsx extends ModeleImports
 			$updatedone = false;
 			$insertdone = false;
 			// For each table to insert, me make a separate insert
-			foreach($objimport->array_import_tables[0] as $alias => $tablename)
+			foreach ($objimport->array_import_tables[0] as $alias => $tablename)
 			{
 				// Build sql request
-				$sql='';
-				$listfields=array();
-				$listvalues=array();
-				$i=0;
-				$errorforthistable=0;
+				$sql = '';
+				$listfields = array();
+				$listvalues = array();
+				$i = 0;
+				$errorforthistable = 0;
 
 				// Define $tablewithentity_cache[$tablename] if not already defined
-				if (! isset($tablewithentity_cache[$tablename]))	// keep this test with "isset"
+				if (!isset($tablewithentity_cache[$tablename]))	// keep this test with "isset"
 				{
 					dol_syslog("Check if table ".$tablename." has an entity field");
-					$resql=$this->db->DDLDescTable($tablename, 'entity');
+					$resql = $this->db->DDLDescTable($tablename, 'entity');
 					if ($resql)
 					{
-						$obj=$this->db->fetch_object($resql);
-						if ($obj) $tablewithentity_cache[$tablename]=1;		// table contains entity field
-						else $tablewithentity_cache[$tablename]=0;			// table does not contains entity field
+						$obj = $this->db->fetch_object($resql);
+						if ($obj) $tablewithentity_cache[$tablename] = 1; // table contains entity field
+						else $tablewithentity_cache[$tablename] = 0; // table does not contains entity field
 					}
 					else dol_print_error($this->db);
 				}
@@ -415,26 +415,26 @@ class ImportXlsx extends ModeleImports
                 }
 
 				// Loop on each fields in the match array: $key = 1..n, $val=alias of field (s.nom)
-				foreach($sort_array_match_file_to_database as $key => $val)
+				foreach ($sort_array_match_file_to_database as $key => $val)
 				{
-				    $fieldalias=preg_replace('/\..*$/i', '', $val);
-				    $fieldname=preg_replace('/^.*\./i', '', $val);
+				    $fieldalias = preg_replace('/\..*$/i', '', $val);
+				    $fieldname = preg_replace('/^.*\./i', '', $val);
 
-				    if ($alias != $fieldalias) continue;    // Not a field of current table
+				    if ($alias != $fieldalias) continue; // Not a field of current table
 
 					if ($key <= $maxfields)
 					{
 						// Set $newval with value to insert and set $listvalues with sql request part for insert
-						$newval='';
-						if ($arrayrecord[($key-1)]['type'] > 0) $newval=$arrayrecord[($key-1)]['val'];    // If type of field into input file is not empty string (so defined into input file), we get value
+						$newval = '';
+						if ($arrayrecord[($key - 1)]['type'] > 0) $newval = $arrayrecord[($key - 1)]['val']; // If type of field into input file is not empty string (so defined into input file), we get value
 
 						// Make some tests on $newval
 
 						// Is it a required field ?
-						if (preg_match('/\*/', $objimport->array_import_fields[0][$val]) && ((string) $newval==''))
+						if (preg_match('/\*/', $objimport->array_import_fields[0][$val]) && ((string) $newval == ''))
 						{
-							$this->errors[$error]['lib']=$langs->trans('ErrorMissingMandatoryValue', $key);
-							$this->errors[$error]['type']='NOTNULL';
+							$this->errors[$error]['lib'] = $langs->trans('ErrorMissingMandatoryValue', $key);
+							$this->errors[$error]['type'] = 'NOTNULL';
 							$errorforthistable++;
 							$error++;
 						}
@@ -442,28 +442,28 @@ class ImportXlsx extends ModeleImports
 						else
 						{
 						    // We convert field if required
-						    if (! empty($objimport->array_import_convertvalue[0][$val]))
+						    if (!empty($objimport->array_import_convertvalue[0][$val]))
 						    {
                                 //print 'Must convert '.$newval.' with rule '.join(',',$objimport->array_import_convertvalue[0][$val]).'. ';
-                                if ($objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromcodeid'
-                                	|| $objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromref'
-                                	|| $objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromcodeorlabel'
+                                if ($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeid'
+                                	|| $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromref'
+                                	|| $objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeorlabel'
                                 	)
                                 {
                                     // New val can be an id or ref. If it start with id: it is forced to id, if it start with ref: it is forced to ref. It not, we try to guess.
-                                    $isidorref='id';
-                                    if (! is_numeric($newval) && $newval != '' && ! preg_match('/^id:/i', $newval)) $isidorref='ref';
-                                    $newval=preg_replace('/^(id|ref):/i', '', $newval);    // Remove id: or ref: that was used to force if field is id or ref
+                                    $isidorref = 'id';
+                                    if (!is_numeric($newval) && $newval != '' && !preg_match('/^id:/i', $newval)) $isidorref = 'ref';
+                                    $newval = preg_replace('/^(id|ref):/i', '', $newval); // Remove id: or ref: that was used to force if field is id or ref
                                     //print 'Val is now '.$newval.' and is type '.$isidorref."<br>\n";
 
                                     if ($isidorref == 'ref')    // If value into input import file is a ref, we apply the function defined into descriptor
                                     {
-                                        $file=(empty($objimport->array_import_convertvalue[0][$val]['classfile'])?$objimport->array_import_convertvalue[0][$val]['file']:$objimport->array_import_convertvalue[0][$val]['classfile']);
-                                        $class=$objimport->array_import_convertvalue[0][$val]['class'];
-                                        $method=$objimport->array_import_convertvalue[0][$val]['method'];
+                                        $file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']);
+                                        $class = $objimport->array_import_convertvalue[0][$val]['class'];
+                                        $method = $objimport->array_import_convertvalue[0][$val]['method'];
                                         if ($this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval] != '')
                                         {
-                                        	$newval=$this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval];
+                                        	$newval = $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'][$newval];
                                         }
                                         else
 										{
@@ -473,7 +473,7 @@ class ImportXlsx extends ModeleImports
                                                 dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method);
                                                 break;
                                             }
-                                            $classinstance=new $class($this->db);
+                                            $classinstance = new $class($this->db);
                                             // Try the fetch from code or ref
                                             $param_array = array('', $newval);
                                             if ($class == 'AccountingAccount')
@@ -577,11 +577,11 @@ class ImportXlsx extends ModeleImports
                                 			dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method.', units='.$units);
                                 			break;
                                 		}
-                                		$classinstance=new $class($this->db);
+                                		$classinstance = new $class($this->db);
                                 		// Try the fetch from code or ref
                                         call_user_func_array(array($classinstance, $method), array('', '', $newval, $units));
-                                        $scaleorid = (($objimport->array_import_convertvalue[0][$val]['rule']=='fetchidfromcodeunits') ? $classinstance->id : $classinstance->scale);
-                                        $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval]=$scaleorid;
+                                        $scaleorid = (($objimport->array_import_convertvalue[0][$val]['rule'] == 'fetchidfromcodeunits') ? $classinstance->id : $classinstance->scale);
+                                        $this->cacheconvert[$file.'_'.$class.'_'.$method.'_'.$units][$newval] = $scaleorid;
                                         //print 'We have made a '.$class.'->'.$method." to get a value from key '".$newval."' and we got '".$scaleorid."'.";exit;
                                         if ($classinstance->id > 0)	// we found record
                                         {
@@ -589,91 +589,91 @@ class ImportXlsx extends ModeleImports
                                         }
                                         else
                                         {
-                                        	if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) $this->errors[$error]['lib']=$langs->trans('ErrorFieldValueNotIn', $key, $newval, 'scale', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
-                                        	else $this->errors[$error]['lib']='ErrorFieldValueNotIn';
-                                			$this->errors[$error]['type']='FOREIGNKEY';
+                                        	if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) $this->errors[$error]['lib'] = $langs->trans('ErrorFieldValueNotIn', $key, $newval, 'scale', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
+                                        	else $this->errors[$error]['lib'] = 'ErrorFieldValueNotIn';
+                                			$this->errors[$error]['type'] = 'FOREIGNKEY';
                                 			$errorforthistable++;
                                 			$error++;
                                 		}
                                 	}
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomercodeifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomercodeifauto')
                                 {
                                     if (strtolower($newval) == 'auto')
                                     {
                                         $this->thirpartyobject->get_codeclient(0, 0);
-                                        $newval=$this->thirpartyobject->code_client;
+                                        $newval = $this->thirpartyobject->code_client;
                                         //print 'code_client='.$newval;
                                     }
-                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                    if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsuppliercodeifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsuppliercodeifauto')
                                 {
                                     if (strtolower($newval) == 'auto')
                                     {
-                                        $newval=$this->thirpartyobject->get_codefournisseur(0, 1);
-                                        $newval=$this->thirpartyobject->code_fournisseur;
+                                        $newval = $this->thirpartyobject->get_codefournisseur(0, 1);
+                                        $newval = $this->thirpartyobject->code_fournisseur;
                                         //print 'code_fournisseur='.$newval;
                                     }
-                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                    if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getcustomeraccountancycodeifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getcustomeraccountancycodeifauto')
                                 {
                                     if (strtolower($newval) == 'auto')
                                     {
                                         $this->thirpartyobject->get_codecompta('customer');
-                                        $newval=$this->thirpartyobject->code_compta;
+                                        $newval = $this->thirpartyobject->code_compta;
                                         //print 'code_compta='.$newval;
                                     }
-                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                    if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getsupplieraccountancycodeifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getsupplieraccountancycodeifauto')
                                 {
                                     if (strtolower($newval) == 'auto')
                                     {
                                         $this->thirpartyobject->get_codecompta('supplier');
-                                        $newval=$this->thirpartyobject->code_compta_fournisseur;
-                                        if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                        $newval = $this->thirpartyobject->code_compta_fournisseur;
+                                        if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                         //print 'code_compta_fournisseur='.$newval;
                                     }
-                                    if (empty($newval)) $arrayrecord[($key-1)]['type']=-1;	// If we get empty value, we will use "null"
+                                    if (empty($newval)) $arrayrecord[($key - 1)]['type'] = -1; // If we get empty value, we will use "null"
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='getrefifauto')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'getrefifauto')
                                 {
-                                    $defaultref='';
+                                    $defaultref = '';
                                     // TODO provide the $modTask (module of generation of ref) as parameter of import_insert function
-                                    $obj = empty($conf->global->PROJECT_TASK_ADDON)?'mod_task_simple':$conf->global->PROJECT_TASK_ADDON;
-                                    if (! empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php"))
+                                    $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
+                                    if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.".php"))
                                     {
-                                        require_once DOL_DOCUMENT_ROOT ."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
+                                        require_once DOL_DOCUMENT_ROOT."/core/modules/project/task/".$conf->global->PROJECT_TASK_ADDON.'.php';
                                         $modTask = new $obj;
                                         $defaultref = $modTask->getNextValue(null, null);
                                     }
-                                    if (is_numeric($defaultref) && $defaultref <= 0) $defaultref='';
-                                    $newval=$defaultref;
+                                    if (is_numeric($defaultref) && $defaultref <= 0) $defaultref = '';
+                                    $newval = $defaultref;
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='compute')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'compute')
                                 {
-                                    $file=(empty($objimport->array_import_convertvalue[0][$val]['classfile'])?$objimport->array_import_convertvalue[0][$val]['file']:$objimport->array_import_convertvalue[0][$val]['classfile']);
-                                    $class=$objimport->array_import_convertvalue[0][$val]['class'];
-                                    $method=$objimport->array_import_convertvalue[0][$val]['method'];
+                                    $file = (empty($objimport->array_import_convertvalue[0][$val]['classfile']) ? $objimport->array_import_convertvalue[0][$val]['file'] : $objimport->array_import_convertvalue[0][$val]['classfile']);
+                                    $class = $objimport->array_import_convertvalue[0][$val]['class'];
+                                    $method = $objimport->array_import_convertvalue[0][$val]['method'];
                                     $resultload = dol_include_once($file);
                                     if (empty($resultload))
                                     {
                                         dol_print_error('', 'Error trying to call file='.$file.', class='.$class.', method='.$method);
                                         break;
                                     }
-                                    $classinstance=new $class($this->db);
+                                    $classinstance = new $class($this->db);
                                     $res = call_user_func_array(array($classinstance, $method), array(&$arrayrecord));
-                                    if ($res<0) {
-                                        if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) $this->errors[$error]['lib']=$langs->trans('ErrorFieldValueNotIn', $key, $newval, 'code', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
-                                        else $this->errors[$error]['lib']='ErrorFieldValueNotIn';
-                                        $this->errors[$error]['type']='FOREIGNKEY';
+                                    if ($res < 0) {
+                                        if (!empty($objimport->array_import_convertvalue[0][$val]['dict'])) $this->errors[$error]['lib'] = $langs->trans('ErrorFieldValueNotIn', $key, $newval, 'code', $langs->transnoentitiesnoconv($objimport->array_import_convertvalue[0][$val]['dict']));
+                                        else $this->errors[$error]['lib'] = 'ErrorFieldValueNotIn';
+                                        $this->errors[$error]['type'] = 'FOREIGNKEY';
                                         $errorforthistable++;
                                         $error++;
                                     }
                                 }
-                                elseif ($objimport->array_import_convertvalue[0][$val]['rule']=='numeric')
+                                elseif ($objimport->array_import_convertvalue[0][$val]['rule'] == 'numeric')
                                 {
                                     $newval = price2num($newval);
                                 }
@@ -682,36 +682,36 @@ class ImportXlsx extends ModeleImports
 						    }
 
 						    // Test regexp
-							if (! empty($objimport->array_import_regex[0][$val]) && ($newval != ''))
+							if (!empty($objimport->array_import_regex[0][$val]) && ($newval != ''))
 							{
 								// If test is "Must exist in a field@table or field@table:..."
 								if (preg_match('/^(.+)@([^:]+)(:.+)?$/', $objimport->array_import_regex[0][$val], $reg))
 								{
-									$field=$reg[1];
-									$table=$reg[2];
-									$filter=!empty($reg[3])?substr($reg[3], 1):'';
+									$field = $reg[1];
+									$table = $reg[2];
+									$filter = !empty($reg[3]) ?substr($reg[3], 1) : '';
 
 									$cachekey = $field.'@'.$table;
-									if(! empty($filter)) $cachekey.= ':'.$filter;
+									if (!empty($filter)) $cachekey .= ':'.$filter;
 
 									// Load content of field@table into cache array
-									if (! is_array($this->cachefieldtable[$cachekey])) // If content of field@table not already loaded into cache
+									if (!is_array($this->cachefieldtable[$cachekey])) // If content of field@table not already loaded into cache
 									{
-										$sql="SELECT ".$field." as aliasfield FROM ".$table;
-										if(! empty($filter))
+										$sql = "SELECT ".$field." as aliasfield FROM ".$table;
+										if (!empty($filter))
 										{
-											$sql.= ' WHERE ' . $filter;
+											$sql .= ' WHERE '.$filter;
 										}
 
-										$resql=$this->db->query($sql);
+										$resql = $this->db->query($sql);
 										if ($resql)
 										{
-											$num=$this->db->num_rows($resql);
-											$i=0;
+											$num = $this->db->num_rows($resql);
+											$i = 0;
 											while ($i < $num)
 											{
-												$obj=$this->db->fetch_object($resql);
-												if ($obj) $this->cachefieldtable[$cachekey][]=$obj->aliasfield;
+												$obj = $this->db->fetch_object($resql);
+												if ($obj) $this->cachefieldtable[$cachekey][] = $obj->aliasfield;
 												$i++;
 											}
 										}
@@ -722,21 +722,21 @@ class ImportXlsx extends ModeleImports
 									}
 
 									// Now we check cache is not empty (should not) and key is into cache
-									if (! is_array($this->cachefieldtable[$cachekey]) || ! in_array($newval, $this->cachefieldtable[$cachekey]))
+									if (!is_array($this->cachefieldtable[$cachekey]) || !in_array($newval, $this->cachefieldtable[$cachekey]))
 									{
 										$tableforerror = $table;
-										if(! empty($filter)) $tableforerror.= ':'.$filter;
-										$this->errors[$error]['lib']=$langs->transnoentitiesnoconv('ErrorFieldValueNotIn', $key, $newval, $field, $tableforerror);
-										$this->errors[$error]['type']='FOREIGNKEY';
+										if (!empty($filter)) $tableforerror .= ':'.$filter;
+										$this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorFieldValueNotIn', $key, $newval, $field, $tableforerror);
+										$this->errors[$error]['type'] = 'FOREIGNKEY';
 									    $errorforthistable++;
 										$error++;
 									}
 								}
 								// If test is just a static regex
-								elseif (! preg_match('/'.$objimport->array_import_regex[0][$val].'/i', $newval)) {
+								elseif (!preg_match('/'.$objimport->array_import_regex[0][$val].'/i', $newval)) {
 								    //if ($key == 19) print "xxx".$newval."zzz".$objimport->array_import_regex[0][$val]."<br>";
-									$this->errors[$error]['lib']=$langs->transnoentitiesnoconv('ErrorWrongValueForField', $key, $newval, $objimport->array_import_regex[0][$val]);
-									$this->errors[$error]['type']='REGEX';
+									$this->errors[$error]['lib'] = $langs->transnoentitiesnoconv('ErrorWrongValueForField', $key, $newval, $objimport->array_import_regex[0][$val]);
+									$this->errors[$error]['type'] = 'REGEX';
 									$errorforthistable++;
 									$error++;
 								}
@@ -750,8 +750,8 @@ class ImportXlsx extends ModeleImports
 						$listfields[] = $fieldname;
 
 						// Note: arrayrecord (and 'type') is filled with ->import_read_record called by import.php page before calling import_insert
-						if (empty($newval) && $arrayrecord[($key-1)]['type'] < 0)		 $listvalues[] = ($newval=='0'?$newval:"null");
-						elseif (empty($newval) && $arrayrecord[($key-1)]['type'] == 0)	 $listvalues[] = "''";
+						if (empty($newval) && $arrayrecord[($key - 1)]['type'] < 0)		 $listvalues[] = ($newval == '0' ? $newval : "null");
+						elseif (empty($newval) && $arrayrecord[($key - 1)]['type'] == 0)	 $listvalues[] = "''";
 						else															 $listvalues[] = "'".$this->db->escape($newval)."'";
 					}
 					$i++;
@@ -761,9 +761,9 @@ class ImportXlsx extends ModeleImports
 				if (!empty($listfields) && is_array($objimport->array_import_fieldshidden[0]))
 				{
     				// Loop on each hidden fields to add them into listfields/listvalues
-				    foreach($objimport->array_import_fieldshidden[0] as $key => $val)
+				    foreach ($objimport->array_import_fieldshidden[0] as $key => $val)
     				{
-    				    if (! preg_match('/^'.preg_quote($alias, '/').'\./', $key)) continue;    // Not a field of current table
+    				    if (!preg_match('/^'.preg_quote($alias, '/').'\./', $key)) continue; // Not a field of current table
     				    if ($val == 'user->id')
     				    {
     				        $listfields[] = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
@@ -771,8 +771,8 @@ class ImportXlsx extends ModeleImports
     				    }
     				    elseif (preg_match('/^lastrowid-/', $val))
     				    {
-    				        $tmp=explode('-', $val);
-    				        $lastinsertid=(isset($last_insert_id_array[$tmp[1]]))?$last_insert_id_array[$tmp[1]]:0;
+    				        $tmp = explode('-', $val);
+    				        $lastinsertid = (isset($last_insert_id_array[$tmp[1]])) ? $last_insert_id_array[$tmp[1]] : 0;
 							$keyfield = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
     				        $listfields[] = $keyfield;
                             $listvalues[] = $lastinsertid;
@@ -780,14 +780,14 @@ class ImportXlsx extends ModeleImports
     				    }
     				    elseif (preg_match('/^const-/', $val))
     				    {
-    				    	$tmp=explode('-', $val, 2);
+    				    	$tmp = explode('-', $val, 2);
     				    	$listfields[] = preg_replace('/^'.preg_quote($alias, '/').'\./', '', $key);
     				    	$listvalues[] = "'".$tmp[1]."'";
     				    }
     				    else
     				    {
-    				    	$this->errors[$error]['lib']='Bad value of profile setup '.$val.' for array_import_fieldshidden';
-    				    	$this->errors[$error]['type']='Import profile setup';
+    				    	$this->errors[$error]['lib'] = 'Bad value of profile setup '.$val.' for array_import_fieldshidden';
+    				    	$this->errors[$error]['type'] = 'Import profile setup';
     				    	$error++;
     				    }
     				}
@@ -796,7 +796,7 @@ class ImportXlsx extends ModeleImports
 
 				// If no error for this $alias/$tablename, we have a complete $listfields and $listvalues that are defined
 				// so we can try to make the insert or update now.
-				if (! $errorforthistable)
+				if (!$errorforthistable)
 				{
 					//print "$alias/$tablename/$listfields/$listvalues<br>";
 					if (!empty($listfields))
@@ -814,21 +814,21 @@ class ImportXlsx extends ModeleImports
 								$filters = array();
 								foreach ($updatekeys as $key) {
 									$col = $objimport->array_import_updatekeys[0][$key];
-									$key=preg_replace('/^.*\./i', '', $key);
+									$key = preg_replace('/^.*\./i', '', $key);
 									$where[] = $key.' = '.$data[$key];
 									$filters[] = $col.' = '.$data[$key];
 								}
-								$sqlSelect.= ' WHERE '.implode(' AND ', $where);
+								$sqlSelect .= ' WHERE '.implode(' AND ', $where);
 
-								$resql=$this->db->query($sqlSelect);
-								if($resql) {
+								$resql = $this->db->query($sqlSelect);
+								if ($resql) {
 									$res = $this->db->fetch_object($resql);
-									if($resql->num_rows == 1) {
+									if ($resql->num_rows == 1) {
 										$lastinsertid = $res->rowid;
 										$last_insert_id_array[$tablename] = $lastinsertid;
-									} elseif($resql->num_rows > 1) {
-										$this->errors[$error]['lib']=$langs->trans('MultipleRecordFoundWithTheseFilters', implode(', ', $filters));
-										$this->errors[$error]['type']='SQL';
+									} elseif ($resql->num_rows > 1) {
+										$this->errors[$error]['lib'] = $langs->trans('MultipleRecordFoundWithTheseFilters', implode(', ', $filters));
+										$this->errors[$error]['type'] = 'SQL';
 										$error++;
 									} else {
 										// No record found with filters, insert will be tried below
@@ -837,8 +837,8 @@ class ImportXlsx extends ModeleImports
 								else
 								{
 									//print 'E';
-									$this->errors[$error]['lib']=$this->db->lasterror();
-									$this->errors[$error]['type']='SQL';
+									$this->errors[$error]['lib'] = $this->db->lasterror();
+									$this->errors[$error]['type'] = 'SQL';
 									$error++;
 								}
 							} else {
@@ -849,13 +849,13 @@ class ImportXlsx extends ModeleImports
 								// Note: For extrafield tablename, we have in importfieldshidden_array an enty 'extra.fk_object'=>'lastrowid-tableparent' so $keyfield is 'fk_object'
 								$sqlSelect = 'SELECT rowid FROM '.$tablename;
 
-								if(empty($keyfield)) $keyfield = 'rowid';
+								if (empty($keyfield)) $keyfield = 'rowid';
 								$sqlSelect .= ' WHERE '.$keyfield.' = '.$lastinsertid;
 
-								$resql=$this->db->query($sqlSelect);
-								if($resql) {
+								$resql = $this->db->query($sqlSelect);
+								if ($resql) {
 									$res = $this->db->fetch_object($resql);
-									if($resql->num_rows == 1) {
+									if ($resql->num_rows == 1) {
 										// We have a row referencing this last foreign key, continue with UPDATE.
 									} else {
 										// No record found referencing this last foreign key,
@@ -866,8 +866,8 @@ class ImportXlsx extends ModeleImports
 								else
 								{
 									//print 'E';
-									$this->errors[$error]['lib']=$this->db->lasterror();
-									$this->errors[$error]['type']='SQL';
+									$this->errors[$error]['lib'] = $this->db->lasterror();
+									$this->errors[$error]['type'] = 'SQL';
 									$error++;
 								}
 							}
@@ -881,24 +881,24 @@ class ImportXlsx extends ModeleImports
 								foreach ($data as $key => $val) {
 									$set[] = $key.' = '.$val;
 								}
-								$sqlstart.= ' SET '.implode(', ', $set);
+								$sqlstart .= ' SET '.implode(', ', $set);
 
-								if(empty($keyfield)) $keyfield = 'rowid';
+								if (empty($keyfield)) $keyfield = 'rowid';
 								$sqlend = ' WHERE '.$keyfield.' = '.$lastinsertid;
 
 								$sql = $sqlstart.$sqlend;
 
 								// Run update request
-								$resql=$this->db->query($sql);
-								if($resql) {
+								$resql = $this->db->query($sql);
+								if ($resql) {
 									// No error, update has been done. $this->db->db->affected_rows can be 0 if data hasn't changed
 									$updatedone = true;
 								}
 								else
 								{
 									//print 'E';
-									$this->errors[$error]['lib']=$this->db->lasterror();
-									$this->errors[$error]['type']='SQL';
+									$this->errors[$error]['lib'] = $this->db->lasterror();
+									$this->errors[$error]['type'] = 'SQL';
 									$error++;
 								}
 							}
@@ -909,13 +909,13 @@ class ImportXlsx extends ModeleImports
 							// Build SQL INSERT request
 							$sqlstart = 'INSERT INTO '.$tablename.'('.implode(', ', $listfields).', import_key';
 							$sqlend = ') VALUES('.implode(', ', $listvalues).", '".$importid."'";
-							if (! empty($tablewithentity_cache[$tablename])) {
-								$sqlstart.= ', entity';
-								$sqlend.= ', '.$conf->entity;
+							if (!empty($tablewithentity_cache[$tablename])) {
+								$sqlstart .= ', entity';
+								$sqlend .= ', '.$conf->entity;
 							}
-							if (! empty($objimport->array_import_tables_creator[0][$alias])) {
-								$sqlstart.= ', '.$objimport->array_import_tables_creator[0][$alias];
-								$sqlend.=', '.$user->id;
+							if (!empty($objimport->array_import_tables_creator[0][$alias])) {
+								$sqlstart .= ', '.$objimport->array_import_tables_creator[0][$alias];
+								$sqlend .= ', '.$user->id;
 							}
 							$sql = $sqlstart.$sqlend.')';
 							dol_syslog("import_xlsx.modules", LOG_DEBUG);
@@ -923,7 +923,7 @@ class ImportXlsx extends ModeleImports
 							// Run insert request
 							if ($sql)
 							{
-								$resql=$this->db->query($sql);
+								$resql = $this->db->query($sql);
 								if ($resql)
 								{
 								    $last_insert_id_array[$tablename] = $this->db->last_insert_id($tablename); // store the last inserted auto_increment id for each table, so that child tables can be inserted with the appropriate id. This must be done just after the INSERT request, else we risk losing the id (because another sql query will be issued somewhere in Dolibarr).
@@ -932,8 +932,8 @@ class ImportXlsx extends ModeleImports
 								else
 								{
 									//print 'E';
-									$this->errors[$error]['lib']=$this->db->lasterror();
-									$this->errors[$error]['type']='SQL';
+									$this->errors[$error]['lib'] = $this->db->lasterror();
+									$this->errors[$error]['type'] = 'SQL';
 									$error++;
 								}
 							}
@@ -948,8 +948,8 @@ class ImportXlsx extends ModeleImports
 			    if ($error) break;
 			}
 
-			if($updatedone) $this->nbupdate++;
-			if($insertdone) $this->nbinsert++;
+			if ($updatedone) $this->nbupdate++;
+			if ($insertdone) $this->nbinsert++;
 		}
 
 		return 1;

+ 112 - 112
htdocs/core/modules/modProduct.class.php

@@ -29,7 +29,7 @@
  *	\ingroup    produit
  *	\brief      File to describe module to manage catalog of predefined products
  */
-include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php';
+include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
 
 
 /**
@@ -59,25 +59,25 @@ class modProduct extends DolibarrModules
 		$this->version = 'dolibarr';
 
 		$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
-		$this->picto='product';
+		$this->picto = 'product';
 
 		// Data directories to create when module is enabled
 		$this->dirs = array("/product/temp");
 
 		// Dependencies
-		$this->hidden = false;			// A condition to hide module
-		$this->depends = array();		// List of module class names as string that must be enabled if this module is enabled
-		$this->requiredby = array("modStock","modBarcode","modProductBatch","modVariants");	// List of module ids to disable if this one is disabled
-		$this->conflictwith = array();	// List of module class names as string this module is in conflict with
-		$this->phpmin = array(5,4);		// Minimum version of PHP required by module
+		$this->hidden = false; // A condition to hide module
+		$this->depends = array(); // List of module class names as string that must be enabled if this module is enabled
+		$this->requiredby = array("modStock", "modBarcode", "modProductBatch", "modVariants"); // List of module ids to disable if this one is disabled
+		$this->conflictwith = array(); // List of module class names as string this module is in conflict with
+		$this->phpmin = array(5, 4); // Minimum version of PHP required by module
 
 		// Config pages
 		$this->config_page_url = array("product.php@product");
-		$this->langfiles = array("products","companies","stocks","bills");
+		$this->langfiles = array("products", "companies", "stocks", "bills");
 
 		// Constants
 		$this->const = array();
-		$r=0;
+		$r = 0;
 
 		$this->const[$r][0] = "PRODUCT_CODEPRODUCT_ADDON";
 		$this->const[$r][1] = "chaine";
@@ -102,15 +102,15 @@ class modProduct extends DolibarrModules
 
 		// Boxes
 		$this->boxes = array(
-			0=>array('file'=>'box_produits.php','enabledbydefaulton'=>'Home'),
-			1=>array('file'=>'box_produits_alerte_stock.php','enabledbydefaulton'=>''),
-			2=>array('file'=>'box_graph_product_distribution.php','enabledbydefaulton'=>'Home')
+			0=>array('file'=>'box_produits.php', 'enabledbydefaulton'=>'Home'),
+			1=>array('file'=>'box_produits_alerte_stock.php', 'enabledbydefaulton'=>''),
+			2=>array('file'=>'box_graph_product_distribution.php', 'enabledbydefaulton'=>'Home')
 		);
 
 		// Permissions
 		$this->rights = array();
 		$this->rights_class = 'produit';
-		$r=0;
+		$r = 0;
 
 		$this->rights[$r][0] = 31; // id de la permission
 		$this->rights[$r][1] = 'Read products'; // libelle de la permission
@@ -133,7 +133,7 @@ class modProduct extends DolibarrModules
 		$this->rights[$r][4] = 'supprimer';
         $r++;
 
-		$this->rights[$r][0] = 38;	// Must be same permission than in service module
+		$this->rights[$r][0] = 38; // Must be same permission than in service module
 		$this->rights[$r][1] = 'Export products';
 		$this->rights[$r][2] = 'r';
 		$this->rights[$r][3] = 0;
@@ -150,7 +150,7 @@ class modProduct extends DolibarrModules
         // Menus
         //-------
 
-        $this->menu = 1;        // This module adds menu entries. They are coded into menu manager.
+        $this->menu = 1; // This module adds menu entries. They are coded into menu manager.
 		/* We can't enable this here because it must be enabled in both product and service module and this creates duplicate inserts
 		$r=0;
 		$this->menu[$r]=array(	'fk_menu'=>'fk_mainmenu=home,fk_leftmenu=admintools',		    // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
@@ -398,28 +398,28 @@ class modProduct extends DolibarrModules
             'p.surface_units' => "SurfaceUnit",
             'p.volume' => "Volume",
 			'p.volume_units' => "VolumeUnits",
-			'p.duration' => "Duration",//duration of service
+			'p.duration' => "Duration", //duration of service
 			'p.finished' => 'Nature',
-			'p.price' => "SellingPriceHT",//without
+			'p.price' => "SellingPriceHT", //without
 			'p.price_min' => "MinPrice",
-			'p.price_ttc' => "SellingPriceTTC",//with tax
+			'p.price_ttc' => "SellingPriceTTC", //with tax
 			'p.price_min_ttc' => "SellingMinPriceTTC",
-			'p.price_base_type' => "PriceBaseType",//price base: with-tax (TTC) or without (HT) tax. Displays accordingly in Product card
+			'p.price_base_type' => "PriceBaseType", //price base: with-tax (TTC) or without (HT) tax. Displays accordingly in Product card
 			'p.tva_tx' => 'VATRate',
 			'p.datec' => 'DateCreation',
 			'p.cost_price' => "CostPrice",
 		);
         if (!empty($conf->stock->enabled)) {//if Stock module enabled
             $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array(
-                'p.seuil_stock_alerte' => 'StockLimit',//lower limit for warning
-                'p.pmp' => 'PMPValue',//weighted average price
+                'p.seuil_stock_alerte' => 'StockLimit', //lower limit for warning
+                'p.pmp' => 'PMPValue', //weighted average price
                 'p.desiredstock' => 'DesiredStock'//desired stock for replenishment feature
             ));
         }
 
         $this->import_convertvalue_array[$r] = array(
         	    'p.weight_units' => array(
-	        	    	'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+	        	    	'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
 						'classfile' => '/core/class/cunits.class.php',
 						'class' => 'CUnits',
 						'method' => 'fetch',
@@ -427,7 +427,7 @@ class modProduct extends DolibarrModules
 						'dict' => 'DictionaryMeasuringUnits'
 				),
 				'p.length_units' => array(
-					'rule' => 'fetchscalefromcodeunits',				// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+					'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
 						'classfile' => '/core/class/cunits.class.php',
 						'class' => 'CUnits',
 						'method' => 'fetch',
@@ -435,7 +435,7 @@ class modProduct extends DolibarrModules
 						'dict' => 'DictionaryMeasuringUnits'
 				),
 				'p.width_units' => array(
-						'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+						'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
 						'classfile' => '/core/class/cunits.class.php',
 						'class' => 'CUnits',
 						'method' => 'fetch',
@@ -443,7 +443,7 @@ class modProduct extends DolibarrModules
 						'dict' => 'DictionaryMeasuringUnits'
 				),
 				'p.height_units' => array(
-						'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+						'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
 						'classfile' => '/core/class/cunits.class.php',
 						'class' => 'CUnits',
 						'method' => 'fetch',
@@ -451,7 +451,7 @@ class modProduct extends DolibarrModules
 						'dict' => 'DictionaryMeasuringUnits'
 				),
 				'p.surface_units' => array(
-						'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+						'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
 						'classfile' => '/core/class/cunits.class.php',
 						'class' => 'CUnits',
 						'method' => 'fetch',
@@ -459,7 +459,7 @@ class modProduct extends DolibarrModules
 						'dict' => 'DictionaryMeasuringUnits'
 				),
 				'p.volume_units' => array(
-						'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+						'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
 						'classfile' => '/core/class/cunits.class.php',
 						'class' => 'CUnits',
 						'method' => 'fetch',
@@ -475,29 +475,29 @@ class modProduct extends DolibarrModules
                 )
 		);
 
-		if (! empty($conf->fournisseur->enabled) || !empty($conf->margin->enabled)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.cost_price'=>'CostPrice'));
-		if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.recuperableonly'=>'NPR'));
-		if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.localtax1_tx'=>'LT1', 'p.localtax1_type'=>'LT1Type'));
-		if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.localtax2_tx'=>'LT2', 'p.localtax2_type'=>'LT2Type'));
-		if (! empty($conf->barcode->enabled)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.barcode'=>'BarCode'));
-		if (! empty($conf->global->PRODUCT_USE_UNITS)) $this->import_fields_array[$r]['p.fk_unit'] = 'Unit';
+		if (!empty($conf->fournisseur->enabled) || !empty($conf->margin->enabled)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.cost_price'=>'CostPrice'));
+		if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.recuperableonly'=>'NPR'));
+		if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.localtax1_tx'=>'LT1', 'p.localtax1_type'=>'LT1Type'));
+		if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.localtax2_tx'=>'LT2', 'p.localtax2_type'=>'LT2Type'));
+		if (!empty($conf->barcode->enabled)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.barcode'=>'BarCode'));
+		if (!empty($conf->global->PRODUCT_USE_UNITS)) $this->import_fields_array[$r]['p.fk_unit'] = 'Unit';
 		// Add extra fields
-		$import_extrafield_sample=array();
-		$sql="SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'product' AND entity IN (0, ".$conf->entity.")";
-		$resql=$this->db->query($sql);
+		$import_extrafield_sample = array();
+		$sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'product' AND entity IN (0, ".$conf->entity.")";
+		$resql = $this->db->query($sql);
 		if ($resql)    // This can fail when class is used on old database (during migration for example)
 		{
-		    while ($obj=$this->db->fetch_object($resql))
+		    while ($obj = $this->db->fetch_object($resql))
 		    {
-		        $fieldname='extra.'.$obj->name;
-		        $fieldlabel=ucfirst($obj->label);
-		        $this->import_fields_array[$r][$fieldname]=$fieldlabel.($obj->fieldrequired?'*':'');
-		        $import_extrafield_sample[$fieldname]=$fieldlabel;
+		        $fieldname = 'extra.'.$obj->name;
+		        $fieldlabel = ucfirst($obj->label);
+		        $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : '');
+		        $import_extrafield_sample[$fieldname] = $fieldlabel;
 		    }
 		}
 		// End add extra fields
-		$this->import_fieldshidden_array[$r]=array('extra.fk_object'=>'lastrowid-'.MAIN_DB_PREFIX.'product');    // aliastable.field => ('user->id' or 'lastrowid-'.tableparent)
-		$this->import_regex_array[$r]=array(
+		$this->import_fieldshidden_array[$r] = array('extra.fk_object'=>'lastrowid-'.MAIN_DB_PREFIX.'product'); // aliastable.field => ('user->id' or 'lastrowid-'.tableparent)
+		$this->import_regex_array[$r] = array(
             'p.ref' => '[^ ]',
             'p.price_base_type' => '\AHT\z|\ATTC\z',
             'p.tosell' => '^[0|1]$',
@@ -523,7 +523,7 @@ class modProduct extends DolibarrModules
             'p.price_ttc' => "110",
 			'p.price_min_ttc' => "110",
             'p.price_base_type' => "HT (show/use price excl. tax) / TTC (show/use price incl. tax)",
-            'p.tva_tx' => '10',	// tax rate eg: 10. Must match numerically one of the tax rates defined for your country'
+            'p.tva_tx' => '10', // tax rate eg: 10. Must match numerically one of the tax rates defined for your country'
             'p.tosell' => "0 (not for sale to customer, eg. raw material) / 1 (for sale)",
             'p.tobuy' => "0 (not for purchase from supplier, eg. virtual product) / 1 (for purchase)",
             'p.fk_product_type' => "0 (product) / 1 (service)",
@@ -534,17 +534,17 @@ class modProduct extends DolibarrModules
             'p.accountancy_code_sell_export' => "",
             'p.accountancy_code_buy' => "",
             'p.weight' => "",
-			'p.weight_units' => 'kg',	// Use a unit of measure from the dictionary. g/Kg/T etc....matches field "Short label" for unit type "weight" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.weight_units' => 'kg', // Use a unit of measure from the dictionary. g/Kg/T etc....matches field "Short label" for unit type "weight" in table "' . MAIN_DB_PREFIX . 'c_units',
             'p.length' => "",
-			'p.length_units' => 'm', 	// Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.length_units' => 'm', // Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
             'p.width' => "",
-			'p.width_units' => 'm',		// Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.width_units' => 'm', // Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
             'p.height' => "",
-			'p.height_units' => 'm',	// Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.height_units' => 'm', // Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
             'p.surface' => "",
-			'p.surface_units' => 'm2',	// Use a unit of measure from the dictionary. m2/cm2/mm2 etc....matches field "Short label" for unit type "surface" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.surface_units' => 'm2', // Use a unit of measure from the dictionary. m2/cm2/mm2 etc....matches field "Short label" for unit type "surface" in table "' . MAIN_DB_PREFIX . 'c_units',
             'p.volume' => "",
-			'p.volume_units' => 'm3',	//Use a unit of measure from the dictionary. m3/cm3/mm3 etc....matches field "Short label" for unit type "volume" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.volume_units' => 'm3', //Use a unit of measure from the dictionary. m3/cm3/mm3 etc....matches field "Short label" for unit type "volume" in table "' . MAIN_DB_PREFIX . 'c_units',
             'p.finished' => '0 (raw material) / 1 (finished goods)'
         );
         //clauses copied from import_fields_array
@@ -553,16 +553,16 @@ class modProduct extends DolibarrModules
                 'p.pmp' => '0',
                 'p.desiredstock' => ''
             ));
-        if (! empty($conf->fournisseur->enabled) || !empty($conf->margin->enabled)) $import_sample=array_merge($import_sample, array('p.cost_price'=>'90'));
-        if (is_object($mysoc) && $mysoc->useNPR()) $import_sample=array_merge($import_sample, array('p.recuperableonly'=>'0'));
-        if (is_object($mysoc) && $mysoc->useLocalTax(1)) $import_sample=array_merge($import_sample, array('p.localtax1_tx'=>'', 'p.localtax1_type'=>''));
-        if (is_object($mysoc) && $mysoc->useLocalTax(2)) $import_sample=array_merge($import_sample, array('p.localtax2_tx'=>'', 'p.localtax2_type'=>''));
-        if (! empty($conf->barcode->enabled)) $import_sample=array_merge($import_sample, array('p.barcode'=>''));
-        if (! empty($conf->global->PRODUCT_USE_UNITS)) {
+        if (!empty($conf->fournisseur->enabled) || !empty($conf->margin->enabled)) $import_sample = array_merge($import_sample, array('p.cost_price'=>'90'));
+        if (is_object($mysoc) && $mysoc->useNPR()) $import_sample = array_merge($import_sample, array('p.recuperableonly'=>'0'));
+        if (is_object($mysoc) && $mysoc->useLocalTax(1)) $import_sample = array_merge($import_sample, array('p.localtax1_tx'=>'', 'p.localtax1_type'=>''));
+        if (is_object($mysoc) && $mysoc->useLocalTax(2)) $import_sample = array_merge($import_sample, array('p.localtax2_tx'=>'', 'p.localtax2_type'=>''));
+        if (!empty($conf->barcode->enabled)) $import_sample = array_merge($import_sample, array('p.barcode'=>''));
+        if (!empty($conf->global->PRODUCT_USE_UNITS)) {
             $import_sample = array_merge(
                 $import_sample,
                 array(
-                    'p.fk_unit' => 'use a unit of measure from the dictionary. G/KG/M2/M3 etc....matches field "code" in table "' . MAIN_DB_PREFIX . 'c_units"'
+                    'p.fk_unit' => 'use a unit of measure from the dictionary. G/KG/M2/M3 etc....matches field "code" in table "'.MAIN_DB_PREFIX.'c_units"'
                 )
             );
 
@@ -577,21 +577,21 @@ class modProduct extends DolibarrModules
 				)
 			));
 		}
-		$this->import_examplevalues_array[$r]=array_merge($import_sample, $import_extrafield_sample);
+		$this->import_examplevalues_array[$r] = array_merge($import_sample, $import_extrafield_sample);
         $this->import_updatekeys_array[$r] = array('p.ref'=>'Ref');
-        if (! empty($conf->barcode->enabled)) $this->import_updatekeys_array[$r]=array_merge($this->import_updatekeys_array[$r], array('p.barcode'=>'BarCode'));//only show/allow barcode as update key if Barcode module enabled
+        if (!empty($conf->barcode->enabled)) $this->import_updatekeys_array[$r] = array_merge($this->import_updatekeys_array[$r], array('p.barcode'=>'BarCode')); //only show/allow barcode as update key if Barcode module enabled
 
-		if (! empty($conf->fournisseur->enabled))
+		if (!empty($conf->fournisseur->enabled))
 		{
 			// Import suppliers prices (note: this code is duplicated in module Service)
 			$r++;
-			$this->import_code[$r]=$this->rights_class.'_supplierprices';
-			$this->import_label[$r]="SuppliersPricesOfProductsOrServices";	// Translation key
-			$this->import_icon[$r]=$this->picto;
-			$this->import_entities_array[$r]=array();		// We define here only fields that use another icon that the one defined into import_icon
-			$this->import_tables_array[$r]=array('sp'=>MAIN_DB_PREFIX.'product_fournisseur_price');
-			$this->import_tables_creator_array[$r]=array('sp'=>'fk_user');
-			$this->import_fields_array[$r]=array(//field order as per structure of table llx_product_fournisseur_price, without optional fields
+			$this->import_code[$r] = $this->rights_class.'_supplierprices';
+			$this->import_label[$r] = "SuppliersPricesOfProductsOrServices"; // Translation key
+			$this->import_icon[$r] = $this->picto;
+			$this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon
+			$this->import_tables_array[$r] = array('sp'=>MAIN_DB_PREFIX.'product_fournisseur_price');
+			$this->import_tables_creator_array[$r] = array('sp'=>'fk_user');
+			$this->import_fields_array[$r] = array(//field order as per structure of table llx_product_fournisseur_price, without optional fields
 			    'sp.fk_product'=>"ProductOrService*",
                 'sp.fk_soc' => "Supplier*",
                 'sp.ref_fourn' => 'SupplierRef',
@@ -601,19 +601,19 @@ class modProduct extends DolibarrModules
                 'sp.delivery_time_days' => 'DeliveryDelay',
                 'sp.supplier_reputation' => 'SupplierReputation'
 			);
-			if (is_object($mysoc) && $mysoc->useNPR())       $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('sp.recuperableonly'=>'VATNPR'));
-			if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('sp.localtax1_tx'=>'LT1', 'sp.localtax1_type'=>'LT1Type'));
-			if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('sp.localtax2_tx'=>'LT2', 'sp.localtax2_type'=>'LT2Type'));
-            $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array(
+			if (is_object($mysoc) && $mysoc->useNPR())       $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('sp.recuperableonly'=>'VATNPR'));
+			if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('sp.localtax1_tx'=>'LT1', 'sp.localtax1_type'=>'LT1Type'));
+			if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('sp.localtax2_tx'=>'LT2', 'sp.localtax2_type'=>'LT2Type'));
+            $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array(
 					'sp.price'=>"PriceQtyMinHT*",
-					'sp.unitprice'=>'UnitPriceHT*',	// TODO Make this field not required and calculate it from price and qty
+					'sp.unitprice'=>'UnitPriceHT*', // TODO Make this field not required and calculate it from price and qty
 					'sp.remise_percent'=>'DiscountQtyMin'
 			));
 
             if ($conf->multicurrency->enabled)
             {
-                $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array(
-                    'sp.fk_multicurrency'=>'CurrencyCodeId',//ideally this should be automatically obtained from the CurrencyCode on the next line
+                $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array(
+                    'sp.fk_multicurrency'=>'CurrencyCodeId', //ideally this should be automatically obtained from the CurrencyCode on the next line
                     'sp.multicurrency_code'=>'CurrencyCode',
                     'sp.multicurrency_tx'=>'CurrencyRate',
                     'sp.multicurrency_unitprice'=>'CurrencyUnitPrice',
@@ -621,12 +621,12 @@ class modProduct extends DolibarrModules
                 ));
             }
 
-			$this->import_convertvalue_array[$r]=array(
-					'sp.fk_soc'=>array('rule'=>'fetchidfromref','classfile'=>'/societe/class/societe.class.php','class'=>'Societe','method'=>'fetch','element'=>'ThirdParty'),
-					'sp.fk_product'=>array('rule'=>'fetchidfromref','classfile'=>'/product/class/product.class.php','class'=>'Product','method'=>'fetch','element'=>'Product')
+			$this->import_convertvalue_array[$r] = array(
+					'sp.fk_soc'=>array('rule'=>'fetchidfromref', 'classfile'=>'/societe/class/societe.class.php', 'class'=>'Societe', 'method'=>'fetch', 'element'=>'ThirdParty'),
+					'sp.fk_product'=>array('rule'=>'fetchidfromref', 'classfile'=>'/product/class/product.class.php', 'class'=>'Product', 'method'=>'fetch', 'element'=>'Product')
 			);
 
-			$this->import_examplevalues_array[$r]=array(
+			$this->import_examplevalues_array[$r] = array(
                 'sp.fk_product' => "PRODUCT_REF or id:123456",
                 'sp.fk_soc' => "My Supplier",
                 'sp.ref_fourn' => "XYZ-F123456",
@@ -639,9 +639,9 @@ class modProduct extends DolibarrModules
                 'sp.delivery_time_days' => '5',
                 'sp.supplier_reputation' => 'FAVORITE / NOTTHGOOD / DONOTORDER'
 			);
-            if (is_object($mysoc) && $mysoc->useNPR()) $this->import_examplevalues_array[$r]=array_merge($this->import_examplevalues_array[$r], array('sp.recuperableonly'=>''));
-            if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_examplevalues_array[$r]=array_merge($this->import_examplevalues_array[$r], array('sp.localtax1_tx'=>'LT1', 'sp.localtax1_type'=>'LT1Type'));
-            if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_examplevalues_array[$r]=array_merge($this->import_examplevalues_array[$r], array('sp.localtax2_tx'=>'LT2', 'sp.localtax2_type'=>'LT2Type'));
+            if (is_object($mysoc) && $mysoc->useNPR()) $this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array('sp.recuperableonly'=>''));
+            if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array('sp.localtax1_tx'=>'LT1', 'sp.localtax1_type'=>'LT1Type'));
+            if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array('sp.localtax2_tx'=>'LT2', 'sp.localtax2_type'=>'LT2Type'));
             $this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array(
                 'sp.price' => "50.00",
                 'sp.unitprice' => '10',
@@ -650,7 +650,7 @@ class modProduct extends DolibarrModules
             ));
             if ($conf->multicurrency->enabled)
             {
-                $this->import_examplevalues_array[$r]=array_merge($this->import_examplevalues_array[$r], array(
+                $this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array(
                     'sp.fk_multicurrency'=>'eg: 2, rowid for code of multicurrency currency',
                     'sp.multicurrency_code'=>'GBP',
                     'sp.multicurrency_tx'=>'1.12345',
@@ -660,32 +660,32 @@ class modProduct extends DolibarrModules
                 ));
             }
 
-			$this->import_updatekeys_array[$r]=array('sp.fk_product'=>'ProductOrService','sp.ref_fourn'=>'SupplierRef','sp.fk_soc'=>'Supplier');
+			$this->import_updatekeys_array[$r] = array('sp.fk_product'=>'ProductOrService', 'sp.ref_fourn'=>'SupplierRef', 'sp.fk_soc'=>'Supplier');
 		}
 
-		if (! empty($conf->global->PRODUIT_MULTIPRICES))
+		if (!empty($conf->global->PRODUIT_MULTIPRICES))
 		{
 			// Import products multiprices
 			$r++;
-			$this->import_code[$r]=$this->rights_class.'_multiprice';
-			$this->import_label[$r]="ProductsOrServiceMultiPrice";	// Translation key
-			$this->import_icon[$r]=$this->picto;
-			$this->import_entities_array[$r]=array();		// We define here only fields that use another icon that the one defined into import_icon
-			$this->import_tables_array[$r]=array('pr'=>MAIN_DB_PREFIX.'product_price');
-			$this->import_tables_creator_array[$r]=array('pr'=>'fk_user_author');	// Fields to store import user id
-			$this->import_fields_array[$r]=array('pr.fk_product'=>"ProductOrService*",
-				'pr.price_base_type'=>"PriceBase",'pr.price_level'=>"PriceLevel",
-				'pr.price'=>"PriceLevelUnitPriceHT",'pr.price_ttc'=>"PriceLevelUnitPriceTTC",
-				'pr.price_min'=>"MinPriceLevelUnitPriceHT",'pr.price_min_ttc'=>"MinPriceLevelUnitPriceTTC",
+			$this->import_code[$r] = $this->rights_class.'_multiprice';
+			$this->import_label[$r] = "ProductsOrServiceMultiPrice"; // Translation key
+			$this->import_icon[$r] = $this->picto;
+			$this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon
+			$this->import_tables_array[$r] = array('pr'=>MAIN_DB_PREFIX.'product_price');
+			$this->import_tables_creator_array[$r] = array('pr'=>'fk_user_author'); // Fields to store import user id
+			$this->import_fields_array[$r] = array('pr.fk_product'=>"ProductOrService*",
+				'pr.price_base_type'=>"PriceBase", 'pr.price_level'=>"PriceLevel",
+				'pr.price'=>"PriceLevelUnitPriceHT", 'pr.price_ttc'=>"PriceLevelUnitPriceTTC",
+				'pr.price_min'=>"MinPriceLevelUnitPriceHT", 'pr.price_min_ttc'=>"MinPriceLevelUnitPriceTTC",
 				'pr.date_price'=>'DateCreation*');
-			if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) $this->import_fields_array[$r]['pr.tva_tx']='VATRate';
-			if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('pr.recuperableonly'=>'NPR'));
-			$this->import_regex_array[$r]=array('pr.datec'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$','pr.recuperableonly'=>'^[0|1]$');
-			$this->import_convertvalue_array[$r]=array(
-			    'pr.fk_product'=>array('rule'=>'fetchidfromref','classfile'=>'/product/class/product.class.php','class'=>'Product','method'=>'fetch','element'=>'Product')
+			if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) $this->import_fields_array[$r]['pr.tva_tx'] = 'VATRate';
+			if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('pr.recuperableonly'=>'NPR'));
+			$this->import_regex_array[$r] = array('pr.datec'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$', 'pr.recuperableonly'=>'^[0|1]$');
+			$this->import_convertvalue_array[$r] = array(
+			    'pr.fk_product'=>array('rule'=>'fetchidfromref', 'classfile'=>'/product/class/product.class.php', 'class'=>'Product', 'method'=>'fetch', 'element'=>'Product')
 			);
-			$this->import_examplevalues_array[$r]=array('pr.fk_product'=>"PRODUCT_REF or id:123456",
-				'pr.price_base_type'=>"HT (for excl tax) or TTC (for inc tax)",'pr.price_level'=>"1",
+			$this->import_examplevalues_array[$r] = array('pr.fk_product'=>"PRODUCT_REF or id:123456",
+				'pr.price_base_type'=>"HT (for excl tax) or TTC (for inc tax)", 'pr.price_level'=>"1",
 				'pr.price'=>"100", 'pr.price_ttc'=>"110",
 				'pr.price_min'=>"100", 'pr.price_min_ttc'=>"110",
 				'pr.tva_tx'=>'20',
@@ -693,23 +693,23 @@ class modProduct extends DolibarrModules
 				'pr.date_price'=>'2013-04-10');
 		}
 
-		if (! empty($conf->global->MAIN_MULTILANGS))
+		if (!empty($conf->global->MAIN_MULTILANGS))
 		{
 		    // Import translations of product names and descriptions
 		    $r++;
-		    $this->import_code[$r]=$this->rights_class.'_languages';
-		    $this->import_label[$r]="ProductsOrServicesTranslations";
-			$this->import_icon[$r]=$this->picto;
-			$this->import_entities_array[$r]=array();		// We define here only fields that use another icon that the one defined into import_icon
-		    $this->import_tables_array[$r]=array('l'=>MAIN_DB_PREFIX.'product_lang');
+		    $this->import_code[$r] = $this->rights_class.'_languages';
+		    $this->import_label[$r] = "ProductsOrServicesTranslations";
+			$this->import_icon[$r] = $this->picto;
+			$this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon
+		    $this->import_tables_array[$r] = array('l'=>MAIN_DB_PREFIX.'product_lang');
 			// multiline translation, one line per translation
-			$this->import_fields_array[$r]=array('l.fk_product'=>'ProductOrService*', 'l.lang'=>'Language*', 'l.label'=>'TranslatedLabel', 'l.description'=>'TranslatedDescription');
+			$this->import_fields_array[$r] = array('l.fk_product'=>'ProductOrService*', 'l.lang'=>'Language*', 'l.label'=>'TranslatedLabel', 'l.description'=>'TranslatedDescription');
 			//$this->import_fields_array[$r]['l.note']='TranslatedNote';
-			$this->import_convertvalue_array[$r]=array(
-					'l.fk_product'=>array('rule'=>'fetchidfromref','classfile'=>'/product/class/product.class.php','class'=>'Product','method'=>'fetch','element'=>'Product')
+			$this->import_convertvalue_array[$r] = array(
+					'l.fk_product'=>array('rule'=>'fetchidfromref', 'classfile'=>'/product/class/product.class.php', 'class'=>'Product', 'method'=>'fetch', 'element'=>'Product')
 			);
-			$this->import_examplevalues_array[$r]=array('l.fk_product'=>'PRODUCT_REF or id:123456','l.lang'=>'en_US','l.label'=>'Label in en_US','l.description'=>'Desc in en_US');
-			$this->import_updatekeys_array[$r]=array('l.fk_product'=>'ProductOrService','l.lang'=>'Language');
+			$this->import_examplevalues_array[$r] = array('l.fk_product'=>'PRODUCT_REF or id:123456', 'l.lang'=>'en_US', 'l.label'=>'Label in en_US', 'l.description'=>'Desc in en_US');
+			$this->import_updatekeys_array[$r] = array('l.fk_product'=>'ProductOrService', 'l.lang'=>'Language');
 		}
 	}
 

+ 112 - 112
htdocs/core/modules/modService.class.php

@@ -26,7 +26,7 @@
  *	\ingroup    service
  *	\brief      Fichier de description et activation du module Service
  */
-include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php';
+include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
 
 
 /**
@@ -57,35 +57,35 @@ class modService extends DolibarrModules
 		$this->version = 'dolibarr';
 
 		$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
-		$this->picto='service';
+		$this->picto = 'service';
 
 		// Data directories to create when module is enabled
 		$this->dirs = array("/product/temp");
 
 		// Dependencies
-		$this->hidden = false;			// A condition to hide module
-		$this->depends = array();		// List of module class names as string that must be enabled if this module is enabled
-		$this->requiredby = array();	// List of module ids to disable if this one is disabled
-		$this->conflictwith = array();	// List of module class names as string this module is in conflict with
-		$this->phpmin = array(5,4);		// Minimum version of PHP required by module
+		$this->hidden = false; // A condition to hide module
+		$this->depends = array(); // List of module class names as string that must be enabled if this module is enabled
+		$this->requiredby = array(); // List of module ids to disable if this one is disabled
+		$this->conflictwith = array(); // List of module class names as string this module is in conflict with
+		$this->phpmin = array(5, 4); // Minimum version of PHP required by module
 
 		// Config pages
 		$this->config_page_url = array("product.php@product");
-		$this->langfiles = array("products","companies","stocks","bills");
+		$this->langfiles = array("products", "companies", "stocks", "bills");
 
 		// Constants
 		$this->const = array();
 
 		// Boxes
 		$this->boxes = array(
-			0=>array('file'=>'box_services_contracts.php','enabledbydefaulton'=>'Home'),
-			1=>array('file'=>'box_graph_product_distribution.php','enabledbydefaulton'=>'Home')
+			0=>array('file'=>'box_services_contracts.php', 'enabledbydefaulton'=>'Home'),
+			1=>array('file'=>'box_graph_product_distribution.php', 'enabledbydefaulton'=>'Home')
 		);
 
 		// Permissions
 		$this->rights = array();
 		$this->rights_class = 'service';
-		$r=0;
+		$r = 0;
 
 		$this->rights[$r][0] = 531; // id de la permission
 		$this->rights[$r][1] = 'Read services'; // libelle de la permission
@@ -108,7 +108,7 @@ class modService extends DolibarrModules
 		$this->rights[$r][4] = 'supprimer';
         $r++;
 
-		$this->rights[$r][0] = 538;	// Must be same permission than in product module
+		$this->rights[$r][0] = 538; // Must be same permission than in product module
 		$this->rights[$r][1] = 'Export services';
 		$this->rights[$r][2] = 'r';
 		$this->rights[$r][3] = 0;
@@ -117,7 +117,7 @@ class modService extends DolibarrModules
 
 		// Menus
 		//-------
-		$this->menu = 1;        // This module add menu entries. They are coded into menu manager.
+		$this->menu = 1; // This module add menu entries. They are coded into menu manager.
 		/* We can't enable this here because it must be enabled in both product and service module and this creates duplicate inserts
 		 $r=0;
 		 $this->menu[$r]=array(	'fk_menu'=>'fk_mainmenu=home,fk_leftmenu=admintools',		    // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
@@ -367,28 +367,28 @@ class modService extends DolibarrModules
         	'p.surface_units' => "SurfaceUnit",
         	'p.volume' => "Volume",
         	'p.volume_units' => "VolumeUnits",
-        	'p.duration' => "Duration",//duration of service
+        	'p.duration' => "Duration", //duration of service
         	'p.finished' => 'Nature',
-        	'p.price' => "SellingPriceHT",//without
+        	'p.price' => "SellingPriceHT", //without
         	'p.price_min' => "MinPrice",
-        	'p.price_ttc' => "SellingPriceTTC",//with tax
+        	'p.price_ttc' => "SellingPriceTTC", //with tax
         	'p.price_min_ttc' => "SellingMinPriceTTC",
-        	'p.price_base_type' => "PriceBaseType",//price base: with-tax (TTC) or without (HT) tax. Displays accordingly in Product card
+        	'p.price_base_type' => "PriceBaseType", //price base: with-tax (TTC) or without (HT) tax. Displays accordingly in Product card
         	'p.tva_tx' => 'VATRate',
         	'p.datec' => 'DateCreation',
         	'p.cost_price' => "CostPrice",
 		);
         if (!empty($conf->stock->enabled)) {//if Stock module enabled
         	$this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array(
-        		'p.seuil_stock_alerte' => 'StockLimit',//lower limit for warning
-        		'p.pmp' => 'PMPValue',//weighted average price
+        		'p.seuil_stock_alerte' => 'StockLimit', //lower limit for warning
+        		'p.pmp' => 'PMPValue', //weighted average price
         		'p.desiredstock' => 'DesiredStock'//desired stock for replenishment feature
         	));
         }
 
         $this->import_convertvalue_array[$r] = array(
         	'p.weight_units' => array(
-        		'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+        		'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
         		'classfile' => '/core/class/cunits.class.php',
         		'class' => 'CUnits',
         		'method' => 'fetch',
@@ -396,7 +396,7 @@ class modService extends DolibarrModules
         		'dict' => 'DictionaryMeasuringUnits'
         	),
         	'p.length_units' => array(
-        		'rule' => 'fetchscalefromcodeunits',				// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+        		'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
         		'classfile' => '/core/class/cunits.class.php',
         		'class' => 'CUnits',
         		'method' => 'fetch',
@@ -404,7 +404,7 @@ class modService extends DolibarrModules
         		'dict' => 'DictionaryMeasuringUnits'
         	),
         	'p.width_units' => array(
-        		'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+        		'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
         		'classfile' => '/core/class/cunits.class.php',
         		'class' => 'CUnits',
         		'method' => 'fetch',
@@ -412,7 +412,7 @@ class modService extends DolibarrModules
         		'dict' => 'DictionaryMeasuringUnits'
         	),
         	'p.height_units' => array(
-        		'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+        		'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
         		'classfile' => '/core/class/cunits.class.php',
         		'class' => 'CUnits',
         		'method' => 'fetch',
@@ -420,7 +420,7 @@ class modService extends DolibarrModules
         		'dict' => 'DictionaryMeasuringUnits'
         	),
         	'p.surface_units' => array(
-        		'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+        		'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
         		'classfile' => '/core/class/cunits.class.php',
         		'class' => 'CUnits',
         		'method' => 'fetch',
@@ -428,7 +428,7 @@ class modService extends DolibarrModules
         		'dict' => 'DictionaryMeasuringUnits'
         	),
         	'p.volume_units' => array(
-        		'rule' => 'fetchscalefromcodeunits',			// Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
+        		'rule' => 'fetchscalefromcodeunits', // Switch this to fetchidfromcodeunits when we will store id instead of scale in product table
         		'classfile' => '/core/class/cunits.class.php',
         		'class' => 'CUnits',
         		'method' => 'fetch',
@@ -443,29 +443,29 @@ class modService extends DolibarrModules
         		'dict' => 'DictionaryCountry'
         	)
         );
-        if (! empty($conf->fournisseur->enabled) || !empty($conf->margin->enabled)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.cost_price'=>'CostPrice'));
-        if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.recuperableonly'=>'NPR'));
-        if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.localtax1_tx'=>'LT1', 'p.localtax1_type'=>'LT1Type'));
-        if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.localtax2_tx'=>'LT2', 'p.localtax2_type'=>'LT2Type'));
-        if (! empty($conf->barcode->enabled)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('p.barcode'=>'BarCode'));
-		if (! empty($conf->global->PRODUCT_USE_UNITS)) $this->import_fields_array[$r]['p.fk_unit'] = 'Unit';
+        if (!empty($conf->fournisseur->enabled) || !empty($conf->margin->enabled)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.cost_price'=>'CostPrice'));
+        if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.recuperableonly'=>'NPR'));
+        if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.localtax1_tx'=>'LT1', 'p.localtax1_type'=>'LT1Type'));
+        if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.localtax2_tx'=>'LT2', 'p.localtax2_type'=>'LT2Type'));
+        if (!empty($conf->barcode->enabled)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('p.barcode'=>'BarCode'));
+		if (!empty($conf->global->PRODUCT_USE_UNITS)) $this->import_fields_array[$r]['p.fk_unit'] = 'Unit';
         // Add extra fields
-		$import_extrafield_sample=array();
-		$sql="SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'product' AND entity IN (0,".$conf->entity.")";
-		$resql=$this->db->query($sql);
+		$import_extrafield_sample = array();
+		$sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'product' AND entity IN (0,".$conf->entity.")";
+		$resql = $this->db->query($sql);
 		if ($resql)    // This can fail when class is used on old database (during migration for example)
 		{
-		    while ($obj=$this->db->fetch_object($resql))
+		    while ($obj = $this->db->fetch_object($resql))
 		    {
-		        $fieldname='extra.'.$obj->name;
-		        $fieldlabel=ucfirst($obj->label);
-		        $this->import_fields_array[$r][$fieldname]=$fieldlabel.($obj->fieldrequired?'*':'');
-		        $import_extrafield_sample[$fieldname]=$fieldlabel;
+		        $fieldname = 'extra.'.$obj->name;
+		        $fieldlabel = ucfirst($obj->label);
+		        $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : '');
+		        $import_extrafield_sample[$fieldname] = $fieldlabel;
 		    }
 		}
 		// End add extra fields
-		$this->import_fieldshidden_array[$r]=array('extra.fk_object'=>'lastrowid-'.MAIN_DB_PREFIX.'product');    // aliastable.field => ('user->id' or 'lastrowid-'.tableparent)
-		$this->import_regex_array[$r]=array(
+		$this->import_fieldshidden_array[$r] = array('extra.fk_object'=>'lastrowid-'.MAIN_DB_PREFIX.'product'); // aliastable.field => ('user->id' or 'lastrowid-'.tableparent)
+		$this->import_regex_array[$r] = array(
             'p.ref'=>'[^ ]',
 			'p.price_base_type' => '\AHT\z|\ATTC\z',
 			'p.tosell'=>'^[0|1]$',
@@ -490,7 +490,7 @@ class modService extends DolibarrModules
 			'p.price_ttc' => "110",
 			'p.price_min_ttc' => "110",
 			'p.price_base_type' => "HT (show/use price excl. tax) / TTC (show/use price incl. tax)",
-			'p.tva_tx' => '10',	// tax rate eg: 10. Must match numerically one of the tax rates defined for your country'
+			'p.tva_tx' => '10', // tax rate eg: 10. Must match numerically one of the tax rates defined for your country'
 			'p.tosell' => "0 (not for sale to customer, eg. raw material) / 1 (for sale)",
 			'p.tobuy' => "0 (not for purchase from supplier, eg. virtual product) / 1 (for purchase)",
 			'p.fk_product_type' => "0 (product) / 1 (service)",
@@ -501,17 +501,17 @@ class modService extends DolibarrModules
 			'p.accountancy_code_sell_export' => "",
 			'p.accountancy_code_buy' => "",
 			'p.weight' => "",
-			'p.weight_units' => 'kg',	// Use a unit of measure from the dictionary. g/Kg/T etc....matches field "Short label" for unit type "weight" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.weight_units' => 'kg', // Use a unit of measure from the dictionary. g/Kg/T etc....matches field "Short label" for unit type "weight" in table "' . MAIN_DB_PREFIX . 'c_units',
 			'p.length' => "",
-			'p.length_units' => 'm', 	// Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.length_units' => 'm', // Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
 			'p.width' => "",
-			'p.width_units' => 'm',		// Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.width_units' => 'm', // Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
 			'p.height' => "",
-			'p.height_units' => 'm',	// Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.height_units' => 'm', // Use a unit of measure from the dictionary. m/cm/mm etc....matches field "Short label" for unit type "size" in table "' . MAIN_DB_PREFIX . 'c_units',
 			'p.surface' => "",
-			'p.surface_units' => 'm2',	// Use a unit of measure from the dictionary. m2/cm2/mm2 etc....matches field "Short label" for unit type "surface" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.surface_units' => 'm2', // Use a unit of measure from the dictionary. m2/cm2/mm2 etc....matches field "Short label" for unit type "surface" in table "' . MAIN_DB_PREFIX . 'c_units',
 			'p.volume' => "",
-			'p.volume_units' => 'm3',	//Use a unit of measure from the dictionary. m3/cm3/mm3 etc....matches field "Short label" for unit type "volume" in table "' . MAIN_DB_PREFIX . 'c_units',
+			'p.volume_units' => 'm3', //Use a unit of measure from the dictionary. m3/cm3/mm3 etc....matches field "Short label" for unit type "volume" in table "' . MAIN_DB_PREFIX . 'c_units',
 			'p.finished' => '0 (raw material) / 1 (finished goods)'
 		);
 		//clauses copied from import_fields_array
@@ -520,16 +520,16 @@ class modService extends DolibarrModules
 			'p.pmp' => '0',
 			'p.desiredstock' => ''
 		));
-		if (! empty($conf->fournisseur->enabled) || !empty($conf->margin->enabled)) $import_sample=array_merge($import_sample, array('p.cost_price'=>'90'));
-		if (is_object($mysoc) && $mysoc->useNPR()) $import_sample=array_merge($import_sample, array('p.recuperableonly'=>'0'));
-		if (is_object($mysoc) && $mysoc->useLocalTax(1)) $import_sample=array_merge($import_sample, array('p.localtax1_tx'=>'', 'p.localtax1_type'=>''));
-		if (is_object($mysoc) && $mysoc->useLocalTax(2)) $import_sample=array_merge($import_sample, array('p.localtax2_tx'=>'', 'p.localtax2_type'=>''));
-		if (! empty($conf->barcode->enabled)) $import_sample=array_merge($import_sample, array('p.barcode'=>''));
-		if (! empty($conf->global->PRODUCT_USE_UNITS)) {
+		if (!empty($conf->fournisseur->enabled) || !empty($conf->margin->enabled)) $import_sample = array_merge($import_sample, array('p.cost_price'=>'90'));
+		if (is_object($mysoc) && $mysoc->useNPR()) $import_sample = array_merge($import_sample, array('p.recuperableonly'=>'0'));
+		if (is_object($mysoc) && $mysoc->useLocalTax(1)) $import_sample = array_merge($import_sample, array('p.localtax1_tx'=>'', 'p.localtax1_type'=>''));
+		if (is_object($mysoc) && $mysoc->useLocalTax(2)) $import_sample = array_merge($import_sample, array('p.localtax2_tx'=>'', 'p.localtax2_type'=>''));
+		if (!empty($conf->barcode->enabled)) $import_sample = array_merge($import_sample, array('p.barcode'=>''));
+		if (!empty($conf->global->PRODUCT_USE_UNITS)) {
 			$import_sample = array_merge(
 				$import_sample,
 				array(
-					'p.fk_unit' => 'use a unit of measure from the dictionary. G/KG/M2/M3 etc....matches field "code" in table "' . MAIN_DB_PREFIX . 'c_units"'
+					'p.fk_unit' => 'use a unit of measure from the dictionary. G/KG/M2/M3 etc....matches field "code" in table "'.MAIN_DB_PREFIX.'c_units"'
 				)
 				);
 
@@ -544,23 +544,23 @@ class modService extends DolibarrModules
 				)
 			));
 		}
-		$this->import_examplevalues_array[$r]=array_merge($import_sample, $import_extrafield_sample);
+		$this->import_examplevalues_array[$r] = array_merge($import_sample, $import_extrafield_sample);
 		$this->import_updatekeys_array[$r] = array('p.ref'=>'Ref');
-		if (! empty($conf->barcode->enabled)) $this->import_updatekeys_array[$r]=array_merge($this->import_updatekeys_array[$r], array('p.barcode'=>'BarCode'));//only show/allow barcode as update key if Barcode module enabled
+		if (!empty($conf->barcode->enabled)) $this->import_updatekeys_array[$r] = array_merge($this->import_updatekeys_array[$r], array('p.barcode'=>'BarCode')); //only show/allow barcode as update key if Barcode module enabled
 
 		if (empty($conf->product->enabled))	// We enable next import templates only if module product not already enabled (to avoid duplicate entries)
 		{
-			if (! empty($conf->fournisseur->enabled))
+			if (!empty($conf->fournisseur->enabled))
 			{
 			    // Import suppliers prices (note: this code is duplicated in module Service)
 				$r++;
-				$this->import_code[$r]=$this->rights_class.'_supplierprices';
-				$this->import_label[$r]="SuppliersPricesOfProductsOrServices";	// Translation key
-				$this->import_icon[$r]=$this->picto;
-				$this->import_entities_array[$r]=array();		// We define here only fields that use another icon that the one defined into import_icon
-				$this->import_tables_array[$r]=array('sp'=>MAIN_DB_PREFIX.'product_fournisseur_price');
-				$this->import_tables_creator_array[$r]=array('sp'=>'fk_user');
-				$this->import_fields_array[$r]=array(//field order as per structure of table llx_product_fournisseur_price, without optional fields
+				$this->import_code[$r] = $this->rights_class.'_supplierprices';
+				$this->import_label[$r] = "SuppliersPricesOfProductsOrServices"; // Translation key
+				$this->import_icon[$r] = $this->picto;
+				$this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon
+				$this->import_tables_array[$r] = array('sp'=>MAIN_DB_PREFIX.'product_fournisseur_price');
+				$this->import_tables_creator_array[$r] = array('sp'=>'fk_user');
+				$this->import_fields_array[$r] = array(//field order as per structure of table llx_product_fournisseur_price, without optional fields
 				    'sp.fk_product'=>"ProductOrService*",
 				    'sp.fk_soc' => "Supplier*",
 				    'sp.ref_fourn' => 'SupplierRef',
@@ -570,19 +570,19 @@ class modService extends DolibarrModules
 				    'sp.delivery_time_days' => 'DeliveryDelay',
 				    'sp.supplier_reputation' => 'SupplierReputation'
 				);
-				if (is_object($mysoc) && $mysoc->useNPR())       $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('sp.recuperableonly'=>'VATNPR'));
-				if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('sp.localtax1_tx'=>'LT1', 'sp.localtax1_type'=>'LT1Type'));
-				if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('sp.localtax2_tx'=>'LT2', 'sp.localtax2_type'=>'LT2Type'));
-				$this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array(
+				if (is_object($mysoc) && $mysoc->useNPR())       $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('sp.recuperableonly'=>'VATNPR'));
+				if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('sp.localtax1_tx'=>'LT1', 'sp.localtax1_type'=>'LT1Type'));
+				if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('sp.localtax2_tx'=>'LT2', 'sp.localtax2_type'=>'LT2Type'));
+				$this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array(
 					'sp.price'=>"PriceQtyMinHT*",
-					'sp.unitprice'=>'UnitPriceHT*',	// TODO Make this field not required and calculate it from price and qty
+					'sp.unitprice'=>'UnitPriceHT*', // TODO Make this field not required and calculate it from price and qty
 					'sp.remise_percent'=>'DiscountQtyMin'
 				));
 
 				if ($conf->multicurrency->enabled)
 				{
-				    $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array(
-				        'sp.fk_multicurrency'=>'CurrencyCodeId',//ideally this should be automatically obtained from the CurrencyCode on the next line
+				    $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array(
+				        'sp.fk_multicurrency'=>'CurrencyCodeId', //ideally this should be automatically obtained from the CurrencyCode on the next line
 				        'sp.multicurrency_code'=>'CurrencyCode',
 				        'sp.multicurrency_tx'=>'CurrencyRate',
 				        'sp.multicurrency_unitprice'=>'CurrencyUnitPrice',
@@ -590,11 +590,11 @@ class modService extends DolibarrModules
 				    ));
 				}
 
-				$this->import_convertvalue_array[$r]=array(
-						'sp.fk_soc'=>array('rule'=>'fetchidfromref','classfile'=>'/societe/class/societe.class.php','class'=>'Societe','method'=>'fetch','element'=>'ThirdParty'),
-						'sp.fk_product'=>array('rule'=>'fetchidfromref','classfile'=>'/product/class/product.class.php','class'=>'Product','method'=>'fetch','element'=>'Product')
+				$this->import_convertvalue_array[$r] = array(
+						'sp.fk_soc'=>array('rule'=>'fetchidfromref', 'classfile'=>'/societe/class/societe.class.php', 'class'=>'Societe', 'method'=>'fetch', 'element'=>'ThirdParty'),
+						'sp.fk_product'=>array('rule'=>'fetchidfromref', 'classfile'=>'/product/class/product.class.php', 'class'=>'Product', 'method'=>'fetch', 'element'=>'Product')
 				);
-				$this->import_examplevalues_array[$r]=array(
+				$this->import_examplevalues_array[$r] = array(
 					'sp.fk_product' => "PRODUCT_REF or id:123456",
 					'sp.fk_soc' => "My Supplier",
 					'sp.ref_fourn' => "XYZ-F123456",
@@ -607,9 +607,9 @@ class modService extends DolibarrModules
 					'sp.delivery_time_days' => '5',
 					'sp.supplier_reputation' => 'FAVORITE / NOTTHGOOD / DONOTORDER'
 				);
-				if (is_object($mysoc) && $mysoc->useNPR()) $this->import_examplevalues_array[$r]=array_merge($this->import_examplevalues_array[$r], array('sp.recuperableonly'=>''));
-				if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_examplevalues_array[$r]=array_merge($this->import_examplevalues_array[$r], array('sp.localtax1_tx'=>'LT1', 'sp.localtax1_type'=>'LT1Type'));
-				if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_examplevalues_array[$r]=array_merge($this->import_examplevalues_array[$r], array('sp.localtax2_tx'=>'LT2', 'sp.localtax2_type'=>'LT2Type'));
+				if (is_object($mysoc) && $mysoc->useNPR()) $this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array('sp.recuperableonly'=>''));
+				if (is_object($mysoc) && $mysoc->useLocalTax(1)) $this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array('sp.localtax1_tx'=>'LT1', 'sp.localtax1_type'=>'LT1Type'));
+				if (is_object($mysoc) && $mysoc->useLocalTax(2)) $this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array('sp.localtax2_tx'=>'LT2', 'sp.localtax2_type'=>'LT2Type'));
 				$this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array(
 					'sp.price' => "50.00",
 					'sp.unitprice' => '10',
@@ -618,7 +618,7 @@ class modService extends DolibarrModules
 				));
 				if ($conf->multicurrency->enabled)
 				{
-					$this->import_examplevalues_array[$r]=array_merge($this->import_examplevalues_array[$r], array(
+					$this->import_examplevalues_array[$r] = array_merge($this->import_examplevalues_array[$r], array(
 						'sp.fk_multicurrency'=>'eg: 2, rowid for code of multicurrency currency',
 						'sp.multicurrency_code'=>'GBP',
 						'sp.multicurrency_tx'=>'1.12345',
@@ -628,56 +628,56 @@ class modService extends DolibarrModules
 					));
 				}
 
-				$this->import_updatekeys_array[$r]=array('sp.fk_product'=>'ProductOrService','sp.ref_fourn'=>'SupplierRef','sp.fk_soc'=>'Supplier');
+				$this->import_updatekeys_array[$r] = array('sp.fk_product'=>'ProductOrService', 'sp.ref_fourn'=>'SupplierRef', 'sp.fk_soc'=>'Supplier');
 			}
 
-			if (! empty($conf->global->PRODUIT_MULTIPRICES))
+			if (!empty($conf->global->PRODUIT_MULTIPRICES))
 			{
 			    // Import products multiprices
 				$r++;
-				$this->import_code[$r]=$this->rights_class.'_multiprice';
-				$this->import_label[$r]="ProductsOrServiceMultiPrice";	// Translation key
-				$this->import_icon[$r]=$this->picto;
-				$this->import_entities_array[$r]=array();		// We define here only fields that use another icon that the one defined into import_icon
-				$this->import_tables_array[$r]=array('pr'=>MAIN_DB_PREFIX.'product_price');
-				$this->import_tables_creator_array[$r]=array('pr'=>'fk_user_author');	// Fields to store import user id
-				$this->import_fields_array[$r]=array('pr.fk_product'=>"ProductOrService*",
-					'pr.price_base_type'=>"PriceBase",'pr.price_level'=>"PriceLevel",
-					'pr.price'=>"PriceLevelUnitPriceHT",'pr.price_ttc'=>"PriceLevelUnitPriceTTC",
-					'pr.price_min'=>"MinPriceLevelUnitPriceHT",'pr.price_min_ttc'=>"MinPriceLevelUnitPriceTTC",
+				$this->import_code[$r] = $this->rights_class.'_multiprice';
+				$this->import_label[$r] = "ProductsOrServiceMultiPrice"; // Translation key
+				$this->import_icon[$r] = $this->picto;
+				$this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon
+				$this->import_tables_array[$r] = array('pr'=>MAIN_DB_PREFIX.'product_price');
+				$this->import_tables_creator_array[$r] = array('pr'=>'fk_user_author'); // Fields to store import user id
+				$this->import_fields_array[$r] = array('pr.fk_product'=>"ProductOrService*",
+					'pr.price_base_type'=>"PriceBase", 'pr.price_level'=>"PriceLevel",
+					'pr.price'=>"PriceLevelUnitPriceHT", 'pr.price_ttc'=>"PriceLevelUnitPriceTTC",
+					'pr.price_min'=>"MinPriceLevelUnitPriceHT", 'pr.price_min_ttc'=>"MinPriceLevelUnitPriceTTC",
 					'pr.date_price'=>'DateCreation*');
-				if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) $this->import_fields_array[$r]['pr.tva_tx']='VATRate';
-				if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r]=array_merge($this->import_fields_array[$r], array('pr.recuperableonly'=>'NPR'));
-				$this->import_regex_array[$r]=array('pr.datec'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$','pr.recuperableonly'=>'^[0|1]$');
-				$this->import_convertvalue_array[$r]=array(
-				    'pr.fk_product'=>array('rule'=>'fetchidfromref','classfile'=>'/product/class/product.class.php','class'=>'Product','method'=>'fetch','element'=>'Product')
+				if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) $this->import_fields_array[$r]['pr.tva_tx'] = 'VATRate';
+				if (is_object($mysoc) && $mysoc->useNPR()) $this->import_fields_array[$r] = array_merge($this->import_fields_array[$r], array('pr.recuperableonly'=>'NPR'));
+				$this->import_regex_array[$r] = array('pr.datec'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$', 'pr.recuperableonly'=>'^[0|1]$');
+				$this->import_convertvalue_array[$r] = array(
+				    'pr.fk_product'=>array('rule'=>'fetchidfromref', 'classfile'=>'/product/class/product.class.php', 'class'=>'Product', 'method'=>'fetch', 'element'=>'Product')
 				);
-				$this->import_examplevalues_array[$r]=array('pr.fk_product'=>"SERVICE_REF or id:123456",
-					'pr.price_base_type'=>"HT (for excl tax) or TTC (for inc tax)",'pr.price_level'=>"1",
-					'pr.price'=>"100",'pr.price_ttc'=>"110",
-					'pr.price_min'=>"100",'pr.price_min_ttc'=>"110",
+				$this->import_examplevalues_array[$r] = array('pr.fk_product'=>"SERVICE_REF or id:123456",
+					'pr.price_base_type'=>"HT (for excl tax) or TTC (for inc tax)", 'pr.price_level'=>"1",
+					'pr.price'=>"100", 'pr.price_ttc'=>"110",
+					'pr.price_min'=>"100", 'pr.price_min_ttc'=>"110",
 					'pr.tva_tx'=>'20',
 				    'pr.recuperableonly'=>'0',
 					'pr.date_price'=>'2013-04-10');
 			}
 
-			if (! empty($conf->global->MAIN_MULTILANGS))
+			if (!empty($conf->global->MAIN_MULTILANGS))
 			{
 			    // Import translations of product names and descriptions
 				$r++;
-				$this->import_code[$r]=$this->rights_class.'_languages';
-				$this->import_label[$r]="ProductsOrServicesTranslations";
-				$this->import_icon[$r]=$this->picto;
-				$this->import_entities_array[$r]=array();		// We define here only fields that use another icon that the one defined into import_icon
-				$this->import_tables_array[$r]=array('l'=>MAIN_DB_PREFIX.'product_lang');
+				$this->import_code[$r] = $this->rights_class.'_languages';
+				$this->import_label[$r] = "ProductsOrServicesTranslations";
+				$this->import_icon[$r] = $this->picto;
+				$this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon
+				$this->import_tables_array[$r] = array('l'=>MAIN_DB_PREFIX.'product_lang');
 				// multiline translation, one line per translation
-				$this->import_fields_array[$r]=array('l.fk_product'=>'ProductOrService*', 'l.lang'=>'Language*', 'l.label'=>'TranslatedLabel', 'l.description'=>'TranslatedDescription');
+				$this->import_fields_array[$r] = array('l.fk_product'=>'ProductOrService*', 'l.lang'=>'Language*', 'l.label'=>'TranslatedLabel', 'l.description'=>'TranslatedDescription');
 				//$this->import_fields_array[$r]['l.note']='TranslatedNote';
-				$this->import_convertvalue_array[$r]=array(
-				'l.fk_product'=>array('rule'=>'fetchidfromref','classfile'=>'/product/class/product.class.php','class'=>'Product','method'=>'fetch','element'=>'Product')
+				$this->import_convertvalue_array[$r] = array(
+				'l.fk_product'=>array('rule'=>'fetchidfromref', 'classfile'=>'/product/class/product.class.php', 'class'=>'Product', 'method'=>'fetch', 'element'=>'Product')
 				);
-				$this->import_examplevalues_array[$r]=array('l.fk_product'=>'SERVICE_REF or id:123456','l.lang'=>'en_US','l.label'=>'Label in en_US','l.description'=>'Desc in en_US');
-				$this->import_updatekeys_array[$r]=array('l.fk_product'=>'ProductOrService','l.lang'=>'Language');
+				$this->import_examplevalues_array[$r] = array('l.fk_product'=>'SERVICE_REF or id:123456', 'l.lang'=>'en_US', 'l.label'=>'Label in en_US', 'l.description'=>'Desc in en_US');
+				$this->import_updatekeys_array[$r] = array('l.fk_product'=>'ProductOrService', 'l.lang'=>'Language');
 			}
 		}
 	}

+ 254 - 254
htdocs/core/modules/project/doc/doc_generic_project_odt.modules.php

@@ -37,16 +37,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
-if (! empty($conf->propal->enabled))      require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
-if (! empty($conf->facture->enabled))     require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
-if (! empty($conf->facture->enabled))     require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
-if (! empty($conf->commande->enabled))    require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
-if (! empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
-if (! empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
-if (! empty($conf->contrat->enabled))     require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
-if (! empty($conf->ficheinter->enabled))  require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
-if (! empty($conf->deplacement->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php';
-if (! empty($conf->agenda->enabled))      require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
+if (!empty($conf->propal->enabled))      require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
+if (!empty($conf->facture->enabled))     require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+if (!empty($conf->facture->enabled))     require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
+if (!empty($conf->commande->enabled))    require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
+if (!empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
+if (!empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
+if (!empty($conf->contrat->enabled))     require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
+if (!empty($conf->ficheinter->enabled))  require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
+if (!empty($conf->deplacement->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php';
+if (!empty($conf->agenda->enabled))      require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
 
 
 /**
@@ -88,32 +88,32 @@ class doc_generic_project_odt extends ModelePDFProjects
 		$this->db = $db;
 		$this->name = "ODT templates";
 		$this->description = $langs->trans("DocumentModelOdt");
-		$this->scandir = 'PROJECT_ADDON_PDF_ODT_PATH';	// Name of constant that is used to save list of directories to scan
+		$this->scandir = 'PROJECT_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan
 
 		// Page size for A4 format
 		$this->type = 'odt';
 		$this->page_largeur = 0;
 		$this->page_hauteur = 0;
-		$this->format = array($this->page_largeur,$this->page_hauteur);
-		$this->marge_gauche=0;
-		$this->marge_droite=0;
-		$this->marge_haute=0;
-		$this->marge_basse=0;
-
-		$this->option_logo = 1;                    // Affiche logo
-		$this->option_tva = 0;                     // Gere option tva COMMANDE_TVAOPTION
-		$this->option_modereg = 0;                 // Affiche mode reglement
-		$this->option_condreg = 0;                 // Affiche conditions reglement
-		$this->option_codeproduitservice = 0;      // Affiche code produit-service
-		$this->option_multilang = 1;               // Dispo en plusieurs langues
-		$this->option_escompte = 0;                // Affiche si il y a eu escompte
-		$this->option_credit_note = 0;             // Support credit notes
-		$this->option_freetext = 1;				   // Support add of a personalised text
-		$this->option_draft_watermark = 0;		   // Support add of a watermark on drafts
+		$this->format = array($this->page_largeur, $this->page_hauteur);
+		$this->marge_gauche = 0;
+		$this->marge_droite = 0;
+		$this->marge_haute = 0;
+		$this->marge_basse = 0;
+
+		$this->option_logo = 1; // Affiche logo
+		$this->option_tva = 0; // Gere option tva COMMANDE_TVAOPTION
+		$this->option_modereg = 0; // Affiche mode reglement
+		$this->option_condreg = 0; // Affiche conditions reglement
+		$this->option_codeproduitservice = 0; // Affiche code produit-service
+		$this->option_multilang = 1; // Dispo en plusieurs langues
+		$this->option_escompte = 0; // Affiche si il y a eu escompte
+		$this->option_credit_note = 0; // Support credit notes
+		$this->option_freetext = 1; // Support add of a personalised text
+		$this->option_draft_watermark = 0; // Support add of a watermark on drafts
 
 		// Recupere emetteur
-		$this->emetteur=$mysoc;
-		if (! $this->emetteur->pays_code) $this->emetteur->pays_code=substr($langs->defaultlang, -2);    // Par defaut, si n'etait pas defini
+		$this->emetteur = $mysoc;
+		if (!$this->emetteur->pays_code) $this->emetteur->pays_code = substr($langs->defaultlang, -2); // Par defaut, si n'etait pas defini
 	}
 
 
@@ -131,7 +131,7 @@ class doc_generic_project_odt extends ModelePDFProjects
         // phpcs:enable
 		global $conf;
 
-		$resarray=array(
+		$resarray = array(
 		    $array_key.'_id'=>$object->id,
             $array_key.'_ref'=>$object->ref,
             $array_key.'_title'=>$object->title,
@@ -209,7 +209,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 	{
         // phpcs:enable
 		global $conf;
-		$pc='projcontacts_'; // prefix to avoid typos
+		$pc = 'projcontacts_'; // prefix to avoid typos
 
 		$ret = array(
 			$pc.'id'=>$contact['id'],
@@ -223,7 +223,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 			$pc.'email'=>$contact['email']
 			);
 
-		if ($contact['source']=='external') {
+		if ($contact['source'] == 'external') {
 			$ret[$pc.'isInternal'] = ''; // not internal
 
 			$ct = new Contact($this->db);
@@ -234,15 +234,15 @@ class doc_generic_project_odt extends ModelePDFProjects
 
 			// fetch external user extrafields
 			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-			$extrafields=new ExtraFields($this->db);
+			$extrafields = new ExtraFields($this->db);
 			$extrafields->fetch_name_optionals_label($ct->table_element, true);
 			$extrafields_num = $ct->fetch_optionals();
 			//dol_syslog(get_class($this)."::get_substitutionarray_project_contacts: ===== Number of Extrafields found: ".$extrafields_num, LOG_DEBUG);
-			foreach($ct->array_options as $efkey => $efval) {
+			foreach ($ct->array_options as $efkey => $efval) {
 				dol_syslog(get_class($this)."::get_substitutionarray_project_contacts: +++++ Extrafield ".$efkey." => ".$efval, LOG_DEBUG);
 				$ret[$pc.$efkey] = $efval; // add nothing else because it already comes as 'options_XX'
 			}
-		} elseif ($contact['source']=='internal') {
+		} elseif ($contact['source'] == 'internal') {
 			$ret[$pc.'isInternal'] = '1'; // this is an internal user
 
 			$ct = new User($this->db);
@@ -381,83 +381,83 @@ class doc_generic_project_odt extends ModelePDFProjects
 	 */
 	public function info($langs)
 	{
-		global $conf,$langs;
+		global $conf, $langs;
 
 		// Load translation files required by the page
-        $langs->loadLangs(array("companies","errors"));
+        $langs->loadLangs(array("companies", "errors"));
 
 		$form = new Form($this->db);
 
 		$texte = $this->description.".<br>\n";
-		$texte.= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
-		$texte.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
-		$texte.= '<input type="hidden" name="action" value="setModuleOptions">';
-		$texte.= '<input type="hidden" name="param1" value="PROJECT_ADDON_PDF_ODT_PATH">';
-		$texte.= '<table class="nobordernopadding" width="100%">';
+		$texte .= '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
+		$texte .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+		$texte .= '<input type="hidden" name="action" value="setModuleOptions">';
+		$texte .= '<input type="hidden" name="param1" value="PROJECT_ADDON_PDF_ODT_PATH">';
+		$texte .= '<table class="nobordernopadding" width="100%">';
 
 		// List of directories area
-		$texte.= '<tr><td>';
-		$texttitle=$langs->trans("ListOfDirectories");
-		$listofdir=explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->PROJECT_ADDON_PDF_ODT_PATH)));
-		$listoffiles=array();
-		foreach($listofdir as $key=>$tmpdir)
+		$texte .= '<tr><td>';
+		$texttitle = $langs->trans("ListOfDirectories");
+		$listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->PROJECT_ADDON_PDF_ODT_PATH)));
+		$listoffiles = array();
+		foreach ($listofdir as $key=>$tmpdir)
 		{
-			$tmpdir=trim($tmpdir);
-			$tmpdir=preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
-			if (! $tmpdir) {
+			$tmpdir = trim($tmpdir);
+			$tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
+			if (!$tmpdir) {
 				unset($listofdir[$key]); continue;
 			}
-			if (! is_dir($tmpdir)) $texttitle.=img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0);
+			if (!is_dir($tmpdir)) $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0);
 			else
 			{
-				$tmpfiles=dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
-				if (count($tmpfiles)) $listoffiles=array_merge($listoffiles, $tmpfiles);
+				$tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)');
+				if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
 			}
 		}
-		$texthelp=$langs->trans("ListOfDirectoriesForModelGenODT");
+		$texthelp = $langs->trans("ListOfDirectoriesForModelGenODT");
 		// Add list of substitution keys
-		$texthelp.='<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
-		$texthelp.=$langs->transnoentitiesnoconv("FullListOnOnlineDocumentation");    // This contains an url, we don't modify it
-
-		$texte.= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1);
-		$texte.= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
-		$texte.= '<textarea class="flat" cols="60" name="value1">';
-		$texte.=$conf->global->PROJECT_ADDON_PDF_ODT_PATH;
-		$texte.= '</textarea>';
-		$texte.= '</div><div style="display: inline-block; vertical-align: middle;">';
-		$texte.= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
-		$texte.= '<br></div></div>';
+		$texthelp .= '<br>'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'<br>';
+		$texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it
+
+		$texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1);
+		$texte .= '<div><div style="display: inline-block; min-width: 100px; vertical-align: middle;">';
+		$texte .= '<textarea class="flat" cols="60" name="value1">';
+		$texte .= $conf->global->PROJECT_ADDON_PDF_ODT_PATH;
+		$texte .= '</textarea>';
+		$texte .= '</div><div style="display: inline-block; vertical-align: middle;">';
+		$texte .= '<input type="submit" class="button" value="'.$langs->trans("Modify").'" name="Button">';
+		$texte .= '<br></div></div>';
 
 		// Scan directories
-		$nbofiles=count($listoffiles);
-		if (! empty($conf->global->PROJECT_ADDON_PDF_ODT_PATH))
+		$nbofiles = count($listoffiles);
+		if (!empty($conf->global->PROJECT_ADDON_PDF_ODT_PATH))
 		{
-			$texte.=$langs->trans("NumberOfModelFilesFound").': <b>';
+			$texte .= $langs->trans("NumberOfModelFilesFound").': <b>';
 			//$texte.=$nbofiles?'<a id="a_'.get_class($this).'" href="#">':'';
-			$texte.=$nbofiles;
+			$texte .= $nbofiles;
 			//$texte.=$nbofiles?'</a>':'';
-			$texte.='</b>';
+			$texte .= '</b>';
 		}
 
 		if ($nbofiles)
 		{
-   			$texte.='<div id="div_'.get_class($this).'" class="hidden">';
-   			foreach($listoffiles as $file)
+   			$texte .= '<div id="div_'.get_class($this).'" class="hidden">';
+   			foreach ($listoffiles as $file)
    			{
-                $texte.=$file['name'].'<br>';
+                $texte .= $file['name'].'<br>';
    			}
-   			$texte.='<div id="div_'.get_class($this).'">';
+   			$texte .= '<div id="div_'.get_class($this).'">';
 		}
 
-		$texte.= '</td>';
+		$texte .= '</td>';
 
-		$texte.= '<td valign="top" rowspan="2" class="hideonsmartphone">';
-		$texte.= $langs->trans("ExampleOfDirectoriesForModelGen");
-		$texte.= '</td>';
-		$texte.= '</tr>';
+		$texte .= '<td valign="top" rowspan="2" class="hideonsmartphone">';
+		$texte .= $langs->trans("ExampleOfDirectoriesForModelGen");
+		$texte .= '</td>';
+		$texte .= '</tr>';
 
-		$texte.= '</table>';
-		$texte.= '</form>';
+		$texte .= '</table>';
+		$texte .= '</form>';
 
 		return $texte;
 	}
@@ -474,7 +474,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 	public function write_file($object, $outputlangs, $srctemplatepath)
 	{
         // phpcs:enable
-		global $user,$langs,$conf,$mysoc,$hookmanager;
+		global $user, $langs, $conf, $mysoc, $hookmanager;
 
 		if (empty($srctemplatepath))
 		{
@@ -483,17 +483,17 @@ class doc_generic_project_odt extends ModelePDFProjects
 		}
 
 		// Add odtgeneration hook
-		if (! is_object($hookmanager))
+		if (!is_object($hookmanager))
 		{
 			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
-			$hookmanager=new HookManager($this->db);
+			$hookmanager = new HookManager($this->db);
 		}
 		$hookmanager->initHooks(array('odtgeneration'));
 		global $action;
 
-		if (! is_object($outputlangs)) $outputlangs=$langs;
-		$sav_charset_output=$outputlangs->charset_output;
-		$outputlangs->charset_output='UTF-8';
+		if (!is_object($outputlangs)) $outputlangs = $langs;
+		$sav_charset_output = $outputlangs->charset_output;
+		$outputlangs->charset_output = 'UTF-8';
 
 		// Load translation files required by the page
 		$outputlangs->loadLangs(array("main", "dict", "companies", "projects"));
@@ -501,11 +501,11 @@ class doc_generic_project_odt extends ModelePDFProjects
 		if ($conf->projet->dir_output)
 		{
 			// If $object is id instead of object
-			if (! is_object($object))
+			if (!is_object($object))
 			{
 				$id = $object;
 				$object = new Project($this->db);
-				$result=$object->fetch($id);
+				$result = $object->fetch($id);
 				if ($result < 0)
 				{
 					dol_print_error($this->db, $object->error);
@@ -515,14 +515,14 @@ class doc_generic_project_odt extends ModelePDFProjects
 
 			$dir = $conf->projet->dir_output;
 			$objectref = dol_sanitizeFileName($object->ref);
-			if (! preg_match('/specimen/i', $objectref)) $dir.= "/" . $objectref;
-			$file = $dir . "/" . $objectref . ".odt";
+			if (!preg_match('/specimen/i', $objectref)) $dir .= "/".$objectref;
+			$file = $dir."/".$objectref.".odt";
 
-			if (! file_exists($dir))
+			if (!file_exists($dir))
 			{
 				if (dol_mkdir($dir) < 0)
 				{
-					$this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir);
+					$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
 					return -1;
 				}
 			}
@@ -530,25 +530,25 @@ class doc_generic_project_odt extends ModelePDFProjects
 			if (file_exists($dir))
 			{
 				//print "srctemplatepath=".$srctemplatepath;	// Src filename
-				$newfile=basename($srctemplatepath);
-				$newfiletmp=preg_replace('/\.od(t|s)/i', '', $newfile);
-				$newfiletmp=preg_replace('/template_/i', '', $newfiletmp);
-				$newfiletmp=preg_replace('/modele_/i', '', $newfiletmp);
-				$newfiletmp=$objectref.'_'.$newfiletmp;
+				$newfile = basename($srctemplatepath);
+				$newfiletmp = preg_replace('/\.od(t|s)/i', '', $newfile);
+				$newfiletmp = preg_replace('/template_/i', '', $newfiletmp);
+				$newfiletmp = preg_replace('/modele_/i', '', $newfiletmp);
+				$newfiletmp = $objectref.'_'.$newfiletmp;
 				//$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt';
 				// Get extension (ods or odt)
-				$newfileformat=substr($newfile, strrpos($newfile, '.')+1);
-				if ( ! empty($conf->global->MAIN_DOC_USE_TIMING))
+				$newfileformat = substr($newfile, strrpos($newfile, '.') + 1);
+				if (!empty($conf->global->MAIN_DOC_USE_TIMING))
 				{
-				    $format=$conf->global->MAIN_DOC_USE_TIMING;
-				    if ($format == '1') $format='%Y%m%d%H%M%S';
-					$filename=$newfiletmp.'-'.dol_print_date(dol_now(), $format).'.'.$newfileformat;
+				    $format = $conf->global->MAIN_DOC_USE_TIMING;
+				    if ($format == '1') $format = '%Y%m%d%H%M%S';
+					$filename = $newfiletmp.'-'.dol_print_date(dol_now(), $format).'.'.$newfileformat;
 				}
 				else
 				{
-					$filename=$newfiletmp.'.'.$newfileformat;
+					$filename = $newfiletmp.'.'.$newfileformat;
 				}
-				$file=$dir.'/'.$filename;
+				$file = $dir.'/'.$filename;
 				//print "newdir=".$dir;
 				//print "newfile=".$newfile;
 				//print "file=".$file;
@@ -557,33 +557,33 @@ class doc_generic_project_odt extends ModelePDFProjects
 				dol_mkdir($conf->projet->dir_temp);
 
 				// If PROJECTLEADER contact defined on project, we use it
-				$usecontact=false;
-				$arrayidcontact=$object->getIdContact('external', 'PROJECTLEADER');
+				$usecontact = false;
+				$arrayidcontact = $object->getIdContact('external', 'PROJECTLEADER');
 				if (count($arrayidcontact) > 0)
 				{
-					$usecontact=true;
-					$result=$object->fetch_contact($arrayidcontact[0]);
+					$usecontact = true;
+					$result = $object->fetch_contact($arrayidcontact[0]);
 				}
 
 				// Recipient name
-				$contactobject=null;
-				if (! empty($usecontact))
+				$contactobject = null;
+				if (!empty($usecontact))
 				{
         			// if we have a PROJECTLEADER contact and we dont use it as recipient we store the contact object for later use
         			$contactobject = $object->contact;
 				}
 
-				$socobject=$object->thirdparty;
+				$socobject = $object->thirdparty;
 
 				// Make substitution
-				$substitutionarray=array(
+				$substitutionarray = array(
 				'__FROM_NAME__' => $this->emetteur->name,
 				'__FROM_EMAIL__' => $this->emetteur->email,
 				);
 				complete_substitutions_array($substitutionarray, $langs, $object);
 				// Call the ODTSubstitution hook
-				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$substitutionarray);
-				$reshook=$hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
+				$parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$substitutionarray);
+				$reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
 
 				// Open and load template
 				require_once ODTPHP_PATH.'odf.php';
@@ -592,13 +592,13 @@ class doc_generic_project_odt extends ModelePDFProjects
 						$srctemplatepath,
 						array(
 						'PATH_TO_TMP'	  => $conf->projet->dir_temp,
-						'ZIP_PROXY'		  => 'PclZipProxy',	// PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
+						'ZIP_PROXY'		  => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy.
 						'DELIMITER_LEFT'  => '{',
 						'DELIMITER_RIGHT' => '}'
 						)
 					);
 				} catch (Exception $e) {
-					$this->error=$e->getMessage();
+					$this->error = $e->getMessage();
 					dol_syslog($e->getMessage(), LOG_INFO);
 					return -1;
 				}
@@ -612,23 +612,23 @@ class doc_generic_project_odt extends ModelePDFProjects
 				// Define substitution array
 				$substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
 				$array_object_from_properties = $this->get_substitutionarray_each_var_object($object, $outputlangs);
-				$array_objet=$this->get_substitutionarray_object($object, $outputlangs);
-				$array_user=$this->get_substitutionarray_user($user, $outputlangs);
-				$array_soc=$this->get_substitutionarray_mysoc($mysoc, $outputlangs);
-				$array_thirdparty=$this->get_substitutionarray_thirdparty($socobject, $outputlangs);
-				$array_other=$this->get_substitutionarray_other($outputlangs);
+				$array_objet = $this->get_substitutionarray_object($object, $outputlangs);
+				$array_user = $this->get_substitutionarray_user($user, $outputlangs);
+				$array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs);
+				$array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs);
+				$array_other = $this->get_substitutionarray_other($outputlangs);
 				// retrieve contact information for use in object as contact_xxx tags
 				$array_project_contact = array();
-				if ($usecontact && is_object($contactobject)) $array_project_contact=$this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
+				if ($usecontact && is_object($contactobject)) $array_project_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact');
 
 				$tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_project_contact);
 				complete_substitutions_array($tmparray, $outputlangs, $object);
 
 				// Call the ODTSubstitution hook
-				$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
-				$reshook=$hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
+				$parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
+				$reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
 
-				foreach($tmparray as $key=>$value)
+				foreach ($tmparray as $key=>$value)
 				{
 					try {
 						if (preg_match('/logo$/', $key)) // Image
@@ -655,43 +655,43 @@ class doc_generic_project_odt extends ModelePDFProjects
 					$taskstatic = new Task($this->db);
 
 					// Security check
-					$socid=0;
+					$socid = 0;
 					if (!empty($object->fk_soc)) $socid = $object->fk_soc;
 
-					$tasksarray=$taskstatic->getTasksArray(0, 0, $object->id, $socid, 0);
+					$tasksarray = $taskstatic->getTasksArray(0, 0, $object->id, $socid, 0);
 
 
 					foreach ($tasksarray as $task)
 					{
-						$tmparray=$this->get_substitutionarray_tasks($task, $outputlangs);
+						$tmparray = $this->get_substitutionarray_tasks($task, $outputlangs);
 						//complete_substitutions_array($tmparray, $outputlangs, $object, $task, "completesubstitutionarray_lines");
-						foreach($tmparray as $key => $val)
+						foreach ($tmparray as $key => $val)
 						{
 							try
 							{
 								$listlines->setVars($key, $val, true, 'UTF-8');
 							}
-							catch(OdfException $e)
+							catch (OdfException $e)
 							{
 								dol_syslog($e->getMessage(), LOG_INFO);
 							}
-							catch(SegmentException $e)
+							catch (SegmentException $e)
 							{
 								dol_syslog($e->getMessage(), LOG_INFO);
 							}
 						}
 
-						$taskobj=new Task($this->db);
+						$taskobj = new Task($this->db);
 						$taskobj->fetch($task->id);
 
 						// Replace tags of lines for contacts task
-						$sourcearray=array('internal','external');
-						$contact_arrray=array();
+						$sourcearray = array('internal', 'external');
+						$contact_arrray = array();
 						foreach ($sourcearray as $source) {
-							$contact_temp=$taskobj->liste_contact(-1, $source);
+							$contact_temp = $taskobj->liste_contact(-1, $source);
 							if ((is_array($contact_temp) && count($contact_temp) > 0))
 							{
-								$contact_arrray=array_merge($contact_arrray, $contact_temp);
+								$contact_arrray = array_merge($contact_arrray, $contact_temp);
 							}
 						}
 						if ((is_array($contact_arrray) && count($contact_arrray) > 0))
@@ -700,33 +700,33 @@ class doc_generic_project_odt extends ModelePDFProjects
 
 							foreach ($contact_arrray as $contact)
 							{
-								if ($contact['source']=='internal') {
-									$objectdetail=new User($this->db);
+								if ($contact['source'] == 'internal') {
+									$objectdetail = new User($this->db);
 									$objectdetail->fetch($contact['id']);
-									$contact['socname']=$mysoc->name;
-								} elseif ($contact['source']=='external') {
-									$objectdetail=new Contact($this->db);
+									$contact['socname'] = $mysoc->name;
+								} elseif ($contact['source'] == 'external') {
+									$objectdetail = new Contact($this->db);
 									$objectdetail->fetch($contact['id']);
 
-									$soc=new Societe($this->db);
+									$soc = new Societe($this->db);
 									$soc->fetch($contact['socid']);
-									$contact['socname']=$soc->name;
+									$contact['socname'] = $soc->name;
 								}
-								$contact['fullname']=$objectdetail->getFullName($outputlangs, 1);
+								$contact['fullname'] = $objectdetail->getFullName($outputlangs, 1);
 
-								$tmparray=$this->get_substitutionarray_tasksressource($contact, $outputlangs);
+								$tmparray = $this->get_substitutionarray_tasksressource($contact, $outputlangs);
 
-								foreach($tmparray as $key => $val)
+								foreach ($tmparray as $key => $val)
 								{
 									try
 									{
 										$listlinestaskres->setVars($key, $val, true, 'UTF-8');
 									}
-									catch(OdfException $e)
+									catch (OdfException $e)
 									{
 										dol_syslog($e->getMessage(), LOG_INFO);
 									}
-									catch(SegmentException $e)
+									catch (SegmentException $e)
 									{
 										dol_syslog($e->getMessage(), LOG_INFO);
 									}
@@ -737,7 +737,7 @@ class doc_generic_project_odt extends ModelePDFProjects
 
 						//Time ressources
 						$sql = "SELECT t.rowid, t.task_date, t.task_duration, t.fk_user, t.note";
-						$sql.= ", u.lastname, u.firstname, t.thm";
+						$sql .= ", u.lastname, u.firstname, t.thm";
 						$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t";
 						$sql .= " , ".MAIN_DB_PREFIX."user as u";
 						$sql .= " WHERE t.fk_task =".$task->id;
@@ -750,33 +750,33 @@ class doc_generic_project_odt extends ModelePDFProjects
 							$num = $this->db->num_rows($resql);
 							$i = 0;
 							$tasks = array();
-							$row=array();
+							$row = array();
 							$listlinestasktime = $listlines->__get('taskstimes');
 							if (empty($num)) {
-								$row['rowid']='';
-								$row['task_date']='';
-								$row['task_duration']='';
-								$row['$tasktime']='';
-								$row['note']='';
-								$row['fk_user']='';
-								$row['name']='';
-								$row['firstname']='';
-								$row['fullcivname']='';
-								$row['amountht']='';
-								$row['amountttc']='';
-								$row['thm']='';
-								$tmparray=$this->get_substitutionarray_taskstime($row, $outputlangs);
-								foreach($tmparray as $key => $val)
+								$row['rowid'] = '';
+								$row['task_date'] = '';
+								$row['task_duration'] = '';
+								$row['$tasktime'] = '';
+								$row['note'] = '';
+								$row['fk_user'] = '';
+								$row['name'] = '';
+								$row['firstname'] = '';
+								$row['fullcivname'] = '';
+								$row['amountht'] = '';
+								$row['amountttc'] = '';
+								$row['thm'] = '';
+								$tmparray = $this->get_substitutionarray_taskstime($row, $outputlangs);
+								foreach ($tmparray as $key => $val)
 								{
 									try
 									{
 										$listlinestasktime->setVars($key, $val, true, 'UTF-8');
 									}
-									catch(OdfException $e)
+									catch (OdfException $e)
 									{
 										dol_syslog($e->getMessage(), LOG_INFO);
 									}
-									catch(SegmentException $e)
+									catch (SegmentException $e)
 									{
 										dol_syslog($e->getMessage(), LOG_INFO);
 									}
@@ -787,36 +787,36 @@ class doc_generic_project_odt extends ModelePDFProjects
 							{
 								$row = $this->db->fetch_array($resql);
 								if (!empty($row['fk_user'])) {
-									$objectdetail=new User($this->db);
+									$objectdetail = new User($this->db);
 									$objectdetail->fetch($row['fk_user']);
-									$row['fullcivname']=$objectdetail->getFullName($outputlangs, 1);
+									$row['fullcivname'] = $objectdetail->getFullName($outputlangs, 1);
 								} else {
-									$row['fullcivname']='';
+									$row['fullcivname'] = '';
 								}
 
 								if (!empty($row['thm'])) {
-									$row['amountht']=($row['task_duration'] / 3600) * $row['thm'];
+									$row['amountht'] = ($row['task_duration'] / 3600) * $row['thm'];
 									$defaultvat = get_default_tva($mysoc, $mysoc);
-									$row['amountttc']=price2num($row['amountht'] * (1 + ($defaultvat / 100)), 'MT');
+									$row['amountttc'] = price2num($row['amountht'] * (1 + ($defaultvat / 100)), 'MT');
 								} else {
-									$row['amountht']=0;
-									$row['amountttc']=0;
-									$row['thm']=0;
+									$row['amountht'] = 0;
+									$row['amountttc'] = 0;
+									$row['thm'] = 0;
 								}
 
-								$tmparray=$this->get_substitutionarray_taskstime($row, $outputlangs);
+								$tmparray = $this->get_substitutionarray_taskstime($row, $outputlangs);
 
-								foreach($tmparray as $key => $val)
+								foreach ($tmparray as $key => $val)
 								{
 									try
 									{
 										$listlinestasktime->setVars($key, $val, true, 'UTF-8');
 									}
-									catch(OdfException $e)
+									catch (OdfException $e)
 									{
 										dol_syslog($e->getMessage(), LOG_INFO);
 									}
-									catch(SegmentException $e)
+									catch (SegmentException $e)
 									{
 										dol_syslog($e->getMessage(), LOG_INFO);
 									}
@@ -832,14 +832,14 @@ class doc_generic_project_odt extends ModelePDFProjects
 						$listtasksfiles = $listlines->__get('tasksfiles');
 
 						$upload_dir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($object->ref).'/'.dol_sanitizeFileName($task->ref);
-						$filearray=dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', 'name', SORT_ASC, 1);
+						$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', 'name', SORT_ASC, 1);
 
 
 						foreach ($filearray as $filedetail)
 						{
-							$tmparray=$this->get_substitutionarray_task_file($filedetail, $outputlangs);
+							$tmparray = $this->get_substitutionarray_task_file($filedetail, $outputlangs);
 							//dol_syslog(get_class($this).'::main $tmparray'.var_export($tmparray,true));
-							foreach($tmparray as $key => $val)
+							foreach ($tmparray as $key => $val)
 							{
 								try
 								{
@@ -860,13 +860,13 @@ class doc_generic_project_odt extends ModelePDFProjects
 					}
 					$odfHandler->mergeSegment($listlines);
 				}
-				catch(OdfException $e)
+				catch (OdfException $e)
 				{
-					$ExceptionTrace=$e->getTrace();
+					$ExceptionTrace = $e->getTrace();
 					// no segment defined on ODT is not an error
-					if($ExceptionTrace[0]['function'] != 'setSegment')
+					if ($ExceptionTrace[0]['function'] != 'setSegment')
 					{
-						$this->error=$e->getMessage();
+						$this->error = $e->getMessage();
 						dol_syslog($this->error, LOG_WARNING);
 						return -1;
 					}
@@ -878,24 +878,24 @@ class doc_generic_project_odt extends ModelePDFProjects
 					$listlines = $odfHandler->setSegment('projectfiles');
 
 					$upload_dir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($object->ref);
-					$filearray=dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', 'name', SORT_ASC, 1);
+					$filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', 'name', SORT_ASC, 1);
 
 					foreach ($filearray as $filedetail)
 					{
 						//dol_syslog(get_class($this).'::main $filedetail'.var_export($filedetail,true));
-						$tmparray=$this->get_substitutionarray_project_file($filedetail, $outputlangs);
+						$tmparray = $this->get_substitutionarray_project_file($filedetail, $outputlangs);
 
-						foreach($tmparray as $key => $val)
+						foreach ($tmparray as $key => $val)
 						{
 							try
 							{
 								$listlines->setVars($key, $val, true, 'UTF-8');
 							}
-							catch(OdfException $e)
+							catch (OdfException $e)
 							{
 								dol_syslog($e->getMessage(), LOG_INFO);
 							}
-							catch(SegmentException $e)
+							catch (SegmentException $e)
 							{
 								dol_syslog($e->getMessage(), LOG_INFO);
 							}
@@ -904,21 +904,21 @@ class doc_generic_project_odt extends ModelePDFProjects
 					}
 					$odfHandler->mergeSegment($listlines);
 				}
-				catch(OdfException $e)
+				catch (OdfException $e)
 				{
-					$this->error=$e->getMessage();
+					$this->error = $e->getMessage();
 					dol_syslog($this->error, LOG_WARNING);
 					return -1;
 				}
 
 				// Replace tags of lines for contacts
-				$sourcearray=array('internal','external');
-				$contact_arrray=array();
+				$sourcearray = array('internal', 'external');
+				$contact_arrray = array();
 				foreach ($sourcearray as $source) {
-					$contact_temp=$object->liste_contact(-1, $source);
+					$contact_temp = $object->liste_contact(-1, $source);
 					if ((is_array($contact_temp) && count($contact_temp) > 0))
 					{
-						$contact_arrray=array_merge($contact_arrray, $contact_temp);
+						$contact_arrray = array_merge($contact_arrray, $contact_temp);
 					}
 				}
 				if ((is_array($contact_arrray) && count($contact_arrray) > 0))
@@ -929,32 +929,32 @@ class doc_generic_project_odt extends ModelePDFProjects
 
 						foreach ($contact_arrray as $contact)
 						{
-							if ($contact['source']=='internal') {
-								$objectdetail=new User($this->db);
+							if ($contact['source'] == 'internal') {
+								$objectdetail = new User($this->db);
 								$objectdetail->fetch($contact['id']);
-								$contact['socname']=$mysoc->name;
-							} elseif ($contact['source']=='external') {
-								$objectdetail=new Contact($this->db);
+								$contact['socname'] = $mysoc->name;
+							} elseif ($contact['source'] == 'external') {
+								$objectdetail = new Contact($this->db);
 								$objectdetail->fetch($contact['id']);
 
-								$soc=new Societe($this->db);
+								$soc = new Societe($this->db);
 								$soc->fetch($contact['socid']);
-								$contact['socname']=$soc->name;
+								$contact['socname'] = $soc->name;
 							}
-							$contact['fullname']=$objectdetail->getFullName($outputlangs, 1);
+							$contact['fullname'] = $objectdetail->getFullName($outputlangs, 1);
 
-							$tmparray=$this->get_substitutionarray_project_contacts($contact, $outputlangs);
-							foreach($tmparray as $key => $val)
+							$tmparray = $this->get_substitutionarray_project_contacts($contact, $outputlangs);
+							foreach ($tmparray as $key => $val)
 							{
 								try
 								{
 									$listlines->setVars($key, $val, true, 'UTF-8');
 								}
-								catch(OdfException $e)
+								catch (OdfException $e)
 								{
 									dol_syslog($e->getMessage(), LOG_INFO);
 								}
-								catch(SegmentException $e)
+								catch (SegmentException $e)
 								{
 									dol_syslog($e->getMessage(), LOG_INFO);
 								}
@@ -963,9 +963,9 @@ class doc_generic_project_odt extends ModelePDFProjects
 						}
 						$odfHandler->mergeSegment($listlines);
 					}
-					catch(OdfException $e)
+					catch (OdfException $e)
 					{
-						$this->error=$e->getMessage();
+						$this->error = $e->getMessage();
 						dol_syslog($this->error, LOG_WARNING);
 						return -1;
 					}
@@ -1065,14 +1065,14 @@ class doc_generic_project_odt extends ModelePDFProjects
 						'title' => "ListSocialContributionAssociatedProject",
 						'class' => 'ChargeSociales',
 						'table' => 'chargesociales',
-						'urlnew' => DOL_URL_ROOT . '/compta/sociales/card.php?action=create&projectid=' . $object->id,
+						'urlnew' => DOL_URL_ROOT.'/compta/sociales/card.php?action=create&projectid='.$object->id,
 						'test' => $conf->tax->enabled && $user->rights->tax->charges->lire
 					),
 					'stock_mouvement' => array(
 						'title' => "ListMouvementStockProject",
 						'class' => 'MouvementStock',
 						'table' => 'stock_mouvement',
-						'test' => ($conf->stock->enabled && $user->rights->stock->mouvement->lire && ! empty($conf->global->STOCK_MOVEMENT_INTO_PROJECT_OVERVIEW))
+						'test' => ($conf->stock->enabled && $user->rights->stock->mouvement->lire && !empty($conf->global->STOCK_MOVEMENT_INTO_PROJECT_OVERVIEW))
 					),
 					'agenda' => array(
 						'title' => "ListActionsAssociatedProject",
@@ -1090,72 +1090,72 @@ class doc_generic_project_odt extends ModelePDFProjects
 
 					foreach ($listofreferent as $keyref => $valueref)
 					{
-						$title=$valueref['title'];
-						$tablename=$valueref['table'];
-						$classname=$valueref['class'];
-						$qualified=$valueref['test'];
+						$title = $valueref['title'];
+						$tablename = $valueref['table'];
+						$classname = $valueref['class'];
+						$qualified = $valueref['test'];
 						if ($qualified)
 						{
 							$elementarray = $object->get_element_list($keyref, $tablename);
-							if (count($elementarray)>0 && is_array($elementarray))
+							if (count($elementarray) > 0 && is_array($elementarray))
 							{
 								$total_ht = 0;
 								$total_ttc = 0;
-								$num=count($elementarray);
+								$num = count($elementarray);
 								for ($i = 0; $i < $num; $i++)
 								{
-									$ref_array=array();
-									$ref_array['type']=$langs->trans($classname);
+									$ref_array = array();
+									$ref_array['type'] = $langs->trans($classname);
 
 									$element = new $classname($this->db);
 									$element->fetch($elementarray[$i]);
 									$element->fetch_thirdparty();
 
 									//Ref object
-									$ref_array['ref']=$element->ref;
+									$ref_array['ref'] = $element->ref;
 
 									//Date object
-									$dateref=$element->date;
-									if (empty($dateref)) $dateref=$element->datep;
-									if (empty($dateref)) $dateref=$element->date_contrat;
-									$ref_array['date']=$dateref;
+									$dateref = $element->date;
+									if (empty($dateref)) $dateref = $element->datep;
+									if (empty($dateref)) $dateref = $element->date_contrat;
+									$ref_array['date'] = $dateref;
 
 									//Soc object
 									if (is_object($element->thirdparty)) {
-										$ref_array['socname']=$element->thirdparty->name;
+										$ref_array['socname'] = $element->thirdparty->name;
 									} else {
-										$ref_array['socname']='';
+										$ref_array['socname'] = '';
 									}
 
 									//Amount object
 									if (empty($valueref['disableamount'])) {
 										if (!empty($element->total_ht)) {
-											$ref_array['amountht']=$element->total_ht;
-											$ref_array['amountttc']=$element->total_ttc;
+											$ref_array['amountht'] = $element->total_ht;
+											$ref_array['amountttc'] = $element->total_ttc;
 										} else {
-											$ref_array['amountht']=0;
-											$ref_array['amountttc']=0;
+											$ref_array['amountht'] = 0;
+											$ref_array['amountttc'] = 0;
 										}
 									} else {
-										$ref_array['amountht']='';
-										$ref_array['amountttc']='';
+										$ref_array['amountht'] = '';
+										$ref_array['amountttc'] = '';
 									}
 
-									$ref_array['status']=$element->getLibStatut(0);
+									$ref_array['status'] = $element->getLibStatut(0);
 
-									$tmparray=$this->get_substitutionarray_project_reference($ref_array, $outputlangs);
+									$tmparray = $this->get_substitutionarray_project_reference($ref_array, $outputlangs);
 
-									foreach($tmparray as $key => $val)
+									foreach ($tmparray as $key => $val)
 									{
 										try
 										{
 											$listlines->setVars($key, $val, true, 'UTF-8');
 										}
-										catch(OdfException $e)
+										catch (OdfException $e)
 										{
 											dol_syslog($e->getMessage(), LOG_INFO);
 										}
-										catch(SegmentException $e)
+										catch (SegmentException $e)
 										{
 											dol_syslog($e->getMessage(), LOG_INFO);
 										}
@@ -1166,15 +1166,15 @@ class doc_generic_project_odt extends ModelePDFProjects
 						}
 						$odfHandler->mergeSegment($listlines);
 					}
-				} catch(OdfException $e) {
-					$this->error=$e->getMessage();
+				} catch (OdfException $e) {
+					$this->error = $e->getMessage();
 					dol_syslog($this->error, LOG_WARNING);
 					return -1;
 				}
 
 				// Replace labels translated
-				$tmparray=$outputlangs->get_translations_for_substitutions();
-				foreach($tmparray as $key=>$value)
+				$tmparray = $outputlangs->get_translations_for_substitutions();
+				foreach ($tmparray as $key=>$value)
 				{
 					try {
 						$odfHandler->setVars($key, $value, true, 'UTF-8');
@@ -1184,8 +1184,8 @@ class doc_generic_project_odt extends ModelePDFProjects
 				}
 
 				// Call the beforeODTSave hook
-				$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
-				$reshook=$hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
+				$parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
+				$reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
 
 
 				// Write new file
@@ -1193,33 +1193,33 @@ class doc_generic_project_odt extends ModelePDFProjects
 					try {
 						$odfHandler->exportAsAttachedPDF($file);
 					} catch (Exception $e) {
-						$this->error=$e->getMessage();
+						$this->error = $e->getMessage();
 						return -1;
 					}
 				} else {
 					try {
 						$odfHandler->saveToDisk($file);
-					} catch (Exception $e){
-						$this->error=$e->getMessage();
+					} catch (Exception $e) {
+						$this->error = $e->getMessage();
                         dol_syslog($e->getMessage(), LOG_INFO);
 						return -1;
 					}
 				}
-				$parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray);
-				$reshook=$hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
+				$parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray);
+				$reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
 
-				if (! empty($conf->global->MAIN_UMASK))
+				if (!empty($conf->global->MAIN_UMASK))
 					@chmod($file, octdec($conf->global->MAIN_UMASK));
 
-				$odfHandler=null;	// Destroy object
+				$odfHandler = null; // Destroy object
 
 				$this->result = array('fullpath'=>$file);
 
-				return 1;   // Success
+				return 1; // Success
 			}
 			else
 			{
-				$this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir);
+				$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
 				return -1;
 			}
 		}

+ 14 - 14
htdocs/core/modules/security/generate/modGeneratePassPerso.class.php

@@ -24,7 +24,7 @@
  *      \brief      File to manage no password generation.
  */
 
-require_once DOL_DOCUMENT_ROOT .'/core/modules/security/generate/modules_genpassword.php';
+require_once DOL_DOCUMENT_ROOT.'/core/modules/security/generate/modules_genpassword.php';
 
 
 /**
@@ -75,10 +75,10 @@ class modGeneratePassPerso extends ModeleGenPassword
 		$this->id = "Perso";
 		$this->length = $langs->trans("SetupPerso");
 
-		$this->db=$db;
-		$this->conf=$conf;
-		$this->langs=$langs;
-		$this->user=$user;
+		$this->db = $db;
+		$this->conf = $conf;
+		$this->langs = $langs;
+		$this->user = $user;
 
 		if (empty($conf->global->USER_PASSWORD_PATTERN)) {
 			// default value (8carac, 1maj, 1digit, 1spe,  3 repeat, no ambi at auto generation.
@@ -89,7 +89,7 @@ class modGeneratePassPerso extends ModeleGenPassword
 		$this->Min = strtolower($this->Maj);
 		$this->Nb = "0123456789";
 		$this->Spe = "!@#$%&*()_-+={}[]\\|:;'/";
-		$this->Ambi = array("1","I","l","|","O","0");
+		$this->Ambi = array("1", "I", "l", "|", "O", "0");
 
 		$tabConf = explode(";", $conf->global->USER_PASSWORD_PATTERN);
 		$this->length2 = $tabConf[0];
@@ -107,7 +107,7 @@ class modGeneratePassPerso extends ModeleGenPassword
 			$this->Spe = str_replace($this->Ambi, "", $this->Spe);
 		}
 
-		$pattern = $this->Min . (! empty($this->NbMaj)?$this->Maj:'') . (! empty($this->NbNum)?$this->Nb:'') . (! empty($this->NbSpe)?$this->Spe:'');
+		$pattern = $this->Min.(!empty($this->NbMaj) ? $this->Maj : '').(!empty($this->NbNum) ? $this->Nb : '').(!empty($this->NbSpe) ? $this->Spe : '');
 		$this->All = str_shuffle($pattern);
 
 		//$this->All = str_shuffle($this->Maj. $this->Min. $this->Nb. $this->Spe);
@@ -144,24 +144,24 @@ class modGeneratePassPerso extends ModeleGenPassword
 	public function getNewGeneratedPassword()
 	{
 		$pass = "";
-		for ($i=0; $i<$this->NbMaj; $i++) {
+		for ($i = 0; $i < $this->NbMaj; $i++) {
             // Y
 			$pass .= $this->Maj[mt_rand(0, strlen($this->Maj) - 1)];
 		}
 
-		for ($i=0; $i<$this->NbNum; $i++) {
+		for ($i = 0; $i < $this->NbNum; $i++) {
             // X
 			$pass .= $this->Nb[mt_rand(0, strlen($this->Nb) - 1)];
 		}
 
-		for ($i=0; $i<$this->NbSpe; $i++) {
+		for ($i = 0; $i < $this->NbSpe; $i++) {
             // @
 			$pass .= $this->Spe[mt_rand(0, strlen($this->Spe) - 1)];
 		}
 
-		for ($i=strlen($pass);$i<$this->length2; $i++) {
+		for ($i = strlen($pass); $i < $this->length2; $i++) {
             // y
-			$pass .= $this->All[mt_rand(0, strlen($this->All) -1)];
+			$pass .= $this->All[mt_rand(0, strlen($this->All) - 1)];
 		}
 
 		$pass = str_shuffle($pass);
@@ -220,8 +220,8 @@ class modGeneratePassPerso extends ModeleGenPassword
 		$count = 0;
 		$char = str_split($password);
 
-		foreach($char as $c) {
-			if($c != $last) {
+		foreach ($char as $c) {
+			if ($c != $last) {
 				$last = $c;
 				$count = 0;
 

+ 169 - 169
htdocs/core/modules/stock/doc/pdf_stdmovement.modules.php

@@ -117,7 +117,7 @@ class pdf_stdmovement extends ModelePDFMovement
 	 */
 	public function __construct($db)
 	{
-		global $conf,$langs,$mysoc;
+		global $conf, $langs, $mysoc;
 
 		// Load traductions files required by page
 		$langs->loadLangs(array("main", "companies"));
@@ -128,54 +128,54 @@ class pdf_stdmovement extends ModelePDFMovement
 
 		// Page size for A4 format
 		$this->type = 'pdf';
-		$formatarray=pdf_getFormat();
+		$formatarray = pdf_getFormat();
 		$this->page_largeur = $formatarray['width'];
 		$this->page_hauteur = $formatarray['height'];
-		$this->format = array($this->page_largeur,$this->page_hauteur);
-		$this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10;
-		$this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10;
-		$this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10;
-		$this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10;
+		$this->format = array($this->page_largeur, $this->page_hauteur);
+		$this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10;
+		$this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10;
+		$this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10;
+		$this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10;
 
-		$this->option_logo = 1;                    // Affiche logo
-		$this->option_codestockservice = 0;      // Affiche code stock-service
-		$this->option_multilang = 1;               // Dispo en plusieurs langues
-		$this->option_freetext = 0;				   // Support add of a personalised text
+		$this->option_logo = 1; // Affiche logo
+		$this->option_codestockservice = 0; // Affiche code stock-service
+		$this->option_multilang = 1; // Dispo en plusieurs langues
+		$this->option_freetext = 0; // Support add of a personalised text
 
 		// Recupere emetteur
-		$this->emetteur=$mysoc;
-		if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang, -2);    // By default if not defined
+		$this->emetteur = $mysoc;
+		if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined
 
 		// Define position of columns
 		$this->wref = 15;
 		$this->posxidref = $this->marge_gauche;
-		$this->posxdatemouv = $this->marge_gauche+8;
-		$this->posxdesc=37;
-		$this->posxlabel=50;
-		$this->posxtva=80;
-		$this->posxqty=105;
-		$this->posxup=119;
-		$this->posxunit=136;
-		$this->posxdiscount=167;
-		$this->postotalht=180;
-
-		if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) || ! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) $this->posxtva=$this->posxup;
-		$this->posxpicture=$this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
+		$this->posxdatemouv = $this->marge_gauche + 8;
+		$this->posxdesc = 37;
+		$this->posxlabel = 50;
+		$this->posxtva = 80;
+		$this->posxqty = 105;
+		$this->posxup = 119;
+		$this->posxunit = 136;
+		$this->posxdiscount = 167;
+		$this->postotalht = 180;
+
+		if (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) || !empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) $this->posxtva = $this->posxup;
+		$this->posxpicture = $this->posxtva - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images
 		if ($this->page_largeur < 210) // To work with US executive format
 		{
-			$this->posxpicture-=20;
-			$this->posxtva-=20;
-			$this->posxup-=20;
-			$this->posxqty-=20;
-			$this->posxunit-=20;
-			$this->posxdiscount-=20;
-			$this->postotalht-=20;
+			$this->posxpicture -= 20;
+			$this->posxtva -= 20;
+			$this->posxup -= 20;
+			$this->posxqty -= 20;
+			$this->posxunit -= 20;
+			$this->posxdiscount -= 20;
+			$this->postotalht -= 20;
 		}
-		$this->tva=array();
-		$this->localtax1=array();
-		$this->localtax2=array();
-		$this->atleastoneratenotnull=0;
-		$this->atleastonediscount=0;
+		$this->tva = array();
+		$this->localtax1 = array();
+		$this->localtax2 = array();
+		$this->atleastoneratenotnull = 0;
+		$this->atleastonediscount = 0;
 	}
 
 
@@ -194,11 +194,11 @@ class pdf_stdmovement extends ModelePDFMovement
 	public function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
 	{
         // phpcs:enable
-		global $user,$langs,$conf,$mysoc,$db,$hookmanager;
+		global $user, $langs, $conf, $mysoc, $db, $hookmanager;
 
-		if (! is_object($outputlangs)) $outputlangs=$langs;
+		if (!is_object($outputlangs)) $outputlangs = $langs;
 		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
-		if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1';
+		if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1';
 
 		// Load traductions files required by page
 		$outputlangs->loadLangs(array("main", "dict", "companies", "bills", "stocks", "orders", "deliveries"));
@@ -207,13 +207,13 @@ class pdf_stdmovement extends ModelePDFMovement
          * TODO: get from object
          */
 
-		$id=GETPOST('id', 'int');
+		$id = GETPOST('id', 'int');
 		$ref = GETPOST('ref', 'alpha');
-		$msid=GETPOST('msid', 'int');
-		$product_id=GETPOST("product_id");
-		$action=GETPOST('action', 'aZ09');
-		$cancel=GETPOST('cancel', 'alpha');
-		$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'movementlist';
+		$msid = GETPOST('msid', 'int');
+		$product_id = GETPOST("product_id");
+		$action = GETPOST('action', 'aZ09');
+		$cancel = GETPOST('cancel', 'alpha');
+		$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'movementlist';
 
 		$idproduct = GETPOST('idproduct', 'int');
 		$year = GETPOST("year");
@@ -227,18 +227,18 @@ class pdf_stdmovement extends ModelePDFMovement
 		$search_user = trim(GETPOST("search_user"));
 		$search_batch = trim(GETPOST("search_batch"));
 		$search_qty = trim(GETPOST("search_qty"));
-		$search_type_mouvement=GETPOST('search_type_mouvement', 'int');
+		$search_type_mouvement = GETPOST('search_type_mouvement', 'int');
 
-		$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+		$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 		$page = GETPOST("page", 'int');
 		$sortfield = GETPOST("sortfield", 'alpha');
 		$sortorder = GETPOST("sortorder", 'alpha');
 		if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
 		$offset = $limit * $page;
-		if (! $sortfield) $sortfield="m.datem";
-		if (! $sortorder) $sortorder="DESC";
+		if (!$sortfield) $sortfield = "m.datem";
+		if (!$sortorder) $sortorder = "DESC";
 
-		$pdluoid=GETPOST('pdluoid', 'int');
+		$pdluoid = GETPOST('pdluoid', 'int');
 
 		// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
 		$hookmanager->initHooks(array('movementlist'));
@@ -324,7 +324,7 @@ class pdf_stdmovement extends ModelePDFMovement
 			}
 		}
 
-		if(empty($search_inventorycode)) $sql.= $db->plimit($limit+1, $offset);
+		if (empty($search_inventorycode)) $sql .= $db->plimit($limit + 1, $offset);
 
 
 		$resql = $db->query($sql);
@@ -358,44 +358,44 @@ class pdf_stdmovement extends ModelePDFMovement
 
 				$num = $db->num_rows($resql);
 
-				$arrayofselected=is_array($toselect)?$toselect:array();
+				$arrayofselected = is_array($toselect) ? $toselect : array();
 
 				$i = 0;
-				$help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks';
+				$help_url = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks';
 				if ($msid) $texte = $langs->trans('StockMovementForId', $msid);
 				else
 				{
 					$texte = $langs->trans("ListOfStockMovements");
-					if ($id) $texte.=' ('.$langs->trans("ForThisWarehouse").')';
+					if ($id) $texte .= ' ('.$langs->trans("ForThisWarehouse").')';
 				}
 			}
 
 			// Definition of $dir and $file
 			if ($object->specimen)
 			{
-				$dir = $conf->stock->dir_output . "/movement";
-				$file = $dir . "/SPECIMEN.pdf";
+				$dir = $conf->stock->dir_output."/movement";
+				$file = $dir."/SPECIMEN.pdf";
 			}
 			else
 			{
 				$objectref = dol_sanitizeFileName($object->ref);
-				if(!empty($search_inventorycode)) $objectref.="_".$id."_".$search_inventorycode;
-				if($search_type_mouvement) $objectref.="_".$search_type_mouvement;
-				$dir = $conf->stock->dir_output . "/movement/" . $objectref;
-				$file = $dir . "/" . $objectref . ".pdf";
+				if (!empty($search_inventorycode)) $objectref .= "_".$id."_".$search_inventorycode;
+				if ($search_type_mouvement) $objectref .= "_".$search_type_mouvement;
+				$dir = $conf->stock->dir_output."/movement/".$objectref;
+				$file = $dir."/".$objectref.".pdf";
 			}
 
 			$stockFournisseur = new ProductFournisseur($this->db);
 			$supplierprices = $stockFournisseur->list_product_fournisseur_price($object->id);
 			$object->supplierprices = $supplierprices;
 
-			$productstatic=new Product($db);
+			$productstatic = new Product($db);
 
-			if (! file_exists($dir))
+			if (!file_exists($dir))
 			{
 				if (dol_mkdir($dir) < 0)
 				{
-					$this->error=$langs->transnoentities("ErrorCanNotCreateDir", $dir);
+					$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
 					return -1;
 				}
 			}
@@ -403,24 +403,24 @@ class pdf_stdmovement extends ModelePDFMovement
 			if (file_exists($dir))
 			{
 				// Add pdfgeneration hook
-				if (! is_object($hookmanager))
+				if (!is_object($hookmanager))
 				{
 					include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
-					$hookmanager=new HookManager($this->db);
+					$hookmanager = new HookManager($this->db);
 				}
 				$hookmanager->initHooks(array('pdfgeneration'));
-				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
+				$parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs);
 				global $action;
-				$reshook=$hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
+				$reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
 
 				// Create pdf instance
-				$pdf=pdf_getInstance($this->format);
-				$default_font_size = pdf_getPDFFontSize($outputlangs);	// Must be after pdf_getInstance
+				$pdf = pdf_getInstance($this->format);
+				$default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance
 				$pdf->SetAutoPageBreak(1, 0);
 
-				$heightforinfotot = 40;	// Height reserved to output the info and total part
-		        $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5);	// Height reserved to output the free text on last page
-	            $heightforfooter = $this->marge_basse + 8;	// Height reserved to output the footer (value include bottom margin)
+				$heightforinfotot = 40; // Height reserved to output the info and total part
+		        $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page
+	            $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin)
 
                 if (class_exists('TCPDF'))
                 {
@@ -429,14 +429,14 @@ class pdf_stdmovement extends ModelePDFMovement
                 }
                 $pdf->SetFont(pdf_getPDFFont($outputlangs));
                 // Set path to the background PDF File
-                if (empty($conf->global->MAIN_DISABLE_FPDI) && ! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
+                if (empty($conf->global->MAIN_DISABLE_FPDI) && !empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
                 {
                     $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND);
                     $tplidx = $pdf->importPage(1);
                 }
 
 				$pdf->Open();
-				$pagenb=0;
+				$pagenb = 0;
 				$pdf->SetDrawColor(128, 128, 128);
 
 				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
@@ -469,12 +469,12 @@ class pdf_stdmovement extends ModelePDFMovement
 				/*                                                                            */
 				/* ************************************************************************** */
 
-				$nexY+=5;
+				$nexY += 5;
 				$nexY = $pdf->GetY();
-				$nexY+=10;
+				$nexY += 10;
 
-				$totalunit=0;
-				$totalvalue=$totalvaluesell=0;
+				$totalunit = 0;
+				$totalvalue = $totalvaluesell = 0;
 				$arrayofuniqueproduct = array();
 
 				//dol_syslog('List products', LOG_DEBUG);
@@ -484,18 +484,18 @@ class pdf_stdmovement extends ModelePDFMovement
 					$num = $db->num_rows($resql);
 					$i = 0;
 					$nblines = $num;
-					for ($i = 0 ; $i < $nblines ; $i++)
+					for ($i = 0; $i < $nblines; $i++)
 					{
 						$objp = $db->fetch_object($resql);
 
 						// Multilangs
-						if (! empty($conf->global->MAIN_MULTILANGS)) // si l'option est active
+						if (!empty($conf->global->MAIN_MULTILANGS)) // si l'option est active
 						{
 							$sql = "SELECT label";
-							$sql.= " FROM ".MAIN_DB_PREFIX."product_lang";
-							$sql.= " WHERE fk_product=".$objp->rowid;
-							$sql.= " AND lang='". $langs->getDefaultLang() ."'";
-							$sql.= " LIMIT 1";
+							$sql .= " FROM ".MAIN_DB_PREFIX."product_lang";
+							$sql .= " WHERE fk_product=".$objp->rowid;
+							$sql .= " AND lang='".$langs->getDefaultLang()."'";
+							$sql .= " LIMIT 1";
 
 							$result = $db->query($sql);
 							if ($result)
@@ -599,60 +599,60 @@ class pdf_stdmovement extends ModelePDFMovement
 
 						// Id movement.
 						$pdf->SetXY($this->posxidref, $curY);
-						$pdf->MultiCell($this->posxdesc-$this->posxidref-0.8, 3, $objp->mid, 0, 'L');
+						$pdf->MultiCell($this->posxdesc - $this->posxidref - 0.8, 3, $objp->mid, 0, 'L');
 
 						// Date.
 						$pdf->SetXY($this->posxdatemouv, $curY);
-						$pdf->MultiCell($this->posxdesc-$this->posxdatemouv-0.8, 6, dol_print_date($db->jdate($objp->datem), 'dayhour'), 0, 'L');
+						$pdf->MultiCell($this->posxdesc - $this->posxdatemouv - 0.8, 6, dol_print_date($db->jdate($objp->datem), 'dayhour'), 0, 'L');
 
 						// Ref.
 						$pdf->SetXY($this->posxdesc, $curY);
-						$pdf->MultiCell($this->posxlabel-$this->posxdesc-0.8, 3, $productstatic->ref, 0, 'L');
+						$pdf->MultiCell($this->posxlabel - $this->posxdesc - 0.8, 3, $productstatic->ref, 0, 'L');
 
 						// Label
-						$pdf->SetXY($this->posxlabel+0.8, $curY);
-						$pdf->MultiCell($this->posxqty-$this->posxlabel-0.8, 6, $productstatic->label, 0, 'L');
+						$pdf->SetXY($this->posxlabel + 0.8, $curY);
+						$pdf->MultiCell($this->posxqty - $this->posxlabel - 0.8, 6, $productstatic->label, 0, 'L');
 
 						// Lot/serie
 						$pdf->SetXY($this->posxqty, $curY);
-						$pdf->MultiCell($this->posxup-$this->posxqty-0.8, 3, $productlot->batch, 0, 'R');
+						$pdf->MultiCell($this->posxup - $this->posxqty - 0.8, 3, $productlot->batch, 0, 'R');
 
 						// Inv. code
 						$pdf->SetXY($this->posxup, $curY);
-						$pdf->MultiCell($this->posxunit-$this->posxup-0.8, 3, $objp->inventorycode, 0, 'R');
+						$pdf->MultiCell($this->posxunit - $this->posxup - 0.8, 3, $objp->inventorycode, 0, 'R');
 
 						// Label mouvement
 						$pdf->SetXY($this->posxunit, $curY);
-						$pdf->MultiCell($this->posxdiscount-$this->posxunit-0.8, 3, $objp->label, 0, 'R');
-						$totalvalue+=price2num($objp->ppmp*$objp->value, 'MT');
+						$pdf->MultiCell($this->posxdiscount - $this->posxunit - 0.8, 3, $objp->label, 0, 'R');
+						$totalvalue += price2num($objp->ppmp * $objp->value, 'MT');
 
 						// Origin
-						$pricemin=$objp->price;
+						$pricemin = $objp->price;
 						$pdf->SetXY($this->posxdiscount, $curY);
-						$pdf->MultiCell($this->postotalht-$this->posxdiscount-0.8, 3, $origin, 0, 'R', 0);
+						$pdf->MultiCell($this->postotalht - $this->posxdiscount - 0.8, 3, $origin, 0, 'R', 0);
 
 						// Qty
-						$valtoshow=price2num($objp->qty, 'MS');
-						$towrite = (empty($valtoshow)?'0':$valtoshow);
-						$totalunit+=$objp->qty;
+						$valtoshow = price2num($objp->qty, 'MS');
+						$towrite = (empty($valtoshow) ? '0' : $valtoshow);
+						$totalunit += $objp->qty;
 
 						$pdf->SetXY($this->postotalht, $curY);
-						$pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalht, 3, $objp->qty, 0, 'R', 0);
+						$pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalht, 3, $objp->qty, 0, 'R', 0);
 
-						$totalvaluesell+=price2num($pricemin*$objp->value, 'MT');
+						$totalvaluesell += price2num($pricemin * $objp->value, 'MT');
 
-						$nexY+=3.5;    // Add space between lines
+						$nexY += 3.5; // Add space between lines
 						// Add line
-						if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1))
+						if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1))
 						{
 							$pdf->setPage($pageposafter);
-							$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80)));
+							$pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80)));
 							//$pdf->SetDrawColor(190,190,200);
-							$pdf->line($this->marge_gauche, $nexY+1, $this->page_largeur - $this->marge_droite, $nexY+1);
+							$pdf->line($this->marge_gauche, $nexY + 1, $this->page_largeur - $this->marge_droite, $nexY + 1);
 							$pdf->SetLineStyle(array('dash'=>0));
 						}
 
-						$nexY+=2;    // Add space between lines
+						$nexY += 2; // Add space between lines
 
 						// Detect if some page were added automatically and output _tableau for past pages
 						while ($pagenb < $pageposafter)
@@ -669,10 +669,10 @@ class pdf_stdmovement extends ModelePDFMovement
 							$this->_pagefoot($pdf, $object, $outputlangs, 1);
 							$pagenb++;
 							$pdf->setPage($pagenb);
-							$pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
+							$pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it.
 							if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
 						}
-						if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak)
+						if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak)
 						{
 							if ($pagenb == 1)
 							{
@@ -685,7 +685,7 @@ class pdf_stdmovement extends ModelePDFMovement
 							$this->_pagefoot($pdf, $object, $outputlangs, 1);
 							// New page
 							$pdf->AddPage();
-							if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+							if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 							$pagenb++;
 							if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
 						}
@@ -697,23 +697,23 @@ class pdf_stdmovement extends ModelePDFMovement
 					 * footer table
 					 */
 					$nexY = $pdf->GetY();
-					$nexY+=5;
+					$nexY += 5;
 					$curY = $nexY;
 
-					$pdf->SetLineStyle(array('dash'=>'0','color'=>array(220,26,26)));
-					$pdf->line($this->marge_gauche, $curY-1, $this->page_largeur-$this->marge_droite, $curY-1);
+					$pdf->SetLineStyle(array('dash'=>'0', 'color'=>array(220, 26, 26)));
+					$pdf->line($this->marge_gauche, $curY - 1, $this->page_largeur - $this->marge_droite, $curY - 1);
 					$pdf->SetLineStyle(array('dash'=>0));
 
-					$pdf->SetFont('', 'B', $default_font_size-1);
+					$pdf->SetFont('', 'B', $default_font_size - 1);
 					$pdf->SetTextColor(0, 0, 120);
 
 					// Total
 					$pdf->SetXY($this->posxidref, $curY);
-					$pdf->MultiCell($this->posxdesc-$this->posxidref, 3, $langs->trans("Total"), 0, 'L');
+					$pdf->MultiCell($this->posxdesc - $this->posxidref, 3, $langs->trans("Total"), 0, 'L');
 
 					// Total Qty
 					$pdf->SetXY($this->postotalht, $curY);
-					$pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalht, 3, $totalunit, 0, 'R', 0);
+					$pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalht, 3, $totalunit, 0, 'R', 0);
 				}
 				else
 				{
@@ -722,7 +722,7 @@ class pdf_stdmovement extends ModelePDFMovement
 
 				if ($notetoshow)
 				{
-					$substitutionarray=pdf_getSubstitutionArray($outputlangs, null, $object);
+					$substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object);
 					complete_substitutions_array($substitutionarray, $outputlangs, $object);
 					$notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs);
 					$notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow);
@@ -730,41 +730,41 @@ class pdf_stdmovement extends ModelePDFMovement
 					$tab_top = 88;
 
 					$pdf->SetFont('', '', $default_font_size - 1);
-					$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1);
+					$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1);
 					$nexY = $pdf->GetY();
-					$height_note=$nexY-$tab_top;
+					$height_note = $nexY - $tab_top;
 
 					// Rect takes a length in 3rd parameter
 					$pdf->SetDrawColor(192, 192, 192);
-					$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);
+					$pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1);
 
 					$tab_height = $tab_height - $height_note;
-					$tab_top = $nexY+6;
+					$tab_top = $nexY + 6;
 				}
 				else
 				{
-					$height_note=0;
+					$height_note = 0;
 				}
 
 				$iniY = $tab_top + 7;
 				$curY = $tab_top + 7;
 				$nexY = $tab_top + 7;
 
-				$tab_top = $tab_top_newpage+21;
+				$tab_top = $tab_top_newpage + 21;
 
 				// Show square
 				if ($pagenb == 1)
 				{
 					$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0, $object->multicurrency_code);
-					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
+					$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
 				}
 				else
 				{
 					$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code);
-					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
+					$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
 				}
 
-				$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
+				$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
 
 				// Affiche zone infos
 				//$posy=$this->_tableau_info($pdf, $object, $bottomlasttab, $outputlangs);
@@ -782,31 +782,31 @@ class pdf_stdmovement extends ModelePDFMovement
 
 				// Add pdfgeneration hook
 				$hookmanager->initHooks(array('pdfgeneration'));
-				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
+				$parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs);
 				global $action;
-				$reshook=$hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
+				$reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
 				if ($reshook < 0)
 				{
 				    $this->error = $hookmanager->error;
 				    $this->errors = $hookmanager->errors;
 				}
 
-				if (! empty($conf->global->MAIN_UMASK))
+				if (!empty($conf->global->MAIN_UMASK))
 					@chmod($file, octdec($conf->global->MAIN_UMASK));
 
 				$this->result = array('fullpath'=>$file);
 
-				return 1;   // No error
+				return 1; // No error
 			}
 			else
 			{
-				$this->error=$langs->trans("ErrorCanNotCreateDir", $dir);
+				$this->error = $langs->trans("ErrorCanNotCreateDir", $dir);
 				return 0;
 			}
 		}
 		else
 		{
-			$this->error=$langs->trans("ErrorConstantNotDefined", "PRODUCT_OUTPUTDIR");
+			$this->error = $langs->trans("ErrorConstantNotDefined", "PRODUCT_OUTPUTDIR");
 			return 0;
 		}
 	}
@@ -830,8 +830,8 @@ class pdf_stdmovement extends ModelePDFMovement
 	    global $conf;
 
 	    // Force to disable hidetop and hidebottom
-	    $hidebottom=0;
-	    if ($hidetop) $hidetop=-1;
+	    $hidebottom = 0;
+	    if ($hidetop) $hidetop = -1;
 
 	    $currency = !empty($currency) ? $currency : $conf->currency;
 	    $default_font_size = pdf_getPDFFontSize($outputlangs);
@@ -843,11 +843,11 @@ class pdf_stdmovement extends ModelePDFMovement
 	    if (empty($hidetop))
 	    {
 	        $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency));
-	        $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top-4);
+	        $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4);
 	        $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre);
 
 	        //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230';
-	        if (! empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite-$this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
+	        if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, 5, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
 	    }
 
 	    $pdf->SetDrawColor(128, 128, 128);
@@ -856,9 +856,9 @@ class pdf_stdmovement extends ModelePDFMovement
 	    // Output Rect
 	    //$this->printRect($pdf,$this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom);	// Rect takes a length in 3rd parameter and 4th parameter
 
-		$pdf->SetLineStyle(array('dash'=>'0','color'=>array(220,26,26)));
+		$pdf->SetLineStyle(array('dash'=>'0', 'color'=>array(220, 26, 26)));
 		$pdf->SetDrawColor(220, 26, 26);
-		$pdf->line($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_droite, $tab_top);
+		$pdf->line($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite, $tab_top);
 		$pdf->SetLineStyle(array('dash'=>0));
 		$pdf->SetDrawColor(128, 128, 128);
 		$pdf->SetTextColor(0, 0, 120);
@@ -867,32 +867,32 @@ class pdf_stdmovement extends ModelePDFMovement
 	    if (empty($hidetop))
 	    {
 	        //$pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5);	// line takes a position y in 2nd parameter and 4th parameter
-	        $pdf->SetXY($this->posxidref, $tab_top+1);
-	        $pdf->MultiCell($this->posxdatemouv-$this->posxdatemouv-0.8, 3, $outputlangs->transnoentities("Ref"), '', 'L');
+	        $pdf->SetXY($this->posxidref, $tab_top + 1);
+	        $pdf->MultiCell($this->posxdatemouv - $this->posxdatemouv - 0.8, 3, $outputlangs->transnoentities("Ref"), '', 'L');
 	    }
 
 		//Date mouv
 		//$pdf->line($this->posxlabel-1, $tab_top, $this->posxlabel-1, $tab_top + $tab_height);
 		if (empty($hidetop))
 		{
-			$pdf->SetXY($this->posxdatemouv, $tab_top+1);
-			$pdf->MultiCell($this->posxdesc-$this->posxdatemouv, 2, $outputlangs->transnoentities("Date"), '', 'C');
+			$pdf->SetXY($this->posxdatemouv, $tab_top + 1);
+			$pdf->MultiCell($this->posxdesc - $this->posxdatemouv, 2, $outputlangs->transnoentities("Date"), '', 'C');
 		}
 
 		//Ref Product
 	    //$pdf->line($this->posxqty-1, $tab_top, $this->posxqty-1, $tab_top + $tab_height);
 	    if (empty($hidetop))
 	    {
-	        $pdf->SetXY($this->posxdesc-1, $tab_top+1);
-	        $pdf->MultiCell($this->posxlabel-$this->posxdesc, 2, $outputlangs->transnoentities("Ref. Product"), '', 'C');
+	        $pdf->SetXY($this->posxdesc - 1, $tab_top + 1);
+	        $pdf->MultiCell($this->posxlabel - $this->posxdesc, 2, $outputlangs->transnoentities("Ref. Product"), '', 'C');
 	    }
 
 		//Label Product
 	    //$pdf->line($this->posxup-1, $tab_top, $this->posxup-1, $tab_top + $tab_height);
 	    if (empty($hidetop))
 	    {
-	        $pdf->SetXY($this->posxlabel-1, $tab_top+1);
-			$pdf->MultiCell($this->posxqty-$this->posxlabel, 2, $outputlangs->transnoentities("Label"), '', 'C');
+	        $pdf->SetXY($this->posxlabel - 1, $tab_top + 1);
+			$pdf->MultiCell($this->posxqty - $this->posxlabel, 2, $outputlangs->transnoentities("Label"), '', 'C');
 	    }
 
 		//Lot/serie Product
@@ -907,37 +907,37 @@ class pdf_stdmovement extends ModelePDFMovement
 	    //$pdf->line($this->posxup-1, $tab_top, $this->posxup-1, $tab_top + $tab_height);
 	    if (empty($hidetop))
 	    {
-			$pdf->SetXY($this->posxup-1, $tab_top+1);
-			$pdf->MultiCell($this->posxunit-$this->posxup, 2, $outputlangs->transnoentities("Inventory Code"), '', 'C');
+			$pdf->SetXY($this->posxup - 1, $tab_top + 1);
+			$pdf->MultiCell($this->posxunit - $this->posxup, 2, $outputlangs->transnoentities("Inventory Code"), '', 'C');
 	    }
 
 		//Label mouvement
 	    //$pdf->line($this->posxunit, $tab_top, $this->posxunit, $tab_top + $tab_height);
 	    if (empty($hidetop))
 	    {
-	        $pdf->SetXY($this->posxunit, $tab_top+1);
-	        $pdf->MultiCell($this->posxdiscount-$this->posxunit, 2, $outputlangs->transnoentities("Label Mouvement"), '', 'C');
+	        $pdf->SetXY($this->posxunit, $tab_top + 1);
+	        $pdf->MultiCell($this->posxdiscount - $this->posxunit, 2, $outputlangs->transnoentities("Label Mouvement"), '', 'C');
 	    }
 
 		//Origin
 	    //$pdf->line($this->postotalht, $tab_top, $this->postotalht, $tab_top + $tab_height);
 	    if (empty($hidetop))
 	    {
-	        $pdf->SetXY($this->posxdiscount+2, $tab_top+1);
-	        $pdf->MultiCell($this->postotalht-$this->posxdiscount-0.8, 2, $outputlangs->transnoentities("Origin"), '', 'C');
+	        $pdf->SetXY($this->posxdiscount + 2, $tab_top + 1);
+	        $pdf->MultiCell($this->postotalht - $this->posxdiscount - 0.8, 2, $outputlangs->transnoentities("Origin"), '', 'C');
 	    }
 
 		//Qty
 	    //$pdf->line($this->postotalht, $tab_top, $this->postotalht, $tab_top + $tab_height);
 	    if (empty($hidetop))
 	    {
-	        $pdf->SetXY($this->postotalht+2, $tab_top+1);
-	        $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalht, 2, $outputlangs->transnoentities("Qty"), '', 'C');
+	        $pdf->SetXY($this->postotalht + 2, $tab_top + 1);
+	        $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalht, 2, $outputlangs->transnoentities("Qty"), '', 'C');
 	    }
 
 		$pdf->SetDrawColor(220, 26, 26);
-		$pdf->SetLineStyle(array('dash'=>'0','color'=>array(220,26,26)));
-		$pdf->line($this->marge_gauche, $tab_top+11, $this->page_largeur-$this->marge_droite, $tab_top+11);
+		$pdf->SetLineStyle(array('dash'=>'0', 'color'=>array(220, 26, 26)));
+		$pdf->line($this->marge_gauche, $tab_top + 11, $this->page_largeur - $this->marge_droite, $tab_top + 11);
 		$pdf->SetLineStyle(array('dash'=>0));
 	}
 
@@ -954,20 +954,20 @@ class pdf_stdmovement extends ModelePDFMovement
 	 */
 	protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $titlekey = "")
 	{
-	    global $conf,$langs,$db,$hookmanager;
+	    global $conf, $langs, $db, $hookmanager;
 
 	    // Load traductions files required by page
 		$outputlangs->loadLangs(array("main", "propal", "companies", "bills", "orders", "stocks"));
 
 	    $default_font_size = pdf_getPDFFontSize($outputlangs);
 
-	    if ($object->type == 1) $titlekey='ServiceSheet';
-	    else $titlekey='StockSheet';
+	    if ($object->type == 1) $titlekey = 'ServiceSheet';
+	    else $titlekey = 'StockSheet';
 
 	    pdf_pagehead($pdf, $outputlangs, $this->page_hauteur);
 
 	    // Show Draft Watermark
-	    if($object->statut==0 && (! empty($conf->global->COMMANDE_DRAFT_WATERMARK)) )
+	    if ($object->statut == 0 && (!empty($conf->global->COMMANDE_DRAFT_WATERMARK)))
 	    {
 	        pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->COMMANDE_DRAFT_WATERMARK);
 	    }
@@ -1048,25 +1048,25 @@ class pdf_stdmovement extends ModelePDFMovement
 
 		// Description
 		$nexY = $pdf->GetY();
-		$nexY+=5;
+		$nexY += 5;
 		$pdf->SetXY($posx, $posy);
 		$pdf->writeHTMLCell(190, 2, $this->marge_gauche, $nexY, '<b>'.$outputlangs->transnoentities("Description").' : </b>'.nl2br($object->description), 0, 1);
 		$nexY = $pdf->GetY();
 
-		$calcproductsunique=$object->nb_different_products();
-		$calcproducts=$object->nb_products();
+		$calcproductsunique = $object->nb_different_products();
+		$calcproducts = $object->nb_products();
 
 		// Total nb of different products
-		$pdf->writeHTMLCell(190, 2, $this->marge_gauche, $nexY, '<b>'.$outputlangs->transnoentities("NumberOfDifferentProducts").' : </b>'.(empty($calcproductsunique['nb'])?'0':$calcproductsunique['nb']), 0, 1);
+		$pdf->writeHTMLCell(190, 2, $this->marge_gauche, $nexY, '<b>'.$outputlangs->transnoentities("NumberOfDifferentProducts").' : </b>'.(empty($calcproductsunique['nb']) ? '0' : $calcproductsunique['nb']), 0, 1);
 		$nexY = $pdf->GetY();
 
 		// Nb of products
-		$valtoshow=price2num($calcproducts['nb'], 'MS');
-		$pdf->writeHTMLCell(190, 2, $this->marge_gauche, $nexY, '<b>'.$outputlangs->transnoentities("NumberOfProducts").' : </b>'.(empty($valtoshow)?'0':$valtoshow), 0, 1);
+		$valtoshow = price2num($calcproducts['nb'], 'MS');
+		$pdf->writeHTMLCell(190, 2, $this->marge_gauche, $nexY, '<b>'.$outputlangs->transnoentities("NumberOfProducts").' : </b>'.(empty($valtoshow) ? '0' : $valtoshow), 0, 1);
 		$nexY = $pdf->GetY();
 
 		// Value
-		$pdf->writeHTMLCell(190, 2, $this->marge_gauche, $nexY, '<b>'.$outputlangs->transnoentities("EstimatedStockValueShort").' : </b>'. price((empty($calcproducts['value'])?'0':price2num($calcproducts['value'], 'MT')), 0, $langs, 0, -1, -1, $conf->currency), 0, 1);
+		$pdf->writeHTMLCell(190, 2, $this->marge_gauche, $nexY, '<b>'.$outputlangs->transnoentities("EstimatedStockValueShort").' : </b>'.price((empty($calcproducts['value']) ? '0' : price2num($calcproducts['value'], 'MT')), 0, $langs, 0, -1, -1, $conf->currency), 0, 1);
 		$nexY = $pdf->GetY();
 
 
@@ -1078,7 +1078,7 @@ class pdf_stdmovement extends ModelePDFMovement
 		if ($resqlbis)
 		{
 			$obj = $db->fetch_object($resqlbis);
-			$lastmovementdate=$db->jdate($obj->datem);
+			$lastmovementdate = $db->jdate($obj->datem);
 		}
 		else
 		{
@@ -1128,7 +1128,7 @@ class pdf_stdmovement extends ModelePDFMovement
 	        }
 	    }*/
 
-	    $posy+=2;
+	    $posy += 2;
 
 	    // Show list of linked objects
 	    //$posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, 100, 3, 'R', $default_font_size);
@@ -1184,7 +1184,7 @@ class pdf_stdmovement extends ModelePDFMovement
 	protected function _pagefoot(&$pdf, $object, $outputlangs, $hidefreetext = 0)
 	{
 	    global $conf;
-	    $showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
+	    $showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
 	    return pdf_pagefoot($pdf, $outputlangs, 'PRODUCT_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext);
 	}
 }

+ 3 - 3
htdocs/core/tpl/extrafields_add.tpl.php

@@ -26,7 +26,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;
@@ -41,8 +41,8 @@ $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)) {
-	$params = isset($tpl_context) ? array('tpl_context' => $tpl_context) : array();	// BUG #11554 : Add tpl_context in params
-	print $object->showOptionals($extrafields, 'edit', $params);				// BUG #11554 : Add context in params
+	$params = isset($tpl_context) ? array('tpl_context' => $tpl_context) : array(); // BUG #11554 : Add tpl_context in params
+	print $object->showOptionals($extrafields, 'edit', $params); // BUG #11554 : Add context in params
 }
 
 ?>

+ 11 - 11
htdocs/core/tpl/extrafields_view.tpl.php

@@ -26,22 +26,22 @@
  */
 
 // Protection to avoid direct call of template
-if (empty($object) || ! is_object($object))
+if (empty($object) || !is_object($object))
 {
 	print "Error, template page can't be called as URL";
 	exit;
 }
 
-if (! is_object($form)) $form=new Form($db);
+if (!is_object($form)) $form = new Form($db);
 
 
 ?>
 <!-- BEGIN PHP TEMPLATE extrafields_view.tpl.php -->
 <?php
-if (! is_array($parameters)) $parameters = array();
-if (! empty($cols)) $parameters['colspan'] = ' colspan="'.$cols.'"';
-if (! empty($cols)) $parameters['cols'] = $cols;
-if (! empty($object->fk_soc)) $parameters['socid'] = $object->fk_soc;
+if (!is_array($parameters)) $parameters = array();
+if (!empty($cols)) $parameters['colspan'] = ' colspan="'.$cols.'"';
+if (!empty($cols)) $parameters['cols'] = $cols;
+if (!empty($object->fk_soc)) $parameters['socid'] = $object->fk_soc;
 $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);
 print $hookmanager->resPrint;
 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
@@ -94,10 +94,10 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element]
             if (!empty($extrafield_param) && is_array($extrafield_param)) {
                 $extrafield_param_list = array_keys($extrafield_param['options']);
 
-                if (count($extrafield_param_list)>0) {
+                if (count($extrafield_param_list) > 0) {
                     $extrafield_collapse_display_value = intval($extrafield_param_list[0]);
 
-                    if ($extrafield_collapse_display_value==1 || $extrafield_collapse_display_value==2) {
+                    if ($extrafield_collapse_display_value == 1 || $extrafield_collapse_display_value == 2) {
                         $extrafields_collapse_num = $extrafields->attributes[$object->table_element]['pos'][$key];
                     }
                 }
@@ -105,7 +105,7 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element]
 
 			print $extrafields->showSeparator($key, $object);
 
-			$lastseparatorkeyfound=$key;
+			$lastseparatorkeyfound = $key;
 		}
 		else
 		{
@@ -184,14 +184,14 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element]
 			}
 
 			print '</td>';
-			print '</tr>' . "\n";
+			print '</tr>'."\n";
 		}
 	}
 
 
 	// Add code to manage list depending on others
 	// TODO Test/enhance this with a more generic solution
-	if (! empty($conf->use_javascript_ajax))
+	if (!empty($conf->use_javascript_ajax))
 	{
 		print "\n";
 		print '

+ 13 - 13
htdocs/core/tpl/objectline_create.tpl.php

@@ -115,12 +115,12 @@ if ($nolinesbefore) {
 	<?php if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) { ?>
 	<td class="linecoluht_currency right"><span id="title_up_ht_currency"><?php echo $langs->trans('PriceUHTCurrency'); ?></span></td>
 	<?php } ?>
-	<?php if (! empty($inputalsopricewithtax)) { ?>
+	<?php if (!empty($inputalsopricewithtax)) { ?>
 	<td class="linecoluttc right"><span id="title_up_ttc"><?php echo $langs->trans('PriceUTTC'); ?></span></td>
 	<?php } ?>
 	<td class="linecolqty right"><?php echo $langs->trans('Qty'); ?></td>
 	<?php
-	if($conf->global->PRODUCT_USE_UNITS)
+	if ($conf->global->PRODUCT_USE_UNITS)
 	{
 		print '<td class="linecoluseunit left">';
 		print '<span id="title_units">';
@@ -466,20 +466,20 @@ $coldisplay+=$colspan;
 
 <?php
 if (is_object($objectline)) {
-	print $objectline->showOptionals($extrafields, 'edit', array('colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
+	print $objectline->showOptionals($extrafields, 'edit', array('colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1);
 }
 
-if ((! empty($conf->service->enabled) || ($object->element == 'contrat')) && $dateSelector && GETPOST('type') != '0')	// We show date field if required
+if ((!empty($conf->service->enabled) || ($object->element == 'contrat')) && $dateSelector && GETPOST('type') != '0')	// We show date field if required
 {
 	?>
 
 	<tr id="trlinefordates" <?php echo $bcnd[$var]; ?>>
-	<?php if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { print '<td></td>'; } ?>
-	<td colspan="<?php echo $coldisplay - (empty($conf->global->MAIN_VIEW_LINE_NUMBER)?0:1); ?>">
+	<?php if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { print '<td></td>'; } ?>
+	<td colspan="<?php echo $coldisplay - (empty($conf->global->MAIN_VIEW_LINE_NUMBER) ? 0 : 1); ?>">
 	<?php
-	$date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
-	$date_end=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
-	if (! empty($object->element) && $object->element == 'contrat')
+	$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
+	$date_end = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
+	if (!empty($object->element) && $object->element == 'contrat')
 	{
 		print $langs->trans("DateStartPlanned").' ';
 		print $form->selectDate($date_start, "date_start", $usehm, $usehm, 1, "addproduct");
@@ -489,9 +489,9 @@ if ((! empty($conf->service->enabled) || ($object->element == 'contrat')) && $da
 	else
 	{
 		echo $langs->trans('ServiceLimitedDuration').' '.$langs->trans('From').' ';
-		print $form->selectDate($date_start, 'date_start', empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE)?0:1, empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE)?0:1, 1, "addproduct", 1, 0);
+		print $form->selectDate($date_start, 'date_start', empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? 0 : 1, empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? 0 : 1, 1, "addproduct", 1, 0);
 		echo ' '.$langs->trans('to').' ';
-		print $form->selectDate($date_end, 'date_end', empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE)?0:1, empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE)?0:1, 1, "addproduct", 1, 0);
+		print $form->selectDate($date_end, 'date_end', empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? 0 : 1, empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? 0 : 1, 1, "addproduct", 1, 0);
 	};
 	print '<script>';
 	if (!$date_start) {
@@ -649,7 +649,7 @@ jQuery(document).ready(function() {
 	});
 
 	<?php
-	if(!$freelines) { ?>
+	if (!$freelines) { ?>
 		$("#prod_entry_mode_predef").click();
 		<?php
 	}
@@ -676,7 +676,7 @@ jQuery(document).ready(function() {
 			<?php
 		}
 
-		if (! empty($usemargins) && $user->rights->margins->creer)
+		if (!empty($usemargins) && $user->rights->margins->creer)
 		{
 			$langs->load('stocks');
 			?>

+ 29 - 29
htdocs/core/tpl/objectline_edit.tpl.php

@@ -71,7 +71,7 @@ $coldisplay++;
 
 	<input type="hidden" name="lineid" value="<?php echo $line->id; ?>">
 	<input type="hidden" id="product_type" name="type" value="<?php echo $line->product_type; ?>">
-	<input type="hidden" id="product_id" name="productid" value="<?php echo (! empty($line->fk_product)?$line->fk_product:0); ?>" />
+	<input type="hidden" id="product_id" name="productid" value="<?php echo (!empty($line->fk_product) ? $line->fk_product : 0); ?>" />
 	<input type="hidden" id="special_code" name="special_code" value="<?php echo $line->special_code; ?>">
 	<input type="hidden" id="fk_parent_line" name="fk_parent_line" value="<?php echo $line->fk_parent_line; ?>">
 
@@ -81,7 +81,7 @@ $coldisplay++;
 		?>
 		<a href="<?php echo DOL_URL_ROOT.'/product/card.php?id='.$line->fk_product; ?>">
 		<?php
-		if ($line->product_type==1) echo img_object($langs->trans('ShowService'), 'service');
+		if ($line->product_type == 1) echo img_object($langs->trans('ShowService'), 'service');
 		else print img_object($langs->trans('ShowProduct'), 'product');
 		echo ' '.$line->ref;
 		?>
@@ -98,28 +98,28 @@ $coldisplay++;
 	if (is_object($hookmanager))
 	{
 		$fk_parent_line = (GETPOST('fk_parent_line') ? GETPOST('fk_parent_line') : $line->fk_parent_line);
-	    $parameters=array('line'=>$line,'fk_parent_line'=>$fk_parent_line,'var'=>$var,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer);
-	    $reshook=$hookmanager->executeHooks('formEditProductOptions', $parameters, $this, $action);
+	    $parameters = array('line'=>$line, 'fk_parent_line'=>$fk_parent_line, 'var'=>$var, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer);
+	    $reshook = $hookmanager->executeHooks('formEditProductOptions', $parameters, $this, $action);
 	}
 
 	// Do not allow editing during a situation cycle
-	if ($line->fk_prev_id == null )
+	if ($line->fk_prev_id == null)
 	{
 		// editeur wysiwyg
 		require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-		$nbrows=ROWS_2;
-		if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
-		$enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0);
-		$toolbarname='dolibarr_details';
-		if (! empty($conf->global->FCKEDITOR_ENABLE_DETAILS_FULL)) $toolbarname='dolibarr_notes';
-		$doleditor=new DolEditor('product_desc', $line->description, '', (empty($conf->global->MAIN_DOLEDITOR_HEIGHT)?164:$conf->global->MAIN_DOLEDITOR_HEIGHT), $toolbarname, '', false, true, $enable, $nbrows, '98%');
+		$nbrows = ROWS_2;
+		if (!empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows = $conf->global->MAIN_INPUT_DESC_HEIGHT;
+		$enable = (isset($conf->global->FCKEDITOR_ENABLE_DETAILS) ? $conf->global->FCKEDITOR_ENABLE_DETAILS : 0);
+		$toolbarname = 'dolibarr_details';
+		if (!empty($conf->global->FCKEDITOR_ENABLE_DETAILS_FULL)) $toolbarname = 'dolibarr_notes';
+		$doleditor = new DolEditor('product_desc', $line->description, '', (empty($conf->global->MAIN_DOLEDITOR_HEIGHT) ? 164 : $conf->global->MAIN_DOLEDITOR_HEIGHT), $toolbarname, '', false, true, $enable, $nbrows, '98%');
 		$doleditor->Create();
 	} else {
-		print '<textarea id="product_desc" class="flat" name="product_desc" readonly style="width: 200px; height:80px;">' . $line->description . '</textarea>';
+		print '<textarea id="product_desc" class="flat" name="product_desc" readonly style="width: 200px; height:80px;">'.$line->description.'</textarea>';
 	}
 
 	// Show autofill date for recuring invoices
-	if (! empty($conf->service->enabled) && $line->product_type == 1 && $line->element == 'facturedetrec')
+	if (!empty($conf->service->enabled) && $line->product_type == 1 && $line->element == 'facturedetrec')
 	{
 		echo '<br>';
 		echo $langs->trans('AutoFillDateFrom').' ';
@@ -143,13 +143,13 @@ $coldisplay++;
 
 	$coldisplay++;
 	if ($line->fk_prev_id == null) {
-		print '<td class="right">' . $form->load_tva('tva_tx', $line->tva_tx.($line->vat_src_code?(' ('.$line->vat_src_code.')'):''), $seller, $buyer, 0, $line->info_bits, $line->product_type, false, 1) . '</td>';
+		print '<td class="right">'.$form->load_tva('tva_tx', $line->tva_tx.($line->vat_src_code ? (' ('.$line->vat_src_code.')') : ''), $seller, $buyer, 0, $line->info_bits, $line->product_type, false, 1).'</td>';
 	} else {
-		print '<td class="right"><input size="1" type="text" class="flat right" name="tva_tx" value="' . price($line->tva_tx) . '" readonly />%</td>';
+		print '<td class="right"><input size="1" type="text" class="flat right" name="tva_tx" value="'.price($line->tva_tx).'" readonly />%</td>';
 	}
 
 	$coldisplay++;
-	print '<td class="right"><input type="text" class="flat right" size="5" id="price_ht" name="price_ht" value="' . (isset($line->pu_ht)?price($line->pu_ht, 0, '', 0):price($line->subprice, 0, '', 0)) . '"';
+	print '<td class="right"><input type="text" class="flat right" size="5" id="price_ht" name="price_ht" value="'.(isset($line->pu_ht) ?price($line->pu_ht, 0, '', 0) : price($line->subprice, 0, '', 0)).'"';
 	if ($line->fk_prev_id != null) print ' readonly';
 	print '></td>';
 
@@ -161,7 +161,7 @@ $coldisplay++;
 	if ($inputalsopricewithtax)
 	{
 		$coldisplay++;
-		print '<td class="right"><input type="text" class="flat right" size="5" id="price_ttc" name="price_ttc" value="'.(isset($line->pu_ttc)?price($line->pu_ttc, 0, '', 0):'').'"';
+		print '<td class="right"><input type="text" class="flat right" size="5" id="price_ttc" name="price_ttc" value="'.(isset($line->pu_ttc) ?price($line->pu_ttc, 0, '', 0) : '').'"';
 		if ($line->fk_prev_id != null) print ' readonly';
 		print '></td>';
 	}
@@ -173,8 +173,8 @@ $coldisplay++;
 		// for example always visible on invoice but must be visible only if stock module on and stock decrease option is on invoice validation and status is not validated
 		// must also not be output for most entities (proposal, intervention, ...)
 		//if($line->qty > $line->stock) print img_picto($langs->trans("StockTooLow"),"warning", 'style="vertical-align: bottom;"')." ";
-		print '<input size="3" type="text" class="flat right" name="qty" id="qty" value="' . $line->qty . '"';
-		if ($line->fk_prev_id != null ) print ' readonly';
+		print '<input size="3" type="text" class="flat right" name="qty" id="qty" value="'.$line->qty.'"';
+		if ($line->fk_prev_id != null) print ' readonly';
 		print '>';
 	} else { ?>
 		&nbsp;
@@ -182,7 +182,7 @@ $coldisplay++;
 	</td>
 
 	<?php
-	if($conf->global->PRODUCT_USE_UNITS)
+	if ($conf->global->PRODUCT_USE_UNITS)
 	{
 	    $coldisplay++;
 		print '<td class="left">';
@@ -204,11 +204,11 @@ $coldisplay++;
 	<?php
 	if ($this->situation_cycle_ref) {
 		$coldisplay++;
-		print '<td class="nowrap right linecolcycleref"><input class="right" type="text" size="1" value="' . $line->situation_percent . '" name="progress">%</td>';
+		print '<td class="nowrap right linecolcycleref"><input class="right" type="text" size="1" value="'.$line->situation_percent.'" name="progress">%</td>';
 		$coldisplay++;
 		print '<td></td>';
 	}
-	if (! empty($usemargins))
+	if (!empty($usemargins))
 	{
         if (!empty($user->rights->margins->creer))
         {
@@ -225,9 +225,9 @@ $coldisplay++;
 		<?php }
 
         if ($user->rights->margins->creer) {
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
+			if (!empty($conf->global->DISPLAY_MARGIN_RATES))
 			{
-				$margin_rate = (isset($_POST["np_marginRate"])?GETPOST("np_marginRate", "alpha", 2):(($line->pa_ht == 0)?'':price($line->marge_tx)));
+				$margin_rate = (isset($_POST["np_marginRate"]) ?GETPOST("np_marginRate", "alpha", 2) : (($line->pa_ht == 0) ? '' : price($line->marge_tx)));
 				// if credit note, dont allow to modify margin
 				if ($line->subprice < 0)
 					echo '<td class="right nowrap margininfos">'.$margin_rate.'<span class="hideonsmartphone">%</span></td>';
@@ -235,9 +235,9 @@ $coldisplay++;
 					echo '<td class="right nowrap margininfos"><input class="right maxwidth75" type="text" name="np_marginRate" value="'.$margin_rate.'"><span class="hideonsmartphone">%</span></td>';
 				$coldisplay++;
 			}
-			elseif (! empty($conf->global->DISPLAY_MARK_RATES))
+			elseif (!empty($conf->global->DISPLAY_MARK_RATES))
 			{
-				$mark_rate = (isset($_POST["np_markRate"])?GETPOST("np_markRate", 'alpha', 2):price($line->marque_tx));
+				$mark_rate = (isset($_POST["np_markRate"]) ?GETPOST("np_markRate", 'alpha', 2) : price($line->marque_tx));
 				// if credit note, dont allow to modify margin
 				if ($line->subprice < 0)
 					echo '<td class="right nowrap margininfos">'.$mark_rate.'<span class="hideonsmartphone">%</span></td>';
@@ -250,7 +250,7 @@ $coldisplay++;
 	?>
 
 	<!-- colspan for this td because it replace total_ht+3 td for buttons+... -->
-	<td class="center valignmiddle" colspan="<?php echo $colspan; ?>"><?php $coldisplay+=$colspan; ?>
+	<td class="center valignmiddle" colspan="<?php echo $colspan; ?>"><?php $coldisplay += $colspan; ?>
 		<input type="submit" class="button" id="savelinebutton" name="save" value="<?php echo $langs->trans("Save"); ?>"><br>
 		<input type="submit" class="button" id="cancellinebutton" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>">
 	</td>
@@ -327,7 +327,7 @@ jQuery(document).ready(function()
 	});
 
     <?php
-    if (! empty($conf->margin->enabled))
+    if (!empty($conf->margin->enabled))
     {
         ?>
 		/* Add rule to clear margin when we change some data, so when we change sell or buy price, margin will be recalculated after submitting form */
@@ -357,7 +357,7 @@ jQuery(document).ready(function()
 		});
 
 		/* Init field buying_price and fournprice */
-		$.post('<?php echo DOL_URL_ROOT; ?>/fourn/ajax/getSupplierPrices.php', {'idprod': <?php echo $line->fk_product?$line->fk_product:0; ?>}, function(data) {
+		$.post('<?php echo DOL_URL_ROOT; ?>/fourn/ajax/getSupplierPrices.php', {'idprod': <?php echo $line->fk_product ? $line->fk_product : 0; ?>}, function(data) {
           if (data && data.length > 0) {
 			var options = '';
 			var trouve=false;

+ 9 - 9
htdocs/core/tpl/objectline_view.tpl.php

@@ -39,7 +39,7 @@
  */
 
 // Protection to avoid direct call of template
-if (empty($object) || ! is_object($object))
+if (empty($object) || !is_object($object))
 {
 	print "Error, template page can't be called as URL";
 	exit;
@@ -48,14 +48,14 @@ if (empty($object) || ! is_object($object))
 
 global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax;
 
-$usemargins=0;
-if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element, array('facture','facturerec','propal','commande'))) $usemargins=1;
+$usemargins = 0;
+if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'facturerec', 'propal', 'commande'))) $usemargins = 1;
 
-if (empty($dateSelector)) $dateSelector=0;
-if (empty($forceall)) $forceall=0;
-if (empty($senderissupplier)) $senderissupplier=0;
-if (empty($inputalsopricewithtax)) $inputalsopricewithtax=0;
-if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax=0;
+if (empty($dateSelector)) $dateSelector = 0;
+if (empty($forceall)) $forceall = 0;
+if (empty($senderissupplier)) $senderissupplier = 0;
+if (empty($inputalsopricewithtax)) $inputalsopricewithtax = 0;
+if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax = 0;
 
 // add html5 elements
 $domData  = ' data-element="'.$line->element.'"';
@@ -351,7 +351,7 @@ print "</tr>\n";
 //Line extrafield
 if (!empty($extrafields))
 {
-	print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"','colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1);
+	print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1);
 }
 
 print "<!-- END PHP TEMPLATE objectline_view.tpl.php -->\n";

+ 17 - 17
htdocs/core/tpl/onlinepaymentlinks.tpl.php

@@ -16,7 +16,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;
@@ -30,12 +30,12 @@ print '<!-- BEGIN PHP TEMPLATE ONLINEPAYMENTLINKS -->';
 print '<u>'.$langs->trans("FollowingUrlAreAvailableToMakePayments").':</u><br><br>';
 print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnFreeAmount", $servicename).':<br>';
 print '<strong class="wordbreak">'.getOnlinePaymentUrl(1, 'free')."</strong><br><br>\n";
-if (! empty($conf->commande->enabled))
+if (!empty($conf->commande->enabled))
 {
     print '<div id="order"></div>';
     print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnOrder", $servicename).':<br>';
 	print '<strong class="wordbreak">'.getOnlinePaymentUrl(1, 'order')."</strong><br>\n";
-	if (! empty($conf->global->PAYMENT_SECURITY_TOKEN) && ! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
+	if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
 	{
 	    $langs->load("orders");
 	    print '<form action="'.$_SERVER["PHP_SELF"].'#order" method="POST">';
@@ -45,7 +45,7 @@ if (! empty($conf->commande->enabled))
         if (GETPOST('generate_order_ref', 'alpha'))
         {
             print '<br> -> <strong class="wordbreak">';
-            $url=getOnlinePaymentUrl(0, 'order', GETPOST('generate_order_ref', 'alpha'));
+            $url = getOnlinePaymentUrl(0, 'order', GETPOST('generate_order_ref', 'alpha'));
             print $url;
             print "</strong><br>\n";
         }
@@ -53,12 +53,12 @@ if (! empty($conf->commande->enabled))
 	}
 	print '<br>';
 }
-if (! empty($conf->facture->enabled))
+if (!empty($conf->facture->enabled))
 {
     print '<div id="invoice"></div>';
     print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnInvoice", $servicename).':<br>';
 	print '<strong class="wordbreak">'.getOnlinePaymentUrl(1, 'invoice')."</strong><br>\n";
-	if (! empty($conf->global->PAYMENT_SECURITY_TOKEN) && ! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
+	if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
 	{
 	    $langs->load("bills");
 	    print '<form action="'.$_SERVER["PHP_SELF"].'#invoice" method="POST">';
@@ -68,7 +68,7 @@ if (! empty($conf->facture->enabled))
         if (GETPOST('generate_invoice_ref', 'alpha'))
         {
             print '<br> -> <strong class="wordbreak">';
-            $url=getOnlinePaymentUrl(0, 'invoice', GETPOST('generate_invoice_ref', 'alpha'));
+            $url = getOnlinePaymentUrl(0, 'invoice', GETPOST('generate_invoice_ref', 'alpha'));
             print $url;
             print "</strong><br>\n";
         }
@@ -76,12 +76,12 @@ if (! empty($conf->facture->enabled))
 	}
 	print '<br>';
 }
-if (! empty($conf->contrat->enabled))
+if (!empty($conf->contrat->enabled))
 {
     print '<div id="contractline"></div>';
     print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnContractLine", $servicename).':<br>';
 	print '<strong class="wordbreak">'.getOnlinePaymentUrl(1, 'contractline')."</strong><br>\n";
-	if (! empty($conf->global->PAYMENT_SECURITY_TOKEN) && ! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
+	if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
 	{
 	    $langs->load("contracts");
 	    print '<form action="'.$_SERVER["PHP_SELF"].'#contractline" method="POST">';
@@ -91,7 +91,7 @@ if (! empty($conf->contrat->enabled))
         if (GETPOST('generate_contract_ref'))
         {
             print '<br> -> <strong class="wordbreak">';
-            $url=getOnlinePaymentUrl(0, 'contractline', GETPOST('generate_contract_ref', 'alpha'));
+            $url = getOnlinePaymentUrl(0, 'contractline', GETPOST('generate_contract_ref', 'alpha'));
             print $url;
             print "</strong><br>\n";
         }
@@ -99,12 +99,12 @@ if (! empty($conf->contrat->enabled))
 	}
 	print '<br>';
 }
-if (! empty($conf->adherent->enabled))
+if (!empty($conf->adherent->enabled))
 {
     print '<div id="membersubscription"></div>';
     print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnMemberSubscription", $servicename).':<br>';
 	print '<strong class="wordbreak">'.getOnlinePaymentUrl(1, 'membersubscription')."</strong><br>\n";
-	if (! empty($conf->global->PAYMENT_SECURITY_TOKEN) && ! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
+	if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
 	{
 	    $langs->load("members");
 	    print '<form action="'.$_SERVER["PHP_SELF"].'#membersubscription" method="POST">';
@@ -114,7 +114,7 @@ if (! empty($conf->adherent->enabled))
         if (GETPOST('generate_member_ref'))
         {
             print '<br> -> <strong class="wordbreak">';
-            $url=getOnlinePaymentUrl(0, 'membersubscription', GETPOST('generate_member_ref', 'alpha'));
+            $url = getOnlinePaymentUrl(0, 'membersubscription', GETPOST('generate_member_ref', 'alpha'));
             print $url;
             print "</strong><br>\n";
         }
@@ -122,12 +122,12 @@ if (! empty($conf->adherent->enabled))
 	}
 	print '<br>';
 }
-if (! empty($conf->don->enabled))
+if (!empty($conf->don->enabled))
 {
     print '<div id="donation"></div>';
 	print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnDonation", $servicename).':<br>';
 	print '<strong class="wordbreak">'.getOnlinePaymentUrl(1, 'donation')."</strong><br>\n";
-	if (! empty($conf->global->PAYMENT_SECURITY_TOKEN) && ! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
+	if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
 	{
 	    $langs->load("members");
 	    print '<form action="'.$_SERVER["PHP_SELF"].'#donation" method="POST">';
@@ -137,7 +137,7 @@ if (! empty($conf->don->enabled))
         if (GETPOST('generate_donation_ref'))
         {
             print '<br> -> <strong class="wordbreak">';
-            $url=getOnlinePaymentUrl(0, 'donation', GETPOST('generate_donation_ref', 'alpha'));
+            $url = getOnlinePaymentUrl(0, 'donation', GETPOST('generate_donation_ref', 'alpha'));
             print $url;
             print "</strong><br>\n";
         }
@@ -146,7 +146,7 @@ if (! empty($conf->don->enabled))
 	print '<br>';
 }
 
-if (! empty($conf->use_javascript_ajax))
+if (!empty($conf->use_javascript_ajax))
 {
 	print "\n".'<script type="text/javascript">';
 	print '$(document).ready(function () {

+ 82 - 82
htdocs/don/card.php

@@ -28,17 +28,17 @@
  */
 
 require '../main.inc.php';
-require_once DOL_DOCUMENT_ROOT . '/core/modules/dons/modules_don.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/donation.lib.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
-require_once DOL_DOCUMENT_ROOT . '/don/class/don.class.php';
-require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
-require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
-if (! empty($conf->projet->enabled)) {
+require_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/donation.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
+require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
+require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+if (!empty($conf->projet->enabled)) {
     require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
     require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 }
@@ -46,11 +46,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 
 $langs->loadLangs(array("bills", "companies", "donations"));
 
-$id=GETPOST('rowid')?GETPOST('rowid', 'int'):GETPOST('id', 'int');
-$action=GETPOST('action', 'alpha');
-$cancel=GETPOST('cancel', 'alpha');
-$amount=GETPOST('amount');
-$donation_date=dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
+$id = GETPOST('rowid') ?GETPOST('rowid', 'int') : GETPOST('id', 'int');
+$action = GETPOST('action', 'alpha');
+$cancel = GETPOST('cancel', 'alpha');
+$amount = GETPOST('amount');
+$donation_date = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
 $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0);
 
 $object = new Don($db);
@@ -63,7 +63,7 @@ $result = restrictedArea($user, 'don', $id);
 $extrafields->fetch_name_optionals_label($object->table_element);
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$hookmanager->initHooks(array('doncard','globalcard'));
+$hookmanager->initHooks(array('doncard', 'globalcard'));
 
 /*
  * Actions
@@ -74,13 +74,13 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
 
 if ($action == 'update')
 {
-	if (! empty($cancel))
+	if (!empty($cancel))
 	{
 		header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
 		exit;
 	}
 
-	$error=0;
+	$error = 0;
 
     if (empty($donation_date))
     {
@@ -96,7 +96,7 @@ if ($action == 'update')
 		$error++;
 	}
 
-	if (! $error)
+	if (!$error)
 	{
 		$object->fetch($id);
 
@@ -130,13 +130,13 @@ if ($action == 'update')
 
 if ($action == 'add')
 {
-	if (! empty($cancel))
+	if (!empty($cancel))
 	{
 		header("Location: index.php");
 		exit;
 	}
 
-	$error=0;
+	$error = 0;
 
     if (empty($donation_date))
     {
@@ -152,7 +152,7 @@ if ($action == 'add')
 		$error++;
 	}
 
-	if (! $error)
+	if (!$error)
 	{
         $object->socid = GETPOST("socid", 'int');
 		$object->firstname = GETPOST("firstname", 'alpha');
@@ -190,7 +190,7 @@ if ($action == 'add')
 if ($action == 'confirm_delete' && GETPOST("confirm") == "yes" && $user->rights->don->supprimer)
 {
     $object->fetch($id);
-    $result=$object->delete($user);
+    $result = $object->delete($user);
     if ($result > 0)
     {
         header("Location: index.php");
@@ -311,16 +311,16 @@ if ($action == 'builddoc')
 
 llxHeader('', $langs->trans("Donation"), 'EN:Module_Donations|FR:Module_Dons|ES:M&oacute;dulo_Donaciones');
 
-$form=new Form($db);
+$form = new Form($db);
 $formfile = new FormFile($db);
 $formcompany = new FormCompany($db);
-if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
+if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
 
 if ($action == 'create')
 {
 	print load_fiche_titre($langs->trans("AddDonation"), '', 'invoicing');
 
-	print '<form name="add" action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
+	print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
 	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 	print '<input type="hidden" name="action" value="add">';
 
@@ -330,27 +330,27 @@ if ($action == 'create')
 	print '<tbody>';
 
 	// Ref
-	print '<tr><td class="titlefieldcreate fieldrequired">' . $langs->trans('Ref') . '</td><td colspan="2">' . $langs->trans('Draft') . '</td></tr>';
+	print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td colspan="2">'.$langs->trans('Draft').'</td></tr>';
 
 	// Company
-	if (! empty($conf->societe->enabled) && ! empty($conf->global->DONATION_USE_THIRDPARTIES))
+	if (!empty($conf->societe->enabled) && !empty($conf->global->DONATION_USE_THIRDPARTIES))
 	{
 		// Thirdparty
-		print '<td>' . $langs->trans('Customer') . '</td>';
-		if ($soc->id > 0 && ! GETPOST('fac_rec', 'alpha'))
+		print '<td>'.$langs->trans('Customer').'</td>';
+		if ($soc->id > 0 && !GETPOST('fac_rec', 'alpha'))
 		{
 			print '<td colspan="2">';
 			print $soc->getNomUrl(1);
-			print '<input type="hidden" name="socid" value="' . $soc->id . '">';
+			print '<input type="hidden" name="socid" value="'.$soc->id.'">';
 			// Outstanding Bill
 			$arrayoutstandingbills = $soc->getOutstandingBills();
 			$outstandingBills = $arrayoutstandingbills['opened'];
-			print ' (' . $langs->trans('CurrentOutstandingBill') . ': ';
+			print ' ('.$langs->trans('CurrentOutstandingBill').': ';
 			print price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency);
 			if ($soc->outstanding_limit != '')
 			{
 				if ($outstandingBills > $soc->outstanding_limit) print img_warning($langs->trans("OutstandingBillReached"));
-				print ' / ' . price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency);
+				print ' / '.price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency);
 			}
 			print ')';
 			print '</td>';
@@ -376,12 +376,12 @@ if ($action == 'create')
 			print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=3&fournisseur=0&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="valignmiddle text-plus-circle">'.$langs->trans("AddThirdParty").'</span><span class="fa fa-plus-circle valignmiddle paddingleft"></span></a>';
 			print '</td>';
 		}
-		print '</tr>' . "\n";
+		print '</tr>'."\n";
 	}
 
 	// Date
 	print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans("Date").'</td><td>';
-	print $form->selectDate($donation_date?$donation_date:-1, '', '', '', '', "add", 1, 1);
+	print $form->selectDate($donation_date ? $donation_date : -1, '', '', '', '', "add", 1, 1);
 	print '</td>';
 
 	// Amount
@@ -389,7 +389,7 @@ if ($action == 'create')
 
 	// Public donation
 	print '<tr><td class="fieldrequired">'.$langs->trans("PublicDonation")."</td><td>";
-	print $form->selectyesno("public", isset($_POST["public"])?$_POST["public"]:1, 1);
+	print $form->selectyesno("public", isset($_POST["public"]) ? $_POST["public"] : 1, 1);
 	print "</td></tr>\n";
 
 	if (empty($conf->societe->enabled) || empty($conf->global->DONATION_USE_THIRDPARTIES))
@@ -402,14 +402,14 @@ if ($action == 'create')
 
 		// Zip / Town
 		print '<tr><td>'.$langs->trans("Zip").' / '.$langs->trans("Town").'</td><td>';
-		print $formcompany->select_ziptown((isset($_POST["zipcode"])?$_POST["zipcode"]:$object->zip), 'zipcode', array('town','selectcountry_id','state_id'), 6);
+		print $formcompany->select_ziptown((isset($_POST["zipcode"]) ? $_POST["zipcode"] : $object->zip), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6);
 		print ' ';
-		print $formcompany->select_ziptown((isset($_POST["town"])?$_POST["town"]:$object->town), 'town', array('zipcode','selectcountry_id','state_id'));
+		print $formcompany->select_ziptown((isset($_POST["town"]) ? $_POST["town"] : $object->town), 'town', array('zipcode', 'selectcountry_id', 'state_id'));
 		print '</tr>';
 
 		// Country
 		print '<tr><td><label for="selectcountry_id">'.$langs->trans('Country').'</label></td><td class="maxwidthonsmartphone">';
-		print $form->select_country(GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id);
+		print $form->select_country(GETPOST('country_id') != '' ?GETPOST('country_id') : $object->country_id);
 		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
 		print '</td></tr>';
 
@@ -424,7 +424,7 @@ if ($action == 'create')
 
 	// Public note
 	print '<tr>';
-	print '<td class="tdtop">' . $langs->trans('NotePublic') . '</td>';
+	print '<td class="tdtop">'.$langs->trans('NotePublic').'</td>';
 	print '<td>';
 
     $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
@@ -434,7 +434,7 @@ if ($action == 'create')
 	// Private note
 	if (empty($user->socid)) {
 		print '<tr>';
-		print '<td class="tdtop">' . $langs->trans('NotePrivate') . '</td>';
+		print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>';
 		print '<td>';
 
 		$doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
@@ -442,7 +442,7 @@ if ($action == 'create')
 		print '</td></tr>';
 	}
 
-	if (! empty($conf->projet->enabled))
+	if (!empty($conf->projet->enabled))
     {
         print "<tr><td>".$langs->trans("Project")."</td><td>";
         $formproject->select_projects(-1, $projectid, 'fk_project', 0, 0, 1, 1);
@@ -450,8 +450,8 @@ if ($action == 'create')
     }
 
     // Other attributes
-    $parameters=array();
-    $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+    $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))
     {
@@ -479,21 +479,21 @@ if ($action == 'create')
 /*                                                              */
 /* ************************************************************ */
 
-if (! empty($id) && $action == 'edit')
+if (!empty($id) && $action == 'edit')
 {
-	$result=$object->fetch($id);
+	$result = $object->fetch($id);
 	if ($result < 0) {
 		dol_print_error($db, $object->error); exit;
 	}
-	$result=$object->fetch_optionals();
+	$result = $object->fetch_optionals();
 	if ($result < 0) {
 		dol_print_error($db); exit;
 	}
 
-	$hselected='card';
+	$hselected = 'card';
 	$head = donation_prepare_head($object);
 
-	print '<form name="update" action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
+	print '<form name="update" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
 	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 	print '<input type="hidden" name="action" value="update">';
 	print '<input type="hidden" name="rowid" value="'.$object->id.'">';
@@ -573,9 +573,9 @@ if (! empty($id) && $action == 'edit')
 	print "<tr>".'<td>'.$langs->trans("Status").'</td><td>'.$object->getLibStatut(4).'</td></tr>';
 
     // Project
-    if (! empty($conf->projet->enabled))
+    if (!empty($conf->projet->enabled))
     {
-    	$formproject=new FormProjets($db);
+    	$formproject = new FormProjets($db);
 
         $langs->load('projects');
         print '<tr><td>'.$langs->trans('Project').'</td><td>';
@@ -584,8 +584,8 @@ if (! empty($id) && $action == 'edit')
     }
 
     // Other attributes
-    $parameters=array();
-    $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
+    $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))
     {
@@ -608,25 +608,25 @@ if (! empty($id) && $action == 'edit')
 /* Donation card in view mode                                   */
 /*                                                              */
 /* ************************************************************ */
-if (! empty($id) && $action != 'edit')
+if (!empty($id) && $action != 'edit')
 {
 	// Confirmation delete
     if ($action == 'delete')
     {
-        $text=$langs->trans("ConfirmDeleteADonation");
+        $text = $langs->trans("ConfirmDeleteADonation");
         print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("DeleteADonation"), $text, "confirm_delete", '', '', 1);
     }
 
-	$result=$object->fetch($id);
+	$result = $object->fetch($id);
 	if ($result < 0) {
 		dol_print_error($db, $object->error); exit;
 	}
-	$result=$object->fetch_optionals();
+	$result = $object->fetch_optionals();
 	if ($result < 0) {
 		dol_print_error($db); exit;
 	}
 
-	$hselected='card';
+	$hselected = 'card';
 
 	$head = donation_prepare_head($object);
 	dol_fiche_head($head, $hselected, $langs->trans("Donation"), -1, 'generic');
@@ -713,7 +713,7 @@ if (! empty($id) && $action != 'edit')
 
 	// Other attributes
 	$cols = 2;
-	include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
 	print '</table>';
 
@@ -725,15 +725,15 @@ if (! empty($id) && $action != 'edit')
 	 * Payments
 	 */
 	$sql = "SELECT p.rowid, p.num_payment, p.datep as dp, p.amount,";
-	$sql.= "c.code as type_code,c.libelle as paiement_type";
-	$sql.= " FROM ".MAIN_DB_PREFIX."payment_donation as p";
-	$sql.= ", ".MAIN_DB_PREFIX."c_paiement as c ";
-	$sql.= ", ".MAIN_DB_PREFIX."don as d";
-	$sql.= " WHERE d.rowid = '".$id."'";
-	$sql.= " AND p.fk_donation = d.rowid";
-	$sql.= " AND d.entity IN (".getEntity('donation').")";
-	$sql.= " AND p.fk_typepayment = c.id";
-	$sql.= " ORDER BY dp";
+	$sql .= "c.code as type_code,c.libelle as paiement_type";
+	$sql .= " FROM ".MAIN_DB_PREFIX."payment_donation as p";
+	$sql .= ", ".MAIN_DB_PREFIX."c_paiement as c ";
+	$sql .= ", ".MAIN_DB_PREFIX."don as d";
+	$sql .= " WHERE d.rowid = '".$id."'";
+	$sql .= " AND p.fk_donation = d.rowid";
+	$sql .= " AND d.entity IN (".getEntity('donation').")";
+	$sql .= " AND p.fk_typepayment = c.id";
+	$sql .= " ORDER BY dp";
 
 	//print $sql;
 	$resql = $db->query($sql);
@@ -756,7 +756,7 @@ if (! empty($id) && $action != 'edit')
 			print '<tr class="oddeven"><td>';
 			print '<a href="'.DOL_URL_ROOT.'/don/payment/card.php?id='.$objp->rowid.'">'.img_object($langs->trans("Payment"), "payment").' '.$objp->rowid.'</a></td>';
 			print '<td>'.dol_print_date($db->jdate($objp->dp), 'day')."</td>\n";
-		    $labeltype=$langs->trans("PaymentType".$objp->type_code)!=("PaymentType".$objp->type_code)?$langs->trans("PaymentType".$objp->type_code):$objp->paiement_type;
+		    $labeltype = $langs->trans("PaymentType".$objp->type_code) != ("PaymentType".$objp->type_code) ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type;
             print "<td>".$labeltype.' '.$objp->num_payment."</td>\n";
 			print '<td class="right">'.price($objp->amount)."</td>\n";
 			print "</tr>";
@@ -772,7 +772,7 @@ if (! empty($id) && $action != 'edit')
 			$remaintopay = $object->amount - $totalpaid;
 
 			print "<tr><td colspan=\"3\" class=\"right\">".$langs->trans("RemainderToPay")." :</td>";
-			print '<td class="right'.($resteapayeraffiche?' amountremaintopay':'').'">'.price($remaintopay)."</td></tr>\n";
+			print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : '').'">'.price($remaintopay)."</td></tr>\n";
 		}
 		print "</table>";
 		$db->free($resql);
@@ -796,16 +796,16 @@ if (! empty($id) && $action != 'edit')
 
 	print '<div class="tabsAction">';
 
-	print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?action=edit&rowid='.$object->id.'">'.$langs->trans('Modify').'</a></div>';
+	print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&rowid='.$object->id.'">'.$langs->trans('Modify').'</a></div>';
 
 	if ($object->statut == 0)
 	{
-		print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?rowid='.$object->id.'&action=valid_promesse">'.$langs->trans("ValidPromess").'</a></div>';
+		print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&action=valid_promesse">'.$langs->trans("ValidPromess").'</a></div>';
 	}
 
     if (($object->statut == 0 || $object->statut == 1) && $totalpaid == 0 && $object->paid == 0)
     {
-        print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?rowid='.$object->id.'&action=set_cancel">'.$langs->trans("ClassifyCanceled")."</a></div>";
+        print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&action=set_cancel">'.$langs->trans("ClassifyCanceled")."</a></div>";
     }
 
 	// Create payment
@@ -813,18 +813,18 @@ if (! empty($id) && $action != 'edit')
 	{
 		if ($remaintopay == 0)
 		{
-			print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseRemainderToPayIsZero") . '">' . $langs->trans('DoPayment') . '</span></div>';
+			print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPayment').'</span></div>';
 		}
 		else
 		{
-			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/don/payment/payment.php?rowid=' . $object->id . '&amp;action=create">' . $langs->trans('DoPayment') . '</a></div>';
+			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/don/payment/payment.php?rowid='.$object->id.'&amp;action=create">'.$langs->trans('DoPayment').'</a></div>';
 		}
 	}
 
 	// Classify 'paid'
 	if ($object->statut == 1 && round($remaintopay) == 0 && $object->paid == 0 && $user->rights->don->creer)
 	{
-		print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?rowid='.$object->id.'&action=set_paid">'.$langs->trans("ClassifyPaid")."</a></div>";
+		print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?rowid='.$object->id.'&action=set_paid">'.$langs->trans("ClassifyPaid")."</a></div>";
 	}
 
 	// Delete
@@ -852,11 +852,11 @@ if (! empty($id) && $action != 'edit')
 	/*
 	 * Documents generes
 	 */
-	$filename	=	dol_sanitizeFileName($object->id);
-	$filedir	=	$conf->don->dir_output . "/" . dol_sanitizeFileName($object->id);
-	$urlsource	=	$_SERVER['PHP_SELF'].'?rowid='.$object->id;
-	$genallowed	=	(($object->paid == 0 || $user->admin) && $user->rights->don->lire);
-	$delallowed	=	$user->rights->don->creer;
+	$filename = dol_sanitizeFileName($object->id);
+	$filedir = $conf->don->dir_output."/".dol_sanitizeFileName($object->id);
+	$urlsource = $_SERVER['PHP_SELF'].'?rowid='.$object->id;
+	$genallowed	= (($object->paid == 0 || $user->admin) && $user->rights->don->lire);
+	$delallowed	= $user->rights->don->creer;
 
 	print $formfile->showdocuments('donation', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf);
 

+ 11 - 11
htdocs/don/document.php

@@ -34,14 +34,14 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/donation.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
-if (! empty($conf->projet->enabled))
+if (!empty($conf->projet->enabled))
 {
     require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
     require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 }
 
 // Load translation files required by the page
-$langs->loadLangs(array("companies","other","donations"));
+$langs->loadLangs(array("companies", "other", "donations"));
 
 $id = GETPOST('id', 'int');
 $ref = GETPOST('ref', 'alpha');
@@ -62,22 +62,22 @@ if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined,
 $offset = $conf->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";
 
 
 $object = new Don($db);
 $object->fetch($id, $ref);
 
-$upload_dir = $conf->don->dir_output . '/' . get_exdir($filename, 0, 0, 0, $object, 'donation'). '/'. dol_sanitizeFileName($object->ref);
-$modulepart='don';
+$upload_dir = $conf->don->dir_output.'/'.get_exdir($filename, 0, 0, 0, $object, 'donation').'/'.dol_sanitizeFileName($object->ref);
+$modulepart = 'don';
 
 
 /*
  * Actions
  */
 
-include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
+include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
 
 if ($action == 'classin' && $user->rights->don->creer)
 {
@@ -90,9 +90,9 @@ if ($action == 'classin' && $user->rights->don->creer)
  */
 
 $form = new Form($db);
-if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
+if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
 
-$title = $langs->trans('Donation') . " - " . $langs->trans('Documents');
+$title = $langs->trans('Donation')." - ".$langs->trans('Documents');
 $helpurl = "";
 llxHeader('', $title, $helpurl);
 
@@ -183,8 +183,8 @@ if ($object->id)
     $modulepart = 'don';
     $permission = $user->rights->don->lire;
     $permtoedit = $user->rights->don->creer;
-    $param = '&id=' . $object->id;
-    include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php';
+    $param = '&id='.$object->id;
+    include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php';
 }
 else
 {

+ 3 - 3
htdocs/don/info.php

@@ -25,7 +25,7 @@ require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/donation.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
-if (! empty($conf->projet->enabled))
+if (!empty($conf->projet->enabled))
 {
     require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
     require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
@@ -56,12 +56,12 @@ if ($action == 'classin' && $user->rights->don->creer)
 /*
  * View
  */
-$title = $langs->trans('Donation') . " - " . $langs->trans('Info');
+$title = $langs->trans('Donation')." - ".$langs->trans('Info');
 $helpurl = "";
 llxHeader('', $title, $helpurl);
 
 $form = new Form($db);
-if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
+if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
 
 $object->info($id);
 

+ 3 - 3
htdocs/don/note.php

@@ -69,14 +69,14 @@ if ($action == 'classin' && $user->rights->don->creer)
  * View
  */
 
-$title = $langs->trans('Donation') . " - " . $langs->trans('Notes');
+$title = $langs->trans('Donation')." - ".$langs->trans('Notes');
 $helpurl = "";
 llxHeader('', $title, $helpurl);
 
 $form = new Form($db);
-if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
+if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
 
-if ($id > 0 || ! empty($ref))
+if ($id > 0 || !empty($ref))
 {
 	$object = new Don($db);
 	$object->fetch($id, $ref);

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