Преглед на файлове

Scrutinizer Auto-Fixes

This commit consists of patches automatically generated for this project on https://scrutinizer-ci.com
Scrutinizer Auto-Fixer преди 5 години
родител
ревизия
5fda829023
променени са 94 файла, в които са добавени 5050 реда и са изтрити 5050 реда
  1. 7 7
      htdocs/accountancy/admin/account.php
  2. 3 3
      htdocs/admin/commande.php
  3. 1 1
      htdocs/admin/contract.php
  4. 113 113
      htdocs/admin/facture.php
  5. 1 1
      htdocs/admin/mails.php
  6. 7 7
      htdocs/admin/mails_senderprofile_list.php
  7. 59 59
      htdocs/admin/mrp.php
  8. 9 9
      htdocs/admin/order_extrafields.php
  9. 9 9
      htdocs/admin/orderdet_extrafields.php
  10. 85 85
      htdocs/admin/tools/listevents.php
  11. 1 1
      htdocs/bom/class/bom.class.php
  12. 133 133
      htdocs/comm/action/class/actioncomm.class.php
  13. 17 17
      htdocs/comm/action/index.php
  14. 1 1
      htdocs/comm/action/list.php
  15. 1 1
      htdocs/comm/propal/class/propal.class.php
  16. 285 285
      htdocs/commande/class/commande.class.php
  17. 12 12
      htdocs/commande/list.php
  18. 27 27
      htdocs/compta/cashcontrol/report.php
  19. 7 7
      htdocs/compta/facture/card.php
  20. 4 4
      htdocs/compta/facture/class/facture.class.php
  21. 7 7
      htdocs/compta/prelevement/card.php
  22. 42 42
      htdocs/compta/prelevement/create.php
  23. 37 37
      htdocs/compta/prelevement/demandes.php
  24. 43 43
      htdocs/compta/sociales/card.php
  25. 44 44
      htdocs/compta/sociales/class/chargesociales.class.php
  26. 23 23
      htdocs/compta/tva/document.php
  27. 1 1
      htdocs/contrat/card.php
  28. 2 2
      htdocs/contrat/class/contrat.class.php
  29. 101 101
      htdocs/contrat/services_list.php
  30. 18 18
      htdocs/core/actions_setmoduleoptions.inc.php
  31. 33 33
      htdocs/core/boxes/box_factures_imp.php
  32. 1 1
      htdocs/core/boxes/box_services_expired.php
  33. 1 1
      htdocs/core/class/doleditor.class.php
  34. 45 45
      htdocs/core/class/dolreceiptprinter.class.php
  35. 154 154
      htdocs/core/class/extrafields.class.php
  36. 3 3
      htdocs/core/class/html.form.class.php
  37. 3 3
      htdocs/core/class/html.formaccounting.class.php
  38. 192 192
      htdocs/core/class/smtps.class.php
  39. 26 26
      htdocs/core/extrafieldsinexport.inc.php
  40. 153 153
      htdocs/core/lib/files.lib.php
  41. 1 1
      htdocs/core/lib/functions2.lib.php
  42. 1 1
      htdocs/core/lib/pdf.lib.php
  43. 124 124
      htdocs/core/lib/security2.lib.php
  44. 229 229
      htdocs/core/modules/commande/doc/pdf_einstein.modules.php
  45. 179 179
      htdocs/core/modules/commande/doc/pdf_eratosthene.modules.php
  46. 137 137
      htdocs/core/modules/expedition/doc/pdf_espadon.modules.php
  47. 167 167
      htdocs/core/modules/expensereport/doc/pdf_standard.modules.php
  48. 1 1
      htdocs/core/modules/facture/doc/pdf_crabe.modules.php
  49. 220 220
      htdocs/core/modules/facture/doc/pdf_sponge.modules.php
  50. 6 6
      htdocs/core/modules/facture/modules_facture.php
  51. 149 149
      htdocs/core/modules/livraison/doc/pdf_typhon.modules.php
  52. 15 15
      htdocs/core/modules/modCashDesk.class.php
  53. 36 36
      htdocs/core/modules/modMrp.class.php
  54. 34 34
      htdocs/core/modules/modTakePos.class.php
  55. 183 183
      htdocs/core/modules/propale/doc/pdf_cyan.modules.php
  56. 156 156
      htdocs/core/modules/supplier_order/doc/pdf_cornas.modules.php
  57. 236 236
      htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php
  58. 128 128
      htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php
  59. 234 234
      htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php
  60. 15 15
      htdocs/core/tpl/massactions_pre.tpl.php
  61. 1 1
      htdocs/cron/class/cronjob.class.php
  62. 6 6
      htdocs/expensereport/card.php
  63. 33 33
      htdocs/expensereport/class/expensereportstats.class.php
  64. 1 1
      htdocs/exports/export.php
  65. 20 20
      htdocs/fourn/ajax/getSupplierPrices.php
  66. 50 50
      htdocs/fourn/class/fournisseur.commande.class.php
  67. 1 1
      htdocs/fourn/class/fournisseur.facture.class.php
  68. 4 4
      htdocs/loan/class/loan.class.php
  69. 209 209
      htdocs/modulebuilder/index.php
  70. 4 4
      htdocs/modulebuilder/template/class/myobject.class.php
  71. 4 4
      htdocs/modulebuilder/template/myobject_list.php
  72. 1 1
      htdocs/mrp/class/mo.class.php
  73. 6 6
      htdocs/product/class/product.class.php
  74. 6 6
      htdocs/product/list.php
  75. 136 136
      htdocs/product/reassortlot.php
  76. 15 15
      htdocs/product/stock/class/api_stockmovements.class.php
  77. 134 134
      htdocs/product/stock/class/entrepot.class.php
  78. 40 40
      htdocs/product/stock/productlot_list.php
  79. 2 2
      htdocs/projet/class/task.class.php
  80. 32 32
      htdocs/projet/tasks/time.php
  81. 89 89
      htdocs/public/demo/index.php
  82. 1 1
      htdocs/resource/class/dolresource.class.php
  83. 9 9
      htdocs/societe/card.php
  84. 11 11
      htdocs/societe/paymentmodes.php
  85. 6 6
      htdocs/stripe/charge.php
  86. 3 3
      htdocs/supplier_proposal/class/supplier_proposal.class.php
  87. 26 26
      htdocs/takepos/floors.php
  88. 8 8
      htdocs/takepos/freezone.php
  89. 1 1
      htdocs/takepos/pay.php
  90. 13 13
      htdocs/takepos/receipt.php
  91. 22 22
      htdocs/takepos/takepos.php
  92. 6 6
      htdocs/theme/eldy/info-box.inc.php
  93. 49 49
      htdocs/user/home.php
  94. 139 139
      htdocs/user/list.php

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

@@ -49,10 +49,10 @@ $search_pcgsubtype = GETPOST('search_pcgsubtype', 'alpha');
 
 // Security check
 if ($user->socid > 0) accessforbidden();
-if (! $user->rights->accounting->chartofaccount) accessforbidden();
+if (!$user->rights->accounting->chartofaccount) accessforbidden();
 
 // 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');
@@ -211,7 +211,7 @@ if (strlen(trim($search_account))) {
 	$search_account_tmp = $search_account;
 	$weremovedsomezero = 0;
 	if (strlen($search_account_tmp) <= $lengthpaddingaccount) {
-		for($i = 0; $i < $lengthpaddingaccount; $i++) {
+		for ($i = 0; $i < $lengthpaddingaccount; $i++) {
 			if (preg_match('/0$/', $search_account_tmp)) {
 				$weremovedsomezero++;
 				$search_account_tmp = preg_replace('/0$/', '', $search_account_tmp);
@@ -271,7 +271,7 @@ if ($resql)
 	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_labelshort) $param.= '&search_labelshort='.urlencode($search_labelshort);
+	if ($search_labelshort) $param .= '&search_labelshort='.urlencode($search_labelshort);
 	if ($search_accountparent > 0 || $search_accountparent == '0') $param .= '&search_accountparent='.urlencode($search_accountparent);
 	if ($search_pcgtype) $param .= '&search_pcgtype='.urlencode($search_pcgtype);
 	if ($search_pcgsubtype) $param .= '&search_pcgsubtype='.urlencode($search_pcgsubtype);
@@ -356,7 +356,7 @@ if ($resql)
 	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.labelshort']['checked']))		print '<td class="liste_titre"><input type="text" class="flat" size="20" name="search_labelshort" value="' . $search_labelshort . '"></td>';
+	if (!empty($arrayfields['aa.labelshort']['checked']))		print '<td class="liste_titre"><input type="text" class="flat" size="20" name="search_labelshort" value="'.$search_labelshort.'"></td>';
 	if (!empty($arrayfields['aa.account_parent']['checked'])) {
 		print '<td class="liste_titre">';
 		print $formaccounting->select_account($search_accountparent, 'search_accountparent', 2);
@@ -416,12 +416,12 @@ if ($resql)
 		}
 
 		// Account label to show (label short)
-		if (! empty($arrayfields['aa.labelshort']['checked']))
+		if (!empty($arrayfields['aa.labelshort']['checked']))
 		{
 			print "<td>";
 			print $obj->labelshort;
 			print "</td>\n";
-			if (! $i) $totalarray['nbfield']++;
+			if (!$i) $totalarray['nbfield']++;
 		}
 
 		// Account parent

+ 3 - 3
htdocs/admin/commande.php

@@ -472,11 +472,11 @@ foreach ($dirmodels as $reldir)
 	                            print '</td>';
 
 	                            // Info
-		    					$htmltooltip =    ''.$langs->trans("Name").': '.$module->name;
-					    		$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown"));
+		    					$htmltooltip = ''.$langs->trans("Name").': '.$module->name;
+					    		$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
 			                    if ($module->type == 'pdf')
 			                    {
-			                        $htmltooltip.='<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
+			                        $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
 			                    }
 			                    $htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file;
 

+ 1 - 1
htdocs/admin/contract.php

@@ -409,7 +409,7 @@ foreach ($dirmodels as $reldir)
 
 	                            // Info
 		    					$htmltooltip = ''.$langs->trans("Name").': '.$module->name;
-					    		$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown"));
+					    		$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
 			                    if ($module->type == 'pdf')
 			                    {
 			                        $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;

+ 113 - 113
htdocs/admin/facture.php

@@ -36,13 +36,13 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
 // Load translation files required by the page
 $langs->loadLangs(array('admin', 'errors', 'other', 'bills'));
 
-if (! $user->admin) accessforbidden();
+if (!$user->admin) accessforbidden();
 
 $action = GETPOST('action', 'alpha');
 $value = GETPOST('value', 'alpha');
 $label = GETPOST('label', 'alpha');
 $scandir = GETPOST('scan_dir', 'alpha');
-$type='invoice';
+$type = 'invoice';
 
 
 /*
@@ -53,22 +53,22 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
 
 if ($action == 'updateMask')
 {
-    $maskconstinvoice=GETPOST('maskconstinvoice', 'alpha');
-    $maskconstreplacement=GETPOST('maskconstreplacement', 'alpha');
-    $maskconstcredit=GETPOST('maskconstcredit', 'alpha');
-	$maskconstdeposit=GETPOST('maskconstdeposit', 'alpha');
-    $maskinvoice=GETPOST('maskinvoice', 'alpha');
-    $maskreplacement=GETPOST('maskreplacement', 'alpha');
-    $maskcredit=GETPOST('maskcredit', 'alpha');
-	$maskdeposit=GETPOST('maskdeposit', 'alpha');
+    $maskconstinvoice = GETPOST('maskconstinvoice', 'alpha');
+    $maskconstreplacement = GETPOST('maskconstreplacement', 'alpha');
+    $maskconstcredit = GETPOST('maskconstcredit', 'alpha');
+	$maskconstdeposit = GETPOST('maskconstdeposit', 'alpha');
+    $maskinvoice = GETPOST('maskinvoice', 'alpha');
+    $maskreplacement = GETPOST('maskreplacement', 'alpha');
+    $maskcredit = GETPOST('maskcredit', 'alpha');
+	$maskdeposit = GETPOST('maskdeposit', 'alpha');
     if ($maskconstinvoice) $res = dolibarr_set_const($db, $maskconstinvoice, $maskinvoice, 'chaine', 0, '', $conf->entity);
     if ($maskconstreplacement) $res = dolibarr_set_const($db, $maskconstreplacement, $maskreplacement, 'chaine', 0, '', $conf->entity);
     if ($maskconstcredit)  $res = dolibarr_set_const($db, $maskconstcredit, $maskcredit, 'chaine', 0, '', $conf->entity);
 	if ($maskconstdeposit)  $res = dolibarr_set_const($db, $maskconstdeposit, $maskdeposit, 'chaine', 0, '', $conf->entity);
 
-	if (! $res > 0) $error++;
+	if (!$res > 0) $error++;
 
- 	if (! $error)
+ 	if (!$error)
     {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
@@ -79,20 +79,20 @@ if ($action == 'updateMask')
 }
 elseif ($action == 'specimen')
 {
-    $modele=GETPOST('module', 'alpha');
+    $modele = GETPOST('module', 'alpha');
 
     $facture = new Facture($db);
     $facture->initAsSpecimen();
 
 	// Search template files
-	$file=''; $classname=''; $filefound=0;
-	$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']);
-	foreach($dirmodels as $reldir)
+	$file = ''; $classname = ''; $filefound = 0;
+	$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+	foreach ($dirmodels as $reldir)
 	{
-	    $file=dol_buildpath($reldir."core/modules/facture/doc/pdf_".$modele.".modules.php", 0);
+	    $file = dol_buildpath($reldir."core/modules/facture/doc/pdf_".$modele.".modules.php", 0);
     	if (file_exists($file))
     	{
-    		$filefound=1;
+    		$filefound = 1;
     		$classname = "pdf_".$modele;
     		break;
     	}
@@ -167,9 +167,9 @@ elseif ($action == 'setribchq')
 	$res = dolibarr_set_const($db, "FACTURE_RIB_NUMBER", $rib, 'chaine', 0, '', $conf->entity);
     $res = dolibarr_set_const($db, "FACTURE_CHQ_NUMBER", $chq, 'chaine', 0, '', $conf->entity);
 
-	if (! $res > 0) $error++;
+	if (!$res > 0) $error++;
 
- 	if (! $error)
+ 	if (!$error)
     {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
@@ -184,9 +184,9 @@ elseif ($action == 'set_FACTURE_DRAFT_WATERMARK')
 
     $res = dolibarr_set_const($db, "FACTURE_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity);
 
-	if (! $res > 0) $error++;
+	if (!$res > 0) $error++;
 
- 	if (! $error)
+ 	if (!$error)
     {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
@@ -198,13 +198,13 @@ elseif ($action == 'set_FACTURE_DRAFT_WATERMARK')
 
 elseif ($action == 'set_INVOICE_FREE_TEXT')
 {
-	$freetext = GETPOST('INVOICE_FREE_TEXT', 'none');	// No alpha here, we want exact string
+	$freetext = GETPOST('INVOICE_FREE_TEXT', 'none'); // No alpha here, we want exact string
 
     $res = dolibarr_set_const($db, "INVOICE_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity);
 
-	if (! $res > 0) $error++;
+	if (!$res > 0) $error++;
 
- 	if (! $error)
+ 	if (!$error)
     {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
@@ -219,9 +219,9 @@ elseif ($action == 'setforcedate')
 
     $res = dolibarr_set_const($db, "FAC_FORCE_DATE_VALIDATION", $forcedate, 'chaine', 0, '', $conf->entity);
 
-	if (! $res > 0) $error++;
+	if (!$res > 0) $error++;
 
- 	if (! $error)
+ 	if (!$error)
     {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
@@ -232,19 +232,19 @@ elseif ($action == 'setforcedate')
 }
 elseif ($action == 'setDefaultPDFModulesByType')
 {
-    $invoicetypemodels =  GETPOST('invoicetypemodels');
+    $invoicetypemodels = GETPOST('invoicetypemodels');
 
-    if(!empty($invoicetypemodels) && is_array($invoicetypemodels))
+    if (!empty($invoicetypemodels) && is_array($invoicetypemodels))
     {
         $error = 0;
 
         foreach ($invoicetypemodels as $type => $value)
         {
             $res = dolibarr_set_const($db, 'FACTURE_ADDON_PDF_'.intval($type), $value, 'chaine', 0, '', $conf->entity);
-            if (! $res > 0) $error++;
+            if (!$res > 0) $error++;
         }
 
-        if (! $error)
+        if (!$error)
         {
             setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
         }
@@ -260,14 +260,14 @@ elseif ($action == 'setDefaultPDFModulesByType')
  * View
  */
 
-$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']);
+$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
 
 llxHeader("", $langs->trans("BillsSetup"), 'EN:Invoice_Configuration|FR:Configuration_module_facture|ES:ConfiguracionFactura');
 
-$form=new Form($db);
+$form = new Form($db);
 
 
-$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("BillsSetup"), $linkback, 'title_setup');
 
 $head = invoice_admin_prepare_head();
@@ -298,24 +298,24 @@ foreach ($dirmodels as $reldir)
         $handle = opendir($dir);
         if (is_resource($handle))
         {
-            while (($file = readdir($handle))!==false)
+            while (($file = readdir($handle)) !== false)
             {
-                if (! is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS'))
+                if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS'))
                 {
                     $filebis = $file;
                     $classname = preg_replace('/\.php$/', '', $file);
                     // For compatibility
-                    if (! is_file($dir.$filebis))
+                    if (!is_file($dir.$filebis))
                     {
                         $filebis = $file."/".$file.".modules.php";
                         $classname = "mod_facture_".$file;
                     }
                     // Check if there is a filter on country
                     preg_match('/\-(.*)_(.*)$/', $classname, $reg);
-                    if (! empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) continue;
+                    if (!empty($reg[2]) && $reg[2] != strtoupper($mysoc->country_code)) continue;
 
                     $classname = preg_replace('/\-.*$/', '', $classname);
-                    if (! class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis)-3, 3) == 'php')
+                    if (!class_exists($classname) && is_readable($dir.$filebis) && (preg_match('/mod_/', $filebis) || preg_match('/mod_/', $classname)) && substr($filebis, dol_strlen($filebis) - 3, 3) == 'php')
                     {
                         // Charging the numbering class
                         require_once $dir.$filebis;
@@ -323,7 +323,7 @@ foreach ($dirmodels as $reldir)
                         $module = new $classname($db);
 
                         // 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())
@@ -338,9 +338,9 @@ foreach ($dirmodels as $reldir)
 
                             // Show example of numbering module
                             print '<td class="nowrap">';
-                            $tmp=$module->getExample();
+                            $tmp = $module->getExample();
                             if (preg_match('/^Error/', $tmp)) 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";
 
@@ -356,62 +356,62 @@ foreach ($dirmodels as $reldir)
                             }
                             print '</td>';
 
-                            $facture=new Facture($db);
+                            $facture = new Facture($db);
                             $facture->initAsSpecimen();
 
                             // Example for standard invoice
-                            $htmltooltip='';
-                            $htmltooltip.=''.$langs->trans("Version").': <b>'.$module->getVersion().'</b><br>';
-                            $facture->type=0;
-                            $nextval=$module->getNextValue($mysoc, $facture);
+                            $htmltooltip = '';
+                            $htmltooltip .= ''.$langs->trans("Version").': <b>'.$module->getVersion().'</b><br>';
+                            $facture->type = 0;
+                            $nextval = $module->getNextValue($mysoc, $facture);
                             if ("$nextval" != $langs->trans("NotAvailable")) {  // Keep " on nextval
-                                $htmltooltip.=$langs->trans("NextValueForInvoices").': ';
+                                $htmltooltip .= $langs->trans("NextValueForInvoices").': ';
                                 if ($nextval) {
-                                    if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured')
+                                    if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured')
                                         $nextval = $langs->trans($nextval);
-                                    $htmltooltip.=$nextval.'<br>';
+                                    $htmltooltip .= $nextval.'<br>';
                                 } else {
-                                    $htmltooltip.=$langs->trans($module->error).'<br>';
+                                    $htmltooltip .= $langs->trans($module->error).'<br>';
                                 }
                             }
                             // Example for remplacement
-                            $facture->type=1;
-                            $nextval=$module->getNextValue($mysoc, $facture);
+                            $facture->type = 1;
+                            $nextval = $module->getNextValue($mysoc, $facture);
                             if ("$nextval" != $langs->trans("NotAvailable")) {  // Keep " on nextval
-                                $htmltooltip.=$langs->trans("NextValueForReplacements").': ';
+                                $htmltooltip .= $langs->trans("NextValueForReplacements").': ';
                                 if ($nextval) {
-                                    if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured')
+                                    if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured')
                                         $nextval = $langs->trans($nextval);
-                                    $htmltooltip.=$nextval.'<br>';
+                                    $htmltooltip .= $nextval.'<br>';
                                 } else {
-                                    $htmltooltip.=$langs->trans($module->error).'<br>';
+                                    $htmltooltip .= $langs->trans($module->error).'<br>';
                                 }
                             }
 
                             // Example for credit invoice
-                            $facture->type=2;
-                            $nextval=$module->getNextValue($mysoc, $facture);
+                            $facture->type = 2;
+                            $nextval = $module->getNextValue($mysoc, $facture);
                             if ("$nextval" != $langs->trans("NotAvailable")) {  // Keep " on nextval
-                                $htmltooltip.=$langs->trans("NextValueForCreditNotes").': ';
+                                $htmltooltip .= $langs->trans("NextValueForCreditNotes").': ';
                                 if ($nextval) {
-                                    if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured')
+                                    if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured')
                                         $nextval = $langs->trans($nextval);
-                                    $htmltooltip.=$nextval.'<br>';
+                                    $htmltooltip .= $nextval.'<br>';
                                 } else {
-                                    $htmltooltip.=$langs->trans($module->error).'<br>';
+                                    $htmltooltip .= $langs->trans($module->error).'<br>';
                                 }
                             }
                             // Example for deposit invoice
-                            $facture->type=3;
-                            $nextval=$module->getNextValue($mysoc, $facture);
+                            $facture->type = 3;
+                            $nextval = $module->getNextValue($mysoc, $facture);
                             if ("$nextval" != $langs->trans("NotAvailable")) {  // Keep " on nextval
-                                $htmltooltip.=$langs->trans("NextValueForDeposit").': ';
+                                $htmltooltip .= $langs->trans("NextValueForDeposit").': ';
                                 if ($nextval) {
-                                    if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured')
+                                    if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured')
                                         $nextval = $langs->trans($nextval);
-                                    $htmltooltip.=$nextval;
+                                    $htmltooltip .= $nextval;
                                 } else {
-                                    $htmltooltip.=$langs->trans($module->error);
+                                    $htmltooltip .= $langs->trans($module->error);
                                 }
                             }
 
@@ -420,7 +420,7 @@ foreach ($dirmodels as $reldir)
 
                             if ($conf->global->FACTURE_ADDON.'.php' == $file)  // If module is the one used, we show existing errors
                             {
-                                if (! empty($module->error)) dol_htmloutput_mesg($module->error, '', 'error', 1);
+                                if (!empty($module->error)) dol_htmloutput_mesg($module->error, '', 'error', 1);
                             }
 
                             print '</td>';
@@ -445,17 +445,17 @@ print '<br>';
 print load_fiche_titre($langs->trans("BillsPDFModules"), '', '');
 
 // Load array def with activated templates
-$type='invoice';
+$type = 'invoice';
 $def = array();
 $sql = "SELECT nom";
-$sql.= " FROM ".MAIN_DB_PREFIX."document_model";
-$sql.= " WHERE type = '".$type."'";
-$sql.= " AND entity = ".$conf->entity;
-$resql=$db->query($sql);
+$sql .= " FROM ".MAIN_DB_PREFIX."document_model";
+$sql .= " WHERE type = '".$type."'";
+$sql .= " AND entity = ".$conf->entity;
+$resql = $db->query($sql);
 if ($resql)
 {
     $i = 0;
-    $num_rows=$db->num_rows($resql);
+    $num_rows = $db->num_rows($resql);
     while ($i < $num_rows)
     {
         $array = $db->fetch_array($resql);
@@ -484,43 +484,43 @@ $activatedModels = array();
 
 foreach ($dirmodels as $reldir)
 {
-    foreach (array('','/doc') as $valdir)
+    foreach (array('', '/doc') as $valdir)
     {
     	$realpath = $reldir."core/modules/facture".$valdir;
     	$dir = dol_buildpath($realpath);
 
         if (is_dir($dir))
         {
-            $handle=opendir($dir);
+            $handle = opendir($dir);
             if (is_resource($handle))
             {
-                while (($file = readdir($handle))!==false)
+                while (($file = readdir($handle)) !== false)
                 {
-                    $filelist[]=$file;
+                    $filelist[] = $file;
                 }
                 closedir($handle);
                 arsort($filelist);
 
-                foreach($filelist as $file)
+                foreach ($filelist as $file)
                 {
                     if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file))
                     {
                     	if (file_exists($dir.'/'.$file))
                     	{
-                    		$name = substr($file, 4, dol_strlen($file) -16);
-	                        $classname = substr($file, 0, dol_strlen($file) -12);
+                    		$name = substr($file, 4, dol_strlen($file) - 16);
+	                        $classname = substr($file, 0, dol_strlen($file) - 12);
 
 	                        require_once $dir.'/'.$file;
 	                        $module = new $classname($db);
 
-	                        $modulequalified=1;
-	                        if ($module->version == 'development'  && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0;
-	                        if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0;
+	                        $modulequalified = 1;
+	                        if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0;
+	                        if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0;
 
 	                        if ($modulequalified)
 	                        {
 	                            print '<tr class="oddeven"><td width="100">';
-	                            print (empty($module->name)?$name:$module->name);
+	                            print (empty($module->name) ? $name : $module->name);
 	                            print "</td><td>\n";
 	                            if (method_exists($module, 'info')) print $module->info($langs);
 	                            else print $module->description;
@@ -555,8 +555,8 @@ foreach ($dirmodels as $reldir)
 	                            print '</td>';
 
 	                            // Info
-	                            $htmltooltip =    ''.$langs->trans("Name").': '.$module->name;
-	                            $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown"));
+	                            $htmltooltip = ''.$langs->trans("Name").': '.$module->name;
+	                            $htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
 	                            if ($module->type == 'pdf')
 	                            {
 	                                $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
@@ -600,7 +600,7 @@ foreach ($dirmodels as $reldir)
 }
 print '</table>';
 
-if(!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf
+if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf
 {
     /*
      *  Document templates generators
@@ -617,13 +617,13 @@ if(!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf
     print '<td class="right"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
     print "</tr>\n";
 
-    $listtype=array(
+    $listtype = array(
         Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"),
         Facture::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"),
         Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"),
         Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"),
     );
-    if (! empty($conf->global->INVOICE_USE_SITUATION))
+    if (!empty($conf->global->INVOICE_USE_SITUATION))
     {
         $listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation");
     }
@@ -631,7 +631,7 @@ if(!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) // Hidden conf
     foreach ($listtype as $type => $trans)
     {
         $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$type;
-        $current = !empty($conf->global->{$thisTypeConfName})?$conf->global->{$thisTypeConfName}:$conf->global->FACTURE_ADDON_PDF;
+        $current = !empty($conf->global->{$thisTypeConfName}) ? $conf->global->{$thisTypeConfName}:$conf->global->FACTURE_ADDON_PDF;
         print '<tr >';
         print '<td>'.$trans.'</td>';
         print '<td colspan="2" >'.$form->selectarray('invoicetypemodels['.$type.']', ModelePDFFactures::liste_modeles($db), $current, 0, 0, 0).'</td>';
@@ -663,14 +663,14 @@ print "</tr>\n";
 print '<tr class="oddeven">';
 print "<td>".$langs->trans("SuggestPaymentByRIBOnAccount")."</td>";
 print "<td>";
-if (! empty($conf->banque->enabled))
+if (!empty($conf->banque->enabled))
 {
     $sql = "SELECT rowid, label";
-    $sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
-    $sql.= " WHERE clos = 0";
-    $sql.= " AND courant = 1";
-    $sql.= " AND entity IN (".getEntity('bank_account').")";
-    $resql=$db->query($sql);
+    $sql .= " FROM ".MAIN_DB_PREFIX."bank_account";
+    $sql .= " WHERE clos = 0";
+    $sql .= " AND courant = 1";
+    $sql .= " AND entity IN (".getEntity('bank_account').")";
+    $resql = $db->query($sql);
     if ($resql)
     {
         $num = $db->num_rows($resql);
@@ -684,7 +684,7 @@ if (! empty($conf->banque->enabled))
                 $row = $db->fetch_row($resql);
 
                 print '<option value="'.$row[0].'"';
-                print $conf->global->FACTURE_RIB_NUMBER == $row[0] ? ' selected':'';
+                print $conf->global->FACTURE_RIB_NUMBER == $row[0] ? ' selected' : '';
                 print '>'.$row[1].'</option>';
 
                 $i++;
@@ -708,15 +708,15 @@ print "<td>".$langs->trans("SuggestPaymentByChequeToAddress")."</td>";
 print "<td>";
 print '<select class="flat" name="chq" id="chq">';
 print '<option value="0">'.$langs->trans("DoNotSuggestPaymentMode").'</option>';
-print '<option value="-1"'.($conf->global->FACTURE_CHQ_NUMBER?' selected':'').'>'.$langs->trans("MenuCompanySetup").' ('.($mysoc->name?$mysoc->name:$langs->trans("NotDefined")).')</option>';
+print '<option value="-1"'.($conf->global->FACTURE_CHQ_NUMBER ? ' selected' : '').'>'.$langs->trans("MenuCompanySetup").' ('.($mysoc->name ? $mysoc->name : $langs->trans("NotDefined")).')</option>';
 
 $sql = "SELECT rowid, label";
-$sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
-$sql.= " WHERE clos = 0";
-$sql.= " AND courant = 1";
-$sql.= " AND entity IN (".getEntity('bank_account').")";
+$sql .= " FROM ".MAIN_DB_PREFIX."bank_account";
+$sql .= " WHERE clos = 0";
+$sql .= " AND courant = 1";
+$sql .= " AND entity IN (".getEntity('bank_account').")";
 
-$resql=$db->query($sql);
+$resql = $db->query($sql);
 if ($resql)
 {
     $num = $db->num_rows($resql);
@@ -726,7 +726,7 @@ if ($resql)
         $row = $db->fetch_row($resql);
 
         print '<option value="'.$row[0].'"';
-        print $conf->global->FACTURE_CHQ_NUMBER == $row[0] ? ' selected':'';
+        print $conf->global->FACTURE_CHQ_NUMBER == $row[0] ? ' selected' : '';
         print '>'.$langs->trans("OwnerOfBankAccount", $row[1]).'</option>';
 
         $i++;
@@ -761,18 +761,18 @@ print '<input type="submit" class="button" value="'.$langs->trans("Modify").'" /
 print "</td></tr>\n";
 print '</form>';
 
-$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2);
-$substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation");
+$substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2);
+$substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation");
 $htmltext = '<i>'.$langs->trans("AvailableVariables").':<br>';
-foreach($substitutionarray as $key => $val)	$htmltext.=$key.'<br>';
-$htmltext.='</i>';
+foreach ($substitutionarray as $key => $val)	$htmltext .= $key.'<br>';
+$htmltext .= '</i>';
 
 print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
 print '<input type="hidden" name="token" value="'.newToken().'" />';
 print '<input type="hidden" name="action" value="set_INVOICE_FREE_TEXT" />';
 print '<tr class="oddeven"><td colspan="2">';
 print $form->textwithpicto($langs->trans("FreeLegalTextOnInvoices"), $langs->trans("AddCRIfTooLong").'<br><br>'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'<br>';
-$variablename='INVOICE_FREE_TEXT';
+$variablename = 'INVOICE_FREE_TEXT';
 if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
 {
     print '<textarea name="'.$variablename.'" class="flat" cols="120">'.$conf->global->$variablename.'</textarea>';
@@ -780,7 +780,7 @@ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
 else
 {
     include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-    $doleditor=new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes');
+    $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes');
     print $doleditor->Create();
 }
 print '</td><td class="right">';

+ 1 - 1
htdocs/admin/mails.php

@@ -638,7 +638,7 @@ else
 	$liste['user'] = $langs->trans('UserEmail');
 	$liste['company'] = $langs->trans('CompanyEmail').' ('.(empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? $langs->trans("NotDefined") : $conf->global->MAIN_INFO_SOCIETE_MAIL).')';
 	$sql = 'SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile';
-	$sql.= ' WHERE active = 1 AND (private = 0 OR private = '.$user->id.')';
+	$sql .= ' WHERE active = 1 AND (private = 0 OR private = '.$user->id.')';
 	$resql = $db->query($sql);
 	if ($resql)
 	{

+ 7 - 7
htdocs/admin/mails_senderprofile_list.php

@@ -108,9 +108,9 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count
 		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),
+				'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])
+				'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])
 			);
 		}
 	}
@@ -451,7 +451,7 @@ foreach ($object->fields as $key => $val)
 		elseif (strpos($val['type'], 'integer:') === 0) {
 			print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1);
 		}
-		elseif (! preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
+		elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
 		print '</td>';
 	}
 }
@@ -555,10 +555,10 @@ while ($i < ($limit ? min($num, $limit) : $num))
 	// Action column
 	print '<td class="nowrap center">';
 	$url = $_SERVER["PHP_SELF"].'?action=list&id='.$obj->rowid;
-	if ($limit) $url.='&limit='.urlencode($limit);
-	if ($page) $url.='&page='.urlencode($page);
-	if ($sortfield) $url.='&sortfield='.urlencode($sortfield);
-	if ($sortorder) $url.='&page='.urlencode($sortorder);
+	if ($limit) $url .= '&limit='.urlencode($limit);
+	if ($page) $url .= '&page='.urlencode($page);
+	if ($sortfield) $url .= '&sortfield='.urlencode($sortfield);
+	if ($sortorder) $url .= '&page='.urlencode($sortorder);
 	//print '<a class="reposition" href="'.$url.'&action=edit">'.img_edit().'</a>';
 	//print ' &nbsp; ';
 	print '<a href="'.$url.'&action=delete">'.img_delete().'</a>  &nbsp; ';

+ 59 - 59
htdocs/admin/mrp.php

@@ -31,7 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/mrp/lib/mrp.lib.php';
 // Load translation files required by the page
 $langs->loadLangs(array('admin', 'errors', 'mrp', 'other'));
 
-if (! $user->admin) accessforbidden();
+if (!$user->admin) accessforbidden();
 
 $action = GETPOST('action', 'alpha');
 $value = GETPOST('value', 'alpha');
@@ -48,14 +48,14 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
 
 if ($action == 'updateMask')
 {
-	$maskconstmrp=GETPOST('maskconstMo', 'alpha');
-	$maskmrp=GETPOST('maskMo', 'alpha');
+	$maskconstmrp = GETPOST('maskconstMo', 'alpha');
+	$maskmrp = GETPOST('maskMo', 'alpha');
 
 	if ($maskconstmrp) $res = dolibarr_set_const($db, $maskconstmrp, $maskmrp, 'chaine', 0, '', $conf->entity);
 
-	if (! $res > 0) $error++;
+	if (!$res > 0) $error++;
 
- 	if (! $error)
+ 	if (!$error)
     {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
@@ -67,20 +67,20 @@ if ($action == 'updateMask')
 
 elseif ($action == 'specimen')
 {
-	$modele=GETPOST('module', 'alpha');
+	$modele = GETPOST('module', 'alpha');
 
 	$mo = new MO($db);
 	$mrp->initAsSpecimen();
 
 	// Search template files
-	$file=''; $classname=''; $filefound=0;
-	$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']);
-	foreach($dirmodels as $reldir)
+	$file = ''; $classname = ''; $filefound = 0;
+	$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+	foreach ($dirmodels as $reldir)
 	{
-	    $file=dol_buildpath($reldir."core/modules/mrp/doc/pdf_".$modele.".modules.php", 0);
+	    $file = dol_buildpath($reldir."core/modules/mrp/doc/pdf_".$modele.".modules.php", 0);
 		if (file_exists($file))
 		{
-			$filefound=1;
+			$filefound = 1;
 			$classname = "pdf_".$modele;
 			break;
 		}
@@ -156,9 +156,9 @@ elseif ($action == 'set_MRP_MO_DRAFT_WATERMARK')
 	$draft = GETPOST("MRP_MO_DRAFT_WATERMARK");
 	$res = dolibarr_set_const($db, "MRP_MO_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity);
 
-	if (! $res > 0) $error++;
+	if (!$res > 0) $error++;
 
- 	if (! $error)
+ 	if (!$error)
     {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
@@ -170,13 +170,13 @@ elseif ($action == 'set_MRP_MO_DRAFT_WATERMARK')
 
 elseif ($action == 'set_MRP_MO_FREE_TEXT')
 {
-	$freetext = GETPOST("MRP_MO_FREE_TEXT", 'none');	// No alpha here, we want exact string
+	$freetext = GETPOST("MRP_MO_FREE_TEXT", 'none'); // No alpha here, we want exact string
 
 	$res = dolibarr_set_const($db, "MRP_MO_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity);
 
-	if (! $res > 0) $error++;
+	if (!$res > 0) $error++;
 
- 	if (! $error)
+ 	if (!$error)
     {
         setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
     }
@@ -191,13 +191,13 @@ elseif ($action == 'set_MRP_MO_FREE_TEXT')
  * View
  */
 
-$form=new Form($db);
+$form = new Form($db);
 
-$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']);
+$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
 
 llxHeader("", $langs->trans("MrpSetupPage"));
 
-$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("MrpSetupPage"), $linkback, 'title_setup');
 
 $head = mrpAdminPrepareHead();
@@ -230,18 +230,18 @@ foreach ($dirmodels as $reldir)
 		$handle = opendir($dir);
 		if (is_resource($handle))
 		{
-			while (($file = readdir($handle))!==false)
+			while (($file = readdir($handle)) !== false)
 			{
-			    if (substr($file, 0, 7) == 'mod_mo_' && substr($file, dol_strlen($file)-3, 3) == 'php')
+			    if (substr($file, 0, 7) == 'mod_mo_' && substr($file, dol_strlen($file) - 3, 3) == 'php')
 				{
-					$file = substr($file, 0, dol_strlen($file)-4);
+					$file = substr($file, 0, dol_strlen($file) - 4);
 
 					require_once $dir.$file.'.php';
 
 					$module = new $file($db);
 
 					// 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())
@@ -252,9 +252,9 @@ foreach ($dirmodels as $reldir)
 
                         // Show example of numbering model
                         print '<td class="nowrap">';
-                        $tmp=$module->getExample();
+                        $tmp = $module->getExample();
                         if (preg_match('/^Error/', $tmp)) 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";
 
@@ -271,22 +271,22 @@ foreach ($dirmodels as $reldir)
 						}
 						print '</td>';
 
-						$mrp=new MO($db);
+						$mrp = new MO($db);
 						$mrp->initAsSpecimen();
 
 						// Info
-						$htmltooltip='';
-						$htmltooltip.=''.$langs->trans("Version").': <b>'.$module->getVersion().'</b><br>';
-						$mrp->type=0;
-						$nextval=$module->getNextValue($mysoc, $mrp);
+						$htmltooltip = '';
+						$htmltooltip .= ''.$langs->trans("Version").': <b>'.$module->getVersion().'</b><br>';
+						$mrp->type = 0;
+						$nextval = $module->getNextValue($mysoc, $mrp);
                         if ("$nextval" != $langs->trans("NotAvailable")) {  // Keep " on nextval
-                            $htmltooltip.=''.$langs->trans("NextValue").': ';
+                            $htmltooltip .= ''.$langs->trans("NextValue").': ';
                             if ($nextval) {
-                                if (preg_match('/^Error/', $nextval) || $nextval=='NotConfigured')
+                                if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured')
                                     $nextval = $langs->trans($nextval);
-                                $htmltooltip.=$nextval.'<br>';
+                                $htmltooltip .= $nextval.'<br>';
                             } else {
-                                $htmltooltip.=$langs->trans($module->error).'<br>';
+                                $htmltooltip .= $langs->trans($module->error).'<br>';
                             }
                         }
 
@@ -314,14 +314,14 @@ print load_fiche_titre($langs->trans("MOsModelModule"), '', '');
 // Load array def with activated templates
 $def = array();
 $sql = "SELECT nom";
-$sql.= " FROM ".MAIN_DB_PREFIX."document_model";
-$sql.= " WHERE type = '".$type."'";
-$sql.= " AND entity = ".$conf->entity;
-$resql=$db->query($sql);
+$sql .= " FROM ".MAIN_DB_PREFIX."document_model";
+$sql .= " WHERE type = '".$type."'";
+$sql .= " AND entity = ".$conf->entity;
+$resql = $db->query($sql);
 if ($resql)
 {
 	$i = 0;
-	$num_rows=$db->num_rows($resql);
+	$num_rows = $db->num_rows($resql);
 	while ($i < $num_rows)
 	{
 		$array = $db->fetch_array($resql);
@@ -349,43 +349,43 @@ clearstatcache();
 
 foreach ($dirmodels as $reldir)
 {
-    foreach (array('','/doc') as $valdir)
+    foreach (array('', '/doc') as $valdir)
     {
     	$realpath = $reldir."core/modules/mrp".$valdir;
     	$dir = dol_buildpath($realpath);
 
         if (is_dir($dir))
         {
-            $handle=opendir($dir);
+            $handle = opendir($dir);
             if (is_resource($handle))
             {
-                while (($file = readdir($handle))!==false)
+                while (($file = readdir($handle)) !== false)
                 {
-                    $filelist[]=$file;
+                    $filelist[] = $file;
                 }
                 closedir($handle);
                 arsort($filelist);
 
-                foreach($filelist as $file)
+                foreach ($filelist as $file)
                 {
                     if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file))
                     {
                     	if (file_exists($dir.'/'.$file))
                     	{
-                    		$name = substr($file, 4, dol_strlen($file) -16);
-	                        $classname = substr($file, 0, dol_strlen($file) -12);
+                    		$name = substr($file, 4, dol_strlen($file) - 16);
+	                        $classname = substr($file, 0, dol_strlen($file) - 12);
 
 	                        require_once $dir.'/'.$file;
 	                        $module = new $classname($db);
 
-	                        $modulequalified=1;
-	                        if ($module->version == 'development'  && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0;
-	                        if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0;
+	                        $modulequalified = 1;
+	                        if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0;
+	                        if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0;
 
 	                        if ($modulequalified)
 	                        {
 	                            print '<tr class="oddeven"><td width="100">';
-	                            print (empty($module->name)?$name:$module->name);
+	                            print (empty($module->name) ? $name : $module->name);
 	                            print "</td><td>\n";
 	                            if (method_exists($module, 'info')) print $module->info($langs);
 	                            else print $module->description;
@@ -420,11 +420,11 @@ foreach ($dirmodels as $reldir)
 	                            print '</td>';
 
 	                            // Info
-		    					$htmltooltip =    ''.$langs->trans("Name").': '.$module->name;
-					    		$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown"));
+		    					$htmltooltip = ''.$langs->trans("Name").': '.$module->name;
+					    		$htmltooltip .= '<br>'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown"));
 			                    if ($module->type == 'pdf')
 			                    {
-			                        $htmltooltip.='<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
+			                        $htmltooltip .= '<br>'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur;
 			                    }
 			                    $htmltooltip .= '<br>'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file;
 
@@ -474,18 +474,18 @@ print '<td class="center" width="60">'.$langs->trans("Value").'</td>';
 print "<td>&nbsp;</td>\n";
 print "</tr>\n";
 
-$substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2);
-$substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation");
+$substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2);
+$substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation");
 $htmltext = '<i>'.$langs->trans("AvailableVariables").':<br>';
-foreach($substitutionarray as $key => $val)	$htmltext.=$key.'<br>';
-$htmltext.='</i>';
+foreach ($substitutionarray as $key => $val)	$htmltext .= $key.'<br>';
+$htmltext .= '</i>';
 
 print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
 print '<input type="hidden" name="token" value="'.newToken().'">';
 print '<input type="hidden" name="action" value="set_MRP_MO_FREE_TEXT">';
 print '<tr class="oddeven"><td colspan="2">';
 print $form->textwithpicto($langs->trans("FreeLegalTextOnMOs"), $langs->trans("AddCRIfTooLong").'<br><br>'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'<br>';
-$variablename='MRP_MO_FREE_TEXT';
+$variablename = 'MRP_MO_FREE_TEXT';
 if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
 {
     print '<textarea name="'.$variablename.'" class="flat" cols="120">'.$conf->global->$variablename.'</textarea>';
@@ -493,7 +493,7 @@ if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
 else
 {
     include_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-    $doleditor=new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes');
+    $doleditor = new DolEditor($variablename, $conf->global->$variablename, '', 80, 'dolibarr_notes');
     print $doleditor->Create();
 }
 print '</td><td class="right">';

+ 9 - 9
htdocs/admin/order_extrafields.php

@@ -41,13 +41,13 @@ $extrafields = new ExtraFields($db);
 $form = new Form($db);
 
 // List of supported format
-$tmptype2label=ExtraFields::$type2label;
-$type2label=array('');
-foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val);
+$tmptype2label = ExtraFields::$type2label;
+$type2label = array('');
+foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val);
 
-$action=GETPOST('action', 'alpha');
-$attrname=GETPOST('attrname', 'alpha');
-$elementtype='commande'; //Must be the $table_element of the class that manage extrafield
+$action = GETPOST('action', 'alpha');
+$attrname = GETPOST('attrname', 'alpha');
+$elementtype = 'commande'; //Must be the $table_element of the class that manage extrafield
 
 if (!$user->admin) accessforbidden();
 
@@ -64,11 +64,11 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php';
  * View
  */
 
-$textobject=$langs->transnoentitiesnoconv("Orders");
+$textobject = $langs->transnoentitiesnoconv("Orders");
 
 llxHeader('', $langs->trans("OrdersSetup"));
 
-$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("OrdersSetup"), $linkback, 'title_setup');
 
 $head = order_admin_prepare_head();
@@ -108,7 +108,7 @@ if ($action == 'create')
 /* Edition of an optional field                                               */
 /*                                                                            */
 /* ************************************************************************** */
-if ($action == 'edit' && ! empty($attrname))
+if ($action == 'edit' && !empty($attrname))
 {
     print "<br>";
     print load_fiche_titre($langs->trans("FieldEdition", $attrname));

+ 9 - 9
htdocs/admin/orderdet_extrafields.php

@@ -42,13 +42,13 @@ $extrafields = new ExtraFields($db);
 $form = new Form($db);
 
 // List of supported format
-$tmptype2label=ExtraFields::$type2label;
-$type2label=array('');
-foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val);
+$tmptype2label = ExtraFields::$type2label;
+$type2label = array('');
+foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val);
 
-$action=GETPOST('action', 'alpha');
-$attrname=GETPOST('attrname', 'alpha');
-$elementtype='commandedet'; //Must be the $table_element of the class that manage extrafield
+$action = GETPOST('action', 'alpha');
+$attrname = GETPOST('attrname', 'alpha');
+$elementtype = 'commandedet'; //Must be the $table_element of the class that manage extrafield
 
 if (!$user->admin) accessforbidden();
 
@@ -65,11 +65,11 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php';
  * View
  */
 
-$textobject=$langs->transnoentitiesnoconv("Orders");
+$textobject = $langs->transnoentitiesnoconv("Orders");
 
 llxHeader('', $langs->trans("OrdersSetup"));
 
-$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("OrdersSetup"), $linkback, 'title_setup');
 
 $head = order_admin_prepare_head();
@@ -109,7 +109,7 @@ if ($action == 'create')
 /* Edition of an optional field                                               */
 /*                                                                            */
 /* ************************************************************************** */
-if ($action == 'edit' && ! empty($attrname))
+if ($action == 'edit' && !empty($attrname))
 {
     print "<br>";
     print load_fiche_titre($langs->trans("FieldEdition", $attrname));

+ 85 - 85
htdocs/admin/tools/listevents.php

@@ -28,11 +28,11 @@ require '../../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/events.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
 
-if (! $user->admin)
+if (!$user->admin)
 	accessforbidden();
 
-$action=GETPOST('action', 'alpha');
-$confirm=GETPOST('confirm', 'alpha');
+$action = GETPOST('action', 'alpha');
+$confirm = GETPOST('confirm', 'alpha');
 
 // Security check
 if ($user->socid > 0)
@@ -42,10 +42,10 @@ if ($user->socid > 0)
 }
 
 // Load translation files required by the page
-$langs->loadLangs(array("companies","admin","users","other"));
+$langs->loadLangs(array("companies", "admin", "users", "other"));
 
 // 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');
@@ -53,8 +53,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="dateevent";
-if (! $sortorder) $sortorder="DESC";
+if (!$sortfield) $sortfield = "dateevent";
+if (!$sortorder) $sortorder = "DESC";
 
 $search_code = GETPOST("search_code", "alpha");
 $search_ip   = GETPOST("search_ip", "alpha");
@@ -63,24 +63,24 @@ $search_desc = GETPOST("search_desc", "alpha");
 $search_ua   = GETPOST("search_ua", "none");
 $search_prefix_session = GETPOST("search_prefix_session", "none");
 
-if (GETPOST("date_startmonth") == '' || GETPOST("date_startmonth") > 0) $date_start=dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear"));
-else $date_start=-1;
-if (GETPOST("date_endmonth") == '' || GETPOST("date_endmonth") > 0) $date_end=dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear"));
-else $date_end=-1;
+if (GETPOST("date_startmonth") == '' || GETPOST("date_startmonth") > 0) $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear"));
+else $date_start = -1;
+if (GETPOST("date_endmonth") == '' || GETPOST("date_endmonth") > 0) $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear"));
+else $date_end = -1;
 
 // checks:if date_start>date_end  then date_end=date_start + 24 hours
-if ($date_start > 0 && $date_end > 0 && $date_start > $date_end) $date_end=$date_start+86400;
+if ($date_start > 0 && $date_end > 0 && $date_start > $date_end) $date_end = $date_start + 86400;
 
 $now = dol_now();
 $nowarray = dol_getdate($now);
 
 if (empty($date_start)) // We define date_start and date_end
 {
-    $date_start=dol_get_first_day($nowarray['year'], $nowarray['mon'], false);
+    $date_start = dol_get_first_day($nowarray['year'], $nowarray['mon'], false);
 }
 if (empty($date_end))
 {
-    $date_end=dol_mktime(23, 59, 59, $nowarray['mon'], $nowarray['mday'], $nowarray['year']);
+    $date_end = dol_mktime(23, 59, 59, $nowarray['mon'], $nowarray['mday'], $nowarray['year']);
 }
 // Set $date_startmonth...
 $tmp = dol_getdate($date_start);
@@ -92,56 +92,56 @@ $date_endday = $tmp['mday'];
 $date_endmonth = $tmp['mon'];
 $date_endyear = $tmp['year'];
 
-$arrayfields=array();
+$arrayfields = array();
 
 
 /*
  * Actions
  */
 
-$now=dol_now();
+$now = dol_now();
 
 // 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
 {
-    $date_start=-1;
-    $date_end=-1;
-    $search_code='';
-    $search_ip='';
-    $search_user='';
-    $search_desc='';
-    $search_ua='';
-    $search_prefix_session='';
+    $date_start = -1;
+    $date_end = -1;
+    $search_code = '';
+    $search_ip = '';
+    $search_user = '';
+    $search_desc = '';
+    $search_ua = '';
+    $search_prefix_session = '';
 }
 
 // Purge audit events
 if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin)
 {
-	$error=0;
+	$error = 0;
 
 	$db->begin();
-	$securityevents=new Events($db);
+	$securityevents = new Events($db);
 
 	// Delete events
 	$sql = "DELETE FROM ".MAIN_DB_PREFIX."events";
-	$sql.= " WHERE entity = ".$conf->entity;
+	$sql .= " WHERE entity = ".$conf->entity;
 
 	dol_syslog("listevents purge", LOG_DEBUG);
 	$resql = $db->query($sql);
-	if (! $resql)
+	if (!$resql)
 	{
 		$error++;
 		setEventMessages($db->lasterror(), null, 'errors');
 	}
 
 	// Add event purge
-	$text=$langs->trans("SecurityEventsPurged");
-	$securityevent=new Events($db);
-	$securityevent->type='SECURITY_EVENTS_PURGE';
-	$securityevent->dateevent=$now;
-	$securityevent->description=$text;
+	$text = $langs->trans("SecurityEventsPurged");
+	$securityevent = new Events($db);
+	$securityevent->type = 'SECURITY_EVENTS_PURGE';
+	$securityevent->dateevent = $now;
+	$securityevent->description = $text;
 
-	$result=$securityevent->create($user);
+	$result = $securityevent->create($user);
 	if ($result > 0)
 	{
 	    $db->commit();
@@ -162,26 +162,26 @@ if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin)
 
 llxHeader('', $langs->trans("Audit"));
 
-$form=new Form($db);
+$form = new Form($db);
 
-$userstatic=new User($db);
-$usefilter=0;
+$userstatic = new User($db);
+$usefilter = 0;
 
 $sql = "SELECT e.rowid, e.type, e.ip, e.user_agent, e.dateevent,";
-$sql.= " e.fk_user, e.description, e.prefix_session,";
-$sql.= " u.login";
-$sql.= " FROM ".MAIN_DB_PREFIX."events as e";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = e.fk_user";
-$sql.= " WHERE e.entity IN (".getEntity('event').")";
-if ($date_start > 0) $sql.= " AND e.dateevent >= '".$db->idate($date_start)."'";
-if ($date_end > 0)   $sql.= " AND e.dateevent <= '".$db->idate($date_end)."'";
-if ($search_code) { $usefilter++; $sql.=natural_search("e.type", $search_code, 0); }
-if ($search_ip)   { $usefilter++; $sql.=natural_search("e.ip", $search_ip, 0); }
-if ($search_user) { $usefilter++; $sql.=natural_search("u.login", $search_user, 0); }
-if ($search_desc) { $usefilter++; $sql.=natural_search("e.description", $search_desc, 0); }
-if ($search_ua)   { $usefilter++; $sql.=natural_search("e.user_agent", $search_ua, 0); }
-if ($search_prefix_session)   { $usefilter++; $sql.=natural_search("e.prefix_session", $search_prefix_session, 0); }
-$sql.= $db->order($sortfield, $sortorder);
+$sql .= " e.fk_user, e.description, e.prefix_session,";
+$sql .= " u.login";
+$sql .= " FROM ".MAIN_DB_PREFIX."events as e";
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = e.fk_user";
+$sql .= " WHERE e.entity IN (".getEntity('event').")";
+if ($date_start > 0) $sql .= " AND e.dateevent >= '".$db->idate($date_start)."'";
+if ($date_end > 0)   $sql .= " AND e.dateevent <= '".$db->idate($date_end)."'";
+if ($search_code) { $usefilter++; $sql .= natural_search("e.type", $search_code, 0); }
+if ($search_ip) { $usefilter++; $sql .= natural_search("e.ip", $search_ip, 0); }
+if ($search_user) { $usefilter++; $sql .= natural_search("u.login", $search_user, 0); }
+if ($search_desc) { $usefilter++; $sql .= natural_search("e.description", $search_desc, 0); }
+if ($search_ua) { $usefilter++; $sql .= natural_search("e.user_agent", $search_ua, 0); }
+if ($search_prefix_session) { $usefilter++; $sql .= natural_search("e.prefix_session", $search_prefix_session, 0); }
+$sql .= $db->order($sortfield, $sortorder);
 
 // Count total nb of records
 $nbtotalofrecords = '';
@@ -196,7 +196,7 @@ $nbtotalofrecords = '';
     }
 }*/
 
-$sql.= $db->plimit($conf->liste_limit+1, $offset);
+$sql .= $db->plimit($conf->liste_limit + 1, $offset);
 //print $sql;
 $result = $db->query($sql);
 if ($result)
@@ -204,27 +204,27 @@ if ($result)
 	$num = $db->num_rows($result);
 	$i = 0;
 
-	$param='';
-	if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
-	if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
-	if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss);
-	if ($search_code) $param.='&search_code='.urlencode($search_code);
-	if ($search_ip)   $param.='&search_ip='.urlencode($search_ip);
-	if ($search_user) $param.='&search_user='.urlencode($search_user);
-	if ($search_desc) $param.='&search_desc='.urlencode($search_desc);
-	if ($search_ua)   $param.='&search_ua='.urlencode($search_ua);
-	if ($search_prefix_sessiona)   $param.='&search_prefix_session='.urlencode($search_prefix_session);
-	if ($date_startmonth) $param.= "&date_startmonth=".urlencode($date_startmonth);
-	if ($date_startday)   $param.= "&date_startday=".urlencode($date_startday);
-	if ($date_startyear)  $param.= "&date_startyear=".urlencode($date_startyear);
-	if ($date_endmonth)   $param.= "&date_endmonth=".urlencode($date_endmonth);
-	if ($date_endday)     $param.= "&date_endday=".urlencode($date_endday);
-	if ($date_endyear)    $param.= "&date_endyear=".urlencode($date_endyear);
+	$param = '';
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
+	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+	if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss);
+	if ($search_code) $param .= '&search_code='.urlencode($search_code);
+	if ($search_ip)   $param .= '&search_ip='.urlencode($search_ip);
+	if ($search_user) $param .= '&search_user='.urlencode($search_user);
+	if ($search_desc) $param .= '&search_desc='.urlencode($search_desc);
+	if ($search_ua)   $param .= '&search_ua='.urlencode($search_ua);
+	if ($search_prefix_sessiona)   $param .= '&search_prefix_session='.urlencode($search_prefix_session);
+	if ($date_startmonth) $param .= "&date_startmonth=".urlencode($date_startmonth);
+	if ($date_startday)   $param .= "&date_startday=".urlencode($date_startday);
+	if ($date_startyear)  $param .= "&date_startyear=".urlencode($date_startyear);
+	if ($date_endmonth)   $param .= "&date_endmonth=".urlencode($date_endmonth);
+	if ($date_endday)     $param .= "&date_endday=".urlencode($date_endday);
+	if ($date_endyear)    $param .= "&date_endyear=".urlencode($date_endyear);
 
     $langs->load('withdrawals');
     if ($num)
     {
-        $center='<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=purge">'.$langs->trans("Purge").'</a>';
+        $center = '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=purge">'.$langs->trans("Purge").'</a>';
     }
 
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
@@ -233,7 +233,7 @@ if ($result)
 
 	if ($action == 'purge')
 	{
-		$formquestion=array();
+		$formquestion = array();
 		print $form->formconfirm($_SERVER["PHP_SELF"].'?noparam=noparam', $langs->trans('PurgeAuditEvents'), $langs->trans('ConfirmPurgeAuditEvents'), 'confirm_purge', $formquestion, 'no', 1);
 	}
 
@@ -262,14 +262,14 @@ if ($result)
 	//print '<input class="flat maxwidth100" type="text" size="10" name="search_desc" value="'.$search_desc.'">';
 	print '</td>';
 
-	if (! empty($arrayfields['e.user_agent']['checked']))
+	if (!empty($arrayfields['e.user_agent']['checked']))
 	{
 		print '<td class="liste_titre left">';
 		print '<input class="flat maxwidth100" type="text" name="search_ua" value="'.$search_ua.'">';
 		print '</td>';
 	}
 
-	if (! empty($arrayfields['e.prefix_session']['checked']))
+	if (!empty($arrayfields['e.prefix_session']['checked']))
 	{
 		print '<td class="liste_titre left">';
 		print '<input class="flat maxwidth100" type="text" name="search_prefix_session" value="'.$search_prefix_session.'">';
@@ -277,7 +277,7 @@ if ($result)
 	}
 
 	print '<td class="liste_titre maxwidthsearch">';
-	$searchpicto=$form->showFilterAndCheckAddButtons(0);
+	$searchpicto = $form->showFilterAndCheckAddButtons(0);
 	print $searchpicto;
 	print '</td>';
 
@@ -290,11 +290,11 @@ if ($result)
 	print_liste_field_titre("IP", $_SERVER["PHP_SELF"], "e.ip", "", $param, '', $sortfield, $sortorder);
 	print_liste_field_titre("User", $_SERVER["PHP_SELF"], "u.login", "", $param, '', $sortfield, $sortorder);
 	print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "e.description", "", $param, '', $sortfield, $sortorder);
-	if (! empty($arrayfields['e.user_agent']['checked']))
+	if (!empty($arrayfields['e.user_agent']['checked']))
 	{
 		print_liste_field_titre("UserAgent", $_SERVER["PHP_SELF"], "e.user_agent", "", $param, '', $sortfield, $sortorder);
 	}
-	if (! empty($arrayfields['e.prefix_session']['checked']))
+	if (!empty($arrayfields['e.prefix_session']['checked']))
 	{
 		print_liste_field_titre("PrefixSession", $_SERVER["PHP_SELF"], "e.prefix_session", "", $param, '', $sortfield, $sortorder);
 	}
@@ -322,8 +322,8 @@ if ($result)
 		print '<td class="nowrap">';
 		if ($obj->fk_user)
 		{
-			$userstatic->id=$obj->fk_user;
-			$userstatic->login=$obj->login;
+			$userstatic->id = $obj->fk_user;
+			$userstatic->login = $obj->login;
 			print $userstatic->getLoginUrl(1);
 		}
 		else print '&nbsp;';
@@ -331,18 +331,18 @@ if ($result)
 
 		// Description
 		print '<td>';
-		$text=$langs->trans($obj->description);
+		$text = $langs->trans($obj->description);
 		$reg = array();
 		if (preg_match('/\((.*)\)(.*)/i', $obj->description, $reg))
 		{
-			$val=explode(',', $reg[1]);
-			$text=$langs->trans($val[0], isset($val[1])?$val[1]:'', isset($val[2])?$val[2]:'', isset($val[3])?$val[3]:'', isset($val[4])?$val[4]:'');
-			if (! empty($reg[2])) $text.=$reg[2];
+			$val = explode(',', $reg[1]);
+			$text = $langs->trans($val[0], isset($val[1]) ? $val[1] : '', isset($val[2]) ? $val[2] : '', isset($val[3]) ? $val[3] : '', isset($val[4]) ? $val[4] : '');
+			if (!empty($reg[2])) $text .= $reg[2];
 		}
 		print dol_escape_htmltag($text);
 		print '</td>';
 
-		if (! empty($arrayfields['e.user_agent']['checked']))
+		if (!empty($arrayfields['e.user_agent']['checked']))
 		{
 			// User agent
 			print '<td>';
@@ -350,7 +350,7 @@ if ($result)
 			print '</td>';
 		}
 
-		if (! empty($arrayfields['e.prefix_session']['checked']))
+		if (!empty($arrayfields['e.prefix_session']['checked']))
 		{
 			// User agent
 			print '<td>';
@@ -360,8 +360,8 @@ if ($result)
 
 		// More informations
 		print '<td class="right">';
-		$htmltext='<b>'.$langs->trans("UserAgent").'</b>: '.($obj->user_agent ? dol_string_nohtmltag($obj->user_agent) : $langs->trans("Unknown"));
-		$htmltext.='<br><b>'.$langs->trans("PrefixSession").'</b>: '.($obj->prefix_session ? dol_string_nohtmltag($obj->prefix_session) : $langs->trans("Unknown"));
+		$htmltext = '<b>'.$langs->trans("UserAgent").'</b>: '.($obj->user_agent ? dol_string_nohtmltag($obj->user_agent) : $langs->trans("Unknown"));
+		$htmltext .= '<br><b>'.$langs->trans("PrefixSession").'</b>: '.($obj->prefix_session ? dol_string_nohtmltag($obj->prefix_session) : $langs->trans("Unknown"));
 		print $form->textwithpicto('', $htmltext);
 		print '</td>';
 

+ 1 - 1
htdocs/bom/class/bom.class.php

@@ -747,7 +747,7 @@ class BOM extends CommonObject
         $label .= '<br>';
         $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
         if (isset($this->status)) {
-        	$label.= '<br><b>' . $langs->trans("Status").":</b> ".$this->getLibStatut(5);
+        	$label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5);
         }
 
         $url = dol_buildpath('/bom/bom_card.php', 1).'?id='.$this->id;

+ 133 - 133
htdocs/comm/action/class/actioncomm.class.php

@@ -272,7 +272,7 @@ class ActionComm extends CommonObject
     /**
      * @var int Id of linked object
      */
-    public $fk_element;    // Id of record
+    public $fk_element; // Id of record
 
     /**
      * @var int Id of record alternative for API
@@ -302,7 +302,7 @@ class ActionComm extends CommonObject
     /**
      * @var array Actions
      */
-    public $actions=array();
+    public $actions = array();
 
     /**
      * @var string Email msgid
@@ -839,11 +839,11 @@ class ActionComm extends CommonObject
     public function fetch_userassigned($override = true)
     {
         // phpcs:enable
-        $sql ="SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency";
-        $sql.=" FROM ".MAIN_DB_PREFIX."actioncomm_resources";
-        $sql.=" WHERE element_type = 'user' AND fk_actioncomm = ".$this->id;
+        $sql = "SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency";
+        $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_resources";
+        $sql .= " WHERE element_type = 'user' AND fk_actioncomm = ".$this->id;
 
-        $resql2=$this->db->query($sql);
+        $resql2 = $this->db->query($sql);
         if ($resql2)
         {
             $this->userassigned = array();
@@ -894,35 +894,35 @@ class ActionComm extends CommonObject
     {
         global $user;
 
-        $error=0;
+        $error = 0;
 
         $this->db->begin();
 
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm";
-        $sql.= " WHERE id=".$this->id;
+        $sql .= " WHERE id=".$this->id;
 
         dol_syslog(get_class($this)."::delete", LOG_DEBUG);
-        $res=$this->db->query($sql);
+        $res = $this->db->query($sql);
         if ($res < 0) {
-        	$this->error=$this->db->lasterror();
+        	$this->error = $this->db->lasterror();
         	$error++;
         }
 
-        if (! $error) {
+        if (!$error) {
             $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources";
-            $sql.= " WHERE fk_actioncomm=".$this->id;
+            $sql .= " WHERE fk_actioncomm=".$this->id;
 
             dol_syslog(get_class($this)."::delete", LOG_DEBUG);
-            $res=$this->db->query($sql);
+            $res = $this->db->query($sql);
             if ($res < 0) {
-                $this->error=$this->db->lasterror();
+                $this->error = $this->db->lasterror();
                 $error++;
             }
         }
 
         // Removed extrafields
-        if (! $error) {
-        	$result=$this->deleteExtraFields();
+        if (!$error) {
+        	$result = $this->deleteExtraFields();
           	if ($result < 0)
            	{
            		$error++;
@@ -1186,52 +1186,52 @@ class ActionComm extends CommonObject
         // phpcs:enable
         global $conf, $langs;
 
-    	if(empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp";
+    	if (empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp";
     	else {
-    		$this->nb=array();
+    		$this->nb = array();
     		$sql = "SELECT count(a.id) as nb";
     	}
-    	$sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
-    	if (! $user->rights->societe->client->voir && ! $user->socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc";
-    	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid";
-    	$sql.= " WHERE 1 = 1";
-    	if(empty($load_state_board)) $sql.= " AND a.percent >= 0 AND a.percent < 100";
-    	$sql.= " AND a.entity IN (".getEntity('agenda').")";
-    	if (! $user->rights->societe->client->voir && ! $user->socid) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")";
-    	if ($user->socid) $sql.=" AND a.fk_soc = ".$user->socid;
-    	if (! $user->rights->agenda->allactions->read) $sql.= " AND (a.fk_user_author = ".$user->id . " OR a.fk_user_action = ".$user->id . " OR a.fk_user_done = ".$user->id . ")";
-
-    	$resql=$this->db->query($sql);
+    	$sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
+    	if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc";
+    	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid";
+    	$sql .= " WHERE 1 = 1";
+    	if (empty($load_state_board)) $sql .= " AND a.percent >= 0 AND a.percent < 100";
+    	$sql .= " AND a.entity IN (".getEntity('agenda').")";
+    	if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")";
+    	if ($user->socid) $sql .= " AND a.fk_soc = ".$user->socid;
+    	if (!$user->rights->agenda->allactions->read) $sql .= " AND (a.fk_user_author = ".$user->id." OR a.fk_user_action = ".$user->id." OR a.fk_user_done = ".$user->id.")";
+
+    	$resql = $this->db->query($sql);
     	if ($resql)
     	{
-    		if(empty($load_state_board)) {
+    		if (empty($load_state_board)) {
 	    		$agenda_static = new ActionComm($this->db);
 	    		$response = new WorkboardResponse();
-	    		$response->warning_delay = $conf->agenda->warning_delay/60/60/24;
+	    		$response->warning_delay = $conf->agenda->warning_delay / 60 / 60 / 24;
 	    		$response->label = $langs->trans("ActionsToDo");
 	    		$response->labelShort = $langs->trans("ActionsToDoShort");
 	    		$response->url = DOL_URL_ROOT.'/comm/action/list.php?actioncode=0&amp;status=todo&amp;mainmenu=agenda';
-	    		if ($user->rights->agenda->allactions->read) $response->url.='&amp;filtert=-1';
+	    		if ($user->rights->agenda->allactions->read) $response->url .= '&amp;filtert=-1';
 	    		$response->img = img_object('', "action", 'class="inline-block valigntextmiddle"');
     		}
     		// This assignment in condition is not a bug. It allows walking the results.
-    		while ($obj=$this->db->fetch_object($resql))
+    		while ($obj = $this->db->fetch_object($resql))
     		{
-    			if(empty($load_state_board)) {
+    			if (empty($load_state_board)) {
 	    			$response->nbtodo++;
 	    			$agenda_static->datep = $this->db->jdate($obj->dp);
 	    			if ($agenda_static->hasDelay()) $response->nbtodolate++;
-    			} else $this->nb["actionscomm"]=$obj->nb;
+    			} else $this->nb["actionscomm"] = $obj->nb;
     		}
 
     		$this->db->free($resql);
-    		if(empty($load_state_board)) return $response;
+    		if (empty($load_state_board)) return $response;
     		else return 1;
     	}
     	else
     	{
     		dol_print_error($this->db);
-    		$this->error=$this->db->error();
+    		$this->error = $this->db->error();
     		return -1;
     	}
     }
@@ -1394,10 +1394,10 @@ class ActionComm extends CommonObject
         if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
 
 		$canread = 0;
-		if ($user->rights->agenda->myactions->read && $this->authorid == $user->id) $canread = 1;	// Can read my event
-		if ($user->rights->agenda->myactions->read && array_key_exists($user->id, $this->userassigned)) $canread = 1;	// Can read my event i am assigned
-		if ($user->rights->agenda->allactions->read) $canread = 1;		// Can read all event of other
-		if (! $canread)
+		if ($user->rights->agenda->myactions->read && $this->authorid == $user->id) $canread = 1; // Can read my event
+		if ($user->rights->agenda->myactions->read && array_key_exists($user->id, $this->userassigned)) $canread = 1; // Can read my event i am assigned
+		if ($user->rights->agenda->allactions->read) $canread = 1; // Can read all event of other
+		if (!$canread)
 		{
             $option = 'nolink';
 		}
@@ -1529,12 +1529,12 @@ class ActionComm extends CommonObject
     public function setCategories($categories)
     {
         // Handle single category
-        if (! is_array($categories)) {
+        if (!is_array($categories)) {
             $categories = array($categories);
         }
 
         // Get current categories
-        include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
+        include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
         $c = new Categorie($this->db);
         $existing = $c->containing($this->id, Categorie::TYPE_ACTIONCOMM, 'id');
 
@@ -1548,7 +1548,7 @@ class ActionComm extends CommonObject
         }
 
         // Process
-        foreach($to_del as $del) {
+        foreach ($to_del as $del) {
             if ($c->fetch($del) > 0) {
                 $c->del_type($this, Categorie::TYPE_ACTIONCOMM);
             }
@@ -1622,105 +1622,105 @@ class ActionComm extends CommonObject
         if ($buildfile)
         {
             // Build event array
-            $eventarray=array();
+            $eventarray = array();
 
             $sql = "SELECT a.id,";
-            $sql.= " a.datep,";		// Start
-            $sql.= " a.datep2,";	// End
-            $sql.= " a.durationp,";			// deprecated
-            $sql.= " a.datec, a.tms as datem,";
-            $sql.= " a.label, a.code, a.note, a.fk_action as type_id,";
-            $sql.= " a.fk_soc,";
-            $sql.= " a.fk_user_author, a.fk_user_mod,";
-            $sql.= " a.fk_user_action,";
-            $sql.= " a.fk_contact, a.percent as percentage,";
-            $sql.= " a.fk_element, a.elementtype,";
-            $sql.= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,";
-            $sql.= " u.firstname, u.lastname, u.email,";
-            $sql.= " s.nom as socname,";
-            $sql.= " c.id as type_id, c.code as type_code, c.libelle as type_label";
-            $sql.= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)";
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";	// Link to get author of event for export
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
-
-			$parameters=array('filters' => $filters);
-			$reshook=$hookmanager->executeHooks('printFieldListFrom', $parameters);    // Note that $action and $object may have been modified by hook
-			$sql.=$hookmanager->resPrint;
+            $sql .= " a.datep,"; // Start
+            $sql .= " a.datep2,"; // End
+            $sql .= " a.durationp,"; // deprecated
+            $sql .= " a.datec, a.tms as datem,";
+            $sql .= " a.label, a.code, a.note, a.fk_action as type_id,";
+            $sql .= " a.fk_soc,";
+            $sql .= " a.fk_user_author, a.fk_user_mod,";
+            $sql .= " a.fk_user_action,";
+            $sql .= " a.fk_contact, a.percent as percentage,";
+            $sql .= " a.fk_element, a.elementtype,";
+            $sql .= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,";
+            $sql .= " u.firstname, u.lastname, u.email,";
+            $sql .= " s.nom as socname,";
+            $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label";
+            $sql .= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)";
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; // Link to get author of event for export
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
+
+			$parameters = array('filters' => $filters);
+			$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
+			$sql .= $hookmanager->resPrint;
 
 			// We must filter on assignement table
-			if ($filters['logint']) $sql.=", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
-			$sql.= " WHERE a.fk_action=c.id";
-            $sql.= " AND a.entity IN (".getEntity('agenda').")";
+			if ($filters['logint']) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar";
+			$sql .= " WHERE a.fk_action=c.id";
+            $sql .= " AND a.entity IN (".getEntity('agenda').")";
             foreach ($filters as $key => $value)
             {
-                if ($key == 'notolderthan' && $value != '') $sql.=" AND a.datep >= '".$this->db->idate($now-($value*24*60*60))."'";
-                if ($key == 'year')         $sql.=" AND a.datep BETWEEN '".$this->db->idate(dol_get_first_day($value, 1))."' AND '".$this->db->idate(dol_get_last_day($value, 12))."'";
-                if ($key == 'id')           $sql.=" AND a.id=".(is_numeric($value)?$value:0);
-                if ($key == 'idfrom')       $sql.=" AND a.id >= ".(is_numeric($value)?$value:0);
-                if ($key == 'idto')         $sql.=" AND a.id <= ".(is_numeric($value)?$value:0);
-                if ($key == 'project')      $sql.=" AND a.fk_project=".(is_numeric($value)?$value:0);
-                if ($key == 'actiontype')    $sql.=" AND c.type = '".$this->db->escape($value)."'";
-                if ($key == 'notactiontype') $sql.=" AND c.type <> '".$this->db->escape($value)."'";
+                if ($key == 'notolderthan' && $value != '') $sql .= " AND a.datep >= '".$this->db->idate($now - ($value * 24 * 60 * 60))."'";
+                if ($key == 'year')         $sql .= " AND a.datep BETWEEN '".$this->db->idate(dol_get_first_day($value, 1))."' AND '".$this->db->idate(dol_get_last_day($value, 12))."'";
+                if ($key == 'id')           $sql .= " AND a.id=".(is_numeric($value) ? $value : 0);
+                if ($key == 'idfrom')       $sql .= " AND a.id >= ".(is_numeric($value) ? $value : 0);
+                if ($key == 'idto')         $sql .= " AND a.id <= ".(is_numeric($value) ? $value : 0);
+                if ($key == 'project')      $sql .= " AND a.fk_project=".(is_numeric($value) ? $value : 0);
+                if ($key == 'actiontype')    $sql .= " AND c.type = '".$this->db->escape($value)."'";
+                if ($key == 'notactiontype') $sql .= " AND c.type <> '".$this->db->escape($value)."'";
                 // We must filter on assignement table
-				if ($key == 'logint')       $sql.= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
+				if ($key == 'logint')       $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'";
                 if ($key == 'logina')
                 {
-                    $logina=$value;
-                    $condition='=';
+                    $logina = $value;
+                    $condition = '=';
                     if (preg_match('/^!/', $logina))
                     {
-                        $logina=preg_replace('/^!/', '', $logina);
-                        $condition='<>';
+                        $logina = preg_replace('/^!/', '', $logina);
+                        $condition = '<>';
                     }
-                    $userforfilter=new User($this->db);
-                    $result=$userforfilter->fetch('', $logina);
-                    if ($result > 0) $sql.= " AND a.fk_user_author ".$condition." ".$userforfilter->id;
-                    elseif ($result < 0 || $condition == '=') $sql.= " AND a.fk_user_author = 0";
+                    $userforfilter = new User($this->db);
+                    $result = $userforfilter->fetch('', $logina);
+                    if ($result > 0) $sql .= " AND a.fk_user_author ".$condition." ".$userforfilter->id;
+                    elseif ($result < 0 || $condition == '=') $sql .= " AND a.fk_user_author = 0";
                 }
                 if ($key == 'logint')
                 {
-                    $logint=$value;
-                    $condition='=';
+                    $logint = $value;
+                    $condition = '=';
                     if (preg_match('/^!/', $logint))
                     {
-                        $logint=preg_replace('/^!/', '', $logint);
-                        $condition='<>';
+                        $logint = preg_replace('/^!/', '', $logint);
+                        $condition = '<>';
                     }
-                    $userforfilter=new User($this->db);
-                    $result=$userforfilter->fetch('', $logint);
-                    if ($result > 0) $sql.= " AND ar.fk_element = ".$userforfilter->id;
-                    elseif ($result < 0 || $condition == '=') $sql.= " AND ar.fk_element = 0";
+                    $userforfilter = new User($this->db);
+                    $result = $userforfilter->fetch('', $logint);
+                    if ($result > 0) $sql .= " AND ar.fk_element = ".$userforfilter->id;
+                    elseif ($result < 0 || $condition == '=') $sql .= " AND ar.fk_element = 0";
                 }
             }
 
-            $sql.= " AND a.datep IS NOT NULL";		// To exclude corrupted events and avoid errors in lightning/sunbird import
+            $sql .= " AND a.datep IS NOT NULL"; // To exclude corrupted events and avoid errors in lightning/sunbird import
 
-			$parameters=array('filters' => $filters);
-			$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters);    // Note that $action and $object may have been modified by hook
-			$sql.=$hookmanager->resPrint;
+			$parameters = array('filters' => $filters);
+			$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
+			$sql .= $hookmanager->resPrint;
 
-            $sql.= " ORDER by datep";
+            $sql .= " ORDER by datep";
             //print $sql;exit;
 
             dol_syslog(get_class($this)."::build_exportfile select events", LOG_DEBUG);
-            $resql=$this->db->query($sql);
+            $resql = $this->db->query($sql);
             if ($resql)
             {
                 // Note: Output of sql request is encoded in $conf->file->character_set_client
                 // This assignment in condition is not a bug. It allows walking the results.
 				$diff = 0;
-                while ($obj=$this->db->fetch_object($resql))
+                while ($obj = $this->db->fetch_object($resql))
                 {
-                    $qualified=true;
+                    $qualified = true;
 
                     // 'eid','startdate','duration','enddate','title','summary','category','email','url','desc','author'
-                    $event=array();
-                    $event['uid']='dolibarragenda-'.$this->db->database_name.'-'.$obj->id."@".$_SERVER["SERVER_NAME"];
-                    $event['type']=$type;
-                    $datestart=$this->db->jdate($obj->datep)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
+                    $event = array();
+                    $event['uid'] = 'dolibarragenda-'.$this->db->database_name.'-'.$obj->id."@".$_SERVER["SERVER_NAME"];
+                    $event['type'] = $type;
+                    $datestart = $this->db->jdate($obj->datep) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
 
                     // fix for -> Warning: A non-numeric value encountered
-                    if(is_numeric($this->db->jdate($obj->datep2)))
+                    if (is_numeric($this->db->jdate($obj->datep2)))
                     {
                         $dateend = $this->db->jdate($obj->datep2)
                                  - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
@@ -1731,28 +1731,28 @@ class ActionComm extends CommonObject
                         $dateend = $datestart;
                     }
 
-                    $duration=($datestart && $dateend)?($dateend - $datestart):0;
-                    $event['summary']=$obj->label.($obj->socname?" (".$obj->socname.")":"");
-                    $event['desc']=$obj->note;
-                    $event['startdate']=$datestart;
-                    $event['enddate']=$dateend;		// Not required with type 'journal'
-                    $event['duration']=$duration;	// Not required with type 'journal'
-                    $event['author']=dolGetFirstLastname($obj->firstname, $obj->lastname);
-                    $event['priority']=$obj->priority;
-                    $event['fulldayevent']=$obj->fulldayevent;
-                    $event['location']=$obj->location;
-                    $event['transparency']=(($obj->transparency > 0)?'OPAQUE':'TRANSPARENT');		// OPAQUE (busy) or TRANSPARENT (not busy)
-                    $event['punctual']=$obj->punctual;
-                    $event['category']=$obj->type_label;
-                    $event['email']=$obj->email;
+                    $duration = ($datestart && $dateend) ? ($dateend - $datestart) : 0;
+                    $event['summary'] = $obj->label.($obj->socname ? " (".$obj->socname.")" : "");
+                    $event['desc'] = $obj->note;
+                    $event['startdate'] = $datestart;
+                    $event['enddate'] = $dateend; // Not required with type 'journal'
+                    $event['duration'] = $duration; // Not required with type 'journal'
+                    $event['author'] = dolGetFirstLastname($obj->firstname, $obj->lastname);
+                    $event['priority'] = $obj->priority;
+                    $event['fulldayevent'] = $obj->fulldayevent;
+                    $event['location'] = $obj->location;
+                    $event['transparency'] = (($obj->transparency > 0) ? 'OPAQUE' : 'TRANSPARENT'); // OPAQUE (busy) or TRANSPARENT (not busy)
+                    $event['punctual'] = $obj->punctual;
+                    $event['category'] = $obj->type_label;
+                    $event['email'] = $obj->email;
 					// 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
-                    $url=$urlwithroot.'/comm/action/card.php?id='.$obj->id;
-                    $event['url']=$url;
-                    $event['created']=$this->db->jdate($obj->datec)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
-                    $event['modified']=$this->db->jdate($obj->datem)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600));
+                    $url = $urlwithroot.'/comm/action/card.php?id='.$obj->id;
+                    $event['url'] = $url;
+                    $event['created'] = $this->db->jdate($obj->datec) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
+                    $event['modified'] = $this->db->jdate($obj->datem) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600));
 
                     // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties
                     $this->id = $obj->id;
@@ -1760,25 +1760,25 @@ class ActionComm extends CommonObject
 
                     $assignedUserArray = array();
 
-                    foreach($this->userassigned as $key => $value)
+                    foreach ($this->userassigned as $key => $value)
                     {
                         $assignedUser = new User($this->db);
                         $assignedUser->fetch($value['id']);
 
-                        $assignedUserArray[$key]=$assignedUser;
+                        $assignedUserArray[$key] = $assignedUser;
                     }
 
-                    $event['assignedUsers']=$assignedUserArray;
+                    $event['assignedUsers'] = $assignedUserArray;
 
                     if ($qualified && $datestart)
                     {
-                        $eventarray[]=$event;
+                        $eventarray[] = $event;
                     }
                     $diff++;
                 }
 
-				$parameters=array('filters' => $filters, 'eventarray' => &$eventarray);
-				$reshook=$hookmanager->executeHooks('addMoreEventsExport', $parameters);    // Note that $action and $object may have been modified by hook
+				$parameters = array('filters' => $filters, 'eventarray' => &$eventarray);
+				$reshook = $hookmanager->executeHooks('addMoreEventsExport', $parameters); // Note that $action and $object may have been modified by hook
 				if ($reshook > 0)
 				{
 					$eventarray = $hookmanager->resArray;

+ 17 - 17
htdocs/comm/action/index.php

@@ -757,29 +757,29 @@ if ($showbirthday)
     }
 }
 
-if($conf->global->AGENDA_SHOW_HOLIDAYS)
+if ($conf->global->AGENDA_SHOW_HOLIDAYS)
 {
     $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status";
-    $sql.= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u";
-    $sql.= " WHERE u.rowid = x.fk_user";
-    $sql.= " AND u.statut = '1'";                           // Show only active users  (0 = inactive user, 1 = active user)
-    $sql.= " AND (x.statut = '2' OR x.statut = '3')";       // Show only public leaves (2 = leave wait for approval, 3 = leave approved)
+    $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u";
+    $sql .= " WHERE u.rowid = x.fk_user";
+    $sql .= " AND u.statut = '1'"; // Show only active users  (0 = inactive user, 1 = active user)
+    $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved)
 
-    if($action == 'show_day')
+    if ($action == 'show_day')
     {
         // Request only leaves for the current selected day
-        $sql.= " AND '".$year."-".$month."-".$day."' BETWEEN x.date_debut AND x.date_fin";
+        $sql .= " AND '".$year."-".$month."-".$day."' BETWEEN x.date_debut AND x.date_fin";
     }
-    elseif($action == 'show_week')
+    elseif ($action == 'show_week')
     {
         // TODO: Add filter to reduce database request
     }
-    elseif($action == 'show_month')
+    elseif ($action == 'show_month')
     {
         // TODO: Add filter to reduce database request
     }
 
-    $resql=$db->query($sql);
+    $resql = $db->query($sql);
     if ($resql)
     {
         $num = $db->num_rows($resql);
@@ -803,22 +803,22 @@ if($conf->global->AGENDA_SHOW_HOLIDAYS)
             $event->date_start_in_calendar  = $event->datep;
             $event->date_end_in_calendar    = $event->datef;
 
-            if($obj->status == 3)
+            if ($obj->status == 3)
             {
                 // Show no symbol for leave with state "leave approved"
                 $event->percentage = -1;
             }
-            elseif($obj->status == 2)
+            elseif ($obj->status == 2)
             {
                 // Show TO-DO symbol for leave with state "leave wait for approval"
                 $event->percentage = 0;
             }
 
-            if($obj->halfday == 1)
+            if ($obj->halfday == 1)
             {
                 $event->label = $obj->lastname.' ('.$langs->trans("Morning").')';
             }
-            elseif($obj->halfday == -1)
+            elseif ($obj->halfday == -1)
             {
                 $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')';
             }
@@ -836,7 +836,7 @@ if($conf->global->AGENDA_SHOW_HOLIDAYS)
             {
                 $eventarray[$daykey][] = $event;
 
-                $daykey += 60*60*24;
+                $daykey += 60 * 60 * 24;
             }
 
             while ($daykey <= $event->date_end_in_calendar);
@@ -1835,12 +1835,12 @@ function dol_color_minus($color, $minus, $minusunit = 16)
 function sort_events_by_date($a, $b)
 {
 	// Sort holidays at first
-    if($a->type_code === 'HOLIDAY')
+    if ($a->type_code === 'HOLIDAY')
     {
         return -1;
     }
 
-    if($b->type_code === 'HOLIDAY')
+    if ($b->type_code === 'HOLIDAY')
     {
         return 1;
     }

+ 1 - 1
htdocs/comm/action/list.php

@@ -554,7 +554,7 @@ if ($resql)
 		$actionstatic->type_picto = $obj->type_picto;
 		$actionstatic->label = $obj->label;
 		$actionstatic->location = $obj->location;
-		$actionstatic->note = dol_htmlentitiesbr($obj->note);			// deprecated
+		$actionstatic->note = dol_htmlentitiesbr($obj->note); // deprecated
 		$actionstatic->note_public = dol_htmlentitiesbr($obj->note);
 
 		$actionstatic->fetchResources();

+ 1 - 1
htdocs/comm/propal/class/propal.class.php

@@ -810,7 +810,7 @@ class Propal extends CommonObject
 
 			if (is_array($array_options) && count($array_options) > 0) {
 				// We replace values in this->line->array_options only for entries defined into $array_options
-				foreach($array_options as $key => $value) {
+				foreach ($array_options as $key => $value) {
 					$this->line->array_options[$key] = $array_options[$key];
 				}
 			}

+ 285 - 285
htdocs/commande/class/commande.class.php

@@ -164,7 +164,7 @@ class Commande extends CommonOrder
 	 */
 	public $availability;
 
-	public $demand_reason_id;   // Source reason. Why we receive order (after a phone campaign, ...)
+	public $demand_reason_id; // Source reason. Why we receive order (after a phone campaign, ...)
 	public $demand_reason_code;
 	/**
      * @var int Date of order
@@ -343,11 +343,11 @@ class Commande extends CommonOrder
 	 */
 	public function valid($user, $idwarehouse = 0, $notrigger = 0)
 	{
-		global $conf,$langs;
+		global $conf, $langs;
 
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 
-		$error=0;
+		$error = 0;
 
 		// Protection
 		if ($this->statut == self::STATUS_VALIDATED)
@@ -388,31 +388,31 @@ class Commande extends CommonOrder
 
 		// Validate
 		$sql = "UPDATE ".MAIN_DB_PREFIX."commande";
-		$sql.= " SET ref = '".$this->db->escape($num)."',";
-		$sql.= " fk_statut = ".self::STATUS_VALIDATED.",";
-		$sql.= " date_valid='".$this->db->idate($now)."',";
-		$sql.= " fk_user_valid = ".$user->id;
-		$sql.= " WHERE rowid = ".$this->id;
+		$sql .= " SET ref = '".$this->db->escape($num)."',";
+		$sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
+		$sql .= " date_valid='".$this->db->idate($now)."',";
+		$sql .= " fk_user_valid = ".$user->id;
+		$sql .= " WHERE rowid = ".$this->id;
 
 		dol_syslog(get_class($this)."::valid()", LOG_DEBUG);
-		$resql=$this->db->query($sql);
-		if (! $resql)
+		$resql = $this->db->query($sql);
+		if (!$resql)
 		{
 			dol_print_error($this->db);
-			$this->error=$this->db->lasterror();
+			$this->error = $this->db->lasterror();
 			$error++;
 		}
 
-		if (! $error)
+		if (!$error)
 		{
 			// If stock is incremented on validate order, we must increment it
-			if ($result >= 0 && ! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
+			if ($result >= 0 && !empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER == 1)
 			{
 				require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
 				$langs->load("agenda");
 
 				// Loop on each line
-				$cpt=count($this->lines);
+				$cpt = count($this->lines);
 				for ($i = 0; $i < $cpt; $i++)
 				{
 					if ($this->lines[$i]->fk_product > 0)
@@ -448,17 +448,17 @@ class Commande extends CommonOrder
 			if (preg_match('/^[\(]?PROV/i', $this->ref))
 			{
 				// Now we rename also files into index
-				$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref)+1).")), filepath = 'commande/".$this->db->escape($this->newref)."'";
-				$sql.= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+				$sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'commande/".$this->db->escape($this->newref)."'";
+				$sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
 				$resql = $this->db->query($sql);
-				if (! $resql) { $error++; $this->error = $this->db->lasterror(); }
+				if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
 
 				// We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
 				$oldref = dol_sanitizeFileName($this->ref);
 				$newref = dol_sanitizeFileName($num);
 				$dirsource = $conf->commande->multidir_output[$this->entity].'/'.$oldref;
 				$dirdest = $conf->commande->multidir_output[$this->entity].'/'.$newref;
-				if (! $error && file_exists($dirsource))
+				if (!$error && file_exists($dirsource))
 				{
 					dol_syslog(get_class($this)."::valid() rename dir ".$dirsource." into ".$dirdest);
 
@@ -466,13 +466,13 @@ class Commande extends CommonOrder
 					{
 						dol_syslog("Rename ok");
 						// Rename docs starting with $oldref with $newref
-						$listoffiles=dol_dir_list($conf->commande->multidir_output[$this->entity].'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
-						foreach($listoffiles as $fileentry)
+						$listoffiles = dol_dir_list($conf->commande->multidir_output[$this->entity].'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
+						foreach ($listoffiles as $fileentry)
 						{
-							$dirsource=$fileentry['name'];
-							$dirdest=preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
-							$dirsource=$fileentry['path'].'/'.$dirsource;
-							$dirdest=$fileentry['path'].'/'.$dirdest;
+							$dirsource = $fileentry['name'];
+							$dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
+							$dirsource = $fileentry['path'].'/'.$dirsource;
+							$dirdest = $fileentry['path'].'/'.$dirdest;
 							@rename($dirsource, $dirdest);
 						}
 					}
@@ -661,34 +661,34 @@ class Commande extends CommonOrder
 	{
 		global $conf;
 
-		$error=0;
+		$error = 0;
 
-		if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer))
-			|| (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate)))
+		if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->creer))
+			|| (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate)))
 		{
 			$this->db->begin();
 
-			$now=dol_now();
+			$now = dol_now();
 
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
-			$sql.= ' SET fk_statut = '.self::STATUS_CLOSED.',';
-			$sql.= ' fk_user_cloture = '.$user->id.',';
-			$sql.= " date_cloture = '".$this->db->idate($now)."'";
-			$sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
+			$sql .= ' SET fk_statut = '.self::STATUS_CLOSED.',';
+			$sql .= ' fk_user_cloture = '.$user->id.',';
+			$sql .= " date_cloture = '".$this->db->idate($now)."'";
+			$sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
 
 			if ($this->db->query($sql))
 			{
-				if (! $notrigger)
+				if (!$notrigger)
 				{
 					// Call trigger
-					$result=$this->call_trigger('ORDER_CLOSE', $user);
+					$result = $this->call_trigger('ORDER_CLOSE', $user);
 					if ($result < 0) $error++;
 					// End call triggers
 				}
 
-				if (! $error)
+				if (!$error)
 				{
-					$this->statut=self::STATUS_CLOSED;
+					$this->statut = self::STATUS_CLOSED;
 
 					$this->db->commit();
 					return 1;
@@ -835,88 +835,88 @@ class Commande extends CommonOrder
 		}
 
 		$soc = new Societe($this->db);
-		$result=$soc->fetch($this->socid);
+		$result = $soc->fetch($this->socid);
 		if ($result < 0)
 		{
-			$this->error="Failed to fetch company";
+			$this->error = "Failed to fetch company";
 			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
 			return -2;
 		}
-		if (! empty($conf->global->COMMANDE_REQUIRE_SOURCE) && $this->source < 0)
+		if (!empty($conf->global->COMMANDE_REQUIRE_SOURCE) && $this->source < 0)
 		{
-			$this->error=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Source"));
+			$this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Source"));
 			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
 			return -1;
 		}
 
-		$now=dol_now();
+		$now = dol_now();
 
 		$this->db->begin();
 
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."commande (";
-		$sql.= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client, ref_int";
-		$sql.= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
-		$sql.= ", fk_shipping_method";
-		$sql.= ", fk_warehouse";
-		$sql.= ", remise_absolue, remise_percent";
-		$sql.= ", fk_incoterms, location_incoterms";
-		$sql.= ", entity, module_source, pos_source";
-		$sql.= ", fk_multicurrency";
-		$sql.= ", multicurrency_code";
-		$sql.= ", multicurrency_tx";
-		$sql.= ")";
-		$sql.= " VALUES ('(PROV)', ".$this->socid.", '".$this->db->idate($now)."', ".$user->id;
-		$sql.= ", ".($this->fk_project>0?$this->fk_project:"null");
-		$sql.= ", '".$this->db->idate($date)."'";
-		$sql.= ", ".($this->source>=0 && $this->source != '' ?$this->db->escape($this->source):'null');
-		$sql.= ", '".$this->db->escape($this->note_private)."'";
-		$sql.= ", '".$this->db->escape($this->note_public)."'";
-		$sql.= ", ".($this->ref_ext?"'".$this->db->escape($this->ref_ext)."'":"null");
-		$sql.= ", ".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null");
-		$sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
-		$sql.= ", '".$this->db->escape($this->modelpdf)."'";
-		$sql.= ", ".($this->cond_reglement_id>0?$this->cond_reglement_id:"null");
-		$sql.= ", ".($this->mode_reglement_id>0?$this->mode_reglement_id:"null");
-		$sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL');
-		$sql.= ", ".($this->availability_id>0?$this->availability_id:"null");
-		$sql.= ", ".($this->demand_reason_id>0?$this->demand_reason_id:"null");
-		$sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null");
-		$sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:'NULL');
-		$sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL');
-		$sql.= ", ".($this->warehouse_id>0?$this->warehouse_id:'NULL');
-		$sql.= ", ".($this->remise_absolue>0?$this->db->escape($this->remise_absolue):'NULL');
-		$sql.= ", ".($this->remise_percent>0?$this->db->escape($this->remise_percent):0);
-		$sql.= ", ".(int) $this->fk_incoterms;
-		$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
-		$sql.= ", ".setEntity($this);
-        $sql.= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
-		$sql.= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null");
-		$sql.= ", ".(int) $this->fk_multicurrency;
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
-		$sql.= ", ".(double) $this->multicurrency_tx;
-		$sql.= ")";
+		$sql .= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_ext, ref_client, ref_int";
+		$sql .= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address";
+		$sql .= ", fk_shipping_method";
+		$sql .= ", fk_warehouse";
+		$sql .= ", remise_absolue, remise_percent";
+		$sql .= ", fk_incoterms, location_incoterms";
+		$sql .= ", entity, module_source, pos_source";
+		$sql .= ", fk_multicurrency";
+		$sql .= ", multicurrency_code";
+		$sql .= ", multicurrency_tx";
+		$sql .= ")";
+		$sql .= " VALUES ('(PROV)', ".$this->socid.", '".$this->db->idate($now)."', ".$user->id;
+		$sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
+		$sql .= ", '".$this->db->idate($date)."'";
+		$sql .= ", ".($this->source >= 0 && $this->source != '' ? $this->db->escape($this->source) : 'null');
+		$sql .= ", '".$this->db->escape($this->note_private)."'";
+		$sql .= ", '".$this->db->escape($this->note_public)."'";
+		$sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
+		$sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
+		$sql .= ", ".($this->ref_int ? "'".$this->db->escape($this->ref_int)."'" : "null");
+		$sql .= ", '".$this->db->escape($this->modelpdf)."'";
+		$sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : "null");
+		$sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : "null");
+		$sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
+		$sql .= ", ".($this->availability_id > 0 ? $this->availability_id : "null");
+		$sql .= ", ".($this->demand_reason_id > 0 ? $this->demand_reason_id : "null");
+		$sql .= ", ".($this->date_livraison ? "'".$this->db->idate($this->date_livraison)."'" : "null");
+		$sql .= ", ".($this->fk_delivery_address > 0 ? $this->fk_delivery_address : 'NULL');
+		$sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
+		$sql .= ", ".($this->warehouse_id > 0 ? $this->warehouse_id : 'NULL');
+		$sql .= ", ".($this->remise_absolue > 0 ? $this->db->escape($this->remise_absolue) : 'NULL');
+		$sql .= ", ".($this->remise_percent > 0 ? $this->db->escape($this->remise_percent) : 0);
+		$sql .= ", ".(int) $this->fk_incoterms;
+		$sql .= ", '".$this->db->escape($this->location_incoterms)."'";
+		$sql .= ", ".setEntity($this);
+        $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
+		$sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null");
+		$sql .= ", ".(int) $this->fk_multicurrency;
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
+		$sql .= ", ".(double) $this->multicurrency_tx;
+		$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.'commande');
 
 			if ($this->id)
 			{
-				$fk_parent_line=0;
-				$num=count($this->lines);
+				$fk_parent_line = 0;
+				$num = count($this->lines);
 
 				/*
 				 *  Insert products details into db
 				 */
-				for ($i=0;$i<$num;$i++)
+				for ($i = 0; $i < $num; $i++)
 				{
 					$line = $this->lines[$i];
 
 					// Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
 					//if (! is_object($line)) $line=json_decode(json_encode($line), false);  // convert recursively array into object.
-					if (! is_object($line)) $line = (object) $line;
+					if (!is_object($line)) $line = (object) $line;
 
 					// Reset fk_parent_line for no child products and special product
 					if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
@@ -1499,69 +1499,69 @@ class Commande extends CommonOrder
 			}
 
 			// Insert line
-			$this->line=new OrderLine($this->db);
+			$this->line = new OrderLine($this->db);
 
 			$this->line->context = $this->context;
 
-			$this->line->fk_commande=$this->id;
-			$this->line->label=$label;
-			$this->line->desc=$desc;
-			$this->line->qty=$qty;
-
-			$this->line->vat_src_code=$vat_src_code;
-			$this->line->tva_tx=$txtva;
-			$this->line->localtax1_tx=($total_localtax1?$localtaxes_type[1]:0);
-			$this->line->localtax2_tx=($total_localtax2?$localtaxes_type[3]:0);
-			$this->line->localtax1_type=$localtaxes_type[0];
-			$this->line->localtax2_type=$localtaxes_type[2];
-			$this->line->fk_product=$fk_product;
-			$this->line->product_type=$product_type;
-			$this->line->fk_remise_except=$fk_remise_except;
-			$this->line->remise_percent=$remise_percent;
-			$this->line->subprice=$pu_ht;
-			$this->line->rang=$ranktouse;
-			$this->line->info_bits=$info_bits;
-			$this->line->total_ht=$total_ht;
-			$this->line->total_tva=$total_tva;
-			$this->line->total_localtax1=$total_localtax1;
-			$this->line->total_localtax2=$total_localtax2;
-			$this->line->total_ttc=$total_ttc;
-			$this->line->special_code=$special_code;
-			$this->line->origin=$origin;
-			$this->line->origin_id=$origin_id;
-			$this->line->fk_parent_line=$fk_parent_line;
-			$this->line->fk_unit=$fk_unit;
-
-			$this->line->date_start=$date_start;
-			$this->line->date_end=$date_end;
+			$this->line->fk_commande = $this->id;
+			$this->line->label = $label;
+			$this->line->desc = $desc;
+			$this->line->qty = $qty;
+
+			$this->line->vat_src_code = $vat_src_code;
+			$this->line->tva_tx = $txtva;
+			$this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
+			$this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
+			$this->line->localtax1_type = $localtaxes_type[0];
+			$this->line->localtax2_type = $localtaxes_type[2];
+			$this->line->fk_product = $fk_product;
+			$this->line->product_type = $product_type;
+			$this->line->fk_remise_except = $fk_remise_except;
+			$this->line->remise_percent = $remise_percent;
+			$this->line->subprice = $pu_ht;
+			$this->line->rang = $ranktouse;
+			$this->line->info_bits = $info_bits;
+			$this->line->total_ht = $total_ht;
+			$this->line->total_tva = $total_tva;
+			$this->line->total_localtax1 = $total_localtax1;
+			$this->line->total_localtax2 = $total_localtax2;
+			$this->line->total_ttc = $total_ttc;
+			$this->line->special_code = $special_code;
+			$this->line->origin = $origin;
+			$this->line->origin_id = $origin_id;
+			$this->line->fk_parent_line = $fk_parent_line;
+			$this->line->fk_unit = $fk_unit;
+
+			$this->line->date_start = $date_start;
+			$this->line->date_end = $date_end;
 
 			$this->line->fk_fournprice = $fk_fournprice;
 			$this->line->pa_ht = $pa_ht;
 
 			// Multicurrency
-			$this->line->fk_multicurrency			= $this->fk_multicurrency;
-			$this->line->multicurrency_code			= $this->multicurrency_code;
+			$this->line->fk_multicurrency = $this->fk_multicurrency;
+			$this->line->multicurrency_code = $this->multicurrency_code;
 			$this->line->multicurrency_subprice		= $pu_ht_devise;
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
 			$this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
 			$this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
 
 			// TODO Ne plus utiliser
-			$this->line->price=$price;
-			$this->line->remise=$remise;
+			$this->line->price = $price;
+			$this->line->remise = $remise;
 
-			if (is_array($array_options) && count($array_options)>0) {
-				$this->line->array_options=$array_options;
+			if (is_array($array_options) && count($array_options) > 0) {
+				$this->line->array_options = $array_options;
 			}
 
-			$result=$this->line->insert($user);
+			$result = $this->line->insert($user);
 			if ($result > 0)
 			{
 				// Reorder if child line
-				if (! empty($fk_parent_line)) $this->line_order(true, 'DESC');
+				if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
 
 				// Mise a jour informations denormalisees au niveau de la commande meme
-				$result=$this->update_price(1, 'auto', 0, $mysoc);	// This method is designed to add line from user input so total calculation must be done using 'auto' mode.
+				$result = $this->update_price(1, 'auto', 0, $mysoc); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
 				if ($result > 0)
 				{
 					$this->db->commit();
@@ -1695,35 +1695,35 @@ class Commande extends CommonOrder
 		if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
 
 		$sql = 'SELECT c.rowid, c.entity, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_statut';
-		$sql.= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
-		$sql.= ', c.fk_account';
-		$sql.= ', c.date_commande, c.date_valid, c.tms';
-		$sql.= ', c.date_livraison';
-		$sql.= ', c.fk_shipping_method';
-		$sql.= ', c.fk_warehouse';
-		$sql.= ', c.fk_projet as fk_project, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed';
-		$sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.last_main_doc, c.fk_delivery_address, c.extraparams';
-		$sql.= ', c.fk_incoterms, c.location_incoterms';
-		$sql.= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
-		$sql.= ", c.module_source, c.pos_source";
-        $sql.= ", i.libelle as label_incoterms";
-		$sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
-		$sql.= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
-		$sql.= ', ca.code as availability_code, ca.label as availability_label';
-		$sql.= ', dr.code as demand_reason_code';
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c';
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid';
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id';
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = dr.rowid';
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
-
-		if ($id) $sql.= " WHERE c.rowid=".$id;
-		else $sql.= " WHERE c.entity IN (".getEntity('commande').")"; // Dont't use entity if you use rowid
-
-		if ($ref)     $sql.= " AND c.ref='".$this->db->escape($ref)."'";
-		if ($ref_ext) $sql.= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
-		if ($ref_int) $sql.= " AND c.ref_int='".$this->db->escape($ref_int)."'";
+		$sql .= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason';
+		$sql .= ', c.fk_account';
+		$sql .= ', c.date_commande, c.date_valid, c.tms';
+		$sql .= ', c.date_livraison';
+		$sql .= ', c.fk_shipping_method';
+		$sql .= ', c.fk_warehouse';
+		$sql .= ', c.fk_projet as fk_project, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed';
+		$sql .= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.last_main_doc, c.fk_delivery_address, c.extraparams';
+		$sql .= ', c.fk_incoterms, c.location_incoterms';
+		$sql .= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc";
+		$sql .= ", c.module_source, c.pos_source";
+        $sql .= ", i.libelle as label_incoterms";
+		$sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
+		$sql .= ', cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle, cr.libelle_facture as cond_reglement_libelle_doc';
+		$sql .= ', ca.code as availability_code, ca.label as availability_label';
+		$sql .= ', dr.code as demand_reason_code';
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c';
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid';
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id';
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid';
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = dr.rowid';
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid';
+
+		if ($id) $sql .= " WHERE c.rowid=".$id;
+		else $sql .= " WHERE c.entity IN (".getEntity('commande').")"; // Dont't use entity if you use rowid
+
+		if ($ref)     $sql .= " AND c.ref='".$this->db->escape($ref)."'";
+		if ($ref_ext) $sql .= " AND c.ref_ext='".$this->db->escape($ref_ext)."'";
+		if ($ref_int) $sql .= " AND c.ref_int='".$this->db->escape($ref_int)."'";
 
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
 		$result = $this->db->query($sql);
@@ -2017,7 +2017,7 @@ class Commande extends CommonOrder
 				$line->fetch_optionals();
 
 				// multilangs
-        		if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($objp->fk_product) && ! empty($loadalsotranslation)) {
+        		if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
             		$line = new Product($this->db);
             		$line->fetch($objp->fk_product);
             		$line->getMultiLangs();
@@ -2860,44 +2860,44 @@ class Commande extends CommonOrder
 		$this->db->begin();
 
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 1';
-		$sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
+		$sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
 
 		dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG);
 		if ($this->db->query($sql))
 		{
-			if (! $error)
+			if (!$error)
 			{
-				$this->oldcopy= clone $this;
-				$this->billed=1;
+				$this->oldcopy = clone $this;
+				$this->billed = 1;
 			}
 
-			if (! $notrigger && empty($error))
+			if (!$notrigger && empty($error))
 			{
 				// Call trigger
-				$result=$this->call_trigger('ORDER_CLASSIFY_BILLED', $user);
+				$result = $this->call_trigger('ORDER_CLASSIFY_BILLED', $user);
 				if ($result < 0) $error++;
 				// End call triggers
 			}
 
-			if (! $error)
+			if (!$error)
 			{
 				$this->db->commit();
 				return 1;
 			}
 			else
 			{
-				foreach($this->errors as $errmsg)
+				foreach ($this->errors as $errmsg)
 				{
 					dol_syslog(get_class($this)."::classifyBilled ".$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
 		{
-			$this->error=$this->db->error();
+			$this->error = $this->db->error();
 			$this->db->rollback();
 			return -1;
 		}
@@ -3100,18 +3100,18 @@ class Commande extends CommonOrder
 			$this->line->context = $this->context;
 
 			// Reorder if fk_parent_line change
-			if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
+			if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
 			{
 				$rangmax = $this->line_max($fk_parent_line);
 				$this->line->rang = $rangmax + 1;
 			}
 
-			$this->line->id=$rowid;
-			$this->line->label=$label;
-			$this->line->desc=$desc;
-			$this->line->qty=$qty;
+			$this->line->id = $rowid;
+			$this->line->label = $label;
+			$this->line->desc = $desc;
+			$this->line->qty = $qty;
 
-			$this->line->vat_src_code	= $vat_src_code;
+			$this->line->vat_src_code = $vat_src_code;
 			$this->line->tva_tx         = $txtva;
 			$this->line->localtax1_tx   = $txlocaltax1;
 			$this->line->localtax2_tx   = $txlocaltax2;
@@ -3148,7 +3148,7 @@ class Commande extends CommonOrder
 
 			if (is_array($array_options) && count($array_options) > 0) {
 				// We replace values in this->line->array_options only for entries defined into $array_options
-				foreach($array_options as $key => $value) {
+				foreach ($array_options as $key => $value) {
 					$this->line->array_options[$key] = $array_options[$key];
 				}
 			}
@@ -3347,30 +3347,30 @@ class Commande extends CommonOrder
 			}
 		}
 
-		if (! $error)
+		if (!$error)
 		{
 			// Delete object
 			$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande WHERE rowid = ".$this->id;
-			if (! $this->db->query($sql) )
+			if (!$this->db->query($sql))
 			{
 				$error++;
-				$this->errors[]=$this->db->lasterror();
+				$this->errors[] = $this->db->lasterror();
 			}
 		}
 
-		if (! $error)
+		if (!$error)
 		{
 			// Remove directory with files
 			$comref = dol_sanitizeFileName($this->ref);
 			if ($conf->commande->multidir_output[$this->entity] && !empty($this->ref))
 			{
-				$dir = $conf->commande->multidir_output[$this->entity] . "/" . $comref ;
-				$file = $conf->commande->multidir_output[$this->entity] . "/" . $comref . "/" . $comref . ".pdf";
+				$dir = $conf->commande->multidir_output[$this->entity]."/".$comref;
+				$file = $conf->commande->multidir_output[$this->entity]."/".$comref."/".$comref.".pdf";
 				if (file_exists($file))	// We must delete all files before deleting directory
 				{
 					dol_delete_preview($this);
 
-					if (! dol_delete_file($file, 0, 0, 0, $this)) // For triggers
+					if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
 					{
 						$this->db->rollback();
 						return 0;
@@ -3420,34 +3420,34 @@ class Commande extends CommonOrder
 		$clause = " WHERE";
 
 		$sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.date_livraison as delivery_date, c.fk_statut, c.total_ht";
-		$sql.= " FROM ".MAIN_DB_PREFIX."commande as c";
+		$sql .= " FROM ".MAIN_DB_PREFIX."commande as c";
 		if (!$user->rights->societe->client->voir && !$user->socid)
 		{
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
-			$sql.= " WHERE sc.fk_user = " .$user->id;
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
+			$sql .= " WHERE sc.fk_user = ".$user->id;
 			$clause = " AND";
 		}
-		$sql.= $clause." c.entity IN (".getEntity('commande').")";
+		$sql .= $clause." c.entity IN (".getEntity('commande').")";
 		//$sql.= " AND c.fk_statut IN (1,2,3) AND c.facture = 0";
-		$sql.= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_SHIPMENTONPROCESS.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))";    // If status is 2 and facture=1, it must be selected
-		if ($user->socid) $sql.=" AND c.fk_soc = ".$user->socid;
+		$sql .= " AND ((c.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_SHIPMENTONPROCESS.")) OR (c.fk_statut = ".self::STATUS_CLOSED." AND c.facture = 0))"; // If status is 2 and facture=1, it must be selected
+		if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid;
 
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
 			$response = new WorkboardResponse();
-			$response->warning_delay=$conf->commande->client->warning_delay/60/60/24;
-			$response->label=$langs->trans("OrdersToProcess");
+			$response->warning_delay = $conf->commande->client->warning_delay / 60 / 60 / 24;
+			$response->label = $langs->trans("OrdersToProcess");
 			$response->labelShort = $langs->trans("Opened");
-			$response->url=DOL_URL_ROOT.'/commande/list.php?viewstatut=-3&mainmenu=commercial&leftmenu=orders';
-			$response->img=img_object('', "order");
+			$response->url = DOL_URL_ROOT.'/commande/list.php?viewstatut=-3&mainmenu=commercial&leftmenu=orders';
+			$response->img = img_object('', "order");
 
 			$generic_commande = new Commande($this->db);
 
-			while ($obj=$this->db->fetch_object($resql))
+			while ($obj = $this->db->fetch_object($resql))
 			{
 				$response->nbtodo++;
-				$response->total+= $obj->total_ht;
+				$response->total += $obj->total_ht;
 
 				$generic_commande->statut = $obj->fk_statut;
 				$generic_commande->date_commande = $this->db->jdate($obj->date_commande);
@@ -3509,47 +3509,47 @@ class Commande extends CommonOrder
 		global $langs, $conf;
 
 		$billedtext = '';
-		if (empty($donotshowbilled)) $billedtext .= ($billed?' - '.$langs->trans("Billed"):'');
+		if (empty($donotshowbilled)) $billedtext .= ($billed ? ' - '.$langs->trans("Billed") : '');
 
-		if ($status==self::STATUS_CANCELED){
+		if ($status == self::STATUS_CANCELED) {
 		    $labelStatus = $langs->trans('StatusOrderCanceled');
 		    $labelStatusShort = $langs->trans('StatusOrderCanceledShort');
-		    $statusType='status5';
+		    $statusType = 'status5';
 		}
-		elseif ($status==self::STATUS_DRAFT){
+		elseif ($status == self::STATUS_DRAFT) {
 		    $labelStatus = $langs->trans('StatusOrderDraft');
 		    $labelStatusShort = $langs->trans('StatusOrderDraftShort');
-		    $statusType='status0';
+		    $statusType = 'status0';
 		}
-		elseif ($status==self::STATUS_VALIDATED){
+		elseif ($status == self::STATUS_VALIDATED) {
 		    $labelStatus = $langs->trans('StatusOrderValidated').$billedtext;
 		    $labelStatusShort = $langs->trans('StatusOrderValidatedShort').$billedtext;
-		    $statusType='status1';
+		    $statusType = 'status1';
 		}
-		elseif ($status==self::STATUS_SHIPMENTONPROCESS){
+		elseif ($status == self::STATUS_SHIPMENTONPROCESS) {
 		    $labelStatus = $langs->trans('StatusOrderSentShort').$billedtext;
 		    $labelStatusShort = $langs->trans('StatusOrderSentShort').$billedtext;
-		    $statusType='status3';
+		    $statusType = 'status3';
 		}
-		elseif ($status==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))){
+		elseif ($status == self::STATUS_CLOSED && (!$billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
 		    $labelStatus = $langs->trans('StatusOrderToBill');
 		    $labelStatusShort = $langs->trans('StatusOrderToBillShort');
-		    $statusType='status4';
+		    $statusType = 'status4';
 		}
-		elseif ($status==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))){
+		elseif ($status == self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
 		    $labelStatus = $langs->trans('StatusOrderProcessed').$billedtext;
 		    $labelStatusShort = $langs->trans('StatusOrderProcessed').$billedtext;
-		    $statusType='status6';
+		    $statusType = 'status6';
 		}
-		elseif ($status==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))){
+		elseif ($status == self::STATUS_CLOSED && (!empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) {
 		    $labelStatus = $langs->trans('StatusOrderDelivered');
 		    $labelStatusShort = $langs->trans('StatusOrderDelivered');
-		    $statusType='status6';
+		    $statusType = 'status6';
 		}
-		else{
+		else {
 		    $labelStatus = $langs->trans('Unknown');
 		    $labelStatusShort = '';
-		    $statusType='';
+		    $statusType = '';
 		    $mode = 0;
 		}
 
@@ -3818,26 +3818,26 @@ class Commande extends CommonOrder
         // phpcs:enable
 		global $user;
 
-		$this->nb=array();
+		$this->nb = array();
 		$clause = "WHERE";
 
 		$sql = "SELECT count(co.rowid) as nb";
-		$sql.= " FROM ".MAIN_DB_PREFIX."commande as co";
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
+		$sql .= " FROM ".MAIN_DB_PREFIX."commande as co";
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
 		if (!$user->rights->societe->client->voir && !$user->socid)
 		{
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
-			$sql.= " WHERE sc.fk_user = " .$user->id;
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
+			$sql .= " WHERE sc.fk_user = ".$user->id;
 			$clause = "AND";
 		}
-		$sql.= " ".$clause." co.entity IN (".getEntity('commande').")";
+		$sql .= " ".$clause." co.entity IN (".getEntity('commande').")";
 
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
-			while ($obj=$this->db->fetch_object($resql))
+			while ($obj = $this->db->fetch_object($resql))
 			{
-				$this->nb["orders"]=$obj->nb;
+				$this->nb["orders"] = $obj->nb;
 			}
 			$this->db->free($resql);
 			return 1;
@@ -3873,16 +3873,16 @@ class Commande extends CommonOrder
 	 */
 	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
 	{
-		global $conf,$langs;
+		global $conf, $langs;
 
 		$langs->load("orders");
 
-		if (! dol_strlen($modele)) {
+		if (!dol_strlen($modele)) {
 			$modele = 'einstein';
 
 			if ($this->modelpdf) {
 				$modele = $this->modelpdf;
-			} elseif (! empty($conf->global->COMMANDE_ADDON_PDF)) {
+			} elseif (!empty($conf->global->COMMANDE_ADDON_PDF)) {
 				$modele = $conf->global->COMMANDE_ADDON_PDF;
 			}
 		}
@@ -4113,13 +4113,13 @@ class OrderLine extends CommonOrderLine
 	{
 		global $conf, $langs;
 
-		$error=0;
+		$error = 0;
 
         // check if order line is not in a shipment line before deleting
         $sqlCheckShipmentLine  = "SELECT";
         $sqlCheckShipmentLine .= " ed.rowid";
-        $sqlCheckShipmentLine .= " FROM " . MAIN_DB_PREFIX . "expeditiondet ed";
-        $sqlCheckShipmentLine .= " WHERE ed.fk_origin_line = " . $this->rowid;
+        $sqlCheckShipmentLine .= " FROM ".MAIN_DB_PREFIX."expeditiondet ed";
+        $sqlCheckShipmentLine .= " WHERE ed.fk_origin_line = ".$this->rowid;
 
         $resqlCheckShipmentLine = $this->db->query($sqlCheckShipmentLine);
         if (!$resqlCheckShipmentLine) {
@@ -4132,13 +4132,13 @@ class OrderLine extends CommonOrderLine
             if ($num > 0) {
                 $error++;
                 $objCheckShipmentLine = $this->db->fetch_object($resqlCheckShipmentLine);
-                $this->error = $langs->trans('ErrorRecordAlreadyExists') . ' : ' . $langs->trans('ShipmentLine') . ' ' . $objCheckShipmentLine->rowid;
+                $this->error = $langs->trans('ErrorRecordAlreadyExists').' : '.$langs->trans('ShipmentLine').' '.$objCheckShipmentLine->rowid;
                 $this->errors[] = $this->error;
             }
             $this->db->free($resqlCheckShipmentLine);
         }
         if ($error) {
-            dol_syslog(__METHOD__ . 'Error ; ' . $this->error, LOG_ERR);
+            dol_syslog(__METHOD__.'Error ; '.$this->error, LOG_ERR);
             return -1;
         }
 
@@ -4147,14 +4147,14 @@ class OrderLine extends CommonOrderLine
 		$sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE rowid=".$this->rowid;
 
 		dol_syslog("OrderLine::delete", LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
 			// Remove extrafields
-			if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
+			if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
 			{
-				$this->id=$this->rowid;
-				$result=$this->deleteExtraFields();
+				$this->id = $this->rowid;
+				$result = $this->deleteExtraFields();
 				if ($result < 0)
 				{
 					$error++;
@@ -4243,73 +4243,73 @@ class OrderLine extends CommonOrderLine
 
 		// Insertion dans base de la ligne
 		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'commandedet';
-		$sql.= ' (fk_commande, fk_parent_line, label, description, qty, ';
-		$sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
-		$sql.= ' fk_product, product_type, remise_percent, subprice, price, remise, fk_remise_except,';
-		$sql.= ' special_code, rang, fk_product_fournisseur_price, buy_price_ht,';
-		$sql.= ' info_bits, total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, date_start, date_end,';
-		$sql.= ' fk_unit';
-		$sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
-		$sql.= ')';
-		$sql.= " VALUES (".$this->fk_commande.",";
-		$sql.= " ".($this->fk_parent_line>0?"'".$this->db->escape($this->fk_parent_line)."'":"null").",";
-		$sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
-		$sql.= " '".$this->db->escape($this->desc)."',";
-		$sql.= " '".price2num($this->qty)."',";
-		$sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->db->escape($this->vat_src_code)."'").",";
-		$sql.= " '".price2num($this->tva_tx)."',";
-		$sql.= " '".price2num($this->localtax1_tx)."',";
-		$sql.= " '".price2num($this->localtax2_tx)."',";
-		$sql.= " '".$this->db->escape($this->localtax1_type)."',";
-		$sql.= " '".$this->db->escape($this->localtax2_type)."',";
-		$sql.= ' '.(! empty($this->fk_product)?$this->fk_product:"null").',';
-		$sql.= " '".$this->db->escape($this->product_type)."',";
-		$sql.= " '".price2num($this->remise_percent)."',";
-		$sql.= " ".(price2num($this->subprice)!==''?price2num($this->subprice):"null").",";
-		$sql.= " ".($this->price!=''?"'".price2num($this->price)."'":"null").",";
-		$sql.= " '".price2num($this->remise)."',";
-		$sql.= ' '.(! empty($this->fk_remise_except)?$this->fk_remise_except:"null").',';
-		$sql.= ' '.$this->special_code.',';
-		$sql.= ' '.$this->rang.',';
-		$sql.= ' '.(! empty($this->fk_fournprice)?$this->fk_fournprice:"null").',';
-		$sql.= ' '.price2num($this->pa_ht).',';
-		$sql.= " '".$this->db->escape($this->info_bits)."',";
-		$sql.= " ".price2num($this->total_ht).",";
-		$sql.= " ".price2num($this->total_tva).",";
-		$sql.= " ".price2num($this->total_localtax1).",";
-		$sql.= " ".price2num($this->total_localtax2).",";
-		$sql.= " ".price2num($this->total_ttc).",";
-		$sql.= " ".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null").',';
-		$sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null").',';
-		$sql.= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit);
-		$sql.= ", ".(! empty($this->fk_multicurrency) ? $this->fk_multicurrency : 'NULL');
-		$sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
-		$sql.= ", ".$this->multicurrency_subprice;
-		$sql.= ", ".$this->multicurrency_total_ht;
-		$sql.= ", ".$this->multicurrency_total_tva;
-		$sql.= ", ".$this->multicurrency_total_ttc;
-		$sql.= ')';
+		$sql .= ' (fk_commande, fk_parent_line, label, description, qty, ';
+		$sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
+		$sql .= ' fk_product, product_type, remise_percent, subprice, price, remise, fk_remise_except,';
+		$sql .= ' special_code, rang, fk_product_fournisseur_price, buy_price_ht,';
+		$sql .= ' info_bits, total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, date_start, date_end,';
+		$sql .= ' fk_unit';
+		$sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
+		$sql .= ')';
+		$sql .= " VALUES (".$this->fk_commande.",";
+		$sql .= " ".($this->fk_parent_line > 0 ? "'".$this->db->escape($this->fk_parent_line)."'" : "null").",";
+		$sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
+		$sql .= " '".$this->db->escape($this->desc)."',";
+		$sql .= " '".price2num($this->qty)."',";
+		$sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
+		$sql .= " '".price2num($this->tva_tx)."',";
+		$sql .= " '".price2num($this->localtax1_tx)."',";
+		$sql .= " '".price2num($this->localtax2_tx)."',";
+		$sql .= " '".$this->db->escape($this->localtax1_type)."',";
+		$sql .= " '".$this->db->escape($this->localtax2_type)."',";
+		$sql .= ' '.(!empty($this->fk_product) ? $this->fk_product : "null").',';
+		$sql .= " '".$this->db->escape($this->product_type)."',";
+		$sql .= " '".price2num($this->remise_percent)."',";
+		$sql .= " ".(price2num($this->subprice) !== '' ?price2num($this->subprice) : "null").",";
+		$sql .= " ".($this->price != '' ? "'".price2num($this->price)."'" : "null").",";
+		$sql .= " '".price2num($this->remise)."',";
+		$sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
+		$sql .= ' '.$this->special_code.',';
+		$sql .= ' '.$this->rang.',';
+		$sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
+		$sql .= ' '.price2num($this->pa_ht).',';
+		$sql .= " '".$this->db->escape($this->info_bits)."',";
+		$sql .= " ".price2num($this->total_ht).",";
+		$sql .= " ".price2num($this->total_tva).",";
+		$sql .= " ".price2num($this->total_localtax1).",";
+		$sql .= " ".price2num($this->total_localtax2).",";
+		$sql .= " ".price2num($this->total_ttc).",";
+		$sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").',';
+		$sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").',';
+		$sql .= ' '.(!$this->fk_unit ? 'NULL' : $this->fk_unit);
+		$sql .= ", ".(!empty($this->fk_multicurrency) ? $this->fk_multicurrency : 'NULL');
+		$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
+		$sql .= ", ".$this->multicurrency_subprice;
+		$sql .= ", ".$this->multicurrency_total_ht;
+		$sql .= ", ".$this->multicurrency_total_tva;
+		$sql .= ", ".$this->multicurrency_total_ttc;
+		$sql .= ')';
 
 		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
-			$this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet');
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'commandedet');
 			$this->rowid = $this->id;
 
 			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
 			{
-				$result=$this->insertExtraFields();
+				$result = $this->insertExtraFields();
 				if ($result < 0)
 				{
 					$error++;
 				}
 			}
 
-			if (! $error && ! $notrigger)
+			if (!$error && !$notrigger)
 			{
 				// Call trigger
-				$result=$this->call_trigger('LINEORDER_INSERT', $user);
+				$result = $this->call_trigger('LINEORDER_INSERT', $user);
 				if ($result < 0) $error++;
 				// End call triggers
 			}

+ 12 - 12
htdocs/commande/list.php

@@ -75,7 +75,7 @@ $search_user = GETPOST('search_user', 'int');
 $search_sale = GETPOST('search_sale', 'int');
 $search_total_ht = GETPOST('search_total_ht', 'alpha');
 $search_total_ttc = GETPOST('search_total_ttc', 'alpha');
-$search_login=GETPOST('search_login', 'alpha');
+$search_login = GETPOST('search_login', 'alpha');
 $search_categ_cus = trim(GETPOST("search_categ_cus", 'int'));
 $optioncss = GETPOST('optioncss', 'alpha');
 $billed = GETPOST('billed', 'int');
@@ -197,7 +197,7 @@ if (empty($reshook))
 		$search_total_ht = '';
 		$search_total_vat = '';
 		$search_total_ttc = '';
-		$search_login='';
+		$search_login = '';
 		$search_dateorder_start = '';
 		$search_dateorder_end = '';
 		$search_datedelivery_start = '';
@@ -249,11 +249,11 @@ if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT';
 $sql .= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,';
 $sql .= " typent.code as typent_code,";
 $sql .= " state.code_departement as state_code, state.nom as state_name,";
-$sql.= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_client, c.fk_user_author,';
+$sql .= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_client, c.fk_user_author,';
 $sql .= ' c.date_valid, c.date_commande, c.note_private, c.date_livraison as date_delivery, c.fk_statut, c.facture as billed,';
 $sql .= ' c.date_creation as date_creation, c.tms as date_update, c.date_cloture as date_cloture,';
 $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label,";
-$sql.= " u.login";
+$sql .= " u.login";
 if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc";
 // Add fields from extrafields
 if (!empty($extrafields->attributes[$object->table_element]['label']))
@@ -272,7 +272,7 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count
 if ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid=pd.fk_commande';
 if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product';
 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = c.fk_projet";
-$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON c.fk_user_author = u.rowid';
+$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON c.fk_user_author = u.rowid';
 
 // We'll need this table joined to the select in order to filter by sale
 if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
@@ -424,7 +424,7 @@ if ($resql)
 	if ($search_total_ht != '') 	$param .= '&search_total_ht='.urlencode($search_total_ht);
 	if ($search_total_vat != '')  	$param .= '&search_total_vat='.urlencode($search_total_vat);
 	if ($search_total_ttc != '')  	$param .= '&search_total_ttc='.urlencode($search_total_ttc);
-	if ($search_login)  	 $param.='&search_login='.urlencode($search_login);
+	if ($search_login)  	 $param .= '&search_login='.urlencode($search_login);
 	if ($search_project_ref >= 0) 	$param .= "&search_project_ref=".urlencode($search_project_ref);
 	if ($search_town != '')       	$param .= '&search_town='.urlencode($search_town);
 	if ($search_zip != '')        	$param .= '&search_zip='.urlencode($search_zip);
@@ -697,7 +697,7 @@ if ($resql)
 		print '<input class="flat" type="text" size="5" name="search_total_ttc" value="'.$search_total_ttc.'">';
 		print '</td>';
 	}
-	if (! empty($arrayfields['u.login']['checked']))
+	if (!empty($arrayfields['u.login']['checked']))
 	{
 		// Author
 		print '<td class="liste_titre" align="center">';
@@ -775,7 +775,7 @@ if ($resql)
 	if (!empty($arrayfields['c.total_ht']['checked']))       print_liste_field_titre($arrayfields['c.total_ht']['label'], $_SERVER["PHP_SELF"], 'c.total_ht', '', $param, '', $sortfield, $sortorder, 'right ');
 	if (!empty($arrayfields['c.total_vat']['checked']))      print_liste_field_titre($arrayfields['c.total_vat']['label'], $_SERVER["PHP_SELF"], 'c.tva', '', $param, '', $sortfield, $sortorder, 'right ');
 	if (!empty($arrayfields['c.total_ttc']['checked']))      print_liste_field_titre($arrayfields['c.total_ttc']['label'], $_SERVER["PHP_SELF"], 'c.total_ttc', '', $param, '', $sortfield, $sortorder, 'right ');
-	if (! empty($arrayfields['u.login']['checked']))       	  print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder);
+	if (!empty($arrayfields['u.login']['checked']))       	  print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder);
 
 	// Extra fields
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
@@ -1097,17 +1097,17 @@ if ($resql)
 			$totalarray['val']['c.total_ttc'] += $obj->total_ttc;
 		}
 
-		$userstatic->id=$obj->fk_user_author;
-		$userstatic->login=$obj->login;
+		$userstatic->id = $obj->fk_user_author;
+		$userstatic->login = $obj->login;
 
 		// Author
-		if (! empty($arrayfields['u.login']['checked']))
+		if (!empty($arrayfields['u.login']['checked']))
 		{
 			print '<td align="center">';
 			if ($userstatic->id) print $userstatic->getLoginUrl(1);
 			else print '&nbsp;';
 			print "</td>\n";
-			if (! $i) $totalarray['nbfield']++;
+			if (!$i) $totalarray['nbfield']++;
 		}
 
 		// Extra fields

+ 27 - 27
htdocs/compta/cashcontrol/report.php

@@ -39,15 +39,15 @@ $langs->load("bills");
 
 $id = GETPOST('id', 'int');
 
-$_GET['optioncss']="print";
-$cashcontrol= new CashControl($db);
+$_GET['optioncss'] = "print";
+$cashcontrol = new CashControl($db);
 $cashcontrol->fetch($id);
 
 //$limit = GETPOST('limit')?GETPOST('limit', 'int'):$conf->liste_limit;
-$sortorder='ASC';
-$sortfield='b.datev,b.dateo,b.rowid';
+$sortorder = 'ASC';
+$sortfield = 'b.datev,b.dateo,b.rowid';
 
-$arrayfields=array(
+$arrayfields = array(
     'b.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1),
     'b.dateo'=>array('label'=>$langs->trans("DateOperationShort"), 'checked'=>1),
     'b.num_chq'=>array('label'=>$langs->trans("Number"), 'checked'=>1),
@@ -99,12 +99,12 @@ $sql.=" OR b.fk_account=".$conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE;
 $sql.=")";
 */
 $sql = "SELECT f.rowid as facid, f.ref, f.datef as do, pf.amount as amount, b.fk_account as bankid, cp.code";
-$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, ".MAIN_DB_PREFIX."bank as b";
-$sql.= " WHERE pf.fk_facture = f.rowid AND p.rowid = pf.fk_paiement AND cp.id = p.fk_paiement AND p.fk_bank = b.rowid";
-$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').")";
+$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, ".MAIN_DB_PREFIX."bank as b";
+$sql .= " WHERE pf.fk_facture = f.rowid AND p.rowid = pf.fk_paiement AND cp.id = p.fk_paiement AND p.fk_bank = b.rowid";
+$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'";
@@ -113,9 +113,9 @@ 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);
@@ -125,7 +125,7 @@ if ($resql)
 	$i = 0;
 
 	print "<center><h2>";
-	if ($cashcontrol->status==2) print $langs->trans("CashControl")." ".$cashcontrol->id;
+	if ($cashcontrol->status == 2) print $langs->trans("CashControl")." ".$cashcontrol->id;
 	else print $langs->trans("CashControl")." - ".$langs->trans("Draft");
 	print "<br>".$langs->trans("DateCreationShort").": ".dol_print_date($cashcontrol->date_creation, 'dayhour')."</h2></center>";
 
@@ -154,7 +154,7 @@ if ($resql)
 
 	// Loop on each record
 	$sign = 1;
-	$cash=$bank=$cheque=$other=0;
+	$cash = $bank = $cheque = $other = 0;
 
     $totalarray = array();
     $cachebankaccount = array();
@@ -167,7 +167,7 @@ if ($resql)
         {
             $bankaccounttmp = new Account($db);
             $bankaccounttmp->fetch($objp->bankid);
-            $cachebankaccount[$objp->bankid]=$bankaccounttmp;
+            $cachebankaccount[$objp->bankid] = $bankaccounttmp;
             $bankaccount = $bankaccounttmp;
         }
         else
@@ -192,21 +192,21 @@ if ($resql)
         print '<td class="nowrap left">';
         print $invoicetmp->getNomUrl(1);
         print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 
         // Date ope
     	print '<td class="nowrap left">';
     	print '<span id="dateoperation_'.$objp->rowid.'">'.dol_print_date($db->jdate($objp->do), "day")."</span>";
     	print "</td>\n";
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 
     	// Bank account
         print '<td class="nowrap right">';
 		print $bankaccount->getNomUrl(1);
-		if ($cashcontrol->posmodule=="takepos"){
+		if ($cashcontrol->posmodule == "takepos") {
 			$var1 = 'CASHDESK_ID_BANKACCOUNT_CASH'.$cashcontrol->posnumber;
 		}
-		else{
+		else {
 			$var1 = 'CASHDESK_ID_BANKACCOUNT_CASH';
 		}
 		if ($objp->code == 'CHQ') {
@@ -220,14 +220,14 @@ if ($resql)
 			else $other += $objp->amount;
 		}
 		print "</td>\n";
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 
         // Type
         print '<td class="right">';
        	print $objp->code;
        	if (empty($amountpertype[$objp->code])) $amountpertype[$objp->code] = 0;
         print "</td>\n";
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 
         // Debit
     	print '<td class="right">';
@@ -238,8 +238,8 @@ if ($resql)
     	    $amountpertype[$objp->code] += $objp->amount;
     	}
     	print "</td>\n";
-    	if (! $i) $totalarray['nbfield']++;
-    	if (! $i) $totalarray['pos'][$totalarray['nbfield']]='totaldebfield';
+    	if (!$i) $totalarray['nbfield']++;
+    	if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totaldebfield';
 
     	// Credit
     	print '<td class="right">';
@@ -250,8 +250,8 @@ if ($resql)
     	    $amountpertype[$objp->code] -= $objp->amount;
     	}
     	print "</td>\n";
-    	if (! $i) $totalarray['nbfield']++;
-    	if (! $i) $totalarray['pos'][$totalarray['nbfield']]='totalcredfield';
+    	if (!$i) $totalarray['nbfield']++;
+    	if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalcredfield';
 
 		print "</tr>";
 

+ 7 - 7
htdocs/compta/facture/card.php

@@ -298,14 +298,14 @@ if (empty($reshook))
 			// Note: Other solution if you want to add a negative line on invoice, is to create a discount for customer and consumme it (but this is possible on standard invoice only).
 			$array_of_pu_ht_per_vat_rate = array();
 			$array_of_pu_ht_devise_per_vat_rate = array();
-			foreach($object->lines as $line) {
+			foreach ($object->lines as $line) {
 				if (empty($array_of_pu_ht_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code])) $array_of_pu_ht_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] = 0;
 				if (empty($array_of_pu_ht_devise_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code])) $array_of_pu_ht_devise_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] = 0;
 				$array_of_pu_ht_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] += $line->subprice;
 				$array_of_pu_ht_devise_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] += $line->multicurrency_subprice;
 			}
 			//var_dump($array_of_pu_ht_per_vat_rate);exit;
-			foreach($array_of_pu_ht_per_vat_rate as $vatrate => $tmpvalue)
+			foreach ($array_of_pu_ht_per_vat_rate as $vatrate => $tmpvalue)
 			{
 				$pu_ht = $array_of_pu_ht_per_vat_rate[$vatrate];
 				$pu_ht_devise = $array_of_pu_ht_devise_per_vat_rate[$vatrate];
@@ -818,11 +818,11 @@ if (empty($reshook))
 			}
 
 			// If some payments were already done, we change the amount to pay using same prorate
-			if (! empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED)) {
-				$alreadypaid = $object->getSommePaiement();		// This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
+			if (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED)) {
+				$alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
 				if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
 					$ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
-					foreach($amount_ht as $vatrate => $val) {
+					foreach ($amount_ht as $vatrate => $val) {
 						$amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
 						$amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
 						$amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
@@ -3903,7 +3903,7 @@ elseif ($id > 0 || !empty($ref))
 
 	$morehtmlref = '<div class="refidno">';
 	// Ref invoice
-	if ($object->status == $object::STATUS_DRAFT && ! $mysoc->isInEEC() && ! empty($conf->global->INVOICE_ALLOW_FREE_REF)) {
+	if ($object->status == $object::STATUS_DRAFT && !$mysoc->isInEEC() && !empty($conf->global->INVOICE_ALLOW_FREE_REF)) {
 		$morehtmlref .= $form->editfieldkey("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', 0, 1);
 		$morehtmlref .= $form->editfieldval("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', null, null, '', 1);
 		$morehtmlref .= '<br>';
@@ -5095,7 +5095,7 @@ elseif ($id > 0 || !empty($ref))
 				}
 				// For credit note
 				if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $usercancreate
-					&& (! empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $object->getSommePaiement() == 0)
+					&& (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $object->getSommePaiement() == 0)
 					) {
 					print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReduc2")).'">'.$langs->trans('ConvertToReduc').'</a>';
 				}

+ 4 - 4
htdocs/compta/facture/class/facture.class.php

@@ -1272,7 +1272,7 @@ class Facture extends CommonInvoice
 		$this->availability_id      = $object->availability_id;
 		$this->demand_reason_id     = $object->demand_reason_id;
 		$this->date_livraison       = $object->date_livraison;
-		$this->fk_delivery_address  = $object->fk_delivery_address;		// deprecated
+		$this->fk_delivery_address  = $object->fk_delivery_address; // deprecated
 		$this->contact_id           = $object->contactid;
 		$this->ref_client           = $object->ref_client;
 
@@ -1688,7 +1688,7 @@ class Facture extends CommonInvoice
 				$line->special_code = $objp->special_code;
 				$line->fk_parent_line = $objp->fk_parent_line;
 				$line->situation_percent = $objp->situation_percent;
-				$line->fk_prev_id       = $objp->fk_prev_id;
+				$line->fk_prev_id = $objp->fk_prev_id;
 				$line->fk_unit = $objp->fk_unit;
 
 				// Accountancy
@@ -3231,7 +3231,7 @@ class Facture extends CommonInvoice
 				$this->line->rang = $rangmax + 1;
 			}
 
-			$this->line->id					= $rowid;
+			$this->line->id = $rowid;
 			$this->line->rowid				= $rowid;
 			$this->line->label				= $label;
 			$this->line->desc = $desc;
@@ -3272,7 +3272,7 @@ class Facture extends CommonInvoice
 
 			if (is_array($array_options) && count($array_options) > 0) {
 				// We replace values in this->line->array_options only for entries defined into $array_options
-				foreach($array_options as $key => $value) {
+				foreach ($array_options as $key => $value) {
 					$this->line->array_options[$key] = $array_options[$key];
 				}
 			}

+ 7 - 7
htdocs/compta/prelevement/card.php

@@ -362,14 +362,14 @@ if ($id > 0 || $ref)
 
 		$urladd = "&amp;id=".$id;
 
-		print '<form method="get" action="' . $_SERVER ['PHP_SELF'] . '" name="search_form">' . "\n";
-		print '<input type="hidden" name="id" value="' . $id . '"/>';
-		print '<input type="hidden" name="socid" value="' . $socid . '"/>';
-		if (! empty($page)) {
-			print '<input type="hidden" name="page" value="' . $page . '"/>';
+		print '<form method="get" action="'.$_SERVER ['PHP_SELF'].'" name="search_form">'."\n";
+		print '<input type="hidden" name="id" value="'.$id.'"/>';
+		print '<input type="hidden" name="socid" value="'.$socid.'"/>';
+		if (!empty($page)) {
+			print '<input type="hidden" name="page" value="'.$page.'"/>';
 		}
-		if (! empty($limit)) {
-			print '<input type="hidden" name="limit" value="' . $limit . '"/>';
+		if (!empty($limit)) {
+			print '<input type="hidden" name="limit" value="'.$limit.'"/>';
 		}
 		print_barre_liste($langs->trans("Lines"), $page, $_SERVER["PHP_SELF"], $urladd, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit);
 

+ 42 - 42
htdocs/compta/prelevement/create.php

@@ -40,19 +40,19 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 $langs->loadLangs(array('banks', 'categories', 'withdrawals', 'companies', 'bills'));
 
 // Security check
-if ($user->socid) $socid=$user->socid;
+if ($user->socid) $socid = $user->socid;
 $result = restrictedArea($user, 'prelevement', '', '', 'bons');
 
 // Get supervariables
 $action = GETPOST('action', 'alpha');
-$mode = GETPOST('mode', 'alpha')?GETPOST('mode', 'alpha'):'real';
+$mode = GETPOST('mode', 'alpha') ?GETPOST('mode', 'alpha') : 'real';
 $format = GETPOST('format', 'aZ09');
-$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) { $page = 0; }     // If $page is not defined, or '' or -1
 $offset = $limit * $page;
 
-$hookmanager->initHooks(array('directdebitcreatecard','globalcard'));
+$hookmanager->initHooks(array('directdebitcreatecard', 'globalcard'));
 
 
 /*
@@ -68,7 +68,7 @@ if (empty($reshook))
 	// Change customer bank information to withdraw
 	if ($action == 'modify')
 	{
-		for ($i = 1 ; $i < 9 ; $i++)
+		for ($i = 1; $i < 9; $i++)
 		{
 			dolibarr_set_const($db, GETPOST("nom$i"), GETPOST("value$i"), 'chaine', 0, '', $conf->entity);
 		}
@@ -77,7 +77,7 @@ if (empty($reshook))
 	{
 		// $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty
 		$bprev = new BonPrelevement($db);
-	    $executiondate = dol_mktime(0, 0, 0, GETPOST('remonth'), (GETPOST('reday')+$conf->global->PRELEVEMENT_ADDDAYS), GETPOST('reyear'));
+	    $executiondate = dol_mktime(0, 0, 0, GETPOST('remonth'), (GETPOST('reday') + $conf->global->PRELEVEMENT_ADDDAYS), GETPOST('reyear'));
 
 	    $result = $bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format, $executiondate);
 		if ($result < 0)
@@ -86,12 +86,12 @@ if (empty($reshook))
 		}
 		elseif ($result == 0)
 		{
-			$mesg=$langs->trans("NoInvoiceCouldBeWithdrawed", $format);
+			$mesg = $langs->trans("NoInvoiceCouldBeWithdrawed", $format);
 			setEventMessages($mesg, null, 'errors');
-			$mesg.='<br>'."\n";
-			foreach($bprev->invoice_in_error as $key => $val)
+			$mesg .= '<br>'."\n";
+			foreach ($bprev->invoice_in_error as $key => $val)
 			{
-				$mesg.='<span class="warning">'.$val."</span><br>\n";
+				$mesg .= '<span class="warning">'.$val."</span><br>\n";
 			}
 		}
 		else
@@ -108,8 +108,8 @@ if (empty($reshook))
 
 $form = new Form($db);
 
-$thirdpartystatic=new Societe($db);
-$invoicestatic=new Facture($db);
+$thirdpartystatic = new Societe($db);
+$invoicestatic = new Facture($db);
 $bprev = new BonPrelevement($db);
 
 llxHeader('', $langs->trans("NewStandingOrder"));
@@ -134,10 +134,10 @@ print load_fiche_titre($langs->trans("NewStandingOrder"));
 
 dol_fiche_head();
 
-$nb=$bprev->NbFactureAPrelever();
-$nb1=$bprev->NbFactureAPrelever(1);
-$nb11=$bprev->NbFactureAPrelever(1, 1);
-$pricetowithdraw=$bprev->SommeAPrelever();
+$nb = $bprev->NbFactureAPrelever();
+$nb1 = $bprev->NbFactureAPrelever(1);
+$nb11 = $bprev->NbFactureAPrelever(1, 1);
+$pricetowithdraw = $bprev->SommeAPrelever();
 if ($nb < 0 || $nb1 < 0 || $nb11 < 0)
 {
 	dol_print_error($bprev->error);
@@ -162,17 +162,17 @@ if ($mesg) print $mesg;
 
 print "<div class=\"tabsAction\">\n";
 
-print '<form action="' . $_SERVER['PHP_SELF'] . '?action=create" method="POST">';
-print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
+print '<form action="'.$_SERVER['PHP_SELF'].'?action=create" method="POST">';
+print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 if ($nb) {
     if ($pricetowithdraw) {
         print $langs->trans('ExecutionDate').' ';
         print $form->selectDate();
         if ($mysoc->isInEEC()) {
             print '<select name="format"><option value="FRST">'.$langs->trans('SEPAFRST').'</option><option value="RCUR">'.$langs->trans('SEPARCUR').'</option></select>';
-            print '<input class="butAction" type="submit" value="' . $langs->trans("CreateForSepa") . '"/>';
+            print '<input class="butAction" type="submit" value="'.$langs->trans("CreateForSepa").'"/>';
         } else {
-            print '<a class="butAction"  type="submit" href="create.php?action=create&format=ALL">' . $langs->trans("CreateAll") . "</a>\n";
+            print '<a class="butAction"  type="submit" href="create.php?action=create&format=ALL">'.$langs->trans("CreateAll")."</a>\n";
 		}
 	}
 	else
@@ -205,20 +205,20 @@ print '<br>';
  */
 
 $sql = "SELECT f.ref, f.rowid, f.total_ttc, s.nom as name, s.rowid as socid,";
-$sql.= " pfd.date_demande, pfd.amount";
-$sql.= " FROM ".MAIN_DB_PREFIX."facture as f,";
-$sql.= " ".MAIN_DB_PREFIX."societe as s,";
-$sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
-$sql.= " WHERE s.rowid = f.fk_soc";
-$sql.= " AND f.entity IN (".getEntity('invoice').")";
+$sql .= " pfd.date_demande, pfd.amount";
+$sql .= " FROM ".MAIN_DB_PREFIX."facture as f,";
+$sql .= " ".MAIN_DB_PREFIX."societe as s,";
+$sql .= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
+$sql .= " WHERE s.rowid = f.fk_soc";
+$sql .= " AND f.entity IN (".getEntity('invoice').")";
 if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS))
 {
-	$sql.= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
+	$sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
 }
-$sql.= " AND f.total_ttc > 0";
-$sql.= " AND pfd.traite = 0";
-$sql.= " AND pfd.fk_facture = f.rowid";
-if ($socid > 0) $sql.= " AND f.fk_soc = ".$socid;
+$sql .= " AND f.total_ttc > 0";
+$sql .= " AND pfd.traite = 0";
+$sql .= " AND pfd.fk_facture = f.rowid";
+if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid;
 
 $nbtotalofrecords = '';
 if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
@@ -232,24 +232,24 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
 	}
 }
 
-$sql.= $db->plimit($limit+1, $offset);
+$sql .= $db->plimit($limit + 1, $offset);
 
-$resql=$db->query($sql);
+$resql = $db->query($sql);
 if ($resql)
 {
 	$num = $db->num_rows($resql);
 	$i = 0;
 
-    $param='';
-	if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
-	if($socid) $param .= '&socid='.urlencode($socid);
-    if($option) $param .= "&option=".urlencode($option);
+    $param = '';
+	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+	if ($socid) $param .= '&socid='.urlencode($socid);
+    if ($option) $param .= "&option=".urlencode($option);
 
     print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="page" value="'.$page.'">';
-	if (! empty($limit)) {
-		print '<input type="hidden" name="limit" value="' . $limit . '"/>';
+	if (!empty($limit)) {
+		print '<input type="hidden" name="limit" value="'.$limit.'"/>';
 	}
 
     print_barre_liste($langs->trans("InvoiceWaitingWithdraw"), $page, $_SERVER['PHP_SELF'], $param, '', '', '', $num, $nbtotalofrecords, 'invoicing', 0, '', '', $limit);
@@ -266,7 +266,7 @@ if ($resql)
 
 	if ($num)
 	{
-		require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
+		require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
 		$bac = new CompanyBankAccount($db);
 
 		while ($i < $num && $i < $limit)
@@ -275,8 +275,8 @@ if ($resql)
 
 			print '<tr class="oddeven">';
 			print '<td>';
-			$invoicestatic->id=$obj->rowid;
-			$invoicestatic->ref=$obj->ref;
+			$invoicestatic->id = $obj->rowid;
+			$invoicestatic->ref = $obj->ref;
 			print $invoicestatic->getNomUrl(1, 'withdraw');
 			print '</td>';
 			// Thirdparty

+ 37 - 37
htdocs/compta/prelevement/demandes.php

@@ -36,18 +36,18 @@ $langs->loadLangs(array('banks', 'categories', 'withdrawals', 'companies'));
 // Security check
 $socid = GETPOST('socid', 'int');
 $status = GETPOST('status', 'int');
-if ($user->socid) $socid=$user->socid;
+if ($user->socid) $socid = $user->socid;
 $result = restrictedArea($user, 'prelevement', '', '', 'bons');
 
-$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')
+$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')
 
 $search_facture = GETPOST('search_facture', 'alpha');
 $search_societe = trim(GETPOST('search_societe', 'alpha'));
 
 // 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');
@@ -55,8 +55,8 @@ if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST(
 $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
-if (! $sortorder) $sortorder="DESC";
-if (! $sortfield) $sortfield="f.ref";
+if (!$sortorder) $sortorder = "DESC";
+if (!$sortfield) $sortfield = "f.ref";
 
 $massactionbutton = '';
 
@@ -96,34 +96,34 @@ else
 
 llxHeader('', $title);
 
-$thirdpartystatic=new Societe($db);
-$invoicestatic=new Facture($db);
+$thirdpartystatic = new Societe($db);
+$invoicestatic = new Facture($db);
 
 // List of requests
 
-$sql= "SELECT f.ref, f.rowid, f.total_ttc,";
-$sql.= " s.nom as name, s.rowid as socid,";
-$sql.= " pfd.date_demande as date_demande,";
-$sql.= " pfd.fk_user_demande";
-$sql.= " FROM ".MAIN_DB_PREFIX."facture as f,";
-$sql.= " ".MAIN_DB_PREFIX."societe as s,";
-$sql.= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
-if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-$sql.= " WHERE s.rowid = f.fk_soc";
-$sql.= " AND f.entity IN (".getEntity('invoice').")";
-if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
-if ($socid) $sql.= " AND f.fk_soc = ".$socid;
-if (!$status) $sql.= " AND pfd.traite = 0";
-if ($status) $sql.= " AND pfd.traite = ".$status;
-$sql.= " AND f.total_ttc > 0";
+$sql = "SELECT f.ref, f.rowid, f.total_ttc,";
+$sql .= " s.nom as name, s.rowid as socid,";
+$sql .= " pfd.date_demande as date_demande,";
+$sql .= " pfd.fk_user_demande";
+$sql .= " FROM ".MAIN_DB_PREFIX."facture as f,";
+$sql .= " ".MAIN_DB_PREFIX."societe as s,";
+$sql .= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
+if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+$sql .= " WHERE s.rowid = f.fk_soc";
+$sql .= " AND f.entity IN (".getEntity('invoice').")";
+if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
+if ($socid) $sql .= " AND f.fk_soc = ".$socid;
+if (!$status) $sql .= " AND pfd.traite = 0";
+if ($status) $sql .= " AND pfd.traite = ".$status;
+$sql .= " AND f.total_ttc > 0";
 if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS))
 {
-	$sql.= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
+	$sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
 }
-$sql.= " AND pfd.fk_facture = f.rowid";
-if ($search_facture) $sql.= natural_search("f.ref", $search_facture);
-if ($search_societe) $sql.= natural_search("s.nom", $search_societe);
-$sql.=$db->order($sortfield, $sortorder);
+$sql .= " AND pfd.fk_facture = f.rowid";
+if ($search_facture) $sql .= natural_search("f.ref", $search_facture);
+if ($search_societe) $sql .= natural_search("s.nom", $search_societe);
+$sql .= $db->order($sortfield, $sortorder);
 
 
 // Count total nb of records
@@ -145,10 +145,10 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords)
 }
 else
 {
-	$sql.= $db->plimit($limit+1, $offset);
+	$sql .= $db->plimit($limit + 1, $offset);
 
-	$resql=$db->query($sql);
-	if (! $resql)
+	$resql = $db->query($sql);
+	if (!$resql)
 	{
 		dol_print_error($db);
 		exit;
@@ -201,20 +201,20 @@ $i = 0;
 while ($i < min($num, $limit))
 {
 	$obj = $db->fetch_object($resql);
-	if (empty($obj)) break;		// Should not happen
+	if (empty($obj)) break; // Should not happen
 
 	print '<tr class="oddeven">';
 
 	// Ref facture
 	print '<td>';
-	$invoicestatic->id=$obj->rowid;
-	$invoicestatic->ref=$obj->ref;
+	$invoicestatic->id = $obj->rowid;
+	$invoicestatic->ref = $obj->ref;
 	print $invoicestatic->getNomUrl(1, 'withdraw');
 	print '</td>';
 
 	print '<td>';
-	$thirdpartystatic->id=$obj->socid;
-	$thirdpartystatic->name=$obj->name;
+	$thirdpartystatic->id = $obj->socid;
+	$thirdpartystatic->name = $obj->name;
 	print $thirdpartystatic->getNomUrl(1, 'customer');
 	print '</td>';
 

+ 43 - 43
htdocs/compta/sociales/card.php

@@ -30,26 +30,26 @@ require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
-if (! empty($conf->projet->enabled))
+if (!empty($conf->projet->enabled))
 {
 	include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 	include_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
 }
-if (! empty($conf->accounting->enabled)) {
-	include_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
+if (!empty($conf->accounting->enabled)) {
+	include_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
 }
 
 // Load translation files required by the page
 $langs->loadLangs(array('compta', 'bills', 'banks'));
 
-$id=GETPOST('id', 'int');
-$action=GETPOST('action', 'aZ09');
-$confirm=GETPOST('confirm');
+$id = GETPOST('id', 'int');
+$action = GETPOST('action', 'aZ09');
+$confirm = GETPOST('confirm');
 $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0);
 
 // Security check
 $socid = GETPOST('socid', 'int');
-if ($user->socid) $socid=$user->socid;
+if ($user->socid) $socid = $user->socid;
 $result = restrictedArea($user, 'tax', $id, 'chargesociales', 'charges');
 
 $object = new ChargeSociales($db);
@@ -159,44 +159,44 @@ if ($action == 'add' && $user->rights->tax->charges->creer)
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")), null, 'errors');
 		$action = 'create';
 	}
-	elseif (! is_numeric($amount))
+	elseif (!is_numeric($amount))
 	{
 		setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentities("Amount")), null, 'errors');
 		$action = 'create';
 	}
 	else
 	{
-		$object->type				= $actioncode;
-		$object->label				= GETPOST('label', 'alpha');
-		$object->date_ech			= $dateech;
+		$object->type = $actioncode;
+		$object->label = GETPOST('label', 'alpha');
+		$object->date_ech = $dateech;
 		$object->periode			= $dateperiod;
 		$object->amount				= $amount;
-		$object->mode_reglement_id	= GETPOST('mode_reglement_id');
+		$object->mode_reglement_id = GETPOST('mode_reglement_id');
 		$object->fk_account			= GETPOST('fk_account', 'int');
 		$object->fk_project			= GETPOST('fk_project');
 
-		$id=$object->create($user);
+		$id = $object->create($user);
 		if ($id <= 0)
 		{
 			setEventMessages($object->error, $object->errors, 'errors');
-			$action='create';
+			$action = 'create';
 		}
 	}
 }
 
 
-if ($action == 'update' && ! $_POST["cancel"] && $user->rights->tax->charges->creer)
+if ($action == 'update' && !$_POST["cancel"] && $user->rights->tax->charges->creer)
 {
-	$dateech=dol_mktime(GETPOST('echhour'), GETPOST('echmin'), GETPOST('echsec'), GETPOST('echmonth'), GETPOST('echday'), GETPOST('echyear'));
-	$dateperiod=dol_mktime(GETPOST('periodhour'), GETPOST('periodmin'), GETPOST('periodsec'), GETPOST('periodmonth'), GETPOST('periodday'), GETPOST('periodyear'));
-	$amount=price2num(GETPOST('amount'));
+	$dateech = dol_mktime(GETPOST('echhour'), GETPOST('echmin'), GETPOST('echsec'), GETPOST('echmonth'), GETPOST('echday'), GETPOST('echyear'));
+	$dateperiod = dol_mktime(GETPOST('periodhour'), GETPOST('periodmin'), GETPOST('periodsec'), GETPOST('periodmonth'), GETPOST('periodday'), GETPOST('periodyear'));
+	$amount = price2num(GETPOST('amount'));
 
-	if (! $dateech)
+	if (!$dateech)
 	{
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors');
 		$action = 'edit';
 	}
-	elseif (! $dateperiod)
+	elseif (!$dateperiod)
 	{
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Period")), null, 'errors');
 		$action = 'edit';
@@ -444,14 +444,14 @@ if ($id > 0)
 
 		if ($action == 'paid')
 		{
-			$text=$langs->trans('ConfirmPaySocialContribution');
+			$text = $langs->trans('ConfirmPaySocialContribution');
 			print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans('PaySocialContribution'), $text, "confirm_paid", '', '', 2);
 		}
 
 		// Confirmation of the removal of the Social Contribution
 		if ($action == 'delete')
 		{
-			$text=$langs->trans('ConfirmDeleteSocialContribution');
+			$text = $langs->trans('ConfirmDeleteSocialContribution');
 			print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('DeleteSocialContribution'), $text, 'confirm_delete', '', '', 2);
 		}
 
@@ -463,48 +463,48 @@ if ($id > 0)
 
 		dol_fiche_head($head, 'card', $langs->trans("SocialContribution"), -1, 'bill');
 
-		$morehtmlref='<div class="refidno">';
+		$morehtmlref = '<div class="refidno">';
 		// Ref customer
-		$morehtmlref.=$form->editfieldkey("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', 0, 1);
-		$morehtmlref.=$form->editfieldval("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', null, null, '', 1);
+		$morehtmlref .= $form->editfieldkey("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', 0, 1);
+		$morehtmlref .= $form->editfieldval("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', null, null, '', 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->tax->charges->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 .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
 				}
 				if ($action == 'classify') {
 					//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
-					$morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
-					$morehtmlref.='<input type="hidden" name="action" value="classin">';
-					$morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">';
-					$morehtmlref.=$formproject->select_projects(0, $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="'.newToken().'">';
+					$morehtmlref .= $formproject->select_projects(0, $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>';
 
-		$linkback = '<a href="' . DOL_URL_ROOT . '/compta/sociales/list.php?restore_lastsearch_values=1">' . $langs->trans("BackToList") . '</a>';
+		$linkback = '<a href="'.DOL_URL_ROOT.'/compta/sociales/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-		$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, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright);
 

+ 44 - 44
htdocs/compta/sociales/class/chargesociales.class.php

@@ -132,41 +132,41 @@ class ChargeSociales extends CommonObject
     public function fetch($id, $ref = '')
     {
         $sql = "SELECT cs.rowid, cs.date_ech";
-        $sql.= ", cs.libelle as label, cs.fk_type, cs.amount, cs.fk_projet as fk_project, cs.paye, cs.periode, cs.import_key";
-        $sql.= ", cs.fk_account, cs.fk_mode_reglement";
-        $sql.= ", c.libelle";
-        $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
-        $sql.= " FROM ".MAIN_DB_PREFIX."chargesociales as cs";
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as c ON cs.fk_type = c.id";
-        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id';
-        $sql.= ' WHERE cs.entity IN ('.getEntity('tax').')';
-        if ($ref) $sql.= " AND cs.rowid = ".$ref;
-        else $sql.= " AND cs.rowid = ".$id;
+        $sql .= ", cs.libelle as label, cs.fk_type, cs.amount, cs.fk_projet as fk_project, cs.paye, cs.periode, cs.import_key";
+        $sql .= ", cs.fk_account, cs.fk_mode_reglement";
+        $sql .= ", c.libelle";
+        $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
+        $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as cs";
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as c ON cs.fk_type = c.id";
+        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id';
+        $sql .= ' WHERE cs.entity IN ('.getEntity('tax').')';
+        if ($ref) $sql .= " AND cs.rowid = ".$ref;
+        else $sql .= " AND cs.rowid = ".$id;
 
         dol_syslog(get_class($this)."::fetch", 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->ref					= $obj->rowid;
-                $this->date_ech				= $this->db->jdate($obj->date_ech);
+                $this->date_ech = $this->db->jdate($obj->date_ech);
                 $this->lib					= $obj->label;
                 $this->label				= $obj->label;
                 $this->type					= $obj->fk_type;
                 $this->type_label			= $obj->libelle;
                 $this->fk_account			= $obj->fk_account;
-                $this->mode_reglement_id	= $obj->fk_mode_reglement;
-                $this->mode_reglement_code	= $obj->mode_reglement_code;
-                $this->mode_reglement		= $obj->mode_reglement_libelle;
-                $this->amount				= $obj->amount;
-				$this->fk_project			= $obj->fk_project;
-                $this->paye					= $obj->paye;
-                $this->periode				= $this->db->jdate($obj->periode);
-                $this->import_key			= $this->import_key;
+                $this->mode_reglement_id = $obj->fk_mode_reglement;
+                $this->mode_reglement_code = $obj->mode_reglement_code;
+                $this->mode_reglement = $obj->mode_reglement_libelle;
+                $this->amount = $obj->amount;
+				$this->fk_project = $obj->fk_project;
+                $this->paye = $obj->paye;
+                $this->periode = $this->db->jdate($obj->periode);
+                $this->import_key = $this->import_key;
 
                 $this->db->free($resql);
 
@@ -497,7 +497,7 @@ class ChargeSociales extends CommonObject
         global $langs;
 
         // Load translation files required by the page
-        $langs->loadLangs(array("customers","bills"));
+        $langs->loadLangs(array("customers", "bills"));
 
         // We reinit status array to force to redefine them because label may change according to properties values.
         $this->labelStatus = array();
@@ -548,41 +548,41 @@ class ChargeSociales extends CommonObject
         if ($option !== 'nolink')
         {
         	// Add param to save lastsearch_values or not
-        	$add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
-        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
-        	if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
+        	$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
+        	if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
         }
 
 
-        if (empty($this->ref)) $this->ref=$this->label;
+        if (empty($this->ref)) $this->ref = $this->label;
 
         $label = '<u>'.$langs->trans("ShowSocialContribution").'</u>';
-        if (! empty($this->ref))
-        	$label .= '<br><b>'.$langs->trans('Ref') . ':</b> ' . $this->ref;
-        if (! empty($this->label))
-        	$label .= '<br><b>'.$langs->trans('Label') . ':</b> ' . $this->label;
-        if (! empty($this->type_label))
-        	$label .= '<br><b>'.$langs->trans('Type') . ':</b> ' . $this->type_label;
-
-        $linkclose='';
+        if (!empty($this->ref))
+        	$label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
+        if (!empty($this->label))
+        	$label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
+        if (!empty($this->type_label))
+        	$label .= '<br><b>'.$langs->trans('Type').':</b> '.$this->type_label;
+
+        $linkclose = '';
         if (empty($notooltip) && $user->rights->facture->lire)
         {
-        	if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+        	if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
         	{
-        		$label=$langs->trans("ShowSocialContribution");
-        		$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
+        		$label = $langs->trans("ShowSocialContribution");
+        		$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>';
 
         $result .= $linkstart;
-        if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
-        if ($withpicto != 2) $result.= ($maxlen?dol_trunc($this->ref, $maxlen):$this->ref);
+        if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+        if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref);
         $result .= $linkend;
 
         return $result;

+ 23 - 23
htdocs/compta/tva/document.php

@@ -34,7 +34,7 @@ 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/lib/vat.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.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';
@@ -48,7 +48,7 @@ $action = GETPOST('action', 'aZ09');
 $confirm = GETPOST('confirm', 'alpha');
 
 // Security check
-if ($user->socid) $socid=$user->socid;
+if ($user->socid) $socid = $user->socid;
 $result = restrictedArea($user, 'tax', '', 'vat', 'charges');
 
 
@@ -63,22 +63,22 @@ if (empty($page) || $page == -1) {
 $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 Tva($db);
 if ($id > 0) $object->fetch($id);
 
 $upload_dir = $conf->tax->dir_output.'/'.dol_sanitizeFileName($object->ref);
-$modulepart='tax';
+$modulepart = 'tax';
 
 
 /*
  * Actions
  */
 
-include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php';
+include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
 
 if ($action == 'setlib' && $user->rights->tax->charges->creer)
 {
@@ -94,29 +94,29 @@ if ($action == 'setlib' && $user->rights->tax->charges->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("VATPayment") . ' - ' . $langs->trans("Documents");
-$help_url='EN:Module_Taxes_and_social_contributions|FR:Module Taxes et dividendes|ES:M&oacute;dulo Impuestos y cargas sociales (IVA, impuestos)';
+$title = $langs->trans("VATPayment").' - '.$langs->trans("Documents");
+$help_url = 'EN:Module_Taxes_and_social_contributions|FR:Module Taxes et dividendes|ES:M&oacute;dulo Impuestos y cargas sociales (IVA, impuestos)';
 llxHeader("", $title, $help_url);
 
 if ($object->id)
 {
-	$alreadypayed=$object->getSommePaiement();
+	$alreadypayed = $object->getSommePaiement();
 
-    $head=vat_prepare_head($object);
+    $head = vat_prepare_head($object);
 
     dol_fiche_head($head, 'documents', $langs->trans("VATPayment"), -1, 'bill');
 
-	$morehtmlref='<div class="refidno">';
+	$morehtmlref = '<div class="refidno">';
 	// Label of social contribution
-	$morehtmlref.=$form->editfieldkey("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', 0, 1);
-	$morehtmlref.=$form->editfieldval("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', null, null, '', 1);
-	$morehtmlref.='</div>';
+	$morehtmlref .= $form->editfieldkey("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', 0, 1);
+	$morehtmlref .= $form->editfieldval("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', null, null, '', 1);
+	$morehtmlref .= '</div>';
 
-	$linkback = '<a href="' . DOL_URL_ROOT . '/compta/tva/list.php?restore_lastsearch_values=1">' . $langs->trans("BackToList") . '</a>';
+	$linkback = '<a href="'.DOL_URL_ROOT.'/compta/tva/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-	$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, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright);
 
@@ -124,11 +124,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'];
     }
 
 
@@ -147,8 +147,8 @@ if ($object->id)
     $modulepart = 'tax';
     $permission = $user->rights->tax->charges->creer;
     $permtoedit = $user->rights->fournisseur->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
 {

+ 1 - 1
htdocs/contrat/card.php

@@ -724,7 +724,7 @@ if (empty($reshook))
 
 			if (is_array($array_options) && count($array_options) > 0) {
 				// We replace values in this->line->array_options only for entries defined into $array_options
-				foreach($array_options as $key => $value) {
+				foreach ($array_options as $key => $value) {
 					$objectline->array_options[$key] = $array_options[$key];
 				}
 			}

+ 2 - 2
htdocs/contrat/class/contrat.class.php

@@ -901,7 +901,7 @@ class Contrat extends CommonObject
 
 				$line->fk_user_author = $objp->fk_user_author;
 				$line->fk_user_ouverture = $objp->fk_user_ouverture;
-				$line->fk_user_cloture  = $objp->fk_user_cloture;
+				$line->fk_user_cloture = $objp->fk_user_cloture;
 				$line->fk_unit = $objp->fk_unit;
 
 				$line->ref = $objp->product_ref; // deprecated
@@ -1807,7 +1807,7 @@ class Contrat extends CommonObject
 					$contractline->fetch_optionals();
 
 					// We replace values in $contractline->array_options only for entries defined into $array_options
-					foreach($array_options as $key => $value) {
+					foreach ($array_options as $key => $value) {
 						$contractline->array_options[$key] = $array_options[$key];
 					}
 

+ 101 - 101
htdocs/contrat/services_list.php

@@ -86,36 +86,36 @@ $extrafields = new ExtraFields($db);
 // fetch optionals attributes and labels
 $extrafields->fetch_name_optionals_label('contratdet');
 
-$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
+$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
 
 // Security check
 $contratid = GETPOST('id', 'int');
-if (! empty($user->socid)) $socid=$user->socid;
+if (!empty($user->socid)) $socid = $user->socid;
 $result = restrictedArea($user, 'contrat', $contratid);
 
 if ($search_status != '')
 {
-	$tmp=explode('&', $search_status);
-	$mode=$tmp[0];
-	if (empty($tmp[1])) $filter='';
+	$tmp = explode('&', $search_status);
+	$mode = $tmp[0];
+	if (empty($tmp[1])) $filter = '';
 	else
 	{
-		if ($tmp[1] == 'filter=notexpired') $filter='notexpired';
-		if ($tmp[1] == 'filter=expired') $filter='expired';
+		if ($tmp[1] == 'filter=notexpired') $filter = 'notexpired';
+		if ($tmp[1] == 'filter=expired') $filter = 'expired';
 	}
 }
 else
 {
 	$search_status = $mode;
-	if ($filter == 'expired') $search_status.='&filter=expired';
-	if ($filter == 'notexpired') $search_status.='&filter=notexpired';
+	if ($filter == 'expired') $search_status .= '&filter=expired';
+	if ($filter == 'notexpired') $search_status .= '&filter=notexpired';
 }
 
-$staticcontrat=new Contrat($db);
-$staticcontratligne=new ContratLigne($db);
-$companystatic=new Societe($db);
+$staticcontrat = new Contrat($db);
+$staticcontratligne = new ContratLigne($db);
+$companystatic = new Societe($db);
 
-$arrayfields=array(
+$arrayfields = array(
 	'c.ref'=>array('label'=>$langs->trans("Contract"), 'checked'=>1, 'position'=>80),
 	'p.description'=>array('label'=>$langs->trans("Service"), 'checked'=>1, 'position'=>80),
 	'cd.qty'=>array('label'=>$langs->trans("Qty"), 'checked'=>0, 'position'=>100),
@@ -198,71 +198,71 @@ if (empty($reshook))
  * View
  */
 
-$now=dol_now();
+$now = dol_now();
 
-$form=new Form($db);
+$form = new Form($db);
 
 $sql = "SELECT c.rowid as cid, c.ref, c.statut as cstatut,";
-$sql.= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,";
-$sql.= " cd.rowid, cd.description, cd.statut,";
-$sql.= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,";
+$sql .= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,";
+$sql .= " cd.rowid, cd.description, cd.statut,";
+$sql .= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,";
 if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,";
-$sql.= " cd.date_ouverture_prevue,";
-$sql.= " cd.date_ouverture,";
-$sql.= " cd.date_fin_validite,";
-$sql.= " cd.date_cloture,";
-$sql.= " cd.qty,";
-$sql.= " cd.total_ht,";
-$sql.= " cd.total_tva,";
-$sql.= " cd.tva_tx,";
-$sql.= " cd.subprice,";
+$sql .= " cd.date_ouverture_prevue,";
+$sql .= " cd.date_ouverture,";
+$sql .= " cd.date_fin_validite,";
+$sql .= " cd.date_cloture,";
+$sql .= " cd.qty,";
+$sql .= " cd.total_ht,";
+$sql .= " cd.total_tva,";
+$sql .= " cd.tva_tx,";
+$sql .= " cd.subprice,";
 //$sql.= " cd.date_c as date_creation,";
-$sql.= " cd.tms as date_update";
+$sql .= " cd.tms as date_update";
 // Add fields from extrafields
-if (! empty($extrafields->attributes[$object->table_element]['label'])) {
-	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
+if (!empty($extrafields->attributes[$object->table_element]['label'])) {
+	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
 }
 // Add fields from hooks
-$parameters=array();
-$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters);    // Note that $action and $object may have been modified by hook
-$sql.=$hookmanager->resPrint;
-$sql.= " FROM ".MAIN_DB_PREFIX."contrat as c,";
-$sql.= " ".MAIN_DB_PREFIX."societe as s,";
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
+$sql .= $hookmanager->resPrint;
+$sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,";
+$sql .= " ".MAIN_DB_PREFIX."societe as s,";
 if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,";
-$sql.= " ".MAIN_DB_PREFIX."contratdet as cd";
-if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cd.rowid = ef.fk_object)";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
-if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product';
-$sql.= " WHERE c.entity = ".$conf->entity;
-$sql.= " AND c.rowid = cd.fk_contrat";
-if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$search_product_category;
-$sql.= " AND c.fk_soc = s.rowid";
-if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
-if ($mode == "0") $sql.= " AND cd.statut = 0";
-if ($mode == "4") $sql.= " AND cd.statut = 4";
-if ($mode == "5") $sql.= " AND cd.statut = 5";
-if ($filter == "expired") $sql.= " AND cd.date_fin_validite < '".$db->idate($now)."'";
-if ($filter == "notexpired") $sql.= " AND cd.date_fin_validite >= '".$db->idate($now)."'";
-if ($search_name)     $sql.= " AND s.nom LIKE '%".$db->escape($search_name)."%'";
-if ($search_contract) $sql.= " AND c.ref LIKE '%".$db->escape($search_contract)."%' ";
-if ($search_service)  $sql.= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')";
-if ($socid > 0)       $sql.= " AND s.rowid = ".$socid;
-$filter_dateouvertureprevue=dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear);
+$sql .= " ".MAIN_DB_PREFIX."contratdet as cd";
+if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cd.rowid = ef.fk_object)";
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
+if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product';
+$sql .= " WHERE c.entity = ".$conf->entity;
+$sql .= " AND c.rowid = cd.fk_contrat";
+if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category;
+$sql .= " AND c.fk_soc = s.rowid";
+if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
+if ($mode == "0") $sql .= " AND cd.statut = 0";
+if ($mode == "4") $sql .= " AND cd.statut = 4";
+if ($mode == "5") $sql .= " AND cd.statut = 5";
+if ($filter == "expired") $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'";
+if ($filter == "notexpired") $sql .= " AND cd.date_fin_validite >= '".$db->idate($now)."'";
+if ($search_name)     $sql .= " AND s.nom LIKE '%".$db->escape($search_name)."%'";
+if ($search_contract) $sql .= " AND c.ref LIKE '%".$db->escape($search_contract)."%' ";
+if ($search_service)  $sql .= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')";
+if ($socid > 0)       $sql .= " AND s.rowid = ".$socid;
+$filter_dateouvertureprevue = dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear);
 if ($filter_dateouvertureprevue != '' && $filter_opouvertureprevue == -1) $filter_opouvertureprevue = '=';
 
-$filter_date1=dol_mktime(0, 0, 0, $op1month, $op1day, $op1year);
+$filter_date1 = dol_mktime(0, 0, 0, $op1month, $op1day, $op1year);
 if ($filter_date1 != '' && $filter_op1 == -1) $filter_op1 = '=';
 
-$filter_date2=dol_mktime(0, 0, 0, $op2month, $op2day, $op2year);
+$filter_date2 = dol_mktime(0, 0, 0, $op2month, $op2day, $op2year);
 if ($filter_date2 != '' && $filter_op2 == -1) $filter_op2 = '=';
 
-$filter_datecloture=dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear);
+$filter_datecloture = dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear);
 if ($filter_datecloture != '' && $filter_opcloture == -1) $filter_opcloture = '=';
 
-if (! empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_dateouvertureprevue != '') $sql.= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue)."'";
-if (! empty($filter_op1) && $filter_op1 != -1 && $filter_date1 != '') $sql.= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1)."'";
-if (! empty($filter_op2) && $filter_op2 != -1 && $filter_date2 != '') $sql.= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2)."'";
-if (! empty($filter_opcloture) && $filter_opcloture != -1 && $filter_datecloture != '') $sql.= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture)."'";
+if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_dateouvertureprevue != '') $sql .= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue)."'";
+if (!empty($filter_op1) && $filter_op1 != -1 && $filter_date1 != '') $sql .= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1)."'";
+if (!empty($filter_op2) && $filter_op2 != -1 && $filter_date2 != '') $sql .= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2)."'";
+if (!empty($filter_opcloture) && $filter_opcloture != -1 && $filter_datecloture != '') $sql .= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture)."'";
 // Add where from extra fields
 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
 $sql .= $db->order($sortfield, $sortorder);
@@ -594,120 +594,120 @@ while ($i < min($num, $limit))
 			if ($obj->type == 1) print img_object($obj->description, 'service').' '.dol_trunc($obj->description, 24);
 		}
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
 
-	if (! empty($arrayfields['cd.qty']['checked']))
+	if (!empty($arrayfields['cd.qty']['checked']))
 	{
 		print '<td>';
 		print $obj->qty;
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['cd.total_ht']['checked']))
+	if (!empty($arrayfields['cd.total_ht']['checked']))
 	{
 		print '<td class="right">';
 		print price($obj->total_ht);
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
-        if (! $i) $totalarray['pos'][$totalarray['nbfield']]='cd.total_ht';
+        if (!$i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_ht';
         $totalarray['val']['cd.total_ht'] += $obj->total_ht;
     }
-	if (! empty($arrayfields['cd.total_tva']['checked']))
+	if (!empty($arrayfields['cd.total_tva']['checked']))
 	{
 		print '<td class="right">';
 		print price($obj->total_tva);
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
-        if (! $i) $totalarray['pos'][$totalarray['nbfield']]='cd.total_tva';
+        if (!$i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_tva';
         $totalarray['val']['cd.total_tva'] += $obj->total_tva;
     }
-	if (! empty($arrayfields['cd.tva_tx']['checked']))
+	if (!empty($arrayfields['cd.tva_tx']['checked']))
 	{
 		print '<td class="right">';
 		print price2num($obj->tva_tx).'%';
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['cd.subprice']['checked']))
+	if (!empty($arrayfields['cd.subprice']['checked']))
 	{
 		print '<td class="right">';
 		print price($obj->subprice);
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
 
 
 	// Third party
-	if (! empty($arrayfields['s.nom']['checked']))
+	if (!empty($arrayfields['s.nom']['checked']))
 	{
 		print '<td>';
 		print $companystatic->getNomUrl(1, 'customer', 28);
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
 
 	// Start date
-	if (! empty($arrayfields['cd.date_ouverture_prevue']['checked']))
+	if (!empty($arrayfields['cd.date_ouverture_prevue']['checked']))
 	{
 		print '<td class="center">';
-		print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour'):'&nbsp;');
+		print ($obj->date_ouverture_prevue ?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour') : '&nbsp;');
 		if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0)
 		print ' '.img_picto($langs->trans("Late"), "warning");
 		else print '&nbsp;&nbsp;&nbsp;&nbsp;';
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['cd.date_ouverture']['checked']))
+	if (!empty($arrayfields['cd.date_ouverture']['checked']))
 	{
-		print '<td class="center">'.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour'):'&nbsp;').'</td>';
-        if (! $i) $totalarray['nbfield']++;
+		print '<td class="center">'.($obj->date_ouverture ?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour') : '&nbsp;').'</td>';
+        if (!$i) $totalarray['nbfield']++;
 	}
 	// End date
-	if (! empty($arrayfields['cd.date_fin_validite']['checked']))
+	if (!empty($arrayfields['cd.date_fin_validite']['checked']))
 	{
-		print '<td class="center">'.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour'):'&nbsp;');
+		print '<td class="center">'.($obj->date_fin_validite ?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour') : '&nbsp;');
 		if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5)
 		{
-			$warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24;
+			$warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24;
 			$textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
 			print img_warning($textlate);
 		}
 		else print '&nbsp;&nbsp;&nbsp;&nbsp;';
 		print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
 	// Close date (real end date)
-	if (! empty($arrayfields['cd.date_cloture']['checked']))
+	if (!empty($arrayfields['cd.date_cloture']['checked']))
 	{
 		print '<td class="center">'.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').'</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
 
 	// Extra fields
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
 	// Fields from hook
-	$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
-	$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['cd.datec']['checked']))
+	if (!empty($arrayfields['cd.datec']['checked']))
 	{
 		print '<td class="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['cd.tms']['checked']))
+	if (!empty($arrayfields['cd.tms']['checked']))
 	{
 		print '<td class="center">';
 		print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
 		print '</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 	// Status
-	if (! empty($arrayfields['status']['checked']))
+	if (!empty($arrayfields['status']['checked']))
 	{
 	    print '<td class="right">';
 	    if ($obj->cstatut == 0)
@@ -717,21 +717,21 @@ while ($i < min($num, $limit))
 	    }
 	    else
 	    {
-		    print $staticcontratligne->LibStatut($obj->statut, 5, ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0);
+		    print $staticcontratligne->LibStatut($obj->statut, 5, ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now) ? 1 : 0);
 	    }
 	    print '</td>';
-        if (! $i) $totalarray['nbfield']++;
+        if (!$i) $totalarray['nbfield']++;
 	}
 	// Action column
 	print '<td class="nowrap center">';
 	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
 	{
-		$selected=0;
-		if (in_array($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++;

+ 18 - 18
htdocs/core/actions_setmoduleoptions.inc.php

@@ -31,22 +31,22 @@ if ($action == 'update' && is_array($arrayofparameters))
 {
 	$db->begin();
 
-	$ok=true;
-	foreach($arrayofparameters as $key => $val)
+	$ok = true;
+	foreach ($arrayofparameters as $key => $val)
 	{
 		// Modify constant only if key was posted (avoid resetting key to the null value)
 		if (GETPOSTISSET($key))
 		{
-			$result=dolibarr_set_const($db, $key, GETPOST($key, 'alpha'), 'chaine', 0, '', $conf->entity);
+			$result = dolibarr_set_const($db, $key, GETPOST($key, 'alpha'), 'chaine', 0, '', $conf->entity);
 		    if ($result < 0)
 		    {
-			    $ok=false;
+			    $ok = false;
 			    break;
 		    }
 		}
 	}
 
-	if (! $error)
+	if (!$error)
 	{
 		$db->commit();
 		if (empty($nomessageinupdate)) setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
@@ -66,16 +66,16 @@ if ($action == 'setModuleOptions')
     // Process common param fields
     if (is_array($_POST))
     {
-        foreach($_POST as $key => $val)
+        foreach ($_POST as $key => $val)
         {
             if (preg_match('/^param(\d*)$/', $key, $reg))    // Works for POST['param'], POST['param1'], POST['param2'], ...
             {
-                $param=GETPOST("param".$reg[1], 'alpha');
-                $value=GETPOST("value".$reg[1], 'alpha');
+                $param = GETPOST("param".$reg[1], 'alpha');
+                $value = GETPOST("value".$reg[1], 'alpha');
                 if ($param)
                 {
                     $res = dolibarr_set_const($db, $param, $value, 'chaine', 0, '', $conf->entity);
-                    if (! $res > 0) $error++;
+                    if (!$res > 0) $error++;
                 }
             }
         }
@@ -85,19 +85,19 @@ if ($action == 'setModuleOptions')
     if (GETPOST('upload', 'alpha') && GETPOST('keyforuploaddir', 'aZ09'))
     {
         include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-        $keyforuploaddir=GETPOST('keyforuploaddir', 'aZ09');
-        $listofdir=explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->$keyforuploaddir)));
-        foreach($listofdir as $key=>$tmpdir)
+        $keyforuploaddir = GETPOST('keyforuploaddir', 'aZ09');
+        $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->$keyforuploaddir)));
+        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
             {
-                $upload_dir=$tmpdir;
+                $upload_dir = $tmpdir;
             }
         }
         if ($upload_dir)
@@ -107,7 +107,7 @@ if ($action == 'setModuleOptions')
         }
     }
 
-    if (! $error)
+    if (!$error)
     {
         $db->commit();
         if (empty($nomessageinsetmoduleoptions)) setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');

+ 33 - 33
htdocs/core/boxes/box_factures_imp.php

@@ -33,9 +33,9 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  */
 class box_factures_imp extends ModeleBoxes
 {
-    public $boxcode="oldestunpaidcustomerbills";
-    public $boximg="object_bill";
-    public $boxlabel="BoxOldestUnpaidCustomerBills";
+    public $boxcode = "oldestunpaidcustomerbills";
+    public $boximg = "object_bill";
+    public $boxlabel = "BoxOldestUnpaidCustomerBills";
     public $depends = array("facture");
 
 	/**
@@ -61,7 +61,7 @@ class box_factures_imp extends ModeleBoxes
 
 	    $this->db = $db;
 
-	    $this->hidden = ! ($user->rights->facture->lire);
+	    $this->hidden = !($user->rights->facture->lire);
 	}
 
 	/**
@@ -74,7 +74,7 @@ class box_factures_imp extends ModeleBoxes
 	{
 		global $conf, $user, $langs;
 
-		$this->max=$max;
+		$this->max = $max;
 
 		include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
         include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
@@ -89,37 +89,37 @@ class box_factures_imp extends ModeleBoxes
 		if ($user->rights->facture->lire)
 		{
 			$sql = "SELECT s.nom as name, s.rowid as socid, s.email,";
-            $sql.= " s.code_client,";
-            $sql.= " s.logo,";
-			$sql.= " f.ref, f.date_lim_reglement as datelimite,";
-            $sql.= " f.type,";
-			$sql.= " f.amount, f.datef as df,";
-            $sql.= " f.total as total_ht,";
-            $sql.= " f.tva as total_tva,";
-            $sql.= " f.total_ttc,";
-			$sql.= " f.paye, f.fk_statut, f.rowid as facid";
-			$sql.= ", sum(pf.amount) as am";
-			$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
-			if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-			$sql.= ", ".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";
-			$sql.= " AND f.entity IN (".getEntity('invoice').")";
-			$sql.= " AND f.paye = 0";
-			$sql.= " AND fk_statut = 1";
-			if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
-			if($user->socid) $sql.= " AND s.rowid = ".$user->socid;
-			$sql.= " GROUP BY s.nom, s.rowid, s.email, s.code_client, s.logo, f.ref, f.date_lim_reglement,";
-			$sql.= " f.type, f.amount, f.datef, f.total, f.tva, f.total_ttc, f.paye, f.fk_statut, f.rowid";
+            $sql .= " s.code_client,";
+            $sql .= " s.logo,";
+			$sql .= " f.ref, f.date_lim_reglement as datelimite,";
+            $sql .= " f.type,";
+			$sql .= " f.amount, f.datef as df,";
+            $sql .= " f.total as total_ht,";
+            $sql .= " f.tva as total_tva,";
+            $sql .= " f.total_ttc,";
+			$sql .= " f.paye, f.fk_statut, f.rowid as facid";
+			$sql .= ", sum(pf.amount) as am";
+			$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
+			if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+			$sql .= ", ".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";
+			$sql .= " AND f.entity IN (".getEntity('invoice').")";
+			$sql .= " AND f.paye = 0";
+			$sql .= " AND fk_statut = 1";
+			if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
+			if ($user->socid) $sql .= " AND s.rowid = ".$user->socid;
+			$sql .= " GROUP BY s.nom, s.rowid, s.email, s.code_client, s.logo, f.ref, f.date_lim_reglement,";
+			$sql .= " f.type, f.amount, f.datef, f.total, f.tva, f.total_ttc, f.paye, f.fk_statut, f.rowid";
 			//$sql.= " ORDER BY f.datef DESC, f.ref DESC ";
-			$sql.= " ORDER BY datelimite ASC, f.ref ASC ";
-			$sql.= $this->db->plimit($max, 0);
+			$sql .= " ORDER BY datelimite ASC, f.ref ASC ";
+			$sql .= $this->db->plimit($max, 0);
 
 			$result = $this->db->query($sql);
 			if ($result)
 			{
 				$num = $this->db->num_rows($result);
-				$now=dol_now();
+				$now = dol_now();
 
 				$line = 0;
 				$l_due_date = $langs->trans('Late').' ('.strtolower($langs->trans('DateDue')).': %s)';
@@ -127,7 +127,7 @@ class box_factures_imp extends ModeleBoxes
 				while ($line < $num)
 				{
 					$objp = $this->db->fetch_object($result);
-					$datelimite=$this->db->jdate($objp->datelimite);
+					$datelimite = $this->db->jdate($objp->datelimite);
                     $facturestatic->id = $objp->facid;
                     $facturestatic->ref = $objp->ref;
                     $facturestatic->type = $objp->type;
@@ -144,7 +144,7 @@ class box_factures_imp extends ModeleBoxes
                     $societestatic->code_client = $objp->code_client;
                     $societestatic->logo = $objp->logo;
 
-					$late='';
+					$late = '';
 					if ($facturestatic->hasDelay()) {
 						$late = img_warning(sprintf($l_due_date, dol_print_date($datelimite, 'day')));
 					}
@@ -180,7 +180,7 @@ class box_factures_imp extends ModeleBoxes
 					$line++;
 				}
 
-				if ($num==0) $this->info_box_contents[$line][0] = array('td' => 'class="center"','text'=>$langs->trans("NoUnpaidCustomerBills"));
+				if ($num == 0) $this->info_box_contents[$line][0] = array('td' => 'class="center"', 'text'=>$langs->trans("NoUnpaidCustomerBills"));
 
 				$this->db->free($result);
 			}

+ 1 - 1
htdocs/core/boxes/box_services_expired.php

@@ -94,7 +94,7 @@ class box_services_expired extends ModeleBoxes
             if ($user->socid) $sql .= ' AND c.fk_soc = '.$user->socid;
             if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
     		$sql .= " GROUP BY c.rowid, c.ref, c.statut, c.date_contrat, c.ref_customer, c.ref_supplier, s.nom, s.rowid";
-    		$sql.= ", s.email, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur";
+    		$sql .= ", s.email, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur";
     		$sql .= " ORDER BY date_line ASC";
     		$sql .= $this->db->plimit($max, 0);
 

+ 1 - 1
htdocs/core/class/doleditor.class.php

@@ -226,7 +226,7 @@ class DolEditor
                                                         });
                                                 }
                                             },
-											disableNativeSpellChecker: '.(empty($conf->global->CKEDITOR_NATIVE_SPELLCHECKER)?'true':'false');
+											disableNativeSpellChecker: '.(empty($conf->global->CKEDITOR_NATIVE_SPELLCHECKER) ? 'true' : 'false');
 
             	if ($this->uselocalbrowser)
             	{

+ 45 - 45
htdocs/core/class/dolreceiptprinter.class.php

@@ -101,7 +101,7 @@
  *
  */
 
-require_once DOL_DOCUMENT_ROOT .'/includes/mike42/escpos-php/autoload.php';
+require_once DOL_DOCUMENT_ROOT.'/includes/mike42/escpos-php/autoload.php';
 use Mike42\Escpos\PrintConnectors\FilePrintConnector;
 use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
 use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
@@ -137,7 +137,7 @@ class dolReceiptPrinter extends Printer
     /**
      * @var string Error code (or message)
      */
-    public $error='';
+    public $error = '';
 
     /**
      * @var string[] Error codes (or messages)
@@ -151,7 +151,7 @@ class dolReceiptPrinter extends Printer
      */
     public function __construct($db)
     {
-        $this->db=$db;
+        $this->db = $db;
         $this->tags = array(
             'dol_line_feed',
             'dol_line_feed_reverse',
@@ -251,8 +251,8 @@ class dolReceiptPrinter extends Printer
         $line = 0;
         $obj = array();
         $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter';
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
-        $sql.= ' WHERE entity = '.$conf->entity;
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
+        $sql .= ' WHERE entity = '.$conf->entity;
         $resql = $this->db->query($sql);
         if ($resql) {
             $num = $this->db->num_rows($resql);
@@ -319,8 +319,8 @@ class dolReceiptPrinter extends Printer
         $line = 0;
         $obj = array();
         $sql = 'SELECT rowid, name, template';
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
-        $sql.= ' WHERE entity = '.$conf->entity;
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
+        $sql .= ' WHERE entity = '.$conf->entity;
         $resql = $this->db->query($sql);
         if ($resql) {
             $num = $this->db->num_rows($resql);
@@ -399,10 +399,10 @@ class dolReceiptPrinter extends Printer
         global $conf;
         $error = 0;
         $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt';
-        $sql.= ' (name, fk_type, fk_profile, parameter, entity)';
-        $sql.= ' VALUES ("'.$this->db->escape($name).'", '.$type.', '.$profile.', "'.$this->db->escape($parameter).'", '.$conf->entity.')';
+        $sql .= ' (name, fk_type, fk_profile, parameter, entity)';
+        $sql .= ' VALUES ("'.$this->db->escape($name).'", '.$type.', '.$profile.', "'.$this->db->escape($parameter).'", '.$conf->entity.')';
         $resql = $this->db->query($sql);
-        if (! $resql) {
+        if (!$resql) {
             $error++;
             $this->errors[] = $this->db->lasterror;
         }
@@ -424,13 +424,13 @@ class dolReceiptPrinter extends Printer
         global $conf;
         $error = 0;
         $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt';
-        $sql.= ' SET name="'.$this->db->escape($name).'"';
-        $sql.= ', fk_type='.$type;
-        $sql.= ', fk_profile='.$profile;
-        $sql.= ', parameter="'.$this->db->escape($parameter).'"';
-        $sql.= ' WHERE rowid='.$printerid;
+        $sql .= ' SET name="'.$this->db->escape($name).'"';
+        $sql .= ', fk_type='.$type;
+        $sql .= ', fk_profile='.$profile;
+        $sql .= ', parameter="'.$this->db->escape($parameter).'"';
+        $sql .= ' WHERE rowid='.$printerid;
         $resql = $this->db->query($sql);
-        if (! $resql) {
+        if (!$resql) {
             $error++;
             $this->errors[] = $this->db->lasterror;
         }
@@ -448,9 +448,9 @@ class dolReceiptPrinter extends Printer
         global $conf;
         $error = 0;
         $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'printer_receipt';
-        $sql.= ' WHERE rowid='.$printerid;
+        $sql .= ' WHERE rowid='.$printerid;
         $resql = $this->db->query($sql);
-        if (! $resql) {
+        if (!$resql) {
             $error++;
             $this->errors[] = $this->db->lasterror;
         }
@@ -469,10 +469,10 @@ class dolReceiptPrinter extends Printer
         global $conf;
         $error = 0;
         $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'printer_receipt_template';
-        $sql.= ' (name, template, entity) VALUES ("'.$this->db->escape($name).'"';
-        $sql.= ', "'.$this->db->escape($template).'", '.$conf->entity.')';
+        $sql .= ' (name, template, entity) VALUES ("'.$this->db->escape($name).'"';
+        $sql .= ', "'.$this->db->escape($template).'", '.$conf->entity.')';
         $resql = $this->db->query($sql);
-        if (! $resql) {
+        if (!$resql) {
             $error++;
             $this->errors[] = $this->db->lasterror;
         }
@@ -493,11 +493,11 @@ class dolReceiptPrinter extends Printer
         global $conf;
         $error = 0;
         $sql = 'UPDATE '.MAIN_DB_PREFIX.'printer_receipt_template';
-        $sql.= ' SET name="'.$this->db->escape($name).'"';
-        $sql.= ', template="'.$this->db->escape($template).'"';
-        $sql.= ' WHERE rowid='.$templateid;
+        $sql .= ' SET name="'.$this->db->escape($name).'"';
+        $sql .= ', template="'.$this->db->escape($template).'"';
+        $sql .= ' WHERE rowid='.$templateid;
         $resql = $this->db->query($sql);
-        if (! $resql) {
+        if (!$resql) {
             $error++;
             $this->errors[] = $this->db->lasterror;
         }
@@ -515,10 +515,10 @@ class dolReceiptPrinter extends Printer
     {
         global $conf;
         $error = 0;
-        $img = EscposImage::load(DOL_DOCUMENT_ROOT .'/theme/common/dolibarr_logo_bw.png');
+        $img = EscposImage::load(DOL_DOCUMENT_ROOT.'/theme/common/dolibarr_logo_bw.png');
         //$this->profile = CapabilityProfile::load("TM-T88IV");
         $ret = $this->initPrinter($printerid);
-        if ($ret>0) {
+        if ($ret > 0) {
             setEventMessages($this->error, $this->errors, 'errors');
         } else {
             try {
@@ -532,7 +532,7 @@ class dolReceiptPrinter extends Printer
                 $this->printer->cut();
 
 				// If is DummyPrintConnector send to log to debugging
-				if($this->printer->connector instanceof DummyPrintConnector)
+				if ($this->printer->connector instanceof DummyPrintConnector)
 				{
 					$data = $this->printer->connector-> getData();
 					dol_syslog($data);
@@ -609,11 +609,11 @@ class dolReceiptPrinter extends Printer
         $level = 0;
         $nbcharactbyline = 48;
         $ret = $this->initPrinter($printerid);
-        if ($ret>0) {
+        if ($ret > 0) {
             setEventMessages($this->error, $this->errors, 'errors');
         } else {
             $nboflines = count($vals);
-            for ($tplline=0; $tplline < $nboflines; $tplline++) {
+            for ($tplline = 0; $tplline < $nboflines; $tplline++) {
                 //var_dump($vals[$tplline]['value']);
                 switch ($vals[$tplline]['tag']) {
                     case 'DOL_PRINT_TEXT':
@@ -622,7 +622,7 @@ class dolReceiptPrinter extends Printer
                     case 'DOL_PRINT_OBJECT_LINES':
                         foreach ($object->lines as $line) {
                             //var_dump($line);
-                            $spacestoadd = $nbcharactbyline - strlen($line->ref)- strlen($line->qty) - 10 - 1;
+                            $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1;
                             $spaces = str_repeat(' ', $spacestoadd);
                             $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n");
                             $this->printer->text(strip_tags(htmlspecialchars_decode($line->desc))."\n");
@@ -634,10 +634,10 @@ class dolReceiptPrinter extends Printer
                         foreach ($object->lines as $line) {
                             $vatarray[$line->tva_tx] += $line->total_tva;
                         }
-                        foreach($vatarray as $vatkey => $vatvalue) {
-                             $spacestoadd = $nbcharactbyline - strlen($vatkey)- 12;
+                        foreach ($vatarray as $vatkey => $vatvalue) {
+                             $spacestoadd = $nbcharactbyline - strlen($vatkey) - 12;
                              $spaces = str_repeat(' ', $spacestoadd);
-                             $this->printer->text($spaces. $vatkey.'% '.str_pad(price($vatvalue), 10, ' ', STR_PAD_LEFT)."\n");
+                             $this->printer->text($spaces.$vatkey.'% '.str_pad(price($vatvalue), 10, ' ', STR_PAD_LEFT)."\n");
                         }
                         break;
                     case 'DOL_PRINT_OBJECT_TOTAL':
@@ -686,11 +686,11 @@ class dolReceiptPrinter extends Printer
                         }
                         break;
                     case 'DOL_PRINT_LOGO':
-                        $img = EscposImage::load(DOL_DATA_ROOT .'/mycompany/logos/'.$mysoc->logo);
+                        $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo);
                         $this->printer->graphics($img);
                         break;
                     case 'DOL_PRINT_LOGO_OLD':
-                        $img = EscposImage::load(DOL_DATA_ROOT .'/mycompany/logos/'.$mysoc->logo);
+                        $img = EscposImage::load(DOL_DATA_ROOT.'/mycompany/logos/'.$mysoc->logo);
                         $this->printer->bitImage($img);
                         break;
                     case 'DOL_PRINT_QRCODE':
@@ -721,7 +721,7 @@ class dolReceiptPrinter extends Printer
                 }
             }
             // If is DummyPrintConnector send to log to debugging
-			if($this->printer->connector instanceof DummyPrintConnector)
+			if ($this->printer->connector instanceof DummyPrintConnector)
 			{
 				$data = $this->printer->connector->getData();
 				dol_syslog($data);
@@ -743,9 +743,9 @@ class dolReceiptPrinter extends Printer
         global $conf;
         $error = 0;
         $sql = 'SELECT template';
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
-        $sql.= ' WHERE rowid='.$templateid;
-        $sql.= ' AND entity = '.$conf->entity;
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt_template';
+        $sql .= ' WHERE rowid='.$templateid;
+        $sql .= ' AND entity = '.$conf->entity;
         $resql = $this->db->query($sql);
         if ($resql) {
             $obj = $this->db->fetch_array($resql);
@@ -773,11 +773,11 @@ class dolReceiptPrinter extends Printer
     public function initPrinter($printerid)
     {
         global $conf;
-        $error=0;
+        $error = 0;
         $sql = 'SELECT rowid, name, fk_type, fk_profile, parameter';
-        $sql.= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
-        $sql.= ' WHERE rowid = '.$printerid;
-        $sql.= ' AND entity = '.$conf->entity;
+        $sql .= ' FROM '.MAIN_DB_PREFIX.'printer_receipt';
+        $sql .= ' WHERE rowid = '.$printerid;
+        $sql .= ' AND entity = '.$conf->entity;
         $resql = $this->db->query($sql);
         if ($resql) {
             $obj = $this->db->fetch_array($resql);
@@ -789,7 +789,7 @@ class dolReceiptPrinter extends Printer
             $error++;
             $this->errors[] = 'PrinterDontExist';
         }
-        if (! $error) {
+        if (!$error) {
             $parameter = $obj['parameter'];
             try {
                 switch ($obj['fk_type']) {

+ 154 - 154
htdocs/core/class/extrafields.class.php

@@ -232,24 +232,24 @@ class ExtraFields
 		if (empty($attrname)) return -1;
 		if (empty($label)) return -1;
 
-		if ($elementtype == 'thirdparty') $elementtype='societe';
-		if ($elementtype == 'contact') $elementtype='socpeople';
+		if ($elementtype == 'thirdparty') $elementtype = 'societe';
+		if ($elementtype == 'contact') $elementtype = 'socpeople';
 
 		// Create field into database except for separator type which is not stored in database
 		if ($type != 'separate')
 		{
-			$result=$this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $computed, $help);
+			$result = $this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $computed, $help);
 		}
-		$err1=$this->errno;
+		$err1 = $this->errno;
 		if ($result > 0 || $err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' || $type == 'separate')
 		{
 			// Add declaration of field into table
-			$result2=$this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled, $totalizable);
-			$err2=$this->errno;
+			$result2 = $this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled, $totalizable);
+			$err2 = $this->errno;
 			if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS'))
 			{
-				$this->error='';
-				$this->errno=0;
+				$this->error = '';
+				$this->errno = 0;
 				return 1;
 			}
 			else return -2;
@@ -402,56 +402,56 @@ class ExtraFields
 			}
 			else
 			{
-				$params='';
+				$params = '';
 			}
 
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(";
-			$sql.= " name,";
-			$sql.= " label,";
-			$sql.= " type,";
-			$sql.= " pos,";
-			$sql.= " size,";
-			$sql.= " entity,";
-			$sql.= " elementtype,";
-			$sql.= " fieldunique,";
-			$sql.= " fieldrequired,";
-			$sql.= " param,";
-			$sql.= " alwayseditable,";
-			$sql.= " perms,";
-			$sql.= " langs,";
-			$sql.= " list,";
-			$sql.= " fielddefault,";
-			$sql.= " fieldcomputed,";
-			$sql.= " fk_user_author,";
-			$sql.= " fk_user_modif,";
-			$sql.= " datec,";
-			$sql.= " enabled,";
-			$sql.= " help,";
-			$sql.= " totalizable";
-			$sql.= " )";
-			$sql.= " VALUES('".$attrname."',";
-			$sql.= " '".$this->db->escape($label)."',";
-			$sql.= " '".$this->db->escape($type)."',";
-			$sql.= " ".$pos.",";
-			$sql.= " '".$this->db->escape($size)."',";
-			$sql.= " ".($entity===''?$conf->entity:$entity).",";
-			$sql.= " '".$this->db->escape($elementtype)."',";
-			$sql.= " ".$unique.",";
-			$sql.= " ".$required.",";
-			$sql.= " '".$this->db->escape($params)."',";
-			$sql.= " ".$alwayseditable.",";
-			$sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").",";
-			$sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").",";
-			$sql.= " '".$this->db->escape($list)."',";
-			$sql.= " ".($default?"'".$this->db->escape($default)."'":"null").",";
-			$sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").",";
-			$sql .= " " . (is_object($user) ? $user->id : 0). ",";
-			$sql .= " " . (is_object($user) ? $user->id : 0). ",";
-			$sql .= "'" . $this->db->idate(dol_now()) . "',";
-			$sql.= " ".($enabled?"'".$this->db->escape($enabled)."'":"1").",";
-			$sql.= " ".($help?"'".$this->db->escape($help)."'":"null").",";
-			$sql.= " ".($totalizable?'1':'0');
-			$sql.=')';
+			$sql .= " name,";
+			$sql .= " label,";
+			$sql .= " type,";
+			$sql .= " pos,";
+			$sql .= " size,";
+			$sql .= " entity,";
+			$sql .= " elementtype,";
+			$sql .= " fieldunique,";
+			$sql .= " fieldrequired,";
+			$sql .= " param,";
+			$sql .= " alwayseditable,";
+			$sql .= " perms,";
+			$sql .= " langs,";
+			$sql .= " list,";
+			$sql .= " fielddefault,";
+			$sql .= " fieldcomputed,";
+			$sql .= " fk_user_author,";
+			$sql .= " fk_user_modif,";
+			$sql .= " datec,";
+			$sql .= " enabled,";
+			$sql .= " help,";
+			$sql .= " totalizable";
+			$sql .= " )";
+			$sql .= " VALUES('".$attrname."',";
+			$sql .= " '".$this->db->escape($label)."',";
+			$sql .= " '".$this->db->escape($type)."',";
+			$sql .= " ".$pos.",";
+			$sql .= " '".$this->db->escape($size)."',";
+			$sql .= " ".($entity === '' ? $conf->entity : $entity).",";
+			$sql .= " '".$this->db->escape($elementtype)."',";
+			$sql .= " ".$unique.",";
+			$sql .= " ".$required.",";
+			$sql .= " '".$this->db->escape($params)."',";
+			$sql .= " ".$alwayseditable.",";
+			$sql .= " ".($perms ? "'".$this->db->escape($perms)."'" : "null").",";
+			$sql .= " ".($langfile ? "'".$this->db->escape($langfile)."'" : "null").",";
+			$sql .= " '".$this->db->escape($list)."',";
+			$sql .= " ".($default ? "'".$this->db->escape($default)."'" : "null").",";
+			$sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").",";
+			$sql .= " ".(is_object($user) ? $user->id : 0).",";
+			$sql .= " ".(is_object($user) ? $user->id : 0).",";
+			$sql .= "'".$this->db->idate(dol_now())."',";
+			$sql .= " ".($enabled ? "'".$this->db->escape($enabled)."'" : "1").",";
+			$sql .= " ".($help ? "'".$this->db->escape($help)."'" : "null").",";
+			$sql .= " ".($totalizable ? '1' : '0');
+			$sql .= ')';
 
 			dol_syslog(get_class($this)."::create_label", LOG_DEBUG);
 			if ($this->db->query($sql))
@@ -896,55 +896,55 @@ class ExtraFields
 					// We can add this attribute to object. TODO Remove this and return $this->attributes[$elementtype]['label']
 					if ($tab->type != 'separate')
 					{
-						$array_name_label[$tab->name]=$tab->label;
+						$array_name_label[$tab->name] = $tab->label;
 					}
 
 					// Old usage
-					$this->attribute_type[$tab->name]=$tab->type;
-					$this->attribute_label[$tab->name]=$tab->label;
-					$this->attribute_size[$tab->name]=$tab->size;
-					$this->attribute_elementtype[$tab->name]=$tab->elementtype;
-					$this->attribute_default[$tab->name]=$tab->fielddefault;
-					$this->attribute_computed[$tab->name]=$tab->fieldcomputed;
-					$this->attribute_unique[$tab->name]=$tab->fieldunique;
-					$this->attribute_required[$tab->name]=$tab->fieldrequired;
-					$this->attribute_param[$tab->name]=($tab->param ? unserialize($tab->param) : '');
-					$this->attribute_pos[$tab->name]=$tab->pos;
-					$this->attribute_alwayseditable[$tab->name]=$tab->alwayseditable;
-					$this->attribute_perms[$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms);
-					$this->attribute_langfile[$tab->name]=$tab->langs;
-					$this->attribute_list[$tab->name]=$tab->list;
-					$this->attribute_totalizable[$tab->name]=$tab->totalizable;
-					$this->attribute_entityid[$tab->name]=$tab->entity;
+					$this->attribute_type[$tab->name] = $tab->type;
+					$this->attribute_label[$tab->name] = $tab->label;
+					$this->attribute_size[$tab->name] = $tab->size;
+					$this->attribute_elementtype[$tab->name] = $tab->elementtype;
+					$this->attribute_default[$tab->name] = $tab->fielddefault;
+					$this->attribute_computed[$tab->name] = $tab->fieldcomputed;
+					$this->attribute_unique[$tab->name] = $tab->fieldunique;
+					$this->attribute_required[$tab->name] = $tab->fieldrequired;
+					$this->attribute_param[$tab->name] = ($tab->param ? unserialize($tab->param) : '');
+					$this->attribute_pos[$tab->name] = $tab->pos;
+					$this->attribute_alwayseditable[$tab->name] = $tab->alwayseditable;
+					$this->attribute_perms[$tab->name] = (strlen($tab->perms) == 0 ? 1 : $tab->perms);
+					$this->attribute_langfile[$tab->name] = $tab->langs;
+					$this->attribute_list[$tab->name] = $tab->list;
+					$this->attribute_totalizable[$tab->name] = $tab->totalizable;
+					$this->attribute_entityid[$tab->name] = $tab->entity;
 
 					// New usage
-					$this->attributes[$tab->elementtype]['type'][$tab->name]=$tab->type;
-					$this->attributes[$tab->elementtype]['label'][$tab->name]=$tab->label;
-					$this->attributes[$tab->elementtype]['size'][$tab->name]=$tab->size;
-					$this->attributes[$tab->elementtype]['elementtype'][$tab->name]=$tab->elementtype;
-					$this->attributes[$tab->elementtype]['default'][$tab->name]=$tab->fielddefault;
-					$this->attributes[$tab->elementtype]['computed'][$tab->name]=$tab->fieldcomputed;
-					$this->attributes[$tab->elementtype]['unique'][$tab->name]=$tab->fieldunique;
-					$this->attributes[$tab->elementtype]['required'][$tab->name]=$tab->fieldrequired;
-					$this->attributes[$tab->elementtype]['param'][$tab->name]=($tab->param ? unserialize($tab->param) : '');
-					$this->attributes[$tab->elementtype]['pos'][$tab->name]=$tab->pos;
-					$this->attributes[$tab->elementtype]['alwayseditable'][$tab->name]=$tab->alwayseditable;
-					$this->attributes[$tab->elementtype]['perms'][$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms);
-					$this->attributes[$tab->elementtype]['langfile'][$tab->name]=$tab->langs;
-					$this->attributes[$tab->elementtype]['list'][$tab->name]=$tab->list;
-                    $this->attributes[$tab->elementtype]['totalizable'][$tab->name]=$tab->totalizable;
-					$this->attributes[$tab->elementtype]['entityid'][$tab->name]=$tab->entity;
-					$this->attributes[$tab->elementtype]['enabled'][$tab->name]=$tab->enabled;
-					$this->attributes[$tab->elementtype]['help'][$tab->name]=$tab->help;
-
-					$this->attributes[$tab->elementtype]['loaded']=1;
+					$this->attributes[$tab->elementtype]['type'][$tab->name] = $tab->type;
+					$this->attributes[$tab->elementtype]['label'][$tab->name] = $tab->label;
+					$this->attributes[$tab->elementtype]['size'][$tab->name] = $tab->size;
+					$this->attributes[$tab->elementtype]['elementtype'][$tab->name] = $tab->elementtype;
+					$this->attributes[$tab->elementtype]['default'][$tab->name] = $tab->fielddefault;
+					$this->attributes[$tab->elementtype]['computed'][$tab->name] = $tab->fieldcomputed;
+					$this->attributes[$tab->elementtype]['unique'][$tab->name] = $tab->fieldunique;
+					$this->attributes[$tab->elementtype]['required'][$tab->name] = $tab->fieldrequired;
+					$this->attributes[$tab->elementtype]['param'][$tab->name] = ($tab->param ? unserialize($tab->param) : '');
+					$this->attributes[$tab->elementtype]['pos'][$tab->name] = $tab->pos;
+					$this->attributes[$tab->elementtype]['alwayseditable'][$tab->name] = $tab->alwayseditable;
+					$this->attributes[$tab->elementtype]['perms'][$tab->name] = (strlen($tab->perms) == 0 ? 1 : $tab->perms);
+					$this->attributes[$tab->elementtype]['langfile'][$tab->name] = $tab->langs;
+					$this->attributes[$tab->elementtype]['list'][$tab->name] = $tab->list;
+                    $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = $tab->totalizable;
+					$this->attributes[$tab->elementtype]['entityid'][$tab->name] = $tab->entity;
+					$this->attributes[$tab->elementtype]['enabled'][$tab->name] = $tab->enabled;
+					$this->attributes[$tab->elementtype]['help'][$tab->name] = $tab->help;
+
+					$this->attributes[$tab->elementtype]['loaded'] = 1;
 				}
 			}
-			if ($elementtype) $this->attributes[$elementtype]['loaded']=1;	// If nothing found, we also save tag 'loaded'
+			if ($elementtype) $this->attributes[$elementtype]['loaded'] = 1; // If nothing found, we also save tag 'loaded'
 		}
 		else
 		{
-			$this->error=$this->db->lasterror();
+			$this->error = $this->db->lasterror();
 			dol_syslog(get_class($this)."::fetch_name_optionals_label ".$this->error, LOG_ERR);
 		}
 
@@ -1594,60 +1594,60 @@ class ExtraFields
 	 */
 	public function showOutputField($key, $value, $moreparam = '', $extrafieldsobjectkey = '')
 	{
-		global $conf,$langs;
-
-		if (! empty($extrafieldsobjectkey))
-		{
-			$label=$this->attributes[$extrafieldsobjectkey]['label'][$key];
-			$type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
-			$size=$this->attributes[$extrafieldsobjectkey]['size'][$key];
-			$default=$this->attributes[$extrafieldsobjectkey]['default'][$key];
-			$computed=$this->attributes[$extrafieldsobjectkey]['computed'][$key];
-			$unique=$this->attributes[$extrafieldsobjectkey]['unique'][$key];
-			$required=$this->attributes[$extrafieldsobjectkey]['required'][$key];
-			$param=$this->attributes[$extrafieldsobjectkey]['param'][$key];
-			$perms=dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
-			$langfile=$this->attributes[$extrafieldsobjectkey]['langfile'][$key];
-			$list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
-			$help=$this->attributes[$extrafieldsobjectkey]['help'][$key];
-			$hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
+		global $conf, $langs;
+
+		if (!empty($extrafieldsobjectkey))
+		{
+			$label = $this->attributes[$extrafieldsobjectkey]['label'][$key];
+			$type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
+			$size = $this->attributes[$extrafieldsobjectkey]['size'][$key];
+			$default = $this->attributes[$extrafieldsobjectkey]['default'][$key];
+			$computed = $this->attributes[$extrafieldsobjectkey]['computed'][$key];
+			$unique = $this->attributes[$extrafieldsobjectkey]['unique'][$key];
+			$required = $this->attributes[$extrafieldsobjectkey]['required'][$key];
+			$param = $this->attributes[$extrafieldsobjectkey]['param'][$key];
+			$perms = dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
+			$langfile = $this->attributes[$extrafieldsobjectkey]['langfile'][$key];
+			$list = dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
+			$help = $this->attributes[$extrafieldsobjectkey]['help'][$key];
+			$hidden = (empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
 		}
 		else	// Old usage
 		{
 			//dol_syslog("Warning: parameter 'extrafieldsobjectkey' is missing", LOG_WARNING);
-			$label=$this->attribute_label[$key];
-			$type=$this->attribute_type[$key];
-			$size=$this->attribute_size[$key];
-			$default=$this->attribute_default[$key];
-			$computed=$this->attribute_computed[$key];
-			$unique=$this->attribute_unique[$key];
-			$required=$this->attribute_required[$key];
-			$param=$this->attribute_param[$key];
-			$perms=dol_eval($this->attribute_perms[$key], 1);
-			$langfile=$this->attribute_langfile[$key];
-			$list=dol_eval($this->attribute_list[$key], 1);
-			$help='';	// Not supported with old syntax
-			$hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
-		}
-
-		if ($hidden) return '';		// This is a protection. If field is hidden, we should just not call this method.
+			$label = $this->attribute_label[$key];
+			$type = $this->attribute_type[$key];
+			$size = $this->attribute_size[$key];
+			$default = $this->attribute_default[$key];
+			$computed = $this->attribute_computed[$key];
+			$unique = $this->attribute_unique[$key];
+			$required = $this->attribute_required[$key];
+			$param = $this->attribute_param[$key];
+			$perms = dol_eval($this->attribute_perms[$key], 1);
+			$langfile = $this->attribute_langfile[$key];
+			$list = dol_eval($this->attribute_list[$key], 1);
+			$help = ''; // Not supported with old syntax
+			$hidden = (empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
+		}
+
+		if ($hidden) return ''; // This is a protection. If field is hidden, we should just not call this method.
 
 		//if ($computed) $value =		// $value is already calculated into $value before calling this method
 
-		$showsize=0;
+		$showsize = 0;
 		if ($type == 'date')
 		{
-			$showsize=10;
-			$value=dol_print_date($value, 'day');
+			$showsize = 10;
+			$value = dol_print_date($value, 'day');
 		}
 		elseif ($type == 'datetime')
 		{
-			$showsize=19;
-			$value=dol_print_date($value, 'dayhour');
+			$showsize = 19;
+			$value = dol_print_date($value, 'dayhour');
 		}
 		elseif ($type == 'int')
 		{
-			$showsize=10;
+			$showsize = 10;
 		}
 		elseif ($type == 'double')
 		{
@@ -1802,20 +1802,20 @@ class ExtraFields
 				$keyList .= implode(', ', $fields_label);
 			}
 
-			$sql = 'SELECT ' . $keyList;
-			$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
+			$sql = 'SELECT '.$keyList;
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
 			if (strpos($InfoFieldList[4], 'extra') !== false) {
 				$sql .= ' as main';
 			}
 			// $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
 			// $sql.= ' AND entity = '.$conf->entity;
 
-			dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst', LOG_DEBUG);
+			dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
 			$resql = $this->db->query($sql);
 			if ($resql) {
 				$value = ''; // value was used, so now we reste it to use it to build final output
-				$toprint=array();
-				while ( $obj = $this->db->fetch_object($resql) ) {
+				$toprint = array();
+				while ($obj = $this->db->fetch_object($resql)) {
 					// Several field into label (eq table:code|libelle:rowid)
 					$fields_label = explode('|', $InfoFieldList[1]);
 					if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
@@ -2068,35 +2068,35 @@ class ExtraFields
 				{
 					// Clean parameters
 					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
-					$value_key=dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
+					$value_key = dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
 				}
 				elseif (in_array($key_type, array('datetime')))
 				{
 					// Clean parameters
 					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
-					$value_key=dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
+					$value_key = dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
 				}
-				elseif (in_array($key_type, array('checkbox','chkbxlst')))
+				elseif (in_array($key_type, array('checkbox', 'chkbxlst')))
 				{
-					$value_arr=GETPOST("options_".$key, 'array'); // check if an array
+					$value_arr = GETPOST("options_".$key, 'array'); // check if an array
 					if (!empty($value_arr)) {
-						$value_key=implode($value_arr, ',');
-					}else {
-						$value_key='';
+						$value_key = implode($value_arr, ',');
+					} else {
+						$value_key = '';
 					}
 				}
-				elseif (in_array($key_type, array('price','double')))
+				elseif (in_array($key_type, array('price', 'double')))
 				{
-					$value_arr=GETPOST("options_".$key, 'alpha');
-					$value_key=price2num($value_arr);
+					$value_arr = GETPOST("options_".$key, 'alpha');
+					$value_key = price2num($value_arr);
 				}
 				else
 				{
-					$value_key=GETPOST("options_".$key);
+					$value_key = GETPOST("options_".$key);
 					if (in_array($key_type, array('link')) && $value_key == '-1') $value_key = '';
 				}
 
-				$object->array_options["options_".$key]=$value_key;
+				$object->array_options["options_".$key] = $value_key;
 			}
 
 			if ($nofillrequired) {
@@ -2149,13 +2149,13 @@ class ExtraFields
 
 				if (in_array($key_type, array('date', 'datetime')))
 				{
-					if (! GETPOSTISSET($keysuffix."options_".$key.$keyprefix)."year") continue;	// Value was not provided, we should not set it.
+					if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)."year") continue; // Value was not provided, we should not set it.
 					// Clean parameters
 					$value_key = dol_mktime(GETPOST($keysuffix."options_".$key.$keyprefix."hour", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."min", 'int'), 0, GETPOST($keysuffix."options_".$key.$keyprefix."month", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."day", 'int'), GETPOST($keysuffix."options_".$key.$keyprefix."year", 'int'));
 				}
 				elseif (in_array($key_type, array('checkbox', 'chkbxlst')))
 				{
-					if (! GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue;	// Value was not provided, we should not set it.
+					if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue; // Value was not provided, we should not set it.
 					$value_arr = GETPOST($keysuffix."options_".$key.$keyprefix);
 					// Make sure we get an array even if there's only one checkbox
 					$value_arr = (array) $value_arr;
@@ -2163,13 +2163,13 @@ class ExtraFields
 				}
 				elseif (in_array($key_type, array('price', 'double', 'int')))
 				{
-					if (! GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue;	// Value was not provided, we should not set it.
+					if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue; // Value was not provided, we should not set it.
 					$value_arr = GETPOST($keysuffix."options_".$key.$keyprefix);
 					$value_key = price2num($value_arr);
 				}
 				else
 				{
-					if (! GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue;	// Value was not provided, we should not set it.
+					if (!GETPOSTISSET($keysuffix."options_".$key.$keyprefix)) continue; // Value was not provided, we should not set it.
 					$value_key = GETPOST($keysuffix."options_".$key.$keyprefix);
 				}
 

+ 3 - 3
htdocs/core/class/html.form.class.php

@@ -767,7 +767,7 @@ class Form
 				{
 					//if (empty($showempty) && empty($row['rowid'])) continue;
 					if (empty($row['rowid'])) continue;
-					if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) continue;	// exclude some countries
+					if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) continue; // exclude some countries
 
 					if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
 					if (empty($row['favorite']) && $atleastonefavorite)
@@ -2643,7 +2643,7 @@ class Form
     			    $langs->load("stocks");
 
     			    $tmpproduct = new Product($this->db);
-    			    $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1);	// Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
+    			    $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
     			    $tmpproduct->load_virtual_stock();
     			    $virtualstock = $tmpproduct->stock_theorique;
 
@@ -6242,7 +6242,7 @@ class Form
 				if (is_array($id)) {
 					if (in_array($key, $id) && !$disabled) $out .= ' selected'; // To preselect a value
 				} else {
-					$id = (string) $id;	// if $id = 0, then $id = '0'
+					$id = (string) $id; // if $id = 0, then $id = '0'
 					if ($id != '' && $id == $key && !$disabled) $out .= ' selected'; // To preselect a value
 				}
 				if ($nohtmlescape) $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';

+ 3 - 3
htdocs/core/class/html.formaccounting.class.php

@@ -309,7 +309,7 @@ class FormAccounting extends Form
     			return -1;
     		}
 
-    		$selected = $selectid;	// selectid can be -1, 0, 123
+    		$selected = $selectid; // selectid can be -1, 0, 123
     		while ($obj = $this->db->fetch_object($resql))
     		{
 				if (empty($obj->labelshort))
@@ -321,7 +321,7 @@ class FormAccounting extends Form
 					$labeltoshow = $obj->labelshort;
 				}
 
-				$label = length_accountg($obj->account_number) . ' - ' . $labeltoshow;
+				$label = length_accountg($obj->account_number).' - '.$labeltoshow;
 				$label = dol_trunc($label, $trunclength);
 
     			$select_value_in = $obj->rowid;
@@ -459,7 +459,7 @@ class FormAccounting extends Form
 
 		$sql = "SELECT DISTINCT date_format(doc_date, '%Y') as dtyear";
 		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping";
-	    $sql .= " WHERE entity IN (" . getEntity('accountancy') . ")";
+	    $sql .= " WHERE entity IN (".getEntity('accountancy').")";
 		$sql .= " ORDER BY date_format(doc_date, '%Y')";
 		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
 		$resql = $this->db->query($sql);

+ 192 - 192
htdocs/core/class/smtps.class.php

@@ -117,10 +117,10 @@ class SMTPs
     /**
      * Message Sensitivity
      */
-    private $_arySensitivity = array ( false,
+    private $_arySensitivity = array(false,
                                   'Personal',
                                   'Private',
-                                  'Company Confidential' );
+                                  'Company Confidential');
 
     /**
      * Message Sensitivity
@@ -131,12 +131,12 @@ class SMTPs
     /**
      * Message Priority
      */
-    private $_aryPriority = array ( 'Bulk',
+    private $_aryPriority = array('Bulk',
                                 'Highest',
                                 'High',
                                 'Normal',
                                 'Low',
-                                'Lowest' );
+                                'Lowest');
 
     /**
      * Content-Transfer-Encoding
@@ -147,13 +147,13 @@ class SMTPs
     /**
      * Content-Transfer-Encoding
      */
-    private $_smtpsTransEncodeTypes = array( '7bit',               // Simple 7-bit ASCII
-                                         '8bit',               // 8-bit coding with line termination characters
-                                         'base64',             // 3 octets encoded into 4 sextets with offset
-                                         'binary',             // Arbitrary binary stream
-                                         'mac-binhex40',       // Macintosh binary to hex encoding
-                                         'quoted-printable',   // Mostly 7-bit, with 8-bit characters encoded as "=HH"
-                                         'uuencode' );         // UUENCODE encoding
+    private $_smtpsTransEncodeTypes = array('7bit', // Simple 7-bit ASCII
+                                         '8bit', // 8-bit coding with line termination characters
+                                         'base64', // 3 octets encoded into 4 sextets with offset
+                                         'binary', // Arbitrary binary stream
+                                         'mac-binhex40', // Macintosh binary to hex encoding
+                                         'quoted-printable', // Mostly 7-bit, with 8-bit characters encoded as "=HH"
+                                         'uuencode'); // UUENCODE encoding
 
     /**
      * Content-Transfer-Encoding
@@ -300,7 +300,7 @@ class SMTPs
      */
     public function setErrorsTo($_strErrorsTo)
     {
-        if ( $_strErrorsTo )
+        if ($_strErrorsTo)
         $this->_errorsTo = $this->_strip_email($_strErrorsTo);
     }
 
@@ -314,7 +314,7 @@ class SMTPs
     {
         $_retValue = '';
 
-        if ( $_part === true )
+        if ($_part === true)
         $_retValue = $this->_errorsTo;
         else
         $_retValue = $this->_errorsTo[$_part];
@@ -359,29 +359,29 @@ class SMTPs
         // We have to make sure the HOST given is valid
         // This is done here because '@fsockopen' will not give me this
         // information if it failes to connect because it can't find the HOST
-        $host=$this->getHost();
+        $host = $this->getHost();
         $usetls = preg_match('@tls://@i', $host);
 
-        $host=preg_replace('@tcp://@i', '', $host);	// Remove prefix
-        $host=preg_replace('@ssl://@i', '', $host);	// Remove prefix
-        $host=preg_replace('@tls://@i', '', $host);	// Remove prefix
+        $host = preg_replace('@tcp://@i', '', $host); // Remove prefix
+        $host = preg_replace('@ssl://@i', '', $host); // Remove prefix
+        $host = preg_replace('@tls://@i', '', $host); // Remove prefix
 
         // @CHANGE LDR
         include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 
-        if ( (! is_ip($host)) && ((gethostbyname($host)) == $host))
+        if ((!is_ip($host)) && ((gethostbyname($host)) == $host))
         {
-            $this->_setErr(99, $host . ' is either offline or is an invalid host name.');
+            $this->_setErr(99, $host.' is either offline or is an invalid host name.');
             $_retVal = false;
         }
         else
         {
             //See if we can connect to the SMTP server
             if ($this->socket = @fsockopen(
-                preg_replace('@tls://@i', '', $this->getHost()),       // Host to 'hit', IP or domain
-                $this->getPort(),       // which Port number to use
-                $this->errno,           // actual system level error
-                $this->errstr,          // and any text that goes with the error
+                preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain
+                $this->getPort(), // which Port number to use
+                $this->errno, // actual system level error
+                $this->errstr, // and any text that goes with the error
                 $this->_smtpTimeout     // timeout for reading/writing data over the socket
             )) {
                 // Fix from PHP SMTP class by 'Chris Ryan'
@@ -391,14 +391,14 @@ class SMTPs
                 if (function_exists('stream_set_timeout')) stream_set_timeout($this->socket, $this->_smtpTimeout, 0);
 
                 // Check response from Server
-                if ( $_retVal = $this->server_parse($this->socket, "220") )
+                if ($_retVal = $this->server_parse($this->socket, "220"))
                 $_retVal = $this->socket;
             }
             // This connection attempt failed.
             else
             {
                 // @CHANGE LDR
-                if (empty($this->errstr)) $this->errstr='Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
+                if (empty($this->errstr)) $this->errstr = 'Failed to connect with fsockopen host='.$this->getHost().' port='.$this->getPort();
                 $this->_setErr($this->errno, $this->errstr);
                 $_retVal = false;
             }
@@ -421,18 +421,18 @@ class SMTPs
         // Send the RFC2554 specified EHLO.
         // This improvment as provided by 'SirSir' to
         // accomodate both SMTP AND ESMTP capable servers
-        $host=$this->getHost();
+        $host = $this->getHost();
         $usetls = preg_match('@tls://@i', $host);
 
-        $host=preg_replace('@tcp://@i', '', $host);	// Remove prefix
-        $host=preg_replace('@ssl://@i', '', $host);	// Remove prefix
-        $host=preg_replace('@tls://@i', '', $host);	// Remove prefix
+        $host = preg_replace('@tcp://@i', '', $host); // Remove prefix
+        $host = preg_replace('@ssl://@i', '', $host); // Remove prefix
+        $host = preg_replace('@tls://@i', '', $host); // Remove prefix
 
-        if ($usetls) $host='tls://'.$host;
+        if ($usetls) $host = 'tls://'.$host;
 
         $hosth = $host;
 
-        if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
+        if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
         {
             // If the from to is 'aaa <bbb@ccc.com>', we will keep 'ccc.com'
             $hosth = $this->getFrom('addr');
@@ -441,7 +441,7 @@ class SMTPs
             $hosth = preg_replace('/.*@/', '', $hosth);
         }
 
-        if ( $_retVal = $this->socket_send_str('EHLO ' . $hosth, '250') )
+        if ($_retVal = $this->socket_send_str('EHLO '.$hosth, '250'))
         {
             if ($usetls)
             {
@@ -492,7 +492,7 @@ class SMTPs
                 // the answer with list of supported AUTH methods. They may differs between non STARTTLS and with STARTTLS.
                 if (!$_retVal = $this->socket_send_str('EHLO '.$host, '250'))
                 {
-                    $this->_setErr(126, '"' . $host . '" does not support authenticated connections.');
+                    $this->_setErr(126, '"'.$host.'" does not support authenticated connections.');
                     return $_retVal;
                 }
             }
@@ -506,7 +506,7 @@ class SMTPs
                 case 'PLAIN':
                     $this->socket_send_str('AUTH PLAIN', '334');
                     // The error here just means the ID/password combo doesn't work.
-                    $_retVal = $this->socket_send_str(base64_encode("\0" . $this->_smtpsID . "\0" . $this->_smtpsPW), '235');
+                    $_retVal = $this->socket_send_str(base64_encode("\0".$this->_smtpsID."\0".$this->_smtpsPW), '235');
                     break;
                 case 'LOGIN':	// most common case
                 default:
@@ -518,13 +518,13 @@ class SMTPs
                     $_retVal = $this->socket_send_str(base64_encode($this->_smtpsPW), '235');
                     break;
             }
-            if (! $_retVal) {
+            if (!$_retVal) {
                 $this->_setErr(130, 'Invalid Authentication Credentials.');
 			}
         }
         else
         {
-            $this->_setErr(126, '"' . $host . '" does not support authenticated connections.');
+            $this->_setErr(126, '"'.$host.'" does not support authenticated connections.');
         }
 
         return $_retVal;
@@ -548,10 +548,10 @@ class SMTPs
         $_retVal = false;
 
         // Connect to Server
-        if ( $this->socket = $this->_server_connect() )
+        if ($this->socket = $this->_server_connect())
         {
             // If a User ID *and* a password is given, assume Authentication is desired
-            if( !empty($this->_smtpsID) && !empty($this->_smtpsPW) )
+            if (!empty($this->_smtpsID) && !empty($this->_smtpsPW))
             {
                 // Send the RFC2554 specified EHLO.
                 $_retVal = $this->_server_authenticate();
@@ -561,16 +561,16 @@ class SMTPs
             else
             {
                 // Send the RFC821 specified HELO.
-                $host=$this->getHost();
+                $host = $this->getHost();
                 $usetls = preg_match('@tls://@i', $host);
 
-                $host=preg_replace('@tcp://@i', '', $host);	// Remove prefix
-                $host=preg_replace('@ssl://@i', '', $host);	// Remove prefix
-                $host=preg_replace('@tls://@i', '', $host);	// Remove prefix
+                $host = preg_replace('@tcp://@i', '', $host); // Remove prefix
+                $host = preg_replace('@ssl://@i', '', $host); // Remove prefix
+                $host = preg_replace('@tls://@i', '', $host); // Remove prefix
 
                 $hosth = $host;
 
-                if (! empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
+                if (!empty($conf->global->MAIL_SMTP_USE_FROM_FOR_HELO))
                 {
                     // If the from to is 'aaa <bbb@ccc.com>', we will keep 'ccc.com'
                     $hosth = $this->getFrom('addr');
@@ -579,17 +579,17 @@ class SMTPs
                     $hosth = preg_replace('/.*@/', '', $hosth);
                 }
 
-                $_retVal = $this->socket_send_str('HELO ' . $hosth, '250');
+                $_retVal = $this->socket_send_str('HELO '.$hosth, '250');
             }
 
             // Well, did we get to the server?
-            if ( $_retVal )
+            if ($_retVal)
             {
                 // From this point onward most server response codes should be 250
                 // Specify who the mail is from....
                 // This has to be the raw email address, strip the "name" off
-                $resultmailfrom = $this->socket_send_str('MAIL FROM: ' . $this->getFrom('addr'), '250');
-			    if (! $resultmailfrom) {
+                $resultmailfrom = $this->socket_send_str('MAIL FROM: '.$this->getFrom('addr'), '250');
+			    if (!$resultmailfrom) {
 			        fclose($this->socket);
 			        return false;
 			    }
@@ -613,7 +613,7 @@ class SMTPs
                      * mark the last address as "bad" and start the address loop over again.
                      * If any address fails, the entire message fails.
                      */
-                    $this->socket_send_str('RCPT TO: <' . $_address . '>', '250');
+                    $this->socket_send_str('RCPT TO: <'.$_address.'>', '250');
                 }
 
                 // Tell the server we are ready to start sending data
@@ -623,7 +623,7 @@ class SMTPs
 
                 // Now we are ready for the message...
                 // Ok, all the ingredients are mixed in let's cook this puppy...
-                $this->socket_send_str($this->getHeader().$this->getBodyContent() . "\r\n" . '.', '250');
+                $this->socket_send_str($this->getHeader().$this->getBodyContent()."\r\n".'.', '250');
 
                 // Now tell the server we are done and close the socket...
                 fputs($this->socket, 'QUIT');
@@ -673,13 +673,13 @@ class SMTPs
         $_retVal = true;
 
         // if we have a path...
-        if ( ! empty($_strConfigPath) )
+        if (!empty($_strConfigPath))
         {
             // If the path is not valid, this will NOT generate an error,
             // it will simply return false.
-            if ( ! @include $_strConfigPath)
+            if (!@include $_strConfigPath)
             {
-                $this->_setErr(110, '"' . $_strConfigPath . '" is not a valid path.');
+                $this->_setErr(110, '"'.$_strConfigPath.'" is not a valid path.');
                 $_retVal = false;
             }
         }
@@ -689,13 +689,13 @@ class SMTPs
         {
             // Set these properties ONLY if they are set in the php.ini file.
             // Otherwise the default values will be used.
-            if ( $_host = ini_get('SMTPs') )
+            if ($_host = ini_get('SMTPs'))
             $this->setHost($_host);
 
-            if ( $_port = ini_get('smtp_port') )
+            if ($_port = ini_get('smtp_port'))
             $this->setPort($_port);
 
-            if ( $_from = ini_get('sendmail_from') )
+            if ($_from = ini_get('sendmail_from'))
             $this->setFrom($_from);
         }
 
@@ -757,7 +757,7 @@ class SMTPs
      */
     public function setHost($_strHost)
     {
-        if ( $_strHost )
+        if ($_strHost)
         $this->_smtpsHost = $_strHost;
     }
 
@@ -782,8 +782,8 @@ class SMTPs
      */
     public function setPort($_intPort)
     {
-        if ( ( is_numeric($_intPort) ) &&
-        ( ( $_intPort >= 1 ) && ( $_intPort <= 65536 ) ) )
+        if ((is_numeric($_intPort)) &&
+        (($_intPort >= 1) && ($_intPort <= 65536)))
         $this->_smtpsPort = $_intPort;
     }
 
@@ -849,7 +849,7 @@ class SMTPs
      */
     public function setCharSet($_strCharSet)
     {
-        if ( $_strCharSet )
+        if ($_strCharSet)
         $this->_smtpsCharSet = $_strCharSet;
     }
 
@@ -937,7 +937,7 @@ class SMTPs
      */
     public function setFrom($_strFrom)
     {
-        if ( $_strFrom )
+        if ($_strFrom)
         $this->_msgFrom = $this->_strip_email($_strFrom);
     }
 
@@ -951,7 +951,7 @@ class SMTPs
     {
         $_retValue = '';
 
-        if ( $_part === true )
+        if ($_part === true)
         $_retValue = $this->_msgFrom;
         else
         $_retValue = $this->_msgFrom[$_part];
@@ -967,7 +967,7 @@ class SMTPs
      */
     public function setReplyTo($_strReplyTo)
     {
-        if ( $_strReplyTo )
+        if ($_strReplyTo)
             $this->_msgReplyTo = $this->_strip_email($_strReplyTo);
     }
 
@@ -981,7 +981,7 @@ class SMTPs
     {
         $_retValue = '';
 
-        if ( $_part === true )
+        if ($_part === true)
             $_retValue = $this->_msgReplyTo;
         else
             $_retValue = $this->_msgReplyTo[$_part];
@@ -1007,13 +1007,13 @@ class SMTPs
         $aryHost = $this->_msgRecipients;
 
         // Only run this if we have something
-        if ( !empty($_addrList))
+        if (!empty($_addrList))
         {
             // $_addrList can be a STRING or an array
-            if ( is_string($_addrList) )
+            if (is_string($_addrList))
             {
                 // This could be a COMMA delimited string
-                if ( strstr($_addrList, ',') )
+                if (strstr($_addrList, ','))
                 // "explode "list" into an array
                 $_addrList = explode(',', $_addrList);
 
@@ -1033,7 +1033,7 @@ class SMTPs
                 $_tmpaddr = explode('<', $_strAddr);
 
                 // We have a "Real Name" and eMail address
-                if ( count($_tmpaddr) == 2 )
+                if (count($_tmpaddr) == 2)
                 {
                     $_tmpHost = explode('@', $_tmpaddr[1]);
                     $_tmpaddr[0] = trim($_tmpaddr[0], ' ">');
@@ -1090,10 +1090,10 @@ class SMTPs
         $_tmpAry = explode('<', $_strAddr);
 
         // Do we have a "Real name"
-        if ( count($_tmpAry) == 2 )
+        if (count($_tmpAry) == 2)
         {
             // We may not really have a "Real Name"
-            if ( $_tmpAry[0])
+            if ($_tmpAry[0])
             $_aryEmail['real'] = trim($_tmpAry[0], ' ">');
 
             $_aryEmail['addr'] = $_tmpAry[1];
@@ -1102,10 +1102,10 @@ class SMTPs
         $_aryEmail['addr'] = $_tmpAry[0];
 
         // Pull User Name and Host.tld apart
-        list($_aryEmail['user'], $_aryEmail['host'] ) = explode('@', $_aryEmail['addr']);
+        list($_aryEmail['user'], $_aryEmail['host']) = explode('@', $_aryEmail['addr']);
 
         // Put the brackets back around the address
-        $_aryEmail['addr'] = '<' . $_aryEmail['addr'] . '>';
+        $_aryEmail['addr'] = '<'.$_aryEmail['addr'].'>';
 
         return $_aryEmail;
     }
@@ -1124,7 +1124,7 @@ class SMTPs
         /**
          * An array of bares addresses for use with 'RCPT TO:'
          */
-        $_RCPT_list=array();
+        $_RCPT_list = array();
 
         // walk down Recipients array and pull just email addresses
         foreach ($this->_msgRecipients as $_host => $_list)
@@ -1134,7 +1134,7 @@ class SMTPs
                 foreach ($_subList as $_name => $_addr)
                 {
                     // build RCPT list
-                    $_RCPT_list[] = $_name . '@' . $_host;
+                    $_RCPT_list[] = $_name.'@'.$_host;
                 }
             }
         }
@@ -1153,27 +1153,27 @@ class SMTPs
     {
         // phpcs:enable
         // We need to know which address segment to pull
-        if ( $_which )
+        if ($_which)
         {
             // Make sure we have addresses to process
-            if ( $this->_msgRecipients )
+            if ($this->_msgRecipients)
             {
-                $_RCPT_list=array();
+                $_RCPT_list = array();
                 // walk down Recipients array and pull just email addresses
                 foreach ($this->_msgRecipients as $_host => $_list)
                 {
-                    if ( $this->_msgRecipients[$_host][$_which] )
+                    if ($this->_msgRecipients[$_host][$_which])
                     {
                         foreach ($this->_msgRecipients[$_host][$_which] as $_addr => $_realName)
                         {
-                            if ( $_realName )	// @CHANGE LDR
+                            if ($_realName)	// @CHANGE LDR
                             {
-                                $_realName = '"' . $_realName . '"';
-                                $_RCPT_list[] = $_realName . ' <' . $_addr . '@' . $_host . '>';
+                                $_realName = '"'.$_realName.'"';
+                                $_RCPT_list[] = $_realName.' <'.$_addr.'@'.$_host.'>';
                             }
                             else
                             {
-                                $_RCPT_list[] = $_addr . '@' . $_host;
+                                $_RCPT_list[] = $_addr.'@'.$_host;
                             }
                         }
                     }
@@ -1202,7 +1202,7 @@ class SMTPs
      */
     public function setTO($_addrTo)
     {
-        if ( $_addrTo )
+        if ($_addrTo)
         $this->_buildAddrList('to', $_addrTo);
     }
 
@@ -1224,7 +1224,7 @@ class SMTPs
      */
     public function setCC($_strCC)
     {
-        if ( $_strCC )
+        if ($_strCC)
         $this->_buildAddrList('cc', $_strCC);
     }
 
@@ -1246,7 +1246,7 @@ class SMTPs
      */
     public function setBCC($_strBCC)
     {
-        if ( $_strBCC )
+        if ($_strBCC)
         $this->_buildAddrList('bcc', $_strBCC);
     }
 
@@ -1268,7 +1268,7 @@ class SMTPs
      */
     public function setSubject($_strSubject = '')
     {
-        if ( $_strSubject )
+        if ($_strSubject)
         $this->_msgSubject = $_strSubject;
     }
 
@@ -1291,11 +1291,11 @@ class SMTPs
     {
         global $conf;
 
-        $_header = 'From: '       . $this->getFrom('org') . "\r\n"
-        . 'To: '         . $this->getTO()          . "\r\n";
+        $_header = 'From: '.$this->getFrom('org')."\r\n"
+        . 'To: '.$this->getTO()."\r\n";
 
-        if ( $this->getCC() )
-        $_header .= 'Cc: ' . $this->getCC()  . "\r\n";
+        if ($this->getCC())
+        $_header .= 'Cc: '.$this->getCC()."\r\n";
 
         /* Note:
          * BCC email addresses must be listed in the RCPT TO command list,
@@ -1308,50 +1308,50 @@ class SMTPs
         $_header .= 'Bcc: ' . $this->getBCC()  . "\r\n";
         */
 
-        $host=dol_getprefix('email');
+        $host = dol_getprefix('email');
 
         //NOTE: Message-ID should probably contain the username of the user who sent the msg
-        $_header .= 'Subject: '    . $this->getSubject()     . "\r\n";
-        $_header .= 'Date: '       . date("r")               . "\r\n";
+        $_header .= 'Subject: '.$this->getSubject()."\r\n";
+        $_header .= 'Date: '.date("r")."\r\n";
 
         $trackid = $this->getTrackId();
         if ($trackid)
         {
             // References is kept in response and Message-ID is returned into In-Reply-To:
-            $_header .= 'Message-ID: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
-            $_header .= 'References: <' . time() . '.SMTPs-dolibarr-'.$trackid.'@' . $host . ">\r\n";
-            $_header .= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host . "\r\n";
+            $_header .= 'Message-ID: <'.time().'.SMTPs-dolibarr-'.$trackid.'@'.$host.">\r\n";
+            $_header .= 'References: <'.time().'.SMTPs-dolibarr-'.$trackid.'@'.$host.">\r\n";
+            $_header .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host."\r\n";
         }
         else
         {
-            $_header .= 'Message-ID: <' . time() . '.SMTPs@' . $host . ">\r\n";
+            $_header .= 'Message-ID: <'.time().'.SMTPs@'.$host.">\r\n";
         }
-        if (! empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. "\r\n";
-        if ( $this->getMoreInHeader() )
-            $_header .= $this->getMoreInHeader();     // Value must include the "\r\n";
+        if (!empty($_SERVER['REMOTE_ADDR'])) $_header .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR']."\r\n";
+        if ($this->getMoreInHeader())
+            $_header .= $this->getMoreInHeader(); // Value must include the "\r\n";
 
         //$_header .=
         //                 'Read-Receipt-To: '   . $this->getFrom( 'org' ) . "\r\n"
         //                 'Return-Receipt-To: ' . $this->getFrom( 'org' ) . "\r\n";
 
-        if ( $this->getSensitivity() )
-        $_header .= 'Sensitivity: ' . $this->getSensitivity()  . "\r\n";
+        if ($this->getSensitivity())
+        $_header .= 'Sensitivity: '.$this->getSensitivity()."\r\n";
 
-        if ( $this->_msgPriority != 3 )
+        if ($this->_msgPriority != 3)
         $_header .= $this->getPriority();
 
 
         // @CHANGE LDR
-        if ( $this->getDeliveryReceipt() )
-            $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr') . "\r\n";
-        if ( $this->getErrorsTo() )
-            $_header .= 'Errors-To: '.$this->getErrorsTo('addr') . "\r\n";
-        if ( $this->getReplyTo() )
-            $_header .= "Reply-To: ".$this->getReplyTo('addr') ."\r\n";
+        if ($this->getDeliveryReceipt())
+            $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr')."\r\n";
+        if ($this->getErrorsTo())
+            $_header .= 'Errors-To: '.$this->getErrorsTo('addr')."\r\n";
+        if ($this->getReplyTo())
+            $_header .= "Reply-To: ".$this->getReplyTo('addr')."\r\n";
 
-        $_header .= 'X-Mailer: Dolibarr version ' . DOL_VERSION .' (using SMTPs Mailer)' . "\r\n";
-        $_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART?'MAIN_MAIL_USE_MULTI_PART':'No MAIN_MAIL_USE_MULTI_PART') . "\r\n";
-        $_header .= 'Mime-Version: 1.0' . "\r\n";
+        $_header .= 'X-Mailer: Dolibarr version '.DOL_VERSION.' (using SMTPs Mailer)'."\r\n";
+        $_header .= 'X-Dolibarr-Option: '.($conf->global->MAIN_MAIL_USE_MULTI_PART ? 'MAIN_MAIL_USE_MULTI_PART' : 'No MAIN_MAIL_USE_MULTI_PART')."\r\n";
+        $_header .= 'Mime-Version: 1.0'."\r\n";
 
 
         return $_header;
@@ -1368,7 +1368,7 @@ class SMTPs
     {
         //if ( $strContent )
         //{
-        if ( $strType == 'html' )
+        if ($strType == 'html')
         $strMimeType = 'text/html';
         else
         $strMimeType = 'text/plain';
@@ -1387,7 +1387,7 @@ class SMTPs
 
         // Make RFC2045 Compliant
         //$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
-        $strContent = rtrim(wordwrap($strContent, 75, "\r\n"));   // TODO Using this method creates unexpected line break on text/plain content.
+        $strContent = rtrim(wordwrap($strContent, 75, "\r\n")); // TODO Using this method creates unexpected line break on text/plain content.
 
         $this->_msgContent[$strType] = array();
 
@@ -1395,7 +1395,7 @@ class SMTPs
         $this->_msgContent[$strType]['data']     = $strContent;
         $this->_msgContent[$strType]['dataText'] = $strContentAltText;
 
-        if ( $this->getMD5flag() )
+        if ($this->getMD5flag())
         $this->_msgContent[$strType]['md5']      = dol_hash($strContent, 3);
         //}
     }
@@ -1419,49 +1419,49 @@ class SMTPs
         $keyCount = count($_types);
 
         // If we have ZERO, we have a problem
-        if( $keyCount === 0 )
+        if ($keyCount === 0)
         die("Sorry, no content");
 
         // If we have ONE, we can use the simple format
-        elseif( $keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
+        elseif ($keyCount === 1 && empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
         {
             $_msgData = $this->_msgContent;
             $_msgData = $_msgData[$_types[0]];
 
-            $content = 'Content-Type: ' . $_msgData['mimeType'] . '; charset="' . $this->getCharSet() . '"' . "\r\n"
-            . 'Content-Transfer-Encoding: ' . $this->getTransEncodeType() . "\r\n"
-            . 'Content-Disposition: inline'  . "\r\n"
-            . 'Content-Description: Message' . "\r\n";
+            $content = 'Content-Type: '.$_msgData['mimeType'].'; charset="'.$this->getCharSet().'"'."\r\n"
+            . 'Content-Transfer-Encoding: '.$this->getTransEncodeType()."\r\n"
+            . 'Content-Disposition: inline'."\r\n"
+            . 'Content-Description: Message'."\r\n";
 
-            if ( $this->getMD5flag() )
-            $content .= 'Content-MD5: ' . $_msgData['md5'] . "\r\n";
+            if ($this->getMD5flag())
+            $content .= 'Content-MD5: '.$_msgData['md5']."\r\n";
 
             $content .= "\r\n"
-            .  $_msgData['data'] . "\r\n";
+            .  $_msgData['data']."\r\n";
         }
 
         // If we have more than ONE, we use the multi-part format
-        elseif( $keyCount >= 1 || ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
+        elseif ($keyCount >= 1 || !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))
         {
             // Since this is an actual multi-part message
             // We need to define a content message Boundary
             // NOTE: This was 'multipart/alternative', but Windows based mail servers have issues with this.
 
             //$content = 'Content-Type: multipart/related; boundary="' . $this->_getBoundary() . '"'   . "\r\n";
-            $content = 'Content-Type: multipart/mixed; boundary="' . $this->_getBoundary('mixed') . '"'   . "\r\n";
+            $content = 'Content-Type: multipart/mixed; boundary="'.$this->_getBoundary('mixed').'"'."\r\n";
 
             //                     . "\r\n"
             //                     . 'This is a multi-part message in MIME format.' . "\r\n";
             $content .= "Content-Transfer-Encoding: 8bit\r\n";
             $content .= "\r\n";
 
-            $content .= "--" . $this->_getBoundary('mixed') . "\r\n";
+            $content .= "--".$this->_getBoundary('mixed')."\r\n";
 
             if (key_exists('image', $this->_msgContent))     // If inline image found
             {
-                $content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
+                $content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
                 $content .= "\r\n";
-                $content .= "--" . $this->_getBoundary('alternative') . "\r\n";
+                $content .= "--".$this->_getBoundary('alternative')."\r\n";
             }
 
 
@@ -1471,91 +1471,91 @@ class SMTPs
             // Loop through message content array
             foreach ($this->_msgContent as $type => $_content)
             {
-                if ( $type == 'attachment' )
+                if ($type == 'attachment')
                 {
                     // loop through all attachments
                     foreach ($_content as $_file => $_data)
                     {
-                        $content .= "--" . $this->_getBoundary('mixed') . "\r\n"
-                        .  'Content-Disposition: attachment; filename="' . $_data['fileName'] . '"' . "\r\n"
-                        .  'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['fileName'] . '"' . "\r\n"
-                        .  'Content-Transfer-Encoding: base64' . "\r\n"
-                        .  'Content-Description: ' . $_data['fileName'] ."\r\n";
+                        $content .= "--".$this->_getBoundary('mixed')."\r\n"
+                        .  'Content-Disposition: attachment; filename="'.$_data['fileName'].'"'."\r\n"
+                        .  'Content-Type: '.$_data['mimeType'].'; name="'.$_data['fileName'].'"'."\r\n"
+                        .  'Content-Transfer-Encoding: base64'."\r\n"
+                        .  'Content-Description: '.$_data['fileName']."\r\n";
 
-                        if ( $this->getMD5flag() )
-                        $content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
+                        if ($this->getMD5flag())
+                        $content .= 'Content-MD5: '.$_data['md5']."\r\n";
 
-                        $content .= "\r\n" .  $_data['data'] . "\r\n\r\n";
+                        $content .= "\r\n".$_data['data']."\r\n\r\n";
                     }
                 }
                 // @CHANGE LDR
-                elseif ( $type == 'image' )
+                elseif ($type == 'image')
                 {
                     // loop through all images
                     foreach ($_content as $_image => $_data)
                     {
-                        $content .= "--" . $this->_getBoundary('related') . "\r\n";  // always related for an inline image
+                        $content .= "--".$this->_getBoundary('related')."\r\n"; // always related for an inline image
 
-                        $content .= 'Content-Type: ' . $_data['mimeType'] . '; name="' . $_data['imageName'] . '"' . "\r\n"
-                        .  'Content-Transfer-Encoding: base64' . "\r\n"
-                        .  'Content-Disposition: inline; filename="' . $_data['imageName'] . '"' . "\r\n"
-                        .  'Content-ID: <' . $_data['cid'] . '> ' . "\r\n";
+                        $content .= 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['imageName'].'"'."\r\n"
+                        .  'Content-Transfer-Encoding: base64'."\r\n"
+                        .  'Content-Disposition: inline; filename="'.$_data['imageName'].'"'."\r\n"
+                        .  'Content-ID: <'.$_data['cid'].'> '."\r\n";
 
-                        if ( $this->getMD5flag() )
-                        $content .= 'Content-MD5: ' . $_data['md5'] . "\r\n";
+                        if ($this->getMD5flag())
+                        $content .= 'Content-MD5: '.$_data['md5']."\r\n";
 
                         $content .= "\r\n"
-                        . $_data['data'] . "\r\n";
+                        . $_data['data']."\r\n";
                     }
 
                     // always end related and end alternative after inline images
-                    $content.= "--" . $this->_getBoundary('related') . "--" . "\r\n";
-                    $content.= "\r\n" . "--" . $this->_getBoundary('alternative') . "--" . "\r\n";
-                    $content.= "\r\n";
+                    $content .= "--".$this->_getBoundary('related')."--"."\r\n";
+                    $content .= "\r\n"."--".$this->_getBoundary('alternative')."--"."\r\n";
+                    $content .= "\r\n";
                 }
                 else
                 {
                     if (key_exists('image', $this->_msgContent))
                     {
-                        $content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n";
-                        $content.= "\r\n" . ($_content['dataText']?$_content['dataText']:strip_tags($_content['data'])) . "\r\n"; // Add plain text message
-                        $content.= "--" . $this->_getBoundary('alternative') . "\r\n";
-                        $content.= 'Content-Type: multipart/related; boundary="' . $this->_getBoundary('related') . '"' . "\r\n";
-                        $content.= "\r\n";
-                        $content.= "--" . $this->_getBoundary('related') . "\r\n";
+                        $content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n";
+                        $content .= "\r\n".($_content['dataText'] ? $_content['dataText'] : strip_tags($_content['data']))."\r\n"; // Add plain text message
+                        $content .= "--".$this->_getBoundary('alternative')."\r\n";
+                        $content .= 'Content-Type: multipart/related; boundary="'.$this->_getBoundary('related').'"'."\r\n";
+                        $content .= "\r\n";
+                        $content .= "--".$this->_getBoundary('related')."\r\n";
                     }
 
-                    if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part before html part
+                    if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part before html part
                     {
-                        $content.= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"' . "\r\n";
+                        $content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
                         $content .= "\r\n";
-                           $content .= "--" . $this->_getBoundary('alternative') . "\r\n";
+                           $content .= "--".$this->_getBoundary('alternative')."\r\n";
 
-                           $content.= "Content-Type: text/plain; charset=" . $this->getCharSet() . "\r\n";
-                           $content.= "\r\n". $_content['dataText'] . "\r\n";
-                           $content.= "--" . $this->_getBoundary('alternative') . "\r\n";
+                           $content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n";
+                           $content .= "\r\n".$_content['dataText']."\r\n";
+                           $content .= "--".$this->_getBoundary('alternative')."\r\n";
                     }
 
-                    $content .= 'Content-Type: ' . $_content['mimeType'] . '; '
+                    $content .= 'Content-Type: '.$_content['mimeType'].'; '
                     //                             . 'charset="' . $this->getCharSet() . '"';
-                    . 'charset=' . $this->getCharSet() . '';
+                    . 'charset='.$this->getCharSet().'';
 
                     //                    $content .= ( $type == 'html') ? '; name="HTML Part"' : '';
-                    $content .=  "\r\n";
+                    $content .= "\r\n";
                     //                    $content .= 'Content-Transfer-Encoding: ';
                     //                    $content .= ($type == 'html') ? 'quoted-printable' : $this->getTransEncodeType();
                     //                    $content .=  "\r\n"
                     //                             . 'Content-Disposition: inline'  . "\r\n"
                     //                             . 'Content-Description: ' . $type . ' message' . "\r\n";
 
-                    if ( $this->getMD5flag() )
-                    $content .= 'Content-MD5: ' . $_content['md5'] . "\r\n";
+                    if ($this->getMD5flag())
+                    $content .= 'Content-MD5: '.$_content['md5']."\r\n";
 
-                    $content .= "\r\n"	. $_content['data'] . "\r\n";
+                    $content .= "\r\n".$_content['data']."\r\n";
 
-                    if (! key_exists('image', $this->_msgContent) && $_content['dataText'] && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part after html part
+                    if (!key_exists('image', $this->_msgContent) && $_content['dataText'] && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))  // Add plain text message part after html part
                     {
-                        $content.= "--" . $this->_getBoundary('alternative') . "--". "\r\n";
+                        $content .= "--".$this->_getBoundary('alternative')."--"."\r\n";
                     }
 
                     $content .= "\r\n";
@@ -1564,7 +1564,7 @@ class SMTPs
 
             // Close message boundries
             //            $content .= "\r\n--" . $this->_getBoundary() . '--' . "\r\n" ;
-            $content .= "--" . $this->_getBoundary('mixed') . '--' . "\r\n" ;
+            $content .= "--".$this->_getBoundary('mixed').'--'."\r\n";
         }
 
         return $content;
@@ -1581,15 +1581,15 @@ class SMTPs
      */
     public function setAttachment($strContent, $strFileName = 'unknown', $strMimeType = 'unknown')
     {
-        if ( $strContent )
+        if ($strContent)
         {
-            $strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n"));    // 76 max is defined into http://tools.ietf.org/html/rfc2047
+            $strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n")); // 76 max is defined into http://tools.ietf.org/html/rfc2047
 
             $this->_msgContent['attachment'][$strFileName]['mimeType'] = $strMimeType;
             $this->_msgContent['attachment'][$strFileName]['fileName'] = $strFileName;
             $this->_msgContent['attachment'][$strFileName]['data']     = $strContent;
 
-            if ( $this->getMD5flag() )
+            if ($this->getMD5flag())
             $this->_msgContent['attachment'][$strFileName]['md5']      = dol_hash($strContent, 3);
         }
     }
@@ -1616,7 +1616,7 @@ class SMTPs
             $this->_msgContent['image'][$strImageName]['cid']      = $strImageCid;
             $this->_msgContent['image'][$strImageName]['data']     = $strContent;
 
-            if ( $this->getMD5flag() )
+            if ($this->getMD5flag())
             $this->_msgContent['image'][$strImageName]['md5']      = dol_hash($strContent, 3);
         }
     }
@@ -1636,8 +1636,8 @@ class SMTPs
      */
     public function setSensitivity($_value = 0)
     {
-        if ( ( is_numeric($_value) ) &&
-        ( ( $_value >= 0 ) && ( $_value <= 3 ) ) )
+        if ((is_numeric($_value)) &&
+        (($_value >= 0) && ($_value <= 3)))
         $this->_msgSensitivity = $_value;
     }
 
@@ -1671,8 +1671,8 @@ class SMTPs
      */
     public function setPriority($_value = 3)
     {
-        if ( ( is_numeric($_value) ) &&
-        ( ( $_value >= 0 ) && ( $_value <= 5 ) ) )
+        if ((is_numeric($_value)) &&
+        (($_value >= 0) && ($_value <= 5)))
         $this->_msgPriority = $_value;
     }
 
@@ -1690,9 +1690,9 @@ class SMTPs
      */
     public function getPriority()
     {
-        return 'Importance: ' . $this->_aryPriority[$this->_msgPriority] . "\r\n"
-        . 'Priority: '   . $this->_aryPriority[$this->_msgPriority] . "\r\n"
-        . 'X-Priority: ' . $this->_msgPriority . ' (' . $this->_aryPriority[$this->_msgPriority] . ')' . "\r\n";
+        return 'Importance: '.$this->_aryPriority[$this->_msgPriority]."\r\n"
+        . 'Priority: '.$this->_aryPriority[$this->_msgPriority]."\r\n"
+        . 'X-Priority: '.$this->_msgPriority.' ('.$this->_aryPriority[$this->_msgPriority].')'."\r\n";
     }
 
     /**
@@ -1726,7 +1726,7 @@ class SMTPs
      */
     public function setXheader($strXdata)
     {
-        if ( $strXdata )
+        if ($strXdata)
         $this->_msgXheader[] = $strXdata;
     }
 
@@ -1747,7 +1747,7 @@ class SMTPs
      */
     private function _setBoundary()
     {
-        $this->_smtpsBoundary = "multipart_x." . time() . ".x_boundary";
+        $this->_smtpsBoundary = "multipart_x.".time().".x_boundary";
         $this->_smtpsRelatedBoundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);
         $this->_smtpsAlternativeBoundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);
     }
@@ -1786,11 +1786,11 @@ class SMTPs
         $server_response = '';
 
         // avoid infinite loop
-        $limit=0;
+        $limit = 0;
 
-        while (substr($server_response, 3, 1) != ' ' && $limit<100)
+        while (substr($server_response, 3, 1) != ' ' && $limit < 100)
         {
-            if (! ($server_response = fgets($socket, 256)))
+            if (!($server_response = fgets($socket, 256)))
             {
                 $this->_setErr(121, "Couldn't get mail server response codes");
                 $_retVal = false;
@@ -1800,7 +1800,7 @@ class SMTPs
             $limit++;
         }
 
-        if (! (substr($server_response, 0, 3) == $response))
+        if (!(substr($server_response, 0, 3) == $response))
         {
             $this->_setErr(120, "Ran into problems sending Mail.\r\nResponse: $server_response");
             $_retVal = false;
@@ -1821,11 +1821,11 @@ class SMTPs
     public function socket_send_str($_strSend, $_returnCode = null, $CRLF = "\r\n")
     {
         // phpcs:enable
-        if ($this->_debug) $this->log.=$_strSend;	// @CHANGE LDR for log
-        fputs($this->socket, $_strSend . $CRLF);
-        if ($this->_debug) $this->log.=' ('.$_returnCode.')' . $CRLF;
+        if ($this->_debug) $this->log .= $_strSend; // @CHANGE LDR for log
+        fputs($this->socket, $_strSend.$CRLF);
+        if ($this->_debug) $this->log .= ' ('.$_returnCode.')'.$CRLF;
 
-        if ( $_returnCode )
+        if ($_returnCode)
         return $this->server_parse($this->socket, $_returnCode);
     }
 
@@ -1860,7 +1860,7 @@ class SMTPs
         {
             foreach ($this->_smtpsErrors as $_err => $_info)
             {
-                $_errMsg[] = 'Error [' . $_info['num'] .']: '. $_info['msg'];
+                $_errMsg[] = 'Error ['.$_info['num'].']: '.$_info['msg'];
             }
         }
 

+ 26 - 26
htdocs/core/extrafieldsinexport.inc.php

@@ -8,67 +8,67 @@ if (empty($keyforselect) || empty($keyforelement) || empty($keyforaliasextra))
 }
 
 // Add extra fields
-$sql="SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.') ORDER BY pos ASC';
+$sql = "SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.') ORDER BY pos ASC';
 //print $sql;
-$resql=$this->db->query($sql);
+$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=$keyforaliasextra.'.'.$obj->name;
-		$fieldlabel=ucfirst($obj->label);
-		$typeFilter="Text";
-		$typefield=preg_replace('/\(.*$/', '', $obj->type);	// double(24,8) -> double
+		$fieldname = $keyforaliasextra.'.'.$obj->name;
+		$fieldlabel = ucfirst($obj->label);
+		$typeFilter = "Text";
+		$typefield = preg_replace('/\(.*$/', '', $obj->type); // double(24,8) -> double
 		switch ($typefield) {
 			case 'int':
 			case 'integer':
 			case 'double':
 			case 'price':
-				$typeFilter="Numeric";
+				$typeFilter = "Numeric";
 				break;
 			case 'date':
 			case 'datetime':
 			case 'timestamp':
-				$typeFilter="Date";
+				$typeFilter = "Date";
 				break;
 			case 'boolean':
-				$typeFilter="Boolean";
+				$typeFilter = "Boolean";
 				break;
 			case 'select':
-			    if (! empty($conf->global->EXPORT_LABEL_FOR_SELECT))
+			    if (!empty($conf->global->EXPORT_LABEL_FOR_SELECT))
 			    {
-    			    $tmpparam=unserialize($obj->param);	// $tmpparam may be array with 'options' = array(key1=>val1, key2=>val2 ...)
+    			    $tmpparam = unserialize($obj->param); // $tmpparam may be array with 'options' = array(key1=>val1, key2=>val2 ...)
     			    if ($tmpparam['options'] && is_array($tmpparam['options'])) {
-    			        $typeFilter="Select:".$obj->param;
+    			        $typeFilter = "Select:".$obj->param;
     			    }
 			    }
 			    break;
 			case 'sellist':
-				$tmp='';
-				$tmpparam=unserialize($obj->param);	// $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
+				$tmp = '';
+				$tmpparam = unserialize($obj->param); // $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
 				if ($tmpparam['options'] && is_array($tmpparam['options'])) {
-					$tmpkeys=array_keys($tmpparam['options']);
-					$tmp=array_shift($tmpkeys);
+					$tmpkeys = array_keys($tmpparam['options']);
+					$tmp = array_shift($tmpkeys);
 				}
-				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp;
+				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter = "List:".$tmp;
 				break;
 		}
-		if ($obj->type!='separate')
+		if ($obj->type != 'separate')
 		{
 		    // If not a computed field
 		    if (empty($obj->fieldcomputed))
 		    {
-    			$this->export_fields_array[$r][$fieldname]=$fieldlabel;
-    			$this->export_TypeFields_array[$r][$fieldname]=$typeFilter;
-    			$this->export_entities_array[$r][$fieldname]=$keyforelement;
+    			$this->export_fields_array[$r][$fieldname] = $fieldlabel;
+    			$this->export_TypeFields_array[$r][$fieldname] = $typeFilter;
+    			$this->export_entities_array[$r][$fieldname] = $keyforelement;
 		    }
 			// If this is a computed field
 			else
 			{
-			    $this->export_fields_array[$r][$fieldname]=$fieldlabel;
-			    $this->export_TypeFields_array[$r][$fieldname]=$typeFilter.'Compute';
-			    $this->export_special_array[$r][$fieldname]=$obj->fieldcomputed;
-			    $this->export_entities_array[$r][$fieldname]=$keyforelement;
+			    $this->export_fields_array[$r][$fieldname] = $fieldlabel;
+			    $this->export_TypeFields_array[$r][$fieldname] = $typeFilter.'Compute';
+			    $this->export_special_array[$r][$fieldname] = $obj->fieldcomputed;
+			    $this->export_entities_array[$r][$fieldname] = $keyforelement;
 			}
 		}
 	}

+ 153 - 153
htdocs/core/lib/files.lib.php

@@ -195,7 +195,7 @@ function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excl
 			closedir($dir);
 
 			// Obtain a list of columns
-			if (! empty($sortcriteria) && $sortorder)
+			if (!empty($sortcriteria) && $sortorder)
 			{
 				$file_list = dol_sort_array($file_list, $sortcriteria, ($sortorder == SORT_ASC ? 'asc' : 'desc'));
 			}
@@ -1435,21 +1435,21 @@ function dol_meta_create($object)
 		if (is_dir($dir))
 		{
 			$nblines = count($object->lines);
-			$client = $object->thirdparty->name . " " . $object->thirdparty->address . " " . $object->thirdparty->zip . " " . $object->thirdparty->town;
-			$meta = "REFERENCE=\"" . $object->ref . "\"
-			DATE=\"" . dol_print_date($object->date, '') . "\"
-			NB_ITEMS=\"" . $nblines . "\"
-			CLIENT=\"" . $client . "\"
-			AMOUNT_EXCL_TAX=\"" . $object->total_ht . "\"
-			AMOUNT=\"" . $object->total_ttc . "\"\n";
-
-			for ($i = 0 ; $i < $nblines ; $i++)
+			$client = $object->thirdparty->name." ".$object->thirdparty->address." ".$object->thirdparty->zip." ".$object->thirdparty->town;
+			$meta = "REFERENCE=\"".$object->ref."\"
+			DATE=\"" . dol_print_date($object->date, '')."\"
+			NB_ITEMS=\"" . $nblines."\"
+			CLIENT=\"" . $client."\"
+			AMOUNT_EXCL_TAX=\"" . $object->total_ht."\"
+			AMOUNT=\"" . $object->total_ttc."\"\n";
+
+			for ($i = 0; $i < $nblines; $i++)
 			{
 				//Pour les articles
-				$meta .= "ITEM_" . $i . "_QUANTITY=\"" . $object->lines[$i]->qty . "\"
-				ITEM_" . $i . "_AMOUNT_WO_TAX=\"" . $object->lines[$i]->total_ht . "\"
-				ITEM_" . $i . "_VAT=\"" .$object->lines[$i]->tva_tx . "\"
-				ITEM_" . $i . "_DESCRIPTION=\"" . str_replace("\r\n", "", nl2br($object->lines[$i]->desc)) . "\"
+				$meta .= "ITEM_".$i."_QUANTITY=\"".$object->lines[$i]->qty."\"
+				ITEM_" . $i."_AMOUNT_WO_TAX=\"".$object->lines[$i]->total_ht."\"
+				ITEM_" . $i."_VAT=\"".$object->lines[$i]->tva_tx."\"
+				ITEM_" . $i."_DESCRIPTION=\"".str_replace("\r\n", "", nl2br($object->lines[$i]->desc))."\"
 				";
 			}
 		}
@@ -1543,21 +1543,21 @@ function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesess
 			for ($i = 0; $i < $nbfile; $i++)
 			{
 				// Define $destfull (path to file including filename) and $destfile (only filename)
-				$destfull=$upload_dir . "/" . $TFile['name'][$i];
-				$destfile=$TFile['name'][$i];
+				$destfull = $upload_dir."/".$TFile['name'][$i];
+				$destfile = $TFile['name'][$i];
 
 				if ($savingdocmask)
 				{
-					$destfull=$upload_dir . "/" . preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
-					$destfile=preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
+					$destfull = $upload_dir."/".preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
+					$destfile = preg_replace('/__file__/', $TFile['name'][$i], $savingdocmask);
 				}
 
 				// dol_sanitizeFileName the file name and lowercase extension
 				$info = pathinfo($destfull);
-				$destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].($info['extension']!='' ? ('.'.strtolower($info['extension'])) : ''));
+				$destfull = $info['dirname'].'/'.dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
 				$info = pathinfo($destfile);
 
-				$destfile = dol_sanitizeFileName($info['filename'].($info['extension']!='' ? ('.'.strtolower($info['extension'])) : ''));
+				$destfile = dol_sanitizeFileName($info['filename'].($info['extension'] != '' ? ('.'.strtolower($info['extension'])) : ''));
 
 				// We apply dol_string_nohtmltag also to clean file names (this remove duplicate spaces) because
 				// this function is also applied when we make try to download file (by the GETPOST(filename, 'alphanohtml') call).
@@ -1845,15 +1845,15 @@ function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '', $page = ''
 			$ret = $image->setImageFormat($ext);
 			if ($ret)
 			{
-				if (empty($fileoutput)) $fileoutput=$fileinput.".".$ext;
+				if (empty($fileoutput)) $fileoutput = $fileinput.".".$ext;
 
 				$count = $image->getNumberImages();
-				if (! dol_is_file($fileoutput) || is_writeable($fileoutput))
+				if (!dol_is_file($fileoutput) || is_writeable($fileoutput))
 				{
 					try {
 						$ret = $image->writeImages($fileoutput, true);
 					}
-					catch(Exception $e)
+					catch (Exception $e)
 					{
 						dol_syslog($e->getMessage(), LOG_WARNING);
 					}
@@ -1896,20 +1896,20 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring
 {
 	global $conf;
 
-	$foundhandler=0;
+	$foundhandler = 0;
 
 	try
 	{
 		dol_syslog("dol_compress_file mode=".$mode." inputfile=".$inputfile." outputfile=".$outputfile);
 
 		$data = implode("", file(dol_osencode($inputfile)));
-		if ($mode == 'gz')     { $foundhandler=1; $compressdata = gzencode($data, 9); }
-		elseif ($mode == 'bz') { $foundhandler=1; $compressdata = bzcompress($data, 9); }
+		if ($mode == 'gz') { $foundhandler = 1; $compressdata = gzencode($data, 9); }
+		elseif ($mode == 'bz') { $foundhandler = 1; $compressdata = bzcompress($data, 9); }
 		elseif ($mode == 'zip')
 		{
-			if (class_exists('ZipArchive') && ! empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS))
+			if (class_exists('ZipArchive') && !empty($conf->global->MAIN_USE_ZIPARCHIVE_FOR_ZIP_COMPRESS))
 			{
-				$foundhandler=1;
+				$foundhandler = 1;
 
 				$rootPath = realpath($inputfile);
 
@@ -1917,7 +1917,7 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring
 				$zip = new ZipArchive;
 
 				if ($zip->open($outputfile, ZipArchive::CREATE) !== true) {
-					$errorstring="dol_compress_file failure - Failed to open file ".$outputfile."\n";
+					$errorstring = "dol_compress_file failure - Failed to open file ".$outputfile."\n";
 					dol_syslog($errorstring, LOG_ERR);
 
 					global $errormsg;
@@ -1956,7 +1956,7 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring
 
 			if (defined('ODTPHP_PATHTOPCLZIP'))
 			{
-				$foundhandler=1;
+				$foundhandler = 1;
 
 				include_once ODTPHP_PATHTOPCLZIP.'/pclzip.lib.php';
 				$archive = new PclZip($outputfile);
@@ -1965,7 +1965,7 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring
 				if ($result === 0)
 				{
 					global $errormsg;
-					$errormsg=$archive->errorInfo(true);
+					$errormsg = $archive->errorInfo(true);
 
 					if ($archive->errorCode() == PCLZIP_ERR_WRITE_OPEN_FAIL)
 					{
@@ -2007,7 +2007,7 @@ function dol_compress_file($inputfile, $outputfile, $mode = "gz", &$errorstring
 	{
 		global $langs, $errormsg;
 		$langs->load("errors");
-		$errormsg=$langs->trans("ErrorFailedToWriteInDir");
+		$errormsg = $langs->trans("ErrorFailedToWriteInDir");
 
 		$errorstring = "Failed to open file ".$outputfile;
 		dol_syslog($errorstring, LOG_ERR);
@@ -2087,22 +2087,22 @@ function dol_uncompress($inputfile, $outputdir)
  */
 function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = '', $rootdirinzip = '')
 {
-	$foundhandler=0;
+	$foundhandler = 0;
 
 	dol_syslog("Try to zip dir ".$inputdir." into ".$outputfile." mode=".$mode);
 
-	if (! dol_is_dir(dirname($outputfile)) || ! is_writable(dirname($outputfile)))
+	if (!dol_is_dir(dirname($outputfile)) || !is_writable(dirname($outputfile)))
 	{
 		global $langs, $errormsg;
 		$langs->load("errors");
-		$errormsg=$langs->trans("ErrorFailedToWriteInDir", $outputfile);
+		$errormsg = $langs->trans("ErrorFailedToWriteInDir", $outputfile);
 		return -3;
 	}
 
 	try
 	{
-		if ($mode == 'gz')     { $foundhandler=0; }
-		elseif ($mode == 'bz') { $foundhandler=0; }
+		if ($mode == 'gz') { $foundhandler = 0; }
+		elseif ($mode == 'bz') { $foundhandler = 0; }
 		elseif ($mode == 'zip')
 		{
 			/*if (defined('ODTPHP_PATHTOPCLZIP'))
@@ -2124,11 +2124,11 @@ function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles =
 				// Initialize archive object
 				$zip = new ZipArchive();
 				$result = $zip->open($outputfile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
-				if (! $result)
+				if (!$result)
 				{
 					global $langs, $errormsg;
 					$langs->load("errors");
-					$errormsg=$langs->trans("ErrorFailedToWriteInFile", $outputfile);
+					$errormsg = $langs->trans("ErrorFailedToWriteInFile", $outputfile);
 					return -4;
 				}
 
@@ -2148,7 +2148,7 @@ function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles =
 						$filePath = $file->getRealPath();
 						$relativePath = ($rootdirinzip ? $rootdirinzip.'/' : '').substr($filePath, strlen($inputdir) + 1);
 
-						if (empty($excludefiles) || ! preg_match($excludefiles, $filePath))
+						if (empty($excludefiles) || !preg_match($excludefiles, $filePath))
 						{
 							// Add current file to archive
 							$zip->addFile($filePath, $relativePath);
@@ -2219,267 +2219,267 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity,
 	global $conf, $db, $user;
 	global $dolibarr_main_data_root, $dolibarr_main_document_root_alt;
 
-	if (! is_object($fuser)) $fuser=$user;
+	if (!is_object($fuser)) $fuser = $user;
 
 	if (empty($modulepart)) return 'ErrorBadParameter';
 	if (empty($entity))
 	{
-		if (empty($conf->multicompany->enabled)) $entity=1;
-		else $entity=0;
+		if (empty($conf->multicompany->enabled)) $entity = 1;
+		else $entity = 0;
 	}
 	// Fix modulepart
-	if ($modulepart == 'users') $modulepart='user';
+	if ($modulepart == 'users') $modulepart = 'user';
 
 	dol_syslog('modulepart='.$modulepart.' original_file='.$original_file.' entity='.$entity);
 
 	// We define $accessallowed and $sqlprotectagainstexternals
-	$accessallowed=0;
-	$sqlprotectagainstexternals='';
-	$ret=array();
+	$accessallowed = 0;
+	$sqlprotectagainstexternals = '';
+	$ret = array();
 
 	// Find the subdirectory name as the reference. For exemple original_file='10/myfile.pdf' -> refname='10'
-	if (empty($refname)) $refname=basename(dirname($original_file)."/");
+	if (empty($refname)) $refname = basename(dirname($original_file)."/");
 
 	// Define possible keys to use for permission check
-	$lire='lire'; $read='read'; $download='download';
+	$lire = 'lire'; $read = 'read'; $download = 'download';
 	if ($mode == 'write')
 	{
-		$lire='creer'; $read='write'; $download='upload';
+		$lire = 'creer'; $read = 'write'; $download = 'upload';
 	}
 
 	// Wrapping for miscellaneous medias files
 	if ($modulepart == 'medias' && !empty($dolibarr_main_data_root))
 	{
 		if (empty($entity) || empty($conf->medias->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
-		$accessallowed=1;
-		$original_file=$conf->medias->multidir_output[$entity].'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->medias->multidir_output[$entity].'/'.$original_file;
 	}
 	// Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
 	elseif ($modulepart == 'logs' && !empty($dolibarr_main_data_root))
 	{
-		$accessallowed=($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file)));
-		$original_file=$dolibarr_main_data_root.'/'.$original_file;
+		$accessallowed = ($user->admin && basename($original_file) == $original_file && preg_match('/^dolibarr.*\.log$/', basename($original_file)));
+		$original_file = $dolibarr_main_data_root.'/'.$original_file;
 	}
 	// Wrapping for *.log files, like when used with url http://.../document.php?modulepart=logs&file=dolibarr.log
 	elseif ($modulepart == 'doctemplateswebsite' && !empty($dolibarr_main_data_root))
 	{
-		$accessallowed=($fuser->rights->website->write && preg_match('/\.jpg$/i', basename($original_file)));
-		$original_file=$dolibarr_main_data_root.'/doctemplates/websites/'.$original_file;
+		$accessallowed = ($fuser->rights->website->write && preg_match('/\.jpg$/i', basename($original_file)));
+		$original_file = $dolibarr_main_data_root.'/doctemplates/websites/'.$original_file;
 	}
 	// Wrapping for *.zip files, like when used with url http://.../document.php?modulepart=packages&file=module_myfile.zip
 	elseif ($modulepart == 'packages' && !empty($dolibarr_main_data_root))
 	{
 		// Dir for custom dirs
-		$tmp=explode(',', $dolibarr_main_document_root_alt);
+		$tmp = explode(',', $dolibarr_main_document_root_alt);
 		$dirins = $tmp[0];
 
-		$accessallowed=($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
-		$original_file=$dirins.'/'.$original_file;
+		$accessallowed = ($user->admin && preg_match('/^module_.*\.zip$/', basename($original_file)));
+		$original_file = $dirins.'/'.$original_file;
 	}
 	// Wrapping for some images
 	elseif ($modulepart == 'mycompany' && !empty($conf->mycompany->dir_output))
 	{
-		$accessallowed=1;
-		$original_file=$conf->mycompany->dir_output.'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->mycompany->dir_output.'/'.$original_file;
 	}
 	// Wrapping for users photos
 	elseif ($modulepart == 'userphoto' && !empty($conf->user->dir_output))
 	{
-		$accessallowed=1;
-		$original_file=$conf->user->dir_output.'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->user->dir_output.'/'.$original_file;
 	}
 	// Wrapping for members photos
 	elseif ($modulepart == 'memberphoto' && !empty($conf->adherent->dir_output))
 	{
-		$accessallowed=1;
-		$original_file=$conf->adherent->dir_output.'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->adherent->dir_output.'/'.$original_file;
 	}
 	// Wrapping pour les apercu factures
 	elseif ($modulepart == 'apercufacture' && !empty($conf->facture->multidir_output[$entity]))
 	{
-		if ($fuser->rights->facture->{$lire}) $accessallowed=1;
-		$original_file=$conf->facture->multidir_output[$entity].'/'.$original_file;
+		if ($fuser->rights->facture->{$lire}) $accessallowed = 1;
+		$original_file = $conf->facture->multidir_output[$entity].'/'.$original_file;
 	}
 	// Wrapping pour les apercu propal
 	elseif ($modulepart == 'apercupropal' && !empty($conf->propal->multidir_output[$entity]))
 	{
-		if ($fuser->rights->propale->{$lire}) $accessallowed=1;
-		$original_file=$conf->propal->multidir_output[$entity].'/'.$original_file;
+		if ($fuser->rights->propale->{$lire}) $accessallowed = 1;
+		$original_file = $conf->propal->multidir_output[$entity].'/'.$original_file;
 	}
 	// Wrapping pour les apercu commande
 	elseif ($modulepart == 'apercucommande' && !empty($conf->commande->multidir_output[$entity]))
 	{
-		if ($fuser->rights->commande->{$lire}) $accessallowed=1;
-		$original_file=$conf->commande->multidir_output[$entity].'/'.$original_file;
+		if ($fuser->rights->commande->{$lire}) $accessallowed = 1;
+		$original_file = $conf->commande->multidir_output[$entity].'/'.$original_file;
 	}
 	// Wrapping pour les apercu intervention
 	elseif (($modulepart == 'apercufichinter' || $modulepart == 'apercuficheinter') && !empty($conf->ficheinter->dir_output))
 	{
-		if ($fuser->rights->ficheinter->{$lire}) $accessallowed=1;
-		$original_file=$conf->ficheinter->dir_output.'/'.$original_file;
+		if ($fuser->rights->ficheinter->{$lire}) $accessallowed = 1;
+		$original_file = $conf->ficheinter->dir_output.'/'.$original_file;
 	}
 	// Wrapping pour les apercu conat
 	elseif (($modulepart == 'apercucontract') && !empty($conf->contrat->dir_output))
 	{
-		if ($fuser->rights->contrat->{$lire}) $accessallowed=1;
-		$original_file=$conf->contrat->dir_output.'/'.$original_file;
+		if ($fuser->rights->contrat->{$lire}) $accessallowed = 1;
+		$original_file = $conf->contrat->dir_output.'/'.$original_file;
 	}
 	// Wrapping pour les apercu supplier proposal
 	elseif (($modulepart == 'apercusupplier_proposal' || $modulepart == 'apercusupplier_proposal') && !empty($conf->supplier_proposal->dir_output))
 	{
-		if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed=1;
-		$original_file=$conf->supplier_proposal->dir_output.'/'.$original_file;
+		if ($fuser->rights->supplier_proposal->{$lire}) $accessallowed = 1;
+		$original_file = $conf->supplier_proposal->dir_output.'/'.$original_file;
 	}
 	// Wrapping pour les apercu supplier order
 	elseif (($modulepart == 'apercusupplier_order' || $modulepart == 'apercusupplier_order') && !empty($conf->fournisseur->commande->dir_output))
 	{
-		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
-		$original_file=$conf->fournisseur->commande->dir_output.'/'.$original_file;
+		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1;
+		$original_file = $conf->fournisseur->commande->dir_output.'/'.$original_file;
 	}
 	// Wrapping pour les apercu supplier invoice
 	elseif (($modulepart == 'apercusupplier_invoice' || $modulepart == 'apercusupplier_invoice') && !empty($conf->fournisseur->facture->dir_output))
 	{
-		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
-		$original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
+		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1;
+		$original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
 	}
 	// Wrapping pour les apercu supplier invoice
 	elseif (($modulepart == 'apercuexpensereport') && !empty($conf->expensereport->dir_output))
 	{
-		if ($fuser->rights->expensereport->{$lire}) $accessallowed=1;
-		$original_file=$conf->expensereport->dir_output.'/'.$original_file;
+		if ($fuser->rights->expensereport->{$lire}) $accessallowed = 1;
+		$original_file = $conf->expensereport->dir_output.'/'.$original_file;
 	}
 	// Wrapping pour les images des stats propales
 	elseif ($modulepart == 'propalstats' && !empty($conf->propal->multidir_temp[$entity]))
 	{
-		if ($fuser->rights->propale->{$lire}) $accessallowed=1;
-		$original_file=$conf->propal->multidir_temp[$entity].'/'.$original_file;
+		if ($fuser->rights->propale->{$lire}) $accessallowed = 1;
+		$original_file = $conf->propal->multidir_temp[$entity].'/'.$original_file;
 	}
 	// Wrapping pour les images des stats commandes
 	elseif ($modulepart == 'orderstats' && !empty($conf->commande->dir_temp))
 	{
-		if ($fuser->rights->commande->{$lire}) $accessallowed=1;
-		$original_file=$conf->commande->dir_temp.'/'.$original_file;
+		if ($fuser->rights->commande->{$lire}) $accessallowed = 1;
+		$original_file = $conf->commande->dir_temp.'/'.$original_file;
 	}
 	elseif ($modulepart == 'orderstatssupplier' && !empty($conf->fournisseur->dir_output))
 	{
-		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed=1;
-		$original_file=$conf->fournisseur->commande->dir_temp.'/'.$original_file;
+		if ($fuser->rights->fournisseur->commande->{$lire}) $accessallowed = 1;
+		$original_file = $conf->fournisseur->commande->dir_temp.'/'.$original_file;
 	}
 	// Wrapping pour les images des stats factures
 	elseif ($modulepart == 'billstats' && !empty($conf->facture->dir_temp))
 	{
-		if ($fuser->rights->facture->{$lire}) $accessallowed=1;
-		$original_file=$conf->facture->dir_temp.'/'.$original_file;
+		if ($fuser->rights->facture->{$lire}) $accessallowed = 1;
+		$original_file = $conf->facture->dir_temp.'/'.$original_file;
 	}
 	elseif ($modulepart == 'billstatssupplier' && !empty($conf->fournisseur->dir_output))
 	{
-		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed=1;
-		$original_file=$conf->fournisseur->facture->dir_temp.'/'.$original_file;
+		if ($fuser->rights->fournisseur->facture->{$lire}) $accessallowed = 1;
+		$original_file = $conf->fournisseur->facture->dir_temp.'/'.$original_file;
 	}
 	// Wrapping pour les images des stats expeditions
 	elseif ($modulepart == 'expeditionstats' && !empty($conf->expedition->dir_temp))
 	{
-		if ($fuser->rights->expedition->{$lire}) $accessallowed=1;
-		$original_file=$conf->expedition->dir_temp.'/'.$original_file;
+		if ($fuser->rights->expedition->{$lire}) $accessallowed = 1;
+		$original_file = $conf->expedition->dir_temp.'/'.$original_file;
 	}
 	// Wrapping pour les images des stats expeditions
 	elseif ($modulepart == 'tripsexpensesstats' && !empty($conf->deplacement->dir_temp))
 	{
-		if ($fuser->rights->deplacement->{$lire}) $accessallowed=1;
-		$original_file=$conf->deplacement->dir_temp.'/'.$original_file;
+		if ($fuser->rights->deplacement->{$lire}) $accessallowed = 1;
+		$original_file = $conf->deplacement->dir_temp.'/'.$original_file;
 	}
 	// Wrapping pour les images des stats expeditions
 	elseif ($modulepart == 'memberstats' && !empty($conf->adherent->dir_temp))
 	{
-		if ($fuser->rights->adherent->{$lire}) $accessallowed=1;
-		$original_file=$conf->adherent->dir_temp.'/'.$original_file;
+		if ($fuser->rights->adherent->{$lire}) $accessallowed = 1;
+		$original_file = $conf->adherent->dir_temp.'/'.$original_file;
 	}
 	// Wrapping pour les images des stats produits
 	elseif (preg_match('/^productstats_/i', $modulepart) && !empty($conf->product->dir_temp))
 	{
-		if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed=1;
-		$original_file=(!empty($conf->product->multidir_temp[$entity])?$conf->product->multidir_temp[$entity]:$conf->service->multidir_temp[$entity]).'/'.$original_file;
+		if ($fuser->rights->produit->{$lire} || $fuser->rights->service->{$lire}) $accessallowed = 1;
+		$original_file = (!empty($conf->product->multidir_temp[$entity]) ? $conf->product->multidir_temp[$entity] : $conf->service->multidir_temp[$entity]).'/'.$original_file;
 	}
 	// Wrapping for taxes
 	elseif ($modulepart == 'tax' && !empty($conf->tax->dir_output))
 	{
-		if ($fuser->rights->tax->charges->{$lire}) $accessallowed=1;
-		$original_file=$conf->tax->dir_output.'/'.$original_file;
+		if ($fuser->rights->tax->charges->{$lire}) $accessallowed = 1;
+		$original_file = $conf->tax->dir_output.'/'.$original_file;
 	}
 	// Wrapping for events
 	elseif ($modulepart == 'actions' && !empty($conf->agenda->dir_output))
 	{
-		if ($fuser->rights->agenda->myactions->{$read}) $accessallowed=1;
-		$original_file=$conf->agenda->dir_output.'/'.$original_file;
+		if ($fuser->rights->agenda->myactions->{$read}) $accessallowed = 1;
+		$original_file = $conf->agenda->dir_output.'/'.$original_file;
 	}
 	// Wrapping for categories
 	elseif ($modulepart == 'category' && !empty($conf->categorie->dir_output))
 	{
 		if (empty($entity) || empty($conf->categorie->multidir_output[$entity])) return array('accessallowed'=>0, 'error'=>'Value entity must be provided');
-		if ($fuser->rights->categorie->{$lire}) $accessallowed=1;
-		$original_file=$conf->categorie->multidir_output[$entity].'/'.$original_file;
+		if ($fuser->rights->categorie->{$lire}) $accessallowed = 1;
+		$original_file = $conf->categorie->multidir_output[$entity].'/'.$original_file;
 	}
 	// Wrapping pour les prelevements
 	elseif ($modulepart == 'prelevement' && !empty($conf->prelevement->dir_output))
 	{
-		if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i', $original_file)) $accessallowed=1;
-		$original_file=$conf->prelevement->dir_output.'/'.$original_file;
+		if ($fuser->rights->prelevement->bons->{$lire} || preg_match('/^specimen/i', $original_file)) $accessallowed = 1;
+		$original_file = $conf->prelevement->dir_output.'/'.$original_file;
 	}
 	// Wrapping pour les graph energie
 	elseif ($modulepart == 'graph_stock' && !empty($conf->stock->dir_temp))
 	{
-		$accessallowed=1;
-		$original_file=$conf->stock->dir_temp.'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->stock->dir_temp.'/'.$original_file;
 	}
 	// Wrapping pour les graph fournisseurs
 	elseif ($modulepart == 'graph_fourn' && !empty($conf->fournisseur->dir_temp))
 	{
-		$accessallowed=1;
-		$original_file=$conf->fournisseur->dir_temp.'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->fournisseur->dir_temp.'/'.$original_file;
 	}
 	// Wrapping pour les graph des produits
 	elseif ($modulepart == 'graph_product' && !empty($conf->product->dir_temp))
 	{
-		$accessallowed=1;
-		$original_file=$conf->product->multidir_temp[$entity].'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->product->multidir_temp[$entity].'/'.$original_file;
 	}
 	// Wrapping pour les code barre
 	elseif ($modulepart == 'barcode')
 	{
-		$accessallowed=1;
+		$accessallowed = 1;
 		// If viewimage is called for barcode, we try to output an image on the fly, with no build of file on disk.
 		//$original_file=$conf->barcode->dir_temp.'/'.$original_file;
-		$original_file='';
+		$original_file = '';
 	}
 	// Wrapping pour les icones de background des mailings
 	elseif ($modulepart == 'iconmailing' && !empty($conf->mailing->dir_temp))
 	{
-		$accessallowed=1;
-		$original_file=$conf->mailing->dir_temp.'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->mailing->dir_temp.'/'.$original_file;
 	}
 	// Wrapping pour le scanner
 	elseif ($modulepart == 'scanner_user_temp' && !empty($conf->scanner->dir_temp))
 	{
-		$accessallowed=1;
-		$original_file=$conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->scanner->dir_temp.'/'.$fuser->id.'/'.$original_file;
 	}
 	// Wrapping pour les images fckeditor
 	elseif ($modulepart == 'fckeditor' && !empty($conf->fckeditor->dir_output))
 	{
-		$accessallowed=1;
-		$original_file=$conf->fckeditor->dir_output.'/'.$original_file;
+		$accessallowed = 1;
+		$original_file = $conf->fckeditor->dir_output.'/'.$original_file;
 	}
 
 	// Wrapping for users
 	elseif ($modulepart == 'user' && !empty($conf->user->dir_output))
 	{
-		$canreaduser=(! empty($fuser->admin) || $fuser->rights->user->user->{$lire});
-		if ($fuser->id == (int) $refname) { $canreaduser=1; } // A user can always read its own card
+		$canreaduser = (!empty($fuser->admin) || $fuser->rights->user->user->{$lire});
+		if ($fuser->id == (int) $refname) { $canreaduser = 1; } // A user can always read its own card
 		if ($canreaduser || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->user->dir_output.'/'.$original_file;
+		$original_file = $conf->user->dir_output.'/'.$original_file;
 	}
 
 	// Wrapping for third parties
@@ -2510,9 +2510,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity,
 	{
 		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->facture->multidir_output[$entity].'/'.$original_file;
+		$original_file = $conf->facture->multidir_output[$entity].'/'.$original_file;
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
 	}
 	// Wrapping for mass actions
@@ -2520,81 +2520,81 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity,
 	{
 		if ($fuser->rights->propal->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->propal->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 	elseif ($modulepart == 'massfilesarea_orders')
 	{
 		if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->commande->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->commande->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 	elseif ($modulepart == 'massfilesarea_sendings')
 	{
 		if ($fuser->rights->expedition->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->expedition->dir_output.'/sending/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->expedition->dir_output.'/sending/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 	elseif ($modulepart == 'massfilesarea_invoices')
 	{
 		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->facture->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->facture->multidir_output[$entity].'/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 	elseif ($modulepart == 'massfilesarea_expensereport')
 	{
 		if ($fuser->rights->facture->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->expensereport->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 	elseif ($modulepart == 'massfilesarea_interventions')
 	{
 		if ($fuser->rights->ficheinter->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 	elseif ($modulepart == 'massfilesarea_supplier_proposal' && !empty($conf->supplier_proposal->dir_output))
 	{
 		if ($fuser->rights->supplier_proposal->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->supplier_proposal->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 	elseif ($modulepart == 'massfilesarea_supplier_order')
 	{
 		if ($fuser->rights->fournisseur->commande->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 	elseif ($modulepart == 'massfilesarea_supplier_invoice')
 	{
 		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 	elseif ($modulepart == 'massfilesarea_contract' && !empty($conf->contrat->dir_output))
 	{
 		if ($fuser->rights->contrat->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
+		$original_file = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id.'/'.$original_file;
 	}
 
 	// Wrapping for interventions
@@ -2634,9 +2634,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity,
 	{
 		if ($fuser->rights->commande->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->commande->multidir_output[$entity].'/'.$original_file;
+		$original_file = $conf->commande->multidir_output[$entity].'/'.$original_file;
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."commande WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
 	}
 
@@ -2676,9 +2676,9 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity,
 	{
 		if ($fuser->rights->fournisseur->facture->{$lire} || preg_match('/^specimen/i', $original_file))
 		{
-			$accessallowed=1;
+			$accessallowed = 1;
 		}
-		$original_file=$conf->fournisseur->facture->dir_output.'/'.$original_file;
+		$original_file = $conf->fournisseur->facture->dir_output.'/'.$original_file;
 		$sqlprotectagainstexternals = "SELECT fk_soc as fk_soc FROM ".MAIN_DB_PREFIX."facture_fourn WHERE ref='".$db->escape($refname)."' AND entity=".$conf->entity;
 	}
 	// Wrapping pour les rapport de paiements

+ 1 - 1
htdocs/core/lib/functions2.lib.php

@@ -2627,7 +2627,7 @@ function price2fec($amount)
 	global $conf;
 
 	// Clean parameters
-	if (empty($amount)) $amount=0;	// To have a numeric value if amount not defined or = ''
+	if (empty($amount)) $amount = 0; // To have a numeric value if amount not defined or = ''
 	$amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
 
 	// Output decimal number by default

+ 1 - 1
htdocs/core/lib/pdf.lib.php

@@ -2157,7 +2157,7 @@ function pdf_getLinkedObjects($object, $outputlangs)
 		elseif ($objecttype == 'fichinter')
 		{
 			$outputlangs->load('interventions');
-			foreach($objects as $elementobject)
+			foreach ($objects as $elementobject)
 			{
 				$linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("InterRef");
 				$linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref);

+ 124 - 124
htdocs/core/lib/security2.lib.php

@@ -34,9 +34,9 @@
  */
 function dol_getwebuser($mode)
 {
-    $t='?';
-    if ($mode=='user')  $t=getenv('APACHE_RUN_USER');   // $_ENV['APACHE_RUN_USER'] is empty
-    if ($mode=='group') $t=getenv('APACHE_RUN_GROUP');
+    $t = '?';
+    if ($mode == 'user')  $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty
+    if ($mode == 'group') $t = getenv('APACHE_RUN_GROUP');
     return $t;
 }
 
@@ -52,11 +52,11 @@ function dol_getwebuser($mode)
  */
 function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode, $context = '')
 {
-	global $conf,$langs;
+	global $conf, $langs;
     //global $dolauthmode;    // To return authentication finally used
 
 	// Check parameters
-	if ($entitytotest == '') $entitytotest=1;
+	if ($entitytotest == '') $entitytotest = 1;
 
     dol_syslog("checkLoginPassEntity usertotest=".$usertotest." entitytotest=".$entitytotest." authmode=".join(',', $authmode));
 	$login = '';
@@ -64,42 +64,42 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth
 	// Validation of login/pass/entity with standard modules
 	if (empty($login))
 	{
-	    $test=true;
-    	foreach($authmode as $mode)
+	    $test = true;
+    	foreach ($authmode as $mode)
     	{
-    		if ($test && $mode && ! $login)
+    		if ($test && $mode && !$login)
     		{
     		    // Validation of login/pass/entity for mode $mode
-    		    $mode=trim($mode);
-        		$authfile='functions_'.$mode.'.php';
-        		$fullauthfile='';
+    		    $mode = trim($mode);
+        		$authfile = 'functions_'.$mode.'.php';
+        		$fullauthfile = '';
 
-    		    $dirlogin=array_merge(array("/core/login"), (array) $conf->modules_parts['login']);
-    		    foreach($dirlogin as $reldir)
+    		    $dirlogin = array_merge(array("/core/login"), (array) $conf->modules_parts['login']);
+    		    foreach ($dirlogin as $reldir)
     		    {
-    		        $dir=dol_buildpath($reldir, 0);
-    		        $newdir=dol_osencode($dir);
+    		        $dir = dol_buildpath($reldir, 0);
+    		        $newdir = dol_osencode($dir);
 
     		        // Check if file found (do not use dol_is_file to avoid loading files.lib.php)
-    		        $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir)?'':'/').$authfile;
-    		        if (is_file($tmpnewauthfile)) $fullauthfile=$tmpnewauthfile;
+    		        $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir) ? '' : '/').$authfile;
+    		        if (is_file($tmpnewauthfile)) $fullauthfile = $tmpnewauthfile;
     		    }
 
-    		    $result=false;
-    		    if ($fullauthfile) $result=include_once $fullauthfile;
+    		    $result = false;
+    		    if ($fullauthfile) $result = include_once $fullauthfile;
     			if ($fullauthfile && $result)
     			{
     				// Call function to check user/password
-    				$function='check_user_password_'.$mode;
-    				$login=call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context);
+    				$function = 'check_user_password_'.$mode;
+    				$login = call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context);
     				if ($login)	// Login is successfull
     				{
-    					$test=false;            // To stop once at first login success
-    					$conf->authmode=$mode;	// This properties is defined only when logged to say what mode was successfully used
-    					$dol_tz=GETPOST('tz');
-    					$dol_dst=GETPOST('dst');
-    					$dol_screenwidth=GETPOST('screenwidth');
-    					$dol_screenheight=GETPOST('screenheight');
+    					$test = false; // To stop once at first login success
+    					$conf->authmode = $mode; // This properties is defined only when logged to say what mode was successfully used
+    					$dol_tz = GETPOST('tz');
+    					$dol_dst = GETPOST('dst');
+    					$dol_screenwidth = GETPOST('screenwidth');
+    					$dol_screenheight = GETPOST('screenheight');
     				}
     			}
     			else
@@ -109,7 +109,7 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth
     				// Load translation files required by the page
                     $langs->loadLangs(array('other', 'main', 'errors'));
 
-    				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorFailedToLoadLoginFileForMode", $mode);
+    				$_SESSION["dol_loginmesg"] = $langs->trans("ErrorFailedToLoadLoginFileForMode", $mode);
     			}
     		}
     	}
@@ -119,7 +119,7 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth
 }
 
 
-if (! function_exists('dol_loginfunction'))
+if (!function_exists('dol_loginfunction'))
 {
     /**
      * Show Dolibarr default login page.
@@ -135,22 +135,22 @@ if (! function_exists('dol_loginfunction'))
 		global $dolibarr_main_demo, $db;
 		global $hookmanager;
 
-		$langs->loadLangs(array("main","other","help","admin"));
+		$langs->loadLangs(array("main", "other", "help", "admin"));
 
 		// Instantiate hooks of thirdparty module only if not already define
 		$hookmanager->initHooks(array('mainloginpage'));
 
-		$main_authentication=$conf->file->main_authentication;
+		$main_authentication = $conf->file->main_authentication;
 
-		$session_name=session_name();	// Get current session name
+		$session_name = session_name(); // Get current session name
 
 		$dol_url_root = DOL_URL_ROOT;
 
 		// Title
-		$appli=constant('DOL_APPLICATION_TITLE');
-		$title=$appli.' '.constant('DOL_VERSION');
-		if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $title=$conf->global->MAIN_APPLICATION_TITLE;
-		$titletruedolibarrversion=constant('DOL_VERSION');	// $title used by login template after the @ to inform of true Dolibarr version
+		$appli = constant('DOL_APPLICATION_TITLE');
+		$title = $appli.' '.constant('DOL_VERSION');
+		if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = $conf->global->MAIN_APPLICATION_TITLE;
+		$titletruedolibarrversion = constant('DOL_VERSION'); // $title used by login template after the @ to inform of true Dolibarr version
 
 		// Note: $conf->css looks like '/theme/eldy/style.css.php'
 		/*
@@ -171,13 +171,13 @@ if (! function_exists('dol_loginfunction'))
 		*/
 
 		// Select templates dir
-		if (! empty($conf->modules_parts['tpl']))	// Using this feature slow down application
+		if (!empty($conf->modules_parts['tpl']))	// Using this feature slow down application
 		{
-			$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)
 			{
-				$tmp=dol_buildpath($reldir.'login.tpl.php');
-				if (file_exists($tmp)) { $template_dir=preg_replace('/login\.tpl\.php$/', '', $tmp); break; }
+				$tmp = dol_buildpath($reldir.'login.tpl.php');
+				if (file_exists($tmp)) { $template_dir = preg_replace('/login\.tpl\.php$/', '', $tmp); break; }
 			}
 		}
 		else
@@ -186,116 +186,116 @@ if (! function_exists('dol_loginfunction'))
 		}
 
 		// Set cookie for timeout management
-		$prefix=dol_getprefix('');
-		$sessiontimeout='DOLSESSTIMEOUT_'.$prefix;
-		if (! empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, false, true);
+		$prefix = dol_getprefix('');
+		$sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix;
+		if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, false, true);
 
-		if (GETPOST('urlfrom', 'alpha')) $_SESSION["urlfrom"]=GETPOST('urlfrom', 'alpha');
+		if (GETPOST('urlfrom', 'alpha')) $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha');
 		else unset($_SESSION["urlfrom"]);
 
-		if (! GETPOST("username", 'alpha')) $focus_element='username';
-		else $focus_element='password';
+		if (!GETPOST("username", 'alpha')) $focus_element = 'username';
+		else $focus_element = 'password';
 
-		$demologin='';
-		$demopassword='';
-		if (! empty($dolibarr_main_demo))
+		$demologin = '';
+		$demopassword = '';
+		if (!empty($dolibarr_main_demo))
 		{
-			$tab=explode(',', $dolibarr_main_demo);
-			$demologin=$tab[0];
-			$demopassword=$tab[1];
+			$tab = explode(',', $dolibarr_main_demo);
+			$demologin = $tab[0];
+			$demopassword = $tab[1];
 		}
 
 		// Execute hook getLoginPageOptions (for table)
-		$parameters=array('entity' => GETPOST('entity', 'int'));
-		$reshook = $hookmanager->executeHooks('getLoginPageOptions', $parameters);    // Note that $action and $object may have been modified by some hooks.
+		$parameters = array('entity' => GETPOST('entity', 'int'));
+		$reshook = $hookmanager->executeHooks('getLoginPageOptions', $parameters); // Note that $action and $object may have been modified by some hooks.
 		$morelogincontent = $hookmanager->resPrint;
 
 		// Execute hook getLoginPageExtraOptions (eg for js)
-		$parameters=array('entity' => GETPOST('entity', 'int'));
-		$reshook = $hookmanager->executeHooks('getLoginPageExtraOptions', $parameters);    // Note that $action and $object may have been modified by some hooks.
+		$parameters = array('entity' => GETPOST('entity', 'int'));
+		$reshook = $hookmanager->executeHooks('getLoginPageExtraOptions', $parameters); // Note that $action and $object may have been modified by some hooks.
 		$moreloginextracontent = $hookmanager->resPrint;
 
 		// Login
-		$login = (! empty($hookmanager->resArray['username']) ? $hookmanager->resArray['username'] : (GETPOST("username", "alpha") ? GETPOST("username", "alpha") : $demologin));
+		$login = (!empty($hookmanager->resArray['username']) ? $hookmanager->resArray['username'] : (GETPOST("username", "alpha") ? GETPOST("username", "alpha") : $demologin));
 		$password = $demopassword;
 
 		// Show logo (search in order: small company logo, large company logo, theme logo, common logo)
-		$width=0;
-		$urllogo=DOL_URL_ROOT.'/theme/login_logo.png';
+		$width = 0;
+		$urllogo = DOL_URL_ROOT.'/theme/login_logo.png';
 
-		if (! empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small))
+		if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small))
 		{
-			$urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small);
+			$urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small);
 		}
-		elseif (! empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo))
+		elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo))
 		{
-			$urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.$mysoc->logo);
-			$width=128;
+			$urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.$mysoc->logo);
+			$width = 128;
 		}
 		elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png'))
 		{
-			$urllogo=DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png';
+			$urllogo = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png';
 		}
 		elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.png'))
 		{
-			$urllogo=DOL_URL_ROOT.'/theme/dolibarr_logo.png';
+			$urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.png';
 		}
 
 		// Security graphical code
-		$captcha=0;
-		$captcha_refresh='';
-		if (function_exists("imagecreatefrompng") && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
+		$captcha = 0;
+		$captcha_refresh = '';
+		if (function_exists("imagecreatefrompng") && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
 		{
-			$captcha=1;
-			$captcha_refresh=img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"');
+			$captcha = 1;
+			$captcha_refresh = img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"');
 		}
 
 		// Extra link
-		$forgetpasslink=0;
-		$helpcenterlink=0;
+		$forgetpasslink = 0;
+		$helpcenterlink = 0;
 		if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK))
 		{
 			if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK))
 			{
-				$forgetpasslink=1;
+				$forgetpasslink = 1;
 			}
 
 			if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK))
 			{
-				$helpcenterlink=1;
+				$helpcenterlink = 1;
 			}
 		}
 
 		// Home message
-		$main_home='';
-		if (! empty($conf->global->MAIN_HOME))
+		$main_home = '';
+		if (!empty($conf->global->MAIN_HOME))
 		{
-		    $substitutionarray=getCommonSubstitutionArray($langs);
+		    $substitutionarray = getCommonSubstitutionArray($langs);
 		    complete_substitutions_array($substitutionarray, $langs);
 		    $texttoshow = make_substitutions($conf->global->MAIN_HOME, $substitutionarray, $langs);
 
-			$main_home=dol_htmlcleanlastbr($texttoshow);
+			$main_home = dol_htmlcleanlastbr($texttoshow);
 		}
 
 		// Google AD
-		$main_google_ad_client = ((! empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && ! empty($conf->global->MAIN_GOOGLE_AD_SLOT))?1:0);
+		$main_google_ad_client = ((!empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) ? 1 : 0);
 
 		// Set jquery theme
-		$dol_loginmesg = (! empty($_SESSION["dol_loginmesg"])?$_SESSION["dol_loginmesg"]:'');
+		$dol_loginmesg = (!empty($_SESSION["dol_loginmesg"]) ? $_SESSION["dol_loginmesg"] : '');
 
 		$favicon = DOL_URL_ROOT.'/theme/dolibarr_logo_256x256.png';
-		if (! empty($mysoc->logo_squarred_mini)) $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini);
-		if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
+		if (!empty($mysoc->logo_squarred_mini)) $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini);
+		if (!empty($conf->global->MAIN_FAVICON_URL)) $favicon = $conf->global->MAIN_FAVICON_URL;
 
 		$jquerytheme = 'base';
-		if (! empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
+		if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
 
 		// Set dol_hide_topmenu, dol_hide_leftmenu, dol_optimize_smallscreen, dol_no_mouse_hover
-		$dol_hide_topmenu=GETPOST('dol_hide_topmenu', 'int');
-		$dol_hide_leftmenu=GETPOST('dol_hide_leftmenu', 'int');
-		$dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen', 'int');
-		$dol_no_mouse_hover=GETPOST('dol_no_mouse_hover', 'int');
-		$dol_use_jmobile=GETPOST('dol_use_jmobile', 'int');
+		$dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int');
+		$dol_hide_leftmenu = GETPOST('dol_hide_leftmenu', 'int');
+		$dol_optimize_smallscreen = GETPOST('dol_optimize_smallscreen', 'int');
+		$dol_no_mouse_hover = GETPOST('dol_no_mouse_hover', 'int');
+		$dol_use_jmobile = GETPOST('dol_use_jmobile', 'int');
 
 		// Include login page template
 		include $template_dir.'login.tpl.php';
@@ -316,20 +316,20 @@ if (! function_exists('dol_loginfunction'))
 function makesalt($type = CRYPT_SALT_LENGTH)
 {
 	dol_syslog("makesalt type=".$type);
-	switch($type)
+	switch ($type)
 	{
 		case 12:	// 8 + 4
-			$saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break;
+			$saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; break;
 		case 8:		// 8 (Pour compatibilite, ne devrait pas etre utilise)
-			$saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break;
+			$saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; break;
 		case 2:		// 2
 		default: 	// by default, fall back on Standard DES (should work everywhere)
-			$saltlen=2; $saltprefix=''; $saltsuffix=''; break;
+			$saltlen = 2; $saltprefix = ''; $saltsuffix = ''; break;
 	}
-	$salt='';
-	while(dol_strlen($salt) < $saltlen) $salt.=chr(mt_rand(64, 126));
+	$salt = '';
+	while (dol_strlen($salt) < $saltlen) $salt .= chr(mt_rand(64, 126));
 
-	$result=$saltprefix.$salt.$saltsuffix;
+	$result = $saltprefix.$salt.$saltsuffix;
 	dol_syslog("makesalt return=".$result);
 	return $result;
 }
@@ -344,35 +344,35 @@ function encodedecode_dbpassconf($level = 0)
 {
 	dol_syslog("encodedecode_dbpassconf level=".$level, LOG_DEBUG);
 	$config = '';
-	$passwd='';
-	$passwd_crypted='';
+	$passwd = '';
+	$passwd_crypted = '';
 
 	if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php', 'r'))
 	{
-		while(!feof($fp))
+		while (!feof($fp))
 		{
 			$buffer = fgets($fp, 4096);
 
-			$lineofpass=0;
+			$lineofpass = 0;
 
 			if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i', $buffer, $reg))	// Old way to save crypted value
 			{
-				$val = trim($reg[1]);	// This also remove CR/LF
-				$val=preg_replace('/^["\']/', '', $val);
-				$val=preg_replace('/["\'][\s;]*$/', '', $val);
-				if (! empty($val))
+				$val = trim($reg[1]); // This also remove CR/LF
+				$val = preg_replace('/^["\']/', '', $val);
+				$val = preg_replace('/["\'][\s;]*$/', '', $val);
+				if (!empty($val))
 				{
 					$passwd_crypted = $val;
 					$val = dol_decode($val);
 					$passwd = $val;
-					$lineofpass=1;
+					$lineofpass = 1;
 				}
 			}
 			elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg))
 			{
-				$val = trim($reg[1]);	// This also remove CR/LF
-				$val=preg_replace('/^["\']/', '', $val);
-				$val=preg_replace('/["\'][\s;]*$/', '', $val);
+				$val = trim($reg[1]); // This also remove CR/LF
+				$val = preg_replace('/^["\']/', '', $val);
+				$val = preg_replace('/["\'][\s;]*$/', '', $val);
 				if (preg_match('/crypted:/i', $buffer))
 				{
 					$val = preg_replace('/crypted:/i', '', $val);
@@ -386,7 +386,7 @@ function encodedecode_dbpassconf($level = 0)
 					$val = dol_encode($val);
 					$passwd_crypted = $val;
 				}
-				$lineofpass=1;
+				$lineofpass = 1;
 			}
 
 			// Output line
@@ -413,7 +413,7 @@ function encodedecode_dbpassconf($level = 0)
 		fclose($fp);
 
 		// Write new conf file
-		$file=DOL_DOCUMENT_ROOT.'/conf/conf.php';
+		$file = DOL_DOCUMENT_ROOT.'/conf/conf.php';
 		if ($fp = @fopen($file, 'w'))
 		{
 			fputs($fp, $config);
@@ -451,17 +451,17 @@ function encodedecode_dbpassconf($level = 0)
  */
 function getRandomPassword($generic = false, $replaceambiguouschars = null, $length = 32)
 {
-	global $db,$conf,$langs,$user;
+	global $db, $conf, $langs, $user;
 
-	$generated_password='';
+	$generated_password = '';
 	if ($generic)
 	{
 		$lowercase = "qwertyuiopasdfghjklzxcvbnm";
 		$uppercase = "ASDFGHJKLZXCVBNMQWERTYUIOP";
 		$numbers = "1234567890";
 		$randomCode = "";
-		$nbofchar = round($length/3);
-		$nbofcharlast = ($length - 2*$nbofchar);
+		$nbofchar = round($length / 3);
+		$nbofcharlast = ($length - 2 * $nbofchar);
 		//var_dump($nbofchar.'-'.$nbofcharlast);
 		if (function_exists('random_int'))	// Cryptographic random
 		{
@@ -478,7 +478,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len
 				$randomCode .= $numbers{random_int(0, $max)};
 			}
 
-			$generated_password=str_shuffle($randomCode);
+			$generated_password = str_shuffle($randomCode);
 		}
 		else	// Old platform, non cryptographic random
 		{
@@ -495,17 +495,17 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len
 				$randomCode .= $numbers{mt_rand(0, $max)};
 			}
 
-			$generated_password=str_shuffle($randomCode);
+			$generated_password = str_shuffle($randomCode);
 		}
 	}
-	elseif (! empty($conf->global->USER_PASSWORD_GENERATED))
+	elseif (!empty($conf->global->USER_PASSWORD_GENERATED))
 	{
-		$nomclass="modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED);
-		$nomfichier=$nomclass.".class.php";
+		$nomclass = "modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED);
+		$nomfichier = $nomclass.".class.php";
 		//print DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomclass;
 		require_once DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomfichier;
-		$genhandler=new $nomclass($db, $conf, $langs, $user);
-		$generated_password=$genhandler->getNewGeneratedPassword();
+		$genhandler = new $nomclass($db, $conf, $langs, $user);
+		$generated_password = $genhandler->getNewGeneratedPassword();
 		unset($genhandler);
 	}
 
@@ -516,11 +516,11 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len
 		$max = strlen($numbers) - 1;
 		if (function_exists('random_int'))	// Cryptographic random
 		{
-			$generated_password=str_replace($replaceambiguouschars, $numbers{random_int(0, $max)}, $generated_password);
+			$generated_password = str_replace($replaceambiguouschars, $numbers{random_int(0, $max)}, $generated_password);
 		}
 		else
 		{
-			$generated_password=str_replace($replaceambiguouschars, $numbers{mt_rand(0, $max)}, $generated_password);
+			$generated_password = str_replace($replaceambiguouschars, $numbers{mt_rand(0, $max)}, $generated_password);
 		}
 	}
 

Файловите разлики са ограничени, защото са твърде много
+ 229 - 229
htdocs/core/modules/commande/doc/pdf_einstein.modules.php


+ 179 - 179
htdocs/core/modules/commande/doc/pdf_eratosthene.modules.php

@@ -136,45 +136,45 @@ class pdf_eratosthene extends ModelePDFCommandes
 		$this->db = $db;
 		$this->name = "eratosthene";
 		$this->description = $langs->trans('PDFEratostheneDescription');
-		$this->update_main_doc_field = 1;		// Save the name of generated file as the main doc when generating a doc with this template
+		$this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template
 
 		// Dimension page
 		$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->option_logo = 1;                    // Display logo
-		$this->option_tva = 1;                     // Manage the vat option FACTURE_TVAOPTION
-		$this->option_modereg = 1;                 // Display payment mode
-		$this->option_condreg = 1;                 // Display payment terms
-		$this->option_codeproduitservice = 1;      // Display product-service code
-		$this->option_multilang = 1;               // Available in several languages
-		$this->option_escompte = 0;                // Displays if there has been a discount
-		$this->option_credit_note = 0;             // Support credit notes
-		$this->option_freetext = 1;				   // Support add of a personalised text
-		$this->option_draft_watermark = 1;		   // Support add of a watermark on drafts
+		$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; // Display logo
+		$this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION
+		$this->option_modereg = 1; // Display payment mode
+		$this->option_condreg = 1; // Display payment terms
+		$this->option_codeproduitservice = 1; // Display product-service code
+		$this->option_multilang = 1; // Available in several languages
+		$this->option_escompte = 0; // Displays if there has been a discount
+		$this->option_credit_note = 0; // Support credit notes
+		$this->option_freetext = 1; // Support add of a personalised text
+		$this->option_draft_watermark = 1; // Support add of a watermark on drafts
 
 		// Get source company
-		$this->emetteur=$mysoc;
-		if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2);    // By default, if was not defined
+		$this->emetteur = $mysoc;
+		if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined
 
 		// Define position of columns
-		$this->posxdesc=$this->marge_gauche+1;
+		$this->posxdesc = $this->marge_gauche + 1;
 
 
 		$this->tabTitleHeight = 5; // default height
 
-		$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;
 	}
 
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
@@ -194,14 +194,14 @@ class pdf_eratosthene extends ModelePDFCommandes
 	    // phpcs:enable
 		global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines;
 
-		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 translation files required by the page
 		$outputlangs->loadLangs(array("main", "dict", "companies", "bills", "products", "orders", "deliveries"));
 
-		if (! empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
+		if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
 			global $outputlangsbis;
 			$outputlangsbis = new Translate('', $conf);
 			$outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE);
@@ -210,39 +210,39 @@ class pdf_eratosthene extends ModelePDFCommandes
 
 		$nblines = count($object->lines);
 
-		$hidetop=0;
-		if(!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)){
-		    $hidetop=$conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE;
+		$hidetop = 0;
+		if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) {
+		    $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE;
 		}
 
 		// Loop on each lines to detect if there is at least one image to show
-		$realpatharray=array();
+		$realpatharray = array();
 		$this->atleastonephoto = false;
-		if (! empty($conf->global->MAIN_GENERATE_ORDERS_WITH_PICTURE))
+		if (!empty($conf->global->MAIN_GENERATE_ORDERS_WITH_PICTURE))
 		{
 		    $objphoto = new Product($this->db);
 
-		    for ($i = 0 ; $i < $nblines ; $i++)
+		    for ($i = 0; $i < $nblines; $i++)
 		    {
 		        if (empty($object->lines[$i]->fk_product)) continue;
 
 		        $objphoto->fetch($object->lines[$i]->fk_product);
 		        //var_dump($objphoto->ref);exit;
-		        if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
+		        if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
 		        {
-		            $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/";
-		            $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/';
+		            $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/";
+		            $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/';
 		        }
 		        else
 		        {
-		            $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/';				// default
-		            $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/";	// alternative
+		            $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default
+		            $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative
 		        }
 
 		        $arephoto = false;
 		        foreach ($pdir as $midir)
 		        {
-		            if (! $arephoto)
+		            if (!$arephoto)
 		            {
 		                $dir = $conf->product->dir_output.'/'.$midir;
 
@@ -287,20 +287,20 @@ class pdf_eratosthene extends ModelePDFCommandes
 			if ($object->specimen)
 			{
 				$dir = $conf->commande->multidir_output[$conf->entity];
-				$file = $dir . "/SPECIMEN.pdf";
+				$file = $dir."/SPECIMEN.pdf";
 			}
 			else
 			{
 				$objectref = dol_sanitizeFileName($object->ref);
-				$dir = $conf->commande->multidir_output[$object->entity] . "/" . $objectref;
-				$file = $dir . "/" . $objectref . ".pdf";
+				$dir = $conf->commande->multidir_output[$object->entity]."/".$objectref;
+				$file = $dir."/".$objectref.".pdf";
 			}
 
-			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 0;
 				}
 			}
@@ -334,14 +334,14 @@ class pdf_eratosthene extends ModelePDFCommandes
                 }
                 $pdf->SetFont(pdf_getPDFFont($outputlangs));
                 // Set path to the background PDF File
-                if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
+                if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
                 {
                 	$pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$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));
@@ -364,16 +364,16 @@ class pdf_eratosthene extends ModelePDFCommandes
 
 				// New page
 				$pdf->AddPage();
-				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+				if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 				$pagenb++;
 				$top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs);
 				$pdf->SetFont('', '', $default_font_size - 1);
-				$pdf->MultiCell(0, 3, '');		// Set interline to 3
+				$pdf->MultiCell(0, 3, ''); // Set interline to 3
 				$pdf->SetTextColor(0, 0, 0);
 
 
-				$tab_top = 90+$top_shift;
-				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42+$top_shift:10);
+				$tab_top = 90 + $top_shift;
+				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10);
 
 				// Incoterm
 				if ($conf->incoterm->enabled)
@@ -384,39 +384,39 @@ class pdf_eratosthene extends ModelePDFCommandes
 						$tab_top -= 2;
 
 						$pdf->SetFont('', '', $default_font_size - 1);
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
+						$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
 						$nexY = $pdf->GetY();
-						$height_incoterms=$nexY-$tab_top;
+						$height_incoterms = $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_incoterms+1);
+						$pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1);
 
-						$tab_top = $nexY+6;
+						$tab_top = $nexY + 6;
 					}
 				}
 
 				// Displays notes
-				$notetoshow=empty($object->note_public)?'':$object->note_public;
-				if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE))
+				$notetoshow = empty($object->note_public) ? '' : $object->note_public;
+				if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE))
 				{
 					// Get first sale rep
 					if (is_object($object->thirdparty))
 					{
-						$salereparray=$object->thirdparty->getSalesRepresentatives($user);
-						$salerepobj=new User($this->db);
+						$salereparray = $object->thirdparty->getSalesRepresentatives($user);
+						$salerepobj = new User($this->db);
 						$salerepobj->fetch($salereparray[0]['id']);
-						if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature);
+						if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature);
 					}
 				}
 
 				$pagenb = $pdf->getPage();
 				if ($notetoshow)
 				{
-				    $tab_width = $this->page_largeur-$this->marge_gauche-$this->marge_droite;
+				    $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite;
 				    $pageposbeforenote = $pagenb;
 
-				    $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);
@@ -544,85 +544,85 @@ class pdf_eratosthene extends ModelePDFCommandes
 				$nexY = $tab_top + $this->tabTitleHeight + 2;
 
 				// Loop on each lines
-				$pageposbeforeprintlines=$pdf->getPage();
+				$pageposbeforeprintlines = $pdf->getPage();
 				$pagenb = $pageposbeforeprintlines;
-				for ($i = 0 ; $i < $nblines ; $i++)
+				for ($i = 0; $i < $nblines; $i++)
 				{
 					$curY = $nexY;
-					$pdf->SetFont('', '', $default_font_size - 1);   // Into loop to work with multipage
+					$pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage
 					$pdf->SetTextColor(0, 0, 0);
 
 					// Define size of image if we need it
-					$imglinesize=array();
-					if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
+					$imglinesize = array();
+					if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]);
 
 					$pdf->setTopMargin($tab_top_newpage);
-					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
-					$pageposbefore=$pdf->getPage();
+					$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
+					$pageposbefore = $pdf->getPage();
 
 					// Description of product line
-					$curX = $this->posxdesc-1;
+					$curX = $this->posxdesc - 1;
 
-					$showpricebeforepagebreak=1;
-					$posYAfterImage=0;
-					$posYAfterDescription=0;
+					$showpricebeforepagebreak = 1;
+					$posYAfterImage = 0;
+					$posYAfterDescription = 0;
 
-					if($this->getColumnStatus('photo'))
+					if ($this->getColumnStatus('photo'))
 					{
 					    // We start with Photo of product line
-					    if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot)))	// If photo too high, we moved completely on new page
+					    if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)))	// If photo too high, we moved completely on new page
 					    {
 					        $pdf->AddPage('', '', true);
-					        if (! empty($tplidx)) $pdf->useTemplate($tplidx);
-					        $pdf->setPage($pageposbefore+1);
+					        if (!empty($tplidx)) $pdf->useTemplate($tplidx);
+					        $pdf->setPage($pageposbefore + 1);
 
 					        $curY = $tab_top_newpage;
-					        $showpricebeforepagebreak=0;
+					        $showpricebeforepagebreak = 0;
 					    }
 
 					    if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height']))
 					    {
-					        $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300);	// Use 300 dpi
+					        $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi
 					        // $pdf->Image does not increase value return by getY, so we save it manually
-					        $posYAfterImage=$curY+$imglinesize['height'];
+					        $posYAfterImage = $curY + $imglinesize['height'];
 					    }
 					}
 
-					if($this->getColumnStatus('desc'))
+					if ($this->getColumnStatus('desc'))
 					{
     					$pdf->startTransaction();
     					pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc);
-    					$pageposafter=$pdf->getPage();
+    					$pageposafter = $pdf->getPage();
     					if ($pageposafter > $pageposbefore)	// There is a pagebreak
     					{
     						$pdf->rollbackTransaction(true);
-    						$pageposafter=$pageposbefore;
+    						$pageposafter = $pageposbefore;
     						//print $pageposafter.'-'.$pageposbefore;exit;
-    						$pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
+    						$pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
     						pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc);
-    						$pageposafter=$pdf->getPage();
-    						$posyafter=$pdf->GetY();
-    						if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot)))	// There is no space left for total+free text
+    						$pageposafter = $pdf->getPage();
+    						$posyafter = $pdf->GetY();
+    						if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)))	// There is no space left for total+free text
     						{
-    							if ($i == ($nblines-1))	// No more lines, and no space left to show total, so we create a new page
+    							if ($i == ($nblines - 1))	// No more lines, and no space left to show total, so we create a new page
     							{
     								$pdf->AddPage('', '', true);
-    								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+    								if (!empty($tplidx)) $pdf->useTemplate($tplidx);
     								//if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-    								$pdf->setPage($pageposafter+1);
+    								$pdf->setPage($pageposafter + 1);
     							}
     						}
     						else
     						{
     							// We found a page break
-    							$showpricebeforepagebreak=0;
+    							$showpricebeforepagebreak = 0;
     						}
     					}
     					else	// No pagebreak
     					{
     						$pdf->commitTransaction();
     					}
-    					$posYAfterDescription=$pdf->GetY();
+    					$posYAfterDescription = $pdf->GetY();
 					}
 
 
@@ -630,18 +630,18 @@ class pdf_eratosthene extends ModelePDFCommandes
 					$nexY = max($pdf->GetY(), $posYAfterImage);
 
 
-					$pageposafter=$pdf->getPage();
+					$pageposafter = $pdf->getPage();
 
 					$pdf->setPage($pageposbefore);
 					$pdf->setTopMargin($this->marge_haute);
-					$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.
 
 					// We suppose that a too long description is moved completely on next page
 					if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
 						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
 					}
 
-					$pdf->SetFont('', '', $default_font_size - 1);   // We reposition the default font
+					$pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font
 
 					// VAT Rate
 					if ($this->getColumnStatus('vat'))
@@ -703,56 +703,56 @@ class pdf_eratosthene extends ModelePDFCommandes
 					    'outputlangs' => $outputlangs,
 					    'hidedetails' => $hidedetails
 					);
-					$reshook=$hookmanager->executeHooks('printPDFline', $parameters, $this);    // Note that $object may have been modified by hook
+					$reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook
 
 
 					// Collection of totals by value of vat in $this->tva["rate"] = total_tva
-					if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne=$object->lines[$i]->multicurrency_total_tva;
-					else $tvaligne=$object->lines[$i]->total_tva;
+					if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva;
+					else $tvaligne = $object->lines[$i]->total_tva;
 
-					$localtax1ligne=$object->lines[$i]->total_localtax1;
-					$localtax2ligne=$object->lines[$i]->total_localtax2;
-					$localtax1_rate=$object->lines[$i]->localtax1_tx;
-					$localtax2_rate=$object->lines[$i]->localtax2_tx;
-					$localtax1_type=$object->lines[$i]->localtax1_type;
-					$localtax2_type=$object->lines[$i]->localtax2_type;
+					$localtax1ligne = $object->lines[$i]->total_localtax1;
+					$localtax2ligne = $object->lines[$i]->total_localtax2;
+					$localtax1_rate = $object->lines[$i]->localtax1_tx;
+					$localtax2_rate = $object->lines[$i]->localtax2_tx;
+					$localtax1_type = $object->lines[$i]->localtax1_type;
+					$localtax2_type = $object->lines[$i]->localtax2_type;
 
-					if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100;
-					if ($object->remise_percent) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100;
-					if ($object->remise_percent) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100;
+					if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100;
+					if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100;
+					if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100;
 
-					$vatrate=(string) $object->lines[$i]->tva_tx;
+					$vatrate = (string) $object->lines[$i]->tva_tx;
 
 					// Retrieve type from database for backward compatibility with old records
-					if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined
-					&& (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax
+					if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined
+					&& (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax
 					{
-						$localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc);
+						$localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc);
 						$localtax1_type = $localtaxtmp_array[0];
 						$localtax2_type = $localtaxtmp_array[2];
 					}
 
 				    // retrieve global local tax
 					if ($localtax1_type && $localtax1ligne != 0)
-						$this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne;
+						$this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne;
 					if ($localtax2_type && $localtax2ligne != 0)
-						$this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne;
+						$this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne;
 
-					if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*';
-					if (! isset($this->tva[$vatrate])) 				$this->tva[$vatrate]=0;
+					if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*';
+					if (!isset($this->tva[$vatrate])) 				$this->tva[$vatrate] = 0;
 					$this->tva[$vatrate] += $tvaligne;
 
 					// 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)
@@ -822,31 +822,31 @@ class pdf_eratosthene extends ModelePDFCommandes
 
 				// 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->transnoentities("ErrorCanNotCreateDir", $dir);
+				$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
 				return 0;
 			}
 		}
 		else
 		{
-			$this->error=$langs->transnoentities("ErrorConstantNotDefined", "COMMANDE_OUTPUTDIR");
+			$this->error = $langs->transnoentities("ErrorConstantNotDefined", "COMMANDE_OUTPUTDIR");
 			return 0;
 		}
 	}
@@ -1080,7 +1080,7 @@ class pdf_eratosthene extends ModelePDFCommandes
 		$index = 0;
 
 		$outputlangsbis = null;
-		if (! empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
+		if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
 			$outputlangsbis = new Translate('', $conf);
 			$outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE);
 			$outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "propal"));
@@ -1112,27 +1112,27 @@ class pdf_eratosthene extends ModelePDFCommandes
 				//Local tax 1 before VAT
 				//if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on')
 				//{
-				foreach($this->localtax1 as $localtax_type => $localtax_rate)
+				foreach ($this->localtax1 as $localtax_type => $localtax_rate)
 				{
-					if (in_array((string) $localtax_type, array('1','3','5'))) continue;
-					foreach($localtax_rate as $tvakey => $tvaval)
+					if (in_array((string) $localtax_type, array('1', '3', '5'))) continue;
+					foreach ($localtax_rate as $tvakey => $tvaval)
 					{
-						if ($tvakey!=0)    // On affiche pas taux 0
+						if ($tvakey != 0)    // On affiche pas taux 0
 						{
 							//$this->atleastoneratenotnull++;
 							$index++;
 							$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
 
-							$tvacompl='';
+							$tvacompl = '';
 							if (preg_match('/\*/', $tvakey))
 							{
-								$tvakey=str_replace('*', '', $tvakey);
+								$tvakey = str_replace('*', '', $tvakey);
 								$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 							}
 							$totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : '');
-							$totalvat.=' ';
-							$totalvat.=vatrate(abs($tvakey), 1).$tvacompl;
-							$pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1);
+							$totalvat .= ' ';
+							$totalvat .= vatrate(abs($tvakey), 1).$tvacompl;
+							$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 
 							$pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index);
 							$pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1);
@@ -1143,28 +1143,28 @@ class pdf_eratosthene extends ModelePDFCommandes
 				//Local tax 2 before VAT
 				//if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on')
 				//{
-				foreach($this->localtax2 as $localtax_type => $localtax_rate)
+				foreach ($this->localtax2 as $localtax_type => $localtax_rate)
 				{
-					if (in_array((string) $localtax_type, array('1','3','5'))) continue;
-					foreach($localtax_rate as $tvakey => $tvaval)
+					if (in_array((string) $localtax_type, array('1', '3', '5'))) continue;
+					foreach ($localtax_rate as $tvakey => $tvaval)
 					{
-						if ($tvakey!=0)    // On affiche pas taux 0
+						if ($tvakey != 0)    // On affiche pas taux 0
 						{
 							//$this->atleastoneratenotnull++;
 
 							$index++;
 							$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
 
-							$tvacompl='';
+							$tvacompl = '';
 							if (preg_match('/\*/', $tvakey))
 							{
-								$tvakey=str_replace('*', '', $tvakey);
+								$tvakey = str_replace('*', '', $tvakey);
 								$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 							}
 							$totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : '');
-							$totalvat.=' ';
-							$totalvat.=vatrate(abs($tvakey), 1).$tvacompl;
-							$pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1);
+							$totalvat .= ' ';
+							$totalvat .= vatrate(abs($tvakey), 1).$tvacompl;
+							$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 
 							$pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index);
 							$pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1);
@@ -1189,7 +1189,7 @@ class pdf_eratosthene extends ModelePDFCommandes
 							$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 						}
 						$totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalVAT", $mysoc->country_code) : '');
-						$totalvat.=' ';
+						$totalvat .= ' ';
 						$totalvat .= vatrate($tvakey, 1).$tvacompl;
 						$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 
@@ -1201,11 +1201,11 @@ class pdf_eratosthene extends ModelePDFCommandes
 				//Local tax 1 after VAT
 				//if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on')
 				//{
-				foreach($this->localtax1 as $localtax_type => $localtax_rate)
+				foreach ($this->localtax1 as $localtax_type => $localtax_rate)
 				{
-					if (in_array((string) $localtax_type, array('2','4','6'))) continue;
+					if (in_array((string) $localtax_type, array('2', '4', '6'))) continue;
 
-					foreach($localtax_rate as $tvakey => $tvaval)
+					foreach ($localtax_rate as $tvakey => $tvaval)
 					{
 						if ($tvakey != 0)    // On affiche pas taux 0
 						{
@@ -1214,17 +1214,17 @@ class pdf_eratosthene extends ModelePDFCommandes
 							$index++;
 							$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
 
-							$tvacompl='';
+							$tvacompl = '';
 							if (preg_match('/\*/', $tvakey))
 							{
-								$tvakey=str_replace('*', '', $tvakey);
+								$tvakey = str_replace('*', '', $tvakey);
 								$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 							}
 							$totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : '');
-							$totalvat.=' ';
+							$totalvat .= ' ';
 
-							$totalvat.=vatrate(abs($tvakey), 1).$tvacompl;
-							$pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1);
+							$totalvat .= vatrate(abs($tvakey), 1).$tvacompl;
+							$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 							$pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index);
 							$pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1);
 						}
@@ -1234,11 +1234,11 @@ class pdf_eratosthene extends ModelePDFCommandes
 				//Local tax 2 after VAT
 				//if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on')
 				//{
-				foreach($this->localtax2 as $localtax_type => $localtax_rate)
+				foreach ($this->localtax2 as $localtax_type => $localtax_rate)
 				{
-					if (in_array((string) $localtax_type, array('2','4','6'))) continue;
+					if (in_array((string) $localtax_type, array('2', '4', '6'))) continue;
 
-					foreach($localtax_rate as $tvakey => $tvaval)
+					foreach ($localtax_rate as $tvakey => $tvaval)
 					{
 						if ($tvakey != 0)    // On affiche pas taux 0
 						{
@@ -1247,17 +1247,17 @@ class pdf_eratosthene extends ModelePDFCommandes
 							$index++;
 							$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
 
-							$tvacompl='';
+							$tvacompl = '';
 							if (preg_match('/\*/', $tvakey))
 							{
-								$tvakey=str_replace('*', '', $tvakey);
+								$tvakey = str_replace('*', '', $tvakey);
 								$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 							}
 							$totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : '');
-							$totalvat.=' ';
+							$totalvat .= ' ';
 
-							$totalvat.=vatrate(abs($tvakey), 1).$tvacompl;
-							$pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1);
+							$totalvat .= vatrate(abs($tvakey), 1).$tvacompl;
+							$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 
 							$pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index);
 							$pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1);
@@ -1347,12 +1347,12 @@ class pdf_eratosthene extends ModelePDFCommandes
 		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, $this->tabTitleHeight, '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, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
 			}
 		}
 
@@ -1360,13 +1360,13 @@ class pdf_eratosthene extends ModelePDFCommandes
 		$pdf->SetFont('', '', $default_font_size - 1);
 
 		// 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
+		$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
 
 
 		$this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop);
 
-		if (empty($hidetop)){
-		    $pdf->line($this->marge_gauche, $tab_top+$this->tabTitleHeight, $this->page_largeur-$this->marge_droite, $tab_top+$this->tabTitleHeight);	// line takes a position y in 2nd parameter and 4th parameter
+		if (empty($hidetop)) {
+		    $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter
 		}
 	}
 
@@ -1385,7 +1385,7 @@ class pdf_eratosthene extends ModelePDFCommandes
 	protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $titlekey = "PdfOrderTitle")
 	{
 		// phpcs:enable
-		global $conf,$langs,$hookmanager;
+		global $conf, $langs, $hookmanager;
 
 		// Load traductions files required by page
 		$outputlangs->loadLangs(array("main", "bills", "propal", "orders", "companies"));
@@ -1403,8 +1403,8 @@ class pdf_eratosthene extends ModelePDFCommandes
 		$pdf->SetTextColor(0, 0, 60);
 		$pdf->SetFont('', 'B', $default_font_size + 3);
 
-		$posy=$this->marge_haute;
-		$posx=$this->page_largeur-$this->marge_droite-100;
+		$posy = $this->marge_haute;
+		$posx = $this->page_largeur - $this->marge_droite - 100;
 
 		$pdf->SetXY($this->marge_gauche, $posy);
 
@@ -1414,7 +1414,7 @@ class pdf_eratosthene extends ModelePDFCommandes
 			if ($this->emetteur->logo)
 			{
 				$logodir = $conf->mycompany->dir_output;
-				if (! empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity];
+				if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity];
 				if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO))
 				{
 					$logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small;
@@ -1424,20 +1424,20 @@ class pdf_eratosthene extends ModelePDFCommandes
 				}
 				if (is_readable($logo))
 				{
-				    $height=pdf_getHeightForLogo($logo);
-				    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
+				    $height = pdf_getHeightForLogo($logo);
+				    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
 				}
 				else
 				{
 					$pdf->SetTextColor(200, 0, 0);
-					$pdf->SetFont('', 'B', $default_font_size -2);
+					$pdf->SetFont('', 'B', $default_font_size - 2);
 					$pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L');
 					$pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
 				}
 			}
 			else
 			{
-				$text=$this->emetteur->name;
+				$text = $this->emetteur->name;
 				$pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
 			}
 		}
@@ -1471,12 +1471,12 @@ class pdf_eratosthene extends ModelePDFCommandes
 		$pdf->SetTextColor(0, 0, 60);
 		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($object->date, "day", false, $outputlangs, true), '', 'R');
 
-		if (!empty($conf->global->DOC_SHOW_CUSTOMER_CODE) && ! empty($object->thirdparty->code_client))
+		if (!empty($conf->global->DOC_SHOW_CUSTOMER_CODE) && !empty($object->thirdparty->code_client))
 		{
-			$posy+=4;
+			$posy += 4;
 			$pdf->SetXY($posx, $posy);
 			$pdf->SetTextColor(0, 0, 60);
-			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
+			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
 		}
 
 		// Get contact

+ 137 - 137
htdocs/core/modules/expedition/doc/pdf_espadon.modules.php

@@ -168,7 +168,7 @@ class pdf_espadon extends ModelePdfExpedition
 		// Load traductions files required by page
 		$outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch"));
 
-		if (! empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
+		if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
 			global $outputlangsbis;
 			$outputlangsbis = new Translate('', $conf);
 			$outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE);
@@ -178,22 +178,22 @@ class pdf_espadon extends ModelePdfExpedition
 		$nblines = count($object->lines);
 
         // Loop on each lines to detect if there is at least one image to show
-        $realpatharray=array();
-        if (! empty($conf->global->MAIN_GENERATE_SHIPMENT_WITH_PICTURE))
+        $realpatharray = array();
+        if (!empty($conf->global->MAIN_GENERATE_SHIPMENT_WITH_PICTURE))
         {
             $objphoto = new Product($this->db);
 
-            for ($i = 0 ; $i < $nblines ; $i++)
+            for ($i = 0; $i < $nblines; $i++)
             {
                 if (empty($object->lines[$i]->fk_product)) continue;
 
 				$objphoto = new Product($this->db);
 				$objphoto->fetch($object->lines[$i]->fk_product);
 
-				$pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product') . $object->lines[$i]->fk_product ."/photos/";
+				$pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product').$object->lines[$i]->fk_product."/photos/";
 				$dir = $conf->product->dir_output.'/'.$pdir;
 
-				$realpath='';
+				$realpath = '';
 
                 foreach ($objphoto->liste_photos($dir, 1) as $key => $obj)
                 {
@@ -250,25 +250,25 @@ class pdf_espadon extends ModelePdfExpedition
 			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
 
 				// Set nblines with the new facture lines content after hook
 				$nblines = count($object->lines);
 
-				$pdf=pdf_getInstance($this->format);
+				$pdf = pdf_getInstance($this->format);
 				$default_font_size = pdf_getPDFFontSize($outputlangs);
-				$heightforinfotot = 8;	// 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 ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6;
+				$heightforinfotot = 8; // 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 ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6;
                 $pdf->SetAutoPageBreak(1, 0);
 
                 if (class_exists('TCPDF'))
@@ -323,51 +323,51 @@ class pdf_espadon extends ModelePdfExpedition
 						$tab_top = 88;
 
 						$pdf->SetFont('', '', $default_font_size - 1);
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
+						$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
 						$nexY = $pdf->GetY();
-						$height_incoterms=$nexY-$tab_top;
+						$height_incoterms = $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_incoterms+1);
+						$pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1);
 
-						$tab_top = $nexY+6;
+						$tab_top = $nexY + 6;
 						$height_incoterms += 4;
 					}
 				}
 
-				if (! empty($object->note_public) || ! empty($object->tracking_number))
+				if (!empty($object->note_public) || !empty($object->tracking_number))
 				{
 					$tab_top = 88 + $height_incoterms;
 					$tab_top_alt = $tab_top;
 
 					$pdf->SetFont('', 'B', $default_font_size - 2);
-					$pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top-1, $outputlangs->transnoentities("TrackingNumber")." : " . $object->tracking_number, 0, 1, false, true, 'L');
+					$pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top - 1, $outputlangs->transnoentities("TrackingNumber")." : ".$object->tracking_number, 0, 1, false, true, 'L');
 
 					$tab_top_alt = $pdf->GetY();
 					//$tab_top_alt += 1;
 
 					// Tracking number
-					if (! empty($object->tracking_number))
+					if (!empty($object->tracking_number))
 					{
 						$object->getUrlTrackingStatus($object->tracking_number);
-						if (! empty($object->tracking_url))
+						if (!empty($object->tracking_url))
 						{
 							if ($object->shipping_method_id > 0)
 							{
 								// Get code using getLabelFromKey
-								$code=$outputlangs->getLabelFromKey($this->db, $object->shipping_method_id, 'c_shipment_mode', 'rowid', 'code');
-								$label='';
-								if ($object->tracking_url != $object->tracking_number) $label.=$outputlangs->trans("LinkToTrackYourPackage")."<br>";
-								$label.=$outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code));
+								$code = $outputlangs->getLabelFromKey($this->db, $object->shipping_method_id, 'c_shipment_mode', 'rowid', 'code');
+								$label = '';
+								if ($object->tracking_url != $object->tracking_number) $label .= $outputlangs->trans("LinkToTrackYourPackage")."<br>";
+								$label .= $outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code));
 								//var_dump($object->tracking_url != $object->tracking_number);exit;
 								if ($object->tracking_url != $object->tracking_number)
 								{
-									$label.=" : ";
-									$label.=$object->tracking_url;
+									$label .= " : ";
+									$label .= $object->tracking_url;
 								}
 								$pdf->SetFont('', 'B', $default_font_size - 2);
-								$pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top_alt, $label, 0, 1, false, true, 'L');
+								$pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top_alt, $label, 0, 1, false, true, 'L');
 
 								$tab_top_alt = $pdf->GetY();
 							}
@@ -375,25 +375,25 @@ class pdf_espadon extends ModelePdfExpedition
 					}
 
 					// Notes
-					if (! empty($object->note_public))
+					if (!empty($object->note_public))
 					{
-					    $pdf->SetFont('', '', $default_font_size - 1);   // In loop to manage multi-page
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 0, 1);
+					    $pdf->SetFont('', '', $default_font_size - 1); // In loop to manage multi-page
+						$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 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;
 				}
 
 
@@ -414,90 +414,90 @@ class pdf_espadon extends ModelePdfExpedition
 				for ($i = 0; $i < $nblines; $i++)
 				{
 					$curY = $nexY;
-					$pdf->SetFont('', '', $default_font_size - 1);   // Into loop to work with multipage
+					$pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage
 					$pdf->SetTextColor(0, 0, 0);
 
 					// Define size of image if we need it
-					$imglinesize=array();
-					if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
+					$imglinesize = array();
+					if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]);
 
 					$pdf->setTopMargin($tab_top_newpage);
-					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
-					$pageposbefore=$pdf->getPage();
+					$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
+					$pageposbefore = $pdf->getPage();
 
-					$showpricebeforepagebreak=1;
-					$posYAfterImage=0;
-					$posYAfterDescription=0;
+					$showpricebeforepagebreak = 1;
+					$posYAfterImage = 0;
+					$posYAfterDescription = 0;
 
-					if($this->getColumnStatus('photo'))
+					if ($this->getColumnStatus('photo'))
 					{
 					    // We start with Photo of product line
-					    if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot)))	// If photo too high, we moved completely on new page
+					    if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot)))	// If photo too high, we moved completely on new page
 					    {
 					        $pdf->AddPage('', '', true);
-					        if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+					        if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 					        //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-					        $pdf->setPage($pageposbefore+1);
+					        $pdf->setPage($pageposbefore + 1);
 
 					        $curY = $tab_top_newpage;
-					        $showpricebeforepagebreak=0;
+					        $showpricebeforepagebreak = 0;
 					    }
 
 
 					    if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height']))
 					    {
-					        $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300);	// Use 300 dpi
+					        $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi
 					        // $pdf->Image does not increase value return by getY, so we save it manually
-					        $posYAfterImage=$curY+$imglinesize['height'];
+					        $posYAfterImage = $curY + $imglinesize['height'];
 					    }
 					}
 
 					// Description of product line
-					if($this->getColumnStatus('desc'))
+					if ($this->getColumnStatus('desc'))
 					{
 					    $pdf->startTransaction();
 					    pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc);
-					    $pageposafter=$pdf->getPage();
+					    $pageposafter = $pdf->getPage();
 					    if ($pageposafter > $pageposbefore)	// There is a pagebreak
 					    {
 					        $pdf->rollbackTransaction(true);
-					        $pageposafter=$pageposbefore;
+					        $pageposafter = $pageposbefore;
 					        //print $pageposafter.'-'.$pageposbefore;exit;
-					        $pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
+					        $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
 					        pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc);
 
-					        $pageposafter=$pdf->getPage();
-					        $posyafter=$pdf->GetY();
+					        $pageposafter = $pdf->getPage();
+					        $posyafter = $pdf->GetY();
 					        //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
-					        if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot)))	// There is no space left for total+free text
+					        if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot)))	// There is no space left for total+free text
 					        {
-					            if ($i == ($nblines-1))	// No more lines, and no space left to show total, so we create a new page
+					            if ($i == ($nblines - 1))	// No more lines, and no space left to show total, so we create a new page
 					            {
 					                $pdf->AddPage('', '', true);
-					                if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+					                if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 					                //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-					                $pdf->setPage($pageposafter+1);
+					                $pdf->setPage($pageposafter + 1);
 					            }
 					        }
 					        else
 					        {
 					            // We found a page break
-					            $showpricebeforepagebreak=0;
+					            $showpricebeforepagebreak = 0;
 					        }
 					    }
 					    else	// No pagebreak
 					    {
 					        $pdf->commitTransaction();
 					    }
-					    $posYAfterDescription=$pdf->GetY();
+					    $posYAfterDescription = $pdf->GetY();
 					}
 
 					$nexY = $pdf->GetY();
-					$pageposafter=$pdf->getPage();
+					$pageposafter = $pdf->getPage();
 
 					$pdf->setPage($pageposbefore);
 					$pdf->setTopMargin($this->marge_haute);
-					$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.
 
 					// We suppose that a too long description or photo were moved completely on next page
 					if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
@@ -509,25 +509,25 @@ class pdf_espadon extends ModelePdfExpedition
 						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
 					}
 
-					$pdf->SetFont('', '', $default_font_size - 1);   // We reposition the default font
+					$pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font
 
 					// weight
 
-					$weighttxt='';
+					$weighttxt = '';
 					if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->weight)
 					{
-						$weighttxt=round($object->lines[$i]->weight * $object->lines[$i]->qty_shipped, 5).' '.measuringUnitString(0, "weight", $object->lines[$i]->weight_units);
+						$weighttxt = round($object->lines[$i]->weight * $object->lines[$i]->qty_shipped, 5).' '.measuringUnitString(0, "weight", $object->lines[$i]->weight_units);
 					}
-					$voltxt='';
+					$voltxt = '';
 					if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->volume)
 					{
-						$voltxt=round($object->lines[$i]->volume * $object->lines[$i]->qty_shipped, 5).' '.measuringUnitString(0, "volume", $object->lines[$i]->volume_units?$object->lines[$i]->volume_units:0);
+						$voltxt = round($object->lines[$i]->volume * $object->lines[$i]->qty_shipped, 5).' '.measuringUnitString(0, "volume", $object->lines[$i]->volume_units ? $object->lines[$i]->volume_units : 0);
 					}
 
 
 					if ($this->getColumnStatus('weight'))
 					{
-					    $this->printStdColumnContent($pdf, $curY, 'weight', $weighttxt.(($weighttxt && $voltxt)?'<br>':'').$voltxt, array('html'=>1));
+					    $this->printStdColumnContent($pdf, $curY, 'weight', $weighttxt.(($weighttxt && $voltxt) ? '<br>' : '').$voltxt, array('html'=>1));
 					    $nexY = max($pdf->GetY(), $nexY);
 					}
 
@@ -551,16 +551,16 @@ class pdf_espadon extends ModelePdfExpedition
 
 
 
-					$nexY+=3;
-					if ($weighttxt && $voltxt) $nexY+=2;
+					$nexY += 3;
+					if ($weighttxt && $voltxt) $nexY += 2;
 
 					// 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));
 					}
 
@@ -579,10 +579,10 @@ class pdf_espadon extends ModelePdfExpedition
 						$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)
 						{
@@ -605,16 +605,16 @@ class pdf_espadon extends ModelePdfExpedition
 				if ($pagenb == 1)
 				{
 					$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
-					$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);
-					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
+					$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
 				}
 
 				// Display total area
-				$posy=$this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs);
+				$posy = $this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs);
 
 				// Pagefoot
 				$this->_pagefoot($pdf, $object, $outputlangs);
@@ -681,7 +681,7 @@ class pdf_espadon extends ModelePdfExpedition
 		$pdf->SetFont('', 'B', $default_font_size - 1);
 
 		// Total table
-		$col1x = $this->posxweightvol-50; $col2x = $this->posxweightvol;
+		$col1x = $this->posxweightvol - 50; $col2x = $this->posxweightvol;
 		/*if ($this->page_largeur < 210) // To work with US executive format
 		{
 			$col2x-=20;
@@ -788,8 +788,8 @@ class pdf_espadon extends ModelePdfExpedition
 		if (empty($hidetop))
 		{
 			//$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, $this->tabTitleHeight, '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, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
 			}
 		}
 
@@ -797,13 +797,13 @@ class pdf_espadon extends ModelePdfExpedition
 		$pdf->SetFont('', '', $default_font_size - 1);
 
 		// 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
+		$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
 
 
 		$this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop);
 
-		if (empty($hidetop)){
-		    $pdf->line($this->marge_gauche, $tab_top+$this->tabTitleHeight, $this->page_largeur-$this->marge_droite, $tab_top+$this->tabTitleHeight);	// line takes a position y in 2nd parameter and 4th parameter
+		if (empty($hidetop)) {
+		    $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter
 		}
 	}
 
@@ -839,19 +839,19 @@ class pdf_espadon extends ModelePdfExpedition
 
 		$w = 110;
 
-		$posy=$this->marge_haute;
-		$posx=$this->page_largeur-$this->marge_droite-$w;
+		$posy = $this->marge_haute;
+		$posx = $this->page_largeur - $this->marge_droite - $w;
 
 		$pdf->SetXY($this->marge_gauche, $posy);
 
 		// Logo
-		$logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
+		$logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
 		if ($this->emetteur->logo)
 		{
 			if (is_readable($logo))
 			{
-			    $height=pdf_getHeightForLogo($logo);
-			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
+			    $height = pdf_getHeightForLogo($logo);
+			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
 			}
 			else
 			{
@@ -863,21 +863,21 @@ class pdf_espadon extends ModelePdfExpedition
 		}
 		else
 		{
-			$text=$this->emetteur->name;
+			$text = $this->emetteur->name;
 			$pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
 		}
 
 		// Show barcode
-		if (! empty($conf->barcode->enabled))
+		if (!empty($conf->barcode->enabled))
 		{
-			$posx=105;
+			$posx = 105;
 		}
 		else
 		{
-			$posx=$this->marge_gauche+3;
+			$posx = $this->marge_gauche + 3;
 		}
 		//$pdf->Rect($this->marge_gauche, $this->marge_haute, $this->page_largeur-$this->marge_gauche-$this->marge_droite, 30);
-		if (! empty($conf->barcode->enabled))
+		if (!empty($conf->barcode->enabled))
 		{
 			// TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref
 			//$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3);
@@ -893,67 +893,67 @@ class pdf_espadon extends ModelePdfExpedition
 		}
 
 
-		$posx=$this->page_largeur - $w - $this->marge_droite;
-		$posy=$this->marge_haute;
+		$posx = $this->page_largeur - $w - $this->marge_droite;
+		$posy = $this->marge_haute;
 
 		$pdf->SetFont('', 'B', $default_font_size + 2);
 		$pdf->SetXY($posx, $posy);
 		$pdf->SetTextColor(0, 0, 60);
-		$title=$outputlangs->transnoentities("SendingSheet");
+		$title = $outputlangs->transnoentities("SendingSheet");
 		$pdf->MultiCell($w, 4, $title, '', 'R');
 
 		$pdf->SetFont('', '', $default_font_size + 1);
 
-		$posy+=5;
+		$posy += 5;
 
 		$pdf->SetXY($posx, $posy);
 		$pdf->SetTextColor(0, 0, 60);
-		$pdf->MultiCell($w, 4, $outputlangs->transnoentities("RefSending") ." : ".$object->ref, '', 'R');
+		$pdf->MultiCell($w, 4, $outputlangs->transnoentities("RefSending")." : ".$object->ref, '', 'R');
 
 		// Date planned delivery
-		if (! empty($object->date_delivery))
+		if (!empty($object->date_delivery))
 		{
-    			$posy+=4;
+    			$posy += 4;
     			$pdf->SetXY($posx, $posy);
     			$pdf->SetTextColor(0, 0, 60);
     			$pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateDeliveryPlanned")." : ".dol_print_date($object->date_delivery, "day", false, $outputlangs, true), '', 'R');
 		}
 
-		if (! empty($object->thirdparty->code_client))
+		if (!empty($object->thirdparty->code_client))
 		{
-			$posy+=4;
+			$posy += 4;
 			$pdf->SetXY($posx, $posy);
 			$pdf->SetTextColor(0, 0, 60);
-			$pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
+			$pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
 		}
 
 
 		$pdf->SetFont('', '', $default_font_size + 3);
-		$Yoff=25;
+		$Yoff = 25;
 
 		// Add list of linked orders
-		$origin 	= $object->origin;
-		$origin_id 	= $object->origin_id;
+		$origin = $object->origin;
+		$origin_id = $object->origin_id;
 
 	    // TODO move to external function
-		if (! empty($conf->$origin->enabled))     // commonly $origin='commande'
+		if (!empty($conf->$origin->enabled))     // commonly $origin='commande'
 		{
 			$outputlangs->load('orders');
 
 			$classname = ucfirst($origin);
 			$linkedobject = new $classname($this->db);
-			$result=$linkedobject->fetch($origin_id);
+			$result = $linkedobject->fetch($origin_id);
 			if ($result >= 0)
 			{
 			    //$linkedobject->fetchObjectLinked()   Get all linked object to the $linkedobject (commonly order) into $linkedobject->linkedObjects
 
 				$pdf->SetFont('', '', $default_font_size - 2);
-				$text=$linkedobject->ref;
-				if ($linkedobject->ref_client) $text.=' ('.$linkedobject->ref_client.')';
-				$Yoff = $Yoff+8;
+				$text = $linkedobject->ref;
+				if ($linkedobject->ref_client) $text .= ' ('.$linkedobject->ref_client.')';
+				$Yoff = $Yoff + 8;
 				$pdf->SetXY($this->page_largeur - $this->marge_droite - $w, $Yoff);
-				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder") ." : ".$outputlangs->transnoentities($text), 0, 'R');
-				$Yoff = $Yoff+3;
+				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder")." : ".$outputlangs->transnoentities($text), 0, 'R');
+				$Yoff = $Yoff + 3;
 				$pdf->SetXY($this->page_largeur - $this->marge_droite - $w, $Yoff);
 				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($linkedobject->date, "day", false, $outputlangs, true), 0, 'R');
 			}
@@ -994,24 +994,24 @@ class pdf_espadon extends ModelePdfExpedition
 			$pdf->SetFillColor(255, 255, 255);
 
 			// Show sender name
-			$pdf->SetXY($posx+2, $posy+3);
+			$pdf->SetXY($posx + 2, $posy + 3);
 			$pdf->SetFont('', 'B', $default_font_size);
-			$pdf->MultiCell($widthrecbox-2, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
-			$posy=$pdf->getY();
+			$pdf->MultiCell($widthrecbox - 2, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
+			$posy = $pdf->getY();
 
 			// Show sender information
-			$pdf->SetXY($posx+2, $posy);
+			$pdf->SetXY($posx + 2, $posy);
 			$pdf->SetFont('', '', $default_font_size - 1);
-			$pdf->MultiCell($widthrecbox-2, 4, $carac_emetteur, 0, 'L');
+			$pdf->MultiCell($widthrecbox - 2, 4, $carac_emetteur, 0, 'L');
 
 
 			// If SHIPPING contact defined, we use it
-			$usecontact=false;
-			$arrayidcontact=$object->$origin->getIdContact('external', 'SHIPPING');
+			$usecontact = false;
+			$arrayidcontact = $object->$origin->getIdContact('external', 'SHIPPING');
 			if (count($arrayidcontact) > 0)
 			{
-				$usecontact=true;
-				$result=$object->fetch_contact($arrayidcontact[0]);
+				$usecontact = true;
+				$result = $object->fetch_contact($arrayidcontact[0]);
 			}
 
 			//Recipient name
@@ -1022,26 +1022,26 @@ class pdf_espadon extends ModelePdfExpedition
 				$thirdparty = $object->thirdparty;
 			}
 
-			$carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs);
+			$carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs);
 
-			$carac_client=pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, (!empty($object->contact)?$object->contact:null), $usecontact, 'targetwithdetails', $object);
+			$carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, (!empty($object->contact) ? $object->contact : null), $usecontact, 'targetwithdetails', $object);
 
 			// Show recipient
-			$widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100;
-			if ($this->page_largeur < 210) $widthrecbox=84;	// To work with US executive format
-			$posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
-			$posx=$this->page_largeur - $this->marge_droite - $widthrecbox;
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;
+			$widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100;
+			if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format
+			$posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
+			$posx = $this->page_largeur - $this->marge_droite - $widthrecbox;
+			if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche;
 
 			// Show recipient frame
 			$pdf->SetTextColor(0, 0, 0);
 			$pdf->SetFont('', '', $default_font_size - 2);
-			$pdf->SetXY($posx+2, $posy-5);
+			$pdf->SetXY($posx + 2, $posy - 5);
 			$pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("Recipient").":", 0, 'L');
 			$pdf->Rect($posx, $posy, $widthrecbox, $hautcadre);
 
 			// Show recipient name
-			$pdf->SetXY($posx+2, $posy+3);
+			$pdf->SetXY($posx + 2, $posy + 3);
 			$pdf->SetFont('', 'B', $default_font_size);
 			$pdf->MultiCell($widthrecbox, 2, $carac_client_name, 0, 'L');
 
@@ -1049,7 +1049,7 @@ class pdf_espadon extends ModelePdfExpedition
 
 			// Show recipient information
 			$pdf->SetFont('', '', $default_font_size - 1);
-			$pdf->SetXY($posx+2, $posy);
+			$pdf->SetXY($posx + 2, $posy);
 			$pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L');
 		}
 

+ 167 - 167
htdocs/core/modules/expensereport/doc/pdf_standard.modules.php

@@ -135,41 +135,41 @@ class pdf_standard extends ModeleExpenseReport
 
 		// 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->option_logo = 1;                    // Affiche logo
-		$this->option_tva = 1;                     // Gere option tva FACTURE_TVAOPTION
-		$this->option_modereg = 1;                 // Affiche mode reglement
-		$this->option_condreg = 1;                 // Affiche conditions reglement
-		$this->option_codeproduitservice = 1;      // 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 = 1;		   // Support add of a watermark on drafts
+		$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_tva = 1; // Gere option tva FACTURE_TVAOPTION
+		$this->option_modereg = 1; // Affiche mode reglement
+		$this->option_condreg = 1; // Affiche conditions reglement
+		$this->option_codeproduitservice = 1; // 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 = 1; // Support add of a watermark on drafts
 
 		// Get source company
-		$this->emetteur=$mysoc;
+		$this->emetteur = $mysoc;
 
-		if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2);    // By default, if was not defined
+		if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined
 
 		// Define position of columns
-		$this->posxpiece=$this->marge_gauche+1;
-		$this->posxcomment=$this->marge_gauche+10;
+		$this->posxpiece = $this->marge_gauche + 1;
+		$this->posxcomment = $this->marge_gauche + 10;
 		//$this->posxdate=88;
 		//$this->posxtype=107;
 		//$this->posxprojet=120;
-		$this->posxtva=130;
-		$this->posxup=145;
-		$this->posxqty=168;
-		$this->postotalttc=178;
+		$this->posxtva = 130;
+		$this->posxup = 145;
+		$this->posxqty = 168;
+		$this->postotalttc = 178;
 		// if (empty($conf->projet->enabled)) {
 		//     $this->posxtva-=20;
 		//     $this->posxup-=20;
@@ -287,40 +287,40 @@ class pdf_standard extends ModeleExpenseReport
 				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
 				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
 				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Trips"));
-				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
+				if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
 
-				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
+				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right
 
 				// New page
 				$pdf->AddPage();
-				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+				if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 				$pagenb++;
 				$this->_pagehead($pdf, $object, 1, $outputlangs);
 				$pdf->SetFont('', '', $default_font_size - 1);
-				$pdf->MultiCell(0, 3, '');		// Set interline to 3
+				$pdf->MultiCell(0, 3, ''); // Set interline to 3
 				$pdf->SetTextColor(0, 0, 0);
 
 				$tab_top = 95;
-				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?65:10);
+				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 65 : 10);
 				$tab_height = 130;
 				$tab_height_newpage = 150;
 
 				// Show notes
-				$notetoshow=empty($object->note_public)?'':$object->note_public;
-				if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE))
+				$notetoshow = empty($object->note_public) ? '' : $object->note_public;
+				if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE))
 				{
 					// Get first sale rep
 					if (is_object($object->thirdparty))
 					{
-						$salereparray=$object->thirdparty->getSalesRepresentatives($user);
-						$salerepobj=new User($this->db);
+						$salereparray = $object->thirdparty->getSalesRepresentatives($user);
+						$salerepobj = new User($this->db);
 						$salerepobj->fetch($salereparray[0]['id']);
-						if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature);
+						if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature);
 					}
 				}
 				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);
@@ -328,20 +328,20 @@ class pdf_standard extends ModeleExpenseReport
 					$tab_top = 95;
 
 					$pdf->SetFont('', '', $default_font_size - 1);
-					$pdf->writeHTMLCell(190, 3, $this->posxpiece-1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1);
+					$pdf->writeHTMLCell(190, 3, $this->posxpiece - 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;
@@ -349,41 +349,41 @@ class pdf_standard extends ModeleExpenseReport
 				$nexY = $tab_top + 7;
 
 				// Loop on each lines
-				for ($i = 0 ; $i < $nblines ; $i++) {
-					$pdf->SetFont('', '', $default_font_size - 2);   // Into loop to work with multipage
+				for ($i = 0; $i < $nblines; $i++) {
+					$pdf->SetFont('', '', $default_font_size - 2); // Into loop to work with multipage
 					$pdf->SetTextColor(0, 0, 0);
 
 					$pdf->setTopMargin($tab_top_newpage);
-					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
+					$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
 					$pageposbefore = $pdf->getPage();
                     $curY = $nexY;
                     $pdf->startTransaction();
                     $this->printLine($pdf, $object, $i, $curY, $default_font_size, $outputlangs, $hidedetails);
-                    $pageposafter=$pdf->getPage();
+                    $pageposafter = $pdf->getPage();
 					if ($pageposafter > $pageposbefore) {
                         // There is a pagebreak
 						$pdf->rollbackTransaction(true);
 						$pageposafter = $pageposbefore;
 						//print $pageposafter.'-'.$pageposbefore;exit;
-						$pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
+						$pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
 						$this->printLine($pdf, $object, $i, $curY, $default_font_size, $outputlangs, $hidedetails);
 						$pageposafter = $pdf->getPage();
 						$posyafter = $pdf->GetY();
 						//var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
-						if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) {
+						if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) {
                             // There is no space left for total+free text
-							if ($i == ($nblines-1)) {
+							if ($i == ($nblines - 1)) {
                                 // No more lines, and no space left to show total, so we create a new page
 								$pdf->AddPage('', '', true);
-								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+								if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-								$pdf->setPage($pageposafter+1);
+								$pdf->setPage($pageposafter + 1);
 							}
 						}
 						else
 						{
 							// We found a page break
-							$showpricebeforepagebreak=0;
+							$showpricebeforepagebreak = 0;
 						}
 					}
 					else	// No pagebreak
@@ -413,7 +413,7 @@ class pdf_standard extends ModeleExpenseReport
 					// }
 
                     //$nexY+=$nblineFollowComment*($pdf->getFontSize()*1.3);    // Add space between lines
-                    $nexY += ($pdf->getFontSize()*1.3);    // Add space between lines
+                    $nexY += ($pdf->getFontSize() * 1.3); // Add space between lines
 
 					// Detect if some page were added automatically and output _tableau for past pages
 					while ($pagenb < $pageposafter)
@@ -509,31 +509,31 @@ class pdf_standard extends ModeleExpenseReport
 
 				// 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", "EXPENSEREPORT_OUTPUTDIR");
+			$this->error = $langs->trans("ErrorConstantNotDefined", "EXPENSEREPORT_OUTPUTDIR");
 			return 0;
 		}
 	}
@@ -592,30 +592,30 @@ class pdf_standard extends ModeleExpenseReport
         if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) {
             $vat_rate = pdf_getlinevatrate($object, $linenumber, $outputlangs, $hidedetails);
             $pdf->SetXY($this->posxtva, $curY);
-            $pdf->MultiCell($this->posxup-$this->posxtva-0.8, 4, $vat_rate, 0, 'R');
+            $pdf->MultiCell($this->posxup - $this->posxtva - 0.8, 4, $vat_rate, 0, 'R');
         }
 
         // Unit price
         $pdf->SetXY($this->posxup, $curY);
-        $pdf->MultiCell($this->posxqty-$this->posxup-0.8, 4, price($object->lines[$linenumber]->value_unit), 0, 'R');
+        $pdf->MultiCell($this->posxqty - $this->posxup - 0.8, 4, price($object->lines[$linenumber]->value_unit), 0, 'R');
 
         // Quantity
         $pdf->SetXY($this->posxqty, $curY);
-        $pdf->MultiCell($this->postotalttc-$this->posxqty-0.8, 4, $object->lines[$linenumber]->qty, 0, 'R');
+        $pdf->MultiCell($this->postotalttc - $this->posxqty - 0.8, 4, $object->lines[$linenumber]->qty, 0, 'R');
 
         // Total with all taxes
-        $pdf->SetXY($this->postotalttc-1, $curY);
-        $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalttc, 4, price($object->lines[$linenumber]->total_ttc), 0, 'R');
+        $pdf->SetXY($this->postotalttc - 1, $curY);
+        $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalttc, 4, price($object->lines[$linenumber]->total_ttc), 0, 'R');
 
         // Comments
         $pdf->SetXY($this->posxcomment, $curY);
-        $comment = $outputlangs->trans("Date").':'. dol_print_date($object->lines[$linenumber]->date, "day", false, $outputlangs).' ';
-        $comment .= $outputlangs->trans("Type").':'. $expensereporttypecodetoshow.'<br>';
-        if (! empty($object->lines[$linenumber]->projet_ref)) {
-            $comment .= $outputlangs->trans("Project").':'. $object->lines[$linenumber]->projet_ref.'<br>';
+        $comment = $outputlangs->trans("Date").':'.dol_print_date($object->lines[$linenumber]->date, "day", false, $outputlangs).' ';
+        $comment .= $outputlangs->trans("Type").':'.$expensereporttypecodetoshow.'<br>';
+        if (!empty($object->lines[$linenumber]->projet_ref)) {
+            $comment .= $outputlangs->trans("Project").':'.$object->lines[$linenumber]->projet_ref.'<br>';
         }
         $comment .= $object->lines[$linenumber]->comments;
-        $pdf->writeHTMLCell($this->posxtva-$this->posxcomment-0.8, 4, $this->posxcomment-1, $curY, $comment, 0, 1);
+        $pdf->writeHTMLCell($this->posxtva - $this->posxcomment - 0.8, 4, $this->posxcomment - 1, $curY, $comment, 0, 1);
 	}
 
 	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
@@ -751,96 +751,96 @@ class pdf_standard extends ModeleExpenseReport
 
 			// Show sender information
 			if (empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
-				$pdf->SetXY($posx+2, $posy+3);
+				$pdf->SetXY($posx + 2, $posy + 3);
 				$pdf->SetFont('', 'B', $default_font_size);
 				$pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
-				$pdf->SetXY($posx+2, $posy+8);
+				$pdf->SetXY($posx + 2, $posy + 8);
 				$pdf->SetFont('', '', $default_font_size - 1);
 				$pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L');
 			} else {
-				$pdf->SetXY($posx+2, $posy+3);
+				$pdf->SetXY($posx + 2, $posy + 3);
 				$pdf->SetFont('', 'B', $default_font_size);
 				$pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset(dolGetFirstLastname($receiver->firstname, $receiver->lastname)), 0, 'L');
-				$pdf->SetXY($posx+2, $posy+8);
+				$pdf->SetXY($posx + 2, $posy + 8);
 				$pdf->SetFont('', '', $default_font_size - 1);
 				$pdf->MultiCell(80, 4, $expense_receiver, 0, 'L');
 			}
 
 			// Show recipient
-			$posy=50;
-			$posx=100;
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;
+			$posy = 50;
+			$posx = 100;
+			if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche;
 
 			// Show recipient frame
 			$pdf->SetTextColor(0, 0, 0);
 			$pdf->SetFont('', 'B', 8);
-			$pdf->SetXY($posx, $posy-5);
+			$pdf->SetXY($posx, $posy - 5);
 			$pdf->MultiCell(80, 5, $outputlangs->transnoentities("TripNDF")." :", 0, 'L');
 			$pdf->rect($posx, $posy, $this->page_largeur - $this->marge_gauche - $posx, $hautcadre);
 
 			// Informations for trip (dates and users workflow)
 			if ($object->fk_user_author > 0) {
-				$userfee=new User($this->db);
+				$userfee = new User($this->db);
 				$userfee->fetch($object->fk_user_author);
-				$posy+=3;
-				$pdf->SetXY($posx+2, $posy);
+				$posy += 3;
+				$pdf->SetXY($posx + 2, $posy);
 				$pdf->SetFont('', '', 10);
 				$pdf->MultiCell(96, 4, $outputlangs->transnoentities("AUTHOR")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L');
-				$posy+=5;
-				$pdf->SetXY($posx+2, $posy);
+				$posy += 5;
+				$pdf->SetXY($posx + 2, $posy);
 				$pdf->MultiCell(96, 4, $outputlangs->transnoentities("DateCreation")." : ".dol_print_date($object->date_create, "day", false, $outputlangs), 0, 'L');
 			}
 
-			if ($object->fk_statut==99) {
+			if ($object->fk_statut == 99) {
 				if ($object->fk_user_refuse > 0) {
-					$userfee=new User($this->db);
-					$userfee->fetch($object->fk_user_refuse); $posy+=6;
-					$pdf->SetXY($posx+2, $posy);
+					$userfee = new User($this->db);
+					$userfee->fetch($object->fk_user_refuse); $posy += 6;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("REFUSEUR")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L');
-					$posy+=5;
-					$pdf->SetXY($posx+2, $posy);
+					$posy += 5;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("MOTIF_REFUS")." : ".$outputlangs->convToOutputCharset($object->detail_refuse), 0, 'L');
-					$posy+=5;
-					$pdf->SetXY($posx+2, $posy);
+					$posy += 5;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("DATE_REFUS")." : ".dol_print_date($object->date_refuse, "day", false, $outputlangs), 0, 'L');
 				}
 			}
-			elseif($object->fk_statut==4)
+			elseif ($object->fk_statut == 4)
 			{
 				if ($object->fk_user_cancel > 0) {
-					$userfee=new User($this->db);
-					$userfee->fetch($object->fk_user_cancel); $posy+=6;
-					$pdf->SetXY($posx+2, $posy);
+					$userfee = new User($this->db);
+					$userfee->fetch($object->fk_user_cancel); $posy += 6;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("CANCEL_USER")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L');
-					$posy+=5;
-					$pdf->SetXY($posx+2, $posy);
+					$posy += 5;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("MOTIF_CANCEL")." : ".$outputlangs->convToOutputCharset($object->detail_cancel), 0, 'L');
-					$posy+=5;
-					$pdf->SetXY($posx+2, $posy);
+					$posy += 5;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("DATE_CANCEL")." : ".dol_print_date($object->date_cancel, "day", false, $outputlangs), 0, 'L');
 				}
 			}
 			else
 			{
 				if ($object->fk_user_approve > 0) {
-					$userfee=new User($this->db);
-					$userfee->fetch($object->fk_user_approve); $posy+=6;
-					$pdf->SetXY($posx+2, $posy);
+					$userfee = new User($this->db);
+					$userfee->fetch($object->fk_user_approve); $posy += 6;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("VALIDOR")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L');
-					$posy+=5;
-					$pdf->SetXY($posx+2, $posy);
+					$posy += 5;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("DateApprove")." : ".dol_print_date($object->date_approve, "day", false, $outputlangs), 0, 'L');
 				}
 			}
 
-			if($object->fk_statut==6) {
+			if ($object->fk_statut == 6) {
 				if ($object->fk_user_paid > 0) {
-					$userfee=new User($this->db);
-					$userfee->fetch($object->fk_user_paid); $posy+=6;
-					$pdf->SetXY($posx+2, $posy);
+					$userfee = new User($this->db);
+					$userfee->fetch($object->fk_user_paid); $posy += 6;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("AUTHORPAIEMENT")." : ".dolGetFirstLastname($userfee->firstname, $userfee->lastname), 0, 'L');
-					$posy+=5;
-					$pdf->SetXY($posx+2, $posy);
+					$posy += 5;
+					$pdf->SetXY($posx + 2, $posy);
 					$pdf->MultiCell(96, 4, $outputlangs->transnoentities("DATE_PAIEMENT")." : ".dol_print_date($object->date_paiement, "day", false, $outputlangs), 0, 'L');
 				}
 			}
@@ -876,31 +876,31 @@ class pdf_standard extends ModeleExpenseReport
 		$pdf->SetTextColor(0, 0, 0);
 		$pdf->SetFont('', '', $default_font_size - 2);
 		$titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency));
-		$pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 4), $tab_top -4);
+		$pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 4), $tab_top - 4);
 		$pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre);
 
 		$pdf->SetDrawColor(128, 128, 128);
 
 		// Rect takes a length in 3rd parameter
-		$pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height);
+		$pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height);
 		// line prend une position y en 3eme param
 		if (empty($hidetop)) {
-			$pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5);
+			$pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5);
 		}
 
 		$pdf->SetFont('', '', 8);
 
 		// Accountancy piece
 		if (empty($hidetop)) {
-			$pdf->SetXY($this->posxpiece-1, $tab_top+1);
-			$pdf->MultiCell($this->posxcomment-$this->posxpiece-1, 1, '', '', 'R');
+			$pdf->SetXY($this->posxpiece - 1, $tab_top + 1);
+			$pdf->MultiCell($this->posxcomment - $this->posxpiece - 1, 1, '', '', 'R');
 		}
 
 		// Comments
-		$pdf->line($this->posxcomment-1, $tab_top, $this->posxcomment-1, $tab_top + $tab_height);
+		$pdf->line($this->posxcomment - 1, $tab_top, $this->posxcomment - 1, $tab_top + $tab_height);
 		if (empty($hidetop)) {
-			$pdf->SetXY($this->posxcomment-1, $tab_top+1);
-			$pdf->MultiCell($this->posxdate-$this->posxcomment-1, 1, $outputlangs->transnoentities("Description"), '', 'L');
+			$pdf->SetXY($this->posxcomment - 1, $tab_top + 1);
+			$pdf->MultiCell($this->posxdate - $this->posxcomment - 1, 1, $outputlangs->transnoentities("Description"), '', 'L');
 		}
 
 		// Date
@@ -931,32 +931,32 @@ class pdf_standard extends ModeleExpenseReport
 
 		// VAT
 		if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) {
-			$pdf->line($this->posxtva-1, $tab_top, $this->posxtva-1, $tab_top + $tab_height);
+			$pdf->line($this->posxtva - 1, $tab_top, $this->posxtva - 1, $tab_top + $tab_height);
 			if (empty($hidetop)) {
-				$pdf->SetXY($this->posxtva-1, $tab_top+1);
-				$pdf->MultiCell($this->posxup-$this->posxtva - 1, 2, $outputlangs->transnoentities("VAT"), '', 'C');
+				$pdf->SetXY($this->posxtva - 1, $tab_top + 1);
+				$pdf->MultiCell($this->posxup - $this->posxtva - 1, 2, $outputlangs->transnoentities("VAT"), '', 'C');
 			}
 		}
 
         // Unit price
-		$pdf->line($this->posxup-1, $tab_top, $this->posxup-1, $tab_top + $tab_height);
+		$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->posxqty-$this->posxup-1, 2, $outputlangs->transnoentities("PriceU"), '', 'C');
+			$pdf->SetXY($this->posxup - 1, $tab_top + 1);
+			$pdf->MultiCell($this->posxqty - $this->posxup - 1, 2, $outputlangs->transnoentities("PriceU"), '', 'C');
 		}
 
 		// Quantity
-		$pdf->line($this->posxqty-1, $tab_top, $this->posxqty-1, $tab_top + $tab_height);
+		$pdf->line($this->posxqty - 1, $tab_top, $this->posxqty - 1, $tab_top + $tab_height);
 		if (empty($hidetop)) {
-			$pdf->SetXY($this->posxqty-1, $tab_top+1);
-			$pdf->MultiCell($this->postotalttc-$this->posxqty - 1, 2, $outputlangs->transnoentities("Qty"), '', 'C');
+			$pdf->SetXY($this->posxqty - 1, $tab_top + 1);
+			$pdf->MultiCell($this->postotalttc - $this->posxqty - 1, 2, $outputlangs->transnoentities("Qty"), '', 'C');
 		}
 
 		// Total with all taxes
 		$pdf->line($this->postotalttc, $tab_top, $this->postotalttc, $tab_top + $tab_height);
 		if (empty($hidetop)) {
-			$pdf->SetXY($this->postotalttc-1, $tab_top+1);
-			$pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->postotalttc, 2, $outputlangs->transnoentities("TotalTTC"), '', 'R');
+			$pdf->SetXY($this->postotalttc - 1, $tab_top + 1);
+			$pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->postotalttc, 2, $outputlangs->transnoentities("TotalTTC"), '', 'R');
 		}
 
 		$pdf->SetTextColor(0, 0, 0);
@@ -983,94 +983,94 @@ class pdf_standard extends ModeleExpenseReport
 
 		$default_font_size = pdf_getPDFFontSize($outputlangs);
 
-		$title=$outputlangs->transnoentities("PaymentsAlreadyDone");
+		$title = $outputlangs->transnoentities("PaymentsAlreadyDone");
 		$pdf->SetFont('', '', $default_font_size - 2);
 		$pdf->SetXY($tab3_posx, $tab3_top - 4);
 		$pdf->SetTextColor(0, 0, 0);
 		$pdf->MultiCell(60, 3, $title, 0, 'L', 0);
 
-		$pdf->line($tab3_posx, $tab3_top, $tab3_posx+$tab3_width+2, $tab3_top); // Top border line of table title
+		$pdf->line($tab3_posx, $tab3_top, $tab3_posx + $tab3_width + 2, $tab3_top); // Top border line of table title
 
-		$pdf->SetXY($tab3_posx, $tab3_top+1);
+		$pdf->SetXY($tab3_posx, $tab3_top + 1);
 		$pdf->MultiCell(20, 3, $outputlangs->transnoentities("Date"), 0, 'L', 0);
-		$pdf->SetXY($tab3_posx+19, $tab3_top+1); // Old value 17
+		$pdf->SetXY($tab3_posx + 19, $tab3_top + 1); // Old value 17
 		$pdf->MultiCell(15, 3, $outputlangs->transnoentities("Amount"), 0, 'C', 0);
-		$pdf->SetXY($tab3_posx+35, $tab3_top+1);
+		$pdf->SetXY($tab3_posx + 35, $tab3_top + 1);
 		$pdf->MultiCell(30, 3, $outputlangs->transnoentities("Type"), 0, 'L', 0);
-		if (! empty($conf->banque->enabled)) {
-			$pdf->SetXY($tab3_posx+65, $tab3_top+1);
+		if (!empty($conf->banque->enabled)) {
+			$pdf->SetXY($tab3_posx + 65, $tab3_top + 1);
 			$pdf->MultiCell(25, 3, $outputlangs->transnoentities("BankAccount"), 0, 'L', 0);
 		}
-		$pdf->line($tab3_posx, $tab3_top+$tab3_height, $tab3_posx+$tab3_width+2, $tab3_top+$tab3_height); // Bottom border line of table title
+		$pdf->line($tab3_posx, $tab3_top + $tab3_height, $tab3_posx + $tab3_width + 2, $tab3_top + $tab3_height); // Bottom border line of table title
 
-		$y=0;
+		$y = 0;
 
 		// Loop on each payment
 		// TODO create method on expensereport class to get payments
 		// Payments already done (from payment on this expensereport)
 		$sql = "SELECT p.rowid, p.num_payment, p.datep as dp, p.amount, p.fk_bank,";
-		$sql.= "c.code as p_code, c.libelle as payment_type,";
-		$sql.= "ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal";
-		$sql.= " FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."payment_expensereport as p";
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = c.id";
-		$sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid';
-		$sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid';
-		$sql.= " WHERE e.rowid = '".$object->id."'";
-		$sql.= " AND p.fk_expensereport = e.rowid";
-		$sql.= ' AND e.entity IN ('.getEntity('expensereport').')';
-		$sql.= " ORDER BY dp";
-
-		$resql=$this->db->query($sql);
+		$sql .= "c.code as p_code, c.libelle as payment_type,";
+		$sql .= "ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal";
+		$sql .= " FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."payment_expensereport as p";
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepayment = c.id";
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
+		$sql .= " WHERE e.rowid = '".$object->id."'";
+		$sql .= " AND p.fk_expensereport = e.rowid";
+		$sql .= ' AND e.entity IN ('.getEntity('expensereport').')';
+		$sql .= " ORDER BY dp";
+
+		$resql = $this->db->query($sql);
 		if ($resql)
 		{
 			$num = $this->db->num_rows($resql);
 			$totalpaid = 0;
-			$i=0;
+			$i = 0;
 			while ($i < $num) {
-				$y+=$tab3_height;
+				$y += $tab3_height;
 				$row = $this->db->fetch_object($resql);
 
-				$pdf->SetXY($tab3_posx, $tab3_top+$y+1);
+				$pdf->SetXY($tab3_posx, $tab3_top + $y + 1);
 				$pdf->MultiCell(20, 3, dol_print_date($this->db->jdate($row->dp), 'day', false, $outputlangs, true), 0, 'L', 0);
-				$pdf->SetXY($tab3_posx+17, $tab3_top+$y+1);
+				$pdf->SetXY($tab3_posx + 17, $tab3_top + $y + 1);
 				$pdf->MultiCell(15, 3, price($sign * $row->amount, 0, $outputlangs), 0, 'R', 0);
-				$pdf->SetXY($tab3_posx+35, $tab3_top+$y+1);
-				$oper = $outputlangs->transnoentitiesnoconv("PaymentTypeShort" . $row->p_code);
+				$pdf->SetXY($tab3_posx + 35, $tab3_top + $y + 1);
+				$oper = $outputlangs->transnoentitiesnoconv("PaymentTypeShort".$row->p_code);
 
 				$pdf->MultiCell(40, 3, $oper, 0, 'L', 0);
-				if (! empty($conf->banque->enabled)) {
-					$pdf->SetXY($tab3_posx+65, $tab3_top+$y+1);
+				if (!empty($conf->banque->enabled)) {
+					$pdf->SetXY($tab3_posx + 65, $tab3_top + $y + 1);
 					$pdf->MultiCell(30, 3, $row->baref, 0, 'L', 0);
 				}
 
-				$pdf->line($tab3_posx, $tab3_top+$y+$tab3_height, $tab3_posx+$tab3_width+2, $tab3_top+$y+$tab3_height); // Bottom line border of table
+				$pdf->line($tab3_posx, $tab3_top + $y + $tab3_height, $tab3_posx + $tab3_width + 2, $tab3_top + $y + $tab3_height); // Bottom line border of table
 				$totalpaid += $row->amount;
 				$i++;
 			}
 			if ($num > 0 && $object->paid == 0)
 			{
-				$y+=$tab3_height;
+				$y += $tab3_height;
 
-				$pdf->SetXY($tab3_posx+17, $tab3_top+$y);
+				$pdf->SetXY($tab3_posx + 17, $tab3_top + $y);
 				$pdf->MultiCell(15, 3, price($totalpaid), 0, 'R', 0);
-				$pdf->SetXY($tab3_posx+35, $tab3_top+$y);
+				$pdf->SetXY($tab3_posx + 35, $tab3_top + $y);
 				$pdf->MultiCell(30, 4, $outputlangs->transnoentitiesnoconv("AlreadyPaid"), 0, 'L', 0);
-				$y+=$tab3_height-2;
-				$pdf->SetXY($tab3_posx+17, $tab3_top+$y);
+				$y += $tab3_height - 2;
+				$pdf->SetXY($tab3_posx + 17, $tab3_top + $y);
 				$pdf->MultiCell(15, 3, price($object->total_ttc), 0, 'R', 0);
-				$pdf->SetXY($tab3_posx+35, $tab3_top+$y);
+				$pdf->SetXY($tab3_posx + 35, $tab3_top + $y);
 				$pdf->MultiCell(30, 4, $outputlangs->transnoentitiesnoconv("AmountExpected"), 0, 'L', 0);
-				$y+=$tab3_height-2;
+				$y += $tab3_height - 2;
 				$remaintopay = $object->total_ttc - $totalpaid;
-				$pdf->SetXY($tab3_posx+17, $tab3_top+$y);
+				$pdf->SetXY($tab3_posx + 17, $tab3_top + $y);
 				$pdf->MultiCell(15, 3, price($remaintopay), 0, 'R', 0);
-				$pdf->SetXY($tab3_posx+35, $tab3_top+$y);
+				$pdf->SetXY($tab3_posx + 35, $tab3_top + $y);
 				$pdf->MultiCell(30, 4, $outputlangs->transnoentitiesnoconv("RemainderToPay"), 0, 'L', 0);
 			}
 		}
 		else
 		{
-			$this->error=$this->db->lasterror();
+			$this->error = $this->db->lasterror();
 			return -1;
 		}
 	}

+ 1 - 1
htdocs/core/modules/facture/doc/pdf_crabe.modules.php

@@ -1632,7 +1632,7 @@ class pdf_crabe extends ModelePDFFactures
 			if ($this->emetteur->logo)
 			{
 				$logodir = $conf->mycompany->dir_output;
-				if (! empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity];
+				if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity];
 				if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO))
 				{
 					$logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small;

Файловите разлики са ограничени, защото са твърде много
+ 220 - 220
htdocs/core/modules/facture/doc/pdf_sponge.modules.php


+ 6 - 6
htdocs/core/modules/facture/modules_facture.php

@@ -29,7 +29,7 @@
 
 require_once DOL_DOCUMENT_ROOT.'/core/class/commondocgenerator.class.php';
 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';   // Required because used in classes that inherit
+require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; // Required because used in classes that inherit
 
 
 /**
@@ -40,7 +40,7 @@ abstract class ModelePDFFactures extends CommonDocGenerator
 	/**
 	 * @var string Error code (or message)
 	 */
-	public $error='';
+	public $error = '';
 
 	public $atleastonediscount = 0;
 	public $atleastoneratenotnull = 0;
@@ -59,11 +59,11 @@ abstract class ModelePDFFactures extends CommonDocGenerator
         // phpcs:enable
 		global $conf;
 
-		$type='invoice';
-		$liste=array();
+		$type = 'invoice';
+		$liste = array();
 
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
-		$liste=getListOfModels($db, $type, $maxfilenamelength);
+		$liste = getListOfModels($db, $type, $maxfilenamelength);
 
 		return $liste;
 	}
@@ -77,7 +77,7 @@ abstract class ModeleNumRefFactures
 	/**
 	 * @var string Error code (or message)
 	 */
-	public $error='';
+	public $error = '';
 
 	/**
 	 * Return if a module can be used or not

+ 149 - 149
htdocs/core/modules/livraison/doc/pdf_typhon.modules.php

@@ -118,7 +118,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 	 */
 	public function __construct($db)
 	{
-		global $conf,$langs,$mysoc;
+		global $conf, $langs, $mysoc;
 
 		// Translations
 		$langs->loadLangs(array("main", "bills", "sendings", "companies"));
@@ -129,45 +129,45 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 
 		// 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;                    // Display logo FAC_PDF_LOGO
-		$this->option_tva = 1;                     // Manage the vat option FACTURE_TVAOPTION
-		$this->option_codeproduitservice = 1;      // Display product-service code
+		$this->option_logo = 1; // Display logo FAC_PDF_LOGO
+		$this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION
+		$this->option_codeproduitservice = 1; // Display product-service code
 
 		// Get source company
-		$this->emetteur=$mysoc;
-		if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2);    // By default, if was not defined
+		$this->emetteur = $mysoc;
+		if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined
 
 		// Define position of columns
-		$this->posxdesc=$this->marge_gauche+1;
-		$this->posxcomm=112;
+		$this->posxdesc = $this->marge_gauche + 1;
+		$this->posxcomm = 112;
 		//$this->posxtva=112;
 		//$this->posxup=126;
-		$this->posxqty=165;
-		$this->posxremainingqty=185;
+		$this->posxqty = 165;
+		$this->posxremainingqty = 185;
 		//$this->posxdiscount=162;
 		//$this->postotalht=174;
 		if ($this->page_largeur < 210) // To work with US executive format
 		{
-			$this->posxcomm-=20;
+			$this->posxcomm -= 20;
 			//$this->posxtva-=20;
 			//$this->posxup-=20;
-			$this->posxqty-=20;
+			$this->posxqty -= 20;
 			//$this->posxdiscount-=20;
 			//$this->postotalht-=20;
 		}
 
-		$this->tva=array();
-		$this->atleastoneratenotnull=0;
-		$this->atleastonediscount=0;
+		$this->tva = array();
+		$this->atleastoneratenotnull = 0;
+		$this->atleastonediscount = 0;
 	}
 
 
@@ -186,11 +186,11 @@ class pdf_typhon extends ModelePDFDeliveryOrder
     public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
     {
         // phpcs:enable
-		global $user,$langs,$conf,$mysoc,$hookmanager;
+		global $user, $langs, $conf, $mysoc, $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 translation files required by the page
 		$outputlangs->loadLangs(array("main", "dict", "companies", "bills", "products", "sendings", "deliveries"));
@@ -203,20 +203,20 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 			if ($object->specimen)
 			{
 				$dir = $conf->expedition->dir_output."/receipt";
-				$file = $dir . "/SPECIMEN.pdf";
+				$file = $dir."/SPECIMEN.pdf";
 			}
 			else
 			{
 				$objectref = dol_sanitizeFileName($object->ref);
-				$dir = $conf->expedition->dir_output."/receipt/" . $objectref;
-				$file = $dir . "/" . $objectref . ".pdf";
+				$dir = $conf->expedition->dir_output."/receipt/".$objectref;
+				$file = $dir."/".$objectref.".pdf";
 			}
 
-			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 0;
 				}
 			}
@@ -224,25 +224,25 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 			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
 
 				$nblines = count($object->lines);
 
 				// Create pdf instance
-				$pdf=pdf_getInstance($this->format);
-                $default_font_size = pdf_getPDFFontSize($outputlangs);	// Must be after pdf_getInstance
-                $heightforinfotot = 30;	// 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 ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6;
+				$pdf = pdf_getInstance($this->format);
+                $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance
+                $heightforinfotot = 30; // 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 ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6;
                 $pdf->SetAutoPageBreak(1, 0);
 
                 if (class_exists('TCPDF'))
@@ -252,14 +252,14 @@ class pdf_typhon extends ModelePDFDeliveryOrder
                 }
                 $pdf->SetFont(pdf_getPDFFont($outputlangs));
                 // Set path to the background PDF File
-                if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
+                if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
                 {
                     $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND);
                     $tplidx = $pdf->importPage(1);
                 }
 
 				// We get the shipment that is the origin of delivery receipt
-				$expedition=new Expedition($this->db);
+				$expedition = new Expedition($this->db);
 				$result = $expedition->fetch($object->origin_id);
 				// Now we get the order that is origin of shipment
 				$commande = new Commande($this->db);
@@ -267,12 +267,12 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 				{
 					$commande->fetch($expedition->origin_id);
 				}
-				$object->commande=$commande;	// We set order of shipment onto delivery.
+				$object->commande = $commande; // We set order of shipment onto delivery.
 				$object->commande->loadExpeditions();
 
 
 				$pdf->Open();
-				$pagenb=0;
+				$pagenb = 0;
 				$pdf->SetDrawColor(128, 128, 128);
 
 				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
@@ -280,9 +280,9 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
 				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
 				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("DeliveryOrder"));
-				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
+				if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
 
-				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
+				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right
 
 				/*
 				// Positionne $this->atleastonediscount si on a au moins une remise
@@ -306,15 +306,15 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 
 				// New page
 				$pdf->AddPage();
-				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+				if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 				$pagenb++;
 				$this->_pagehead($pdf, $object, 1, $outputlangs);
 				$pdf->SetFont('', '', $default_font_size - 1);
-				$pdf->MultiCell(0, 3, '');		// Set interline to 3
+				$pdf->MultiCell(0, 3, ''); // Set interline to 3
 				$pdf->SetTextColor(0, 0, 0);
 
 				$tab_top = 90;
-				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42:10);
+				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10);
 				$tab_height = 130;
 				$tab_height_newpage = 150;
 
@@ -328,39 +328,39 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 						$tab_top = 88;
 
 						$pdf->SetFont('', '', $default_font_size - 1);
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
+						$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
 						$nexY = $pdf->GetY();
-						$height_incoterms=$nexY-$tab_top;
+						$height_incoterms = $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_incoterms+1);
+						$pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1);
 
-						$tab_top = $nexY+6;
+						$tab_top = $nexY + 6;
 						$height_incoterms += 4;
 					}
 				}
 
 				// Affiche notes
-				if (! empty($object->note_public))
+				if (!empty($object->note_public))
 				{
 					$tab_top = 88 + $height_incoterms;
 
 					$pdf->SetFont('', '', $default_font_size - 1);
-					$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top, dol_htmlentitiesbr($object->note_public), 0, 1);
+					$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($object->note_public), 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 + 11;
@@ -368,46 +368,46 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 				$nexY = $tab_top + 11;
 
 				// Loop on each lines
-				for ($i = 0 ; $i < $nblines ; $i++)
+				for ($i = 0; $i < $nblines; $i++)
 				{
 					$curY = $nexY;
-					$pdf->SetFont('', '', $default_font_size - 1);   // Into loop to work with multipage
+					$pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage
 					$pdf->SetTextColor(0, 0, 0);
 
 					$pdf->setTopMargin($tab_top_newpage);
-					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
-					$pageposbefore=$pdf->getPage();
+					$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
+					$pageposbefore = $pdf->getPage();
 
 					// Description of product line
-					$curX = $this->posxdesc-1;
+					$curX = $this->posxdesc - 1;
 
-                    $showpricebeforepagebreak=1;
+                    $showpricebeforepagebreak = 1;
 
                     $pdf->startTransaction();
-                    pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm-$curX, 3, $curX, $curY, $hideref, $hidedesc);
-                    $pageposafter=$pdf->getPage();
+                    pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm - $curX, 3, $curX, $curY, $hideref, $hidedesc);
+                    $pageposafter = $pdf->getPage();
                     if ($pageposafter > $pageposbefore)	// There is a pagebreak
                     {
                     	$pdf->rollbackTransaction(true);
-                    	$pageposafter=$pageposbefore;
+                    	$pageposafter = $pageposbefore;
                     	//print $pageposafter.'-'.$pageposbefore;exit;
-                    	$pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
-                    	pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm-$curX, 4, $curX, $curY, $hideref, $hidedesc);
-                    	$posyafter=$pdf->GetY();
-                    	if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot)))	// There is no space left for total+free text
+                    	$pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
+                    	pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxcomm - $curX, 4, $curX, $curY, $hideref, $hidedesc);
+                    	$posyafter = $pdf->GetY();
+                    	if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)))	// There is no space left for total+free text
                     	{
-                    		if ($i == ($nblines-1))	// No more lines, and no space left to show total, so we create a new page
+                    		if ($i == ($nblines - 1))	// No more lines, and no space left to show total, so we create a new page
                     		{
                     			$pdf->AddPage('', '', true);
-                    			if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+                    			if (!empty($tplidx)) $pdf->useTemplate($tplidx);
                     			if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-                    			$pdf->setPage($pageposafter+1);
+                    			$pdf->setPage($pageposafter + 1);
                     		}
                     	}
                     	else
                     	{
                     		// We found a page break
-                    		$showpricebeforepagebreak=0;
+                    		$showpricebeforepagebreak = 0;
                     	}
                     }
                     else	// No pagebreak
@@ -416,17 +416,17 @@ class pdf_typhon extends ModelePDFDeliveryOrder
                     }
 
 					$nexY = $pdf->GetY();
-                    $pageposafter=$pdf->getPage();
+                    $pageposafter = $pdf->getPage();
 					$pdf->setPage($pageposbefore);
 					$pdf->setTopMargin($this->marge_haute);
-					$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.
 
 					// We suppose that a too long description is moved completely on next page
 					if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
 						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
 					}
 
-					$pdf->SetFont('', '', $default_font_size - 1);   // On repositionne la police par defaut
+					$pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut
 
 					/*
 					 // TVA
@@ -445,7 +445,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 					// Remaining to ship
 					$pdf->SetXY($this->posxremainingqty, $curY);
 					$qtyRemaining = $object->lines[$i]->qty_asked - $object->commande->expeditions[$object->lines[$i]->fk_origin_line];
-					$pdf->MultiCell($this->page_largeur-$this->marge_droite - $this->posxremainingqty, 3, $qtyRemaining, 0, 'R');
+					$pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxremainingqty, 3, $qtyRemaining, 0, 'R');
 					/*
 					 // Remise sur ligne
 					 $pdf->SetXY($this->posxdiscount, $curY);
@@ -467,16 +467,16 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 					 */
 
 					// 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)
@@ -493,10 +493,10 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 						$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)
 						{
@@ -509,7 +509,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 						$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);
 					}
@@ -519,12 +519,12 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 				if ($pagenb == 1)
 				{
 					$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
-					$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);
-					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
+					$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
 				}
 
 				// Affiche zone infos
@@ -601,36 +601,36 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 				$pdf->Output($file, 'F');
 
 				// 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('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->transnoentities("ErrorCanNotCreateDir", $dir);
+				$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
 				return 0;
 			}
 		}
 
-		$this->error=$langs->transnoentities("ErrorConstantNotDefined", "LIVRAISON_OUTPUTDIR");
+		$this->error = $langs->transnoentities("ErrorConstantNotDefined", "LIVRAISON_OUTPUTDIR");
 		return 0;
 	}
 
@@ -648,19 +648,19 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 	protected function _tableau_info(&$pdf, $object, $posy, $outputlangs)
 	{
         // phpcs:enable
-		global $conf,$mysoc;
+		global $conf, $mysoc;
 		$default_font_size = pdf_getPDFFontSize($outputlangs);
 
 		$pdf->SetFont('', '', $default_font_size);
 		$pdf->SetXY($this->marge_gauche, $posy);
 
-		$larg_sign = ($this->page_largeur-$this->marge_gauche-$this->marge_droite)/3;
+		$larg_sign = ($this->page_largeur - $this->marge_gauche - $this->marge_droite) / 3;
 		$pdf->Rect($this->marge_gauche, $posy + 1, $larg_sign, 25);
 		$pdf->SetXY($this->marge_gauche + 2, $posy + 2);
 		$pdf->MultiCell($larg_sign, 2, $outputlangs->trans("For").' '.$outputlangs->convToOutputCharset($mysoc->name).":", '', 'L');
 
-		$pdf->Rect(2*$larg_sign+$this->marge_gauche, $posy + 1, $larg_sign, 25);
-		$pdf->SetXY(2*$larg_sign+$this->marge_gauche + 2, $posy + 2);
+		$pdf->Rect(2 * $larg_sign + $this->marge_gauche, $posy + 1, $larg_sign, 25);
+		$pdf->SetXY(2 * $larg_sign + $this->marge_gauche + 2, $posy + 2);
 		$pdf->MultiCell($larg_sign, 2, $outputlangs->trans("ForCustomer").':', '', 'L');
 	}
 
@@ -679,11 +679,11 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 	 */
 	protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0)
 	{
-		global $conf,$mysoc;
+		global $conf, $mysoc;
 
 		// Force to disable hidetop and hidebottom
-		$hidebottom=0;
-		if ($hidetop) $hidetop=-1;
+		$hidebottom = 0;
+		if ($hidetop) $hidetop = -1;
 
 		$default_font_size = pdf_getPDFFontSize($outputlangs);
 
@@ -692,11 +692,11 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 		$pdf->SetFont('', '', $default_font_size - 2);
 
 		// Output Rec
-		$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
+		$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
 
 		if (empty($hidetop))
 		{
-			$pdf->line($this->marge_gauche, $tab_top+10, $this->page_largeur-$this->marge_droite, $tab_top+10);
+			$pdf->line($this->marge_gauche, $tab_top + 10, $this->page_largeur - $this->marge_droite, $tab_top + 10);
 		}
 
 		$pdf->SetDrawColor(128, 128, 128);
@@ -704,29 +704,29 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 
 		if (empty($hidetop))
 		{
-			$pdf->SetXY($this->posxdesc-1, $tab_top+1);
+			$pdf->SetXY($this->posxdesc - 1, $tab_top + 1);
 			$pdf->MultiCell($this->posxcomm - $this->posxdesc, 2, $outputlangs->transnoentities("Designation"), '', 'L');
 		}
 
 		// Modif SEB pour avoir une col en plus pour les commentaires clients
 		$pdf->line($this->posxcomm, $tab_top, $this->posxcomm, $tab_top + $tab_height);
 		if (empty($hidetop)) {
-			$pdf->SetXY($this->posxcomm, $tab_top+1);
+			$pdf->SetXY($this->posxcomm, $tab_top + 1);
 			$pdf->MultiCell($this->posxqty - $this->posxcomm, 2, $outputlangs->transnoentities("Comments"), '', 'L');
 		}
 
 		// Qty
 		$pdf->line($this->posxqty, $tab_top, $this->posxqty, $tab_top + $tab_height);
 		if (empty($hidetop)) {
-			$pdf->SetXY($this->posxqty, $tab_top+1);
+			$pdf->SetXY($this->posxqty, $tab_top + 1);
 			$pdf->MultiCell($this->posxremainingqty - $this->posxqty, 2, $outputlangs->transnoentities("QtyShippedShort"), '', 'R');
 		}
 
 		// Remain to ship
 		$pdf->line($this->posxremainingqty, $tab_top, $this->posxremainingqty, $tab_top + $tab_height);
 		if (empty($hidetop)) {
-			$pdf->SetXY($this->posxremainingqty, $tab_top+1);
-			$pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->posxremainingqty, 2, $outputlangs->transnoentities("KeepToShipShort"), '', 'R');
+			$pdf->SetXY($this->posxremainingqty, $tab_top + 1);
+			$pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxremainingqty, 2, $outputlangs->transnoentities("KeepToShipShort"), '', 'R');
 		}
 	}
 
@@ -742,14 +742,14 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 	 */
 	protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs)
 	{
-		global $conf,$langs,$hookmanager;
+		global $conf, $langs, $hookmanager;
 
 		$default_font_size = pdf_getPDFFontSize($outputlangs);
 
 		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);
 		}
@@ -757,19 +757,19 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 		$pdf->SetTextColor(0, 0, 60);
 		$pdf->SetFont('', 'B', $default_font_size + 3);
 
-		$posy=$this->marge_haute;
-		$posx=$this->page_largeur-$this->marge_droite-100;
+		$posy = $this->marge_haute;
+		$posx = $this->page_largeur - $this->marge_droite - 100;
 
 		$pdf->SetXY($this->marge_gauche, $posy);
 
 		// Logo
-		$logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
+		$logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
 		if ($this->emetteur->logo)
 		{
 			if (is_readable($logo))
 			{
-			    $height=pdf_getHeightForLogo($logo);
-			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
+			    $height = pdf_getHeightForLogo($logo);
+			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
 			}
 			else
 			{
@@ -788,12 +788,12 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 
 		$pdf->SetFont('', '', $default_font_size + 2);
 
-		$posy+=5;
+		$posy += 5;
 		$pdf->SetXY($posx, $posy);
 		$pdf->SetTextColor(0, 0, 60);
 		if ($object->date_valid)
 		{
-			$pdf->MultiCell(100, 4, $outputlangs->transnoentities("Date")." : " . dol_print_date($object->date_delivery, "%d %b %Y", false, $outputlangs, true), '', 'R');
+			$pdf->MultiCell(100, 4, $outputlangs->transnoentities("Date")." : ".dol_print_date($object->date_delivery, "%d %b %Y", false, $outputlangs, true), '', 'R');
 		}
 		else
 		{
@@ -804,15 +804,15 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 
 		if ($object->thirdparty->code_client)
 		{
-			$posy+=5;
+			$posy += 5;
 			$pdf->SetXY($posx, $posy);
 			$pdf->SetTextColor(0, 0, 60);
-			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
+			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
 		}
 
 		$pdf->SetTextColor(0, 0, 60);
 
-		$posy+=2;
+		$posy += 2;
 
 		// Show list of linked objects
 		$posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, 100, 3, 'R', $default_font_size);
@@ -823,15 +823,15 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 			$carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object);
 
 			// Show sender
-			$posy=42;
-			$posx=$this->marge_gauche;
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80;
-			$hautcadre=40;
+			$posy = 42;
+			$posx = $this->marge_gauche;
+			if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80;
+			$hautcadre = 40;
 
 			// Show sender frame
 			$pdf->SetTextColor(0, 0, 0);
 			$pdf->SetFont('', '', $default_font_size - 2);
-			$pdf->SetXY($posx, $posy-5);
+			$pdf->SetXY($posx, $posy - 5);
 			$pdf->MultiCell(66, 5, $outputlangs->transnoentities("BillFrom").":", 0, 'L');
 			$pdf->SetXY($posx, $posy);
 			$pdf->SetFillColor(230, 230, 230);
@@ -839,32 +839,32 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 			$pdf->SetTextColor(0, 0, 60);
 
 			// Show sender name
-			$pdf->SetXY($posx+2, $posy+3);
+			$pdf->SetXY($posx + 2, $posy + 3);
 			$pdf->SetFont('', 'B', $default_font_size);
 			$pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
-			$posy=$pdf->getY();
+			$posy = $pdf->getY();
 
 			// Show sender information
-			$pdf->SetXY($posx+2, $posy);
+			$pdf->SetXY($posx + 2, $posy);
 			$pdf->SetFont('', '', $default_font_size - 1);
 			$pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L');
 
 			// Client destinataire
-			$posy=42;
-			$posx=102;
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;
+			$posy = 42;
+			$posx = 102;
+			if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche;
 			$pdf->SetTextColor(0, 0, 0);
 			$pdf->SetFont('', '', $default_font_size - 2);
-			$pdf->SetXY($posx, $posy-5);
+			$pdf->SetXY($posx, $posy - 5);
 			$pdf->MultiCell(80, 5, $outputlangs->transnoentities("DeliveryAddress").":", 0, 'L');
 
 			// If SHIPPING contact defined on order, we use it
-			$usecontact=false;
-			$arrayidcontact=$object->commande->getIdContact('external', 'SHIPPING');
+			$usecontact = false;
+			$arrayidcontact = $object->commande->getIdContact('external', 'SHIPPING');
 			if (count($arrayidcontact) > 0)
 			{
-				$usecontact=true;
-				$result=$object->fetch_contact($arrayidcontact[0]);
+				$usecontact = true;
+				$result = $object->fetch_contact($arrayidcontact[0]);
 			}
 
 			//Recipient name
@@ -875,26 +875,26 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 				$thirdparty = $object->thirdparty;
 			}
 
-			$carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs);
+			$carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs);
 
-			$carac_client=pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact?$object->contact:''), $usecontact, 'target', $object);
+			$carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact ? $object->contact : ''), $usecontact, 'target', $object);
 
 			// Show recipient
-			$widthrecbox=100;
-			if ($this->page_largeur < 210) $widthrecbox=84;	// To work with US executive format
-			$posy=42;
-			$posx=$this->page_largeur-$this->marge_droite-$widthrecbox;
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;
+			$widthrecbox = 100;
+			if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format
+			$posy = 42;
+			$posx = $this->page_largeur - $this->marge_droite - $widthrecbox;
+			if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche;
 
 			// Show recipient frame
 			$pdf->SetTextColor(0, 0, 0);
 			$pdf->SetFont('', '', $default_font_size - 2);
-			$pdf->SetXY($posx+2, $posy-5);
+			$pdf->SetXY($posx + 2, $posy - 5);
 			//$pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("BillTo").":",0,'L');
 			$pdf->Rect($posx, $posy, $widthrecbox, $hautcadre);
 
 			// Show recipient name
-			$pdf->SetXY($posx+2, $posy+3);
+			$pdf->SetXY($posx + 2, $posy + 3);
 			$pdf->SetFont('', 'B', $default_font_size);
 			$pdf->MultiCell($widthrecbox, 4, $carac_client_name, 0, 'L');
 
@@ -902,7 +902,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 
 			// Show recipient information
 			$pdf->SetFont('', '', $default_font_size - 1);
-			$pdf->SetXY($posx+2, $posy);
+			$pdf->SetXY($posx + 2, $posy);
 			$pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L');
 		}
 
@@ -922,7 +922,7 @@ class pdf_typhon extends ModelePDFDeliveryOrder
 	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, 'DELIVERY_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext);
     }
 }

+ 15 - 15
htdocs/core/modules/modCashDesk.class.php

@@ -22,7 +22,7 @@
  *      \ingroup    pos
  *      \brief      File to enable/disable module Point Of Sales
  */
-include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php';
+include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
 
 
 /**
@@ -64,13 +64,13 @@ class modCashDesk extends DolibarrModules
 		$this->config_page_url = array("cashdesk.php@cashdesk");
 
 		// Dependencies
-		$this->hidden = false;			            // A condition to hide module
-		$this->depends = array('always'=>"modBanque", 'always'=>"modFacture", 'always'=>"modProduct", 'FR'=>'modBlockedLog');	// List of modules id that must be enabled if this module is enabled
-		$this->requiredby = array();			    // List of modules id to disable if this one is disabled
-		$this->phpmin = array(5,4);					// Minimum version of PHP required by module
-		$this->need_dolibarr_version = array(2,4);	// Minimum version of Dolibarr required by module
+		$this->hidden = false; // A condition to hide module
+		$this->depends = array('always'=>"modBanque", 'always'=>"modFacture", 'always'=>"modProduct", 'FR'=>'modBlockedLog'); // List of modules id that must be enabled if this module is enabled
+		$this->requiredby = array(); // List of modules id to disable if this one is disabled
+		$this->phpmin = array(5, 4); // Minimum version of PHP required by module
+		$this->need_dolibarr_version = array(2, 4); // Minimum version of Dolibarr required by module
 		$this->langfiles = array("cashdesk");
-		$this->warnings_activation = array('FR'=>'WarningNoteModulePOSForFrenchLaw');                     // Warning to show when we activate module. array('always'='text') or array('FR'='text')
+		$this->warnings_activation = array('FR'=>'WarningNoteModulePOSForFrenchLaw'); // Warning to show when we activate module. array('always'='text') or array('FR'='text')
 		//$this->warnings_activation_ext = array('FR'=>'WarningInstallationMayBecomeNotCompliantWithLaw');  // Warning to show when we activate an external module. array('always'='text') or array('FR'='text')
 
 		// Constants
@@ -81,7 +81,7 @@ class modCashDesk extends DolibarrModules
 
 		// Permissions
 		$this->rights = array();
-		$r=0;
+		$r = 0;
 
 		$r++;
 		$this->rights[$r][0] = 50101;
@@ -91,21 +91,21 @@ class modCashDesk extends DolibarrModules
 		$this->rights[$r][4] = 'run';
 
 		// Main menu entries
-		$this->menus = array();			// List of menus to add
-		$r=0;
+		$this->menus = array(); // List of menus to add
+		$r = 0;
 
 		// This is to declare the Top Menu entry:
-		$this->menu[$r]=array(	    'fk_menu'=>0,			// Put 0 if this is a top menu
-									'type'=>'top',			// This is a Top menu entry
+		$this->menu[$r] = array('fk_menu'=>0, // Put 0 if this is a top menu
+									'type'=>'top', // This is a Top menu entry
 									'titre'=>'PointOfSaleShort',
 									'mainmenu'=>'cashdesk',
 									'url'=>'/cashdesk/index.php?user=__USER_LOGIN__',
-									'langs'=>'cashdesk',	// Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
+									'langs'=>'cashdesk', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
 									'position'=>900,
                                     'enabled'=>'$conf->cashdesk->enabled',
-		                            'perms'=>'$user->rights->cashdesk->run',		// Use 'perms'=>'1' if you want your menu with no permission rules
+		                            'perms'=>'$user->rights->cashdesk->run', // Use 'perms'=>'1' if you want your menu with no permission rules
 									'target'=>'pointofsale',
-									'user'=>0);				// 0=Menu for internal users, 1=external users, 2=both
+									'user'=>0); // 0=Menu for internal users, 1=external users, 2=both
 
 		$r++;
 

+ 36 - 36
htdocs/core/modules/modMrp.class.php

@@ -26,7 +26,7 @@
  *  \ingroup    mrp
  *  \brief      Description and activation file for module Mrp
  */
-include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php';
+include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
 
 /**
  *  Description and activation class for module Mrp
@@ -40,7 +40,7 @@ class modMrp extends DolibarrModules
      */
     public function __construct($db)
     {
-        global $langs,$conf;
+        global $langs, $conf;
         $this->db = $db;
 
         // Id for module (must be unique).
@@ -71,7 +71,7 @@ class modMrp extends DolibarrModules
         // Name of image file used for this module.
         // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue'
         // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module'
-        $this->picto='mrp';
+        $this->picto = 'mrp';
         // Define some features supported by module (triggers, login, substitutions, menus, css, etc...)
         $this->module_parts = array(
             // Set this to 1 if module has its own trigger directory (core/triggers)
@@ -119,13 +119,13 @@ class modMrp extends DolibarrModules
         $this->hidden = false;
         // List of module class names as string that must be enabled if this module is enabled. Example: array('always1'=>'modModuleToEnable1','always2'=>'modModuleToEnable2', 'FR1'=>'modModuleToEnableFR'...)
         $this->depends = array('modBom');
-        $this->requiredby = array();	// List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...)
-        $this->conflictwith = array();	// List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...)
+        $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...)
+        $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...)
         $this->langfiles = array("mrp");
-        $this->phpmin = array(5,5);					    // Minimum version of PHP required by module
-        $this->need_dolibarr_version = array(8,0);		// Minimum version of Dolibarr required by module
-        $this->warnings_activation = array();			// Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...)
-        $this->warnings_activation_ext = array();		// Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...)
+        $this->phpmin = array(5, 5); // Minimum version of PHP required by module
+        $this->need_dolibarr_version = array(8, 0); // Minimum version of Dolibarr required by module
+        $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...)
+        $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...)
         //$this->automatic_activation = array('FR'=>'MrpWasAutomaticallyActivatedBecauseOfYourCountryChoice');
         //$this->always_enabled = true;								// If true, can't be disabled
 
@@ -146,9 +146,9 @@ class modMrp extends DolibarrModules
             'fr_FR:ParentCompany'=>'Maison mère ou revendeur'
         )*/
 
-        if (! isset($conf->mrp) || ! isset($conf->mrp->enabled)) {
-            $conf->mrp=new stdClass();
-            $conf->mrp->enabled=0;
+        if (!isset($conf->mrp) || !isset($conf->mrp->enabled)) {
+            $conf->mrp = new stdClass();
+            $conf->mrp->enabled = 0;
         }
 
         // Array to add new pages in new tabs
@@ -180,7 +180,7 @@ class modMrp extends DolibarrModules
         // 'user'             to add a tab in user view
 
         // Dictionaries
-        $this->dictionaries=array();
+        $this->dictionaries = array();
         /* Example:
         $this->dictionaries=array(
             'langs'=>'mylangfile@mrp',
@@ -236,35 +236,35 @@ class modMrp extends DolibarrModules
 
         // Permissions provided by this module
         $this->rights = array();
-        $r=0;
+        $r = 0;
         // Add here entries to declare new permissions
         /* BEGIN MODULEBUILDER PERMISSIONS */
-        $this->rights[$r][0] = $this->numero + $r;	// Permission id (must not be already used)
-        $this->rights[$r][1] = 'Read Manufacturing Order';	// Permission label
-        $this->rights[$r][4] = 'read';				// In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
-        $this->rights[$r][5] = '';				    // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
+        $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used)
+        $this->rights[$r][1] = 'Read Manufacturing Order'; // Permission label
+        $this->rights[$r][4] = 'read'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
+        $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
         $r++;
-        $this->rights[$r][0] = $this->numero + $r;	// Permission id (must not be already used)
-        $this->rights[$r][1] = 'Create/Update Manufacturing Order';	// Permission label
-        $this->rights[$r][4] = 'write';				// In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
-        $this->rights[$r][5] = '';				    // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
+        $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used)
+        $this->rights[$r][1] = 'Create/Update Manufacturing Order'; // Permission label
+        $this->rights[$r][4] = 'write'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
+        $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
         $r++;
-        $this->rights[$r][0] = $this->numero + $r;	// Permission id (must not be already used)
-        $this->rights[$r][1] = 'Delete Manufacturing Order';	// Permission label
-        $this->rights[$r][4] = 'delete';				// In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
-        $this->rights[$r][5] = '';				    // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
+        $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used)
+        $this->rights[$r][1] = 'Delete Manufacturing Order'; // Permission label
+        $this->rights[$r][4] = 'delete'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
+        $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2)
         $r++;
         /* END MODULEBUILDER PERMISSIONS */
 
         // Main menu entries to add
         $this->menu = array();
-        $r=0;
+        $r = 0;
         // Add here entries to declare new menus
         /* BEGIN MODULEBUILDER TOPMENU */
 		/* END MODULEBUILDER LEFTMENU MO */
 
         // Exports profiles provided by this module
-        $r=1;
+        $r = 1;
         /* BEGIN MODULEBUILDER EXPORT MO */
         /*
         $langs->load("mrp");
@@ -284,7 +284,7 @@ class modMrp extends DolibarrModules
         /* END MODULEBUILDER EXPORT MO */
 
         // Imports profiles provided by this module
-        $r=1;
+        $r = 1;
         /* BEGIN MODULEBUILDER IMPORT MO */
         /*
          $langs->load("mrp");
@@ -316,7 +316,7 @@ class modMrp extends DolibarrModules
     {
     	global $conf, $langs;
 
-        $result=$this->_load_tables('/mrp/sql/');
+        $result = $this->_load_tables('/mrp/sql/');
         if ($result < 0) return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default')
 
         // Create extrafields during init
@@ -334,19 +334,19 @@ class modMrp extends DolibarrModules
         $sql = array();
 
         // ODT template
-        $src=DOL_DOCUMENT_ROOT.'/install/doctemplates/mrps/template_mo.odt';
-        $dirodt=DOL_DATA_ROOT.'/doctemplates/mrps';
-        $dest=$dirodt.'/template_mo.odt';
+        $src = DOL_DOCUMENT_ROOT.'/install/doctemplates/mrps/template_mo.odt';
+        $dirodt = DOL_DATA_ROOT.'/doctemplates/mrps';
+        $dest = $dirodt.'/template_mo.odt';
 
-        if (file_exists($src) && ! file_exists($dest))
+        if (file_exists($src) && !file_exists($dest))
         {
         	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
         	dol_mkdir($dirodt);
-        	$result=dol_copy($src, $dest, 0, 0);
+        	$result = dol_copy($src, $dest, 0, 0);
         	if ($result < 0)
         	{
         		$langs->load("errors");
-        		$this->error=$langs->trans('ErrorFailToCopyFile', $src, $dest);
+        		$this->error = $langs->trans('ErrorFailToCopyFile', $src, $dest);
         		return 0;
         	}
         }

+ 34 - 34
htdocs/core/modules/modTakePos.class.php

@@ -24,7 +24,7 @@
  *  \ingroup    takepos
  *  \brief      Description and activation file for module TakePos
  */
-include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php';
+include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
 
 
 /**
@@ -39,7 +39,7 @@ class modTakePos extends DolibarrModules
 	 */
 	public function __construct($db)
 	{
-        global $langs,$conf;
+        global $langs, $conf;
 
         $this->db = $db;
 
@@ -71,21 +71,21 @@ class modTakePos extends DolibarrModules
 		// Name of image file used for this module.
 		// If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue'
 		// If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module'
-		$this->picto='list';
+		$this->picto = 'list';
 
 		// Defined all module parts (triggers, login, substitutions, menus, css, etc...)
 		// for default path (eg: /takepos/core/xxxxx) (0=disable, 1=enable)
 		// for specific path of parts (eg: /takepos/core/modules/barcode)
 		// for specific css file (eg: /takepos/css/takepos.css.php)
 		$this->module_parts = array(
-		                        	'triggers' => 0,                                 	// Set this to 1 if module has its own trigger directory (core/triggers)
-									'login' => 0,                                    	// Set this to 1 if module has its own login method file (core/login)
-									'substitutions' => 1,                            	// Set this to 1 if module has its own substitution function file (core/substitutions)
-									'menus' => 0,                                    	// Set this to 1 if module has its own menus handler directory (core/menus)
-									'theme' => 0,                                    	// Set this to 1 if module has its own theme directory (theme)
-		                        	'tpl' => 0,                                      	// Set this to 1 if module overwrite template dir (core/tpl)
-									'barcode' => 0,                                  	// Set this to 1 if module has its own barcode directory (core/modules/barcode)
-									'models' => 0,                                   	// Set this to 1 if module has its own models directory (core/modules/xxx)
+		                        	'triggers' => 0, // Set this to 1 if module has its own trigger directory (core/triggers)
+									'login' => 0, // Set this to 1 if module has its own login method file (core/login)
+									'substitutions' => 1, // Set this to 1 if module has its own substitution function file (core/substitutions)
+									'menus' => 0, // Set this to 1 if module has its own menus handler directory (core/menus)
+									'theme' => 0, // Set this to 1 if module has its own theme directory (theme)
+		                        	'tpl' => 0, // Set this to 1 if module overwrite template dir (core/tpl)
+									'barcode' => 0, // Set this to 1 if module has its own barcode directory (core/modules/barcode)
+									'models' => 0, // Set this to 1 if module has its own models directory (core/modules/xxx)
 									'hooks' => array() 	                                // Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context 'all'
 		                        );
 
@@ -97,15 +97,15 @@ class modTakePos extends DolibarrModules
 		$this->config_page_url = array("setup.php@takepos");
 
 		// Dependencies
-		$this->hidden = false;			// A condition to hide module
-		$this->depends = array('always1'=>"modBanque", 'always2'=>"modFacture", 'always3'=>"modProduct", 'always4'=>'modCategorie', 'FR1'=>'modBlockedLog');			// 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->hidden = false; // A condition to hide module
+		$this->depends = array('always1'=>"modBanque", 'always2'=>"modFacture", 'always3'=>"modProduct", 'always4'=>'modCategorie', 'FR1'=>'modBlockedLog'); // 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->langfiles = array("cashdesk");
-		$this->phpmin = array(5,4);					// Minimum version of PHP required by module
-		$this->need_dolibarr_version = array(4,0);	// Minimum version of Dolibarr required by module
-		$this->warnings_activation = array('FR'=>'WarningNoteModulePOSForFrenchLaw');                     // Warning to show when we activate module. array('always'='text') or array('FR'='text')
-		$this->warnings_activation_ext = array();                 // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...)
+		$this->phpmin = array(5, 4); // Minimum version of PHP required by module
+		$this->need_dolibarr_version = array(4, 0); // Minimum version of Dolibarr required by module
+		$this->warnings_activation = array('FR'=>'WarningNoteModulePOSForFrenchLaw'); // Warning to show when we activate module. array('always'='text') or array('FR'='text')
+		$this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...)
 		//$this->automatic_activation = array('FR'=>'TakePosWasAutomaticallyActivatedBecauseOfYourCountryChoice');
 		//$this->always_enabled = true;								// If true, can't be disabled
 
@@ -119,10 +119,10 @@ class modTakePos extends DolibarrModules
 		);
 
 
-		if (! isset($conf->takepos) || ! isset($conf->takepos->enabled))
+		if (!isset($conf->takepos) || !isset($conf->takepos->enabled))
 		{
-			$conf->takepos=new stdClass();
-			$conf->takepos->enabled=0;
+			$conf->takepos = new stdClass();
+			$conf->takepos->enabled = 0;
 		}
 
 
@@ -156,7 +156,7 @@ class modTakePos extends DolibarrModules
 
 
         // Dictionaries
-		$this->dictionaries=array();
+		$this->dictionaries = array();
         /* Example:
         $this->dictionaries=array(
             'langs'=>'mylangfile@takepos',
@@ -193,9 +193,9 @@ class modTakePos extends DolibarrModules
 
 
 		// Permissions
-		$this->rights = array();		// Permission array used by this module
+		$this->rights = array(); // Permission array used by this module
 
-		$r=0;
+		$r = 0;
 
 		$r++;
 		$this->rights[$r][0] = 50151;
@@ -206,24 +206,24 @@ class modTakePos extends DolibarrModules
 
 
 		// Main menu entries
-		$this->menu = array();			// List of menus to add
-		$r=0;
+		$this->menu = array(); // List of menus to add
+		$r = 0;
 
 		// Add here entries to declare new menus
 
 		/* BEGIN MODULEBUILDER TOPMENU */
-		$this->menu[$r++]=array('fk_menu'=>'',			                // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
-								'type'=>'top',			                // This is a Top menu entry
+		$this->menu[$r++] = array('fk_menu'=>'', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
+								'type'=>'top', // This is a Top menu entry
 								'titre'=>'PointOfSaleShort',
 								'mainmenu'=>'takepos',
 								'leftmenu'=>'',
 								'url'=>'/takepos/takepos.php',
-								'langs'=>'cashdesk',	        // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
-								'position'=>1000+$r,
-								'enabled'=>'$conf->takepos->enabled',	// Define condition to show or hide menu entry. Use '$conf->takepos->enabled' if entry must be visible if module is enabled.
-								'perms'=>'$user->rights->takepos->run',			                // Use 'perms'=>'$user->rights->takepos->level1->level2' if you want your menu with a permission rules
+								'langs'=>'cashdesk', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
+								'position'=>1000 + $r,
+								'enabled'=>'$conf->takepos->enabled', // Define condition to show or hide menu entry. Use '$conf->takepos->enabled' if entry must be visible if module is enabled.
+								'perms'=>'$user->rights->takepos->run', // Use 'perms'=>'$user->rights->takepos->level1->level2' if you want your menu with a permission rules
 								'target'=>'takepos',
-								'user'=>2);				                // 0=Menu for internal users, 1=external users, 2=both
+								'user'=>2); // 0=Menu for internal users, 1=external users, 2=both
 
 		/* END MODULEBUILDER TOPMENU */
 

+ 183 - 183
htdocs/core/modules/propale/doc/pdf_cyan.modules.php

@@ -135,45 +135,45 @@ class pdf_cyan extends ModelePDFPropales
 		$this->db = $db;
 		$this->name = "cyan";
 		$this->description = $langs->trans('DocModelCyanDescription');
-		$this->update_main_doc_field = 1;		// Save the name of generated file as the main doc when generating a doc with this template
+		$this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template
 
 		// Dimension page
 		$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->option_logo = 1;                    // Display logo
-		$this->option_tva = 1;                     // Manage the vat option FACTURE_TVAOPTION
-		$this->option_modereg = 1;                 // Display payment mode
-		$this->option_condreg = 1;                 // Display payment terms
-		$this->option_codeproduitservice = 1;      // Display product-service code
-		$this->option_multilang = 1;               // Available in several languages
-		$this->option_escompte = 0;                // Displays if there has been a discount
-		$this->option_credit_note = 0;             // Support credit notes
-		$this->option_freetext = 1;				   // Support add of a personalised text
-		$this->option_draft_watermark = 1;		   // Support add of a watermark on drafts
+		$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; // Display logo
+		$this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION
+		$this->option_modereg = 1; // Display payment mode
+		$this->option_condreg = 1; // Display payment terms
+		$this->option_codeproduitservice = 1; // Display product-service code
+		$this->option_multilang = 1; // Available in several languages
+		$this->option_escompte = 0; // Displays if there has been a discount
+		$this->option_credit_note = 0; // Support credit notes
+		$this->option_freetext = 1; // Support add of a personalised text
+		$this->option_draft_watermark = 1; // Support add of a watermark on drafts
 
 		// Get source company
-		$this->emetteur=$mysoc;
-		if (empty($this->emetteur->country_code)) $this->emetteur->country_code=substr($langs->defaultlang, -2);    // By default, if was not defined
+		$this->emetteur = $mysoc;
+		if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined
 
 		// Define position of columns
-		$this->posxdesc=$this->marge_gauche+1;
+		$this->posxdesc = $this->marge_gauche + 1;
 
 
 		$this->tabTitleHeight = 5; // default height
 
-		$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;
 	}
 
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
@@ -191,16 +191,16 @@ class pdf_cyan extends ModelePDFPropales
 	public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
 	{
 	  // phpcs:enable
-		global $user,$langs,$conf,$mysoc,$db,$hookmanager,$nblines;
+		global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines;
 
-		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", "products", "propal"));
 
-		if (! empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
+		if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
 			global $outputlangsbis;
 			$outputlangsbis = new Translate('', $conf);
 			$outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE);
@@ -209,39 +209,39 @@ class pdf_cyan extends ModelePDFPropales
 
 		$nblines = count($object->lines);
 
-		$hidetop=0;
-		if(!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)){
-		    $hidetop=$conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE;
+		$hidetop = 0;
+		if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) {
+		    $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE;
 		}
 
 		// Loop on each lines to detect if there is at least one image to show
-		$realpatharray=array();
+		$realpatharray = array();
 		$this->atleastonephoto = false;
-		if (! empty($conf->global->MAIN_GENERATE_PROPOSALS_WITH_PICTURE))
+		if (!empty($conf->global->MAIN_GENERATE_PROPOSALS_WITH_PICTURE))
 		{
 			$objphoto = new Product($this->db);
 
-			for ($i = 0 ; $i < $nblines ; $i++)
+			for ($i = 0; $i < $nblines; $i++)
 			{
 				if (empty($object->lines[$i]->fk_product)) continue;
 
 				$objphoto->fetch($object->lines[$i]->fk_product);
                 //var_dump($objphoto->ref);exit;
-				if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
+				if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
 				{
-					$pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/";
-					$pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/';
+					$pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/";
+					$pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/';
 				}
 				else
 				{
-					$pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/';				// default
-					$pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product') . $objphoto->id ."/photos/";	// alternative
+					$pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default
+					$pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative
 				}
 
 				$arephoto = false;
 				foreach ($pdir as $midir)
 				{
-					if (! $arephoto)
+					if (!$arephoto)
 					{
 						if ($conf->product->entity != $objphoto->entity) {
 							$dir = $conf->product->multidir_output[$objphoto->entity].'/'.$midir; //Check repertories of current entities
@@ -333,14 +333,14 @@ class pdf_cyan extends ModelePDFPropales
                 }
                 $pdf->SetFont(pdf_getPDFFont($outputlangs));
                 // Set path to the background PDF File
-                if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
+                if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
                 {
                 	$pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$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));
@@ -393,38 +393,38 @@ class pdf_cyan extends ModelePDFPropales
 						$tab_top -= 2;
 
 						$pdf->SetFont('', '', $default_font_size - 1);
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
+						$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
 						$nexY = $pdf->GetY();
-						$height_incoterms=$nexY-$tab_top;
+						$height_incoterms = $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_incoterms+1);
+						$pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1);
 
-						$tab_top = $nexY+6;
+						$tab_top = $nexY + 6;
 					}
 				}
 
 				// Affiche notes
-				$notetoshow=empty($object->note_public)?'':$object->note_public;
-				if (! empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE))
+				$notetoshow = empty($object->note_public) ? '' : $object->note_public;
+				if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE))
 				{
 					// Get first sale rep
 					if (is_object($object->thirdparty))
 					{
-						$salereparray=$object->thirdparty->getSalesRepresentatives($user);
-						$salerepobj=new User($this->db);
+						$salereparray = $object->thirdparty->getSalesRepresentatives($user);
+						$salerepobj = new User($this->db);
 						$salerepobj->fetch($salereparray[0]['id']);
-						if (! empty($salerepobj->signature)) $notetoshow=dol_concatdesc($notetoshow, $salerepobj->signature);
+						if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature);
 					}
 				}
-				if (! empty($conf->global->MAIN_ADD_CREATOR_IN_NOTE) && $object->user_author_id > 0)
+				if (!empty($conf->global->MAIN_ADD_CREATOR_IN_NOTE) && $object->user_author_id > 0)
 				{
-				    $tmpuser=new User($this->db);
+				    $tmpuser = new User($this->db);
 				    $tmpuser->fetch($object->user_author_id);
 				    $notetoshow .= $langs->trans("CaseFollowedBy").' '.$tmpuser->getFullName($langs);
-				    if ($tmpuser->email) $notetoshow.=',  Mail: '.$tmpuser->email;
-				    if ($tmpuser->office_phone) $notetoshow.=', Tel: '.$tmpuser->office_phone;
+				    if ($tmpuser->email) $notetoshow .= ',  Mail: '.$tmpuser->email;
+				    if ($tmpuser->office_phone) $notetoshow .= ', Tel: '.$tmpuser->office_phone;
 				}
 
 				$tab_height = $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforsignature - $heightforfooter;
@@ -561,102 +561,102 @@ class pdf_cyan extends ModelePDFPropales
 				$nexY = $tab_top + $this->tabTitleHeight + 2;
 
 				// Loop on each lines
-				$pageposbeforeprintlines=$pdf->getPage();
+				$pageposbeforeprintlines = $pdf->getPage();
 				$pagenb = $pageposbeforeprintlines;
 				for ($i = 0; $i < $nblines; $i++)
 				{
 					$curY = $nexY;
-					$pdf->SetFont('', '', $default_font_size - 1);   // Into loop to work with multipage
+					$pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage
 					$pdf->SetTextColor(0, 0, 0);
 
 					// Define size of image if we need it
-					$imglinesize=array();
-					if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
+					$imglinesize = array();
+					if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]);
 
 					$pdf->setTopMargin($tab_top_newpage);
-					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
-					$pageposbefore=$pdf->getPage();
+					$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
+					$pageposbefore = $pdf->getPage();
 
-					$showpricebeforepagebreak=1;
-					$posYAfterImage=0;
-					$posYAfterDescription=0;
+					$showpricebeforepagebreak = 1;
+					$posYAfterImage = 0;
+					$posYAfterDescription = 0;
 
-					if($this->getColumnStatus('photo'))
+					if ($this->getColumnStatus('photo'))
 					{
     					// We start with Photo of product line
-    					if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot)))	// If photo too high, we moved completely on new page
+    					if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot)))	// If photo too high, we moved completely on new page
     					{
     						$pdf->AddPage('', '', true);
-    						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+    						if (!empty($tplidx)) $pdf->useTemplate($tplidx);
     						//if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-    						$pdf->setPage($pageposbefore+1);
+    						$pdf->setPage($pageposbefore + 1);
 
     						$curY = $tab_top_newpage;
-    						$showpricebeforepagebreak=0;
+    						$showpricebeforepagebreak = 0;
     					}
 
 
     					if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height']))
     					{
-    						$pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300);	// Use 300 dpi
+    						$pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi
     						// $pdf->Image does not increase value return by getY, so we save it manually
-    						$posYAfterImage=$curY+$imglinesize['height'];
+    						$posYAfterImage = $curY + $imglinesize['height'];
     					}
 					}
 
 					// Description of product line
-					if($this->getColumnStatus('desc'))
+					if ($this->getColumnStatus('desc'))
 					{
     					$pdf->startTransaction();
     					pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc);
-    					$pageposafter=$pdf->getPage();
+    					$pageposafter = $pdf->getPage();
     					if ($pageposafter > $pageposbefore)	// There is a pagebreak
     					{
     						$pdf->rollbackTransaction(true);
-    						$pageposafter=$pageposbefore;
+    						$pageposafter = $pageposbefore;
     						//print $pageposafter.'-'.$pageposbefore;exit;
-    						$pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
+    						$pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
     						pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc);
 
-    						$pageposafter=$pdf->getPage();
-    						$posyafter=$pdf->GetY();
+    						$pageposafter = $pdf->getPage();
+    						$posyafter = $pdf->GetY();
     						//var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
-    						if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforsignature+$heightforinfotot)))	// There is no space left for total+free text
+    						if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforsignature + $heightforinfotot)))	// There is no space left for total+free text
     						{
-    							if ($i == ($nblines-1))	// No more lines, and no space left to show total, so we create a new page
+    							if ($i == ($nblines - 1))	// No more lines, and no space left to show total, so we create a new page
     							{
     								$pdf->AddPage('', '', true);
-    								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+    								if (!empty($tplidx)) $pdf->useTemplate($tplidx);
     								//if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-    								$pdf->setPage($pageposafter+1);
+    								$pdf->setPage($pageposafter + 1);
     							}
     						}
     						else
     						{
     							// We found a page break
-    							$showpricebeforepagebreak=0;
+    							$showpricebeforepagebreak = 0;
     						}
     					}
     					else	// No pagebreak
     					{
     						$pdf->commitTransaction();
     					}
-    					$posYAfterDescription=$pdf->GetY();
+    					$posYAfterDescription = $pdf->GetY();
 					}
 
 					$nexY = $pdf->GetY();
-					$pageposafter=$pdf->getPage();
+					$pageposafter = $pdf->getPage();
 
 					$pdf->setPage($pageposbefore);
 					$pdf->setTopMargin($this->marge_haute);
-					$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.
 
 					// We suppose that a too long description or photo were moved completely on next page
 					if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
 						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
 					}
 
-					$pdf->SetFont('', '', $default_font_size - 1);   // On repositionne la police par defaut
+					$pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut
 
 					// VAT Rate
 					if ($this->getColumnStatus('vat'))
@@ -718,59 +718,59 @@ class pdf_cyan extends ModelePDFPropales
 					    'outputlangs' => $outputlangs,
 					    'hidedetails' => $hidedetails
 					);
-					$reshook=$hookmanager->executeHooks('printPDFline', $parameters, $this);    // Note that $object may have been modified by hook
+					$reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook
 
 
 
 					// Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva
-					if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne=$object->lines[$i]->multicurrency_total_tva;
-					else $tvaligne=$object->lines[$i]->total_tva;
+					if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva;
+					else $tvaligne = $object->lines[$i]->total_tva;
 
-					$localtax1ligne=$object->lines[$i]->total_localtax1;
-					$localtax2ligne=$object->lines[$i]->total_localtax2;
-					$localtax1_rate=$object->lines[$i]->localtax1_tx;
-					$localtax2_rate=$object->lines[$i]->localtax2_tx;
-					$localtax1_type=$object->lines[$i]->localtax1_type;
-					$localtax2_type=$object->lines[$i]->localtax2_type;
+					$localtax1ligne = $object->lines[$i]->total_localtax1;
+					$localtax2ligne = $object->lines[$i]->total_localtax2;
+					$localtax1_rate = $object->lines[$i]->localtax1_tx;
+					$localtax2_rate = $object->lines[$i]->localtax2_tx;
+					$localtax1_type = $object->lines[$i]->localtax1_type;
+					$localtax2_type = $object->lines[$i]->localtax2_type;
 
-					if ($object->remise_percent) $tvaligne-=($tvaligne*$object->remise_percent)/100;
-					if ($object->remise_percent) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100;
-					if ($object->remise_percent) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100;
+					if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100;
+					if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100;
+					if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100;
 
-					$vatrate=(string) $object->lines[$i]->tva_tx;
+					$vatrate = (string) $object->lines[$i]->tva_tx;
 
 					// Retrieve type from database for backward compatibility with old records
-					if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined
-					&& (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax
+					if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined
+					&& (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax
 					{
-						$localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc);
+						$localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc);
 						$localtax1_type = $localtaxtmp_array[0];
 						$localtax2_type = $localtaxtmp_array[2];
 					}
 
 				    // retrieve global local tax
 					if ($localtax1_type && $localtax1ligne != 0)
-						$this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne;
+						$this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne;
 					if ($localtax2_type && $localtax2ligne != 0)
-						$this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne;
+						$this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne;
 
-					if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*';
-					if (! isset($this->tva[$vatrate]))				$this->tva[$vatrate]=0;
+					if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*';
+					if (!isset($this->tva[$vatrate]))				$this->tva[$vatrate] = 0;
 					$this->tva[$vatrate] += $tvaligne;
 
-					if ($posYAfterImage > $posYAfterDescription) $nexY=$posYAfterImage;
+					if ($posYAfterImage > $posYAfterDescription) $nexY = $posYAfterImage;
 
 					// 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)
@@ -867,41 +867,41 @@ class pdf_cyan extends ModelePDFPropales
 							$product = new Product($this->db);
 							$product->fetch($line->fk_product);
 
-							if ($product->entity!=$conf->entity) {
-								$entity_product_file=$product->entity;
+							if ($product->entity != $conf->entity) {
+								$entity_product_file = $product->entity;
 							} else {
-								$entity_product_file=$conf->entity;
+								$entity_product_file = $conf->entity;
 							}
 
 							// If PDF is selected and file is not empty
 							if (count($filetomerge->lines) > 0) {
 								foreach ($filetomerge->lines as $linefile) {
-									if (! empty($linefile->id) && ! empty($linefile->file_name)) {
-										if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
+									if (!empty($linefile->id) && !empty($linefile->file_name)) {
+										if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
 										{
-											if (! empty($conf->product->enabled)) {
-												$filetomerge_dir = $conf->product->multidir_output[$entity_product_file] . '/' . get_exdir($product->id, 2, 0, 0, $product, 'product') . $product->id ."/photos";
-											} elseif (! empty($conf->service->enabled)) {
-												$filetomerge_dir = $conf->service->multidir_output[$entity_product_file] . '/' . get_exdir($product->id, 2, 0, 0, $product, 'product') . $product->id ."/photos";
+											if (!empty($conf->product->enabled)) {
+												$filetomerge_dir = $conf->product->multidir_output[$entity_product_file].'/'.get_exdir($product->id, 2, 0, 0, $product, 'product').$product->id."/photos";
+											} elseif (!empty($conf->service->enabled)) {
+												$filetomerge_dir = $conf->service->multidir_output[$entity_product_file].'/'.get_exdir($product->id, 2, 0, 0, $product, 'product').$product->id."/photos";
 											}
 										}
 										else
 										{
-											if (! empty($conf->product->enabled)) {
-												$filetomerge_dir = $conf->product->multidir_output[$entity_product_file] . '/' . get_exdir(0, 0, 0, 0, $product, 'product') . dol_sanitizeFileName($product->ref);
-											} elseif (! empty($conf->service->enabled)) {
-												$filetomerge_dir = $conf->service->multidir_output[$entity_product_file] . '/' . get_exdir(0, 0, 0, 0, $product, 'product') . dol_sanitizeFileName($product->ref);
+											if (!empty($conf->product->enabled)) {
+												$filetomerge_dir = $conf->product->multidir_output[$entity_product_file].'/'.get_exdir(0, 0, 0, 0, $product, 'product').dol_sanitizeFileName($product->ref);
+											} elseif (!empty($conf->service->enabled)) {
+												$filetomerge_dir = $conf->service->multidir_output[$entity_product_file].'/'.get_exdir(0, 0, 0, 0, $product, 'product').dol_sanitizeFileName($product->ref);
 											}
 										}
 
-										dol_syslog(get_class($this) . ':: upload_dir=' . $filetomerge_dir, LOG_DEBUG);
+										dol_syslog(get_class($this).':: upload_dir='.$filetomerge_dir, LOG_DEBUG);
 
-										$infile = $filetomerge_dir . '/' . $linefile->file_name;
+										$infile = $filetomerge_dir.'/'.$linefile->file_name;
 										if (file_exists($infile) && is_readable($infile)) {
 											$pagecount = $pdf->setSourceFile($infile);
-											for($i = 1; $i <= $pagecount; $i ++) {
+											for ($i = 1; $i <= $pagecount; $i++) {
 												$tplIdx = $pdf->importPage($i);
-												if ($tplIdx!==false) {
+												if ($tplIdx !== false) {
 													$s = $pdf->getTemplatesize($tplIdx);
 													$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
 													$pdf->useTemplate($tplIdx);
@@ -923,31 +923,31 @@ class pdf_cyan extends ModelePDFPropales
 
 				//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", "PROP_OUTPUTDIR");
+			$this->error = $langs->trans("ErrorConstantNotDefined", "PROP_OUTPUTDIR");
 			return 0;
 		}
 	}
@@ -1176,7 +1176,7 @@ class pdf_cyan extends ModelePDFPropales
 		$index = 0;
 
 		$outputlangsbis = null;
-		if (! empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
+		if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
 			$outputlangsbis = new Translate('', $conf);
 			$outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE);
 			$outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "propal"));
@@ -1209,29 +1209,29 @@ class pdf_cyan extends ModelePDFPropales
 				//Local tax 1 before VAT
 				//if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on')
 				//{
-				foreach($this->localtax1 as $localtax_type => $localtax_rate)
+				foreach ($this->localtax1 as $localtax_type => $localtax_rate)
 				{
-					if (in_array((string) $localtax_type, array('1','3','5'))) continue;
+					if (in_array((string) $localtax_type, array('1', '3', '5'))) continue;
 
-					foreach($localtax_rate as $tvakey => $tvaval)
+					foreach ($localtax_rate as $tvakey => $tvaval)
 					{
-						if ($tvakey!=0)    // On affiche pas taux 0
+						if ($tvakey != 0)    // On affiche pas taux 0
 						{
 							//$this->atleastoneratenotnull++;
 
 							$index++;
 							$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
 
-							$tvacompl='';
+							$tvacompl = '';
 							if (preg_match('/\*/', $tvakey))
 							{
-								$tvakey=str_replace('*', '', $tvakey);
+								$tvakey = str_replace('*', '', $tvakey);
 								$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 							}
 							$totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : '');
-							$totalvat.=' ';
-							$totalvat.=vatrate(abs($tvakey), 1).$tvacompl;
-							$pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1);
+							$totalvat .= ' ';
+							$totalvat .= vatrate(abs($tvakey), 1).$tvacompl;
+							$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 
 							$pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index);
 							$pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1);
@@ -1242,13 +1242,13 @@ class pdf_cyan extends ModelePDFPropales
 				//Local tax 2 before VAT
 				//if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on')
 				//{
-				foreach($this->localtax2 as $localtax_type => $localtax_rate)
+				foreach ($this->localtax2 as $localtax_type => $localtax_rate)
 				{
-					if (in_array((string) $localtax_type, array('1','3','5'))) continue;
+					if (in_array((string) $localtax_type, array('1', '3', '5'))) continue;
 
-					foreach($localtax_rate as $tvakey => $tvaval)
+					foreach ($localtax_rate as $tvakey => $tvaval)
 					{
-						if ($tvakey!=0)    // On affiche pas taux 0
+						if ($tvakey != 0)    // On affiche pas taux 0
 						{
 							//$this->atleastoneratenotnull++;
 
@@ -1257,16 +1257,16 @@ class pdf_cyan extends ModelePDFPropales
 							$index++;
 							$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
 
-							$tvacompl='';
+							$tvacompl = '';
 							if (preg_match('/\*/', $tvakey))
 							{
-								$tvakey=str_replace('*', '', $tvakey);
+								$tvakey = str_replace('*', '', $tvakey);
 								$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 							}
 							$totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : '');
-							$totalvat.=' ';
-							$totalvat.=vatrate(abs($tvakey), 1).$tvacompl;
-							$pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1);
+							$totalvat .= ' ';
+							$totalvat .= vatrate(abs($tvakey), 1).$tvacompl;
+							$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 
 							$pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index);
 							$pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1);
@@ -1291,7 +1291,7 @@ class pdf_cyan extends ModelePDFPropales
 							$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 						}
 						$totalvat = $outputlangs->transcountrynoentities("TotalVAT", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalVAT", $mysoc->country_code) : '');
-						$totalvat.=' ';
+						$totalvat .= ' ';
 						$totalvat .= vatrate($tvakey, 1).$tvacompl;
 						$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 
@@ -1303,11 +1303,11 @@ class pdf_cyan extends ModelePDFPropales
 				//Local tax 1 after VAT
 				//if (! empty($conf->global->FACTURE_LOCAL_TAX1_OPTION) && $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on')
 				//{
-				foreach($this->localtax1 as $localtax_type => $localtax_rate)
+				foreach ($this->localtax1 as $localtax_type => $localtax_rate)
 				{
-					if (in_array((string) $localtax_type, array('2','4','6'))) continue;
+					if (in_array((string) $localtax_type, array('2', '4', '6'))) continue;
 
-					foreach($localtax_rate as $tvakey => $tvaval)
+					foreach ($localtax_rate as $tvakey => $tvaval)
 					{
 						if ($tvakey != 0)    // On affiche pas taux 0
 						{
@@ -1316,17 +1316,17 @@ class pdf_cyan extends ModelePDFPropales
 							$index++;
 							$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
 
-							$tvacompl='';
+							$tvacompl = '';
 							if (preg_match('/\*/', $tvakey))
 							{
-								$tvakey=str_replace('*', '', $tvakey);
+								$tvakey = str_replace('*', '', $tvakey);
 								$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 							}
 							$totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT1", $mysoc->country_code) : '');
-							$totalvat.=' ';
+							$totalvat .= ' ';
 
-							$totalvat.=vatrate(abs($tvakey), 1).$tvacompl;
-							$pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1);
+							$totalvat .= vatrate(abs($tvakey), 1).$tvacompl;
+							$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 							$pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index);
 							$pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1);
 						}
@@ -1336,11 +1336,11 @@ class pdf_cyan extends ModelePDFPropales
 				//Local tax 2 after VAT
 				//if (! empty($conf->global->FACTURE_LOCAL_TAX2_OPTION) && $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on')
 				//{
-				foreach($this->localtax2 as $localtax_type => $localtax_rate)
+				foreach ($this->localtax2 as $localtax_type => $localtax_rate)
 				{
-					if (in_array((string) $localtax_type, array('2','4','6'))) continue;
+					if (in_array((string) $localtax_type, array('2', '4', '6'))) continue;
 
-					foreach($localtax_rate as $tvakey => $tvaval)
+					foreach ($localtax_rate as $tvakey => $tvaval)
 					{
 					    // retrieve global local tax
 						if ($tvakey != 0)    // On affiche pas taux 0
@@ -1350,17 +1350,17 @@ class pdf_cyan extends ModelePDFPropales
 							$index++;
 							$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
 
-							$tvacompl='';
+							$tvacompl = '';
 							if (preg_match('/\*/', $tvakey))
 							{
-								$tvakey=str_replace('*', '', $tvakey);
+								$tvakey = str_replace('*', '', $tvakey);
 								$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 							}
 							$totalvat = $outputlangs->transcountrynoentities("TotalLT2", $mysoc->country_code).(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("TotalLT2", $mysoc->country_code) : '');
-							$totalvat.= ' ';
+							$totalvat .= ' ';
 
-							$totalvat.=vatrate(abs($tvakey), 1).$tvacompl;
-							$pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1);
+							$totalvat .= vatrate(abs($tvakey), 1).$tvacompl;
+							$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 
 							$pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index);
 							$pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1);
@@ -1464,12 +1464,12 @@ class pdf_cyan extends ModelePDFPropales
 		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, $this->tabTitleHeight, '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, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
 			}
 		}
 
@@ -1477,12 +1477,12 @@ class pdf_cyan extends ModelePDFPropales
 		$pdf->SetFont('', '', $default_font_size - 1);
 
 		// 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
+		$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
 
 		$this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop);
 
-		if (empty($hidetop)){
-		    $pdf->line($this->marge_gauche, $tab_top+$this->tabTitleHeight, $this->page_largeur-$this->marge_droite, $tab_top+$this->tabTitleHeight);	// line takes a position y in 2nd parameter and 4th parameter
+		if (empty($hidetop)) {
+		    $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter
 		}
 	}
 
@@ -1516,8 +1516,8 @@ class pdf_cyan extends ModelePDFPropales
 		$pdf->SetTextColor(0, 0, 60);
 		$pdf->SetFont('', 'B', $default_font_size + 3);
 
-		$posy=$this->marge_haute;
-		$posx=$this->page_largeur-$this->marge_droite-100;
+		$posy = $this->marge_haute;
+		$posx = $this->page_largeur - $this->marge_droite - 100;
 
 		$pdf->SetXY($this->marge_gauche, $posy);
 
@@ -1527,7 +1527,7 @@ class pdf_cyan extends ModelePDFPropales
 			if ($this->emetteur->logo)
 			{
 				$logodir = $conf->mycompany->dir_output;
-				if (! empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity];
+				if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity];
 				if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO))
 				{
 					$logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small;
@@ -1537,8 +1537,8 @@ class pdf_cyan extends ModelePDFPropales
 				}
 				if (is_readable($logo))
 				{
-				    $height=pdf_getHeightForLogo($logo);
-				    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
+				    $height = pdf_getHeightForLogo($logo);
+				    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
 				}
 				else
 				{

+ 156 - 156
htdocs/core/modules/supplier_order/doc/pdf_cornas.modules.php

@@ -183,16 +183,16 @@ class pdf_cornas extends ModelePDFSuppliersOrders
     public function write_file($object, $outputlangs = '', $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
 	{
         // phpcs:enable
-		global $user,$langs,$conf,$hookmanager,$mysoc,$nblines;
+		global $user, $langs, $conf, $hookmanager, $mysoc, $nblines;
 
-		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 translation files required by the page
 		$outputlangs->loadLangs(array("main", "orders", "companies", "bills", "dict", "products"));
 
-		if (! empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
+		if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) {
 			global $outputlangsbis;
 			$outputlangsbis = new Translate('', $conf);
 			$outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE);
@@ -201,46 +201,46 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 
 		$nblines = count($object->lines);
 
-		$hidetop=0;
-		if(!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)){
-		    $hidetop=$conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE;
+		$hidetop = 0;
+		if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) {
+		    $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE;
 		}
 
 		// Loop on each lines to detect if there is at least one image to show
-		$realpatharray=array();
-		if (! empty($conf->global->MAIN_GENERATE_SUPPLIER_ORDER_WITH_PICTURE))
+		$realpatharray = array();
+		if (!empty($conf->global->MAIN_GENERATE_SUPPLIER_ORDER_WITH_PICTURE))
 		{
-			for ($i = 0 ; $i < $nblines ; $i++)
+			for ($i = 0; $i < $nblines; $i++)
 			{
 				if (empty($object->lines[$i]->fk_product)) continue;
 
 				$objphoto = new Product($this->db);
 				$objphoto->fetch($object->lines[$i]->fk_product);
 
-				if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
+				if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
 				{
-					$pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product') . $object->lines[$i]->fk_product ."/photos/";
+					$pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product').$object->lines[$i]->fk_product."/photos/";
 					$dir = $conf->product->dir_output.'/'.$pdir;
 				}
 				else
 				{
-					$pdir = get_exdir(0, 2, 0, 0, $objphoto, 'product') . dol_sanitizeFileName($objphoto->ref).'/';
+					$pdir = get_exdir(0, 2, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/';
 					$dir = $conf->product->dir_output.'/'.$pdir;
 				}
 
-				$realpath='';
+				$realpath = '';
 				foreach ($objphoto->liste_photos($dir, 1) as $key => $obj)
 				{
-					$filename=$obj['photo'];
+					$filename = $obj['photo'];
 					//if ($obj['photo_vignette']) $filename='thumbs/'.$obj['photo_vignette'];
 					$realpath = $dir.$filename;
 					break;
 				}
 
-				if ($realpath) $realpatharray[$i]=$realpath;
+				if ($realpath) $realpatharray[$i] = $realpath;
 			}
 		}
-		if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva;
+		if (count($realpatharray) == 0) $this->posxpicture = $this->posxtva;
 
 		if ($conf->fournisseur->commande->dir_output)
 		{
@@ -279,24 +279,24 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 			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
 
 				$nblines = count($object->lines);
 
-                $pdf=pdf_getInstance($this->format);
-                $default_font_size = pdf_getPDFFontSize($outputlangs);	// Must be after pdf_getInstance
-                $heightforinfotot = 50;	// 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 ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6;
+                $pdf = pdf_getInstance($this->format);
+                $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance
+                $heightforinfotot = 50; // 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 ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6;
                 $pdf->SetAutoPageBreak(1, 0);
 
                 if (class_exists('TCPDF'))
@@ -354,28 +354,28 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 						$tab_top -= 2;
 
 						$pdf->SetFont('', '', $default_font_size - 1);
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
+						$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
 						$nexY = $pdf->GetY();
-						$height_incoterms=$nexY-$tab_top;
+						$height_incoterms = $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_incoterms+1);
+						$pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1);
 
-						$tab_top = $nexY+6;
+						$tab_top = $nexY + 6;
 					}
 				}
 
 				// Affiche notes
-				$notetoshow=empty($object->note_public)?'':$object->note_public;
+				$notetoshow = empty($object->note_public) ? '' : $object->note_public;
 
 				$pagenb = $pdf->getPage();
 				if ($notetoshow)
 				{
-				    $tab_width = $this->page_largeur-$this->marge_gauche-$this->marge_droite;
+				    $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite;
 				    $pageposbeforenote = $pagenb;
 
-				    $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);
@@ -497,98 +497,98 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 				$this->prepareArrayColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref);
 
 				// Loop on each lines
-				$pageposbeforeprintlines=$pdf->getPage();
+				$pageposbeforeprintlines = $pdf->getPage();
 				$pagenb = $pageposbeforeprintlines;
-				for ($i = 0 ; $i < $nblines ; $i++)
+				for ($i = 0; $i < $nblines; $i++)
 				{
 					$curY = $nexY;
-					$pdf->SetFont('', '', $default_font_size - 1);   // Into loop to work with multipage
+					$pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage
 					$pdf->SetTextColor(0, 0, 0);
 
 					// Define size of image if we need it
-					$imglinesize=array();
-					if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
+					$imglinesize = array();
+					if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]);
 
 					$pdf->setTopMargin($tab_top_newpage);
-					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
-					$pageposbefore=$pdf->getPage();
+					$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
+					$pageposbefore = $pdf->getPage();
 
-					$showpricebeforepagebreak=1;
-					$posYAfterImage=0;
-					$posYAfterDescription=0;
+					$showpricebeforepagebreak = 1;
+					$posYAfterImage = 0;
+					$posYAfterDescription = 0;
 
 					// We start with Photo of product line
-					if (!empty($imglinesize['width']) && !empty($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot)))	// If photo too high, we moved completely on new page
+					if (!empty($imglinesize['width']) && !empty($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)))	// If photo too high, we moved completely on new page
 					{
 						$pdf->AddPage('', '', true);
-						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+						if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-						$pdf->setPage($pageposbefore+1);
+						$pdf->setPage($pageposbefore + 1);
 
 						$curY = $tab_top_newpage;
-						$showpricebeforepagebreak=0;
+						$showpricebeforepagebreak = 0;
 					}
 
 					if (!empty($imglinesize['width']) && !empty($imglinesize['height']))
 					{
-						$curX = $this->posxpicture-1;
-						$pdf->Image($realpatharray[$i], $curX + (($this->posxtva-$this->posxpicture-$imglinesize['width'])/2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300);	// Use 300 dpi
+						$curX = $this->posxpicture - 1;
+						$pdf->Image($realpatharray[$i], $curX + (($this->posxtva - $this->posxpicture - $imglinesize['width']) / 2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi
 						// $pdf->Image does not increase value return by getY, so we save it manually
-						$posYAfterImage=$curY+$imglinesize['height'];
+						$posYAfterImage = $curY + $imglinesize['height'];
 					}
 					// Description of product line
-					$curX = $this->posxdesc-1;
-					$showpricebeforepagebreak=1;
+					$curX = $this->posxdesc - 1;
+					$showpricebeforepagebreak = 1;
 
-					if($this->getColumnStatus('desc'))
+					if ($this->getColumnStatus('desc'))
 					{
 					    $pdf->startTransaction();
 					    pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc);
-					    $pageposafter=$pdf->getPage();
+					    $pageposafter = $pdf->getPage();
 					    if ($pageposafter > $pageposbefore)	// There is a pagebreak
 					    {
 					        $pdf->rollbackTransaction(true);
-					        $pageposafter=$pageposbefore;
+					        $pageposafter = $pageposbefore;
 					        //print $pageposafter.'-'.$pageposbefore;exit;
-					        $pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
+					        $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
 					        pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->getColumnContentWidth('desc'), 3, $this->getColumnContentXStart('desc'), $curY, $hideref, $hidedesc);
-					        $pageposafter=$pdf->getPage();
-					        $posyafter=$pdf->GetY();
-					        if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot)))	// There is no space left for total+free text
+					        $pageposafter = $pdf->getPage();
+					        $posyafter = $pdf->GetY();
+					        if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)))	// There is no space left for total+free text
 					        {
-					            if ($i == ($nblines-1))	// No more lines, and no space left to show total, so we create a new page
+					            if ($i == ($nblines - 1))	// No more lines, and no space left to show total, so we create a new page
 					            {
 					                $pdf->AddPage('', '', true);
-					                if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+					                if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 					                //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-					                $pdf->setPage($pageposafter+1);
+					                $pdf->setPage($pageposafter + 1);
 					            }
 					        }
 					        else
 					        {
 					            // We found a page break
-					            $showpricebeforepagebreak=0;
+					            $showpricebeforepagebreak = 0;
 					        }
 					    }
 					    else	// No pagebreak
 					    {
 					        $pdf->commitTransaction();
 					    }
-					    $posYAfterDescription=$pdf->GetY();
+					    $posYAfterDescription = $pdf->GetY();
 					}
 
 					$nexY = $pdf->GetY();
-                    $pageposafter=$pdf->getPage();
+                    $pageposafter = $pdf->getPage();
 					$pdf->setPage($pageposbefore);
 					$pdf->setTopMargin($this->marge_haute);
-					$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.
 
 					// We suppose that a too long description is moved completely on next page
 					if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
 						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
 					}
 
-					$pdf->SetFont('', '', $default_font_size - 1);   // On repositionne la police par defaut
+					$pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut
 
 					// VAT Rate
 					if ($this->getColumnStatus('vat'))
@@ -641,7 +641,7 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 					}
 
 
-					$parameters=array(
+					$parameters = array(
 					    'object' => $object,
 					    'i' => $i,
 					    'pdf' =>& $pdf,
@@ -650,58 +650,58 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 					    'outputlangs' => $outputlangs,
 					    'hidedetails' => $hidedetails
 					);
-					$reshook=$hookmanager->executeHooks('printPDFline', $parameters, $this);    // Note that $object may have been modified by hook
+					$reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook
 
 
 					// Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva
-					if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne=$object->lines[$i]->multicurrency_total_tva;
-					else $tvaligne=$object->lines[$i]->total_tva;
+					if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva;
+					else $tvaligne = $object->lines[$i]->total_tva;
 
-					$localtax1ligne=$object->lines[$i]->total_localtax1;
-					$localtax2ligne=$object->lines[$i]->total_localtax2;
-					$localtax1_rate=$object->lines[$i]->localtax1_tx;
-					$localtax2_rate=$object->lines[$i]->localtax2_tx;
-					$localtax1_type=$object->lines[$i]->localtax1_type;
-					$localtax2_type=$object->lines[$i]->localtax2_type;
+					$localtax1ligne = $object->lines[$i]->total_localtax1;
+					$localtax2ligne = $object->lines[$i]->total_localtax2;
+					$localtax1_rate = $object->lines[$i]->localtax1_tx;
+					$localtax2_rate = $object->lines[$i]->localtax2_tx;
+					$localtax1_type = $object->lines[$i]->localtax1_type;
+					$localtax2_type = $object->lines[$i]->localtax2_type;
 
-					if (! empty($object->remise_percent)) $tvaligne-=($tvaligne*$object->remise_percent)/100;
-					if (! empty($object->remise_percent)) $localtax1ligne-=($localtax1ligne*$object->remise_percent)/100;
-					if (! empty($object->remise_percent)) $localtax2ligne-=($localtax2ligne*$object->remise_percent)/100;
+					if (!empty($object->remise_percent)) $tvaligne -= ($tvaligne * $object->remise_percent) / 100;
+					if (!empty($object->remise_percent)) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100;
+					if (!empty($object->remise_percent)) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100;
 
-					$vatrate=(string) $object->lines[$i]->tva_tx;
+					$vatrate = (string) $object->lines[$i]->tva_tx;
 
 					// Retrieve type from database for backward compatibility with old records
-					if ((! isset($localtax1_type) || $localtax1_type=='' || ! isset($localtax2_type) || $localtax2_type=='') // if tax type not defined
-					&& (! empty($localtax1_rate) || ! empty($localtax2_rate))) // and there is local tax
+					if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined
+					&& (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax
 					{
-						$localtaxtmp_array=getLocalTaxesFromRate($vatrate, 0, $mysoc, $object->thirdparty);
+						$localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $mysoc, $object->thirdparty);
 						$localtax1_type = $localtaxtmp_array[0];
 						$localtax2_type = $localtaxtmp_array[2];
 					}
 
 				    // retrieve global local tax
 					if ($localtax1_type && $localtax1ligne != 0)
-						$this->localtax1[$localtax1_type][$localtax1_rate]+=$localtax1ligne;
+						$this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne;
 					if ($localtax2_type && $localtax2ligne != 0)
-						$this->localtax2[$localtax2_type][$localtax2_rate]+=$localtax2ligne;
+						$this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne;
 
-					if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate.='*';
-					if (! isset($this->tva[$vatrate])) 				$this->tva[$vatrate]=0;
+					if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*';
+					if (!isset($this->tva[$vatrate])) 				$this->tva[$vatrate] = 0;
 					$this->tva[$vatrate] += $tvaligne;
 
-					if ($posYAfterImage > $posYAfterDescription) $nexY=$posYAfterImage;
+					if ($posYAfterImage > $posYAfterDescription) $nexY = $posYAfterImage;
 
 					// 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)
@@ -774,31 +774,31 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 
 				// 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", "SUPPLIER_OUTPUTDIR");
+			$this->error = $langs->trans("ErrorConstantNotDefined", "SUPPLIER_OUTPUTDIR");
 			return 0;
 		}
 	}
@@ -858,11 +858,11 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 
 			$pdf->SetFont('', '', $default_font_size - 2);
 			$pdf->SetXY($posxval, $posy);
-			$lib_condition_paiement=$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code)!=('PaymentCondition'.$object->cond_reglement_code)?$outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code):$outputlangs->convToOutputCharset($object->cond_reglement);
-			$lib_condition_paiement=str_replace('\n', "\n", $lib_condition_paiement);
+			$lib_condition_paiement = $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) != ('PaymentCondition'.$object->cond_reglement_code) ? $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) : $outputlangs->convToOutputCharset($object->cond_reglement);
+			$lib_condition_paiement = str_replace('\n', "\n", $lib_condition_paiement);
 			$pdf->MultiCell(80, 4, $lib_condition_paiement, 0, 'L');
 
-	        $posy=$pdf->GetY()+3;
+	        $posy = $pdf->GetY() + 3;
 	    }
 
       	// Show payment mode
@@ -993,7 +993,7 @@ class pdf_cornas extends ModelePDFSuppliersOrders
     			//Local tax 1
 			foreach ($this->localtax1 as $localtax_type => $localtax_rate)
 			{
-				if (in_array((string) $localtax_type, array('2','4','6'))) continue;
+				if (in_array((string) $localtax_type, array('2', '4', '6'))) continue;
 
 				foreach ($localtax_rate as $tvakey => $tvaval)
 				{
@@ -1004,15 +1004,15 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 						$index++;
 						$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
 
-						$tvacompl='';
+						$tvacompl = '';
 						if (preg_match('/\*/', $tvakey))
 						{
-							$tvakey=str_replace('*', '', $tvakey);
+							$tvakey = str_replace('*', '', $tvakey);
 							$tvacompl = " (".$outputlangs->transnoentities("NonPercuRecuperable").")";
 						}
-						$totalvat =$outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' ';
-						$totalvat.=vatrate(abs($tvakey), 1).$tvacompl;
-						$pdf->MultiCell($col2x-$col1x, $tab2_hl, $totalvat, 0, 'L', 1);
+						$totalvat = $outputlangs->transcountrynoentities("TotalLT1", $mysoc->country_code).' ';
+						$totalvat .= vatrate(abs($tvakey), 1).$tvacompl;
+						$pdf->MultiCell($col2x - $col1x, $tab2_hl, $totalvat, 0, 'L', 1);
 
 						$pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index);
 						$pdf->MultiCell($largcol2, $tab2_hl, price($tvaval, 0, $outputlangs), 0, 'R', 1);
@@ -1133,12 +1133,12 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 		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, $this->tabTitleHeight, '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, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR));
 			}
 		}
 
@@ -1146,17 +1146,17 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 		$pdf->SetFont('', '', $default_font_size - 1);
 
 		// 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
+		$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
 
 		foreach ($this->cols as $colKey => $colDef)
 		{
-		    if(!$this->getColumnStatus($colKey)) continue;
+		    if (!$this->getColumnStatus($colKey)) continue;
 
 		    // get title label
-		    $colDef['title']['label'] = !empty($colDef['title']['label'])?$colDef['title']['label']:$outputlangs->transnoentities($colDef['title']['textkey']);
+		    $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']);
 
 		    // Add column separator
-		    if(!empty($colDef['border-left'])){
+		    if (!empty($colDef['border-left'])) {
 		        $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height);
 		    }
 
@@ -1164,13 +1164,13 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 		    {
 		        $pdf->SetXY($colDef['xStartPos'] + $colDef['title']['padding'][3], $tab_top + $colDef['title']['padding'][0]);
 
-		        $textWidth = $colDef['width'] - $colDef['title']['padding'][3] -$colDef['title']['padding'][1];
+		        $textWidth = $colDef['width'] - $colDef['title']['padding'][3] - $colDef['title']['padding'][1];
 		        $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']);
 		    }
 		}
 
-		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
+		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
 		}
 	}
 
@@ -1206,19 +1206,19 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 		$pdf->SetTextColor(0, 0, 60);
 		$pdf->SetFont('', 'B', $default_font_size + 3);
 
-		$posx=$this->page_largeur-$this->marge_droite-100;
-		$posy=$this->marge_haute;
+		$posx = $this->page_largeur - $this->marge_droite - 100;
+		$posy = $this->marge_haute;
 
 		$pdf->SetXY($this->marge_gauche, $posy);
 
 		// Logo
-		$logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
+		$logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
 		if ($this->emetteur->logo)
 		{
 			if (is_readable($logo))
 			{
-			    $height=pdf_getHeightForLogo($logo);
-			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
+			    $height = pdf_getHeightForLogo($logo);
+			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
 			}
 			else
 			{
@@ -1230,91 +1230,91 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 		}
 		else
 		{
-			$text=$this->emetteur->name;
+			$text = $this->emetteur->name;
 			$pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
 		}
 
 		$pdf->SetFont('', 'B', $default_font_size + 3);
 		$pdf->SetXY($posx, $posy);
 		$pdf->SetTextColor(0, 0, 60);
-		$title=$outputlangs->transnoentities("SupplierOrder")." ".$outputlangs->convToOutputCharset($object->ref);
+		$title = $outputlangs->transnoentities("SupplierOrder")." ".$outputlangs->convToOutputCharset($object->ref);
 		$pdf->MultiCell(100, 3, $title, '', 'R');
-		$posy+=1;
+		$posy += 1;
 
 		if ($object->ref_supplier)
 		{
-			$posy+=4;
+			$posy += 4;
 			$pdf->SetFont('', 'B', $default_font_size);
 			$pdf->SetXY($posx, $posy);
 			$pdf->SetTextColor(0, 0, 60);
-			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefSupplier")." : " . $outputlangs->convToOutputCharset($object->ref_supplier), '', 'R');
-			$posy+=1;
+			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefSupplier")." : ".$outputlangs->convToOutputCharset($object->ref_supplier), '', 'R');
+			$posy += 1;
 		}
 
-		$pdf->SetFont('', '', $default_font_size -1);
+		$pdf->SetFont('', '', $default_font_size - 1);
 
-		if (! empty($conf->global->PDF_SHOW_PROJECT))
+		if (!empty($conf->global->PDF_SHOW_PROJECT))
 		{
 			$object->fetch_projet();
-			if (! empty($object->project->ref))
+			if (!empty($object->project->ref))
 			{
-				$posy+=4;
+				$posy += 4;
 				$pdf->SetXY($posx, $posy);
 				$langs->load("projects");
 				$pdf->SetTextColor(0, 0, 60);
-				$pdf->MultiCell(100, 3, $outputlangs->transnoentities("Project")." : " . (empty($object->project->ref)?'':$object->projet->ref), '', 'R');
+				$pdf->MultiCell(100, 3, $outputlangs->transnoentities("Project")." : ".(empty($object->project->ref) ? '' : $object->projet->ref), '', 'R');
 			}
 		}
 
-		if (! empty($object->date_commande))
+		if (!empty($object->date_commande))
 		{
-			$posy+=5;
+			$posy += 5;
 			$pdf->SetXY($posx, $posy);
 			$pdf->SetTextColor(0, 0, 60);
-			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : " . dol_print_date($object->date_commande, "day", false, $outputlangs, true), '', 'R');
+			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($object->date_commande, "day", false, $outputlangs, true), '', 'R');
 		}
 		else
 		{
-			$posy+=5;
+			$posy += 5;
 			$pdf->SetXY($posx, $posy);
 			$pdf->SetTextColor(255, 0, 0);
 			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("OrderToProcess"), '', 'R');
 		}
 
 		$pdf->SetTextColor(0, 0, 60);
-		$usehourmin='day';
-		if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin='dayhour';
-		if (! empty($object->date_livraison))
+		$usehourmin = 'day';
+		if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 'dayhour';
+		if (!empty($object->date_livraison))
 		{
-			$posy+=4;
-			$pdf->SetXY($posx-90, $posy);
-			$pdf->MultiCell(190, 3, $outputlangs->transnoentities("DateDeliveryPlanned")." : " . dol_print_date($object->date_livraison, $usehourmin, false, $outputlangs, true), '', 'R');
+			$posy += 4;
+			$pdf->SetXY($posx - 90, $posy);
+			$pdf->MultiCell(190, 3, $outputlangs->transnoentities("DateDeliveryPlanned")." : ".dol_print_date($object->date_livraison, $usehourmin, false, $outputlangs, true), '', 'R');
 		}
 
 		if ($object->thirdparty->code_fournisseur)
 		{
-			$posy+=4;
+			$posy += 4;
 			$pdf->SetXY($posx, $posy);
 			$pdf->SetTextColor(0, 0, 60);
-			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("SupplierCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_fournisseur), '', 'R');
+			$pdf->MultiCell(100, 3, $outputlangs->transnoentities("SupplierCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_fournisseur), '', 'R');
 		}
 
 		// Get contact
 		if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP))
 		{
-    		$arrayidcontact=$object->getIdContact('internal', 'SALESREPFOLL');
+    		$arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL');
     		if (count($arrayidcontact) > 0)
     		{
-    		    $usertmp=new User($this->db);
+    		    $usertmp = new User($this->db);
     		    $usertmp->fetch($arrayidcontact[0]);
-                $posy+=4;
+                $posy += 4;
                 $pdf->SetXY($posx, $posy);
     		    $pdf->SetTextColor(0, 0, 60);
     		    $pdf->MultiCell(100, 3, $langs->trans("BuyerName")." : ".$usertmp->getFullName($langs), '', 'R');
     		}
 		}
 
-		$posy+=1;
+		$posy += 1;
 		$pdf->SetTextColor(0, 0, 60);
 
 		$top_shift = 0;
@@ -1666,10 +1666,10 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 	    uasort($this->cols, array($this, 'columnSort'));
 
 	    // Positionning
-	    $curX = $this->page_largeur-$this->marge_droite; // start from right
+	    $curX = $this->page_largeur - $this->marge_droite; // start from right
 
 	    // Array width
-	    $arrayWidth = $this->page_largeur-$this->marge_droite-$this->marge_gauche;
+	    $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche;
 
 	    // Count flexible column
 	    $totalDefinedColWidth = 0;
@@ -1818,16 +1818,16 @@ class pdf_cornas extends ModelePDFSuppliersOrders
 	{
 	    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->MultiCell($this->getColumnContentWidth($colKey), 2, $columnText, '', $colDef['content']['align']);

Файловите разлики са ограничени, защото са твърде много
+ 236 - 236
htdocs/core/modules/supplier_order/doc/pdf_muscadet.modules.php


+ 128 - 128
htdocs/core/modules/supplier_payment/doc/pdf_standard.modules.php

@@ -130,47 +130,47 @@ class pdf_standard extends ModelePDFSuppliersPayments
 
 		// 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_multilang = 1;               // Dispo en plusieurs langues
+		$this->option_logo = 1; // Affiche logo
+		$this->option_multilang = 1; // Dispo en plusieurs langues
 
         // Define column position
-		$this->posxdate=$this->marge_gauche+1;
-		$this->posxreffacturefourn=30;
-		$this->posxreffacture=65;
-		$this->posxtype=100;
-		$this->posxtotalht=80;
-		$this->posxtva=90;
-		$this->posxtotalttc=180;
+		$this->posxdate = $this->marge_gauche + 1;
+		$this->posxreffacturefourn = 30;
+		$this->posxreffacture = 65;
+		$this->posxtype = 100;
+		$this->posxtotalht = 80;
+		$this->posxtva = 90;
+		$this->posxtotalttc = 180;
 
 		//if (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT)) $this->posxtva=$this->posxup;
 		if ($this->page_largeur < 210) // To work with US executive format
 		{
-			$this->posxreffacturefourn-=20;
-			$this->posxreffacture-=20;
-			$this->posxtype-=20;
-			$this->posxtotalht-=20;
-			$this->posxtva-=20;
-			$this->posxtotalttc-=20;
+			$this->posxreffacturefourn -= 20;
+			$this->posxreffacture -= 20;
+			$this->posxtype -= 20;
+			$this->posxtotalht -= 20;
+			$this->posxtva -= 20;
+			$this->posxtotalttc -= 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;
 
 		// 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
 	}
 
 
@@ -191,9 +191,9 @@ class pdf_standard extends ModelePDFSuppliersPayments
         // phpcs:enable
 		global $user, $langs, $conf, $mysoc, $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 translation files required by the page
 		$outputlangs->loadLangs(array("main", "suppliers", "companies", "bills", "dict", "products"));
@@ -211,12 +211,12 @@ class pdf_standard extends ModelePDFSuppliersPayments
 			$sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf,'.MAIN_DB_PREFIX.'facture_fourn as f,'.MAIN_DB_PREFIX.'societe as s';
 			$sql .= ' WHERE pf.fk_facturefourn = f.rowid AND f.fk_soc = s.rowid';
 			$sql .= ' AND pf.fk_paiementfourn = '.$object->id;
-			$resql=$this->db->query($sql);
+			$resql = $this->db->query($sql);
 			if ($resql)
 			{
 				if ($this->db->num_rows($resql) > 0)
 				{
-					while($objp = $this->db->fetch_object($resql)) {
+					while ($objp = $this->db->fetch_object($resql)) {
 						$objp->type = $outputlangs->trans('SupplierInvoice');
 						$object->lines[] = $objp;
 					}
@@ -229,22 +229,22 @@ class pdf_standard extends ModelePDFSuppliersPayments
 			if ($object->specimen)
 			{
 				$dir = $conf->fournisseur->payment->dir_output;
-				$file = $dir . "/SPECIMEN.pdf";
+				$file = $dir."/SPECIMEN.pdf";
 			}
 			else
 			{
 				$objectref = dol_sanitizeFileName($object->ref);
 				$objectrefsupplier = dol_sanitizeFileName($object->ref_supplier);
                 $dir = $conf->fournisseur->payment->dir_output.'/'.$objectref;
-				$file = $dir . "/" . $objectref . ".pdf";
-				if (! empty($conf->global->SUPPLIER_REF_IN_NAME)) $file = $dir . "/" . $objectref . ($objectrefsupplier?"_".$objectrefsupplier:"").".pdf";
+				$file = $dir."/".$objectref.".pdf";
+				if (!empty($conf->global->SUPPLIER_REF_IN_NAME)) $file = $dir."/".$objectref.($objectrefsupplier ? "_".$objectrefsupplier : "").".pdf";
 			}
 
-			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 0;
 				}
 			}
@@ -252,24 +252,24 @@ class pdf_standard extends ModelePDFSuppliersPayments
 			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
 
 				$nblines = count($object->lines);
 
-                $pdf=pdf_getInstance($this->format);
-                $default_font_size = pdf_getPDFFontSize($outputlangs);	// Must be after pdf_getInstance
-                $heightforinfotot = 50;	// 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 ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6;
+                $pdf = pdf_getInstance($this->format);
+                $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance
+                $heightforinfotot = 50; // 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 ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6;
                 $pdf->SetAutoPageBreak(1, 0);
 
                 if (class_exists('TCPDF'))
@@ -279,14 +279,14 @@ class pdf_standard extends ModelePDFSuppliersPayments
                 }
                 $pdf->SetFont(pdf_getPDFFont($outputlangs));
                 // Set path to the background PDF File
-                if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
+                if (!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));
@@ -294,76 +294,76 @@ class pdf_standard extends ModelePDFSuppliersPayments
 				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
 				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
 				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Order")." ".$outputlangs->convToOutputCharset($object->thirdparty->name));
-				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
+				if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
 
-				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
+				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right
 
 
                 // New page
 				$pdf->AddPage();
-				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+				if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 				$pagenb++;
 				$this->_pagehead($pdf, $object, 1, $outputlangs);
 				$pdf->SetFont('', '', $default_font_size - 1);
-				$pdf->MultiCell(0, 3, '');		// Set interline to 3
+				$pdf->MultiCell(0, 3, ''); // Set interline to 3
 				$pdf->SetTextColor(0, 0, 0);
 
 				$tab_top = 90;
-				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42:10);
+				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10);
 				$tab_height = 130;
 				$tab_height_newpage = 150;
 
 				// Incoterm
 				$height_incoterms = 0;
 
-				$height_note=0;
+				$height_note = 0;
 
 				$iniY = $tab_top + 7;
 				$curY = $tab_top + 7;
 				$nexY = $tab_top + 7;
 
 				// Loop on each lines
-				for ($i = 0 ; $i < $nblines ; $i++)
+				for ($i = 0; $i < $nblines; $i++)
 				{
 					$curY = $nexY;
-					$pdf->SetFont('', '', $default_font_size - 1);   // Into loop to work with multipage
+					$pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage
 					$pdf->SetTextColor(0, 0, 0);
 
 					$pdf->setTopMargin($tab_top_newpage);
-					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
-					$pageposbefore=$pdf->getPage();
+					$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
+					$pageposbefore = $pdf->getPage();
 
 					// Description of product line
-					$curX = $this->posxdate-1;
-					$showpricebeforepagebreak=1;
+					$curX = $this->posxdate - 1;
+					$showpricebeforepagebreak = 1;
 
 					$pdf->startTransaction();
 					//pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxtva-$curX,3,$curX,$curY,$hideref,$hidedesc,1);
-					$pdf->writeHTMLCell($this->posxtva-$curX, 4, $curX, $curY, $object->lines[$i]->datef, 0, 1, false, true, 'J', true);
-					$pageposafter=$pdf->getPage();
+					$pdf->writeHTMLCell($this->posxtva - $curX, 4, $curX, $curY, $object->lines[$i]->datef, 0, 1, false, true, 'J', true);
+					$pageposafter = $pdf->getPage();
 					if ($pageposafter > $pageposbefore)	// There is a pagebreak
 					{
 						$pdf->rollbackTransaction(true);
-						$pageposafter=$pageposbefore;
+						$pageposafter = $pageposbefore;
 						//print $pageposafter.'-'.$pageposbefore;exit;
-						$pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
+						$pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
 						//pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxtva-$curX,4,$curX,$curY,$hideref,$hidedesc,1);
-						$pdf->writeHTMLCell($this->posxtva-$curX, 4, $curX, $curY, $object->lines[$i]->datef, 0, 1, false, true, 'J', true);
-						$posyafter=$pdf->GetY();
-						if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot)))	// There is no space left for total+free text
+						$pdf->writeHTMLCell($this->posxtva - $curX, 4, $curX, $curY, $object->lines[$i]->datef, 0, 1, false, true, 'J', true);
+						$posyafter = $pdf->GetY();
+						if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)))	// There is no space left for total+free text
 						{
-							if ($i == ($nblines-1))	// No more lines, and no space left to show total, so we create a new page
+							if ($i == ($nblines - 1))	// No more lines, and no space left to show total, so we create a new page
 							{
 								$pdf->AddPage('', '', true);
-								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
+								if (!empty($tplidx)) $pdf->useTemplate($tplidx);
 								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
-								$pdf->setPage($pageposafter+1);
+								$pdf->setPage($pageposafter + 1);
 							}
 						}
 						else
 						{
 							// We found a page break
-							$showpricebeforepagebreak=0;
+							$showpricebeforepagebreak = 0;
 						}
 					}
 					else	// No pagebreak
@@ -372,54 +372,54 @@ class pdf_standard extends ModelePDFSuppliersPayments
 					}
 
 					$nexY = $pdf->GetY();
-                    $pageposafter=$pdf->getPage();
+                    $pageposafter = $pdf->getPage();
 					$pdf->setPage($pageposbefore);
 					$pdf->setTopMargin($this->marge_haute);
-					$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.
 
 					// We suppose that a too long description is moved completely on next page
 					if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
 						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
 					}
 
-					$pdf->SetFont('', '', $default_font_size - 1);   // On repositionne la police par defaut
+					$pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut
 
 					// ref fourn
 					$pdf->SetXY($this->posxreffacturefourn, $curY);
-					$pdf->MultiCell($this->posxreffacturefourn-$this->posxup-0.8, 3, $object->lines[$i]->ref_supplier, 0, 'L', 0);
+					$pdf->MultiCell($this->posxreffacturefourn - $this->posxup - 0.8, 3, $object->lines[$i]->ref_supplier, 0, 'L', 0);
 
 					// ref facture fourn
 					$pdf->SetXY($this->posxreffacture, $curY);
-					$pdf->MultiCell($this->posxreffacture-$this->posxup-0.8, 3, $object->lines[$i]->ref, 0, 'L', 0);
+					$pdf->MultiCell($this->posxreffacture - $this->posxup - 0.8, 3, $object->lines[$i]->ref, 0, 'L', 0);
 
 					// type
 					$pdf->SetXY($this->posxtype, $curY);
-					$pdf->MultiCell($this->posxtype-$this->posxup-0.8, 3, $object->lines[$i]->type, 0, 'L', 0);
+					$pdf->MultiCell($this->posxtype - $this->posxup - 0.8, 3, $object->lines[$i]->type, 0, 'L', 0);
 
 					// Total ht
 					$pdf->SetXY($this->posxtotalht, $curY);
-					$pdf->MultiCell($this->posxtotalht-$this->posxup-0.8, 3, price($object->lines[$i]->total_ht), 0, 'R', 0);
+					$pdf->MultiCell($this->posxtotalht - $this->posxup - 0.8, 3, price($object->lines[$i]->total_ht), 0, 'R', 0);
 
 					// Total tva
 					$pdf->SetXY($this->posxtva, $curY);
-					$pdf->MultiCell($this->posxtva-$this->posxup-0.8, 3, price($object->lines[$i]->total_tva), 0, 'R', 0);
+					$pdf->MultiCell($this->posxtva - $this->posxup - 0.8, 3, price($object->lines[$i]->total_tva), 0, 'R', 0);
 
 					// Total TTC line
                     $pdf->SetXY($this->posxtotalttc, $curY);
-                    $pdf->MultiCell($this->page_largeur-$this->marge_droite-$this->posxtotalttc, 3, price($object->lines[$i]->total_ttc), 0, 'R', 0);
+                    $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxtotalttc, 3, price($object->lines[$i]->total_ttc), 0, 'R', 0);
 
 
 					// 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)
@@ -436,10 +436,10 @@ class pdf_standard extends ModelePDFSuppliersPayments
 						$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)
 						{
@@ -452,7 +452,7 @@ class pdf_standard extends ModelePDFSuppliersPayments
 						$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);
 					}
@@ -462,16 +462,16 @@ class pdf_standard extends ModelePDFSuppliersPayments
 				if ($pagenb == 1)
 				{
 					$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
-					$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);
-					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
+					$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
 				}
 
 				// Affiche zone cheèque
-				$posy=$this->_tableau_cheque($pdf, $object, $bottomlasttab, $outputlangs);
+				$posy = $this->_tableau_cheque($pdf, $object, $bottomlasttab, $outputlangs);
 
 				// Affiche zone totaux
 				//$posy=$this->_tableau_tot($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs);
@@ -486,31 +486,31 @@ class pdf_standard extends ModelePDFSuppliersPayments
 
 				// 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", "SUPPLIER_OUTPUTDIR");
+			$this->error = $langs->trans("ErrorConstantNotDefined", "SUPPLIER_OUTPUTDIR");
 			return 0;
 		}
 	}
@@ -529,7 +529,7 @@ class pdf_standard extends ModelePDFSuppliersPayments
 	protected function _tableau_cheque(&$pdf, $object, $posy, $outputlangs)
 	{
         // phpcs:enable
-		global $conf,$mysoc;
+		global $conf, $mysoc;
 
         $default_font_size = pdf_getPDFFontSize($outputlangs);
 
@@ -561,7 +561,7 @@ class pdf_standard extends ModelePDFSuppliersPayments
 		$pdf->MultiCell(150, 4, $object->thirdparty->nom, 0, 'L', 1);
 
 		$pdf->SetXY($this->page_largeur - $this->marge_droite - 30, $posy);
-		$pdf->MultiCell(35, 4, str_pad(price($object->montant). ' '.$currency, 18, '*', STR_PAD_LEFT), 0, 'R', 1);
+		$pdf->MultiCell(35, 4, str_pad(price($object->montant).' '.$currency, 18, '*', STR_PAD_LEFT), 0, 'R', 1);
 		$posy += 10;
 
 
@@ -591,11 +591,11 @@ class pdf_standard extends ModelePDFSuppliersPayments
 	 */
 	protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0, $currency = '')
 	{
-		global $conf,$mysoc;
+		global $conf, $mysoc;
 
 		// 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);
@@ -605,7 +605,7 @@ class pdf_standard extends ModelePDFSuppliersPayments
 		$pdf->SetFont('', '', $default_font_size - 2);
 
 		$titre = strtoupper($mysoc->town).', le '.date("d").' '.$outputlangs->transnoentitiesnoconv(date("F")).' '.date("Y");
-		$pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3) - 60, $tab_top-6);
+		$pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3) - 60, $tab_top - 6);
 		$pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre);
 
 		$titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency));
@@ -645,19 +645,19 @@ class pdf_standard extends ModelePDFSuppliersPayments
 		$pdf->SetTextColor(0, 0, 60);
 		$pdf->SetFont('', 'B', $default_font_size + 3);
 
-		$posy=$this->marge_haute;
-		$posx=$this->page_largeur-$this->marge_droite-100;
+		$posy = $this->marge_haute;
+		$posx = $this->page_largeur - $this->marge_droite - 100;
 
 		$pdf->SetXY($this->marge_gauche, $posy);
 
 		// Logo
-		$logo=$conf->mycompany->dir_output.'/logos/'.$mysoc->logo;
+		$logo = $conf->mycompany->dir_output.'/logos/'.$mysoc->logo;
 		if ($mysoc->logo)
 		{
 			if (is_readable($logo))
 			{
-			    $height=pdf_getHeightForLogo($logo);
-			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
+			    $height = pdf_getHeightForLogo($logo);
+			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
 			}
 			else
 			{
@@ -669,7 +669,7 @@ class pdf_standard extends ModelePDFSuppliersPayments
 		}
 		else
 		{
-			$text=$this->emetteur->name;
+			$text = $this->emetteur->name;
 			$pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
 		}
         /*
@@ -739,15 +739,15 @@ class pdf_standard extends ModelePDFSuppliersPayments
 			$carac_emetteur = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty);
 
 			// Show payer
-			$posy=42;
-			$posx=$this->marge_gauche;
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80;
-			$hautcadre=40;
+			$posy = 42;
+			$posx = $this->marge_gauche;
+			if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80;
+			$hautcadre = 40;
 
 			// Show sender frame
 			$pdf->SetTextColor(0, 0, 0);
 			$pdf->SetFont('', '', $default_font_size - 2);
-			$pdf->SetXY($posx, $posy-5);
+			$pdf->SetXY($posx, $posy - 5);
 			$pdf->MultiCell(66, 5, $outputlangs->transnoentities("PayedBy").":", 0, 'L');
 			$pdf->SetXY($posx, $posy);
 			$pdf->SetFillColor(230, 230, 230);
@@ -755,39 +755,39 @@ class pdf_standard extends ModelePDFSuppliersPayments
 			$pdf->SetTextColor(0, 0, 60);
 
 			// Show sender name
-			$pdf->SetXY($posx+2, $posy+3);
+			$pdf->SetXY($posx + 2, $posy + 3);
 			$pdf->SetFont('', 'B', $default_font_size);
 			$pdf->MultiCell(80, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
-			$posy=$pdf->getY();
+			$posy = $pdf->getY();
 
 			// Show sender information
-			$pdf->SetXY($posx+2, $posy);
+			$pdf->SetXY($posx + 2, $posy);
 			$pdf->SetFont('', '', $default_font_size - 1);
 			$pdf->MultiCell(80, 4, $carac_emetteur, 0, 'L');
 
 			// Payed
 			$thirdparty = $object->thirdparty;
 
-			$carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs);
+			$carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs);
 
-			$carac_client=pdf_build_address($outputlangs, $this->emetteur, $mysoc, ((!empty($object->contact))?$object->contact:null), $usecontact, 'target', $object);
+			$carac_client = pdf_build_address($outputlangs, $this->emetteur, $mysoc, ((!empty($object->contact)) ? $object->contact : null), $usecontact, 'target', $object);
 
 			// Show recipient
-			$widthrecbox=90;
-			if ($this->page_largeur < 210) $widthrecbox=84;	// To work with US executive format
-			$posy=42;
-			$posx=$this->page_largeur-$this->marge_droite-$widthrecbox;
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;
+			$widthrecbox = 90;
+			if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format
+			$posy = 42;
+			$posx = $this->page_largeur - $this->marge_droite - $widthrecbox;
+			if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche;
 
 			// Show recipient frame
 			$pdf->SetTextColor(0, 0, 0);
 			$pdf->SetFont('', '', $default_font_size - 2);
-			$pdf->SetXY($posx+2, $posy-5);
+			$pdf->SetXY($posx + 2, $posy - 5);
 			$pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("PayedTo").":", 0, 'L');
 			$pdf->Rect($posx, $posy, $widthrecbox, $hautcadre);
 
 			// Show recipient name
-			$pdf->SetXY($posx+2, $posy+3);
+			$pdf->SetXY($posx + 2, $posy + 3);
 			$pdf->SetFont('', 'B', $default_font_size);
 			$pdf->MultiCell($widthrecbox, 4, $carac_client_name, 0, 'L');
 
@@ -795,7 +795,7 @@ class pdf_standard extends ModelePDFSuppliersPayments
 
 			// Show recipient information
 			$pdf->SetFont('', '', $default_font_size - 1);
-			$pdf->SetXY($posx+2, $posy);
+			$pdf->SetXY($posx + 2, $posy);
 			$pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L');
 		}
 	}
@@ -813,7 +813,7 @@ class pdf_standard extends ModelePDFSuppliersPayments
 	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, 'SUPPLIER_INVOICE_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext);
 	}
 }

Файловите разлики са ограничени, защото са твърде много
+ 234 - 234
htdocs/core/modules/supplier_proposal/doc/pdf_aurore.modules.php


+ 15 - 15
htdocs/core/tpl/massactions_pre.tpl.php

@@ -45,7 +45,7 @@ if ($massaction == 'presend')
 	$listofselectedthirdparties = array();
 	$listofselectedref = array();
 
-	if (! GETPOST('cancel', 'alpha'))
+	if (!GETPOST('cancel', 'alpha'))
 	{
 		foreach ($arrayofselected as $toselectid)
 		{
@@ -66,25 +66,25 @@ if ($massaction == 'presend')
 
 	print '<input type="hidden" name="massaction" value="confirm_presend">';
 
-	include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
+	include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
 	$formmail = new FormMail($db);
 
 	dol_fiche_head(null, '', '');
 
 	// Cree l'objet formulaire mail
-	include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
+	include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
 	$formmail = new FormMail($db);
 	$formmail->withform = -1;
-	$formmail->fromtype = (GETPOST('fromtype') ? GETPOST('fromtype') : (! empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE) ? $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE : 'user'));
+	$formmail->fromtype = (GETPOST('fromtype') ? GETPOST('fromtype') : (!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE) ? $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE : 'user'));
 
 	if ($formmail->fromtype === 'user')
 	{
 		$formmail->fromid = $user->id;
 	}
 	$formmail->trackid = $trackid;
-	if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set
+	if (!empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set
 	{
-		include DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
+		include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 		$formmail->frommail = dolAddEmailTrackId($formmail->frommail, $trackid);
 	}
 	$formmail->withfrom = 1;
@@ -112,10 +112,10 @@ if ($massaction == 'presend')
 		$formmail->withtoreadonly = 1;
 	}
 
-	$formmail->withoptiononeemailperrecipient = ((count($listofselectedref) == 1 && count(reset($listofselectedref)) == 1) || empty($liste)) ? 0 : ((GETPOST('oneemailperrecipient')=='on')?1:-1);
+	$formmail->withoptiononeemailperrecipient = ((count($listofselectedref) == 1 && count(reset($listofselectedref)) == 1) || empty($liste)) ? 0 : ((GETPOST('oneemailperrecipient') == 'on') ? 1 : -1);
 
-	$formmail->withto = empty($liste)?(GETPOST('sendto', 'alpha')?GETPOST('sendto', 'alpha'):array()):$liste;
-	$formmail->withtofree = empty($liste)?1:0;
+	$formmail->withto = empty($liste) ? (GETPOST('sendto', 'alpha') ?GETPOST('sendto', 'alpha') : array()) : $liste;
+	$formmail->withtofree = empty($liste) ? 1 : 0;
 	$formmail->withtocc = 1;
 	$formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC;
 	$formmail->withtopic = $langs->transnoentities($topicmail, '__REF__', '__REFCLIENT__');
@@ -134,8 +134,8 @@ if ($massaction == 'presend')
 	$substitutionarray = getCommonSubstitutionArray($langs, 0, null, $object);
 
 	$substitutionarray['__EMAIL__'] = $sendto;
-	$substitutionarray['__CHECK_READ__'] = (is_object($object) && is_object($object->thirdparty)) ? '<img src="' . DOL_MAIN_URL_ROOT . '/public/emailing/mailing-read.php?tag=' . $object->thirdparty->tag . '&securitykey=' . urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY) . '" width="1" height="1" style="width:1px;height:1px" border="0"/>' : '';
-	$substitutionarray['__PERSONALIZED__'] = '';	// deprecated
+	$substitutionarray['__CHECK_READ__'] = (is_object($object) && is_object($object->thirdparty)) ? '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$object->thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>' : '';
+	$substitutionarray['__PERSONALIZED__'] = ''; // deprecated
 	$substitutionarray['__CONTACTCIVNAME__'] = '';
 
 	$parameters = array(
@@ -152,11 +152,11 @@ if ($massaction == 'presend')
 	$formmail->param['models_id'] = GETPOST('modelmailselected', 'int');
 	$formmail->param['id'] = join(',', $arrayofselected);
 	// $formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id;
-	if (! empty($conf->global->MAILING_LIMIT_SENDBYWEB) && count($listofselectedthirdparties) > $conf->global->MAILING_LIMIT_SENDBYWEB)
+	if (!empty($conf->global->MAILING_LIMIT_SENDBYWEB) && count($listofselectedthirdparties) > $conf->global->MAILING_LIMIT_SENDBYWEB)
 	{
 		$langs->load("errors");
-		print img_warning() . ' ' . $langs->trans('WarningNumberOfRecipientIsRestrictedInMassAction', $conf->global->MAILING_LIMIT_SENDBYWEB);
-		print ' - <a href="javascript: window.history.go(-1)">' . $langs->trans("GoBack") . '</a>';
+		print img_warning().' '.$langs->trans('WarningNumberOfRecipientIsRestrictedInMassAction', $conf->global->MAILING_LIMIT_SENDBYWEB);
+		print ' - <a href="javascript: window.history.go(-1)">'.$langs->trans("GoBack").'</a>';
 		$arrayofmassactions = array();
 	}
 	else
@@ -172,7 +172,7 @@ $parameters = array(
 	'uploaddir' => $uploaddir
 );
 
-$reshook=$hookmanager->executeHooks('doPreMassActions', $parameters, $object, $action);
+$reshook = $hookmanager->executeHooks('doPreMassActions', $parameters, $object, $action);
 if ($reshook < 0) {
     setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
 } else {

+ 1 - 1
htdocs/cron/class/cronjob.class.php

@@ -1308,7 +1308,7 @@ class Cronjob extends CommonObject
     public function LibStatut($status, $mode = 0, $processing = 0, $lastresult = 0)
 	{
 		// phpcs:enable
-		$this->labelStatus = array();		// Force reset o array because label depends on other fields
+		$this->labelStatus = array(); // Force reset o array because label depends on other fields
 		$this->labelStatusShort = array();
 
 		if (empty($this->labelStatus) || empty($this->labelStatusShort))

+ 6 - 6
htdocs/expensereport/card.php

@@ -389,7 +389,7 @@ if (empty($reshook))
 
     			// CONTENT
     			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-				$link = '<a href="' . $link . '">' . $link . '</a>';
+				$link = '<a href="'.$link.'">'.$link.'</a>';
     			$message = $langs->transnoentities("ExpenseReportWaitingForApprovalMessage", $expediteur->getFullName($langs), get_date_range($object->date_debut, $object->date_fin, '', $langs), $link);
 
     			// Rebuild pdf
@@ -509,7 +509,7 @@ if (empty($reshook))
 
     			// CONTENT
     			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-				$link = '<a href="' . $link . '">' . $link . '</a>';
+				$link = '<a href="'.$link.'">'.$link.'</a>';
 				$dateRefusEx = explode(" ", $object->date_refuse);
     			$message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link);
 
@@ -635,7 +635,7 @@ if (empty($reshook))
 
        			// CONTENT
        			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-				$link = '<a href="' . $link . '">' . $link . '</a>';
+				$link = '<a href="'.$link.'">'.$link.'</a>';
        			$message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
 
        			// Rebuilt pdf
@@ -755,7 +755,7 @@ if (empty($reshook))
 
        			// CONTENT
        			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-				$link = '<a href="' . $link . '">' . $link . '</a>';
+				$link = '<a href="'.$link.'">'.$link.'</a>';
     			$message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailRefuse, $link);
 
        			// Rebuilt pdf
@@ -885,7 +885,7 @@ if (empty($reshook))
 
 	    				// CONTENT
 	    				$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-						$link = '<a href="' . $link . '">' . $link . '</a>';
+						$link = '<a href="'.$link.'">'.$link.'</a>';
 	    				$message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailCancel, $link);
 
 	    				// Rebuilt pdf
@@ -1111,7 +1111,7 @@ if (empty($reshook))
 
     			// CONTENT
     			$link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
-				$link = '<a href="' . $link . '">' . $link . '</a>';
+				$link = '<a href="'.$link.'">'.$link.'</a>';
     			$message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
 
         		// Generate pdf before attachment

+ 33 - 33
htdocs/expensereport/class/expensereportstats.class.php

@@ -22,8 +22,8 @@
  *       \ingroup    expensereport
  *       \brief      Fichier de la classe de gestion des stats des expensereport et notes de frais
  */
-require_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php';
-require_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/stats.class.php';
+require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
 
 /**
  *  Classe permettant la gestion des stats des expensereports et notes de frais
@@ -61,29 +61,29 @@ class ExpenseReportStats extends Stats
         $this->socid = $socid;
         $this->userid = $userid;
 
-		$object=new ExpenseReport($this->db);
+		$object = new ExpenseReport($this->db);
 		$this->from = MAIN_DB_PREFIX.$object->table_element." as e";
-		$this->field='total_ht';
+		$this->field = 'total_ht';
 
 		//$this->where = " e.fk_statut > 0";
 		//$this->where.= " AND e.date_valid > '2000-01-01'";    // To filter only correct "valid date". If date is invalid, the group by on it will fails. Launch a repair.php if you have.
-		$this->where.= ' e.entity IN ('.getEntity('expensereport').')';
+		$this->where .= ' e.entity IN ('.getEntity('expensereport').')';
 
 		//$this->where.= " AND entity = ".$conf->entity;
 		if ($this->socid)
 		{
-			$this->where.=" AND e.fk_soc = ".$this->socid;
+			$this->where .= " AND e.fk_soc = ".$this->socid;
 		}
 
 		// Only me and subordinates
 		if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous))
 		{
 			$childids = $user->getAllChildIds();
-			$childids[]=$user->id;
-			$this->where.=" AND e.fk_user_author IN (".(join(',', $childids)).")";
+			$childids[] = $user->id;
+			$this->where .= " AND e.fk_user_author IN (".(join(',', $childids)).")";
 		}
 
-		if ($this->userid > 0) $this->where.=' AND e.fk_user_author = '.$this->userid;
+		if ($this->userid > 0) $this->where .= ' AND e.fk_user_author = '.$this->userid;
 	}
 
 
@@ -95,9 +95,9 @@ class ExpenseReportStats extends Stats
 	public function getNbByYear()
 	{
 		$sql = "SELECT YEAR(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).") as dm, count(*)";
-		$sql.= " FROM ".$this->from;
-		$sql.= " GROUP BY dm DESC";
-		$sql.= " WHERE ".$this->where;
+		$sql .= " FROM ".$this->from;
+		$sql .= " GROUP BY dm DESC";
+		$sql .= " WHERE ".$this->where;
 
 		return $this->_getNbByYear($sql);
 	}
@@ -113,13 +113,13 @@ class ExpenseReportStats extends Stats
 	public function getNbByMonth($year, $format = 0)
 	{
 		$sql = "SELECT MONTH(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).") as dm, count(*)";
-		$sql.= " FROM ".$this->from;
-		$sql.= " WHERE YEAR(e.".$this->datetouse.") = ".$year;
-		$sql.= " AND ".$this->where;
-		$sql.= " GROUP BY dm";
-        $sql.= $this->db->order('dm', 'DESC');
+		$sql .= " FROM ".$this->from;
+		$sql .= " WHERE YEAR(e.".$this->datetouse.") = ".$year;
+		$sql .= " AND ".$this->where;
+		$sql .= " GROUP BY dm";
+        $sql .= $this->db->order('dm', 'DESC');
 
-		$res=$this->_getNbByMonth($year, $sql, $format);
+		$res = $this->_getNbByMonth($year, $sql, $format);
 		//var_dump($res);print '<br>';
 		return $res;
 	}
@@ -135,13 +135,13 @@ class ExpenseReportStats extends Stats
 	public function getAmountByMonth($year, $format = 0)
 	{
 		$sql = "SELECT date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%m') as dm, sum(".$this->field.")";
-		$sql.= " FROM ".$this->from;
-		$sql.= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$year."'";
-		$sql.= " AND ".$this->where;
-		$sql.= " GROUP BY dm";
-		$sql.= $this->db->order('dm', 'DESC');
+		$sql .= " FROM ".$this->from;
+		$sql .= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$year."'";
+		$sql .= " AND ".$this->where;
+		$sql .= " GROUP BY dm";
+		$sql .= $this->db->order('dm', 'DESC');
 
-		$res=$this->_getAmountByMonth($year, $sql, $format);
+		$res = $this->_getAmountByMonth($year, $sql, $format);
 		//var_dump($res);print '<br>';
 		return $res;
 	}
@@ -155,11 +155,11 @@ class ExpenseReportStats extends Stats
 	public function getAverageByMonth($year)
 	{
 		$sql = "SELECT date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%m') as dm, avg(".$this->field.")";
-		$sql.= " FROM ".$this->from;
-		$sql.= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$year."'";
-		$sql.= " AND ".$this->where;
-		$sql.= " GROUP BY dm";
-        $sql.= $this->db->order('dm', 'DESC');
+		$sql .= " FROM ".$this->from;
+		$sql .= " WHERE date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') = '".$year."'";
+		$sql .= " AND ".$this->where;
+		$sql .= " GROUP BY dm";
+        $sql .= $this->db->order('dm', 'DESC');
 
 		return $this->_getAverageByMonth($year, $sql);
 	}
@@ -172,10 +172,10 @@ class ExpenseReportStats extends Stats
 	public function getAllByYear()
 	{
 		$sql = "SELECT date_format(".$this->db->ifsql('e.'.$this->datetouse.' IS NULL', 'e.date_create', 'e.'.$this->datetouse).",'%Y') as year, count(*) as nb, sum(".$this->field.") as total, avg(".$this->field.") as avg";
-		$sql.= " FROM ".$this->from;
-		$sql.= " WHERE ".$this->where;
-		$sql.= " GROUP BY year";
-        $sql.= $this->db->order('year', 'DESC');
+		$sql .= " FROM ".$this->from;
+		$sql .= " WHERE ".$this->where;
+		$sql .= " GROUP BY year";
+        $sql .= $this->db->order('year', 'DESC');
 
         return $this->_getAllByYear($sql);
     }

+ 1 - 1
htdocs/exports/export.php

@@ -379,7 +379,7 @@ if ($step == 2 && $action == 'select_model')
     {
 		$fieldsarray = preg_split("/,(?! [^(]*\))/", $objexport->hexa);
 		$i = 1;
-		foreach($fieldsarray as $val)
+		foreach ($fieldsarray as $val)
 		{
 			$array_selected[$val] = $i;
 			$i++;

+ 20 - 20
htdocs/fourn/ajax/getSupplierPrices.php

@@ -22,20 +22,20 @@
  *	\brief      File to return an Ajax response to get list of possible prices for margin calculation
  */
 
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
-if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC', '1');
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
+if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
+if (!defined('NOREQUIRESOC'))   define('NOREQUIRESOC', '1');
 
 require '../../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
 
-$idprod=GETPOST('idprod', 'int');
+$idprod = GETPOST('idprod', 'int');
 
 $prices = array();
 
 // Load translation files required by the page
-$langs->loadLangs(array("stocks","margins"));
+$langs->loadLangs(array("stocks", "margins"));
 
 
 /*
@@ -48,14 +48,14 @@ top_httphead();
 
 if ($idprod > 0)
 {
-	$producttmp=new ProductFournisseur($db);
+	$producttmp = new ProductFournisseur($db);
 	$producttmp->fetch($idprod);
 
 	$sorttouse = 's.nom, pfp.quantity, pfp.price';
 	if (GETPOST('bestpricefirst')) $sorttouse = 'pfp.unitprice, s.nom, pfp.quantity, pfp.price';
 
-	$productSupplierArray = $producttmp->list_product_fournisseur_price($idprod, $sorttouse);    // We list all price per supplier, and then firstly with the lower quantity. So we can choose first one with enough quantity into list.
-	if ( is_array($productSupplierArray))
+	$productSupplierArray = $producttmp->list_product_fournisseur_price($idprod, $sorttouse); // We list all price per supplier, and then firstly with the lower quantity. So we can choose first one with enough quantity into list.
+	if (is_array($productSupplierArray))
 	{
 		foreach ($productSupplierArray as $productSupplier)
 		{
@@ -66,35 +66,35 @@ if ($idprod > 0)
 
 			if ($productSupplier->fourn_qty == 1)
 			{
-				$title.= price($price, 0, $langs, 0, 0, -1, $conf->currency)."/";
+				$title .= price($price, 0, $langs, 0, 0, -1, $conf->currency)."/";
 			}
-			$title.= $productSupplier->fourn_qty.' '.($productSupplier->fourn_qty == 1 ? $langs->trans("Unit") : $langs->trans("Units"));
+			$title .= $productSupplier->fourn_qty.' '.($productSupplier->fourn_qty == 1 ? $langs->trans("Unit") : $langs->trans("Units"));
 
 			if ($productSupplier->fourn_qty > 1)
 			{
-				$title.=" - ";
-				$title.= price($unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit");
+				$title .= " - ";
+				$title .= price($unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit");
 				$price = $unitprice;
 			}
 
 			$label = price($price, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit");
-			if ($productSupplier->fourn_ref) $label.=' ('.$productSupplier->fourn_ref.')';
+			if ($productSupplier->fourn_ref) $label .= ' ('.$productSupplier->fourn_ref.')';
 
-			$prices[] = array("id" => $productSupplier->product_fourn_price_id, "price" => price2num($price, 0, '', 0), "label" => $label, "title" => $title);  // For price field, we must use price2num(), for label or title, price()
+			$prices[] = array("id" => $productSupplier->product_fourn_price_id, "price" => price2num($price, 0, '', 0), "label" => $label, "title" => $title); // For price field, we must use price2num(), for label or title, price()
 		}
 	}
 
 	// After best supplier prices and before costprice
-	if(!empty($conf->stock->enabled))
+	if (!empty($conf->stock->enabled))
 	{
 		// Add price for pmp
-		$price=$producttmp->pmp;
-		$prices[] = array("id" => 'pmpprice', "price" => price2num($price), "label" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency));  // For price field, we must use price2num(), for label or title, price()
+		$price = $producttmp->pmp;
+		$prices[] = array("id" => 'pmpprice', "price" => price2num($price), "label" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency)); // For price field, we must use price2num(), for label or title, price()
 	}
 
 	// Add price for costprice (at end)
-	$price=$producttmp->cost_price;
-	$prices[] = array("id" => 'costprice', "price" => price2num($price), "label" => $langs->trans("CostPrice").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency));  // For price field, we must use price2num(), for label or title, price()
+	$price = $producttmp->cost_price;
+	$prices[] = array("id" => 'costprice', "price" => price2num($price), "label" => $langs->trans("CostPrice").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency)); // For price field, we must use price2num(), for label or title, price()
 }
 
 echo json_encode($prices);

+ 50 - 50
htdocs/fourn/class/fournisseur.commande.class.php

@@ -65,7 +65,7 @@ class CommandeFournisseur extends CommonOrder
 	/**
 	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
 	 */
-	public $picto='order';
+	public $picto = 'order';
 
     /**
      * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
@@ -442,7 +442,7 @@ class CommandeFournisseur extends CommonOrder
 
     			$line->fk_product          = $objp->fk_product;
 
-    			$line->libelle             = $objp->product_label;	// deprecated
+    			$line->libelle             = $objp->product_label; // deprecated
     			$line->product_label       = $objp->product_label;
     			$line->product_desc        = $objp->product_desc;
 
@@ -1414,38 +1414,38 @@ class CommandeFournisseur extends CommonOrder
      */
     public function createFromClone(User $user, $socid = 0)
     {
-    	global $conf, $user,$hookmanager;
+    	global $conf, $user, $hookmanager;
 
-        $error=0;
+        $error = 0;
 
 		$this->db->begin();
 
 		// get lines so they will be clone
-		foreach($this->lines as $line)
+		foreach ($this->lines as $line)
 			$line->fetch_optionals();
 
 		// Load source object
 		$objFrom = clone $this;
 
 		// Change socid if needed
-		if (! empty($socid) && $socid != $this->socid)
+		if (!empty($socid) && $socid != $this->socid)
 		{
 			$objsoc = new Societe($this->db);
 
-			if ($objsoc->fetch($socid)>0)
+			if ($objsoc->fetch($socid) > 0)
 			{
-				$this->socid 				= $objsoc->id;
-				$this->cond_reglement_id	= (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
-				$this->mode_reglement_id	= (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
-				$this->fk_project			= 0;
-				$this->fk_delivery_address	= 0;
+				$this->socid = $objsoc->id;
+				$this->cond_reglement_id	= (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
+				$this->mode_reglement_id	= (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
+				$this->fk_project = 0;
+				$this->fk_delivery_address = 0;
 			}
 
 			// TODO Change product price if multi-prices
 		}
 
-        $this->id=0;
-        $this->statut=self::STATUS_DRAFT;
+        $this->id = 0;
+        $this->statut = self::STATUS_DRAFT;
 
         // Clear fields
         $this->user_author_id     = $user->id;
@@ -2400,7 +2400,7 @@ class CommandeFournisseur extends CommonOrder
 
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseurdet";
             $sql .= " (fk_commande, label, description, fk_product, price, qty, tva_tx, localtax1_tx, localtax2_tx, remise_percent, subprice, remise, ref)";
-            $sql .= " VALUES (".$idc.", '" . $this->db->escape($label) . "','" . $this->db->escape($comclient->lines[$i]->desc) . "'";
+            $sql .= " VALUES (".$idc.", '".$this->db->escape($label)."','".$this->db->escape($comclient->lines[$i]->desc)."'";
             $sql .= ",".$comclient->lines[$i]->fk_product.",'".price2num($comclient->lines[$i]->price)."'";
             $sql .= ", '".$comclient->lines[$i]->qty."', ".$comclient->lines[$i]->tva_tx.", ".$comclient->lines[$i]->localtax1_tx.", ".$comclient->lines[$i]->localtax2_tx.", ".$comclient->lines[$i]->remise_percent;
             $sql .= ", '".price2num($comclient->lines[$i]->subprice)."','0','".$ref."');";
@@ -2623,7 +2623,7 @@ class CommandeFournisseur extends CommonOrder
 
             if (is_array($array_options) && count($array_options) > 0) {
             	// We replace values in this->line->array_options only for entries defined into $array_options
-            	foreach($array_options as $key => $value) {
+            	foreach ($array_options as $key => $value) {
             		$this->line->array_options[$key] = $array_options[$key];
             	}
             }
@@ -2795,26 +2795,26 @@ class CommandeFournisseur extends CommonOrder
         // phpcs:enable
         global $conf, $user;
 
-        $this->nb=array();
+        $this->nb = array();
         $clause = "WHERE";
 
         $sql = "SELECT count(co.rowid) as nb";
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co";
-        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
+        $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co";
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid";
         if (!$user->rights->societe->client->voir && !$user->socid)
         {
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
-            $sql.= " WHERE sc.fk_user = " .$user->id;
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
+            $sql .= " WHERE sc.fk_user = ".$user->id;
             $clause = "AND";
         }
-        $sql.= " ".$clause." co.entity = ".$conf->entity;
+        $sql .= " ".$clause." co.entity = ".$conf->entity;
 
-        $resql=$this->db->query($sql);
+        $resql = $this->db->query($sql);
         if ($resql)
         {
-            while ($obj=$this->db->fetch_object($resql))
+            while ($obj = $this->db->fetch_object($resql))
             {
-                $this->nb["supplier_orders"]=$obj->nb;
+                $this->nb["supplier_orders"] = $obj->nb;
             }
             $this->db->free($resql);
             return 1;
@@ -2843,41 +2843,41 @@ class CommandeFournisseur extends CommonOrder
         $clause = " WHERE";
 
         $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date";
-        $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
+        $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
         if (!$user->rights->societe->client->voir && !$user->socid)
         {
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
-            $sql.= " WHERE sc.fk_user = " .$user->id;
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc";
+            $sql .= " WHERE sc.fk_user = ".$user->id;
             $clause = " AND";
         }
-        $sql.= $clause." c.entity = ".$conf->entity;
-        if($mode==='awaiting'){
-            $sql.= " AND c.fk_statut = ".self::STATUS_ORDERSENT;
+        $sql .= $clause." c.entity = ".$conf->entity;
+        if ($mode === 'awaiting') {
+            $sql .= " AND c.fk_statut = ".self::STATUS_ORDERSENT;
         }
-        else{
-            $sql.= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")";
+        else {
+            $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")";
         }
-        if ($user->socid) $sql.=" AND c.fk_soc = ".$user->socid;
+        if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid;
 
-        $resql=$this->db->query($sql);
+        $resql = $this->db->query($sql);
         if ($resql)
         {
             $commandestatic = new CommandeFournisseur($this->db);
 
 	        $response = new WorkboardResponse();
-	        $response->warning_delay=$conf->commande->fournisseur->warning_delay/60/60/24;
-	        $response->label=$langs->trans("SuppliersOrdersToProcess");
-	        $response->labelShort=$langs->trans("Opened");
-	        $response->url=DOL_URL_ROOT.'/fourn/commande/list.php?statut=1,2&mainmenu=commercial&leftmenu=orders_suppliers';
-	        $response->img=img_object('', "order");
+	        $response->warning_delay = $conf->commande->fournisseur->warning_delay / 60 / 60 / 24;
+	        $response->label = $langs->trans("SuppliersOrdersToProcess");
+	        $response->labelShort = $langs->trans("Opened");
+	        $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?statut=1,2&mainmenu=commercial&leftmenu=orders_suppliers';
+	        $response->img = img_object('', "order");
 
-            if($mode==='awaiting'){
-                $response->label=$langs->trans("SuppliersOrdersAwaitingReception");
-                $response->labelShort=$langs->trans("AwaitingReception");
-                $response->url=DOL_URL_ROOT.'/fourn/commande/list.php?statut=3&mainmenu=commercial&leftmenu=orders_suppliers';
+            if ($mode === 'awaiting') {
+                $response->label = $langs->trans("SuppliersOrdersAwaitingReception");
+                $response->labelShort = $langs->trans("AwaitingReception");
+                $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?statut=3&mainmenu=commercial&leftmenu=orders_suppliers';
             }
 
-            while ($obj=$this->db->fetch_object($resql))
+            while ($obj = $this->db->fetch_object($resql))
             {
                 $response->nbtodo++;
 
@@ -2953,12 +2953,12 @@ class CommandeFournisseur extends CommonOrder
 
 		$langs->load("suppliers");
 
-		if (! dol_strlen($modele)) {
+		if (!dol_strlen($modele)) {
 			$modele = 'muscadet';
 
 			if ($this->modelpdf) {
 				$modele = $this->modelpdf;
-			} elseif (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) {
+			} elseif (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) {
 				$modele = $conf->global->COMMANDE_SUPPLIER_ADDON_PDF;
 			}
 		}
@@ -3642,20 +3642,20 @@ class CommandeFournisseurLigne extends CommonOrderLine
     {
         global $user;
 
-        $error=0;
+        $error = 0;
 
         $this->db->begin();
 
         $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande_fournisseurdet WHERE rowid=".$this->id;
 
         dol_syslog(__METHOD__, LOG_DEBUG);
-        $resql=$this->db->query($sql);
+        $resql = $this->db->query($sql);
         if ($resql)
         {
             if (!$notrigger)
             {
                 // Call trigger
-                $result=$this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user);
+                $result = $this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user);
                 if ($result < 0) $error++;
                 // End call triggers
             }

+ 1 - 1
htdocs/fourn/class/fournisseur.facture.class.php

@@ -1952,7 +1952,7 @@ class FactureFournisseur extends CommonInvoice
 
 	    if (is_array($array_options) && count($array_options) > 0) {
 	    	// We replace values in this->line->array_options only for entries defined into $array_options
-	    	foreach($array_options as $key => $value) {
+	    	foreach ($array_options as $key => $value) {
 	    		$this->line->array_options[$key] = $array_options[$key];
 	    	}
 	    }

+ 4 - 4
htdocs/loan/class/loan.class.php

@@ -433,19 +433,19 @@ class Loan extends CommonObject
 		global $langs;
 
 		// Load translation files required by the page
-		$langs->loadLangs(array("customers","bills"));
+		$langs->loadLangs(array("customers", "bills"));
 
-		unset($this->labelStatus);	// Force to reset the array of status label, because label can change depending on parameters
+		unset($this->labelStatus); // Force to reset the array of status label, because label can change depending on parameters
 		if (empty($this->labelStatus) || empty($this->labelStatusShort))
 		{
 			global $langs;
 			//$langs->load("mymodule");
 			$this->labelStatus[self::STATUS_UNPAID] = $langs->trans('Unpaid');
 			$this->labelStatus[self::STATUS_PAID] = $langs->trans('Paid');
-			if ($status ==  0 && $alreadypaid > 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted");
+			if ($status == 0 && $alreadypaid > 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted");
 			$this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans('Unpaid');
 			$this->labelStatusShort[self::STATUS_PAID] = $langs->trans('Enabled');
-			if ($status ==  0 && $alreadypaid > 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted");
+			if ($status == 0 && $alreadypaid > 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted");
 		}
 
 		$statusType = 'status1';

Файловите разлики са ограничени, защото са твърде много
+ 209 - 209
htdocs/modulebuilder/index.php


+ 4 - 4
htdocs/modulebuilder/template/class/myobject.class.php

@@ -237,13 +237,13 @@ class MyObject extends CommonObject
 		// Translate some data of arrayofkeyval
 		if (is_object($langs))
 		{
-			foreach($this->fields as $key => $val)
+			foreach ($this->fields as $key => $val)
 			{
 				if (is_array($val['arrayofkeyval']))
 				{
-					foreach($val['arrayofkeyval'] as $key2 => $val2)
+					foreach ($val['arrayofkeyval'] as $key2 => $val2)
 					{
-						$this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2);
+						$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
 					}
 				}
 			}
@@ -733,7 +733,7 @@ class MyObject extends CommonObject
         $label .= '<br>';
         $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
         if (isset($this->status)) {
-        	$label.= '<br><b>' . $langs->trans("Status").":</b> ".$this->getLibStatut(5);
+        	$label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5);
         }
 
         $url = dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$this->id;

+ 4 - 4
htdocs/modulebuilder/template/myobject_list.php

@@ -142,14 +142,14 @@ foreach($object->fields as $key => $val)
 // 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),
+				'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])
+				'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])
 			);
 		}
 	}
@@ -429,7 +429,7 @@ foreach ($object->fields as $key => $val)
 		elseif (strpos($val['type'], 'integer:') === 0) {
 			print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1);
 		}
-		elseif (! preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
+		elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
 		print '</td>';
 	}
 }

+ 1 - 1
htdocs/mrp/class/mo.class.php

@@ -965,7 +965,7 @@ class Mo extends CommonObject
         $label .= '<br>';
         $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
         if (isset($this->status)) {
-        	$label.= '<br><b>' . $langs->trans("Status").":</b> ".$this->getLibStatut(5);
+        	$label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5);
         }
 
         $url = dol_buildpath('/mrp/mo_card.php', 1).'?id='.$this->id;

+ 6 - 6
htdocs/product/class/product.class.php

@@ -844,10 +844,10 @@ class Product extends CommonObject
         $this->height_units = trim($this->height_units);
         // set unit not defined
         if (is_numeric($this->length_units)) {
-        	$this->width_units = $this->length_units;    // Not used yet
+        	$this->width_units = $this->length_units; // Not used yet
         }
         if (is_numeric($this->length_units)) {
-        	$this->height_units = $this->length_units;    // Not used yet
+        	$this->height_units = $this->length_units; // Not used yet
         }
         // Automated compute surface and volume if not filled
         if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) {
@@ -1882,7 +1882,7 @@ class Product extends CommonObject
         	$newminprice = 0;
         }
         if (empty($newminprice)) {
-        	$newminprice=0;
+        	$newminprice = 0;
         }
 
         // Check parameters
@@ -4348,8 +4348,8 @@ class Product extends CommonObject
             $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
         }
         if (isset($this->status) && isset($this->status_buy)) {
-        	$label.= '<br><b>' . $langs->trans("Status").":</b> ".$this->getLibStatut(5, 0);
-        	$label.= ' '.$this->getLibStatut(5, 1);
+        	$label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5, 0);
+        	$label .= ' '.$this->getLibStatut(5, 1);
         }
 
         if (!empty($this->entity)) {
@@ -4801,7 +4801,7 @@ class Product extends CommonObject
 		}
 		if (!empty($conf->fournisseur->enabled) && !empty($conf->reception->enabled))
 		{
-			$result = $this->load_stats_reception(0, '4', 1);			// Use same tables than when module reception is not used.
+			$result = $this->load_stats_reception(0, '4', 1); // Use same tables than when module reception is not used.
 			if ($result < 0) dol_print_error($this->db, $this->error);
 			$stock_reception_fournisseur = $this->stats_reception['qty'];
 		}

+ 6 - 6
htdocs/product/list.php

@@ -191,7 +191,7 @@ $arrayfields = array(
     'p.tva_tx'=>array('label'=>$langs->trans("VATRate"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>43),
     'p.pmp'=>array('label'=>$langs->trans("PMPValueShort"), 'checked'=>0, 'enabled'=>(!empty($user->rights->fournisseur->lire)), 'position'=>44),
 	'p.seuil_stock_alerte'=>array('label'=>$langs->trans("StockLimit"), 'checked'=>0, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>50),
-	'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'),'position'=>51),
+	'p.desiredstock'=>array('label'=>$langs->trans("DesiredStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>51),
 	'p.stock'=>array('label'=>$langs->trans("PhysicalStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service'), 'position'=>52),
 	'stock_virtual'=>array('label'=>$langs->trans("VirtualStock"), 'checked'=>1, 'enabled'=>(!empty($conf->stock->enabled) && $user->rights->stock->lire && $contextpage != 'service' && $virtualdiffersfromphysical), 'position'=>53),
 	'p.tobatch'=>array('label'=>$langs->trans("ManageLotSerial"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled)), 'position'=>60),
@@ -321,7 +321,7 @@ if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX
 if (!empty($conf->variants->enabled) && (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD) && !$show_childproducts)) {
 	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
 }
-if (!empty($conf->global->PRODUCT_USE_UNITS))   $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_units cu ON cu.rowid = p.fk_unit";
+if (!empty($conf->global->PRODUCT_USE_UNITS))   $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units cu ON cu.rowid = p.fk_unit";
 
 
 $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
@@ -488,11 +488,11 @@ if ($resql)
 	    //'builddoc'=>$langs->trans("PDFMerge"),
 	    //'presend'=>$langs->trans("SendByMail"),
 	);
-    $rightskey='produit';
-	if ($type == Product::TYPE_SERVICE) $rightskey='service';
+    $rightskey = 'produit';
+	if ($type == Product::TYPE_SERVICE) $rightskey = 'service';
 	if ($user->rights->{$rightskey}->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 = '';
 	if ($type === "") $perm = ($user->rights->produit->creer || $user->rights->service->creer);

+ 136 - 136
htdocs/product/reassortlot.php

@@ -38,20 +38,20 @@ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
 $langs->loadLangs(array('products', 'stocks', 'productbatch'));
 
 // Security check
-if ($user->socid) $socid=$user->socid;
-$result=restrictedArea($user, 'produit|service');
-
-
-$action=GETPOST('action', 'alpha');
-$sref=GETPOST("sref", 'alpha');
-$snom=GETPOST("snom", 'alpha');
-$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml'));
-$type=GETPOST("type", "int");
-$search_barcode=GETPOST("search_barcode", 'alpha');
-$search_warehouse=GETPOST('search_warehouse', 'alpha');
-$search_batch=GETPOST('search_batch', 'alpha');
-$catid=GETPOST('catid', 'int');
-$toolowstock=GETPOST('toolowstock');
+if ($user->socid) $socid = $user->socid;
+$result = restrictedArea($user, 'produit|service');
+
+
+$action = GETPOST('action', 'alpha');
+$sref = GETPOST("sref", 'alpha');
+$snom = GETPOST("snom", 'alpha');
+$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
+$type = GETPOST("type", "int");
+$search_barcode = GETPOST("search_barcode", 'alpha');
+$search_warehouse = GETPOST('search_warehouse', 'alpha');
+$search_batch = GETPOST('search_batch', 'alpha');
+$catid = GETPOST('catid', 'int');
+$toolowstock = GETPOST('toolowstock');
 $tosell = GETPOST("tosell");
 $tobuy = GETPOST("tobuy");
 $fourn_id = GETPOST("fourn_id", 'int');
@@ -60,20 +60,20 @@ $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
 $page = GETPOST("page", 'int');
 if (empty($page) || $page < 0) $page = 0;
-if (! $sortfield) $sortfield="p.ref";
-if (! $sortorder) $sortorder="ASC";
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+if (!$sortfield) $sortfield = "p.ref";
+if (!$sortorder) $sortorder = "ASC";
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
-$offset = $limit * $page ;
+$offset = $limit * $page;
 
 // Load sale and categ filters
 $search_sale = GETPOST("search_sale");
 $search_categ = GETPOST("search_categ");
 
 // Get object canvas (By default, this is not defined, so standard usage of dolibarr)
-$canvas=GETPOST("canvas");
-$objcanvas=null;
-if (! empty($canvas))
+$canvas = GETPOST("canvas");
+$objcanvas = null;
+if (!empty($canvas))
 {
 	require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
 	$objcanvas = new Canvas($db, $action);
@@ -88,20 +88,20 @@ if (! empty($canvas))
 
 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
 {
-    $sref="";
-    $snom="";
-    $sall="";
-	$tosell="";
-	$tobuy="";
-    $search_sale="";
-    $search_categ="";
-    $type="";
-    $catid='';
-    $toolowstock='';
-    $search_batch='';
-    $search_warehouse='';
-	$fourn_id='';
-	$sbarcode='';
+    $sref = "";
+    $snom = "";
+    $sall = "";
+	$tosell = "";
+	$tobuy = "";
+    $search_sale = "";
+    $search_categ = "";
+    $type = "";
+    $catid = '';
+    $toolowstock = '';
+    $search_batch = '';
+    $search_warehouse = '';
+	$fourn_id = '';
+	$sbarcode = '';
 }
 
 
@@ -109,64 +109,64 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x'
  * View
  */
 
-$helpurl='EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks';
+$helpurl = 'EN:Module_Stocks_En|FR:Module_Stock|ES:M&oacute;dulo_Stocks';
 
-$form=new Form($db);
-$htmlother=new FormOther($db);
+$form = new Form($db);
+$htmlother = new FormOther($db);
 
-$title=$langs->trans("ProductsAndServices");
+$title = $langs->trans("ProductsAndServices");
 
 $sql = 'SELECT p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,';
-$sql.= ' p.fk_product_type, p.tms as datem,';
-$sql.= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,';
-$sql.= ' ps.fk_entrepot,';
-$sql.= ' e.ref as warehouse_ref, e.lieu as warehouse_lieu, e.fk_parent as warehouse_parent,';
-$sql.= ' pb.batch, pb.eatby as oldeatby, pb.sellby as oldsellby,';
-$sql.= ' pl.rowid as lotid, pl.eatby, pl.sellby,';
-$sql.= ' SUM(pb.qty) as stock_physique, COUNT(pb.rowid) as nbinbatchtable';
-$sql.= ' FROM '.MAIN_DB_PREFIX.'product as p';
-$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as ps on p.rowid = ps.fk_product';                       // Detail for each warehouse
-$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot as e on ps.fk_entrepot = e.rowid';                            // Link on unique key
-$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_batch as pb on pb.fk_product_stock = ps.rowid';                // Detail for each lot on each warehouse
-$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_lot as pl on pl.fk_product = p.rowid AND pl.batch = pb.batch'; // Link on unique key
+$sql .= ' p.fk_product_type, p.tms as datem,';
+$sql .= ' p.duration, p.tosell as statut, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,';
+$sql .= ' ps.fk_entrepot,';
+$sql .= ' e.ref as warehouse_ref, e.lieu as warehouse_lieu, e.fk_parent as warehouse_parent,';
+$sql .= ' pb.batch, pb.eatby as oldeatby, pb.sellby as oldsellby,';
+$sql .= ' pl.rowid as lotid, pl.eatby, pl.sellby,';
+$sql .= ' SUM(pb.qty) as stock_physique, COUNT(pb.rowid) as nbinbatchtable';
+$sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
+$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as ps on p.rowid = ps.fk_product'; // Detail for each warehouse
+$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot as e on ps.fk_entrepot = e.rowid'; // Link on unique key
+$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_batch as pb on pb.fk_product_stock = ps.rowid'; // Detail for each lot on each warehouse
+$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_lot as pl on pl.fk_product = p.rowid AND pl.batch = pb.batch'; // Link on unique key
 // We'll need this table joined to the select in order to filter by categ
-if ($search_categ) $sql.= ", ".MAIN_DB_PREFIX."categorie_product as cp";
-$sql.= " WHERE p.entity IN (".getEntity('product').")";
-if ($search_categ) $sql.= " AND p.rowid = cp.fk_product";	// Join for the needed table to filter by categ
-if ($sall) $sql.=natural_search(array('p.ref','p.label','p.description','p.note'), $sall);
+if ($search_categ) $sql .= ", ".MAIN_DB_PREFIX."categorie_product as cp";
+$sql .= " WHERE p.entity IN (".getEntity('product').")";
+if ($search_categ) $sql .= " AND p.rowid = cp.fk_product"; // Join for the needed table to filter by categ
+if ($sall) $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall);
 // if the type is not 1, we show all products (type = 0,2,3)
 if (dol_strlen($type))
 {
-    if ($type==1)
+    if ($type == 1)
     {
-        $sql.= " AND p.fk_product_type = '1'";
+        $sql .= " AND p.fk_product_type = '1'";
     }
     else
     {
-        $sql.= " AND p.fk_product_type <> '1'";
+        $sql .= " AND p.fk_product_type <> '1'";
     }
 }
-if ($sref)     $sql.= natural_search("p.ref", $sref);
-if ($search_barcode) $sql.= natural_search("p.barcode", $search_barcode);
-if ($snom)     $sql.= natural_search("p.label", $snom);
-if (! empty($tosell)) $sql.= " AND p.tosell = ".$tosell;
-if (! empty($tobuy))  $sql.= " AND p.tobuy = ".$tobuy;
-if (! empty($canvas)) $sql.= " AND p.canvas = '".$db->escape($canvas)."'";
-if($catid) $sql.= " AND cp.fk_categorie = ".$catid;
-if ($fourn_id > 0) $sql.= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id;
+if ($sref)     $sql .= natural_search("p.ref", $sref);
+if ($search_barcode) $sql .= natural_search("p.barcode", $search_barcode);
+if ($snom)     $sql .= natural_search("p.label", $snom);
+if (!empty($tosell)) $sql .= " AND p.tosell = ".$tosell;
+if (!empty($tobuy))  $sql .= " AND p.tobuy = ".$tobuy;
+if (!empty($canvas)) $sql .= " AND p.canvas = '".$db->escape($canvas)."'";
+if ($catid) $sql .= " AND cp.fk_categorie = ".$catid;
+if ($fourn_id > 0) $sql .= " AND p.rowid = pf.fk_product AND pf.fk_soc = ".$fourn_id;
 // Insert categ filter
 if ($search_categ) $sql .= " AND cp.fk_categorie = ".$db->escape($search_categ);
 if ($search_warehouse) $sql .= natural_search("e.ref", $search_warehouse);
 if ($search_batch) $sql .= natural_search("pb.batch", $search_batch);
-$sql.= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,";
-$sql.= " p.fk_product_type, p.tms,";
-$sql.= " p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,";
-$sql.= " ps.fk_entrepot,";
-$sql.= " e.ref, e.lieu, e.fk_parent,";
-$sql.= " pb.batch, pb.eatby, pb.sellby,";
-$sql.= " pl.rowid, pl.eatby, pl.sellby";
-if ($toolowstock) $sql.= " HAVING SUM(".$db->ifsql('ps.reel IS NULL', '0', 'ps.reel').") < p.seuil_stock_alerte";    // Not used yet
-$sql.= $db->order($sortfield, $sortorder);
+$sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,";
+$sql .= " p.fk_product_type, p.tms,";
+$sql .= " p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,";
+$sql .= " ps.fk_entrepot,";
+$sql .= " e.ref, e.lieu, e.fk_parent,";
+$sql .= " pb.batch, pb.eatby, pb.sellby,";
+$sql .= " pl.rowid, pl.eatby, pl.sellby";
+if ($toolowstock) $sql .= " HAVING SUM(".$db->ifsql('ps.reel IS NULL', '0', 'ps.reel').") < p.seuil_stock_alerte"; // Not used yet
+$sql .= $db->order($sortfield, $sortorder);
 
 $nbtotalofrecords = '';
 if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
@@ -180,7 +180,7 @@ 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)
@@ -198,35 +198,35 @@ if ($resql)
 
 	if (isset($type))
 	{
-		if ($type==1) { $texte = $langs->trans("Services"); }
+		if ($type == 1) { $texte = $langs->trans("Services"); }
 		else { $texte = $langs->trans("Products"); }
 	} else {
 		$texte = $langs->trans("ProductsAndServices");
 	}
-	$texte.=' ('.$langs->trans("StocksByLotSerial").')';
-
-	$param='';
-	if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
-	if ($sall)		$param.="&sall=".urlencode($sall);
-	if ($tosell)		$param.="&tosell=".urlencode($tosell);
-	if ($tobuy)			$param.="&tobuy=".urlencode($tobuy);
-	if ($type)			$param.="&type=".urlencode($type);
-	if ($fourn_id)		$param.="&fourn_id=".urlencode($fourn_id);
-	if ($snom)			$param.="&snom=".urlencode($snom);
-	if ($sref)			$param.="&sref=".urlencode($sref);
-	if ($search_batch)	$param.="&search_batch=".urlencode($search_batch);
-	if ($sbarcode)		$param.="&sbarcode=".urlencode($sbarcode);
-	if ($search_warehouse)	$param.="&search_warehouse=".urlencode($search_warehouse);
-	if ($catid)			$param.="&catid=".urlencode($catid);
-	if ($toolowstock)	$param.="&toolowstock=".urlencode($toolowstock);
-	if ($search_sale)	$param.="&search_sale=".urlencode($search_sale);
-	if ($search_categ)	$param.="&search_categ=".urlencode($search_categ);
+	$texte .= ' ('.$langs->trans("StocksByLotSerial").')';
+
+	$param = '';
+	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
+	if ($sall)		$param .= "&sall=".urlencode($sall);
+	if ($tosell)		$param .= "&tosell=".urlencode($tosell);
+	if ($tobuy)			$param .= "&tobuy=".urlencode($tobuy);
+	if ($type)			$param .= "&type=".urlencode($type);
+	if ($fourn_id)		$param .= "&fourn_id=".urlencode($fourn_id);
+	if ($snom)			$param .= "&snom=".urlencode($snom);
+	if ($sref)			$param .= "&sref=".urlencode($sref);
+	if ($search_batch)	$param .= "&search_batch=".urlencode($search_batch);
+	if ($sbarcode)		$param .= "&sbarcode=".urlencode($sbarcode);
+	if ($search_warehouse)	$param .= "&search_warehouse=".urlencode($search_warehouse);
+	if ($catid)			$param .= "&catid=".urlencode($catid);
+	if ($toolowstock)	$param .= "&toolowstock=".urlencode($toolowstock);
+	if ($search_sale)	$param .= "&search_sale=".urlencode($search_sale);
+	if ($search_categ)	$param .= "&search_categ=".urlencode($search_categ);
 	/*if ($eatby)		$param.="&eatby=".$eatby;
 	if ($sellby)	$param.="&sellby=".$sellby;*/
 
 	llxHeader("", $title, $helpurl, $texte);
 
-	print '<form action="'. $_SERVER["PHP_SELF"] .'" method="post" name="formulaire">';
+	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post" name="formulaire">';
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
 	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
@@ -236,7 +236,7 @@ if ($resql)
 	print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'products', 0, '', '', $limit);
 
 
-	if (! empty($catid))
+	if (!empty($catid))
 	{
 		print "<div id='ways'>";
 		$c = new Categorie($db);
@@ -247,29 +247,29 @@ if ($resql)
 	}
 
 	// Filter on categories
- 	$moreforfilter='';
-	if (! empty($conf->categorie->enabled))
+ 	$moreforfilter = '';
+	if (!empty($conf->categorie->enabled))
 	{
-	 	$moreforfilter.='<div class="divsearchfield">';
-	 	$moreforfilter.=$langs->trans('Categories'). ': ';
-		$moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ');
-	 	$moreforfilter.='</div>';
+	 	$moreforfilter .= '<div class="divsearchfield">';
+	 	$moreforfilter .= $langs->trans('Categories').': ';
+		$moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ');
+	 	$moreforfilter .= '</div>';
 	}
 	//$moreforfilter.=$langs->trans("StockTooLow").' <input type="checkbox" name="toolowstock" value="1"'.($toolowstock?' checked':'').'>';
 
-    if (! empty($moreforfilter))
+    if (!empty($moreforfilter))
     {
         print '<div class="liste_titre liste_titre_bydiv centpercent">';
         print $moreforfilter;
-        $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
         print $hookmanager->resPrint;
         print '</div>';
     }
 
 
     print '<div class="div-table-responsive">';
-	print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">';
+	print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">';
 
 	// Fields title search
 	print '<tr class="liste_titre_filter">';
@@ -279,7 +279,7 @@ if ($resql)
 	print '<td class="liste_titre">';
 	print '<input class="flat" type="text" name="snom" size="8" value="'.$snom.'">';
 	print '</td>';
-	if (! empty($conf->service->enabled) && $type == 1)
+	if (!empty($conf->service->enabled) && $type == 1)
 	{
 		print '<td class="liste_titre">';
 		print '&nbsp;';
@@ -294,7 +294,7 @@ if ($resql)
 	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>';
@@ -303,7 +303,7 @@ if ($resql)
 	print "<tr class=\"liste_titre\">";
 	print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", $param, "", "", $sortfield, $sortorder);
 	print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", $param, "", "", $sortfield, $sortorder);
-	if (! empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center ');
+	if (!empty($conf->service->enabled) && $type == 1) print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", $param, "", '', $sortfield, $sortorder, 'center ');
 	print_liste_field_titre("Warehouse", $_SERVER["PHP_SELF"], "e.ref", $param, "", '', $sortfield, $sortorder);
 	//print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock",$param,"",'',$sortfield,$sortorder, 'right );
 	print_liste_field_titre("Batch", $_SERVER["PHP_SELF"], "pb.batch", $param, "", '', $sortfield, $sortorder, 'center ');
@@ -318,52 +318,52 @@ if ($resql)
 	print_liste_field_titre('');
 	print "</tr>\n";
 
-	$product_static=new Product($db);
-	$product_lot_static=new Productlot($db);
-	$warehousetmp=new Entrepot($db);
+	$product_static = new Product($db);
+	$product_lot_static = new Productlot($db);
+	$warehousetmp = new Entrepot($db);
 
 	while ($i < min($num, $limit))
 	{
 		$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)
 			{
 				$objtp = $db->fetch_object($result);
-				if (! empty($objtp->label)) $objp->label = $objtp->label;
+				if (!empty($objtp->label)) $objp->label = $objtp->label;
 			}
 		}
 
 
-		$product_static->ref=$objp->ref;
-		$product_static->id=$objp->rowid;
+		$product_static->ref = $objp->ref;
+		$product_static->id = $objp->rowid;
         $product_static->label = $objp->label;
-		$product_static->type=$objp->fk_product_type;
-		$product_static->entity=$objp->entity;
-		$product_static->status=$objp->tosell;
-		$product_static->status_buy=$objp->tobuy;
-		$product_static->status_batch=$objp->tobatch;
+		$product_static->type = $objp->fk_product_type;
+		$product_static->entity = $objp->entity;
+		$product_static->status = $objp->tosell;
+		$product_static->status_buy = $objp->tobuy;
+		$product_static->status_batch = $objp->tobatch;
 
-		$product_lot_static->batch=$objp->batch;
-		$product_lot_static->product_id=$objp->rowid;
-		$product_lot_static->id=$objp->lotid;
-		$product_lot_static->eatby=$objp->eatby;
-		$product_lot_static->sellby=$objp->sellby;
+		$product_lot_static->batch = $objp->batch;
+		$product_lot_static->product_id = $objp->rowid;
+		$product_lot_static->id = $objp->lotid;
+		$product_lot_static->eatby = $objp->eatby;
+		$product_lot_static->sellby = $objp->sellby;
 
 
-		$warehousetmp->id=$objp->fk_entrepot;
-		$warehousetmp->ref=$objp->warehouse_ref;
-		$warehousetmp->label=$objp->warehouse_ref;
-		$warehousetmp->fk_parent=$objp->warehouse_parent;
+		$warehousetmp->id = $objp->fk_entrepot;
+		$warehousetmp->ref = $objp->warehouse_ref;
+		$warehousetmp->label = $objp->warehouse_ref;
+		$warehousetmp->fk_parent = $objp->warehouse_parent;
 
 		print '<tr>';
 
@@ -376,7 +376,7 @@ if ($resql)
 		// Label
 		print '<td>'.$objp->label.'</td>';
 
-		if (! empty($conf->service->enabled) && $type == 1)
+		if (!empty($conf->service->enabled) && $type == 1)
 		{
 			print '<td class="center">';
 			if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) print $regs[1].' '.$langs->trans("DurationYear");

+ 15 - 15
htdocs/product/stock/class/api_stockmovements.class.php

@@ -99,47 +99,47 @@ class StockMovements extends DolibarrApi
 
         $obj_ret = array();
 
-        if(! DolibarrApiAccess::$user->rights->stock->lire) {
+        if (!DolibarrApiAccess::$user->rights->stock->lire) {
             throw new RestException(401);
         }
 
         $sql = "SELECT t.rowid";
-        $sql.= " FROM ".MAIN_DB_PREFIX."stock_mouvement as t";
+        $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement as t";
         //$sql.= ' WHERE t.entity IN ('.getEntity('stock').')';
-        $sql.= ' WHERE 1 = 1';
+        $sql .= ' WHERE 1 = 1';
         // Add sql filters
         if ($sqlfilters)
         {
-            if (! DolibarrApi::_checkFilters($sqlfilters))
+            if (!DolibarrApi::_checkFilters($sqlfilters))
             {
                 throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
             }
-            $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
-            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
+            $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
+            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
         }
 
-        $sql.= $db->order($sortfield, $sortorder);
-        if ($limit)	{
+        $sql .= $db->order($sortfield, $sortorder);
+        if ($limit) {
             if ($page < 0)
             {
                 $page = 0;
             }
             $offset = $limit * $page;
 
-            $sql.= $db->plimit($limit + 1, $offset);
+            $sql .= $db->plimit($limit + 1, $offset);
         }
 
         $result = $db->query($sql);
         if ($result)
         {
-            $i=0;
+            $i = 0;
             $num = $db->num_rows($result);
             $min = min($num, ($limit <= 0 ? $num : $limit));
             while ($i < $min)
             {
                 $obj = $db->fetch_object($result);
                 $stockmovement_static = new MouvementStock($db);
-                if($stockmovement_static->fetch($obj->rowid)) {
+                if ($stockmovement_static->fetch($obj->rowid)) {
                     $obj_ret[] = $this->_cleanObjectDatas($stockmovement_static);
                 }
                 $i++;
@@ -148,7 +148,7 @@ class StockMovements extends DolibarrApi
         else {
             throw new RestException(503, 'Error when retrieve stock movement list : '.$db->lasterror());
         }
-        if( ! count($obj_ret)) {
+        if (!count($obj_ret)) {
             throw new RestException(404, 'No stock movement found');
         }
         return $obj_ret;
@@ -177,7 +177,7 @@ class StockMovements extends DolibarrApi
      */
     public function post($product_id, $warehouse_id, $qty, $lot = '', $movementcode = '', $movementlabel = '', $price = '', $dlc = '', $dluo = '')
     {
-        if(! DolibarrApiAccess::$user->rights->stock->creer) {
+        if (!DolibarrApiAccess::$user->rights->stock->creer) {
             throw new RestException(401);
         }
 
@@ -187,7 +187,7 @@ class StockMovements extends DolibarrApi
 
         // Type increase or decrease
         $type = 2;
-        if ($qty >= 0){
+        if ($qty >= 0) {
             $type = 3;
         }
 
@@ -195,7 +195,7 @@ class StockMovements extends DolibarrApi
         $eatBy = empty($dluo) ? '' : dol_stringtotime($dluo);
         $sellBy = empty($dlc) ? '' : dol_stringtotime($dlc);
 
-        if($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, '', $eatBy, $sellBy, $lot) <= 0) {
+        if ($this->stockmovement->_create(DolibarrApiAccess::$user, $product_id, $warehouse_id, $qty, $type, $price, $movementlabel, $movementcode, '', $eatBy, $sellBy, $lot) <= 0) {
         	$errormessage = $this->stockmovement->error;
         	if (empty($errormessage)) $errormessage = join(',', $this->stockmovement->errors);
         	throw new RestException(503, 'Error when create stock movement : '.$errormessage);

+ 134 - 134
htdocs/product/stock/class/entrepot.class.php

@@ -37,18 +37,18 @@ class Entrepot extends CommonObject
 	/**
 	 * @var string ID to identify managed object
 	 */
-	public $element='stock';
+	public $element = 'stock';
 
 	/**
 	 * @var string Name of table without prefix where object is stored
 	 */
-	public $table_element='entrepot';
+	public $table_element = 'entrepot';
 
 	/**
 	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
 	 */
-	public $picto='stock';
-	public $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
+	public $picto = 'stock';
+	public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
 
 	/**
 	 * @var string	Label
@@ -102,7 +102,7 @@ class Entrepot extends CommonObject
 	/**
 	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
 	 */
-	public $fields=array(
+	public $fields = array(
 		'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>10),
 		'ref' =>array('type'=>'varchar(255)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-2, 'showoncombobox'=>1, 'position'=>25),
 		'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>30),
@@ -181,7 +181,7 @@ class Entrepot extends CommonObject
 			return 0;
 		}
 
-		$now=dol_now();
+		$now = dol_now();
 
 		$this->db->begin();
 
@@ -189,7 +189,7 @@ class Entrepot extends CommonObject
 		$sql .= " VALUES ('".$this->db->escape($this->libelle)."', ".$conf->entity.", '".$this->db->idate($now)."', ".$user->id.", ".($this->fk_parent > 0 ? $this->fk_parent : "NULL").")";
 
 		dol_syslog(get_class($this)."::create", LOG_DEBUG);
-		$result=$this->db->query($sql);
+		$result = $this->db->query($sql);
 		if ($result)
 		{
 			$id = $this->db->last_insert_id(MAIN_DB_PREFIX."entrepot");
@@ -197,7 +197,7 @@ class Entrepot extends CommonObject
 			{
 				$this->id = $id;
 
-				if (! $error)
+				if (!$error)
 				{
 					$result = $this->update($id, $user);
 					if ($result <= 0)
@@ -207,11 +207,11 @@ class Entrepot extends CommonObject
 				}
 
                 // Actions on extra fields
-                if (! $error)
+                if (!$error)
                 {
                     if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
                     {
-                        $result=$this->insertExtraFields();
+                        $result = $this->insertExtraFields();
                         if ($result < 0)
                         {
                             $error++;
@@ -219,7 +219,7 @@ class Entrepot extends CommonObject
                     }
                 }
 
-				if (! $error)
+				if (!$error)
 				{
 					$this->db->commit();
 					return $id;
@@ -232,14 +232,14 @@ class Entrepot extends CommonObject
 				}
 			}
 			else {
-				$this->error="Failed to get insert id";
+				$this->error = "Failed to get insert id";
 				dol_syslog(get_class($this)."::create return -2");
 				return -2;
 			}
 		}
 		else
 		{
-			$this->error=$this->db->error();
+			$this->error = $this->db->error();
 			dol_syslog(get_class($this)."::create Error ".$this->db->error());
 			$this->db->rollback();
 			return -1;
@@ -257,56 +257,56 @@ class Entrepot extends CommonObject
 	{
 	    global $conf;
 
-        $error=0;
+        $error = 0;
 
 	    if (empty($id)) $id = $this->id;
 
 		// Check if new parent is already a child of current warehouse
-		if(!empty($this->fk_parent))
+		if (!empty($this->fk_parent))
 		{
 			$TChildWarehouses = array($id);
 			$TChildWarehouses = $this->get_children_warehouses($this->id, $TChildWarehouses);
-			if(in_array($this->fk_parent, $TChildWarehouses))
+			if (in_array($this->fk_parent, $TChildWarehouses))
 			{
 				$this->error = 'ErrorCannotAddThisParentWarehouse';
 				return -2;
 			}
 		}
 
-		$this->libelle=trim($this->libelle);
-		$this->description=trim($this->description);
+		$this->libelle = trim($this->libelle);
+		$this->description = trim($this->description);
 
-		$this->lieu=trim($this->lieu);
+		$this->lieu = trim($this->lieu);
 
-		$this->address=trim($this->address);
-		$this->zip=trim($this->zip);
-		$this->town=trim($this->town);
-		$this->country_id=($this->country_id > 0 ? $this->country_id : 0);
+		$this->address = trim($this->address);
+		$this->zip = trim($this->zip);
+		$this->town = trim($this->town);
+		$this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
 
 		$sql = "UPDATE ".MAIN_DB_PREFIX."entrepot ";
-		$sql .= " SET ref = '" . $this->db->escape($this->libelle) ."'";
-		$sql .= ", fk_parent = " . (($this->fk_parent > 0) ? $this->fk_parent : "NULL");
-		$sql .= ", description = '" . $this->db->escape($this->description) ."'";
-		$sql .= ", statut = " . $this->statut;
-		$sql .= ", lieu = '" . $this->db->escape($this->lieu) ."'";
-		$sql .= ", address = '" . $this->db->escape($this->address) ."'";
-		$sql .= ", zip = '" . $this->db->escape($this->zip) ."'";
-		$sql .= ", town = '" . $this->db->escape($this->town) ."'";
-		$sql .= ", fk_pays = " . $this->country_id;
-		$sql .= " WHERE rowid = " . $id;
+		$sql .= " SET ref = '".$this->db->escape($this->libelle)."'";
+		$sql .= ", fk_parent = ".(($this->fk_parent > 0) ? $this->fk_parent : "NULL");
+		$sql .= ", description = '".$this->db->escape($this->description)."'";
+		$sql .= ", statut = ".$this->statut;
+		$sql .= ", lieu = '".$this->db->escape($this->lieu)."'";
+		$sql .= ", address = '".$this->db->escape($this->address)."'";
+		$sql .= ", zip = '".$this->db->escape($this->zip)."'";
+		$sql .= ", town = '".$this->db->escape($this->town)."'";
+		$sql .= ", fk_pays = ".$this->country_id;
+		$sql .= " WHERE rowid = ".$id;
 
 		$this->db->begin();
 
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
-		$resql=$this->db->query($sql);
+		$resql = $this->db->query($sql);
 
-        if (! $resql) {
+        if (!$resql) {
             $error++;
-            $this->errors[]="Error ".$this->db->lasterror();
+            $this->errors[] = "Error ".$this->db->lasterror();
         }
 
-        if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) {
-            $result=$this->insertExtraFields();
+        if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) {
+            $result = $this->insertExtraFields();
             if ($result < 0)
             {
                 $error++;
@@ -318,7 +318,7 @@ class Entrepot extends CommonObject
 			return 1;
 		} else {
 			$this->db->rollback();
-			$this->error=$this->db->lasterror();
+			$this->error = $this->db->lasterror();
 			return -1;
 		}
 	}
@@ -341,24 +341,24 @@ class Entrepot extends CommonObject
 
 		$this->db->begin();
 
-		if (! $error && empty($notrigger))
+		if (!$error && empty($notrigger))
 		{
             // Call trigger
-            $result=$this->call_trigger('WAREHOUSE_DELETE', $user);
+            $result = $this->call_trigger('WAREHOUSE_DELETE', $user);
             if ($result < 0) { $error++; }
             // End call triggers
 		}
 
-		$elements = array('stock_mouvement','product_stock','product_warehouse_properties');
-		foreach($elements as $table)
+		$elements = array('stock_mouvement', 'product_stock', 'product_warehouse_properties');
+		foreach ($elements as $table)
 		{
-			if (! $error)
+			if (!$error)
 			{
 				$sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
-				$sql.= " WHERE fk_entrepot = " . $this->id;
+				$sql .= " WHERE fk_entrepot = ".$this->id;
 
-				$result=$this->db->query($sql);
-				if (! $result)
+				$result = $this->db->query($sql);
+				if (!$result)
 				{
 					$error++;
 					$this->errors[] = $this->db->lasterror();
@@ -367,11 +367,11 @@ class Entrepot extends CommonObject
 		}
 
 		// Removed extrafields
-		if (! $error)
+		if (!$error)
 		{
 			if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
 			{
-				$result=$this->deleteExtraFields();
+				$result = $this->deleteExtraFields();
 				if ($result < 0)
 				{
 					$error++;
@@ -380,12 +380,12 @@ class Entrepot extends CommonObject
 			}
 		}
 
-		if (! $error)
+		if (!$error)
 		{
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."entrepot";
-			$sql.= " WHERE rowid = " . $this->id;
-			$resql1=$this->db->query($sql);
-			if (! $resql1)
+			$sql .= " WHERE rowid = ".$this->id;
+			$resql1 = $this->db->query($sql);
+			if (!$resql1)
 			{
 				$error++;
 				$this->errors[] = $this->db->lasterror();
@@ -393,12 +393,12 @@ class Entrepot extends CommonObject
 			}
 		}
 
-		if (! $error)
+		if (!$error)
 		{
 			// Update denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
 			$sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET stock = (SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)";
-			$resql2=$this->db->query($sql);
-			if (! $resql2)
+			$resql2 = $this->db->query($sql);
+			if (!$resql2)
 			{
 				$error++;
 				$this->errors[] = $this->db->lasterror();
@@ -406,7 +406,7 @@ class Entrepot extends CommonObject
 			}
 		}
 
-		if (! $error)
+		if (!$error)
 		{
 			$this->db->commit();
 			return 1;
@@ -433,9 +433,9 @@ class Entrepot extends CommonObject
 		dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref);
 
 		// Check parameters
-		if (! $id && ! $ref)
+		if (!$id && !$ref)
 		{
-			$this->error='ErrorWrongParameters';
+			$this->error = 'ErrorWrongParameters';
 			dol_syslog(get_class($this)."::fetch ".$this->error);
 			return -1;
 		}
@@ -444,12 +444,12 @@ class Entrepot extends CommonObject
 		$sql .= " FROM ".MAIN_DB_PREFIX."entrepot";
 		if ($id)
 		{
-			$sql.= " WHERE rowid = '".$id."'";
+			$sql .= " WHERE rowid = '".$id."'";
 		}
 		else
 		{
-			$sql.= " WHERE entity = " .$conf->entity;
-			if ($ref) $sql.= " AND ref = '".$this->db->escape($ref)."'";
+			$sql .= " WHERE entity = ".$conf->entity;
+			if ($ref) $sql .= " AND ref = '".$this->db->escape($ref)."'";
 		}
 
 		$result = $this->db->query($sql);
@@ -457,13 +457,13 @@ class Entrepot extends CommonObject
 		{
 			if ($this->db->num_rows($result) > 0)
 			{
-				$obj=$this->db->fetch_object($result);
+				$obj = $this->db->fetch_object($result);
 
 				$this->id             = $obj->rowid;
 				$this->fk_parent      = $obj->fk_parent;
 				$this->ref            = $obj->label;
 				$this->label          = $obj->label;
-				$this->libelle        = $obj->label;            // deprecated
+				$this->libelle        = $obj->label; // deprecated
 				$this->description    = $obj->description;
 				$this->statut         = $obj->statut;
 				$this->lieu           = $obj->lieu;
@@ -477,21 +477,21 @@ class Entrepot extends CommonObject
                 $this->fetch_optionals();
 
 				include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
-	            $tmp=getCountry($this->country_id, 'all');
-				$this->country=$tmp['label'];
-				$this->country_code=$tmp['code'];
+	            $tmp = getCountry($this->country_id, 'all');
+				$this->country = $tmp['label'];
+				$this->country_code = $tmp['code'];
 
 				return 1;
 			}
 			else
 			{
-                $this->error="Record Not Found";
+                $this->error = "Record Not Found";
 				return 0;
 			}
 		}
 		else
 		{
-			$this->error=$this->db->error();
+			$this->error = $this->db->error();
 			return -1;
 		}
 	}
@@ -506,11 +506,11 @@ class Entrepot extends CommonObject
 	public function info($id)
 	{
 		$sql = "SELECT e.rowid, e.datec, e.tms as datem, e.fk_user_author";
-		$sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e";
-		$sql.= " WHERE e.rowid = ".$id;
+		$sql .= " FROM ".MAIN_DB_PREFIX."entrepot as e";
+		$sql .= " WHERE e.rowid = ".$id;
 
 		dol_syslog(get_class($this)."::info", LOG_DEBUG);
-		$result=$this->db->query($sql);
+		$result = $this->db->query($sql);
 		if ($result)
 		{
 			if ($this->db->num_rows($result))
@@ -522,7 +522,7 @@ class Entrepot extends CommonObject
 				if ($obj->fk_user_author) {
 					$cuser = new User($this->db);
 					$cuser->fetch($obj->fk_user_author);
-					$this->user_creation     = $cuser;
+					$this->user_creation = $cuser;
 				}
 
 				if ($obj->fk_user_valid) {
@@ -557,14 +557,14 @@ class Entrepot extends CommonObject
 		$liste = array();
 
 		$sql = "SELECT rowid, ref as label";
-		$sql.= " FROM ".MAIN_DB_PREFIX."entrepot";
-		$sql.= " WHERE entity IN (".getEntity('stock').")";
-		$sql.= " AND statut = ".$status;
+		$sql .= " FROM ".MAIN_DB_PREFIX."entrepot";
+		$sql .= " WHERE entity IN (".getEntity('stock').")";
+		$sql .= " AND statut = ".$status;
 
 		$result = $this->db->query($sql);
 		$i = 0;
 		$num = $this->db->num_rows($result);
-		if ( $result )
+		if ($result)
 		{
 			while ($i < $num)
 			{
@@ -586,25 +586,25 @@ class Entrepot extends CommonObject
 	public function nb_different_products()
 	{
         // phpcs:enable
-		$ret=array();
+		$ret = array();
 
 		$sql = "SELECT count(distinct p.rowid) as nb";
-		$sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
-		$sql.= ", ".MAIN_DB_PREFIX."product as p";
-		$sql.= " WHERE ps.fk_entrepot = ".$this->id;
-		$sql.= " AND ps.fk_product = p.rowid";
+		$sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
+		$sql .= ", ".MAIN_DB_PREFIX."product as p";
+		$sql .= " WHERE ps.fk_entrepot = ".$this->id;
+		$sql .= " AND ps.fk_product = p.rowid";
 
 		//print $sql;
 		$result = $this->db->query($sql);
 		if ($result)
 		{
 			$obj = $this->db->fetch_object($result);
-			$ret['nb']=$obj->nb;
+			$ret['nb'] = $obj->nb;
 			$this->db->free($result);
 		}
 		else
 		{
-			$this->error=$this->db->lasterror();
+			$this->error = $this->db->lasterror();
 			return -1;
 		}
 
@@ -620,26 +620,26 @@ class Entrepot extends CommonObject
 	public function nb_products()
 	{
         // phpcs:enable
-		$ret=array();
+		$ret = array();
 
 		$sql = "SELECT sum(ps.reel) as nb, sum(ps.reel * p.pmp) as value";
-		$sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
-		$sql.= ", ".MAIN_DB_PREFIX."product as p";
-		$sql.= " WHERE ps.fk_entrepot = ".$this->id;
-		$sql.= " AND ps.fk_product = p.rowid";
+		$sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
+		$sql .= ", ".MAIN_DB_PREFIX."product as p";
+		$sql .= " WHERE ps.fk_entrepot = ".$this->id;
+		$sql .= " AND ps.fk_product = p.rowid";
 
 		//print $sql;
 		$result = $this->db->query($sql);
 		if ($result)
 		{
 			$obj = $this->db->fetch_object($result);
-			$ret['nb']=$obj->nb;
-			$ret['value']=$obj->value;
+			$ret['nb'] = $obj->nb;
+			$ret['value'] = $obj->value;
 			$this->db->free($result);
 		}
 		else
 		{
-			$this->error=$this->db->lasterror();
+			$this->error = $this->db->lasterror();
 			return -1;
 		}
 
@@ -695,40 +695,40 @@ class Entrepot extends CommonObject
 		global $conf, $langs;
 		$langs->load("stocks");
 
-        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='';
+        $result = '';
 
-        $label = '<u>' . $langs->trans("ShowWarehouse").'</u>';
-        $label.= '<br><b>' . $langs->trans('Ref') . ':</b> ' . (empty($this->ref)?(empty($this->label)?$this->libelle:$this->label):$this->ref);
-        if (! empty($this->lieu)) {
-            $label.= '<br><b>' . $langs->trans('LocationSummary').':</b> '.$this->lieu;
+        $label = '<u>'.$langs->trans("ShowWarehouse").'</u>';
+        $label .= '<br><b>'.$langs->trans('Ref').':</b> '.(empty($this->ref) ? (empty($this->label) ? $this->libelle : $this->label) : $this->ref);
+        if (!empty($this->lieu)) {
+            $label .= '<br><b>'.$langs->trans('LocationSummary').':</b> '.$this->lieu;
         }
         if (isset($this->statut)) {
-            $label.= '<br><b>' . $langs->trans("Status").":</b> ".$this->getLibStatut(5);
+            $label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5);
         }
 
         $url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id;
 
-        $linkclose='';
+        $linkclose = '';
         if (empty($notooltip))
         {
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
             {
-                $label=$langs->trans("ShowWarehouse");
-                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
+                $label = $langs->trans("ShowWarehouse");
+                $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 .= $linkclose.'>';
+        $linkend = '</a>';
 
         $result .= $linkstart;
-        if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
-        if ($withpicto != 2) $result.= ($showfullpath ? $this->get_full_arbo() : (empty($this->label)?$this->libelle:$this->label));
+        if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+        if ($withpicto != 2) $result .= ($showfullpath ? $this->get_full_arbo() : (empty($this->label) ? $this->libelle : $this->label));
         $result .= $linkend;
 
 		return $result;
@@ -743,23 +743,23 @@ class Entrepot extends CommonObject
      */
     public function initAsSpecimen()
     {
-        global $user,$langs,$conf,$mysoc;
+        global $user, $langs, $conf, $mysoc;
 
-        $now=dol_now();
+        $now = dol_now();
 
         // Initialize parameters
-        $this->id=0;
+        $this->id = 0;
         $this->libelle = 'WAREHOUSE SPECIMEN';
         $this->description = 'WAREHOUSE SPECIMEN '.dol_print_date($now, 'dayhourlog');
-		$this->statut=1;
-        $this->specimen=1;
-
-		$this->lieu='Location test';
-        $this->address='21 jump street';
-        $this->zip='99999';
-        $this->town='MyTown';
-        $this->country_id=1;
-        $this->country_code='FR';
+		$this->statut = 1;
+        $this->specimen = 1;
+
+		$this->lieu = 'Location test';
+        $this->address = '21 jump street';
+        $this->zip = '99999';
+        $this->town = 'MyTown';
+        $this->country_id = 1;
+        $this->country_code = 'FR';
     }
 
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
@@ -771,16 +771,16 @@ class Entrepot extends CommonObject
 	public function get_full_arbo()
 	{
         // phpcs:enable
-        global $user,$langs,$conf;
+        global $user, $langs, $conf;
 
-        $TArbo = array(empty($this->label)?$this->libelle:$this->label);
+        $TArbo = array(empty($this->label) ? $this->libelle : $this->label);
 
-        $protection=100; // We limit depth of warehouses to 100
+        $protection = 100; // We limit depth of warehouses to 100
 
         $warehousetmp = new Entrepot($this->db);
 
-        $parentid = $this->fk_parent;       // If parent_id not defined on current object, we do not start consecutive searches of parents
-        $i=0;
+        $parentid = $this->fk_parent; // If parent_id not defined on current object, we do not start consecutive searches of parents
+        $i = 0;
         while ($parentid > 0 && $i < $protection)
         {
             $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'entrepot WHERE rowid = '.$parentid;
@@ -821,8 +821,8 @@ class Entrepot extends CommonObject
 				WHERE fk_parent = '.$id;
 
 		$resql = $this->db->query($sql);
-		if($resql) {
-			while($res = $this->db->fetch_object($resql)) {
+		if ($resql) {
+			while ($res = $this->db->fetch_object($resql)) {
 				$TChildWarehouses[] = $res->rowid;
 				$this->get_children_warehouses($res->rowid, $TChildWarehouses);
 			}
@@ -843,16 +843,16 @@ class Entrepot extends CommonObject
 	 */
 	public function generateDocument($modele, $outputlangs = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
 	{
-		global $conf,$user,$langs;
+		global $conf, $user, $langs;
 
 		$langs->load("stocks");
 
-		if (! dol_strlen($modele)) {
+		if (!dol_strlen($modele)) {
 			$modele = 'standard';
 
 			if ($this->modelpdf) {
 				$modele = $this->modelpdf;
-			} elseif (! empty($conf->global->STOCK_ADDON_PDF)) {
+			} elseif (!empty($conf->global->STOCK_ADDON_PDF)) {
 				$modele = $conf->global->STOCK_ADDON_PDF;
 			}
 		}
@@ -877,12 +877,12 @@ class Entrepot extends CommonObject
     	$type_categ = Categorie::TYPE_WAREHOUSE;
 
     	// Handle single category
-		if (! is_array($categories)) {
+		if (!is_array($categories)) {
 			$categories = array($categories);
 		}
 
 		// Get current categories
-		require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
+		require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
 		$c = new Categorie($this->db);
 		$existing = $c->containing($this->id, $type_categ, 'id');
 
@@ -896,7 +896,7 @@ class Entrepot extends CommonObject
 		}
 
 		// Process
-		foreach($to_del as $del) {
+		foreach ($to_del as $del) {
 			if ($c->fetch($del) > 0) {
 				$c->del_type($this, $type_categ);
 			}

+ 40 - 40
htdocs/product/stock/productlot_list.php

@@ -200,52 +200,52 @@ jQuery(document).ready(function() {
 
 
 $sql = "SELECT";
-$sql.= " t.rowid,";
-$sql.= " t.entity,";
-$sql.= " t.fk_product,";
-$sql.= " t.batch,";
-$sql.= " t.sellby,";
-$sql.= " t.eatby,";
-$sql.= " t.datec as date_creation,";
-$sql.= " t.tms as date_update,";
-$sql.= " t.fk_user_creat,";
-$sql.= " t.fk_user_modif,";
-$sql.= " t.import_key,";
-$sql.= " p.fk_product_type as product_type,";
-$sql.= " p.ref as product_ref,";
-$sql.= " p.label as product_label,";
-$sql.= " p.tosell,";
-$sql.= " p.tobuy,";
-$sql.= " p.tobatch";
+$sql .= " t.rowid,";
+$sql .= " t.entity,";
+$sql .= " t.fk_product,";
+$sql .= " t.batch,";
+$sql .= " t.sellby,";
+$sql .= " t.eatby,";
+$sql .= " t.datec as date_creation,";
+$sql .= " t.tms as date_update,";
+$sql .= " t.fk_user_creat,";
+$sql .= " t.fk_user_modif,";
+$sql .= " t.import_key,";
+$sql .= " p.fk_product_type as product_type,";
+$sql .= " p.ref as product_ref,";
+$sql .= " p.label as product_label,";
+$sql .= " p.tosell,";
+$sql .= " p.tobuy,";
+$sql .= " p.tobatch";
 // Add fields for extrafields
-if (! empty($extrafields->attributes[$object->table_element]['label'])) {
-	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
+if (!empty($extrafields->attributes[$object->table_element]['label'])) {
+	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
 }
 // Add fields from hooks
-$parameters=array();
-$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters);    // Note that $action and $object may have been modified by hook
-$sql.=$hookmanager->resPrint;
-$sql.= " FROM ".MAIN_DB_PREFIX."product_lot as t";
-if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
-$sql.= ", ".MAIN_DB_PREFIX."product as p";
-$sql.= " WHERE p.rowid = t.fk_product";
-$sql.= " AND p.entity IN (".getEntity('product').")";
-
-if ($search_entity) $sql.= natural_search("entity", $search_entity);
-if ($search_product) $sql.= natural_search("p.ref", $search_product);
-if ($search_batch) $sql.= natural_search("batch", $search_batch);
-if ($search_fk_user_creat) $sql.= natural_search("fk_user_creat", $search_fk_user_creat);
-if ($search_fk_user_modif) $sql.= natural_search("fk_user_modif", $search_fk_user_modif);
-if ($search_import_key) $sql.= natural_search("import_key", $search_import_key);
-
-if ($sall) $sql.= natural_search(array_keys($fieldstosearchall), $sall);
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
+$sql .= $hookmanager->resPrint;
+$sql .= " FROM ".MAIN_DB_PREFIX."product_lot as t";
+if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
+$sql .= ", ".MAIN_DB_PREFIX."product as p";
+$sql .= " WHERE p.rowid = t.fk_product";
+$sql .= " AND p.entity IN (".getEntity('product').")";
+
+if ($search_entity) $sql .= natural_search("entity", $search_entity);
+if ($search_product) $sql .= natural_search("p.ref", $search_product);
+if ($search_batch) $sql .= natural_search("batch", $search_batch);
+if ($search_fk_user_creat) $sql .= natural_search("fk_user_creat", $search_fk_user_creat);
+if ($search_fk_user_modif) $sql .= natural_search("fk_user_modif", $search_fk_user_modif);
+if ($search_import_key) $sql .= natural_search("import_key", $search_import_key);
+
+if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall);
 // 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;
-$sql.=$db->order($sortfield, $sortorder);
+$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->plimit($conf->liste_limit+1, $offset);
 
 // Count total nb of records

+ 2 - 2
htdocs/projet/class/task.class.php

@@ -156,7 +156,7 @@ class Task extends CommonObject
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."projet_task (";
 		$sql .= "fk_projet";
 		$sql .= ", ref";
-		$sql.= ", entity";
+		$sql .= ", entity";
 		$sql .= ", fk_task_parent";
 		$sql .= ", label";
 		$sql .= ", description";
@@ -169,7 +169,7 @@ class Task extends CommonObject
 		$sql .= ") VALUES (";
 		$sql .= $this->fk_project;
 		$sql .= ", ".(!empty($this->ref) ? "'".$this->db->escape($this->ref)."'" : 'null');
-		$sql.= ", ".$conf->entity;
+		$sql .= ", ".$conf->entity;
 		$sql .= ", ".$this->fk_task_parent;
 		$sql .= ", '".$this->db->escape($this->label)."'";
 		$sql .= ", '".$this->db->escape($this->description)."'";

+ 32 - 32
htdocs/projet/tasks/time.php

@@ -43,7 +43,7 @@ $action		= GETPOST('action', 'alpha');
 $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
 $confirm	= GETPOST('confirm', 'alpha');
 $cancel		= GETPOST('cancel', 'alpha');
-$toselect	= GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
+$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', 'alpha');
@@ -237,8 +237,8 @@ if (($action == 'updateline' || $action == 'updatesplitline') && !$_POST["cancel
 			$object->fetch($id, $ref);
 			$object->timespent_note = $_POST["timespent_note_line"];
 			$object->timespent_old_duration = $_POST["old_duration"];
-			$object->timespent_duration = $_POST["new_durationhour"] * 60 * 60;	// We store duration in seconds
-			$object->timespent_duration += ($_POST["new_durationmin"] ? $_POST["new_durationmin"] : 0) * 60;   // We store duration in seconds
+			$object->timespent_duration = $_POST["new_durationhour"] * 60 * 60; // We store duration in seconds
+			$object->timespent_duration += ($_POST["new_durationmin"] ? $_POST["new_durationmin"] : 0) * 60; // We store duration in seconds
 			if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0)	// If hour was entered
 			{
 				$object->timespent_date = dol_mktime(GETPOST("timelinehour"), GETPOST("timelinemin"), 0, GETPOST("timelinemonth"), GETPOST("timelineday"), GETPOST("timelineyear"));
@@ -387,18 +387,18 @@ if ($action == 'confirm_generateinvoice')
 		if ($idprod > 0)
 		{
 			$tmpproduct->fetch($idprod);
-            if ($tmpproduct->duration_unit=='i')
-                $prodDurationHours = 1./60;
-            if ($tmpproduct->duration_unit=='h')
+            if ($tmpproduct->duration_unit == 'i')
+                $prodDurationHours = 1. / 60;
+            if ($tmpproduct->duration_unit == 'h')
                 $prodDurationHours = 1.;
-            if ($tmpproduct->duration_unit=='d')
+            if ($tmpproduct->duration_unit == 'd')
                 $prodDurationHours = 24.;
-            if ($tmpproduct->duration_unit=='w')
-                $prodDurationHours = 24.*7;
-            if ($tmpproduct->duration_unit=='m')
-                $prodDurationHours = 24.*30;
-            if ($tmpproduct->duration_unit=='y')
-                $prodDurationHours = 24.*365;
+            if ($tmpproduct->duration_unit == 'w')
+                $prodDurationHours = 24. * 7;
+            if ($tmpproduct->duration_unit == 'm')
+                $prodDurationHours = 24. * 30;
+            if ($tmpproduct->duration_unit == 'y')
+                $prodDurationHours = 24. * 365;
             $prodDurationHours *= $tmpproduct->duration_value;
 
 			$dataforprice = $tmpproduct->getSellPrice($mysoc, $projectstatic->thirdparty, 0);
@@ -433,7 +433,7 @@ if ($action == 'confirm_generateinvoice')
 
 		if (!$error)
 		{
-			if ($generateinvoicemode=='onelineperuser') {
+			if ($generateinvoicemode == 'onelineperuser') {
 					$arrayoftasks = array();
 				foreach ($toselect as $key => $value)
 					{
@@ -460,7 +460,7 @@ if ($action == 'confirm_generateinvoice')
 					}
 
 					// Add lines
-					$lineid = $tmpinvoice->addline($langs->trans("TimeSpentForInvoice", $username).' : '.$qtyhourtext, $pu_ht, round($qtyhour/$prodDurationHours, 2), $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0));
+					$lineid = $tmpinvoice->addline($langs->trans("TimeSpentForInvoice", $username).' : '.$qtyhourtext, $pu_ht, round($qtyhour / $prodDurationHours, 2), $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0));
 
 					// Update lineid into line of timespent
 					$sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id;
@@ -474,7 +474,7 @@ if ($action == 'confirm_generateinvoice')
 					}
 				}
 			}
-			elseif ($generateinvoicemode=='onelineperperiod') {
+			elseif ($generateinvoicemode == 'onelineperperiod') {
 					$arrayoftasks = array();
 				foreach ($toselect as $key => $value)
 					{
@@ -504,7 +504,7 @@ if ($action == 'confirm_generateinvoice')
 					}
 
 					// Add lines
-					$lineid = $tmpinvoice->addline($value['note'], $pu_ht, round($qtyhour/$prodDurationHours, 2), $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0));
+					$lineid = $tmpinvoice->addline($value['note'], $pu_ht, round($qtyhour / $prodDurationHours, 2), $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0));
 
 					// Update lineid into line of timespent
 					$sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id;
@@ -518,7 +518,7 @@ if ($action == 'confirm_generateinvoice')
 					}
 				}
 			}
-			elseif ($generateinvoicemode=='onelinepertask') {
+			elseif ($generateinvoicemode == 'onelinepertask') {
 					$arrayoftasks = array();
 				foreach ($toselect as $key => $value)
 					{
@@ -545,7 +545,7 @@ if ($action == 'confirm_generateinvoice')
 
 					// Add lines
 					$lineName = $ftask->ref.' - '.$ftask->label;
-					$lineid = $tmpinvoice->addline($lineName, $pu_ht, round($qtyhour/$prodDurationHours, 2), $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0));
+					$lineid = $tmpinvoice->addline($lineName, $pu_ht, round($qtyhour / $prodDurationHours, 2), $txtva, $localtax1, $localtax2, ($idprod > 0 ? $idprod : 0));
 
 					// Update lineid into line of timespent
 					$sql = 'UPDATE '.MAIN_DB_PREFIX.'projet_task_time SET invoice_line_id = '.$lineid.', invoice_id = '.$tmpinvoice->id;
@@ -1346,7 +1346,7 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0)
         			print '<td class="nowrap">';
 					if ($action == 'editline' && $_GET['lineid'] == $task_time->rowid)
 					{
-						$formproject->selectTasks(-1, GETPOST('taskid', 'int')?GETPOST('taskid', 'int'):$task_time->fk_task, 'taskid', 0, 0, 1, 1, 0, 0, 'maxwidth300', $projectstatic->id, '');
+						$formproject->selectTasks(-1, GETPOST('taskid', 'int') ?GETPOST('taskid', 'int') : $task_time->fk_task, 'taskid', 0, 0, 1, 1, 0, 0, 'maxwidth300', $projectstatic->id, '');
 					}
 					else
 					{
@@ -1392,11 +1392,11 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0)
 				}
 				else
 				{
-					$userstatic->id			= $task_time->fk_user;
+					$userstatic->id = $task_time->fk_user;
 					$userstatic->lastname = $task_time->lastname;
-					$userstatic->firstname	= $task_time->firstname;
-					$userstatic->photo		= $task_time->photo;
-					$userstatic->statut		= $task_time->user_status;
+					$userstatic->firstname = $task_time->firstname;
+					$userstatic->photo = $task_time->photo;
+					$userstatic->statut = $task_time->user_status;
 					print $userstatic->getNomUrl(-1);
 				}
 				print '</td>';
@@ -1615,11 +1615,11 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0)
 					}
 					else
 					{
-						$userstatic->id			= $task_time->fk_user;
+						$userstatic->id = $task_time->fk_user;
 						$userstatic->lastname = $task_time->lastname;
-						$userstatic->firstname	= $task_time->firstname;
-						$userstatic->photo		= $task_time->photo;
-						$userstatic->statut		= $task_time->user_status;
+						$userstatic->firstname = $task_time->firstname;
+						$userstatic->photo = $task_time->photo;
+						$userstatic->statut = $task_time->user_status;
 						print $userstatic->getNomUrl(-1);
 					}
 					print '</td>';
@@ -1763,11 +1763,11 @@ if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0)
 					}
 					else
 					{
-						$userstatic->id			= $task_time->fk_user;
+						$userstatic->id = $task_time->fk_user;
 						$userstatic->lastname = $task_time->lastname;
-						$userstatic->firstname	= $task_time->firstname;
-						$userstatic->photo		= $task_time->photo;
-						$userstatic->statut		= $task_time->user_status;
+						$userstatic->firstname = $task_time->firstname;
+						$userstatic->photo = $task_time->photo;
+						$userstatic->statut = $task_time->user_status;
 						print $userstatic->getNomUrl(-1);
 					}
 					print '</td>';

+ 89 - 89
htdocs/public/demo/index.php

@@ -24,74 +24,74 @@
  *		\brief      Entry page to access demo
  */
 
-define("NOLOGIN", 1);	// This means this output page does not require to be logged.
-define("NOCSRFCHECK", 1);	// We accept to go on this page from external web site.
+define("NOLOGIN", 1); // This means this output page does not require to be logged.
+define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
 
 require '../../main.inc.php';
 require_once '../../core/lib/functions2.lib.php';
 
 $langs->loadLangs(array("main", "install", "other"));
 
-$conf->dol_hide_topmenu=GETPOST('dol_hide_topmenu', 'int');
-$conf->dol_hide_leftmenu=GETPOST('dol_hide_leftmenu', 'int');
-$conf->dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen', 'int');
-$conf->dol_no_mouse_hover=GETPOST('dol_no_mouse_hover', 'int');
-$conf->dol_use_jmobile=GETPOST('dol_use_jmobile', 'int');
+$conf->dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int');
+$conf->dol_hide_leftmenu = GETPOST('dol_hide_leftmenu', 'int');
+$conf->dol_optimize_smallscreen = GETPOST('dol_optimize_smallscreen', 'int');
+$conf->dol_no_mouse_hover = GETPOST('dol_no_mouse_hover', 'int');
+$conf->dol_use_jmobile = GETPOST('dol_use_jmobile', 'int');
 
 // Security check
 global $dolibarr_main_demo;
 if (empty($dolibarr_main_demo)) accessforbidden('Parameter dolibarr_main_demo must be defined in conf file with value "default login,default pass" to enable the demo entry page', 0, 0, 1);
 
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
-$res=$hookmanager->initHooks(array('demo'));
-
-$demoprofiles=array();
-$alwayscheckedmodules=array();
-$alwaysuncheckedmodules=array();
-$alwayshiddencheckedmodules=array();
-$alwayshiddenuncheckedmodules=array();
-
-$url='';
-$url.=($url?'&':'').($conf->dol_hide_topmenu?'dol_hide_topmenu='.$conf->dol_hide_topmenu:'');
-$url.=($url?'&':'').($conf->dol_hide_leftmenu?'dol_hide_leftmenu='.$conf->dol_hide_leftmenu:'');
-$url.=($url?'&':'').($conf->dol_optimize_smallscreen?'dol_optimize_smallscreen='.$conf->dol_optimize_smallscreen:'');
-$url.=($url?'&':'').($conf->dol_no_mouse_hover?'dol_no_mouse_hover='.$conf->dol_no_mouse_hover:'');
-$url.=($url?'&':'').($conf->dol_use_jmobile?'dol_use_jmobile='.$conf->dol_use_jmobile:'');
-$url=DOL_URL_ROOT.'/index.php'.($url?'?'.$url:'');
+$res = $hookmanager->initHooks(array('demo'));
+
+$demoprofiles = array();
+$alwayscheckedmodules = array();
+$alwaysuncheckedmodules = array();
+$alwayshiddencheckedmodules = array();
+$alwayshiddenuncheckedmodules = array();
+
+$url = '';
+$url .= ($url ? '&' : '').($conf->dol_hide_topmenu ? 'dol_hide_topmenu='.$conf->dol_hide_topmenu : '');
+$url .= ($url ? '&' : '').($conf->dol_hide_leftmenu ? 'dol_hide_leftmenu='.$conf->dol_hide_leftmenu : '');
+$url .= ($url ? '&' : '').($conf->dol_optimize_smallscreen ? 'dol_optimize_smallscreen='.$conf->dol_optimize_smallscreen : '');
+$url .= ($url ? '&' : '').($conf->dol_no_mouse_hover ? 'dol_no_mouse_hover='.$conf->dol_no_mouse_hover : '');
+$url .= ($url ? '&' : '').($conf->dol_use_jmobile ? 'dol_use_jmobile='.$conf->dol_use_jmobile : '');
+$url = DOL_URL_ROOT.'/index.php'.($url ? '?'.$url : '');
 
 $tmpaction = 'view';
-$parameters=array();
-$object=new stdClass();
-$reshook=$hookmanager->executeHooks('addDemoProfile', $parameters, $object, $tmpaction);    // Note that $action and $object may have been modified by some hooks
-$error=$hookmanager->error; $errors=$hookmanager->errors;
+$parameters = array();
+$object = new stdClass();
+$reshook = $hookmanager->executeHooks('addDemoProfile', $parameters, $object, $tmpaction); // Note that $action and $object may have been modified by some hooks
+$error = $hookmanager->error; $errors = $hookmanager->errors;
 if (empty($reshook))
 {
-	$demoprofiles=array(
-		array('default'=>'1', 'key'=>'profdemoservonly','label'=>'DemoCompanyServiceOnly',
+	$demoprofiles = array(
+		array('default'=>'1', 'key'=>'profdemoservonly', 'label'=>'DemoCompanyServiceOnly',
 		'disablemodules'=>'adherent,barcode,bom,cashdesk,don,expedition,externalsite,ftp,incoterm,mailmanspip,margin,mrp,prelevement,product,productbatch,stock,takepos',
 		//'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot8.png',
 		'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-service.jpg',
 		'url'=>$url
 		),
-		array('default'=>'0', 'key'=>'profmanufacture','label'=>'DemoCompanyManufacturing',
+		array('default'=>'0', 'key'=>'profmanufacture', 'label'=>'DemoCompanyManufacturing',
 			'disablemodules'=>'adherent,contrat,don,externalsite,ficheinter,ftp,mailmanspip,prelevement,service',
 			'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-manufacturing.jpg',
 			'url'=>$url
 		),
-		array('default'=>'0', 'key'=>'profdemoprodstock','label'=>'DemoCompanyProductAndStocks',
+		array('default'=>'0', 'key'=>'profdemoprodstock', 'label'=>'DemoCompanyProductAndStocks',
 		'disablemodules'=>'adherent,bom,contrat,don,externalsite,ficheinter,ftp,mailmanspip,mrp,prelevement,service',
 		//'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot2.png',
 		'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-product.jpg',
 		'url'=>$url
 		),
-		array('default'=>'0', 'key'=>'profdemofun2','label'=>'DemoFundation2',
+		array('default'=>'0', 'key'=>'profdemofun2', 'label'=>'DemoFundation2',
 		'disablemodules'=>'barcode,cashdesk,bom,commande,commercial,compta,comptabilite,contrat,expedition,externalsite,ficheinter,ftp,incoterm,mailmanspip,margin,mrp,prelevement,product,productbatch,projet,propal,propale,service,societe,stock,tax,takepos',
 		//'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot6.png',
 		'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-foundation.jpg',
 		'url'=>$url
 		),
 	    // All demo profile
-	    array('default'=>'0', 'key'=>'profdemoall','label'=>'ChooseYourDemoProfilMore',
+	    array('default'=>'0', 'key'=>'profdemoall', 'label'=>'ChooseYourDemoProfilMore',
 		'disablemodules'=>'adherent,cashdesk,don,externalsite,mailmanspip',
 	    //'icon'=>DOL_URL_ROOT.'/public/demo/dolibarr_screenshot9.png'
 		'icon'=>DOL_URL_ROOT.'/public/demo/demo-profile-all.jpg'
@@ -100,21 +100,21 @@ if (empty($reshook))
 
 
 	// Visible
-	$alwayscheckedmodules=array('barcode','bookmark','categorie','externalrss','fckeditor','geoipmaxmind','gravatar','memcached','syslog','user','webservices');  // Technical module we always want
-	$alwaysuncheckedmodules=array('dav','dynamicprices','incoterm','loan','multicurrency','paybox','paypal','stripe','google','printing','scanner','skype','website');  // Module we dont want by default
+	$alwayscheckedmodules = array('barcode', 'bookmark', 'categorie', 'externalrss', 'fckeditor', 'geoipmaxmind', 'gravatar', 'memcached', 'syslog', 'user', 'webservices'); // Technical module we always want
+	$alwaysuncheckedmodules = array('dav', 'dynamicprices', 'incoterm', 'loan', 'multicurrency', 'paybox', 'paypal', 'stripe', 'google', 'printing', 'scanner', 'skype', 'website'); // Module we dont want by default
 	// Not visible
-	$alwayshiddencheckedmodules=array('accounting','api','barcode','blockedlog','bookmark','clicktodial','comptabilite','cron','document','domain','externalrss','externalsite','fckeditor','geoipmaxmind','gravatar','label','ldap',
-									'mailmanspip','notification','oauth','syslog','user','webservices','workflow',
+	$alwayshiddencheckedmodules = array('accounting', 'api', 'barcode', 'blockedlog', 'bookmark', 'clicktodial', 'comptabilite', 'cron', 'document', 'domain', 'externalrss', 'externalsite', 'fckeditor', 'geoipmaxmind', 'gravatar', 'label', 'ldap',
+									'mailmanspip', 'notification', 'oauth', 'syslog', 'user', 'webservices', 'workflow',
 	                                // Extended modules
-	                                'memcached','numberwords','zipautofillfr');
-	$alwayshiddenuncheckedmodules=array('dav','debugbar','emailcollector','ftp','hrm','modulebuilder','printing','webservicesclient',
+	                                'memcached', 'numberwords', 'zipautofillfr');
+	$alwayshiddenuncheckedmodules = array('dav', 'debugbar', 'emailcollector', 'ftp', 'hrm', 'modulebuilder', 'printing', 'webservicesclient',
 	                                // Extended modules
-	                                'awstats','bittorrent','bootstrap','cabinetmed','cmcic','concatpdf','customfield','deplacement','dolicloud','filemanager','lightbox','mantis','monitoring','moretemplates','multicompany','nltechno','numberingpack','openstreetmap',
-	                                'ovh','phenix','phpsysinfo','pibarcode','postnuke','selectbank','skincoloreditor','submiteverywhere','survey','thomsonphonebook','topten','tvacerfa','voyage','webcalendar','webmail');
+	                                'awstats', 'bittorrent', 'bootstrap', 'cabinetmed', 'cmcic', 'concatpdf', 'customfield', 'deplacement', 'dolicloud', 'filemanager', 'lightbox', 'mantis', 'monitoring', 'moretemplates', 'multicompany', 'nltechno', 'numberingpack', 'openstreetmap',
+	                                'ovh', 'phenix', 'phpsysinfo', 'pibarcode', 'postnuke', 'selectbank', 'skincoloreditor', 'submiteverywhere', 'survey', 'thomsonphonebook', 'topten', 'tvacerfa', 'voyage', 'webcalendar', 'webmail');
 }
 
 // Search modules
-$dirlist=$conf->file->dol_document_root;
+$dirlist = $conf->file->dol_document_root;
 
 
 // Search modules dirs
@@ -132,13 +132,13 @@ $j = 0; // j is module number. Automatically affected if module number not defin
 foreach ($modulesdir as $dir)
 {
     // Charge tableaux modules, nom, numero, orders depuis repertoire dir
-    $handle=@opendir($dir);
+    $handle = @opendir($dir);
     if (is_resource($handle))
     {
-        while (($file = readdir($handle))!==false)
+        while (($file = readdir($handle)) !== false)
         {
             //print "$i ".$file."\n<br>";
-            if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod'  && substr($file, dol_strlen($file) - 10) == '.class.php')
+            if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php')
             {
                 $modName = substr($file, 0, dol_strlen($file) - 10);
 
@@ -158,25 +158,25 @@ foreach ($modulesdir as $dir)
                             $j = 1000 + $i;
                         }
 
-                        $modulequalified=1;
+                        $modulequalified = 1;
 
                         // We discard modules according to features level (PS: if module is activated we always show it)
                         $const_name = 'MAIN_MODULE_'.strtoupper(preg_replace('/^mod/i', '', get_class($objMod)));
-                        if ($objMod->version == 'development'  && $conf->global->MAIN_FEATURES_LEVEL < 2 && empty($conf->global->$const_name)) $modulequalified=0;
-                        if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && empty($conf->global->$const_name)) $modulequalified=0;
+                        if ($objMod->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && empty($conf->global->$const_name)) $modulequalified = 0;
+                        if ($objMod->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && empty($conf->global->$const_name)) $modulequalified = 0;
 
                         if ($modulequalified)
                         {
                             $modules[$i] = $objMod;
-                            $filename[$i]= $modName;
-                            $orders[$i]  = $objMod->family."_".$j;   // Tri par famille puis numero module
+                            $filename[$i] = $modName;
+                            $orders[$i]  = $objMod->family."_".$j; // Tri par famille puis numero module
                             //print "x".$modName." ".$orders[$i]."\n<br>";
                             $dirmod[$i] = $dirroot;
                             $j++;
                             $i++;
                         }
 		            }
-                    catch(Exception $e)
+                    catch (Exception $e)
                     {
                         dol_syslog("Failed to load ".$dir.$file." ".$e->getMessage(), LOG_ERR);
                     }
@@ -197,7 +197,7 @@ asort($orders);
 if (GETPOST('action', 'aZ09') == 'gotodemo')     // Action run when we click on "Start" after selection modules
 {
 	//print 'ee'.GETPOST("demochoice");
-	$disablestring='';
+	$disablestring = '';
 	// If we disable modules using a profile choice
 	if (GETPOST("demochoice"))
 	{
@@ -205,27 +205,27 @@ if (GETPOST('action', 'aZ09') == 'gotodemo')     // Action run when we click on
     	{
     		if ($profilearray['key'] == GETPOST("demochoice"))
     		{
-    			$disablestring=$profilearray['disablemodules'];
+    			$disablestring = $profilearray['disablemodules'];
     			break;
     		}
     	}
 	}
 	// If we disable modules using personalized list
-	foreach($modules as $val)
+	foreach ($modules as $val)
 	{
-	    $modulekeyname=strtolower($val->name);
-	    if (empty($_POST[$modulekeyname]) && empty($val->always_enabled) && ! in_array($modulekeyname, $alwayscheckedmodules))
+	    $modulekeyname = strtolower($val->name);
+	    if (empty($_POST[$modulekeyname]) && empty($val->always_enabled) && !in_array($modulekeyname, $alwayscheckedmodules))
 	    {
-	        $disablestring.=$modulekeyname.',';
-	        if ($modulekeyname=='propale') $disablestring.='propal,';
+	        $disablestring .= $modulekeyname.',';
+	        if ($modulekeyname == 'propale') $disablestring .= 'propal,';
 	    }
 	}
 
     // Do redirect to login page
 	if ($disablestring)
 	{
-		if (GETPOST('urlfrom')) $url.=(preg_match('/\?/', $url)?'&amp;':'?').'urlfrom='.urlencode(GETPOST('urlfrom', 'alpha'));
-		$url.=(preg_match('/\?/', $url)?'&amp;':'?').'disablemodules='.$disablestring;
+		if (GETPOST('urlfrom')) $url .= (preg_match('/\?/', $url) ? '&amp;' : '?').'urlfrom='.urlencode(GETPOST('urlfrom', 'alpha'));
+		$url .= (preg_match('/\?/', $url) ? '&amp;' : '?').'disablemodules='.$disablestring;
         //var_dump($url);exit;
 		header("Location: ".$url);
 		exit;
@@ -237,11 +237,11 @@ if (GETPOST('action', 'aZ09') == 'gotodemo')     // Action run when we click on
  * View
  */
 
-$head='';
-$head.='<meta name="keywords" content="demo,online,demonstration,example,test,erp,crm,demos,web">'."\n";
-$head.='<meta name="description" content="Dolibarr ERP and CRM demo. You can test here several profiles for Dolibarr ERP and CRM demonstration.">'."\n";
+$head = '';
+$head .= '<meta name="keywords" content="demo,online,demonstration,example,test,erp,crm,demos,web">'."\n";
+$head .= '<meta name="description" content="Dolibarr ERP and CRM demo. You can test here several profiles for Dolibarr ERP and CRM demonstration.">'."\n";
 
-$head.='
+$head .= '
 <script type="text/javascript">
 var openedId="";
 jQuery(document).ready(function () {
@@ -289,29 +289,29 @@ print '</div>';
 print '<div class="clearboth"></div>';
 print '<div class="demobanbox">';
 
-$i=0;
+$i = 0;
 foreach ($demoprofiles as $profilearray)
 {
 	if ($profilearray['default'] >= 0)
 	{
 	    //print $profilearray['lang'];
-	    if (! empty($profilearray['lang'])) $langs->load($profilearray['lang']);
+	    if (!empty($profilearray['lang'])) $langs->load($profilearray['lang']);
 
-		$url=$_SERVER["PHP_SELF"].'?action=gotodemo';
-		$urlwithmod=$url.'&amp;demochoice='.$profilearray['key'];
+		$url = $_SERVER["PHP_SELF"].'?action=gotodemo';
+		$urlwithmod = $url.'&amp;demochoice='.$profilearray['key'];
 		// Should work with DOL_URL_ROOT='' or DOL_URL_ROOT='/dolibarr'
 		//print "xx".$_SERVER["PHP_SELF"].' '.DOL_URL_ROOT.'<br>';
 
-        $urlfrom=preg_replace('/^'.preg_quote(DOL_URL_ROOT, '/').'/i', '', $_SERVER["PHP_SELF"]);
+        $urlfrom = preg_replace('/^'.preg_quote(DOL_URL_ROOT, '/').'/i', '', $_SERVER["PHP_SELF"]);
 		//print $urlfrom;
 
-		if (! empty($profilearray['url']))
+		if (!empty($profilearray['url']))
 		{
-		    $urlwithmod=$profilearray['url'];
-		    $urlwithmod=$urlwithmod.(preg_match('/\?/', $urlwithmod)?'&amp;':'?').'urlfrom='.urlencode($urlfrom);
-		    if (! empty($profilearray['disablemodules']))
+		    $urlwithmod = $profilearray['url'];
+		    $urlwithmod = $urlwithmod.(preg_match('/\?/', $urlwithmod) ? '&amp;' : '?').'urlfrom='.urlencode($urlfrom);
+		    if (!empty($profilearray['disablemodules']))
 		    {
-		          $urlwithmod=$urlwithmod.(preg_match('/\?/', $urlwithmod)?'&amp;':'?').'disablemodules='.$profilearray['disablemodules'];
+		          $urlwithmod = $urlwithmod.(preg_match('/\?/', $urlwithmod) ? '&amp;' : '?').'disablemodules='.$profilearray['disablemodules'];
 		    }
 		}
 
@@ -331,12 +331,12 @@ foreach ($demoprofiles as $profilearray)
         print '<input type="hidden" name="dol_no_mouse_hover" value="'.$conf->dol_no_mouse_hover.'">'."\n";
         print '<input type="hidden" name="dol_use_jmobile" value="'.$conf->dol_use_jmobile.'">'."\n";
 
-        print '<div id="div'.$profilearray['key'].'" summary="Dolibarr online demonstration for profile '.$profilearray['label'].'" class="center inline-block CTable CTableRow'.($i%2==0?'1':'0').'">'."\n";
+        print '<div id="div'.$profilearray['key'].'" summary="Dolibarr online demonstration for profile '.$profilearray['label'].'" class="center inline-block CTable CTableRow'.($i % 2 == 0 ? '1' : '0').'">'."\n";
 
 
-        print '<div id="a1'.$profilearray['key'].'" class="demobox '.(empty($profilearray['url'])?'modulelineshow cursorpointer':'nomodulelines').'">';
+        print '<div id="a1'.$profilearray['key'].'" class="demobox '.(empty($profilearray['url']) ? 'modulelineshow cursorpointer' : 'nomodulelines').'">';
 
-        print '<a href="'.$urlwithmod.'" class="'.(empty($profilearray['url'])?'modulelineshow':'nomodulelines').'">';
+        print '<a href="'.$urlwithmod.'" class="'.(empty($profilearray['url']) ? 'modulelineshow' : 'nomodulelines').'">';
 		print '<div style="padding: 10px;">';
 
 		print '<img class="demothumb" src="'.$profilearray['icon'].'" alt="Demo '.$profilearray['label'].'">';
@@ -360,21 +360,21 @@ foreach ($demoprofiles as $profilearray)
 
     		print '<div class="csscolumns">';
 
-    		$listofdisabledmodules=explode(',', $profilearray['disablemodules']);
-    		$j=0;
-    		$nbcolsmod=empty($conf->dol_optimize_smallscreen)?4:3;
+    		$listofdisabledmodules = explode(',', $profilearray['disablemodules']);
+    		$j = 0;
+    		$nbcolsmod = empty($conf->dol_optimize_smallscreen) ? 4 : 3;
     		//var_dump($modules);
-    		foreach($orders as $index => $key) // Loop on qualified (enabled) modules
+    		foreach ($orders as $index => $key) // Loop on qualified (enabled) modules
     		{
     			//print $index.' '.$key;
     			$val = $modules[$index];
-    		    $modulekeyname=strtolower($val->name);
+    		    $modulekeyname = strtolower($val->name);
 
-    		    $modulequalified=1;
-                if (! empty($val->always_enabled) || in_array($modulekeyname, $alwayshiddenuncheckedmodules)) $modulequalified=0;
-                if ($val->version == 'development'  && $conf->global->MAIN_FEATURES_LEVEL < 2 && ! $conf->global->$const_name) $modulequalified=0;
-                if ($val->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && ! $conf->global->$const_name) $modulequalified=0;
-                if (! $modulequalified) continue;
+    		    $modulequalified = 1;
+                if (!empty($val->always_enabled) || in_array($modulekeyname, $alwayshiddenuncheckedmodules)) $modulequalified = 0;
+                if ($val->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2 && !$conf->global->$const_name) $modulequalified = 0;
+                if ($val->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1 && !$conf->global->$const_name) $modulequalified = 0;
+                if (!$modulequalified) continue;
 
                 if (in_array($modulekeyname, $alwayshiddencheckedmodules))
                 {
@@ -383,13 +383,13 @@ foreach ($demoprofiles as $profilearray)
                 }
                 else
                 {
-                    $modulo=($j % $nbcolsmod);
+                    $modulo = ($j % $nbcolsmod);
         		    //if ($modulo == 0) print '<tr>';
                     print '<!-- id='.$val->numero.' -->';
                     print '<div class="nowrap">';
                     print '<input type="checkbox" class="checkbox" id="id'.$modulekeyname.'" name="'.$modulekeyname.'" value="1" title="'.dol_escape_htmltag($val->getName()).'"';
                     if (in_array($modulekeyname, $alwaysuncheckedmodules)) print ' disabled';
-                    if (! in_array($modulekeyname, $alwaysuncheckedmodules)  && (! in_array($modulekeyname, $listofdisabledmodules) || in_array($modulekeyname, $alwayscheckedmodules))) print ' checked';
+                    if (!in_array($modulekeyname, $alwaysuncheckedmodules) && (!in_array($modulekeyname, $listofdisabledmodules) || in_array($modulekeyname, $alwayscheckedmodules))) print ' checked';
                     print '> <label for="id'.$modulekeyname.'" class="inline-block demomaxoveflow" title="'.dol_escape_htmltag($val->getName()).'">'.$val->getName().'</label><br>';
                     print '</div>';
                     //if ($modulo == ($nbcolsmod - 1)) print '</tr>';
@@ -418,7 +418,7 @@ print '</div>';
 
 // TODO Replace this with a hook
 // Google Adsense (need Google module)
-if (! empty($conf->google->enabled) && ! empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && ! empty($conf->global->MAIN_GOOGLE_AD_SLOT))
+if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT))
 {
 	if (empty($conf->dol_use_jmobile))
 	{

+ 1 - 1
htdocs/resource/class/dolresource.class.php

@@ -958,7 +958,7 @@ class Dolresource extends CommonObject
         	$label.= '<br><b>' . $langs->trans("Status").":</b> ".$this->getLibStatut(5);
         }*/
         if (isset($this->type_label)) {
-        	$label.= '<br><b>' . $langs->trans("ResourceType").":</b> ".$this->type_label;
+        	$label .= '<br><b>'.$langs->trans("ResourceType").":</b> ".$this->type_label;
         }
 
         $url = DOL_URL_ROOT.'/resource/card.php?id='.$this->id;

+ 9 - 9
htdocs/societe/card.php

@@ -965,7 +965,7 @@ else
         if (!empty($conf->fournisseur->enabled) && (GETPOST("type") == 'f' || (GETPOST("type") == '' && !empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)))) { $object->fournisseur = 1; }
 
         $object->name = GETPOST('name', 'alpha');
-        $object->name_alias	= GETPOST('name_alias', 'alpha');
+        $object->name_alias = GETPOST('name_alias', 'alpha');
         $object->firstname = GETPOST('firstname', 'alpha');
         $object->particulier		= $private;
         $object->prefix_comm		= GETPOST('prefix_comm', 'alpha');
@@ -1073,11 +1073,11 @@ else
 
         if (!empty($conf->use_javascript_ajax)) {
 			if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) {
-				print "\n" . '<script type="text/javascript">';
+				print "\n".'<script type="text/javascript">';
 				print '$(document).ready(function () {
 						id_te_private=8;
                         id_ef15=1;
-                        is_private=' . $private . ';
+                        is_private=' . $private.';
 						if (is_private) {
 							$(".individualline").show();
 						} else {
@@ -1104,7 +1104,7 @@ else
 						});
 						function init_customer_categ() {
 								console.log("is customer or prospect = "+jQuery("#customerprospect").val());
-								if (jQuery("#customerprospect").val() == 0 && (jQuery("#fournisseur").val() == 0 || ' . (empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER) ? '1' : '0') . '))
+								if (jQuery("#customerprospect").val() == 0 && (jQuery("#fournisseur").val() == 0 || ' . (empty($conf->global->THIRDPARTY_CAN_HAVE_CATEGORY_EVEN_IF_NOT_CUSTOMER_PROSPECT_SUPPLIER) ? '1' : '0').'))
 								{
 									jQuery(".visibleifcustomer").hide();
 								}
@@ -1135,20 +1135,20 @@ else
                         	document.formsoc.submit();
                         });
                      });';
-				print '</script>' . "\n";
+				print '</script>'."\n";
 
 				print '<div id="selectthirdpartytype">';
 				print '<div class="hideonsmartphone float">';
-				print $langs->trans("ThirdPartyType") . ': &nbsp; &nbsp; ';
+				print $langs->trans("ThirdPartyType").': &nbsp; &nbsp; ';
 				print '</div>';
 				print '<label for="radiocompany" class="radiocompany">';
-				print '<input type="radio" id="radiocompany" class="flat" name="private"  value="0"' . ($private ? '' : ' checked') . '>';
+				print '<input type="radio" id="radiocompany" class="flat" name="private"  value="0"'.($private ? '' : ' checked').'>';
 				print '&nbsp;';
 				print $langs->trans("CreateThirdPartyOnly");
 				print '</label>';
 				print ' &nbsp; &nbsp; ';
 				print '<label for="radioprivate" class="radioprivate">';
-				$text = '<input type="radio" id="radioprivate" class="flat" name="private" value="1"' . ($private ? ' checked' : '') . '>';
+				$text = '<input type="radio" id="radioprivate" class="flat" name="private" value="1"'.($private ? ' checked' : '').'>';
 				$text .= '&nbsp;';
 				$text .= $langs->trans("CreateThirdPartyAndContact");
 				$htmltext = $langs->trans("ToCreateContactWithSameName");
@@ -1164,7 +1164,7 @@ else
                         	document.formsoc.submit();
                         });
                      });';
-				print '</script>' . "\n";
+				print '</script>'."\n";
 			}
 		}
 

+ 11 - 11
htdocs/societe/paymentmodes.php

@@ -584,7 +584,7 @@ if (empty($reshook))
             }
 
 			$resql = $db->query($sql);
-			$num = $db->num_rows($resql);		// Note: $num is always 0 on an update and delete, it is defined for select only.
+			$num = $db->num_rows($resql); // Note: $num is always 0 on an update and delete, it is defined for select only.
 			if (!empty($newcu)) {
 				if (empty($num))
 				{
@@ -1009,17 +1009,17 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 					}
 				}
 			}
-			catch(Exception $e)
+			catch (Exception $e)
 			{
 				dol_syslog("Error when searching/loading Stripe customer for thirdparty id =".$object->id);
 			}
 		}
 
 		print '<!-- List of stripe payments -->'."\n";
-		print '<div class="div-table-responsive-no-min">';		// You can use div-table-responsive-no-min if you dont need reserved height for your table
+		print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
 		print '<table class="liste centpercent">'."\n";
 		print '<tr class="liste_titre">';
-		if (! empty($conf->global->STRIPE_ALLOW_LOCAL_CARD))
+		if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD))
 		{
 			print '<td>'.$langs->trans('LocalID').'</td>';
 		}
@@ -1346,7 +1346,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 		{
 			foreach ($balance->available as $cpt)
 			{
-		        $arrayzerounitcurrency=array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
+		        $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
 		        if (!in_array($cpt->currency, $arrayzerounitcurrency)) {
     					$currencybalance[$cpt->currency]['available'] = $cpt->amount / 100;
 				} else {
@@ -1360,11 +1360,11 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 		{
 			foreach ($balance->pending as $cpt)
 			{
-				$arrayzerounitcurrency=array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
+				$arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
 				if (!in_array($cpt->currency, $arrayzerounitcurrency)) {
-					$currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available']+$cpt->amount / 100;
+					$currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available'] + $cpt->amount / 100;
 				} else {
-					$currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available']+$cpt->amount;
+					$currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available'] + $cpt->amount;
 				}
 			}
         }
@@ -1373,7 +1373,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 		{
 			foreach ($currencybalance as $cpt)
 			{
-				print '<tr><td>'.$langs->trans("Currency".strtoupper($cpt['currency'])).'</td><td>'.price($cpt['available'], 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td><td>'.price($cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td><td>'.price($cpt['available']+$cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td></tr>';
+				print '<tr><td>'.$langs->trans("Currency".strtoupper($cpt['currency'])).'</td><td>'.price($cpt['available'], 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td><td>'.price($cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td><td>'.price($cpt['available'] + $cpt->pending, 0, '', 1, - 1, - 1, strtoupper($cpt['currency'])).'</td></tr>';
 			}
 		}
 
@@ -1383,14 +1383,14 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 
 	// List of bank accounts
 
-    $morehtmlright= dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=create');
+    $morehtmlright = dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=create');
 
 	print load_fiche_titre($langs->trans("BankAccounts"), $morehtmlright, '');
 
 	$rib_list = $object->get_all_rib();
 	if (is_array($rib_list))
 	{
-		print '<div class="div-table-responsive-no-min">';		// You can use div-table-responsive-no-min if you dont need reserved height for your table
+		print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
 		print '<table class="liste centpercent">';
 
 		print '<tr class="liste_titre">';

+ 6 - 6
htdocs/stripe/charge.php

@@ -26,17 +26,17 @@ require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
-if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.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('compta', 'salaries', 'bills', 'hrm', 'stripe'));
 
 // Security check
 $socid = GETPOST("socid", "int");
-if ($user->socid) $socid=$user->socid;
+if ($user->socid) $socid = $user->socid;
 //$result = restrictedArea($user, 'salaries', '', '', '');
 
-$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit;
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 $rowid = GETPOST("rowid", 'alpha');
 $sortfield = GETPOST("sortfield", 'alpha');
 $sortorder = GETPOST("sortorder", 'alpha');
@@ -154,16 +154,16 @@ if (!$rowid)
         }
 
 		// The metadata FULLTAG is defined by the online payment page
-		$FULLTAG=$charge->metadata->FULLTAG;
+		$FULLTAG = $charge->metadata->FULLTAG;
 
 		// Save into $tmparray all metadata
 		$tmparray = dolExplodeIntoArray($FULLTAG, '.', '=');
 		// Load origin object according to metadata
-		if (! empty($tmparray['CUS']) && $tmparray['CUS'] > 0)
+		if (!empty($tmparray['CUS']) && $tmparray['CUS'] > 0)
 		{
 			$societestatic->fetch($tmparray['CUS']);
 		}
-		elseif (! empty($charge->metadata->dol_thirdparty_id) && $charge->metadata->dol_thirdparty_id > 0)
+		elseif (!empty($charge->metadata->dol_thirdparty_id) && $charge->metadata->dol_thirdparty_id > 0)
 		{
 			$societestatic->fetch($charge->metadata->dol_thirdparty_id);
 		}

+ 3 - 3
htdocs/supplier_proposal/class/supplier_proposal.class.php

@@ -589,7 +589,7 @@ class SupplierProposal extends CommonObject
                 $productFournisseur->find_min_price_product_fournisseur($fk_product);
                 $this->line->fk_fournprice = $productFournisseur->product_fourn_price_id;
             } else {
-            	$this->line->fk_fournprice = ($fk_fournprice > 0 ? $fk_fournprice : 0);		// If fk_fournprice is -1, we will not use fk_fournprice
+            	$this->line->fk_fournprice = ($fk_fournprice > 0 ? $fk_fournprice : 0); // If fk_fournprice is -1, we will not use fk_fournprice
             }
             $this->line->pa_ht = $pa_ht;
             //var_dump($this->line->fk_fournprice);exit;
@@ -777,9 +777,9 @@ class SupplierProposal extends CommonObject
             }
             $this->line->pa_ht = $pa_ht;
 
-            if (is_array($array_options) && count($array_options)>0) {
+            if (is_array($array_options) && count($array_options) > 0) {
             	// We replace values in this->line->array_options only for entries defined into $array_options
-            	foreach($array_options as $key => $value) {
+            	foreach ($array_options as $key => $value) {
             		$this->line->array_options[$key] = $array_options[$key];
             	}
             }

+ 26 - 26
htdocs/takepos/floors.php

@@ -25,65 +25,65 @@
 //if (! defined('NOREQUIREDB'))		define('NOREQUIREDB','1');		// Not disabled cause need to load personalized language
 //if (! defined('NOREQUIRESOC'))		define('NOREQUIRESOC','1');
 //if (! defined('NOREQUIRETRAN'))		define('NOREQUIRETRAN','1');
-if (! defined('NOCSRFCHECK'))		define('NOCSRFCHECK', '1');
-if (! defined('NOTOKENRENEWAL'))	define('NOTOKENRENEWAL', '1');
-if (! defined('NOREQUIREMENU'))		define('NOREQUIREMENU', '1');
-if (! defined('NOREQUIREHTML'))		define('NOREQUIREHTML', '1');
-if (! defined('NOREQUIREAJAX'))		define('NOREQUIREAJAX', '1');
+if (!defined('NOCSRFCHECK'))		define('NOCSRFCHECK', '1');
+if (!defined('NOTOKENRENEWAL'))	define('NOTOKENRENEWAL', '1');
+if (!defined('NOREQUIREMENU'))		define('NOREQUIREMENU', '1');
+if (!defined('NOREQUIREHTML'))		define('NOREQUIREHTML', '1');
+if (!defined('NOREQUIREAJAX'))		define('NOREQUIREAJAX', '1');
 
-require '../main.inc.php';	// Load $user and permissions
+require '../main.inc.php'; // Load $user and permissions
 
-$langs->loadLangs(array("bills","orders","commercial","cashdesk"));
+$langs->loadLangs(array("bills", "orders", "commercial", "cashdesk"));
 
-$floor=GETPOST('floor', 'int');
-if ($floor=="") $floor=1;
+$floor = GETPOST('floor', 'int');
+if ($floor == "") $floor = 1;
 $id = GETPOST('id', 'int');
 $action = GETPOST('action', 'alpha');
 $left = GETPOST('left', 'alpha');
 $top = GETPOST('top', 'alpha');
 
-$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0);   // $place is id of table for Ba or Restaurant
+$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant
 
 $newname = GETPOST('newname', 'alpha');
 $mode = GETPOST('mode', 'alpha');
 
-if ($action=="getTables")
+if ($action == "getTables")
 {
-    $sql="SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables where floor=".$floor;
+    $sql = "SELECT rowid, entity, label, leftpos, toppos, floor FROM ".MAIN_DB_PREFIX."takepos_floor_tables where floor=".$floor;
     $resql = $db->query($sql);
     $rows = array();
-    while($row = $db->fetch_array($resql)){
+    while ($row = $db->fetch_array($resql)) {
         $rows[] = $row;
     }
     echo json_encode($rows);
     exit;
 }
 
-if ($action=="update")
+if ($action == "update")
 {
-    if ($left>95) $left=95;
-    if ($top>95) $top=95;
-    if ($left>3 or $top>4) $db->query("UPDATE ".MAIN_DB_PREFIX."takepos_floor_tables set leftpos=".$left.", toppos=".$top." WHERE rowid='".$place."'");
+    if ($left > 95) $left = 95;
+    if ($top > 95) $top = 95;
+    if ($left > 3 or $top > 4) $db->query("UPDATE ".MAIN_DB_PREFIX."takepos_floor_tables set leftpos=".$left.", toppos=".$top." WHERE rowid='".$place."'");
     else $db->query("DELETE from ".MAIN_DB_PREFIX."takepos_floor_tables where rowid='".$place."'");
 }
 
-if ($action=="updatename")
+if ($action == "updatename")
 {
     $newname = preg_replace("/[^a-zA-Z0-9\s]/", "", $newname); // Only English chars
     if (strlen($newname) > 3) $newname = substr($newname, 0, 3); // Only 3 chars
     $db->query("UPDATE ".MAIN_DB_PREFIX."takepos_floor_tables set label='".$db->escape($newname)."' WHERE rowid='".$place."'");
 }
 
-if ($action=="add")
+if ($action == "add")
 {
-    $sql="INSERT INTO ".MAIN_DB_PREFIX."takepos_floor_tables(entity, label, leftpos, toppos, floor) VALUES (".$conf->entity.", '', '45', '45', ".$floor.")";
-    $asdf=$db->query($sql);
+    $sql = "INSERT INTO ".MAIN_DB_PREFIX."takepos_floor_tables(entity, label, leftpos, toppos, floor) VALUES (".$conf->entity.", '', '45', '45', ".$floor.")";
+    $asdf = $db->query($sql);
     $db->query("update ".MAIN_DB_PREFIX."takepos_floor_tables set label=rowid where label=''"); // No empty table names
 }
 
 // Title
-$title='TakePOS - Dolibarr '.DOL_VERSION;
-if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $title='TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE;
+$title = 'TakePOS - Dolibarr '.DOL_VERSION;
+if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = 'TakePOS - '.$conf->global->MAIN_APPLICATION_TITLE;
 top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
 ?>
 <link rel="stylesheet" href="css/pos.css.php?a=xxx">
@@ -169,10 +169,10 @@ $( document ).ready(function() {
 <body style="overflow: hidden">
 <?php if ($user->admin) {?>
 <div style="position: absolute; left: 0.1%; top: 0.8%; width:8%; height:11%;">
-    <?php if ($mode=="edit"){?>
-<a id="add" onclick="window.location.href='floors.php?mode=edit&action=add&floor=<?php echo $floor;?>';"><?php echo $langs->trans("AddTable"); ?></a>
+    <?php if ($mode == "edit") {?>
+<a id="add" onclick="window.location.href='floors.php?mode=edit&action=add&floor=<?php echo $floor; ?>';"><?php echo $langs->trans("AddTable"); ?></a>
     <?php } else { ?>
-<a onclick="window.location.href='floors.php?mode=edit&floor=<?php echo $floor;?>';"><?php echo $langs->trans("Edit"); ?></a>
+<a onclick="window.location.href='floors.php?mode=edit&floor=<?php echo $floor; ?>';"><?php echo $langs->trans("Edit"); ?></a>
     <?php } ?>
 </div>
 <?php }

+ 8 - 8
htdocs/takepos/freezone.php

@@ -25,17 +25,17 @@
 //if (! defined('NOREQUIREDB'))		define('NOREQUIREDB','1');		// Not disabled cause need to load personalized language
 //if (! defined('NOREQUIRESOC'))		define('NOREQUIRESOC','1');
 //if (! defined('NOREQUIRETRAN'))		define('NOREQUIRETRAN','1');
-if (! defined('NOCSRFCHECK'))		define('NOCSRFCHECK', '1');
-if (! defined('NOTOKENRENEWAL'))	define('NOTOKENRENEWAL', '1');
-if (! defined('NOREQUIREMENU'))		define('NOREQUIREMENU', '1');
-if (! defined('NOREQUIREHTML'))		define('NOREQUIREHTML', '1');
-if (! defined('NOREQUIREAJAX'))		define('NOREQUIREAJAX', '1');
+if (!defined('NOCSRFCHECK'))		define('NOCSRFCHECK', '1');
+if (!defined('NOTOKENRENEWAL'))	define('NOTOKENRENEWAL', '1');
+if (!defined('NOREQUIREMENU'))		define('NOREQUIREMENU', '1');
+if (!defined('NOREQUIREHTML'))		define('NOREQUIREHTML', '1');
+if (!defined('NOREQUIREAJAX'))		define('NOREQUIREAJAX', '1');
 
-require '../main.inc.php';	// Load $user and permissions
+require '../main.inc.php'; // Load $user and permissions
 
 $langs->loadLangs(array("bills", "cashdesk"));
 
-$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0);   // $place is id of table for Ba or Restaurant
+$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant
 
 $idline = GETPOST('idline', 'int');
 $action = GETPOST('action', 'alpha');
@@ -46,7 +46,7 @@ $action = GETPOST('action', 'alpha');
  */
 
 $arrayofcss = array('/takepos/css/pos.css.php');
-$arrayofjs=array();
+$arrayofjs = array();
 
 top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
 

+ 1 - 1
htdocs/takepos/pay.php

@@ -68,7 +68,7 @@ else
 }
 
 $arrayofcss = array('/takepos/css/pos.css.php');
-$arrayofjs=array();
+$arrayofjs = array();
 
 top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
 

+ 13 - 13
htdocs/takepos/receipt.php

@@ -135,11 +135,11 @@ if ($conf->global->TAKEPOS_CUSTOM_RECEIPT && $conf->global->TAKEPOS_SHOW_CUSTOME
     <tr>
         <td>
 		<?php if (!empty($line->product_label)) echo $line->product_label;
-        else echo $line->description;?>
+        else echo $line->description; ?>
         </td>
-        <td class="right"><?php echo $line->qty;?></td>
-        <td class="right"><?php echo price(price2num($line->total_ttc / $line->qty, 'MT'), 1);?></td>
-        <td class="right"><?php echo price($line->total_ttc, 1);?></td>
+        <td class="right"><?php echo $line->qty; ?></td>
+        <td class="right"><?php echo price(price2num($line->total_ttc / $line->qty, 'MT'), 1); ?></td>
+        <td class="right"><?php echo price($line->total_ttc, 1); ?></td>
     </tr>
         <?php
     }
@@ -149,33 +149,33 @@ if ($conf->global->TAKEPOS_CUSTOM_RECEIPT && $conf->global->TAKEPOS_SHOW_CUSTOME
 <br>
 <table class="right">
 <tr>
-    <th class="right"><?php echo $langs->trans("TotalHT");?></th>
-    <td class="right"><?php echo price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency)."\n";?></td>
+    <th class="right"><?php echo $langs->trans("TotalHT"); ?></th>
+    <td class="right"><?php echo price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
 </tr>
-<?php if($conf->global->TAKEPOS_TICKET_VAT_GROUPPED) {
+<?php if ($conf->global->TAKEPOS_TICKET_VAT_GROUPPED) {
 	$vat_groups = array();
 	foreach ($object->lines as $line)
 	{
-		if(!array_key_exists($line->tva_tx, $vat_groups)) {
+		if (!array_key_exists($line->tva_tx, $vat_groups)) {
 			$vat_groups[$line->tva_tx] = 0;
 		}
 		$vat_groups[$line->tva_tx] += $line->total_tva;
 	}
-	foreach($vat_groups as $key => $val) {
+	foreach ($vat_groups as $key => $val) {
 	    ?>
 	<tr>
-		<th align="right"><?php echo $langs->trans("VAT").' '.vatrate($key, 1);?></th>
-		<td align="right"><?php echo price($val, 1, '', 1, - 1, - 1, $conf->currency)."\n";?></td>
+		<th align="right"><?php echo $langs->trans("VAT").' '.vatrate($key, 1); ?></th>
+		<td align="right"><?php echo price($val, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
 	</tr>
         <?php
 	}
 } else { ?>
 <tr>
-	<th class="right"><?php echo $langs->trans("TotalVAT").'</th><td class="right">'.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency)."\n";?></td>
+	<th class="right"><?php echo $langs->trans("TotalVAT").'</th><td class="right">'.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
 </tr>
 <?php } ?>
 <tr>
-	<th class="right"><?php echo ''.$langs->trans("TotalTTC").'</th><td class="right">'.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency)."\n";?></td>
+	<th class="right"><?php echo ''.$langs->trans("TotalTTC").'</th><td class="right">'.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
 </tr>
 </table>
 <div style="border-top-style: double;">

+ 22 - 22
htdocs/takepos/takepos.php

@@ -565,7 +565,7 @@ function OpenDrawer(){
 	console.log("OpenDrawer");
 	$.ajax({
 		type: "POST",
-		url: 'http://<?php print $conf->global->TAKEPOS_PRINT_SERVER;?>:8111/print',
+		url: 'http://<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>:8111/print',
 		data: "opendrawer"
 	});
 }
@@ -667,10 +667,10 @@ if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
 			<a onclick="Customer();"><?php echo $langs->trans("Customer"); ?></a>
 			</div>
 			<div class="topnav-right">
-				<input type="text" id="search" name="search" onkeyup="Search2();"  placeholder="<?php echo $langs->trans("Search");?>" autofocus>
+				<input type="text" id="search" name="search" onkeyup="Search2();"  placeholder="<?php echo $langs->trans("Search"); ?>" autofocus>
 				<a onclick="ClearSearch();"><span class="fa fa-backspace"></span></a>
-				<a onclick="window.location.href='<?php echo DOL_URL_ROOT;?>';"><span class="fas fa-sign-out-alt"></span></a>
-				<a onclick="window.location.href='<?php echo DOL_URL_ROOT;?>/user/logout.php';"><span class="fas fa-user"></span></a>
+				<a onclick="window.location.href='<?php echo DOL_URL_ROOT; ?>';"><span class="fas fa-sign-out-alt"></span></a>
+				<a onclick="window.location.href='<?php echo DOL_URL_ROOT; ?>/user/logout.php';"><span class="fas fa-user"></span></a>
 				<a onclick="FullScreen();"><span class="fa fa-expand-arrows-alt"></span></a>
 			</div>
 		</div>
@@ -679,7 +679,7 @@ if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
 }
 ?>
 
-	<div class="row1<?php if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) print 'withhead';?>">
+	<div class="row1<?php if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) print 'withhead'; ?>">
 
 		<div id="poslines" class="div1">
 		</div>
@@ -747,7 +747,7 @@ else
     $menus[$r++] = array('title'=>'<span class="fa fa-layer-group paddingrightonly"></span><div class="trunc">'.$langs->trans("Place").'</div>', 'action'=>'Floors();');
 }
 
-if (! empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
+if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
 	$menus[$r++] = array('title'=>'<span class="far fa-building paddingrightonly"></span><div class="trunc">'.$langs->trans("Customer").'</div>', 'action'=>'Customer();');
 }
 $menus[$r++] = array('title'=>'<span class="fa fa-history paddingrightonly"></span><div class="trunc">'.$langs->trans("History").'</div>', 'action'=>'History();');
@@ -763,29 +763,29 @@ if ($conf->global->TAKEPOS_BAR_RESTAURANT)
 {
 	if ($conf->global->TAKEPOS_ORDER_PRINTERS)
 	{
-		$menus[$r++]=array('title'=>$langs->trans("Order"), 'action'=>'TakeposPrintingOrder();');
+		$menus[$r++] = array('title'=>$langs->trans("Order"), 'action'=>'TakeposPrintingOrder();');
 	}
 	//add temp ticket button
 	if ($conf->global->TAKEPOS_BAR_RESTAURANT)
 	{
 	    if ($conf->global->TAKEPOSCONNECTOR) {
-			$menus[$r++]=array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>','action'=>'TakeposPrinting(placeid);');
+			$menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>', 'action'=>'TakeposPrinting(placeid);');
 		} else {
-			$menus[$r++]=array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>','action'=>'Print(placeid);');
+			$menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("Receipt").'</div>', 'action'=>'Print(placeid);');
 		}
 	}
-	if ($conf->global->TAKEPOSCONNECTOR && $conf->global->TAKEPOS_ORDER_NOTES==1)
+	if ($conf->global->TAKEPOSCONNECTOR && $conf->global->TAKEPOS_ORDER_NOTES == 1)
 	{
-	    $menus[$r++]=array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("OrderNotes").'</div>', 'action'=>'TakeposOrderNotes();');
+	    $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("OrderNotes").'</div>', 'action'=>'TakeposOrderNotes();');
 	}
 	if ($conf->global->TAKEPOS_SUPPLEMENTS)
 	{
-	    $menus[$r++]=array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("ProductSupplements").'</div>', 'action'=>'LoadProducts(\'supplements\');');
+	    $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("ProductSupplements").'</div>', 'action'=>'LoadProducts(\'supplements\');');
 	}
 }
 
 if ($conf->global->TAKEPOSCONNECTOR) {
-    $menus[$r++]=array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("DOL_OPEN_DRAWER").'</div>', 'action'=>'OpenDrawer();');
+    $menus[$r++] = array('title'=>'<span class="fa fa-receipt paddingrightonly"></span><div class="trunc">'.$langs->trans("DOL_OPEN_DRAWER").'</div>', 'action'=>'OpenDrawer();');
 }
 if ($conf->global->TAKEPOS_DOLIBARR_PRINTER) {
     $menus[$r++] = array(
@@ -795,17 +795,17 @@ if ($conf->global->TAKEPOS_DOLIBARR_PRINTER) {
 }
 
 $hookmanager->initHooks(array('takeposfrontend'));
-$reshook=$hookmanager->executeHooks('ActionButtons');
+$reshook = $hookmanager->executeHooks('ActionButtons');
 if (!empty($reshook)) {
-    $menus[$r++]=$reshook;
+    $menus[$r++] = $reshook;
 }
 
-if ($r % 3 == 2) $menus[$r++]=array('title'=>'', 'style'=>'visibility: hidden;');
+if ($r % 3 == 2) $menus[$r++] = array('title'=>'', 'style'=>'visibility: hidden;');
 
-$menus[$r++]=array('title'=>'<span class="fa fa-home paddingrightonly"></span><div class="trunc">'.$langs->trans("BackOffice").'</div>', 'action'=>'window.open(\''.(DOL_URL_ROOT ? DOL_URL_ROOT : '/').'\', \'_backoffice\');');
+$menus[$r++] = array('title'=>'<span class="fa fa-home paddingrightonly"></span><div class="trunc">'.$langs->trans("BackOffice").'</div>', 'action'=>'window.open(\''.(DOL_URL_ROOT ? DOL_URL_ROOT : '/').'\', \'_backoffice\');');
 
-if (! empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
-	$menus[$r++]=array('title'=>'<span class="fa fa-sign-out-alt paddingrightonly"></span><div class="trunc">'.$langs->trans("Logout").'</div>', 'action'=>'window.location.href=\''.DOL_URL_ROOT.'/user/logout.php\';');
+if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
+	$menus[$r++] = array('title'=>'<span class="fa fa-sign-out-alt paddingrightonly"></span><div class="trunc">'.$langs->trans("Logout").'</div>', 'action'=>'window.location.href=\''.DOL_URL_ROOT.'/user/logout.php\';');
 }
 
 ?>
@@ -813,7 +813,7 @@ if (! empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
 		<div class="div3">
 		<?php
         $i = 0;
-        foreach($menus as $menu)
+        foreach ($menus as $menu)
         {
         	$i++;
         	if (count($menus) > 9 and $i == 9)
@@ -825,7 +825,7 @@ if (! empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
             else echo '<button style="'.$menu['style'].'" type="button" id="action'.$i.'" class="actionbutton" onclick="'.$menu['action'].'">'.$menu['title'].'</button>';
         }
 
-		if (! empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
+		if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
 			print '<!-- Show the search input text -->'."\n";
 			print '<div class="margintoponly">';
 			print '<input type="text" id="search" name="search" onkeyup="Search2();" style="width:80%;width:calc(100% - 51px);font-size: 150%;" placeholder="'.$langs->trans("Search").'" autofocus> ';
@@ -836,7 +836,7 @@ if (! empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
 		</div>
 	</div>
 
-	<div class="row2<?php if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) print 'withhead';?>">
+	<div class="row2<?php if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) print 'withhead'; ?>">
 
 		<!--  Show categories -->
 		<div class="div4">

+ 6 - 6
htdocs/theme/eldy/info-box.inc.php

@@ -1,5 +1,5 @@
 <?php
-if (! defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?>
+if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?>
 /* <style type="text/css" > */
 
 /*
@@ -92,7 +92,7 @@ if (! defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?>
     transition: opacity 0.5s, visibility 0s 0.5s;
 }
 
-<?php if(empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS) && !empty($conf->global->MAIN_INCLUDE_GLOBAL_STATS_IN_OPENED_DASHBOARD)){ ?>
+<?php if (empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS) && !empty($conf->global->MAIN_INCLUDE_GLOBAL_STATS_IN_OPENED_DASHBOARD)) { ?>
 .info-box-icon-text{
     opacity: 1;
 }
@@ -152,12 +152,12 @@ a.info-box-text{ text-decoration: none;}
 <?php
 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
 
-$prefix='';
+$prefix = '';
 //$prefix = 'background-';
-if (! empty($conf->global->THEME_INFOBOX_COLOR_ON_BACKGROUND)) $prefix = 'background-';
+if (!empty($conf->global->THEME_INFOBOX_COLOR_ON_BACKGROUND)) $prefix = 'background-';
 
-if (! isset($conf->global->THEME_AGRESSIVENESS_RATIO) && $prefix) $conf->global->THEME_AGRESSIVENESS_RATIO=-50;
-if (GETPOSTISSET('THEME_AGRESSIVENESS_RATIO')) $conf->global->THEME_AGRESSIVENESS_RATIO=GETPOST('THEME_AGRESSIVENESS_RATIO', 'int');
+if (!isset($conf->global->THEME_AGRESSIVENESS_RATIO) && $prefix) $conf->global->THEME_AGRESSIVENESS_RATIO = -50;
+if (GETPOSTISSET('THEME_AGRESSIVENESS_RATIO')) $conf->global->THEME_AGRESSIVENESS_RATIO = GETPOST('THEME_AGRESSIVENESS_RATIO', 'int');
 //var_dump($conf->global->THEME_AGRESSIVENESS_RATIO);
 ?>
 .info-box-icon {

+ 49 - 49
htdocs/user/home.php

@@ -25,9 +25,9 @@
 require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
 
-$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'userhome';   // To manage different context of search
+$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'userhome'; // To manage different context of search
 
-if (! $user->rights->user->user->lire && ! $user->admin)
+if (!$user->rights->user->user->lire && !$user->admin)
 {
 	// Redirection vers la page de l'utilisateur
 	header("Location: card.php?id=".$user->id);
@@ -37,14 +37,14 @@ if (! $user->rights->user->user->lire && ! $user->admin)
 // Load translation files required by page
 $langs->load("users");
 
-$canreadperms=true;
-if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS))
+$canreadperms = true;
+if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS))
 {
-	$canreadperms=($user->admin || $user->rights->user->group_advance->read);
+	$canreadperms = ($user->admin || $user->rights->user->group_advance->read);
 }
 
 // Security check (for external users)
-$socid=0;
+$socid = 0;
 if ($user->socid > 0) $socid = $user->socid;
 
 $companystatic = new Societe($db);
@@ -94,33 +94,33 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
 /*
  * Last created users
  */
-$max=10;
+$max = 10;
 
 $sql = "SELECT DISTINCT u.rowid, u.lastname, u.firstname, u.admin, u.login, u.fk_soc, u.datec, u.statut";
-$sql.= ", u.entity";
-$sql.= ", u.ldap_sid";
-$sql.= ", u.photo";
-$sql.= ", u.admin";
-$sql.= ", u.email";
-$sql.= ", u.skype";
-$sql.= ", s.nom as name";
-$sql.= ", s.code_client";
-$sql.= ", s.canvas";
-$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_soc = s.rowid";
+$sql .= ", u.entity";
+$sql .= ", u.ldap_sid";
+$sql .= ", u.photo";
+$sql .= ", u.admin";
+$sql .= ", u.email";
+$sql .= ", u.skype";
+$sql .= ", s.nom as name";
+$sql .= ", s.code_client";
+$sql .= ", s.canvas";
+$sql .= " FROM ".MAIN_DB_PREFIX."user as u";
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_soc = s.rowid";
 // Add fields from hooks
-$parameters=array();
-$reshook=$hookmanager->executeHooks('printUserListWhere', $parameters);    // Note that $action and $object may have been modified by hook
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
 if ($reshook > 0) {
-	$sql.=$hookmanager->resPrint;
+	$sql .= $hookmanager->resPrint;
 } else {
-	$sql.= " WHERE u.entity IN (".getEntity('user').")";
+	$sql .= " WHERE u.entity IN (".getEntity('user').")";
 }
-if (!empty($socid)) $sql.= " AND u.fk_soc = ".$socid;
-$sql.= $db->order("u.datec", "DESC");
-$sql.= $db->plimit($max);
+if (!empty($socid)) $sql .= " AND u.fk_soc = ".$socid;
+$sql .= $db->order("u.datec", "DESC");
+$sql .= $db->plimit($max);
 
-$resql=$db->query($sql);
+$resql = $db->query($sql);
 if ($resql)
 {
 	$num = $db->num_rows($resql);
@@ -148,15 +148,15 @@ if ($resql)
 		$fuserstatic->skype = $obj->skype;
 		$fuserstatic->socid = $obj->fk_soc;
 
-		$companystatic->id=$obj->fk_soc;
-		$companystatic->name=$obj->name;
+		$companystatic->id = $obj->fk_soc;
+		$companystatic->name = $obj->name;
 		$companystatic->code_client = $obj->code_client;
-		$companystatic->canvas=$obj->canvas;
+		$companystatic->canvas = $obj->canvas;
 
 		print '<tr class="oddeven">';
 		print '<td class="nowraponall">';
         print $fuserstatic->getNomUrl(-1);
-		if (! empty($conf->multicompany->enabled) && $obj->admin && ! $obj->entity)
+		if (!empty($conf->multicompany->enabled) && $obj->admin && !$obj->entity)
 		{
 			print img_picto($langs->trans("SuperAdministrator"), 'redstar');
 		}
@@ -180,22 +180,22 @@ if ($resql)
 			print ' ('.$langs->trans("DomainUser").')';
 		}
 
-		$entity=$obj->entity;
-		$entitystring='';
+		$entity = $obj->entity;
+		$entitystring = '';
         // TODO Set of entitystring should be done with a hook
-		if (! empty($conf->multicompany->enabled) && is_object($mc))
+		if (!empty($conf->multicompany->enabled) && is_object($mc))
 		{
 			if (empty($entity))
 			{
-				$entitystring=$langs->trans("AllEntities");
+				$entitystring = $langs->trans("AllEntities");
 			}
 			else
 			{
 				$mc->getInfo($entity);
-				$entitystring=$mc->label;
+				$entitystring = $mc->label;
 			}
 		}
-        print ($entitystring?' ('.$entitystring.')':'');
+        print ($entitystring ? ' ('.$entitystring.')' : '');
 
 		print '</td>';
 		print '<td class="center nowrap">'.dol_print_date($db->jdate($obj->datec), 'dayhour').'</td>';
@@ -222,26 +222,26 @@ else
  */
 if ($canreadperms)
 {
-	$max=5;
+	$max = 5;
 
 	$sql = "SELECT g.rowid, g.nom as name, g.note, g.entity, g.datec";
-	$sql.= " FROM ".MAIN_DB_PREFIX."usergroup as g";
-	if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && ! $user->entity)))
+	$sql .= " FROM ".MAIN_DB_PREFIX."usergroup as g";
+	if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->global->MULTICOMPANY_TRANSVERSE_MODE || ($user->admin && !$user->entity)))
 	{
-		$sql.= " WHERE g.entity IS NOT NULL";
+		$sql .= " WHERE g.entity IS NOT NULL";
 	}
 	else
 	{
-		$sql.= " WHERE g.entity IN (0,".$conf->entity.")";
+		$sql .= " WHERE g.entity IN (0,".$conf->entity.")";
 	}
-	$sql.= $db->order("g.datec", "DESC");
-	$sql.= $db->plimit($max);
+	$sql .= $db->order("g.datec", "DESC");
+	$sql .= $db->plimit($max);
 
-	$resql=$db->query($sql);
+	$resql = $db->query($sql);
 	if ($resql)
 	{
-		$colspan=1;
-		if (! empty($conf->multicompany->enabled)) $colspan++;
+		$colspan = 1;
+		if (!empty($conf->multicompany->enabled)) $colspan++;
 		$num = $db->num_rows($resql);
 
 		print '<div class="div-table-responsive-no-min">';
@@ -253,7 +253,7 @@ if ($canreadperms)
 
 		$grouptemp = new UserGroup($db);
 
-		while ($i < $num && (! $max || $i < $max))
+		while ($i < $num && (!$max || $i < $max))
 		{
 			$obj = $db->fetch_object($resql);
 
@@ -264,12 +264,12 @@ if ($canreadperms)
 			print '<tr class="oddeven">';
 			print '<td>';
 			print $grouptemp->getNomUrl(1);
-			if (! $obj->entity)
+			if (!$obj->entity)
 			{
 				print img_picto($langs->trans("GlobalGroup"), 'redstar');
 			}
 			print "</td>";
-			if (! empty($conf->multicompany->enabled) && is_object($mc))
+			if (!empty($conf->multicompany->enabled) && is_object($mc))
 			{
 	        	$mc->getInfo($obj->entity);
 	        	print '<td>';

+ 139 - 139
htdocs/user/list.php

@@ -27,21 +27,21 @@
 
 require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
-if (! empty($conf->categorie->enabled)) {
+if (!empty($conf->categorie->enabled)) {
 	require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
 }
 
-if (! $user->rights->user->user->lire && ! $user->admin) {
+if (!$user->rights->user->user->lire && !$user->admin) {
 	accessforbidden();
 }
 
 // Load translation files required by page
 $langs->loadLangs(array('users', 'companies', 'hrm'));
 
-$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'userlist';   // To manage different context of search
+$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'userlist'; // To manage different context of search
 
 // Security check (for external users)
-$socid=0;
+$socid = 0;
 if ($user->socid > 0) {
 	$socid = $user->socid;
 }
@@ -113,36 +113,36 @@ $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');
 $arrayfields = dol_sort_array($arrayfields, 'position');
 
 // Init search fields
-$sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml'));
-$search_user=GETPOST('search_user', 'alpha');
-$search_login=GETPOST('search_login', 'alpha');
-$search_lastname=GETPOST('search_lastname', 'alpha');
-$search_firstname=GETPOST('search_firstname', 'alpha');
-$search_gender=GETPOST('search_gender', 'alpha');
-$search_employee=GETPOST('search_employee', 'alpha');
-$search_accountancy_code=GETPOST('search_accountancy_code', 'alpha');
-$search_email=GETPOST('search_email', 'alpha');
-$search_api_key=GETPOST('search_api_key', 'alphanohtml');
-$search_statut=GETPOST('search_statut', 'intcomma');
-$search_thirdparty=GETPOST('search_thirdparty', 'alpha');
-$search_supervisor=GETPOST('search_supervisor', 'intcomma');
+$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
+$search_user = GETPOST('search_user', 'alpha');
+$search_login = GETPOST('search_login', 'alpha');
+$search_lastname = GETPOST('search_lastname', 'alpha');
+$search_firstname = GETPOST('search_firstname', 'alpha');
+$search_gender = GETPOST('search_gender', 'alpha');
+$search_employee = GETPOST('search_employee', 'alpha');
+$search_accountancy_code = GETPOST('search_accountancy_code', 'alpha');
+$search_email = GETPOST('search_email', 'alpha');
+$search_api_key = GETPOST('search_api_key', 'alphanohtml');
+$search_statut = GETPOST('search_statut', 'intcomma');
+$search_thirdparty = GETPOST('search_thirdparty', 'alpha');
+$search_supervisor = GETPOST('search_supervisor', 'intcomma');
 $optioncss = GETPOST('optioncss', 'alpha');
 $search_categ = GETPOST("search_categ", 'int');
 $catid = GETPOST('catid', 'int');
 
 // Default search
-if ($search_statut == '') $search_statut='1';
-if ($mode == 'employee' && ! GETPOSTISSET('search_employee')) $search_employee=1;
+if ($search_statut == '') $search_statut = '1';
+if ($mode == 'employee' && !GETPOSTISSET('search_employee')) $search_employee = 1;
 
 
 
@@ -191,78 +191,78 @@ if (empty($reshook))
  * View
  */
 
-$htmlother=new FormOther($db);
+$htmlother = new FormOther($db);
 
-$user2=new User($db);
+$user2 = new User($db);
 
-$buttonviewhierarchy='<form action="'.DOL_URL_ROOT.'/user/hierarchy.php'.(($search_statut != '' && $search_statut >= 0) ? '?search_statut='.$search_statut : '').'" method="POST"><input type="submit" class="button" style="width:120px" name="viewcal" value="'.dol_escape_htmltag($langs->trans("HierarchicView")).'"></form>';
+$buttonviewhierarchy = '<form action="'.DOL_URL_ROOT.'/user/hierarchy.php'.(($search_statut != '' && $search_statut >= 0) ? '?search_statut='.$search_statut : '').'" method="POST"><input type="submit" class="button" style="width:120px" name="viewcal" value="'.dol_escape_htmltag($langs->trans("HierarchicView")).'"></form>';
 
 $sql = "SELECT DISTINCT u.rowid, u.lastname, u.firstname, u.admin, u.fk_soc, u.login, u.email, u.api_key, u.accountancy_code, u.gender, u.employee, u.photo,";
-$sql.= " u.datelastlogin, u.datepreviouslogin,";
-$sql.= " u.ldap_sid, u.statut, u.entity,";
-$sql.= " u.tms as date_update, u.datec as date_creation,";
-$sql.= " u2.rowid as id2, u2.login as login2, u2.firstname as firstname2, u2.lastname as lastname2, u2.admin as admin2, u2.fk_soc as fk_soc2, u2.email as email2, u2.gender as gender2, u2.photo as photo2, u2.entity as entity2,";
-$sql.= " s.nom as name, s.canvas";
+$sql .= " u.datelastlogin, u.datepreviouslogin,";
+$sql .= " u.ldap_sid, u.statut, u.entity,";
+$sql .= " u.tms as date_update, u.datec as date_creation,";
+$sql .= " u2.rowid as id2, u2.login as login2, u2.firstname as firstname2, u2.lastname as lastname2, u2.admin as admin2, u2.fk_soc as fk_soc2, u2.email as email2, u2.gender as gender2, u2.photo as photo2, u2.entity as entity2,";
+$sql .= " s.nom as name, s.canvas";
 // Add fields from extrafields
-if (! empty($extrafields->attributes[$object->table_element]['label'])) {
-	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
+if (!empty($extrafields->attributes[$object->table_element]['label'])) {
+	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
 }
 // Add fields from hooks
-$parameters=array();
-$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters);    // Note that $action and $object may have been modified by hook
-$sql.=$hookmanager->resPrint;
-$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
-if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (u.rowid = ef.fk_object)";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_soc = s.rowid";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u2 ON u.fk_user = u2.rowid";
-if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_user as cu ON u.rowid = cu.fk_user"; // We'll need this table joined to the select in order to filter by categ
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
+$sql .= $hookmanager->resPrint;
+$sql .= " FROM ".MAIN_DB_PREFIX."user as u";
+if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (u.rowid = ef.fk_object)";
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_soc = s.rowid";
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u2 ON u.fk_user = u2.rowid";
+if (!empty($search_categ) || !empty($catid)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_user as cu ON u.rowid = cu.fk_user"; // We'll need this table joined to the select in order to filter by categ
 // Add fields from hooks
-$parameters=array();
-$reshook=$hookmanager->executeHooks('printUserListWhere', $parameters);    // Note that $action and $object may have been modified by hook
+$parameters = array();
+$reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
 if ($reshook > 0) {
-	$sql.=$hookmanager->resPrint;
+	$sql .= $hookmanager->resPrint;
 } else {
-	$sql.= " WHERE u.entity IN (".getEntity('user').")";
+	$sql .= " WHERE u.entity IN (".getEntity('user').")";
 }
-if ($socid > 0) $sql.= " AND u.fk_soc = ".$socid;
+if ($socid > 0) $sql .= " AND u.fk_soc = ".$socid;
 //if ($search_user != '')       $sql.=natural_search(array('u.login', 'u.lastname', 'u.firstname'), $search_user);
-if ($search_supervisor > 0)   $sql.= " AND u.fk_user IN (".$db->escape($search_supervisor).")";
-if ($search_thirdparty != '') $sql.= natural_search(array('s.nom'), $search_thirdparty);
-if ($search_login != '')      $sql.= natural_search("u.login", $search_login);
-if ($search_lastname != '')   $sql.= natural_search("u.lastname", $search_lastname);
-if ($search_firstname != '')  $sql.= natural_search("u.firstname", $search_firstname);
-if ($search_gender != '' && $search_gender != '-1')     $sql.= " AND u.gender = '".$search_gender."'";
-if (is_numeric($search_employee) && $search_employee >= 0)    {
+if ($search_supervisor > 0)   $sql .= " AND u.fk_user IN (".$db->escape($search_supervisor).")";
+if ($search_thirdparty != '') $sql .= natural_search(array('s.nom'), $search_thirdparty);
+if ($search_login != '')      $sql .= natural_search("u.login", $search_login);
+if ($search_lastname != '')   $sql .= natural_search("u.lastname", $search_lastname);
+if ($search_firstname != '')  $sql .= natural_search("u.firstname", $search_firstname);
+if ($search_gender != '' && $search_gender != '-1')     $sql .= " AND u.gender = '".$search_gender."'";
+if (is_numeric($search_employee) && $search_employee >= 0) {
 	$sql .= ' AND u.employee = '.(int) $search_employee;
 }
-if ($search_accountancy_code != '')  $sql.= natural_search("u.accountancy_code", $search_accountancy_code);
-if ($search_email != '')             $sql.= natural_search("u.email", $search_email);
-if ($search_api_key != '')           $sql.= natural_search("u.api_key", $search_api_key);
-if ($search_statut != '' && $search_statut >= 0) $sql.= " AND u.statut IN (".$db->escape($search_statut).")";
-if ($sall)                           $sql.= natural_search(array_keys($fieldstosearchall), $sall);
-if ($catid > 0)     $sql.= " AND cu.fk_categorie = ".$catid;
-if ($catid == -2)   $sql.= " AND cu.fk_categorie IS NULL";
-if ($search_categ > 0)   $sql.= " AND cu.fk_categorie = ".$db->escape($search_categ);
-if ($search_categ == -2) $sql.= " AND cu.fk_categorie IS NULL";
+if ($search_accountancy_code != '')  $sql .= natural_search("u.accountancy_code", $search_accountancy_code);
+if ($search_email != '')             $sql .= natural_search("u.email", $search_email);
+if ($search_api_key != '')           $sql .= natural_search("u.api_key", $search_api_key);
+if ($search_statut != '' && $search_statut >= 0) $sql .= " AND u.statut IN (".$db->escape($search_statut).")";
+if ($sall)                           $sql .= natural_search(array_keys($fieldstosearchall), $sall);
+if ($catid > 0)     $sql .= " AND cu.fk_categorie = ".$catid;
+if ($catid == -2)   $sql .= " AND cu.fk_categorie IS NULL";
+if ($search_categ > 0)   $sql .= " AND cu.fk_categorie = ".$db->escape($search_categ);
+if ($search_categ == -2) $sql .= " AND cu.fk_categorie IS NULL";
 // 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;
-$sql.=$db->order($sortfield, $sortorder);
+$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);
 
-$nbtotalofrecords=0;
-$result=$db->query($sql);
+$nbtotalofrecords = 0;
+$result = $db->query($sql);
 if ($result)
 {
 	$nbtotalofrecords = $db->num_rows($result);
 }
 
-$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;
@@ -468,60 +468,60 @@ print "</tr>\n";
 
 
 print '<tr class="liste_titre">';
-if (! empty($arrayfields['u.login']['checked']))          print_liste_field_titre("Login", $_SERVER['PHP_SELF'], "u.login", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.lastname']['checked']))       print_liste_field_titre("Lastname", $_SERVER['PHP_SELF'], "u.lastname", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.firstname']['checked']))      print_liste_field_titre("FirstName", $_SERVER['PHP_SELF'], "u.firstname", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.gender']['checked']))         print_liste_field_titre("Gender", $_SERVER['PHP_SELF'], "u.gender", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.employee']['checked']))       print_liste_field_titre("Employee", $_SERVER['PHP_SELF'], "u.employee", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.accountancy_code']['checked'])) print_liste_field_titre("AccountancyCode", $_SERVER['PHP_SELF'], "u.accountancy_code", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.email']['checked']))          print_liste_field_titre("EMail", $_SERVER['PHP_SELF'], "u.email", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.api_key']['checked']))        print_liste_field_titre("ApiKey", $_SERVER['PHP_SELF'], "u.api_key", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.fk_soc']['checked']))         print_liste_field_titre("Company", $_SERVER['PHP_SELF'], "u.fk_soc", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.entity']['checked']))         print_liste_field_titre("Entity", $_SERVER['PHP_SELF'], "u.entity", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.fk_user']['checked']))        print_liste_field_titre("HierarchicalResponsible", $_SERVER['PHP_SELF'], "u.fk_user", $param, "", "", $sortfield, $sortorder);
-if (! empty($arrayfields['u.datelastlogin']['checked']))  print_liste_field_titre("LastConnexion", $_SERVER['PHP_SELF'], "u.datelastlogin", $param, "", '', $sortfield, $sortorder, 'center ');
-if (! empty($arrayfields['u.datepreviouslogin']['checked'])) print_liste_field_titre("PreviousConnexion", $_SERVER['PHP_SELF'], "u.datepreviouslogin", $param, "", '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['u.login']['checked']))          print_liste_field_titre("Login", $_SERVER['PHP_SELF'], "u.login", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.lastname']['checked']))       print_liste_field_titre("Lastname", $_SERVER['PHP_SELF'], "u.lastname", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.firstname']['checked']))      print_liste_field_titre("FirstName", $_SERVER['PHP_SELF'], "u.firstname", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.gender']['checked']))         print_liste_field_titre("Gender", $_SERVER['PHP_SELF'], "u.gender", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.employee']['checked']))       print_liste_field_titre("Employee", $_SERVER['PHP_SELF'], "u.employee", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.accountancy_code']['checked'])) print_liste_field_titre("AccountancyCode", $_SERVER['PHP_SELF'], "u.accountancy_code", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.email']['checked']))          print_liste_field_titre("EMail", $_SERVER['PHP_SELF'], "u.email", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.api_key']['checked']))        print_liste_field_titre("ApiKey", $_SERVER['PHP_SELF'], "u.api_key", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.fk_soc']['checked']))         print_liste_field_titre("Company", $_SERVER['PHP_SELF'], "u.fk_soc", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.entity']['checked']))         print_liste_field_titre("Entity", $_SERVER['PHP_SELF'], "u.entity", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.fk_user']['checked']))        print_liste_field_titre("HierarchicalResponsible", $_SERVER['PHP_SELF'], "u.fk_user", $param, "", "", $sortfield, $sortorder);
+if (!empty($arrayfields['u.datelastlogin']['checked']))  print_liste_field_titre("LastConnexion", $_SERVER['PHP_SELF'], "u.datelastlogin", $param, "", '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['u.datepreviouslogin']['checked'])) print_liste_field_titre("PreviousConnexion", $_SERVER['PHP_SELF'], "u.datepreviouslogin", $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['u.datec']['checked']))  print_liste_field_titre("DateCreationShort", $_SERVER["PHP_SELF"], "u.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['u.tms']['checked']))    print_liste_field_titre("DateModificationShort", $_SERVER["PHP_SELF"], "u.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
-if (! empty($arrayfields['u.statut']['checked'])) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "u.statut", "", $param, '', $sortfield, $sortorder, 'center ');
+if (!empty($arrayfields['u.datec']['checked']))  print_liste_field_titre("DateCreationShort", $_SERVER["PHP_SELF"], "u.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['u.tms']['checked']))    print_liste_field_titre("DateModificationShort", $_SERVER["PHP_SELF"], "u.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap ');
+if (!empty($arrayfields['u.statut']['checked'])) print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "u.statut", "", $param, '', $sortfield, $sortorder, 'center ');
 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ');
 print "</tr>\n";
 
 
 
 $i = 0;
-$totalarray=array();
+$totalarray = array();
 while ($i < min($num, $limit))
 {
 	$obj = $db->fetch_object($result);
 
-	$userstatic->id=$obj->rowid;
+	$userstatic->id = $obj->rowid;
 	$userstatic->admin = $obj->admin;
-	$userstatic->ref=$obj->label;
-	$userstatic->login=$obj->login;
-	$userstatic->statut=$obj->statut;
-	$userstatic->email=$obj->email;
-	$userstatic->gender=$obj->gender;
-	$userstatic->socid=$obj->fk_soc;
-	$userstatic->firstname=$obj->firstname;
-	$userstatic->lastname=$obj->lastname;
-	$userstatic->employee=$obj->employee;
-	$userstatic->photo=$obj->photo;
-
-	$li=$userstatic->getNomUrl(-1, '', 0, 0, 24, 1, 'login', '', 1);
+	$userstatic->ref = $obj->label;
+	$userstatic->login = $obj->login;
+	$userstatic->statut = $obj->statut;
+	$userstatic->email = $obj->email;
+	$userstatic->gender = $obj->gender;
+	$userstatic->socid = $obj->fk_soc;
+	$userstatic->firstname = $obj->firstname;
+	$userstatic->lastname = $obj->lastname;
+	$userstatic->employee = $obj->employee;
+	$userstatic->photo = $obj->photo;
+
+	$li = $userstatic->getNomUrl(-1, '', 0, 0, 24, 1, 'login', '', 1);
 
 	print "<tr>";
-	if (! empty($arrayfields['u.login']['checked']))
+	if (!empty($arrayfields['u.login']['checked']))
 	{
 		print '<td class="nowraponall">';
 		print $li;
-		if (! empty($conf->multicompany->enabled) && $obj->admin && ! $obj->entity)
+		if (!empty($conf->multicompany->enabled) && $obj->admin && !$obj->entity)
 		{
 		  	print img_picto($langs->trans("SuperAdministrator"), 'redstar', 'class="valignmiddle paddingleft"');
 		}
@@ -530,53 +530,53 @@ while ($i < min($num, $limit))
 			print img_picto($langs->trans("Administrator"), 'star', 'class="valignmiddle paddingleft"');
 		}
 		print '</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['u.lastname']['checked']))
+	if (!empty($arrayfields['u.lastname']['checked']))
 	{
 		  print '<td>'.$obj->lastname.'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['u.firstname']['checked']))
+	if (!empty($arrayfields['u.firstname']['checked']))
 	{
 	    print '<td>'.$obj->firstname.'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['u.gender']['checked']))
+	if (!empty($arrayfields['u.gender']['checked']))
 	{
 	    print '<td>';
 	    if ($obj->gender) print $langs->trans("Gender".$obj->gender);
 	    print '</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['u.employee']['checked']))
+	if (!empty($arrayfields['u.employee']['checked']))
 	{
 	    print '<td>'.yn($obj->employee).'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['u.accountancy_code']['checked']))
+	if (!empty($arrayfields['u.accountancy_code']['checked']))
 	{
 	    print '<td>'.$obj->accountancy_code.'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['u.email']['checked']))
+	if (!empty($arrayfields['u.email']['checked']))
 	{
 	    print '<td>'.$obj->email.'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['u.api_key']['checked']))
+	if (!empty($arrayfields['u.api_key']['checked']))
 	{
 		print '<td>'.$obj->api_key.'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
-	if (! empty($arrayfields['u.fk_soc']['checked']))
+	if (!empty($arrayfields['u.fk_soc']['checked']))
 	{
 		print "<td>";
 		if ($obj->fk_soc)
 		{
-			$companystatic->id=$obj->fk_soc;
-			$companystatic->name=$obj->name;
-			$companystatic->canvas=$obj->canvas;
+			$companystatic->id = $obj->fk_soc;
+			$companystatic->name = $obj->name;
+			$companystatic->canvas = $obj->canvas;
 			print $companystatic->getNomUrl(1);
 		}
 		elseif ($obj->ldap_sid)
@@ -636,62 +636,62 @@ while ($i < min($num, $limit))
 			}
 		}
 		print '</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 
 	// Date last login
-	if (! empty($arrayfields['u.datelastlogin']['checked']))
+	if (!empty($arrayfields['u.datelastlogin']['checked']))
 	{
 		print '<td class="nowrap center">'.dol_print_date($db->jdate($obj->datelastlogin), "dayhour").'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 	// Date previous login
-	if (! empty($arrayfields['u.datepreviouslogin']['checked']))
+	if (!empty($arrayfields['u.datepreviouslogin']['checked']))
 	{
 		print '<td class="nowrap center">'.dol_print_date($db->jdate($obj->datepreviouslogin), "dayhour").'</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 
 	// Extra fields
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
 	// Fields from hook
-	$parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj);
-	$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['u.datec']['checked']))
+	if (!empty($arrayfields['u.datec']['checked']))
 	{
 		print '<td class="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['u.tms']['checked']))
+	if (!empty($arrayfields['u.tms']['checked']))
 	{
 		print '<td class="center">';
 		print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser');
 		print '</td>';
-		if (! $i) $totalarray['nbfield']++;
+		if (!$i) $totalarray['nbfield']++;
 	}
 	// Status
-	if (! empty($arrayfields['u.statut']['checked']))
+	if (!empty($arrayfields['u.statut']['checked']))
 	{
-	    $userstatic->statut=$obj->statut;
+	    $userstatic->statut = $obj->statut;
 	    print '<td class="center">'.$userstatic->getLibStatut(5).'</td>';
-	    if (! $i) $totalarray['nbfield']++;
+	    if (!$i) $totalarray['nbfield']++;
 	}
 	// Action column
 	print '<td></td>';
-	if (! $i) $totalarray['nbfield']++;
+	if (!$i) $totalarray['nbfield']++;
 
 	print "</tr>\n";
 
 	$i++;
 }
 
-$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql);
-$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters);    // Note that $action and $object may have been modified by hook
+$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
+$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook
 print $hookmanager->resPrint;
 
 print "</table>";

Някои файлове не бяха показани, защото твърде много файлове са промени