Browse Source

Scrutinizer Auto-Fixes

This commit consists of patches automatically generated for this project on https://scrutinizer-ci.com
Scrutinizer Auto-Fixer 4 years ago
parent
commit
1512521d91
81 changed files with 14133 additions and 14133 deletions
  1. 20 20
      htdocs/accountancy/admin/defaultaccounts.php
  2. 5 5
      htdocs/accountancy/admin/fiscalyear_card.php
  3. 1 1
      htdocs/accountancy/admin/journals_list.php
  4. 18 18
      htdocs/accountancy/admin/subaccount.php
  5. 159 159
      htdocs/accountancy/class/bookkeeping.class.php
  6. 4 4
      htdocs/accountancy/journal/bankjournal.php
  7. 88 88
      htdocs/adherents/subscription/card.php
  8. 85 85
      htdocs/admin/defaultvalues.php
  9. 609 609
      htdocs/admin/dict.php
  10. 10 10
      htdocs/admin/ecm_directories_extrafields.php
  11. 10 10
      htdocs/admin/ecm_files_extrafields.php
  12. 4 4
      htdocs/admin/menus/index.php
  13. 292 292
      htdocs/admin/oauthlogintokens.php
  14. 331 331
      htdocs/admin/receiptprinter.php
  15. 10 10
      htdocs/admin/security_file.php
  16. 225 225
      htdocs/admin/tools/dolibarr_export.php
  17. 257 257
      htdocs/admin/translation.php
  18. 397 397
      htdocs/admin/website.php
  19. 1859 1859
      htdocs/api/class/api_setup.class.php
  20. 20 20
      htdocs/bom/tpl/objectline_view.tpl.php
  21. 82 82
      htdocs/categories/photos.php
  22. 74 74
      htdocs/categories/traduction.php
  23. 337 337
      htdocs/comm/card.php
  24. 290 290
      htdocs/comm/propal/class/api_proposals.class.php
  25. 6 6
      htdocs/commande/class/api_orders.class.php
  26. 601 601
      htdocs/compta/bank/bankentries_list.php
  27. 404 404
      htdocs/compta/deplacement/card.php
  28. 2 2
      htdocs/contact/list.php
  29. 422 422
      htdocs/core/boxes/box_activity.php
  30. 1066 1066
      htdocs/core/class/commondocgenerator.class.php
  31. 127 127
      htdocs/core/class/hookmanager.class.php
  32. 666 666
      htdocs/core/class/html.formother.class.php
  33. 19 19
      htdocs/core/lib/ecm.lib.php
  34. 2 2
      htdocs/core/lib/files.lib.php
  35. 10 10
      htdocs/core/lib/functions.lib.php
  36. 127 127
      htdocs/core/lib/payments.lib.php
  37. 3 3
      htdocs/core/lib/pdf.lib.php
  38. 18 18
      htdocs/core/modules/modCommande.class.php
  39. 29 29
      htdocs/core/modules/modFournisseur.class.php
  40. 262 262
      htdocs/core/modules/modMrp.class.php
  41. 17 17
      htdocs/core/modules/modPropale.class.php
  42. 34 34
      htdocs/core/modules/modWebServicesClient.class.php
  43. 468 468
      htdocs/core/modules/printing/printgcp.modules.php
  44. 49 49
      htdocs/core/tpl/bloc_comment.tpl.php
  45. 1 1
      htdocs/ecm/class/ecmdirectory.class.php
  46. 91 91
      htdocs/ecm/file_card.php
  47. 2 2
      htdocs/expensereport/class/expensereport.class.php
  48. 271 271
      htdocs/fichinter/card.php
  49. 2 2
      htdocs/fourn/class/fournisseur.facture.class.php
  50. 21 21
      htdocs/fourn/commande/list.php
  51. 276 276
      htdocs/fourn/facture/card.php
  52. 51 51
      htdocs/fourn/facture/document.php
  53. 131 131
      htdocs/hrm/index.php
  54. 550 550
      htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php
  55. 263 263
      htdocs/mrp/mo_card.php
  56. 249 249
      htdocs/product/admin/dynamic_prices.php
  57. 28 28
      htdocs/product/card.php
  58. 1 1
      htdocs/product/class/productcustomerprice.class.php
  59. 429 429
      htdocs/product/price.php
  60. 3 3
      htdocs/product/stock/replenish.php
  61. 2 2
      htdocs/projet/class/project.class.php
  62. 65 65
      htdocs/projet/list.php
  63. 145 145
      htdocs/projet/tasks/task.php
  64. 20 20
      htdocs/resource/card.php
  65. 41 41
      htdocs/resource/list.php
  66. 572 572
      htdocs/societe/card.php
  67. 311 311
      htdocs/societe/notify/card.php
  68. 68 68
      htdocs/societe/paymentmodes.php
  69. 215 215
      htdocs/societe/price.php
  70. 4 4
      htdocs/takepos/index.php
  71. 7 7
      htdocs/takepos/invoice.php
  72. 2 2
      htdocs/takepos/pay.php
  73. 16 16
      htdocs/takepos/receipt.php
  74. 24 24
      htdocs/takepos/send.php
  75. 6 6
      htdocs/user/class/user.class.php
  76. 24 24
      htdocs/user/list.php
  77. 281 281
      htdocs/user/notify/card.php
  78. 71 71
      htdocs/website/class/websitepage.class.php
  79. 267 267
      htdocs/website/index.php
  80. 33 33
      htdocs/website/websiteaccount_card.php
  81. 71 71
      htdocs/zapier/hook_card.php

+ 20 - 20
htdocs/accountancy/admin/defaultaccounts.php

@@ -47,9 +47,9 @@ $action = GETPOST('action', 'aZ09');
 
 
 $list_account_main = array(
-    'ACCOUNTING_ACCOUNT_CUSTOMER',
-    'ACCOUNTING_ACCOUNT_SUPPLIER',
-    'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT',
+	'ACCOUNTING_ACCOUNT_CUSTOMER',
+	'ACCOUNTING_ACCOUNT_SUPPLIER',
+	'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT',
 );
 
 $list_account = array();
@@ -120,9 +120,9 @@ if ($action == 'update') {
 
 		$constvalue = GETPOST($constname, 'alpha');
 
-	    if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) {
-	        $error++;
-	    }
+		if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) {
+			$error++;
+		}
 	}
 
 	if (!$error) {
@@ -159,20 +159,20 @@ print '<table class="noborder centpercent">';
 print '<tr class="liste_titre"><td>'.$langs->trans("ThirdParties").' | '.$langs->trans("Users").'</td><td></td></tr>';
 
 foreach ($list_account_main as $key) {
-    print '<tr class="oddeven value">';
-    // Param
-    $label = $langs->trans($key);
-    $keydesc = $key.'_Desc';
-
-    $htmltext = $langs->trans($keydesc);
-    print '<td class="fieldrequired" width="50%">';
-    print $form->textwithpicto($label, $htmltext);
-    print '</td>';
-    // Value
-    print '<td>'; // Do not force class=right, or it align also the content of the select box
-    print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1);
-    print '</td>';
-    print '</tr>';
+	print '<tr class="oddeven value">';
+	// Param
+	$label = $langs->trans($key);
+	$keydesc = $key.'_Desc';
+
+	$htmltext = $langs->trans($keydesc);
+	print '<td class="fieldrequired" width="50%">';
+	print $form->textwithpicto($label, $htmltext);
+	print '</td>';
+	// Value
+	print '<td>'; // Do not force class=right, or it align also the content of the select box
+	print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1);
+	print '</td>';
+	print '</tr>';
 }
 
 

+ 5 - 5
htdocs/accountancy/admin/fiscalyear_card.php

@@ -300,16 +300,16 @@ if ($action == 'create')
 
 			if (!empty($user->rights->accounting->fiscalyear->write))
 			{
-    			/*
+				/*
     			 * Barre d'actions
     			 */
-    			print '<div class="tabsAction">';
+				print '<div class="tabsAction">';
 
-    			print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&token='.newToken().'&id='.$id.'">'.$langs->trans('Modify').'</a>';
+				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&token='.newToken().'&id='.$id.'">'.$langs->trans('Modify').'</a>';
 
-    			// print '<a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?action=delete&token='.newToken().'&id=' . $id . '">' . $langs->trans('Delete') . '</a>';
+				// print '<a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?action=delete&token='.newToken().'&id=' . $id . '">' . $langs->trans('Delete') . '</a>';
 
-    			print '</div>';
+				print '</div>';
 			}
 		}
 	} else {

+ 1 - 1
htdocs/accountancy/admin/journals_list.php

@@ -22,7 +22,7 @@
  * \brief		Setup page to configure journals
  */
 
-if (!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1');		// Force use of CSRF protection with tokens even for GET
+if (!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET
 
 require '../../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';

+ 18 - 18
htdocs/accountancy/admin/subaccount.php

@@ -59,10 +59,10 @@ if (!$sortfield) $sortfield = "label";
 if (!$sortorder) $sortorder = "ASC";
 
 $arrayfields = array(
-    'subaccount'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1),
-    'label'=>array('label'=>$langs->trans("Label"), 'checked'=>1),
-    'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1),
-    'reconcilable'=>array('label'=>$langs->trans("Reconcilable"), 'checked'=>1)
+	'subaccount'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1),
+	'label'=>array('label'=>$langs->trans("Label"), 'checked'=>1),
+	'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1),
+	'reconcilable'=>array('label'=>$langs->trans("Reconcilable"), 'checked'=>1)
 );
 
 if ($conf->global->MAIN_FEATURES_LEVEL < 2) unset($arrayfields['reconcilable']);
@@ -80,17 +80,17 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
 
 if (empty($reshook))
 {
-    if (!empty($cancel)) $action = '';
+	if (!empty($cancel)) $action = '';
 
-    include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
-    if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
-    {
-    	$search_subaccount = "";
-    	$search_label = "";
-    	$search_type = "";
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers
+	{
+		$search_subaccount = "";
+		$search_label = "";
+		$search_type = "";
 		$search_array_options = array();
-    }
+	}
 }
 
 
@@ -273,13 +273,13 @@ if ($resql)
 	print '<div class="warning">'.$langs->trans("WarningCreateSubAccounts").'</div>';
 
 	$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
-    $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
+	$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
 
-    $moreforfilter = '';
-    $massactionbutton = '';
+	$moreforfilter = '';
+	$massactionbutton = '';
 
-    print '<div class="div-table-responsive">';
-    print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
+	print '<div class="div-table-responsive">';
+	print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
 
 	// Line for search fields
 	print '<tr class="liste_titre_filter">';
@@ -293,7 +293,7 @@ if ($resql)
 	print '</td>';
 	print '</tr>';
 
-    print '<tr class="liste_titre">';
+	print '<tr class="liste_titre">';
 	if (!empty($arrayfields['subaccount']['checked']))	print_liste_field_titre($arrayfields['subaccount']['label'], $_SERVER["PHP_SELF"], "subaccount", "", $param, '', $sortfield, $sortorder);
 	if (!empty($arrayfields['label']['checked']))		print_liste_field_titre($arrayfields['label']['label'], $_SERVER["PHP_SELF"], "label", "", $param, '', $sortfield, $sortorder);
 	if (!empty($arrayfields['type']['checked']))		print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder, 'center ');

+ 159 - 159
htdocs/accountancy/class/bookkeeping.class.php

@@ -57,80 +57,80 @@ class BookKeeping extends CommonObject
 	 */
 	public $id;
 
-    /**
-     * @var string Date of source document, in db date NOT NULL
-     */
+	/**
+	 * @var string Date of source document, in db date NOT NULL
+	 */
 	public $doc_date;
 
-    /**
-     * @var int Deadline for payment
-     */
+	/**
+	 * @var int Deadline for payment
+	 */
 	public $date_lim_reglement;
 
-    /**
-     * @var string doc_type
-     */
-    public $doc_type;
+	/**
+	 * @var string doc_type
+	 */
+	public $doc_type;
 
-    /**
-     * @var string doc_ref
-     */
+	/**
+	 * @var string doc_ref
+	 */
 	public $doc_ref;
 
 	/**
-     * @var int ID
-     */
+	 * @var int ID
+	 */
 	public $fk_doc;
 
 	/**
-     * @var int ID
-     */
+	 * @var int ID
+	 */
 	public $fk_docdet;
 
-    /**
-     * @var string thirdparty code
-     */
-    public $thirdparty_code;
+	/**
+	 * @var string thirdparty code
+	 */
+	public $thirdparty_code;
 
-    /**
-     * @var string subledger account
-     */
+	/**
+	 * @var string subledger account
+	 */
 	public $subledger_account;
 
-    /**
-     * @var string subledger label
-     */
+	/**
+	 * @var string subledger label
+	 */
 	public $subledger_label;
 
-    /**
-     * @var string  doc_type
-     */
+	/**
+	 * @var string  doc_type
+	 */
 	public $numero_compte;
 
-    /**
-     * @var string label compte
-     */
-    public $label_compte;
+	/**
+	 * @var string label compte
+	 */
+	public $label_compte;
 
-    /**
-     * @var string label operation
-     */
-    public $label_operation;
+	/**
+	 * @var string label operation
+	 */
+	public $label_operation;
 
-    /**
-     * @var float FEC:Debit
-     */
+	/**
+	 * @var float FEC:Debit
+	 */
 	public $debit;
 
-    /**
-     * @var float FEC:Credit
-     */
+	/**
+	 * @var float FEC:Credit
+	 */
 	public $credit;
 
-    /**
-     * @var float FEC:Amount (Not necessary)
-     * @deprecated Use $amount
-     */
+	/**
+	 * @var float FEC:Amount (Not necessary)
+	 * @deprecated Use $amount
+	 */
 	public $montant;
 
 	/**
@@ -138,34 +138,34 @@ class BookKeeping extends CommonObject
 	 */
 	public $amount;
 
-    /**
-     * @var string FEC:Sens (Not necessary)
-     */
+	/**
+	 * @var string FEC:Sens (Not necessary)
+	 */
 	public $sens;
 
 	/**
-     * @var int ID
-     */
+	 * @var int ID
+	 */
 	public $fk_user_author;
 
-    /**
-     * @var string key for import
-     */
+	/**
+	 * @var string key for import
+	 */
 	public $import_key;
 
-    /**
-     * @var string code journal
-     */
+	/**
+	 * @var string code journal
+	 */
 	public $code_journal;
 
-    /**
-     * @var string label journal
-     */
+	/**
+	 * @var string label journal
+	 */
 	public $journal_label;
 
-    /**
-     * @var int accounting transaction id
-     */
+	/**
+	 * @var int accounting transaction id
+	 */
 	public $piece_num;
 
 	/**
@@ -179,8 +179,8 @@ class BookKeeping extends CommonObject
 	 *
 	 * @param DoliDb $db Database handler
 	 */
-    public function __construct(DoliDB $db)
-    {
+	public function __construct(DoliDB $db)
+	{
 		$this->db = $db;
 	}
 
@@ -191,8 +191,8 @@ class BookKeeping extends CommonObject
 	 * @param  bool	$notrigger	false=launch triggers after, true=disable triggers
 	 * @return int				<0 if KO, Id of created object if OK
 	 */
-    public function create(User $user, $notrigger = false)
-    {
+	public function create(User $user, $notrigger = false)
+	{
 		global $conf, $langs;
 
 		dol_syslog(__METHOD__, LOG_DEBUG);
@@ -504,11 +504,11 @@ class BookKeeping extends CommonObject
 	 * @param  string  $mode 	   Mode
 	 * @return int				 <0 if KO, Id of created object if OK
 	 */
-    public function createStd(User $user, $notrigger = false, $mode = '')
-    {
+	public function createStd(User $user, $notrigger = false, $mode = '')
+	{
 		global $conf, $langs;
 
-        $langs->loadLangs(array("accountancy", "bills", "compta"));
+		$langs->loadLangs(array("accountancy", "bills", "compta"));
 
 		dol_syslog(__METHOD__, LOG_DEBUG);
 
@@ -578,7 +578,7 @@ class BookKeeping extends CommonObject
 		$now = dol_now();
 
 		// Check parameters
-        $this->journal_label = $langs->trans($this->journal_label);
+		$this->journal_label = $langs->trans($this->journal_label);
 
 		// Insert request
 		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.$mode.' (';
@@ -673,8 +673,8 @@ class BookKeeping extends CommonObject
 	 *
 	 * @return int <0 if KO, 0 if not found, >0 if OK
 	 */
-    public function fetch($id, $ref = null, $mode = '')
-    {
+	public function fetch($id, $ref = null, $mode = '')
+	{
 		global $conf;
 
 		dol_syslog(__METHOD__, LOG_DEBUG);
@@ -771,8 +771,8 @@ class BookKeeping extends CommonObject
 	 *
 	 * @return int <0 if KO, >=0 if OK
 	 */
-    public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
-    {
+	public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+	{
 		global $conf;
 
 		dol_syslog(__METHOD__, LOG_DEBUG);
@@ -904,11 +904,11 @@ class BookKeeping extends CommonObject
 	 * @param int 			$offset                         Offset limit
 	 * @param array 		$filter                         Filter array
 	 * @param string 		$filtermode                     Filter mode (AND or OR)
-     * @param int           $showAlreadyExportMovements     Show movements when field 'date_export' is not empty (0:No / 1:Yes (Default))
+	 * @param int           $showAlreadyExportMovements     Show movements when field 'date_export' is not empty (0:No / 1:Yes (Default))
 	 * @return int                                          <0 if KO, >0 if OK
 	 */
-    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $showAlreadyExportMovements = 1)
-    {
+	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $showAlreadyExportMovements = 1)
+	{
 		global $conf;
 
 		dol_syslog(__METHOD__, LOG_DEBUG);
@@ -940,7 +940,7 @@ class BookKeeping extends CommonObject
 		$sql .= " t.date_creation,";
 		$sql .= " t.date_lim_reglement,";
 		$sql .= " t.tms as date_modification,";
-        $sql .= " t.date_export";
+		$sql .= " t.date_export";
 		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
 		// Manage filter
 		$sqlwhere = array();
@@ -960,8 +960,8 @@ class BookKeeping extends CommonObject
 					$sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
 				} elseif ($key == 't.tms>=' || $key == 't.tms<=') {
 					$sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
-                } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') {
-                    $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
+				} elseif ($key == 't.date_export>=' || $key == 't.date_export<=') {
+					$sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
 				} elseif ($key == 't.credit' || $key == 't.debit') {
 					$sqlwhere[] = natural_search($key, $value, 1, 1);
 				} else {
@@ -970,9 +970,9 @@ class BookKeeping extends CommonObject
 			}
 		}
 		$sql .= ' WHERE t.entity IN ('.getEntity('accountancy').')';
-        if ($showAlreadyExportMovements == 0) {
-            $sql .= " AND t.date_export IS NULL";
-        }
+		if ($showAlreadyExportMovements == 0) {
+			$sql .= " AND t.date_export IS NULL";
+		}
 		if (count($sqlwhere) > 0) {
 			$sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere);
 		}
@@ -1020,7 +1020,7 @@ class BookKeeping extends CommonObject
 				$line->date_creation = $this->db->jdate($obj->date_creation);
 				$line->date_lim_reglement = $this->db->jdate($obj->date_lim_reglement);
 				$line->date_modification = $this->db->jdate($obj->date_modification);
-                $line->date_export = $this->db->jdate($obj->date_export);
+				$line->date_export = $this->db->jdate($obj->date_export);
 
 				$this->lines[] = $line;
 
@@ -1133,8 +1133,8 @@ class BookKeeping extends CommonObject
 	 * @param  string  $mode       Mode ('' or _tmp')
 	 * @return int                 <0 if KO, >0 if OK
 	 */
-    public function update(User $user, $notrigger = false, $mode = '')
-    {
+	public function update(User $user, $notrigger = false, $mode = '')
+	{
 		$error = 0;
 
 		dol_syslog(__METHOD__, LOG_DEBUG);
@@ -1300,8 +1300,8 @@ class BookKeeping extends CommonObject
 	 * @param string $mode Mode
 	 * @return int <0 if KO, >0 if OK
 	 */
-    public function delete(User $user, $notrigger = false, $mode = '')
-    {
+	public function delete(User $user, $notrigger = false, $mode = '')
+	{
 		dol_syslog(__METHOD__, LOG_DEBUG);
 
 		$error = 0;
@@ -1348,8 +1348,8 @@ class BookKeeping extends CommonObject
 	 * @param  string		$importkey		Import key
 	 * @return int Result
 	 */
-    public function deleteByImportkey($importkey)
-    {
+	public function deleteByImportkey($importkey)
+	{
 		$this->db->begin();
 
 		// first check if line not yet in bookkeeping
@@ -1379,11 +1379,11 @@ class BookKeeping extends CommonObject
 	 * @param  int	  $delmonth     Month
 	 * @return int					<0 if KO, >0 if OK
 	 */
-    public function deleteByYearAndJournal($delyear = 0, $journal = '', $mode = '', $delmonth = 0)
-    {
-    	global $langs;
+	public function deleteByYearAndJournal($delyear = 0, $journal = '', $mode = '', $delmonth = 0)
+	{
+		global $langs;
 
-    	if (empty($delyear) && empty($journal))
+		if (empty($delyear) && empty($journal))
 		{
 			$this->error = 'ErrorOneFieldRequired';
 			return -1;
@@ -1428,8 +1428,8 @@ class BookKeeping extends CommonObject
 	 * @param 	int 	$piecenum 	Piecenum to delete
 	 * @return 	int 				Result
 	 */
-    public function deleteMvtNum($piecenum)
-    {
+	public function deleteMvtNum($piecenum)
+	{
 		global $conf;
 
 		$this->db->begin();
@@ -1463,8 +1463,8 @@ class BookKeeping extends CommonObject
 	 * @param   int     $fromid     Id of object to clone
 	 * @return  int                 New id of clone
 	 */
-    public function createFromClone(User $user, $fromid)
-    {
+	public function createFromClone(User $user, $fromid)
+	{
 		dol_syslog(__METHOD__, LOG_DEBUG);
 
 		$error = 0;
@@ -1511,8 +1511,8 @@ class BookKeeping extends CommonObject
 	 *
 	 * @return void
 	 */
-    public function initAsSpecimen()
-    {
+	public function initAsSpecimen()
+	{
 		global $user;
 
 		$now = dol_now();
@@ -1548,8 +1548,8 @@ class BookKeeping extends CommonObject
 	 * @param string $mode Mode
 	 * @return int <0 if KO, >0 if OK
 	 */
-    public function fetchPerMvt($piecenum, $mode = '')
-    {
+	public function fetchPerMvt($piecenum, $mode = '')
+	{
 		global $conf;
 
 		$sql = "SELECT piece_num,doc_date,code_journal,journal_label,doc_ref,doc_type,date_creation";
@@ -1613,8 +1613,8 @@ class BookKeeping extends CommonObject
 	 * @param  string  $mode       Mode
 	 * @return int                 <0 if KO, >0 if OK
 	 */
-    public function fetchAllPerMvt($piecenum, $mode = '')
-    {
+	public function fetchAllPerMvt($piecenum, $mode = '')
+	{
 		global $conf;
 
 		$sql = "SELECT rowid, doc_date, doc_type,";
@@ -1664,16 +1664,16 @@ class BookKeeping extends CommonObject
 		return 1;
 	}
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
 	 * Export bookkeeping
 	 *
 	 * @param	string	$model	Model
 	 * @return	int				Result
 	 */
-    public function export_bookkeeping($model = 'ebp')
-    {
-        // phpcs:enable
+	public function export_bookkeeping($model = 'ebp')
+	{
+		// phpcs:enable
 		global $conf;
 
 		$sql = "SELECT rowid, doc_date, doc_type,";
@@ -1739,10 +1739,10 @@ class BookKeeping extends CommonObject
 
 		$this->db->begin();
 
-        if ($direction == 0)
+		if ($direction == 0)
 		{
 			$next_piecenum = $this->getNextNumMvt();
-            $now = dol_now();
+			$now = dol_now();
 
 			if ($next_piecenum < 0) {
 				$error++;
@@ -1819,22 +1819,22 @@ class BookKeeping extends CommonObject
 		*/
 	}
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
-	* Return list of accounts with label by chart of accounts
-	*
-	* @param string     $selectid   Preselected chart of accounts
-	* @param string     $htmlname	Name of field in html form
-	* @param int		$showempty	Add an empty field
-	* @param array		$event		Event options
-	* @param int		$select_in	Value is a aa.rowid (0 default) or aa.account_number (1)
-	* @param int		$select_out	Set value returned by select 0=rowid (default), 1=account_number
-	* @param int		$aabase		Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number
-	* @return string	String with HTML select
-    */
-    public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '')
-    {
-        // phpcs:enable
+	 * Return list of accounts with label by chart of accounts
+	 *
+	 * @param string     $selectid   Preselected chart of accounts
+	 * @param string     $htmlname	Name of field in html form
+	 * @param int		$showempty	Add an empty field
+	 * @param array		$event		Event options
+	 * @param int		$select_in	Value is a aa.rowid (0 default) or aa.account_number (1)
+	 * @param int		$select_out	Set value returned by select 0=rowid (default), 1=account_number
+	 * @param int		$aabase		Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number
+	 * @return string	String with HTML select
+	 */
+	public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '')
+	{
+		// phpcs:enable
 		global $conf;
 
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
@@ -1891,7 +1891,7 @@ class BookKeeping extends CommonObject
 		return $out;
 	}
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
 	 * Description of a root accounting account
 	 *
@@ -1900,7 +1900,7 @@ class BookKeeping extends CommonObject
 	 */
 	public function get_compte_racine($account = null)
 	{
-        // phpcs:enable
+		// phpcs:enable
 		global $conf;
 		$pcgver = $conf->global->CHARTOFACCOUNTS;
 
@@ -1932,16 +1932,16 @@ class BookKeeping extends CommonObject
 		}
 	}
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
 	 * Description of accounting account
 	 *
 	 * @param	string	$account	Accounting account
 	 * @return	string				Account desc
 	 */
-    public function get_compte_desc($account = null)
-    {
-        // phpcs:enable
+	public function get_compte_desc($account = null)
+	{
+		// phpcs:enable
 		global $conf;
 
 		$pcgver = $conf->global->CHARTOFACCOUNTS;
@@ -1989,13 +1989,13 @@ class BookKeepingLine
 	public $doc_ref;
 
 	/**
-     * @var int ID
-     */
+	 * @var int ID
+	 */
 	public $fk_doc;
 
 	/**
-     * @var int ID
-     */
+	 * @var int ID
+	 */
 	public $fk_docdet;
 
 	public $thirdparty_code;
@@ -2007,26 +2007,26 @@ class BookKeepingLine
 	public $debit;
 	public $credit;
 
-    /**
-     * @var float Amount
-     * @deprecated see $amount
-     */
+	/**
+	 * @var float Amount
+	 * @deprecated see $amount
+	 */
 	public $montant;
 
-    /**
-     * @var float Amount
-     */
+	/**
+	 * @var float Amount
+	 */
 	public $amount;
 
-    /**
-     * @var string Sens
-     */
-    public $sens;
-    public $lettering_code;
+	/**
+	 * @var string Sens
+	 */
+	public $sens;
+	public $lettering_code;
 
 	/**
-     * @var int ID
-     */
+	 * @var int ID
+	 */
 	public $fk_user_author;
 
 	public $import_key;
@@ -2035,17 +2035,17 @@ class BookKeepingLine
 	public $piece_num;
 
 	/**
-     * @var integer|string date_creation
-     */
+	 * @var integer|string date_creation
+	 */
 	public $date_creation;
 
 	/**
 	 * @var integer|string $date_modification;
 	 */
-    public $date_modification;
+	public $date_modification;
 
-    /**
-     * @var integer|string $date_export;
-     */
-    public $date_export;
+	/**
+	 * @var integer|string $date_export;
+	 */
+	public $date_export;
 }

+ 4 - 4
htdocs/accountancy/journal/bankjournal.php

@@ -180,10 +180,10 @@ if ($result) {
 	$account_supplier			= (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : 'NotDefined'); // NotDefined is a reserved word
 	$account_customer			= (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined'); // NotDefined is a reserved word
 	$account_employee			= (!empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) ? $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT : 'NotDefined'); // NotDefined is a reserved word
-	$account_pay_vat			= (!empty($conf->global->ACCOUNTING_VAT_PAY_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT : 'NotDefined'); // NotDefined is a reserved word
-	$account_pay_donation		= (!empty($conf->global->DONATION_ACCOUNTINGACCOUNT) ? $conf->global->DONATION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
-	$account_pay_subscription	= (!empty($conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT) ? $conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
-	$account_transfer			= (!empty($conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH) ? $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH : 'NotDefined'); // NotDefined is a reserved word
+	$account_pay_vat = (!empty($conf->global->ACCOUNTING_VAT_PAY_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT : 'NotDefined'); // NotDefined is a reserved word
+	$account_pay_donation = (!empty($conf->global->DONATION_ACCOUNTINGACCOUNT) ? $conf->global->DONATION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
+	$account_pay_subscription = (!empty($conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT) ? $conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
+	$account_transfer = (!empty($conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH) ? $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH : 'NotDefined'); // NotDefined is a reserved word
 
 	$tabcompany = array();
 	$tabuser = array();

+ 88 - 88
htdocs/adherents/subscription/card.php

@@ -110,7 +110,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'update' && !$cance
 			} else {
 				$db->rollback();
 
-			    if ($object->error) {
+				if ($object->error) {
 					$errmsg = $object->error;
 				} else {
 					foreach ($object->errors as $error) {
@@ -128,13 +128,13 @@ if ($user->rights->adherent->cotisation->creer && $action == 'update' && !$cance
 
 if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->adherent->cotisation->creer) {
 	$result = $object->fetch($rowid);
-    $result = $object->delete($user);
-    if ($result > 0) {
-    	header("Location: ".DOL_URL_ROOT."/adherents/card.php?rowid=".$object->fk_adherent);
-    	exit;
-    } else {
-    	$mesg = $adh->error;
-    }
+	$result = $object->delete($user);
+	if ($result > 0) {
+		header("Location: ".DOL_URL_ROOT."/adherents/card.php?rowid=".$object->fk_adherent);
+		exit;
+	} else {
+		$mesg = $adh->error;
+	}
 }
 
 
@@ -159,7 +159,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') {
 	 *
 	 ********************************************/
 
-    $object->fetch($rowid);
+	$object->fetch($rowid);
 	$result = $adh->fetch($object->fk_adherent);
 
 	$head = subscription_prepare_head($object);
@@ -172,13 +172,13 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') {
 
 	dol_fiche_head($head, 'general', $langs->trans("Subscription"), 0, 'payment');
 
-    $linkback = '<a href="'.DOL_URL_ROOT.'/adherents/subscription/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
+	$linkback = '<a href="'.DOL_URL_ROOT.'/adherents/subscription/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-    print "\n";
+	print "\n";
 	print '<table class="border centpercent">';
 
-    // Ref
-    print '<tr><td class="titlefieldcreate">'.$langs->trans("Ref").'</td>';
+	// Ref
+	print '<tr><td class="titlefieldcreate">'.$langs->trans("Ref").'</td>';
 	print '<td class="valeur" colspan="3">';
 	print $form->showrefnav($object, 'rowid', $linkback, 1);
 	print '</td></tr>';
@@ -195,24 +195,24 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') {
 	print $form->selectarray("typeid", $adht->liste_array(), (GETPOSTISSET("typeid") ? GETPOST("typeid") : $object->fk_type));
 	print'</td></tr>';
 
-    // Date start subscription
-    print '<tr><td>'.$langs->trans("DateSubscription").'</td><td class="valeur" colspan="2">';
+	// Date start subscription
+	print '<tr><td>'.$langs->trans("DateSubscription").'</td><td class="valeur" colspan="2">';
 	print $form->selectDate($object->dateh, 'datesub', 1, 1, 0, 'update', 1);
 	print '</td>';
-    print '</tr>';
+	print '</tr>';
 
-    // Date end subscription
-    print '<tr><td>'.$langs->trans("DateEndSubscription").'</td><td class="valeur" colspan="2">';
+	// Date end subscription
+	print '<tr><td>'.$langs->trans("DateEndSubscription").'</td><td class="valeur" colspan="2">';
 	print $form->selectDate($object->datef, 'datesubend', 0, 0, 0, 'update', 1);
 	print '</td>';
-    print '</tr>';
+	print '</tr>';
 
-    // Amount
-    print '<tr><td>'.$langs->trans("Amount").'</td><td class="valeur" colspan="2">';
+	// Amount
+	print '<tr><td>'.$langs->trans("Amount").'</td><td class="valeur" colspan="2">';
 	print '<input type="text" class="flat" size="10" name="amount" value="'.price($object->amount).'"></td></tr>';
 
-    // Label
-    print '<tr><td>'.$langs->trans("Label").'</td><td class="valeur" colspan="2">';
+	// Label
+	print '<tr><td>'.$langs->trans("Label").'</td><td class="valeur" colspan="2">';
 	print '<input type="text" class="flat" size="60" name="note" value="'.$object->note.'"></td></tr>';
 
 	// Bank line
@@ -234,11 +234,11 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') {
 
 	dol_fiche_end();
 
-    print '<div class="center">';
-    print '<input type="submit" class="button" name="submit" value="'.$langs->trans("Save").'">';
+	print '<div class="center">';
+	print '<input type="submit" class="button" name="submit" value="'.$langs->trans("Save").'">';
 	print ' &nbsp; &nbsp; &nbsp; ';
 	print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
-    print '</div>';
+	print '</div>';
 
 	print '</form>';
 	print "\n";
@@ -251,69 +251,69 @@ if ($rowid && $action != 'edit') {
 	 *
 	 ********************************************/
 
-    $result = $object->fetch($rowid);
+	$result = $object->fetch($rowid);
 	$result = $adh->fetch($object->fk_adherent);
 
 	$head = subscription_prepare_head($object);
 
 	dol_fiche_head($head, 'general', $langs->trans("Subscription"), -1, 'payment');
 
-    // Confirmation to delete subscription
-    if ($action == 'delete') {
+	// Confirmation to delete subscription
+	if ($action == 'delete') {
 		//$formquestion=array();
-        //$formquestion['text']='<b>'.$langs->trans("ThisWillAlsoDeleteBankRecord").'</b>';
+		//$formquestion['text']='<b>'.$langs->trans("ThisWillAlsoDeleteBankRecord").'</b>';
 		$text = $langs->trans("ConfirmDeleteSubscription");
 		if (!empty($conf->banque->enabled) && !empty($conf->global->ADHERENT_BANK_USE)) $text .= '<br>'.img_warning().' '.$langs->trans("ThisWillAlsoDeleteBankRecord");
 		print $form->formconfirm($_SERVER["PHP_SELF"]."?rowid=".$object->id, $langs->trans("DeleteSubscription"), $text, "confirm_delete", $formquestion, 0, 1);
-    }
+	}
 
-    print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
 
-    $linkback = '<a href="'.DOL_URL_ROOT.'/adherents/subscription/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
+	$linkback = '<a href="'.DOL_URL_ROOT.'/adherents/subscription/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-    dol_banner_tab($object, 'rowid', $linkback, 1);
+	dol_banner_tab($object, 'rowid', $linkback, 1);
 
-    print '<div class="fichecenter">';
+	print '<div class="fichecenter">';
 
-    print '<div class="underbanner clearboth"></div>';
+	print '<div class="underbanner clearboth"></div>';
 
-    print '<table class="border centpercent">';
+	print '<table class="border centpercent">';
 
-    // Member
-    $adh->ref = $adh->getFullName($langs);
-    print '<tr>';
-    print '<td class="titlefield">'.$langs->trans("Member").'</td><td class="valeur">'.$adh->getNomUrl(1, 0, 'subscription').'</td>';
-    print '</tr>';
+	// Member
+	$adh->ref = $adh->getFullName($langs);
+	print '<tr>';
+	print '<td class="titlefield">'.$langs->trans("Member").'</td><td class="valeur">'.$adh->getNomUrl(1, 0, 'subscription').'</td>';
+	print '</tr>';
 
-    // Type
-    print '<tr>';
-    print '<td class="titlefield">'.$langs->trans("Type").'</td>';
-    print '<td class="valeur">';
-    if ($object->fk_type > 0 || $adh->typeid > 0) {
-    	$typeid = ($object->fk_type > 0 ? $object->fk_type : $adh->typeid);
-    	$adht->fetch($typeid);
-        print $adht->getNomUrl(1);
-    } else {
-        print $langs->trans("NoType");
-    }
-    print '</td></tr>';
+	// Type
+	print '<tr>';
+	print '<td class="titlefield">'.$langs->trans("Type").'</td>';
+	print '<td class="valeur">';
+	if ($object->fk_type > 0 || $adh->typeid > 0) {
+		$typeid = ($object->fk_type > 0 ? $object->fk_type : $adh->typeid);
+		$adht->fetch($typeid);
+		print $adht->getNomUrl(1);
+	} else {
+		print $langs->trans("NoType");
+	}
+	print '</td></tr>';
 
-    // Date subscription
-    print '<tr>';
+	// Date subscription
+	print '<tr>';
 	print '<td>'.$langs->trans("DateSubscription").'</td><td class="valeur">'.dol_print_date($object->dateh, 'day').'</td>';
-    print '</tr>';
+	print '</tr>';
 
-    // Date end subscription
-    print '<tr>';
+	// Date end subscription
+	print '<tr>';
 	print '<td>'.$langs->trans("DateEndSubscription").'</td><td class="valeur">'.dol_print_date($object->datef, 'day').'</td>';
-    print '</tr>';
+	print '</tr>';
 
-    // Amount
-    print '<tr><td>'.$langs->trans("Amount").'</td><td class="valeur">'.price($object->amount).'</td></tr>';
+	// Amount
+	print '<tr><td>'.$langs->trans("Amount").'</td><td class="valeur">'.price($object->amount).'</td></tr>';
 
-    // Label
-    print '<tr><td>'.$langs->trans("Label").'</td><td class="valeur">'.$object->note.'</td></tr>';
+	// Label
+	print '<tr><td>'.$langs->trans("Label").'</td><td class="valeur">'.$object->note.'</td></tr>';
 
 	// Bank line
 	if (!empty($conf->banque->enabled)) {
@@ -330,20 +330,20 @@ if ($rowid && $action != 'edit') {
 		}
 	}
 
-    print "</table>\n";
-    print '</div>';
+	print "</table>\n";
+	print '</div>';
 
-    print '</form>';
+	print '</form>';
 
-    dol_fiche_end();
+	dol_fiche_end();
 
-    /*
+	/*
      * Barre d'actions
      *
      */
-    print '<div class="tabsAction">';
+	print '<div class="tabsAction">';
 
-    if ($user->rights->adherent->cotisation->creer) {
+	if ($user->rights->adherent->cotisation->creer) {
 		if (!$bankline->rappro) {
 			print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"]."?rowid=".$object->id.'&action=edit&token='.newToken().'">'.$langs->trans("Modify")."</a></div>";
 		} else {
@@ -351,19 +351,19 @@ if ($rowid && $action != 'edit') {
 		}
 	}
 
-    // Delete
-    if ($user->rights->adherent->cotisation->creer) {
-        print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"]."?rowid=".$object->id.'&action=delete&token='.newToken().'">'.$langs->trans("Delete")."</a></div>\n";
-    }
+	// Delete
+	if ($user->rights->adherent->cotisation->creer) {
+		print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"]."?rowid=".$object->id.'&action=delete&token='.newToken().'">'.$langs->trans("Delete")."</a></div>\n";
+	}
 
-    print '</div>';
+	print '</div>';
 
 
-    print '<div class="fichecenter"><div class="fichehalfleft">';
-    print '<a name="builddoc"></a>'; // ancre
+	print '<div class="fichecenter"><div class="fichehalfleft">';
+	print '<a name="builddoc"></a>'; // ancre
 
-    // Documents generes
-    /*
+	// Documents generes
+	/*
     $filename = dol_sanitizeFileName($object->ref);
     $filedir = $conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref);
     $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id;
@@ -375,23 +375,23 @@ if ($rowid && $action != 'edit') {
     */
 	// Show links to link elements
 	//$linktoelem = $form->showLinkToObjectBlock($object, null, array('subscription'));
-    $somethingshown = $form->showLinkedObjectBlock($object, '');
+	$somethingshown = $form->showLinkedObjectBlock($object, '');
 
-    // Show links to link elements
-    /*$linktoelem = $form->showLinkToObjectBlock($object,array('order'));
+	// Show links to link elements
+	/*$linktoelem = $form->showLinkToObjectBlock($object,array('order'));
 	if ($linktoelem) print ($somethingshown?'':'<br>').$linktoelem;
     */
 
-    print '</div><div class="fichehalfright"><div class="ficheaddleft">';
+	print '</div><div class="fichehalfright"><div class="ficheaddleft">';
 
-    // List of actions on element
-    /*
+	// List of actions on element
+	/*
     include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
     $formactions = new FormActions($db);
     $somethingshown = $formactions->showactions($object, 'invoice', $socid, 1);
     */
 
-    print '</div></div></div>';
+	print '</div></div></div>';
 }
 
 // End of page

+ 85 - 85
htdocs/admin/defaultvalues.php

@@ -83,17 +83,17 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 // Purge search criteria
 if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
 {
-    $defaulturl = '';
-    $defaultkey = '';
-    $defaultvalue = '';
-    $toselect = '';
-    $search_array_options = array();
+	$defaulturl = '';
+	$defaultkey = '';
+	$defaultvalue = '';
+	$toselect = '';
+	$search_array_options = array();
 }
 
 if ($action == 'setMAIN_ENABLE_DEFAULT_VALUES')
 {
-    if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 1, 'chaine', 0, '', $conf->entity);
-    else dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 0, 'chaine', 0, '', $conf->entity);
+	if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 1, 'chaine', 0, '', $conf->entity);
+	else dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 0, 'chaine', 0, '', $conf->entity);
 }
 
 if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('actionmodify'))
@@ -102,57 +102,57 @@ if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('ac
 
 	if (($action == 'add' || (GETPOST('add') && $action != 'update')))
 	{
-    	if (empty($defaulturl))
-    	{
-    		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors');
-    		$error++;
-    	}
-    	if (empty($defaultkey))
-    	{
-    		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors');
-    		$error++;
-    	}
+		if (empty($defaulturl))
+		{
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors');
+			$error++;
+		}
+		if (empty($defaultkey))
+		{
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors');
+			$error++;
+		}
 	}
 	if (GETPOST('actionmodify'))
 	{
-	    if (empty($urlpage))
-	    {
-	        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors');
-	        $error++;
-	    }
-	    if (empty($key))
-	    {
-	        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors');
-	        $error++;
-	    }
+		if (empty($urlpage))
+		{
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors');
+			$error++;
+		}
+		if (empty($key))
+		{
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors');
+			$error++;
+		}
 	}
 
 	if (!$error)
 	{
-	    $db->begin();
-
-	    if ($action == 'add' || (GETPOST('add') && $action != 'update'))
-	    {
-            $sql = "INSERT INTO ".MAIN_DB_PREFIX."default_values(type, user_id, page, param, value, entity) VALUES ('".$db->escape($mode)."', 0, '".$db->escape($defaulturl)."','".$db->escape($defaultkey)."','".$db->escape($defaultvalue)."', ".$db->escape($conf->entity).")";
-	    }
-	    if (GETPOST('actionmodify'))
-	    {
-		    $sql = "UPDATE ".MAIN_DB_PREFIX."default_values SET page = '".$db->escape($urlpage)."', param = '".$db->escape($key)."', value = '".$db->escape($value)."'";
-		    $sql .= " WHERE rowid = ".$id;
-	    }
+		$db->begin();
+
+		if ($action == 'add' || (GETPOST('add') && $action != 'update'))
+		{
+			$sql = "INSERT INTO ".MAIN_DB_PREFIX."default_values(type, user_id, page, param, value, entity) VALUES ('".$db->escape($mode)."', 0, '".$db->escape($defaulturl)."','".$db->escape($defaultkey)."','".$db->escape($defaultvalue)."', ".$db->escape($conf->entity).")";
+		}
+		if (GETPOST('actionmodify'))
+		{
+			$sql = "UPDATE ".MAIN_DB_PREFIX."default_values SET page = '".$db->escape($urlpage)."', param = '".$db->escape($key)."', value = '".$db->escape($value)."'";
+			$sql .= " WHERE rowid = ".$id;
+		}
 
 		$result = $db->query($sql);
 		if ($result > 0)
 		{
-		    $db->commit();
+			$db->commit();
 			setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
 			$action = "";
 			$defaulturl = '';
 			$defaultkey = '';
 			$defaultvalue = '';
 		} else {
-	        $db->rollback();
-		    setEventMessages($db->lasterror(), null, 'errors');
+			$db->rollback();
+			setEventMessages($db->lasterror(), null, 'errors');
 			$action = '';
 		}
 	}
@@ -189,15 +189,15 @@ $param = '&mode='.$mode;
 $enabledisablehtml .= $langs->trans("EnableDefaultValues").' ';
 if (empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))
 {
-    // Button off, click to enable
-    $enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_DEFAULT_VALUES&amp;token='.newToken().'&amp;value=1'.$param.'">';
-    $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off');
-    $enabledisablehtml .= '</a>';
+	// Button off, click to enable
+	$enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_DEFAULT_VALUES&amp;token='.newToken().'&amp;value=1'.$param.'">';
+	$enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off');
+	$enabledisablehtml .= '</a>';
 } else {
-    // Button on, click to disable
-    $enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_DEFAULT_VALUES&amp;token='.newToken().'&amp;value=0'.$param.'">';
-    $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on');
-    $enabledisablehtml .= '</a>';
+	// Button on, click to disable
+	$enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_DEFAULT_VALUES&amp;token='.newToken().'&amp;value=0'.$param.'">';
+	$enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on');
+	$enabledisablehtml .= '</a>';
 }
 
 print load_fiche_titre($langs->trans("DefaultValues"), $enabledisablehtml, 'title_setup');
@@ -228,7 +228,7 @@ dol_fiche_head($head, $mode, '', -1, '');
 
 if ($mode == 'sortorder')
 {
-    print info_admin($langs->trans("WarningSettingSortOrder")).'<br>';
+	print info_admin($langs->trans("WarningSettingSortOrder")).'<br>';
 }
 if ($mode == 'mandatory')
 {
@@ -253,30 +253,30 @@ print_liste_field_titre($texturl, $_SERVER["PHP_SELF"], 'page,param', '', $param
 $texthelp = $langs->trans("TheKeyIsTheNameOfHtmlField");
 if ($mode != 'sortorder')
 {
-    $textkey = $form->textwithpicto($langs->trans("Field"), $texthelp);
+	$textkey = $form->textwithpicto($langs->trans("Field"), $texthelp);
 } else {
-    $texthelp = 'field or alias.field';
-    $textkey = $form->textwithpicto($langs->trans("Field"), $texthelp);
+	$texthelp = 'field or alias.field';
+	$textkey = $form->textwithpicto($langs->trans("Field"), $texthelp);
 }
 print_liste_field_titre($textkey, $_SERVER["PHP_SELF"], 'param', '', $param, '', $sortfield, $sortorder);
 // Value
 if ($mode != 'focus' && $mode != 'mandatory')
 {
-    if ($mode != 'sortorder')
-    {
-        $substitutionarray = getCommonSubstitutionArray($langs, 2, array('object', 'objectamount')); // Must match list into GETPOST
+	if ($mode != 'sortorder')
+	{
+		$substitutionarray = getCommonSubstitutionArray($langs, 2, array('object', 'objectamount')); // Must match list into GETPOST
 		unset($substitutionarray['__USER_SIGNATURE__']);
-        $texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'<br>';
-        foreach ($substitutionarray as $key => $val)
-        {
-            $texthelp .= $key.' -> '.$val.'<br>';
-        }
-        $textvalue = $form->textwithpicto($langs->trans("Value"), $texthelp, 1, 'help', '', 0, 2, 'subsitutiontooltip');
-    } else {
-        $texthelp = 'ASC or DESC';
-        $textvalue = $form->textwithpicto($langs->trans("SortOrder"), $texthelp);
-    }
-    print_liste_field_titre($textvalue, $_SERVER["PHP_SELF"], 'value', '', $param, '', $sortfield, $sortorder);
+		$texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'<br>';
+		foreach ($substitutionarray as $key => $val)
+		{
+			$texthelp .= $key.' -> '.$val.'<br>';
+		}
+		$textvalue = $form->textwithpicto($langs->trans("Value"), $texthelp, 1, 'help', '', 0, 2, 'subsitutiontooltip');
+	} else {
+		$texthelp = 'ASC or DESC';
+		$textvalue = $form->textwithpicto($langs->trans("SortOrder"), $texthelp);
+	}
+	print_liste_field_titre($textvalue, $_SERVER["PHP_SELF"], 'value', '', $param, '', $sortfield, $sortorder);
 }
 // Entity
 if (!empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,page', '', $param, '', $sortfield, $sortorder);
@@ -301,9 +301,9 @@ print '</td>';
 // Value
 if ($mode != 'focus' && $mode != 'mandatory')
 {
-    print '<td>';
-    print '<input type="text" class="flat maxwidth100onsmartphone" name="defaultvalue" value="">';
-    print '</td>';
+	print '<td>';
+	print '<input type="text" class="flat maxwidth100onsmartphone" name="defaultvalue" value="">';
+	print '</td>';
 }
 // Limit to superadmin
 if (!empty($conf->multicompany->enabled) && !$user->entity)
@@ -361,32 +361,32 @@ if ($result)
 		// Value
 		if ($mode != 'focus' && $mode != 'mandatory')
 		{
-    		print '<td>';
-    		/*print '<input type="hidden" name="const['.$i.'][rowid]" value="'.$obj->rowid.'">';
+			print '<td>';
+			/*print '<input type="hidden" name="const['.$i.'][rowid]" value="'.$obj->rowid.'">';
     		print '<input type="hidden" name="const['.$i.'][lang]" value="'.$obj->lang.'">';
     		print '<input type="hidden" name="const['.$i.'][name]" value="'.$obj->transkey.'">';
     		print '<input type="text" id="value_'.$i.'" class="flat inputforupdate" size="30" name="const['.$i.'][value]" value="'.dol_escape_htmltag($obj->transvalue).'">';
     		*/
-    		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print dol_escape_htmltag($obj->value);
-    		else print '<input type="text" name="value" value="'.dol_escape_htmltag($obj->value).'">';
-    		print '</td>';
+			if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print dol_escape_htmltag($obj->value);
+			else print '<input type="text" name="value" value="'.dol_escape_htmltag($obj->value).'">';
+			print '</td>';
 		}
 
-	    print '<td></td>';
+		print '<td></td>';
 
 		// Actions
 		print '<td class="center">';
 		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid)
 		{
-    		print '<a href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&mode='.$mode.'&action=edit&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_edit().'</a>';
-    		print ' &nbsp; ';
-    		print '<a href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&mode='.$mode.'&action=delete&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_delete().'</a>';
+			print '<a href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&mode='.$mode.'&action=edit&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_edit().'</a>';
+			print ' &nbsp; ';
+			print '<a href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&mode='.$mode.'&action=delete&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_delete().'</a>';
 		} else {
-		    print '<input type="hidden" name="page" value="'.$page.'">';
-		    print '<input type="hidden" name="rowid" value="'.$id.'">';
-		    print '<div name="'.(!empty($obj->rowid) ? $obj->rowid : 'none').'"></div>';
-		    print '<input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
-		    print '<input type="submit" class="button" name="actioncancel" value="'.$langs->trans("Cancel").'">';
+			print '<input type="hidden" name="page" value="'.$page.'">';
+			print '<input type="hidden" name="rowid" value="'.$id.'">';
+			print '<div name="'.(!empty($obj->rowid) ? $obj->rowid : 'none').'"></div>';
+			print '<input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
+			print '<input type="submit" class="button" name="actioncancel" value="'.$langs->trans("Cancel").'">';
 		}
 		print '</td>';
 
@@ -395,7 +395,7 @@ if ($result)
 		$i++;
 	}
 } else {
-    dol_print_error($db);
+	dol_print_error($db);
 }
 
 print '</table>';

File diff suppressed because it is too large
+ 609 - 609
htdocs/admin/dict.php


+ 10 - 10
htdocs/admin/ecm_directories_extrafields.php

@@ -34,7 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
 
 
 if (!$user->admin)
-    accessforbidden();
+	accessforbidden();
 
 // Load translation files required by the page
 $langs->loadLangs(array('admin', 'other', 'ecm'));
@@ -89,9 +89,9 @@ dol_fiche_end();
 
 // Buttons
 if ($action != 'create' && $action != 'edit') {
-    print '<div class="tabsAction">';
-    print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
-    print "</div>";
+	print '<div class="tabsAction">';
+	print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
+	print "</div>";
 }
 
 
@@ -102,9 +102,9 @@ if ($action != 'create' && $action != 'edit') {
 /* ************************************************************************** */
 
 if ($action == 'create') {
-    print '<br><div id="newattrib"></div>';
-    print load_fiche_titre($langs->trans('NewAttribute'));
-    require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
+	print '<br><div id="newattrib"></div>';
+	print load_fiche_titre($langs->trans('NewAttribute'));
+	require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
 }
 
 /* ************************************************************************** */
@@ -113,9 +113,9 @@ if ($action == 'create') {
 /*                                                                            */
 /* ************************************************************************** */
 if ($action == 'edit' && !empty($attrname)) {
-    print "<br>";
-    print load_fiche_titre($langs->trans("FieldEdition", $attrname));
-    require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php';
+	print "<br>";
+	print load_fiche_titre($langs->trans("FieldEdition", $attrname));
+	require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php';
 }
 
 // End of page

+ 10 - 10
htdocs/admin/ecm_files_extrafields.php

@@ -34,7 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
 
 
 if (!$user->admin)
-    accessforbidden();
+	accessforbidden();
 
 // Load translation files required by the page
 $langs->loadLangs(array('admin', 'other', 'ecm'));
@@ -89,9 +89,9 @@ dol_fiche_end();
 
 // Buttons
 if ($action != 'create' && $action != 'edit') {
-    print '<div class="tabsAction">';
-    print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
-    print "</div>";
+	print '<div class="tabsAction">';
+	print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>";
+	print "</div>";
 }
 
 
@@ -102,9 +102,9 @@ if ($action != 'create' && $action != 'edit') {
 /* ************************************************************************** */
 
 if ($action == 'create') {
-    print '<br><div id="newattrib"></div>';
-    print load_fiche_titre($langs->trans('NewAttribute'));
-    require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
+	print '<br><div id="newattrib"></div>';
+	print load_fiche_titre($langs->trans('NewAttribute'));
+	require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php';
 }
 
 /* ************************************************************************** */
@@ -113,9 +113,9 @@ if ($action == 'create') {
 /*                                                                            */
 /* ************************************************************************** */
 if ($action == 'edit' && !empty($attrname)) {
-    print "<br>";
-    print load_fiche_titre($langs->trans("FieldEdition", $attrname));
-    require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php';
+	print "<br>";
+	print load_fiche_titre($langs->trans("FieldEdition", $attrname));
+	require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php';
 }
 
 // End of page

+ 4 - 4
htdocs/admin/menus/index.php

@@ -330,10 +330,10 @@ if ($conf->use_javascript_ajax)
 			$entry .= '</td></tr></table>';
 
 			$buttons = '<a class="editfielda marginleftonly marginrightonly" href="edit.php?menu_handler='.$menu_handler_to_search.'&action=edit&token='.newToken().'&menuId='.$menu['rowid'].'">'.img_edit('default', 0, 'class="menuEdit" id="edit'.$menu['rowid'].'"').'</a> ';
-			$buttons .=	'<a class="marginleftonly marginrightonly" href="edit.php?menu_handler='.$menu_handler_to_search.'&action=create&token='.newToken().'&menuId='.$menu['rowid'].'">'.img_edit_add('default').'</a> ';
-			$buttons .=	'<a class="marginleftonly marginrightonly" href="index.php?menu_handler='.$menu_handler_to_search.'&action=delete&token='.newToken().'&menuId='.$menu['rowid'].'">'.img_delete('default').'</a> ';
-			$buttons .=	'&nbsp; &nbsp; &nbsp;';
-			$buttons .=	'<a class="marginleftonly marginrightonly" href="index.php?menu_handler='.$menu_handler_to_search.'&action=up&token='.newToken().'&menuId='.$menu['rowid'].'">'.img_picto("Up", "1uparrow").'</a><a href="index.php?menu_handler='.$menu_handler_to_search.'&action=down&menuId='.$menu['rowid'].'">'.img_picto("Down", "1downarrow").'</a>';
+			$buttons .= '<a class="marginleftonly marginrightonly" href="edit.php?menu_handler='.$menu_handler_to_search.'&action=create&token='.newToken().'&menuId='.$menu['rowid'].'">'.img_edit_add('default').'</a> ';
+			$buttons .= '<a class="marginleftonly marginrightonly" href="index.php?menu_handler='.$menu_handler_to_search.'&action=delete&token='.newToken().'&menuId='.$menu['rowid'].'">'.img_delete('default').'</a> ';
+			$buttons .= '&nbsp; &nbsp; &nbsp;';
+			$buttons .= '<a class="marginleftonly marginrightonly" href="index.php?menu_handler='.$menu_handler_to_search.'&action=up&token='.newToken().'&menuId='.$menu['rowid'].'">'.img_picto("Up", "1uparrow").'</a><a href="index.php?menu_handler='.$menu_handler_to_search.'&action=down&menuId='.$menu['rowid'].'">'.img_picto("Down", "1downarrow").'</a>';
 
 			$data[] = array(
 				'rowid'=>$menu['rowid'],

+ 292 - 292
htdocs/admin/oauthlogintokens.php

@@ -58,50 +58,50 @@ if (!$mode) $mode = 'setup';
 
 if ($action == 'setconst' && $user->admin)
 {
-    $error = 0;
-    $db->begin();
-
-    $setupconstarray = GETPOST('setupdriver', 'array');
-
-    foreach ($setupconstarray as $setupconst) {
-        //print '<pre>'.print_r($setupconst, true).'</pre>';
-
-    	$constname = dol_escape_htmltag($setupconst['varname']);
-    	$constvalue = dol_escape_htmltag($setupconst['value']);
-    	$consttype = dol_escape_htmltag($setupconst['type']);
-    	$constnote = dol_escape_htmltag($setupconst['note']);
-
-    	$result = dolibarr_set_const($db, $constname, $constvalue, $consttype, 0, $constnote, $conf->entity);
-        if (!$result > 0) $error++;
-    }
-
-    if (!$error)
-    {
-        $db->commit();
-        setEventMessages($langs->trans("SetupSaved"), null);
-    } else {
-        $db->rollback();
-        dol_print_error($db);
-    }
-    $action = '';
+	$error = 0;
+	$db->begin();
+
+	$setupconstarray = GETPOST('setupdriver', 'array');
+
+	foreach ($setupconstarray as $setupconst) {
+		//print '<pre>'.print_r($setupconst, true).'</pre>';
+
+		$constname = dol_escape_htmltag($setupconst['varname']);
+		$constvalue = dol_escape_htmltag($setupconst['value']);
+		$consttype = dol_escape_htmltag($setupconst['type']);
+		$constnote = dol_escape_htmltag($setupconst['note']);
+
+		$result = dolibarr_set_const($db, $constname, $constvalue, $consttype, 0, $constnote, $conf->entity);
+		if (!$result > 0) $error++;
+	}
+
+	if (!$error)
+	{
+		$db->commit();
+		setEventMessages($langs->trans("SetupSaved"), null);
+	} else {
+		$db->rollback();
+		dol_print_error($db);
+	}
+	$action = '';
 }
 
 if ($action == 'setvalue' && $user->admin)
 {
-    $db->begin();
-
-    $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity);
-    if (!$result > 0) $error++;
-
-    if (!$error)
-    {
-        $db->commit();
-        setEventMessages($langs->trans("SetupSaved"), null);
-    } else {
-        $db->rollback();
-        dol_print_error($db);
-    }
-    $action = '';
+	$db->begin();
+
+	$result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity);
+	if (!$result > 0) $error++;
+
+	if (!$error)
+	{
+		$db->commit();
+		setEventMessages($langs->trans("SetupSaved"), null);
+	} else {
+		$db->rollback();
+		dol_print_error($db);
+	}
+	$action = '';
 }
 
 
@@ -131,275 +131,275 @@ if (GETPOST('error')) {
 
 if ($mode == 'setup' && $user->admin)
 {
-    print '<span class="opacitymedium">'.$langs->trans("OAuthSetupForLogin")."</span><br><br>\n";
-
-    foreach ($list as $key)
-    {
-        $supported = 0;
-        if (in_array($key[0], array_keys($supportedoauth2array))) $supported = 1;
-        if (!$supported) continue; // show only supported
-
-
-        $OAUTH_SERVICENAME = 'Unknown';
-        if ($key[0] == 'OAUTH_GITHUB_NAME')
-        {
-            $OAUTH_SERVICENAME = 'GitHub';
-            // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service).
-            // We pass this param list in to 'state' because we need it before and after the redirect.
-            $shortscope = 'user,public_repo';
-            $urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
-            $urltodelete = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
-            $urltocheckperms = 'https://github.com/settings/applications/';
-        } elseif ($key[0] == 'OAUTH_GOOGLE_NAME')
-        {
-            $OAUTH_SERVICENAME = 'Google';
-            // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service).
-            // We pass this param list in to 'state' because we need it before and after the redirect.
-            $shortscope = 'userinfo_email,userinfo_profile,cloud_print';
-            if (!empty($conf->global->OAUTH_GSUITE)){
-            	$shortscope .= ',admin_directory_user';
+	print '<span class="opacitymedium">'.$langs->trans("OAuthSetupForLogin")."</span><br><br>\n";
+
+	foreach ($list as $key)
+	{
+		$supported = 0;
+		if (in_array($key[0], array_keys($supportedoauth2array))) $supported = 1;
+		if (!$supported) continue; // show only supported
+
+
+		$OAUTH_SERVICENAME = 'Unknown';
+		if ($key[0] == 'OAUTH_GITHUB_NAME')
+		{
+			$OAUTH_SERVICENAME = 'GitHub';
+			// List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service).
+			// We pass this param list in to 'state' because we need it before and after the redirect.
+			$shortscope = 'user,public_repo';
+			$urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
+			$urltodelete = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
+			$urltocheckperms = 'https://github.com/settings/applications/';
+		} elseif ($key[0] == 'OAUTH_GOOGLE_NAME')
+		{
+			$OAUTH_SERVICENAME = 'Google';
+			// List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service).
+			// We pass this param list in to 'state' because we need it before and after the redirect.
+			$shortscope = 'userinfo_email,userinfo_profile,cloud_print';
+			if (!empty($conf->global->OAUTH_GSUITE)){
+				$shortscope .= ',admin_directory_user';
 			}
-            //$scope.=',gmail_full';
-            $urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
-            $urltodelete = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
-            $urltocheckperms = 'https://security.google.com/settings/security/permissions';
-        } elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME')
-        {
-        	$OAUTH_SERVICENAME = 'StripeTest';
-        	$urltorenew = $urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
-        	$urltodelete = '';
-        	$urltocheckperms = '';
-        } elseif ($key[0] == 'OAUTH_STRIPE_LIVE_NAME')
-        {
-        	$OAUTH_SERVICENAME = 'StripeLive';
-        	$urltorenew = $urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
-        	$urltodelete = '';
-        	$urltocheckperms = '';
-        } else {
+			//$scope.=',gmail_full';
+			$urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
+			$urltodelete = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
+			$urltocheckperms = 'https://security.google.com/settings/security/permissions';
+		} elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME')
+		{
+			$OAUTH_SERVICENAME = 'StripeTest';
+			$urltorenew = $urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
+			$urltodelete = '';
+			$urltocheckperms = '';
+		} elseif ($key[0] == 'OAUTH_STRIPE_LIVE_NAME')
+		{
+			$OAUTH_SERVICENAME = 'StripeLive';
+			$urltorenew = $urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
+			$urltodelete = '';
+			$urltocheckperms = '';
+		} else {
 			$urltorenew = '';
 			$urltodelete = '';
 			$urltocheckperms = '';
 		}
 
 
-        // Show value of token
-        $tokenobj = null;
-        // Token
-        require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
-        require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
-        // Dolibarr storage
-        $storage = new DoliStorage($db, $conf);
-        try {
-            $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
-        } catch (Exception $e)
-        {
-            // Return an error if token not found
-        }
-
-        // Set other properties
-        $refreshtoken = false;
-        $expiredat = '';
-
-        $expire = false;
-        // Is token expired or will token expire in the next 30 seconds
-        if (is_object($tokenobj)) {
-            $expire = ($tokenobj->getEndOfLife() !== $tokenobj::EOL_NEVER_EXPIRES && $tokenobj->getEndOfLife() !== $tokenobj::EOL_UNKNOWN && time() > ($tokenobj->getEndOfLife() - 30));
-        }
-
-        if ($key[1] != '' && $key[2] != '') {
-            if (is_object($tokenobj)) {
-                $refreshtoken = $tokenobj->getRefreshToken();
-
-                $endoflife = $tokenobj->getEndOfLife();
-                if ($endoflife == $tokenobj::EOL_NEVER_EXPIRES)
-                {
-                    $expiredat = $langs->trans("Never");
-                } elseif ($endoflife == $tokenobj::EOL_UNKNOWN)
-                {
-                    $expiredat = $langs->trans("Unknown");
-                } else {
-                    $expiredat = dol_print_date($endoflife, "dayhour");
-                }
-            }
-        }
-
-        $submit_enabled = 0;
-
-        print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?mode=setup&amp;driver='.$driver.'" autocomplete="off">';
-        print '<input type="hidden" name="token" value="'.newToken().'">';
-        print '<input type="hidden" name="action" value="setconst">';
-
-
-        print '<table class="noborder centpercent">'."\n";
-
-        print '<tr class="liste_titre">';
-        print '<th class="titlefieldcreate">'.$langs->trans($key[0]).'</th>';
-        print '<th></th>';
-        print '<th></th>';
-        print "</tr>\n";
-
-        print '<tr class="oddeven">';
-        print '<td'.($key['required'] ? ' class="required"' : '').'>';
-        //var_dump($key);
-        print $langs->trans("OAuthIDSecret").'</td>';
-        print '<td>';
-        print $langs->trans("SeePreviousTab");
-        print '</td>';
-        print '<td>';
-        print '</td>';
-        print '</tr>'."\n";
-
-        print '<tr class="oddeven">';
-        print '<td'.($key['required'] ? ' class="required"' : '').'>';
-        //var_dump($key);
-        print $langs->trans("IsTokenGenerated");
-        print '</td>';
-        print '<td>';
-        if (is_object($tokenobj)) print $langs->trans("HasAccessToken");
-        else print $langs->trans("NoAccessToken");
-        print '</td>';
-        print '<td>';
-        // Links to delete/checks token
-        if (is_object($tokenobj))
-        {
-            //test on $storage->hasAccessToken($OAUTH_SERVICENAME) ?
-            print '<a class="button" href="'.$urltodelete.'">'.$langs->trans('DeleteAccess').'</a><br>';
-        }
-        // Request remote token
-        if ($urltorenew)
-        {
-        	print '<a class="button" href="'.$urltorenew.'">'.$langs->trans('RequestAccess').'</a><br>';
-        }
-        // Check remote access
-        if ($urltocheckperms)
-        {
-            print '<br>'.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': <a href="'.$urltocheckperms.'" target="_'.strtolower($OAUTH_SERVICENAME).'">'.$urltocheckperms.'</a>';
-        }
-        print '</td>';
-        print '</tr>';
-
-        print '<tr class="oddeven">';
-        print '<td'.($key['required'] ? ' class="required"' : '').'>';
-        //var_dump($key);
-        print $langs->trans("Token").'</td>';
-        print '<td colspan="2">';
-        if (is_object($tokenobj))
-        {
-            //var_dump($tokenobj);
-            print $tokenobj->getAccessToken().'<br>';
-            //print 'Refresh: '.$tokenobj->getRefreshToken().'<br>';
-            //print 'EndOfLife: '.$tokenobj->getEndOfLife().'<br>';
-            //var_dump($tokenobj->getExtraParams());
-            /*print '<br>Extra: <br><textarea class="quatrevingtpercent">';
+		// Show value of token
+		$tokenobj = null;
+		// Token
+		require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
+		require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
+		// Dolibarr storage
+		$storage = new DoliStorage($db, $conf);
+		try {
+			$tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
+		} catch (Exception $e)
+		{
+			// Return an error if token not found
+		}
+
+		// Set other properties
+		$refreshtoken = false;
+		$expiredat = '';
+
+		$expire = false;
+		// Is token expired or will token expire in the next 30 seconds
+		if (is_object($tokenobj)) {
+			$expire = ($tokenobj->getEndOfLife() !== $tokenobj::EOL_NEVER_EXPIRES && $tokenobj->getEndOfLife() !== $tokenobj::EOL_UNKNOWN && time() > ($tokenobj->getEndOfLife() - 30));
+		}
+
+		if ($key[1] != '' && $key[2] != '') {
+			if (is_object($tokenobj)) {
+				$refreshtoken = $tokenobj->getRefreshToken();
+
+				$endoflife = $tokenobj->getEndOfLife();
+				if ($endoflife == $tokenobj::EOL_NEVER_EXPIRES)
+				{
+					$expiredat = $langs->trans("Never");
+				} elseif ($endoflife == $tokenobj::EOL_UNKNOWN)
+				{
+					$expiredat = $langs->trans("Unknown");
+				} else {
+					$expiredat = dol_print_date($endoflife, "dayhour");
+				}
+			}
+		}
+
+		$submit_enabled = 0;
+
+		print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?mode=setup&amp;driver='.$driver.'" autocomplete="off">';
+		print '<input type="hidden" name="token" value="'.newToken().'">';
+		print '<input type="hidden" name="action" value="setconst">';
+
+
+		print '<table class="noborder centpercent">'."\n";
+
+		print '<tr class="liste_titre">';
+		print '<th class="titlefieldcreate">'.$langs->trans($key[0]).'</th>';
+		print '<th></th>';
+		print '<th></th>';
+		print "</tr>\n";
+
+		print '<tr class="oddeven">';
+		print '<td'.($key['required'] ? ' class="required"' : '').'>';
+		//var_dump($key);
+		print $langs->trans("OAuthIDSecret").'</td>';
+		print '<td>';
+		print $langs->trans("SeePreviousTab");
+		print '</td>';
+		print '<td>';
+		print '</td>';
+		print '</tr>'."\n";
+
+		print '<tr class="oddeven">';
+		print '<td'.($key['required'] ? ' class="required"' : '').'>';
+		//var_dump($key);
+		print $langs->trans("IsTokenGenerated");
+		print '</td>';
+		print '<td>';
+		if (is_object($tokenobj)) print $langs->trans("HasAccessToken");
+		else print $langs->trans("NoAccessToken");
+		print '</td>';
+		print '<td>';
+		// Links to delete/checks token
+		if (is_object($tokenobj))
+		{
+			//test on $storage->hasAccessToken($OAUTH_SERVICENAME) ?
+			print '<a class="button" href="'.$urltodelete.'">'.$langs->trans('DeleteAccess').'</a><br>';
+		}
+		// Request remote token
+		if ($urltorenew)
+		{
+			print '<a class="button" href="'.$urltorenew.'">'.$langs->trans('RequestAccess').'</a><br>';
+		}
+		// Check remote access
+		if ($urltocheckperms)
+		{
+			print '<br>'.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': <a href="'.$urltocheckperms.'" target="_'.strtolower($OAUTH_SERVICENAME).'">'.$urltocheckperms.'</a>';
+		}
+		print '</td>';
+		print '</tr>';
+
+		print '<tr class="oddeven">';
+		print '<td'.($key['required'] ? ' class="required"' : '').'>';
+		//var_dump($key);
+		print $langs->trans("Token").'</td>';
+		print '<td colspan="2">';
+		if (is_object($tokenobj))
+		{
+			//var_dump($tokenobj);
+			print $tokenobj->getAccessToken().'<br>';
+			//print 'Refresh: '.$tokenobj->getRefreshToken().'<br>';
+			//print 'EndOfLife: '.$tokenobj->getEndOfLife().'<br>';
+			//var_dump($tokenobj->getExtraParams());
+			/*print '<br>Extra: <br><textarea class="quatrevingtpercent">';
             print ''.join(',',$tokenobj->getExtraParams());
             print '</textarea>';*/
-        }
-        print '</td>';
-        print '</tr>'."\n";
-
-        if (is_object($tokenobj))
-        {
-            // Token refresh
-            print '<tr class="oddeven">';
-            print '<td'.($key['required'] ? ' class="required"' : '').'>';
-            //var_dump($key);
-            print $langs->trans("TOKEN_REFRESH").'</td>';
-            print '<td colspan="2">';
-            print yn($refreshtoken);
-            print '</td>';
-            print '</tr>';
-
-            // Token expired
-            print '<tr class="oddeven">';
-            print '<td'.($key['required'] ? ' class="required"' : '').'>';
-            //var_dump($key);
-            print $langs->trans("TOKEN_EXPIRED").'</td>';
-            print '<td colspan="2">';
-            print yn($expire);
-            print '</td>';
-            print '</tr>';
-
-            // Token expired at
-            print '<tr class="oddeven">';
-            print '<td'.($key['required'] ? ' class="required"' : '').'>';
-            //var_dump($key);
-            print $langs->trans("TOKEN_EXPIRE_AT").'</td>';
-            print '<td colspan="2">';
-            print $expiredat;
-            print '</td>';
-            print '</tr>';
-        }
-
-        print '</table>';
-
-        if (!empty($driver))
-        {
-            if ($submit_enabled) {
-                print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Modify")).'"></div>';
-            }
-        }
-
-
-        print '</form>';
-    }
+		}
+		print '</td>';
+		print '</tr>'."\n";
+
+		if (is_object($tokenobj))
+		{
+			// Token refresh
+			print '<tr class="oddeven">';
+			print '<td'.($key['required'] ? ' class="required"' : '').'>';
+			//var_dump($key);
+			print $langs->trans("TOKEN_REFRESH").'</td>';
+			print '<td colspan="2">';
+			print yn($refreshtoken);
+			print '</td>';
+			print '</tr>';
+
+			// Token expired
+			print '<tr class="oddeven">';
+			print '<td'.($key['required'] ? ' class="required"' : '').'>';
+			//var_dump($key);
+			print $langs->trans("TOKEN_EXPIRED").'</td>';
+			print '<td colspan="2">';
+			print yn($expire);
+			print '</td>';
+			print '</tr>';
+
+			// Token expired at
+			print '<tr class="oddeven">';
+			print '<td'.($key['required'] ? ' class="required"' : '').'>';
+			//var_dump($key);
+			print $langs->trans("TOKEN_EXPIRE_AT").'</td>';
+			print '<td colspan="2">';
+			print $expiredat;
+			print '</td>';
+			print '</tr>';
+		}
+
+		print '</table>';
+
+		if (!empty($driver))
+		{
+			if ($submit_enabled) {
+				print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Modify")).'"></div>';
+			}
+		}
+
+
+		print '</form>';
+	}
 }
 
 if ($mode == 'test' && $user->admin)
 {
-    print $langs->trans('PrintTestDesc'.$driver)."<br><br>\n";
-
-    print '<table class="noborder centpercent">';
-    if (!empty($driver))
-    {
-        require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php';
-        $classname = 'printing_'.$driver;
-        $langs->load($driver);
-        $printer = new $classname($db);
-        //print '<pre>'.print_r($printer, true).'</pre>';
-        if (count($printer->getlistAvailablePrinters())) {
-            if ($printer->listAvailablePrinters() == 0) {
-                print $printer->resprint;
-            } else {
-                setEventMessages($printer->error, $printer->errors, 'errors');
-            }
-        } else {
-            print $langs->trans('PleaseConfigureDriverfromList');
-        }
-    }
-
-    print '</table>';
+	print $langs->trans('PrintTestDesc'.$driver)."<br><br>\n";
+
+	print '<table class="noborder centpercent">';
+	if (!empty($driver))
+	{
+		require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php';
+		$classname = 'printing_'.$driver;
+		$langs->load($driver);
+		$printer = new $classname($db);
+		//print '<pre>'.print_r($printer, true).'</pre>';
+		if (count($printer->getlistAvailablePrinters())) {
+			if ($printer->listAvailablePrinters() == 0) {
+				print $printer->resprint;
+			} else {
+				setEventMessages($printer->error, $printer->errors, 'errors');
+			}
+		} else {
+			print $langs->trans('PleaseConfigureDriverfromList');
+		}
+	}
+
+	print '</table>';
 }
 
 if ($mode == 'userconf' && $user->admin)
 {
-    print $langs->trans('PrintUserConfDesc'.$driver)."<br><br>\n";
-
-    print '<table class="noborder centpercent">';
-    print '<tr class="liste_titre">';
-    print '<th>'.$langs->trans("User").'</th>';
-    print '<th>'.$langs->trans("PrintModule").'</th>';
-    print '<th>'.$langs->trans("PrintDriver").'</th>';
-    print '<th>'.$langs->trans("Printer").'</th>';
-    print '<th>'.$langs->trans("PrinterLocation").'</th>';
-    print '<th>'.$langs->trans("PrinterId").'</th>';
-    print '<th>'.$langs->trans("NumberOfCopy").'</th>';
-    print '<th class="center">'.$langs->trans("Delete").'</th>';
-    print "</tr>\n";
-    $sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid';
-    $resql = $db->query($sql);
-    while ($row = $db->fetch_array($resql)) {
-        print '<tr class="oddeven">';
-        print '<td>'.$row['login'].'</td>';
-        print '<td>'.$row['module'].'</td>';
-        print '<td>'.$row['driver'].'</td>';
-        print '<td>'.$row['printer_name'].'</td>';
-        print '<td>'.$row['printer_location'].'</td>';
-        print '<td>'.$row['printer_id'].'</td>';
-        print '<td>'.$row['copy'].'</td>';
-        print '<td class="center">'.img_picto($langs->trans("Delete"), 'delete').'</td>';
-        print "</tr>\n";
-    }
-    print '</table>';
+	print $langs->trans('PrintUserConfDesc'.$driver)."<br><br>\n";
+
+	print '<table class="noborder centpercent">';
+	print '<tr class="liste_titre">';
+	print '<th>'.$langs->trans("User").'</th>';
+	print '<th>'.$langs->trans("PrintModule").'</th>';
+	print '<th>'.$langs->trans("PrintDriver").'</th>';
+	print '<th>'.$langs->trans("Printer").'</th>';
+	print '<th>'.$langs->trans("PrinterLocation").'</th>';
+	print '<th>'.$langs->trans("PrinterId").'</th>';
+	print '<th>'.$langs->trans("NumberOfCopy").'</th>';
+	print '<th class="center">'.$langs->trans("Delete").'</th>';
+	print "</tr>\n";
+	$sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid';
+	$resql = $db->query($sql);
+	while ($row = $db->fetch_array($resql)) {
+		print '<tr class="oddeven">';
+		print '<td>'.$row['login'].'</td>';
+		print '<td>'.$row['module'].'</td>';
+		print '<td>'.$row['driver'].'</td>';
+		print '<td>'.$row['printer_name'].'</td>';
+		print '<td>'.$row['printer_location'].'</td>';
+		print '<td>'.$row['printer_id'].'</td>';
+		print '<td>'.$row['copy'].'</td>';
+		print '<td class="center">'.img_picto($langs->trans("Delete"), 'delete').'</td>';
+		print "</tr>\n";
+	}
+	print '</table>';
 }
 
 dol_fiche_end();

+ 331 - 331
htdocs/admin/receiptprinter.php

@@ -53,16 +53,16 @@ if (!$mode) $mode = 'config';
 
 // used in library escpos maybe useful if php doesn't support gzdecode
 if (!function_exists('gzdecode')) {
-    /**
-     * Gzdecode
-     *
-     * @param string    $data   data to deflate
-     * @return string           data deflated
-     */
-    function gzdecode($data)
-    {
-        return gzinflate(substr($data, 10, -8));
-    }
+	/**
+	 * Gzdecode
+	 *
+	 * @param string    $data   data to deflate
+	 * @return string           data deflated
+	 */
+	function gzdecode($data)
+	{
+		return gzinflate(substr($data, 10, -8));
+	}
 }
 
 
@@ -71,167 +71,167 @@ if (!function_exists('gzdecode')) {
  */
 
 if ($action == 'addprinter' && $user->admin) {
-    $error = 0;
-    if (empty($printername)) {
-        $error++;
-        setEventMessages($langs->trans("PrinterNameEmpty"), null, 'errors');
-    }
-
-    if (empty($parameter)) {
-        setEventMessages($langs->trans("PrinterParameterEmpty"), null, 'warnings');
-    }
-
-    if (!$error) {
-    	$db->begin();
-    	$result = $printer->addPrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter);
-        if ($result > 0) $error++;
-
-        if (!$error)
-        {
-            $db->commit();
-            setEventMessages($langs->trans("PrinterAdded", $printername), null);
-        } else {
-            $db->rollback();
-            dol_print_error($db);
-        }
-    }
-    $action = '';
+	$error = 0;
+	if (empty($printername)) {
+		$error++;
+		setEventMessages($langs->trans("PrinterNameEmpty"), null, 'errors');
+	}
+
+	if (empty($parameter)) {
+		setEventMessages($langs->trans("PrinterParameterEmpty"), null, 'warnings');
+	}
+
+	if (!$error) {
+		$db->begin();
+		$result = $printer->addPrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter);
+		if ($result > 0) $error++;
+
+		if (!$error)
+		{
+			$db->commit();
+			setEventMessages($langs->trans("PrinterAdded", $printername), null);
+		} else {
+			$db->rollback();
+			dol_print_error($db);
+		}
+	}
+	$action = '';
 }
 
 if ($action == 'deleteprinter' && $user->admin) {
-    $error = 0;
-    if (empty($printerid)) {
-        $error++;
-        setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors');
-    }
-
-    if (!$error) {
-    	$db->begin();
-    	$result = $printer->deletePrinter($printerid);
-        if ($result > 0) $error++;
-
-        if (!$error)
-        {
-            $db->commit();
-            setEventMessages($langs->trans("PrinterDeleted", $printername), null);
-        } else {
-            $db->rollback();
-            dol_print_error($db);
-        }
-    }
-    $action = '';
+	$error = 0;
+	if (empty($printerid)) {
+		$error++;
+		setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors');
+	}
+
+	if (!$error) {
+		$db->begin();
+		$result = $printer->deletePrinter($printerid);
+		if ($result > 0) $error++;
+
+		if (!$error)
+		{
+			$db->commit();
+			setEventMessages($langs->trans("PrinterDeleted", $printername), null);
+		} else {
+			$db->rollback();
+			dol_print_error($db);
+		}
+	}
+	$action = '';
 }
 
 if ($action == 'updateprinter' && $user->admin) {
-    $error = 0;
-    if (empty($printerid)) {
-        $error++;
-        setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors');
-    }
-
-    if (!$error) {
-    	$db->begin();
-    	$result = $printer->updatePrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter, $printerid);
-        if ($result > 0) $error++;
-
-        if (!$error) {
-            $db->commit();
-            setEventMessages($langs->trans("PrinterUpdated", $printername), null);
-        } else {
-            $db->rollback();
-            dol_print_error($db);
-        }
-    }
-    $action = '';
+	$error = 0;
+	if (empty($printerid)) {
+		$error++;
+		setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors');
+	}
+
+	if (!$error) {
+		$db->begin();
+		$result = $printer->updatePrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter, $printerid);
+		if ($result > 0) $error++;
+
+		if (!$error) {
+			$db->commit();
+			setEventMessages($langs->trans("PrinterUpdated", $printername), null);
+		} else {
+			$db->rollback();
+			dol_print_error($db);
+		}
+	}
+	$action = '';
 }
 
 if ($action == 'testprinter' && $user->admin) {
-    $error = 0;
-    if (empty($printerid)) {
-        $error++;
-        setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors');
-    }
-
-    if (!$error) {
-        // test
-        $ret = $printer->sendTestToPrinter($printerid);
-        if ($ret == 0) {
-            setEventMessages($langs->trans("TestSentToPrinter", $printername), null);
-        } else {
-            setEventMessages($printer->error, $printer->errors, 'errors');
-        }
-    }
-    $action = '';
+	$error = 0;
+	if (empty($printerid)) {
+		$error++;
+		setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors');
+	}
+
+	if (!$error) {
+		// test
+		$ret = $printer->sendTestToPrinter($printerid);
+		if ($ret == 0) {
+			setEventMessages($langs->trans("TestSentToPrinter", $printername), null);
+		} else {
+			setEventMessages($printer->error, $printer->errors, 'errors');
+		}
+	}
+	$action = '';
 }
 
 if ($action == 'testtemplate' && $user->admin) {
-    $error = 0;
-    // if (empty($printerid)) {
-    //     $error++;
-    //     setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors');
-    // }
+	$error = 0;
+	// if (empty($printerid)) {
+	//     $error++;
+	//     setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors');
+	// }
 
-    // if (! $error) {
+	// if (! $error) {
 	// test
 	require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
 	$object = new Facture($db);
 	//$object->initAsSpecimen();
 	$object->fetch(18);
 	//var_dump($object->lines);
-    $ret = $printer->sendToPrinter($object, $templateid, 1);
-    if ($ret == 0) {
-        setEventMessages($langs->trans("TestTemplateToPrinter", $printername), null);
-    } else {
-        setEventMessages($printer->error, $printer->errors, 'errors');
-    }
-    //}
-    $action = '';
+	$ret = $printer->sendToPrinter($object, $templateid, 1);
+	if ($ret == 0) {
+		setEventMessages($langs->trans("TestTemplateToPrinter", $printername), null);
+	} else {
+		setEventMessages($printer->error, $printer->errors, 'errors');
+	}
+	//}
+	$action = '';
 }
 
 if ($action == 'updatetemplate' && $user->admin) {
-    $error = 0;
-    if (empty($templateid)) {
-        $error++;
-        setEventMessages($langs->trans("TemplateIdEmpty"), null, 'errors');
-    }
-
-    if (!$error) {
-    	$db->begin();
-    	$result = $printer->updateTemplate($templatename, $template, $templateid);
-        if ($result > 0) $error++;
-
-        if (!$error) {
-            $db->commit();
-            setEventMessages($langs->trans("TemplateUpdated", $templatename), null);
-        } else {
-            $db->rollback();
-            dol_print_error($db);
-        }
-    }
-    $action = '';
+	$error = 0;
+	if (empty($templateid)) {
+		$error++;
+		setEventMessages($langs->trans("TemplateIdEmpty"), null, 'errors');
+	}
+
+	if (!$error) {
+		$db->begin();
+		$result = $printer->updateTemplate($templatename, $template, $templateid);
+		if ($result > 0) $error++;
+
+		if (!$error) {
+			$db->commit();
+			setEventMessages($langs->trans("TemplateUpdated", $templatename), null);
+		} else {
+			$db->rollback();
+			dol_print_error($db);
+		}
+	}
+	$action = '';
 }
 
 if ($action == 'addtemplate' && $user->admin) {
-    $error = 0;
-    if (empty($templatename)) {
-        $error++;
-        setEventMessages($langs->trans("TemplateNameEmpty"), null, 'errors');
-    }
-
-    if (!$error) {
-    	$db->begin();
-    	$result = $printer->addTemplate($templatename, $template);
-        if ($result > 0) $error++;
-
-        if (!$error) {
-            $db->commit();
-            setEventMessages($langs->trans("TemplateAdded", $templatename), null);
-        } else {
-            $db->rollback();
-            dol_print_error($db);
-        }
-    }
-    $action = '';
+	$error = 0;
+	if (empty($templatename)) {
+		$error++;
+		setEventMessages($langs->trans("TemplateNameEmpty"), null, 'errors');
+	}
+
+	if (!$error) {
+		$db->begin();
+		$result = $printer->addTemplate($templatename, $template);
+		if ($result > 0) $error++;
+
+		if (!$error) {
+			$db->commit();
+			setEventMessages($langs->trans("TemplateAdded", $templatename), null);
+		} else {
+			$db->rollback();
+			dol_print_error($db);
+		}
+	}
+	$action = '';
 }
 
 if ($action == 'deletetemplate' && $user->admin) {
@@ -273,116 +273,116 @@ $head = receiptprinteradmin_prepare_head($mode);
 
 // mode = config
 if ($mode == 'config' && $user->admin) {
-    print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?mode=config" autocomplete="off">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    if ($action != 'editprinter') {
-        print '<input type="hidden" name="action" value="addprinter">';
-    } else {
-        print '<input type="hidden" name="action" value="updateprinter">';
-    }
-
-
-    dol_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic');
-
-    print '<span class="opacitymedium">'.$langs->trans("ReceiptPrinterDesc")."</span><br><br>\n";
-
-    print '<table class="noborder centpercent">'."\n";
-    print '<tr class="liste_titre">';
-    print '<th>'.$langs->trans("Name").'</th>';
-    print '<th>'.$langs->trans("Type").'</th>';
-    print '<th>'.$langs->trans("Profile").'</th>';
-    print '<th>'.$langs->trans("Parameters").'</th>';
-    print '<th></th>';
-    print "</tr>\n";
-    $ret = $printer->listprinters();
-    $nbofprinters = count($printer->listprinters);
-
-    if ($action != 'editprinter') {
-    	print '<tr>';
-    	print '<td><input size="50" type="text" name="printername"></td>';
-    	$ret = $printer->selectTypePrinter();
-    	print '<td>'.$printer->resprint.'</td>';
-    	$ret = $printer->selectProfilePrinter();
-    	print '<td>'.$printer->profileresprint.'</td>';
-    	print '<td><input size="60" type="text" name="parameter"></td>';
-    	print '<td class="right">';
-    	if ($action != 'editprinter') {
-    		print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Add")).'"></div>';
-    	}
-    	print '</td>';
-    	print '</tr>';
-    }
-
-    if ($ret > 0) {
-        setEventMessages($printer->error, $printer->errors, 'errors');
-    } else {
-        for ($line = 0; $line < $nbofprinters; $line++) {
-            print '<tr class="oddeven">';
-            if ($action == 'editprinter' && $printer->listprinters[$line]['rowid'] == $printerid) {
-                print '<input type="hidden" name="printerid" value="'.$printer->listprinters[$line]['rowid'].'">';
-                print '<td><input size="50" type="text" name="printername" value="'.$printer->listprinters[$line]['name'].'"></td>';
-                $ret = $printer->selectTypePrinter($printer->listprinters[$line]['fk_type']);
-                print '<td>'.$printer->resprint.'</td>';
-                $ret = $printer->selectProfilePrinter($printer->listprinters[$line]['fk_profile']);
-                print '<td>'.$printer->profileresprint.'</td>';
-                print '<td><input size="60" type="text" name="parameter" value="'.$printer->listprinters[$line]['parameter'].'"></td>';
-                print '<td>';
-                print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Save")).'"></div>';
-                print '</td>';
-                print '</tr>';
-            } else {
-                print '<td>'.$printer->listprinters[$line]['name'].'</td>';
-                print '<td>'.$langs->trans($printer->listprinters[$line]['fk_type_name']).'</td>';
-                print '<td>'.$langs->trans($printer->listprinters[$line]['fk_profile_name']).'</td>';
-                print '<td>'.$printer->listprinters[$line]['parameter'].'</td>';
-                // edit icon
-                print '<td class="right"><a class="editfielda marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=config&amp;action=editprinter&amp;printerid='.$printer->listprinters[$line]['rowid'].'">';
-                print img_picto($langs->trans("Edit"), 'edit');
-                print '</a>';
-                // delete icon
-                print '<a class="marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=config&amp;action=deleteprinter&amp;token='.newToken().'&amp;printerid='.$printer->listprinters[$line]['rowid'].'&amp;printername='.$printer->listprinters[$line]['name'].'">';
-                print img_picto($langs->trans("Delete"), 'delete');
-                print '</a>';
-                // test icon
-                print '<a class="marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=config&amp;action=testprinter&amp;token='.newToken().'&amp;printerid='.$printer->listprinters[$line]['rowid'].'&amp;printername='.$printer->listprinters[$line]['name'].'">';
-                print img_picto($langs->trans("TestPrinter"), 'printer');
-                print '</a></td>';
-                print '</tr>';
-            }
-        }
-    }
-
-    print '</table>';
-
-    dol_fiche_end();
-
-    print '</form>';
-
-    print '<br>';
-
-
-    print load_fiche_titre($langs->trans("ReceiptPrinterTypeDesc"), '', '')."\n";
-
-    print '<table class="noborder centpercent">'."\n";
-    print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_DUMMY").':</td><td>'.$langs->trans("CONNECTOR_DUMMY_HELP").'</td></tr>';
-    print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_NETWORK_PRINT").':</td><td>'.$langs->trans("CONNECTOR_NETWORK_PRINT_HELP").'</td></tr>';
-    print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_FILE_PRINT").':</td><td>'.$langs->trans("CONNECTOR_FILE_PRINT_HELP").'</td></tr>';
-    print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_WINDOWS_PRINT").':</td><td>'.$langs->trans("CONNECTOR_WINDOWS_PRINT_HELP").'</td></tr>';
-    print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_CUPS_PRINT").':</td><td>'.$langs->trans("CONNECTOR_CUPS_PRINT_HELP").'</td></tr>';
-    print '</table>';
-
-    print '<br>';
-
-
-    print load_fiche_titre($langs->trans("ReceiptPrinterProfileDesc"), '', '')."\n";
-
-    print '<table class="noborder centpercent">'."\n";
-    print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_DEFAULT").':</td><td>'.$langs->trans("PROFILE_DEFAULT_HELP").'</td></tr>';
-    print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_SIMPLE").':</td><td>'.$langs->trans("PROFILE_SIMPLE_HELP").'</td></tr>';
-    print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_EPOSTEP").':</td><td>'.$langs->trans("PROFILE_EPOSTEP_HELP").'</td></tr>';
-    print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_P822D").':</td><td>'.$langs->trans("PROFILE_P822D_HELP").'</td></tr>';
-    print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_STAR").':</td><td>'.$langs->trans("PROFILE_STAR_HELP").'</td></tr>';
-    print '</table>';
+	print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?mode=config" autocomplete="off">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	if ($action != 'editprinter') {
+		print '<input type="hidden" name="action" value="addprinter">';
+	} else {
+		print '<input type="hidden" name="action" value="updateprinter">';
+	}
+
+
+	dol_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic');
+
+	print '<span class="opacitymedium">'.$langs->trans("ReceiptPrinterDesc")."</span><br><br>\n";
+
+	print '<table class="noborder centpercent">'."\n";
+	print '<tr class="liste_titre">';
+	print '<th>'.$langs->trans("Name").'</th>';
+	print '<th>'.$langs->trans("Type").'</th>';
+	print '<th>'.$langs->trans("Profile").'</th>';
+	print '<th>'.$langs->trans("Parameters").'</th>';
+	print '<th></th>';
+	print "</tr>\n";
+	$ret = $printer->listprinters();
+	$nbofprinters = count($printer->listprinters);
+
+	if ($action != 'editprinter') {
+		print '<tr>';
+		print '<td><input size="50" type="text" name="printername"></td>';
+		$ret = $printer->selectTypePrinter();
+		print '<td>'.$printer->resprint.'</td>';
+		$ret = $printer->selectProfilePrinter();
+		print '<td>'.$printer->profileresprint.'</td>';
+		print '<td><input size="60" type="text" name="parameter"></td>';
+		print '<td class="right">';
+		if ($action != 'editprinter') {
+			print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Add")).'"></div>';
+		}
+		print '</td>';
+		print '</tr>';
+	}
+
+	if ($ret > 0) {
+		setEventMessages($printer->error, $printer->errors, 'errors');
+	} else {
+		for ($line = 0; $line < $nbofprinters; $line++) {
+			print '<tr class="oddeven">';
+			if ($action == 'editprinter' && $printer->listprinters[$line]['rowid'] == $printerid) {
+				print '<input type="hidden" name="printerid" value="'.$printer->listprinters[$line]['rowid'].'">';
+				print '<td><input size="50" type="text" name="printername" value="'.$printer->listprinters[$line]['name'].'"></td>';
+				$ret = $printer->selectTypePrinter($printer->listprinters[$line]['fk_type']);
+				print '<td>'.$printer->resprint.'</td>';
+				$ret = $printer->selectProfilePrinter($printer->listprinters[$line]['fk_profile']);
+				print '<td>'.$printer->profileresprint.'</td>';
+				print '<td><input size="60" type="text" name="parameter" value="'.$printer->listprinters[$line]['parameter'].'"></td>';
+				print '<td>';
+				print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Save")).'"></div>';
+				print '</td>';
+				print '</tr>';
+			} else {
+				print '<td>'.$printer->listprinters[$line]['name'].'</td>';
+				print '<td>'.$langs->trans($printer->listprinters[$line]['fk_type_name']).'</td>';
+				print '<td>'.$langs->trans($printer->listprinters[$line]['fk_profile_name']).'</td>';
+				print '<td>'.$printer->listprinters[$line]['parameter'].'</td>';
+				// edit icon
+				print '<td class="right"><a class="editfielda marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=config&amp;action=editprinter&amp;printerid='.$printer->listprinters[$line]['rowid'].'">';
+				print img_picto($langs->trans("Edit"), 'edit');
+				print '</a>';
+				// delete icon
+				print '<a class="marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=config&amp;action=deleteprinter&amp;token='.newToken().'&amp;printerid='.$printer->listprinters[$line]['rowid'].'&amp;printername='.$printer->listprinters[$line]['name'].'">';
+				print img_picto($langs->trans("Delete"), 'delete');
+				print '</a>';
+				// test icon
+				print '<a class="marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=config&amp;action=testprinter&amp;token='.newToken().'&amp;printerid='.$printer->listprinters[$line]['rowid'].'&amp;printername='.$printer->listprinters[$line]['name'].'">';
+				print img_picto($langs->trans("TestPrinter"), 'printer');
+				print '</a></td>';
+				print '</tr>';
+			}
+		}
+	}
+
+	print '</table>';
+
+	dol_fiche_end();
+
+	print '</form>';
+
+	print '<br>';
+
+
+	print load_fiche_titre($langs->trans("ReceiptPrinterTypeDesc"), '', '')."\n";
+
+	print '<table class="noborder centpercent">'."\n";
+	print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_DUMMY").':</td><td>'.$langs->trans("CONNECTOR_DUMMY_HELP").'</td></tr>';
+	print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_NETWORK_PRINT").':</td><td>'.$langs->trans("CONNECTOR_NETWORK_PRINT_HELP").'</td></tr>';
+	print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_FILE_PRINT").':</td><td>'.$langs->trans("CONNECTOR_FILE_PRINT_HELP").'</td></tr>';
+	print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_WINDOWS_PRINT").':</td><td>'.$langs->trans("CONNECTOR_WINDOWS_PRINT_HELP").'</td></tr>';
+	print '<tr class="oddeven"><td>'.$langs->trans("CONNECTOR_CUPS_PRINT").':</td><td>'.$langs->trans("CONNECTOR_CUPS_PRINT_HELP").'</td></tr>';
+	print '</table>';
+
+	print '<br>';
+
+
+	print load_fiche_titre($langs->trans("ReceiptPrinterProfileDesc"), '', '')."\n";
+
+	print '<table class="noborder centpercent">'."\n";
+	print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_DEFAULT").':</td><td>'.$langs->trans("PROFILE_DEFAULT_HELP").'</td></tr>';
+	print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_SIMPLE").':</td><td>'.$langs->trans("PROFILE_SIMPLE_HELP").'</td></tr>';
+	print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_EPOSTEP").':</td><td>'.$langs->trans("PROFILE_EPOSTEP_HELP").'</td></tr>';
+	print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_P822D").':</td><td>'.$langs->trans("PROFILE_P822D_HELP").'</td></tr>';
+	print '<tr class="oddeven"><td>'.$langs->trans("PROFILE_STAR").':</td><td>'.$langs->trans("PROFILE_STAR_HELP").'</td></tr>';
+	print '</table>';
 }
 
 // mode = template
@@ -390,56 +390,56 @@ if ($mode == 'template' && $user->admin) {
 	dol_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic');
 
 	print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?mode=template" autocomplete="off">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    if ($action != 'edittemplate') {
-        print '<input type="hidden" name="action" value="addtemplate">';
-    } else {
-        print '<input type="hidden" name="action" value="updatetemplate">';
-    }
-
-    print '<table class="noborder centpercent">'."\n";
-    print '<tr class="liste_titre">';
-    print '<th>'.$langs->trans("Name").'</th>';
-    print '<th>'.$langs->trans("Template").'</th>';
-    print '<th></th>';
-    print "</tr>\n";
-    $ret = $printer->listPrintersTemplates();
-    //print '<pre>'.print_r($printer->listprinterstemplates, true).'</pre>';
-    if ($ret > 0) {
-        setEventMessages($printer->error, $printer->errors, 'errors');
-    } else {
-        $max = count($printer->listprinterstemplates);
-        for ($line = 0; $line < $max; $line++) {
-            print '<tr class="oddeven">';
-            if ($action == 'edittemplate' && $printer->listprinterstemplates[$line]['rowid'] == $templateid) {
-                print '<input type="hidden" name="templateid" value="'.$printer->listprinterstemplates[$line]['rowid'].'">';
-                print '<td><input size="50" type="text" name="templatename" value="'.$printer->listprinterstemplates[$line]['name'].'"></td>';
-                print '<td>';
-                print '<textarea name="template" wrap="soft" cols="120" rows="12">'.$printer->listprinterstemplates[$line]['template'].'</textarea>';
-                print '</td>';
-                print '<td></td>';
-            } else {
-                print '<td>'.$printer->listprinterstemplates[$line]['name'].'</td>';
-                print '<td>'.nl2br(htmlentities($printer->listprinterstemplates[$line]['template'])).'</td>';
-                // edit icon
-                print '<td><a class="editfielda paddingleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=template&amp;action=edittemplate&amp;templateid='.$printer->listprinterstemplates[$line]['rowid'].'">';
-                print img_picto($langs->trans("Edit"), 'edit');
-                print '</a>';
-                // delete icon
-                print '<a class="paddingleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=template&amp;action=deletetemplate&amp;templateid='.$printer->listprinterstemplates[$line]['rowid'].'&amp;templatename='.$printer->listprinterstemplates[$line]['name'].'">';
-                print img_picto($langs->trans("Delete"), 'delete');
-                print '</a>';
-                // test icon
-                print '<a class="paddingleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=template&amp;action=testtemplate&amp;templateid='.$printer->listprinterstemplates[$line]['rowid'].'&amp;templatename='.$printer->listprinterstemplates[$line]['name'].'">';
-                print img_picto($langs->trans("TestPrinterTemplate"), 'printer');
-                print '</a></td>';
-            }
-            print '</tr>';
-        }
-    }
-
-    if ($action != 'edittemplate') {
-    	print '<tr>';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	if ($action != 'edittemplate') {
+		print '<input type="hidden" name="action" value="addtemplate">';
+	} else {
+		print '<input type="hidden" name="action" value="updatetemplate">';
+	}
+
+	print '<table class="noborder centpercent">'."\n";
+	print '<tr class="liste_titre">';
+	print '<th>'.$langs->trans("Name").'</th>';
+	print '<th>'.$langs->trans("Template").'</th>';
+	print '<th></th>';
+	print "</tr>\n";
+	$ret = $printer->listPrintersTemplates();
+	//print '<pre>'.print_r($printer->listprinterstemplates, true).'</pre>';
+	if ($ret > 0) {
+		setEventMessages($printer->error, $printer->errors, 'errors');
+	} else {
+		$max = count($printer->listprinterstemplates);
+		for ($line = 0; $line < $max; $line++) {
+			print '<tr class="oddeven">';
+			if ($action == 'edittemplate' && $printer->listprinterstemplates[$line]['rowid'] == $templateid) {
+				print '<input type="hidden" name="templateid" value="'.$printer->listprinterstemplates[$line]['rowid'].'">';
+				print '<td><input size="50" type="text" name="templatename" value="'.$printer->listprinterstemplates[$line]['name'].'"></td>';
+				print '<td>';
+				print '<textarea name="template" wrap="soft" cols="120" rows="12">'.$printer->listprinterstemplates[$line]['template'].'</textarea>';
+				print '</td>';
+				print '<td></td>';
+			} else {
+				print '<td>'.$printer->listprinterstemplates[$line]['name'].'</td>';
+				print '<td>'.nl2br(htmlentities($printer->listprinterstemplates[$line]['template'])).'</td>';
+				// edit icon
+				print '<td><a class="editfielda paddingleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=template&amp;action=edittemplate&amp;templateid='.$printer->listprinterstemplates[$line]['rowid'].'">';
+				print img_picto($langs->trans("Edit"), 'edit');
+				print '</a>';
+				// delete icon
+				print '<a class="paddingleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=template&amp;action=deletetemplate&amp;templateid='.$printer->listprinterstemplates[$line]['rowid'].'&amp;templatename='.$printer->listprinterstemplates[$line]['name'].'">';
+				print img_picto($langs->trans("Delete"), 'delete');
+				print '</a>';
+				// test icon
+				print '<a class="paddingleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=template&amp;action=testtemplate&amp;templateid='.$printer->listprinterstemplates[$line]['rowid'].'&amp;templatename='.$printer->listprinterstemplates[$line]['name'].'">';
+				print img_picto($langs->trans("TestPrinterTemplate"), 'printer');
+				print '</a></td>';
+			}
+			print '</tr>';
+		}
+	}
+
+	if ($action != 'edittemplate') {
+		print '<tr>';
 		print '<td><input size="50" type="text" name="templatename" value="'.$printer->listprinterstemplates[$line]['name'].'"></td>';
 		print '<td>';
 		print '<textarea name="template" wrap="soft" cols="120" rows="12">';
@@ -448,35 +448,35 @@ if ($mode == 'template' && $user->admin) {
 		print '</td>';
 		print '<td></td>';
 		print '</tr>';
-    }
+	}
 
-    print '</table>';
+	print '</table>';
 
-    if ($action != 'edittemplate') {
+	if ($action != 'edittemplate') {
 		print '<input type="hidden" name="templateid" value="'.$printer->listprinterstemplates[$line]['rowid'].'">';
 		print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Add")).'"></div>';
-    } else {
-        print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Save")).'"></div>';
-    }
-    print '</form>';
-
-    dol_fiche_end();
-
-    print '<br>';
-
-    print '<table class="noborder centpercent">'."\n";
-    print '<tr class="liste_titre">';
-    print '<th>'.$langs->trans("Tag").'</th>';
-    print '<th>'.$langs->trans("Description").'</th>';
-    print "</tr>\n";
-
-    $langs->loadLangs(array("bills", "companies"));
-    foreach ($printer->tags as $key => $val) {
-        print '<tr class="oddeven">';
-        print '<td>&lt;'.$key.'&gt;</td><td>'.$langs->trans($val).'</td>';
-        print '</tr>';
-    }
-    print '</table>';
+	} else {
+		print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Save")).'"></div>';
+	}
+	print '</form>';
+
+	dol_fiche_end();
+
+	print '<br>';
+
+	print '<table class="noborder centpercent">'."\n";
+	print '<tr class="liste_titre">';
+	print '<th>'.$langs->trans("Tag").'</th>';
+	print '<th>'.$langs->trans("Description").'</th>';
+	print "</tr>\n";
+
+	$langs->loadLangs(array("bills", "companies"));
+	foreach ($printer->tags as $key => $val) {
+		print '<tr class="oddeven">';
+		print '<td>&lt;'.$key.'&gt;</td><td>'.$langs->trans($val).'</td>';
+		print '</tr>';
+	}
+	print '</table>';
 }
 
 // End of page

+ 10 - 10
htdocs/admin/security_file.php

@@ -45,9 +45,9 @@ $upload_dir = $conf->admin->dir_temp;
 
 if (GETPOST('sendit') && !empty($conf->global->MAIN_UPLOAD_DOC))
 {
-    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 
-    dol_add_file_process($upload_dir, 1, 0, 'userfile');
+	dol_add_file_process($upload_dir, 1, 0, 'userfile');
 }
 
 if ($action == 'updateform')
@@ -144,14 +144,14 @@ print '</td>';
 print '<td>';
 if (ini_get('safe_mode') && !empty($conf->global->MAIN_ANTIVIRUS_COMMAND))
 {
-    $langs->load("errors");
-    $basedir = preg_replace('/"/', '', dirname($conf->global->MAIN_ANTIVIRUS_COMMAND));
-    $listdir = explode(';', ini_get('safe_mode_exec_dir'));
-    if (!in_array($basedir, $listdir))
-    {
-        print img_warning($langs->trans('WarningSafeModeOnCheckExecDir'));
-        dol_syslog("safe_mode is on, basedir is ".$basedir.", safe_mode_exec_dir is ".ini_get('safe_mode_exec_dir'), LOG_WARNING);
-    }
+	$langs->load("errors");
+	$basedir = preg_replace('/"/', '', dirname($conf->global->MAIN_ANTIVIRUS_COMMAND));
+	$listdir = explode(';', ini_get('safe_mode_exec_dir'));
+	if (!in_array($basedir, $listdir))
+	{
+		print img_warning($langs->trans('WarningSafeModeOnCheckExecDir'));
+		dol_syslog("safe_mode is on, basedir is ".$basedir.", safe_mode_exec_dir is ".ini_get('safe_mode_exec_dir'), LOG_WARNING);
+	}
 }
 print '<input type="text" name="MAIN_ANTIVIRUS_COMMAND" class="minwidth500imp" value="'.(!empty($conf->global->MAIN_ANTIVIRUS_COMMAND) ?dol_escape_htmltag($conf->global->MAIN_ANTIVIRUS_COMMAND) : '').'">';
 if (defined('MAIN_ANTIVIRUS_COMMAND')) {

+ 225 - 225
htdocs/admin/tools/dolibarr_export.php

@@ -155,19 +155,19 @@ print '<td class="tdtop">';
 print '<div id="div_container_exportoptions">';
 print '<fieldset id="exportoptions"><legend>'.$langs->trans("ExportMethod").'</legend>';
 if (in_array($type, array('mysql', 'mysqli'))) {
-    print '<div class="formelementrow"><input type="radio" name="what" value="mysql" id="radio_dump_mysql" />';
-    print '<label for="radio_dump_mysql">MySQL	Dump (mysqldump)</label>';
-    print '</div>';
-    print '<br>';
-    print '<div class="formelementrow"><input type="radio" name="what" value="mysqlnobin" id="radio_dump_mysql_nobin" />';
-    print '<label for="radio_dump_mysql_nobin">MySQL Dump (php) '.img_warning($langs->trans('BackupPHPWarning')).'</label>';
-    print '</div>';
+	print '<div class="formelementrow"><input type="radio" name="what" value="mysql" id="radio_dump_mysql" />';
+	print '<label for="radio_dump_mysql">MySQL	Dump (mysqldump)</label>';
+	print '</div>';
+	print '<br>';
+	print '<div class="formelementrow"><input type="radio" name="what" value="mysqlnobin" id="radio_dump_mysql_nobin" />';
+	print '<label for="radio_dump_mysql_nobin">MySQL Dump (php) '.img_warning($langs->trans('BackupPHPWarning')).'</label>';
+	print '</div>';
 } elseif (in_array($type, array('pgsql'))) {
-    print '<div class="formelementrow"><input type="radio" name="what" value="postgresql" id="radio_dump_postgresql" />';
-    print '<label for="radio_dump_postgresql">PostgreSQL Dump (pg_dump)</label>';
-    print '</div>';
+	print '<div class="formelementrow"><input type="radio" name="what" value="postgresql" id="radio_dump_postgresql" />';
+	print '<label for="radio_dump_postgresql">PostgreSQL Dump (pg_dump)</label>';
+	print '</div>';
 } else {
-    print 'No method available with database '.$label;
+	print 'No method available with database '.$label;
 }
 print '</fieldset>';
 print '</div>';
@@ -178,200 +178,200 @@ print '<td class="tdtop">';
 
 print '<div id="div_container_sub_exportoptions">';
 if (in_array($type, array('mysql', 'mysqli'))) {
-    print "<!--  Fieldset mysqldump -->\n";
-    print '<fieldset id="mysql_options"><legend>'.$langs->trans("MySqlExportParameters").'</legend>';
-
-    print '<div class="formelementrow">'.$langs->trans("FullPathToMysqldumpCommand");
-    if (empty($conf->global->SYSTEMTOOLS_MYSQLDUMP))
-    {
-        $fullpathofmysqldump = $db->getPathOfDump();
-    } else {
-        $fullpathofmysqldump = $conf->global->SYSTEMTOOLS_MYSQLDUMP;
-    }
-    print '<br>';
-    print '<input type="text" name="mysqldump" style="width: 80%" value="'.$fullpathofmysqldump.'" /></div>';
-
-    print '<br>';
-    print '<fieldset><legend>'.$langs->trans("ExportOptions").'</legend>';
-    print '<div class="formelementrow">';
-    print '<input type="checkbox" name="use_transaction" value="yes" id="checkbox_use_transaction" />';
-    print '<label for="checkbox_use_transaction">'.$langs->trans("UseTransactionnalMode").'</label>';
-    print '</div>';
-
-    if (!empty($conf->global->MYSQL_OLD_OPTION_DISABLE_FK)) {
-        print '<div class="formelementrow">';
-        print '<input type="checkbox" name="disable_fk" value="yes" id="checkbox_disable_fk" checked />';
-        print '<label for="checkbox_disable_fk">'.$langs->trans("CommandsToDisableForeignKeysForImport").' '.img_info($langs->trans('CommandsToDisableForeignKeysForImportWarning')).'</label>';
-        print '</div>';
-    }
-
-    print '<label for="select_sql_compat">'.$langs->trans("ExportCompatibility").'</label>';
-
-    print '<select name="sql_compat" id="select_sql_compat" class="flat">';
-    print '<option value="NONE" selected>NONE</option>';
-    print '<option value="ANSI">ANSI</option>';
-    print '<option value="DB2">DB2</option>';
-    print '<option value="MAXDB">MAXDB</option>';
-    print '<option value="MYSQL323">MYSQL323</option>';
-    print '<option value="MYSQL40">MYSQL40</option>';
-    print '<option value="MSSQL">MSSQL</option>';
-    print '<option value="ORACLE">ORACLE</option>';
-    print '<option value="POSTGRESQL">POSTGRESQL</option>';
-    print '</select>';
-    print '<br>';
-
-    print '<input type="checkbox" name="use_mysql_quick_param" value="yes" id="checkbox_use_quick" />';
-    print '<label for="checkbox_use_quick">';
-    print $form->textwithpicto($langs->trans('ExportUseMySQLQuickParameter'), $langs->trans('ExportUseMySQLQuickParameterHelp'));
+	print "<!--  Fieldset mysqldump -->\n";
+	print '<fieldset id="mysql_options"><legend>'.$langs->trans("MySqlExportParameters").'</legend>';
+
+	print '<div class="formelementrow">'.$langs->trans("FullPathToMysqldumpCommand");
+	if (empty($conf->global->SYSTEMTOOLS_MYSQLDUMP))
+	{
+		$fullpathofmysqldump = $db->getPathOfDump();
+	} else {
+		$fullpathofmysqldump = $conf->global->SYSTEMTOOLS_MYSQLDUMP;
+	}
+	print '<br>';
+	print '<input type="text" name="mysqldump" style="width: 80%" value="'.$fullpathofmysqldump.'" /></div>';
+
+	print '<br>';
+	print '<fieldset><legend>'.$langs->trans("ExportOptions").'</legend>';
+	print '<div class="formelementrow">';
+	print '<input type="checkbox" name="use_transaction" value="yes" id="checkbox_use_transaction" />';
+	print '<label for="checkbox_use_transaction">'.$langs->trans("UseTransactionnalMode").'</label>';
+	print '</div>';
+
+	if (!empty($conf->global->MYSQL_OLD_OPTION_DISABLE_FK)) {
+		print '<div class="formelementrow">';
+		print '<input type="checkbox" name="disable_fk" value="yes" id="checkbox_disable_fk" checked />';
+		print '<label for="checkbox_disable_fk">'.$langs->trans("CommandsToDisableForeignKeysForImport").' '.img_info($langs->trans('CommandsToDisableForeignKeysForImportWarning')).'</label>';
+		print '</div>';
+	}
+
+	print '<label for="select_sql_compat">'.$langs->trans("ExportCompatibility").'</label>';
+
+	print '<select name="sql_compat" id="select_sql_compat" class="flat">';
+	print '<option value="NONE" selected>NONE</option>';
+	print '<option value="ANSI">ANSI</option>';
+	print '<option value="DB2">DB2</option>';
+	print '<option value="MAXDB">MAXDB</option>';
+	print '<option value="MYSQL323">MYSQL323</option>';
+	print '<option value="MYSQL40">MYSQL40</option>';
+	print '<option value="MSSQL">MSSQL</option>';
+	print '<option value="ORACLE">ORACLE</option>';
+	print '<option value="POSTGRESQL">POSTGRESQL</option>';
+	print '</select>';
+	print '<br>';
+
+	print '<input type="checkbox" name="use_mysql_quick_param" value="yes" id="checkbox_use_quick" />';
+	print '<label for="checkbox_use_quick">';
+	print $form->textwithpicto($langs->trans('ExportUseMySQLQuickParameter'), $langs->trans('ExportUseMySQLQuickParameterHelp'));
 	print '</label>';
 	print '<br/>';
 
-    print '<!-- <input type="checkbox" name="drop_database" value="yes" id="checkbox_drop_database" />';
-    print '<label for="checkbox_drop_database">'.$langs->trans("AddDropDatabase").'</label>';
-    print '-->';
-    print '</fieldset>';
-
-    print '<br>';
-    print '<fieldset>';
-    print '<legend>';
-    print '<input type="checkbox" name="sql_structure" value="structure" id="checkbox_sql_structure" checked />';
-    print '<label for="checkbox_sql_structure">'.$langs->trans('ExportStructure').'</label>';
-    print '</legend>';
-
-    print '<input type="checkbox" name="drop"'.((! GETPOSTISSET("drop") || GETPOST('drop')) ? ' checked' : '').' id="checkbox_dump_drop" />';
-    print '<label for="checkbox_dump_drop">'.$langs->trans("AddDropTable").'</label>';
-    print '<br>';
-    print '</fieldset>';
-
-    print '<br>';
-    print '<fieldset>';
-    print '<legend>';
-    print '<input type="checkbox" name="sql_data" value="data" id="checkbox_sql_data" checked />';
-    print '<label for="checkbox_sql_data">'.$langs->trans("Datas").'</label>';
-    print '</legend>';
-    print '<input type="checkbox" name="showcolumns" value="yes" id="checkbox_dump_showcolumns" checked />';
-    print '<label for="checkbox_dump_showcolumns">'.$langs->trans("NameColumn").'</label>';
-    print '<br>';
-
-    print '<input type="checkbox" name="extended_ins" value="yes" id="checkbox_dump_extended_ins" checked />';
-    print '<label for="checkbox_dump_extended_ins">'.$langs->trans("ExtendedInsert").'</label>';
-    print '<br>';
-
-    print '<input type="checkbox" name="disable-add-locks" value="no" id="checkbox_dump_disable-add-locks" />';
-    print '<label for="checkbox_dump_disable-add-locks">'.$langs->trans("NoLockBeforeInsert").'</label>';
-    print '<br>';
-
-    print '<input type="checkbox" name="delayed" value="yes" id="checkbox_dump_delayed" />';
-    print '<label for="checkbox_dump_delayed">'.$langs->trans("DelayedInsert").'</label>';
-    print '<br>';
-
-    print '<input type="checkbox" name="sql_ignore" value="yes" id="checkbox_dump_ignore" />';
-    print '<label for="checkbox_dump_ignore">'.$langs->trans("IgnoreDuplicateRecords").'</label>';
-    print '<br>';
-
-    print '<input type="checkbox" name="hexforbinary" value="yes" id="checkbox_hexforbinary" checked />';
-    print '<label for="checkbox_hexforbinary">'.$langs->trans("EncodeBinariesInHexa").'</label>';
-    print '<br>';
-
-    print '<input type="checkbox" name="charset_utf8" value="yes" id="checkbox_charset_utf8" checked disabled />';
-    print '<label for="checkbox_charset_utf8">'.$langs->trans("UTF8").'</label>';
-    print '<br>';
-
-    print '</fieldset>';
-    print '</fieldset>';
-    print "<!--  Fieldset mysql_nobin -->\n";
-    print '<fieldset id="mysql_nobin_options">';
-    print '<legend>'.$langs->trans("MySqlExportParameters").'</legend>';
-    print '<fieldset>';
-    print '<legend>'.$langs->trans("ExportOptions").'</legend>';
-    print '<div class="formelementrow">';
-    print '<input type="checkbox" name="nobin_use_transaction" value="yes" id="checkbox_use_transaction" />';
-    print '<label for="checkbox_use_transaction">'.$langs->trans("UseTransactionnalMode").'</label>';
-
-    print '</div>';
-    if (!empty($conf->global->MYSQL_OLD_OPTION_DISABLE_FK)) {
-        print '<div class="formelementrow">';
-        print '<input type="checkbox" name="nobin_disable_fk" value="yes" id="checkbox_disable_fk" checked />';
-        print '<label for="checkbox_disable_fk">'.$langs->trans("CommandsToDisableForeignKeysForImport").' '.img_info($langs->trans('CommandsToDisableForeignKeysForImportWarning')).'</label>';
-        print '</div>';
-    }
-    print '</fieldset>';
-
-    print '<br>';
-    print '<fieldset><legend>'.$langs->trans('ExportStructure').'</legend>';
-    print '<input type="checkbox" name="nobin_drop"'.((! GETPOSTISSET("nobin_drop") || GETPOST('nobin_drop')) ? ' checked' : '').' id="checkbox_dump_drop" />';
-    print '<label for="checkbox_dump_drop">'.$langs->trans("AddDropTable").'</label>';
-    print '<br>';
-    print '</fieldset>';
-
-    print '<br>';
-    print '<fieldset>';
-    print '<legend>'.$langs->trans("Datas").'</legend>';
-
-    print '<input type="checkbox" name="nobin_nolocks" value="no" id="checkbox_dump_disable-add-locks" />';
-    print '<label for="checkbox_dump_disable-add-locks">'.$langs->trans("NoLockBeforeInsert").'</label>';
-    print '<br>';
-
-    print '<input type="checkbox" name="nobin_delayed" value="yes" id="checkbox_dump_delayed" />';
-    print '<label for="checkbox_dump_delayed">'.$langs->trans("DelayedInsert").'</label>';
-    print '<br>';
-
-    print '<input type="checkbox" name="nobin_sql_ignore" value="yes" id="checkbox_dump_ignore" />';
-    print '<label for="checkbox_dump_ignore">'.$langs->trans("IgnoreDuplicateRecords").'</label>';
-    print '<br>';
-
-    print '<input type="checkbox" name="nobin_charset_utf8" value="yes" id="checkbox_charset_utf8" checked disabled />';
-    print '<label for="checkbox_charset_utf8">'.$langs->trans("UTF8").'</label>';
-    print '<br>';
-
-    print '</fieldset>';
-    print '</fieldset>';
+	print '<!-- <input type="checkbox" name="drop_database" value="yes" id="checkbox_drop_database" />';
+	print '<label for="checkbox_drop_database">'.$langs->trans("AddDropDatabase").'</label>';
+	print '-->';
+	print '</fieldset>';
+
+	print '<br>';
+	print '<fieldset>';
+	print '<legend>';
+	print '<input type="checkbox" name="sql_structure" value="structure" id="checkbox_sql_structure" checked />';
+	print '<label for="checkbox_sql_structure">'.$langs->trans('ExportStructure').'</label>';
+	print '</legend>';
+
+	print '<input type="checkbox" name="drop"'.((! GETPOSTISSET("drop") || GETPOST('drop')) ? ' checked' : '').' id="checkbox_dump_drop" />';
+	print '<label for="checkbox_dump_drop">'.$langs->trans("AddDropTable").'</label>';
+	print '<br>';
+	print '</fieldset>';
+
+	print '<br>';
+	print '<fieldset>';
+	print '<legend>';
+	print '<input type="checkbox" name="sql_data" value="data" id="checkbox_sql_data" checked />';
+	print '<label for="checkbox_sql_data">'.$langs->trans("Datas").'</label>';
+	print '</legend>';
+	print '<input type="checkbox" name="showcolumns" value="yes" id="checkbox_dump_showcolumns" checked />';
+	print '<label for="checkbox_dump_showcolumns">'.$langs->trans("NameColumn").'</label>';
+	print '<br>';
+
+	print '<input type="checkbox" name="extended_ins" value="yes" id="checkbox_dump_extended_ins" checked />';
+	print '<label for="checkbox_dump_extended_ins">'.$langs->trans("ExtendedInsert").'</label>';
+	print '<br>';
+
+	print '<input type="checkbox" name="disable-add-locks" value="no" id="checkbox_dump_disable-add-locks" />';
+	print '<label for="checkbox_dump_disable-add-locks">'.$langs->trans("NoLockBeforeInsert").'</label>';
+	print '<br>';
+
+	print '<input type="checkbox" name="delayed" value="yes" id="checkbox_dump_delayed" />';
+	print '<label for="checkbox_dump_delayed">'.$langs->trans("DelayedInsert").'</label>';
+	print '<br>';
+
+	print '<input type="checkbox" name="sql_ignore" value="yes" id="checkbox_dump_ignore" />';
+	print '<label for="checkbox_dump_ignore">'.$langs->trans("IgnoreDuplicateRecords").'</label>';
+	print '<br>';
+
+	print '<input type="checkbox" name="hexforbinary" value="yes" id="checkbox_hexforbinary" checked />';
+	print '<label for="checkbox_hexforbinary">'.$langs->trans("EncodeBinariesInHexa").'</label>';
+	print '<br>';
+
+	print '<input type="checkbox" name="charset_utf8" value="yes" id="checkbox_charset_utf8" checked disabled />';
+	print '<label for="checkbox_charset_utf8">'.$langs->trans("UTF8").'</label>';
+	print '<br>';
+
+	print '</fieldset>';
+	print '</fieldset>';
+	print "<!--  Fieldset mysql_nobin -->\n";
+	print '<fieldset id="mysql_nobin_options">';
+	print '<legend>'.$langs->trans("MySqlExportParameters").'</legend>';
+	print '<fieldset>';
+	print '<legend>'.$langs->trans("ExportOptions").'</legend>';
+	print '<div class="formelementrow">';
+	print '<input type="checkbox" name="nobin_use_transaction" value="yes" id="checkbox_use_transaction" />';
+	print '<label for="checkbox_use_transaction">'.$langs->trans("UseTransactionnalMode").'</label>';
+
+	print '</div>';
+	if (!empty($conf->global->MYSQL_OLD_OPTION_DISABLE_FK)) {
+		print '<div class="formelementrow">';
+		print '<input type="checkbox" name="nobin_disable_fk" value="yes" id="checkbox_disable_fk" checked />';
+		print '<label for="checkbox_disable_fk">'.$langs->trans("CommandsToDisableForeignKeysForImport").' '.img_info($langs->trans('CommandsToDisableForeignKeysForImportWarning')).'</label>';
+		print '</div>';
+	}
+	print '</fieldset>';
+
+	print '<br>';
+	print '<fieldset><legend>'.$langs->trans('ExportStructure').'</legend>';
+	print '<input type="checkbox" name="nobin_drop"'.((! GETPOSTISSET("nobin_drop") || GETPOST('nobin_drop')) ? ' checked' : '').' id="checkbox_dump_drop" />';
+	print '<label for="checkbox_dump_drop">'.$langs->trans("AddDropTable").'</label>';
+	print '<br>';
+	print '</fieldset>';
+
+	print '<br>';
+	print '<fieldset>';
+	print '<legend>'.$langs->trans("Datas").'</legend>';
+
+	print '<input type="checkbox" name="nobin_nolocks" value="no" id="checkbox_dump_disable-add-locks" />';
+	print '<label for="checkbox_dump_disable-add-locks">'.$langs->trans("NoLockBeforeInsert").'</label>';
+	print '<br>';
+
+	print '<input type="checkbox" name="nobin_delayed" value="yes" id="checkbox_dump_delayed" />';
+	print '<label for="checkbox_dump_delayed">'.$langs->trans("DelayedInsert").'</label>';
+	print '<br>';
+
+	print '<input type="checkbox" name="nobin_sql_ignore" value="yes" id="checkbox_dump_ignore" />';
+	print '<label for="checkbox_dump_ignore">'.$langs->trans("IgnoreDuplicateRecords").'</label>';
+	print '<br>';
+
+	print '<input type="checkbox" name="nobin_charset_utf8" value="yes" id="checkbox_charset_utf8" checked disabled />';
+	print '<label for="checkbox_charset_utf8">'.$langs->trans("UTF8").'</label>';
+	print '<br>';
+
+	print '</fieldset>';
+	print '</fieldset>';
 }
 
 if (in_array($type, array('pgsql'))) {
-    print "<!--  Fieldset pg_dump -->\n";
-    print '<fieldset id="postgresql_options"><legend>'.$langs->trans("PostgreSqlExportParameters").'</legend>';
-
-    print '<div class="formelementrow">'.$langs->trans("FullPathToPostgreSQLdumpCommand");
-    if (empty($conf->global->SYSTEMTOOLS_POSTGRESQLDUMP)) {
-        $fullpathofpgdump = $db->getPathOfDump();
-    } else {
-        $fullpathofpgdump = $conf->global->SYSTEMTOOLS_POSTGRESQLDUMP;
-    }
-    print '<br>';
-    print '<input type="text" name="postgresqldump" style="width: 80%" value="'.$fullpathofpgdump.'" /></div>';
-
-    print '<br>';
-    print '<fieldset>';
-    print '<legend>'.$langs->trans("ExportOptions").'</legend>';
-    print '<label for="select_sql_compat">'.$langs->trans("ExportCompatibility").'</label>';
-    print '<select name="sql_compat" id="select_sql_compat" class="flat">';
-    print '<option value="POSTGRESQL" selected>POSTGRESQL</option>';
-    print '<option value="ANSI">ANSI</option>';
-    print '</select>';
-    print '<br>';
-    print '<!-- <input type="checkbox" name="drop_database" value="yes" id="checkbox_drop_database" />';
-    print '<label for="checkbox_drop_database">'.$langs->trans("AddDropDatabase").'</label>';
-    print '-->';
-    print '</fieldset>';
-    print '<br>';
-    print '<fieldset>';
-    print '<legend>';
-    print '<input type="checkbox" name="sql_structure" value="structure" id="checkbox_sql_structure" checked />';
-    print '<label for="checkbox_sql_structure">'.$langs->trans('ExportStructure').'</label>';
-    print '</legend>';
-    print '</fieldset>';
-    print '<br>';
-    print '<fieldset>';
-    print '<legend>';
-    print '<input type="checkbox" name="sql_data" value="data" id="checkbox_sql_data" checked />';
-    print '<label for="checkbox_sql_data">'.$langs->trans("Datas").'</label>';
-    print '</legend>';
-    print '<input type="checkbox" name="showcolumns" value="yes" id="checkbox_dump_showcolumns" checked />';
-    print '<label for="checkbox_dump_showcolumns">'.$langs->trans("NameColumn").'</label>';
-    print '<br>';
-    print '</fieldset>';
-    print '</fieldset>';
+	print "<!--  Fieldset pg_dump -->\n";
+	print '<fieldset id="postgresql_options"><legend>'.$langs->trans("PostgreSqlExportParameters").'</legend>';
+
+	print '<div class="formelementrow">'.$langs->trans("FullPathToPostgreSQLdumpCommand");
+	if (empty($conf->global->SYSTEMTOOLS_POSTGRESQLDUMP)) {
+		$fullpathofpgdump = $db->getPathOfDump();
+	} else {
+		$fullpathofpgdump = $conf->global->SYSTEMTOOLS_POSTGRESQLDUMP;
+	}
+	print '<br>';
+	print '<input type="text" name="postgresqldump" style="width: 80%" value="'.$fullpathofpgdump.'" /></div>';
+
+	print '<br>';
+	print '<fieldset>';
+	print '<legend>'.$langs->trans("ExportOptions").'</legend>';
+	print '<label for="select_sql_compat">'.$langs->trans("ExportCompatibility").'</label>';
+	print '<select name="sql_compat" id="select_sql_compat" class="flat">';
+	print '<option value="POSTGRESQL" selected>POSTGRESQL</option>';
+	print '<option value="ANSI">ANSI</option>';
+	print '</select>';
+	print '<br>';
+	print '<!-- <input type="checkbox" name="drop_database" value="yes" id="checkbox_drop_database" />';
+	print '<label for="checkbox_drop_database">'.$langs->trans("AddDropDatabase").'</label>';
+	print '-->';
+	print '</fieldset>';
+	print '<br>';
+	print '<fieldset>';
+	print '<legend>';
+	print '<input type="checkbox" name="sql_structure" value="structure" id="checkbox_sql_structure" checked />';
+	print '<label for="checkbox_sql_structure">'.$langs->trans('ExportStructure').'</label>';
+	print '</legend>';
+	print '</fieldset>';
+	print '<br>';
+	print '<fieldset>';
+	print '<legend>';
+	print '<input type="checkbox" name="sql_data" value="data" id="checkbox_sql_data" checked />';
+	print '<label for="checkbox_sql_data">'.$langs->trans("Datas").'</label>';
+	print '</legend>';
+	print '<input type="checkbox" name="showcolumns" value="yes" id="checkbox_dump_showcolumns" checked />';
+	print '<label for="checkbox_dump_showcolumns">'.$langs->trans("NameColumn").'</label>';
+	print '<br>';
+	print '</fieldset>';
+	print '</fieldset>';
 }
 print '</div>';
 
@@ -418,16 +418,16 @@ if (in_array($type, array('mysql', 'mysqli'))) {
 	//     'id' => 'radio_compression_zip',
 	//     'label' => $langs->trans("FormatZip")
 	// );
-    $compression['bz'] = array(
+	$compression['bz'] = array(
 		'function' => 'bzopen',
 		'id' => 'radio_compression_bzip',
 		'label' => $langs->trans("Bzip2")
 	);
-    $compression['none'] = array(
-    	'function' => '',
-    	'id' => 'radio_compression_none',
-    	'label' => $langs->trans("None")
-    );
+	$compression['none'] = array(
+		'function' => '',
+		'id' => 'radio_compression_none',
+		'label' => $langs->trans("None")
+	);
 } else {
 	$compression['none'] = array(
 		'function' => '',
@@ -480,14 +480,14 @@ print '<br>';
 
 if (!empty($_SESSION["commandbackuplastdone"]))
 {
-    print '<br><b>'.$langs->trans("RunCommandSummary").':</b><br>'."\n";
-    print '<textarea rows="'.ROWS_2.'" class="centpercent">'.$_SESSION["commandbackuplastdone"].'</textarea><br>'."\n";
-    print '<br>';
+	print '<br><b>'.$langs->trans("RunCommandSummary").':</b><br>'."\n";
+	print '<textarea rows="'.ROWS_2.'" class="centpercent">'.$_SESSION["commandbackuplastdone"].'</textarea><br>'."\n";
+	print '<br>';
 
-    //print $paramclear;
+	//print $paramclear;
 
-    // Now show result
-    print '<b>'.$langs->trans("BackupResult").':</b> ';
+	// Now show result
+	print '<b>'.$langs->trans("BackupResult").':</b> ';
 	print $_SESSION["commandbackupresult"];
 
 	$_SESSION["commandbackuplastdone"] = '';
@@ -568,20 +568,20 @@ $filecompression['zip'] = array('function' => 'dol_compress_dir', 'id' => 'radio
 $i = 0;
 foreach ($filecompression as $key => $val)
 {
-    if (!$val['function'] || function_exists($val['function']))	// Enabled export format
-    {
-    	$checked = '';
-    	if ($key == 'gz') $checked = ' checked';
-        print '<input type="radio" name="compression" value="'.$key.'" id="'.$val['id'].'"'.$checked.'>';
-        print ' <label for="'.$val['id'].'">'.$val['label'].'</label>';
-    } else // Disabled export format
-    {
-        print '<input type="radio" name="compression" value="'.$key.'" id="'.$val['id'].'" disabled>';
-        print ' <label for="'.$val['id'].'">'.$val['label'].'</label>';
-        print ' <span class="opacitymedium">('.$langs->trans("NotAvailable").')</span>';
-    }
-    print ' &nbsp; &nbsp; ';
-    $i++;
+	if (!$val['function'] || function_exists($val['function']))	// Enabled export format
+	{
+		$checked = '';
+		if ($key == 'gz') $checked = ' checked';
+		print '<input type="radio" name="compression" value="'.$key.'" id="'.$val['id'].'"'.$checked.'>';
+		print ' <label for="'.$val['id'].'">'.$val['label'].'</label>';
+	} else // Disabled export format
+	{
+		print '<input type="radio" name="compression" value="'.$key.'" id="'.$val['id'].'" disabled>';
+		print ' <label for="'.$val['id'].'">'.$val['label'].'</label>';
+		print ' <span class="opacitymedium">('.$langs->trans("NotAvailable").')</span>';
+	}
+	print ' &nbsp; &nbsp; ';
+	$i++;
 }
 
 print '</div>';

+ 257 - 257
htdocs/admin/translation.php

@@ -73,16 +73,16 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 // Purge search criteria
 if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
 {
-    $transkey = '';
-    $transvalue = '';
-    $toselect = '';
-    $search_array_options = array();
+	$transkey = '';
+	$transvalue = '';
+	$toselect = '';
+	$search_array_options = array();
 }
 
 if ($action == 'setMAIN_ENABLE_OVERWRITE_TRANSLATION')
 {
-    if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 1, 'chaine', 0, '', $conf->entity);
-    else dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 0, 'chaine', 0, '', $conf->entity);
+	if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 1, 'chaine', 0, '', $conf->entity);
+	else dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 0, 'chaine', 0, '', $conf->entity);
 }
 
 if ($action == 'update')
@@ -139,25 +139,25 @@ if ($action == 'add')
 	}
 	if (!$error)
 	{
-	    $db->begin();
+		$db->begin();
 
-	    $sql = "INSERT INTO ".MAIN_DB_PREFIX."overwrite_trans(lang, transkey, transvalue, entity) VALUES ('".$db->escape($langcode)."','".$db->escape($transkey)."','".$db->escape($transvalue)."', ".$db->escape($conf->entity).")";
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."overwrite_trans(lang, transkey, transvalue, entity) VALUES ('".$db->escape($langcode)."','".$db->escape($transkey)."','".$db->escape($transvalue)."', ".$db->escape($conf->entity).")";
 		$result = $db->query($sql);
 		if ($result > 0)
 		{
-		    $db->commit();
-		    setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
+			$db->commit();
+			setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
 			$action = "";
 			$transkey = "";
 			$transvalue = "";
 		} else {
-		    $db->rollback();
-		    if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
-		    {
-		        setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings');
-		    } else {
-		        setEventMessages($db->lasterror(), null, 'errors');
-            }
+			$db->rollback();
+			if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
+			{
+				setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings');
+			} else {
+				setEventMessages($db->lasterror(), null, 'errors');
+			}
 			$action = '';
 		}
 	}
@@ -196,15 +196,15 @@ $enabledisablehtml = '';
 $enabledisablehtml .= $langs->trans("EnableOverwriteTranslation").' ';
 if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION))
 {
-    // Button off, click to enable
-    $enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_OVERWRITE_TRANSLATION&token='.newToken().'&value=1'.$param.'">';
-    $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off');
-    $enabledisablehtml .= '</a>';
+	// Button off, click to enable
+	$enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_OVERWRITE_TRANSLATION&token='.newToken().'&value=1'.$param.'">';
+	$enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off');
+	$enabledisablehtml .= '</a>';
 } else {
-    // Button on, click to disable
-    $enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_OVERWRITE_TRANSLATION&token='.newToken().'&value=0'.$param.'">';
-    $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on');
-    $enabledisablehtml .= '</a>';
+	// Button on, click to disable
+	$enabledisablehtml .= '<a class="reposition valignmiddle" href="'.$_SERVER["PHP_SELF"].'?action=setMAIN_ENABLE_OVERWRITE_TRANSLATION&token='.newToken().'&value=0'.$param.'">';
+	$enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on');
+	$enabledisablehtml .= '</a>';
 }
 
 print load_fiche_titre($langs->trans("Translation"), $enabledisablehtml, 'title_setup');
@@ -247,43 +247,43 @@ if ($mode == 'overwrite')
 	if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disablededit = ' disabled';
 
 	print '<div class="justify"><span class="opacitymedium">';
-    print img_info().' '.$langs->trans("SomeTranslationAreUncomplete");
-    $urlwikitranslatordoc = 'https://wiki.dolibarr.org/index.php/Translator_documentation';
-    print ' ('.$langs->trans("SeeAlso", '<a href="'.$urlwikitranslatordoc.'" target="_blank">'.$langs->trans("Here").'</a>').')<br>';
-    print $langs->trans("TranslationOverwriteDesc", $langs->transnoentitiesnoconv("Language"), $langs->transnoentitiesnoconv("Key"), $langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n";
-    print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."<br>\n";
-    print '</span></div>';
+	print img_info().' '.$langs->trans("SomeTranslationAreUncomplete");
+	$urlwikitranslatordoc = 'https://wiki.dolibarr.org/index.php/Translator_documentation';
+	print ' ('.$langs->trans("SeeAlso", '<a href="'.$urlwikitranslatordoc.'" target="_blank">'.$langs->trans("Here").'</a>').')<br>';
+	print $langs->trans("TranslationOverwriteDesc", $langs->transnoentitiesnoconv("Language"), $langs->transnoentitiesnoconv("Key"), $langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n";
+	print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."<br>\n";
+	print '</span></div>';
 
-    print '<br>';
+	print '<br>';
 
 
 	print '<input type="hidden" name="action" value="'.($action == 'edit' ? 'update' : 'add').'">';
-    print '<input type="hidden" id="mode" name="mode" value="'.$mode.'">';
+	print '<input type="hidden" id="mode" name="mode" value="'.$mode.'">';
 
 	print '<div class="div-table-responsive-no-min">';
-    print '<table class="noborder centpercent">';
-    print '<tr class="liste_titre">';
-    print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder);
-    print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder);
-    print_liste_field_titre("NewTranslationStringToShow", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder);
-    //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder);
-    print '<td align="center"></td>';
-    print "</tr>\n";
-
-
-    // Line to add new record
-    print "\n";
-
-    print '<tr class="oddeven"><td>';
-    print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit ? 1 : 0, 'maxwidthonsmartphone', 1);
-    print '</td>'."\n";
-    print '<td>';
-    print '<input type="text" class="flat maxwidthonsmartphone"'.$disablededit.' name="transkey" id="transkey" value="'.(!empty($transkey) ? $transkey : "").'">';
-    print '</td><td>';
-    print '<input type="text" class="quatrevingtpercent"'.$disablededit.' name="transvalue" id="transvalue" value="'.(!empty($transvalue) ? $transvalue : "").'">';
-    print '</td>';
-    // Limit to superadmin
-    /*if (! empty($conf->multicompany->enabled) && !$user->entity)
+	print '<table class="noborder centpercent">';
+	print '<tr class="liste_titre">';
+	print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder);
+	print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder);
+	print_liste_field_titre("NewTranslationStringToShow", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder);
+	//if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder);
+	print '<td align="center"></td>';
+	print "</tr>\n";
+
+
+	// Line to add new record
+	print "\n";
+
+	print '<tr class="oddeven"><td>';
+	print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit ? 1 : 0, 'maxwidthonsmartphone', 1);
+	print '</td>'."\n";
+	print '<td>';
+	print '<input type="text" class="flat maxwidthonsmartphone"'.$disablededit.' name="transkey" id="transkey" value="'.(!empty($transkey) ? $transkey : "").'">';
+	print '</td><td>';
+	print '<input type="text" class="quatrevingtpercent"'.$disablededit.' name="transvalue" id="transvalue" value="'.(!empty($transvalue) ? $transvalue : "").'">';
+	print '</td>';
+	// Limit to superadmin
+	/*if (! empty($conf->multicompany->enabled) && !$user->entity)
     {
     	print '<td>';
     	print '<input type="text" class="flat" size="1" name="entity" value="'.$conf->entity.'">';
@@ -292,118 +292,118 @@ if ($mode == 'overwrite')
     }
     else
     {*/
-    	print '<td class="center">';
-    	print '<input type="hidden" name="entity" value="'.$conf->entity.'">';
-    //}
-    print '<input type="submit" class="button"'.$disabled.' value="'.$langs->trans("Add").'" name="add" title="'.dol_escape_htmltag($langs->trans("YouMustEnabledTranslationOverwriteBefore")).'">';
-    print "</td>\n";
-    print '</tr>';
-
-
-    // Show constants
-    $sql = "SELECT rowid, entity, lang, transkey, transvalue";
-    $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans";
-    $sql .= " WHERE 1 = 1";
-    $sql .= " AND entity IN (".getEntity('overwrite_trans').")";
-    $sql .= $db->order($sortfield, $sortorder);
-
-    dol_syslog("translation::select from table", LOG_DEBUG);
-    $result = $db->query($sql);
-    if ($result)
-    {
-    	$num = $db->num_rows($result);
-    	$i = 0;
+		print '<td class="center">';
+		print '<input type="hidden" name="entity" value="'.$conf->entity.'">';
+	//}
+	print '<input type="submit" class="button"'.$disabled.' value="'.$langs->trans("Add").'" name="add" title="'.dol_escape_htmltag($langs->trans("YouMustEnabledTranslationOverwriteBefore")).'">';
+	print "</td>\n";
+	print '</tr>';
+
+
+	// Show constants
+	$sql = "SELECT rowid, entity, lang, transkey, transvalue";
+	$sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans";
+	$sql .= " WHERE 1 = 1";
+	$sql .= " AND entity IN (".getEntity('overwrite_trans').")";
+	$sql .= $db->order($sortfield, $sortorder);
+
+	dol_syslog("translation::select from table", LOG_DEBUG);
+	$result = $db->query($sql);
+	if ($result)
+	{
+		$num = $db->num_rows($result);
+		$i = 0;
 
-    	while ($i < $num)
-    	{
-    		$obj = $db->fetch_object($result);
+		while ($i < $num)
+		{
+			$obj = $db->fetch_object($result);
 
-    		print "\n";
+			print "\n";
 
-    		print '<tr class="oddeven">';
+			print '<tr class="oddeven">';
 
-    		print '<td>'.$obj->lang.'</td>'."\n";
-    		print '<td>'.$obj->transkey.'</td>'."\n";
+			print '<td>'.$obj->lang.'</td>'."\n";
+			print '<td>'.$obj->transkey.'</td>'."\n";
 
-    		// Value
-    		print '<td>';
-    		/*print '<input type="hidden" name="const['.$i.'][rowid]" value="'.$obj->rowid.'">';
+			// Value
+			print '<td>';
+			/*print '<input type="hidden" name="const['.$i.'][rowid]" value="'.$obj->rowid.'">';
     		print '<input type="hidden" name="const['.$i.'][lang]" value="'.$obj->lang.'">';
     		print '<input type="hidden" name="const['.$i.'][name]" value="'.$obj->transkey.'">';
     		print '<input type="text" id="value_'.$i.'" class="flat inputforupdate" size="30" name="const['.$i.'][value]" value="'.dol_escape_htmltag($obj->transvalue).'">';
     		*/
-    		if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int'))
-    		{
-    			print '<input type="text" class="quatrevingtpercent" name="transvalue" value="'.dol_escape_htmltag($obj->transvalue).'">';
-    		} else {
-    			print dol_escape_htmltag($obj->transvalue);
-    		}
-    		print '</td>';
-
-    		print '<td class="center">';
-    		if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int'))
-    		{
-    			print '<input type="hidden" class="button" name="rowid" value="'.$obj->rowid.'">';
-    			print '<input type="submit" class="button buttongen" name="save" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
-    			print ' &nbsp; ';
-    			print '<input type="submit" class="button buttongen" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
-    		} else {
-    			print '<a class="reposition editfielda paddingrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&action=edit'.((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_edit().'</a>';
+			if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int'))
+			{
+				print '<input type="text" class="quatrevingtpercent" name="transvalue" value="'.dol_escape_htmltag($obj->transvalue).'">';
+			} else {
+				print dol_escape_htmltag($obj->transvalue);
+			}
+			print '</td>';
+
+			print '<td class="center">';
+			if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int'))
+			{
+				print '<input type="hidden" class="button" name="rowid" value="'.$obj->rowid.'">';
+				print '<input type="submit" class="button buttongen" name="save" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
 				print ' &nbsp; ';
-    			print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&action=delete&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_delete().'</a>';
-    		}
-    		print '</td>';
-
-    		print "</tr>\n";
-    		print "\n";
-    		$i++;
-    	}
-    }
+				print '<input type="submit" class="button buttongen" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
+			} else {
+				print '<a class="reposition editfielda paddingrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&action=edit'.((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_edit().'</a>';
+				print ' &nbsp; ';
+				print '<a class="reposition" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&action=delete&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_delete().'</a>';
+			}
+			print '</td>';
 
-    print '</table>';
-    print '</div>';
+			print "</tr>\n";
+			print "\n";
+			$i++;
+		}
+	}
+
+	print '</table>';
+	print '</div>';
 }
 
 if ($mode == 'searchkey')
 {
-    $langcode = GETPOST('langcode') ?GETPOST('langcode') : $langs->defaultlang;
+	$langcode = GETPOST('langcode') ?GETPOST('langcode') : $langs->defaultlang;
 
-    $newlang = new Translate('', $conf);
-    $newlang->setDefaultLang($langcode);
+	$newlang = new Translate('', $conf);
+	$newlang->setDefaultLang($langcode);
 
-    $newlangfileonly = new Translate('', $conf);
-    $newlangfileonly->setDefaultLang($langcode);
+	$newlangfileonly = new Translate('', $conf);
+	$newlangfileonly->setDefaultLang($langcode);
 
-    $recordtoshow = array();
+	$recordtoshow = array();
 
-    // Search modules dirs
-    $modulesdir = dolGetModulesDirs();
+	// Search modules dirs
+	$modulesdir = dolGetModulesDirs();
 
-    $nbtotaloffiles = 0;
-    $nbempty = 0;
-    /*var_dump($langcode);
+	$nbtotaloffiles = 0;
+	$nbempty = 0;
+	/*var_dump($langcode);
      var_dump($transkey);
      var_dump($transvalue);*/
-    if (empty($langcode) || $langcode == '-1') $nbempty++;
-    if (empty($transkey)) $nbempty++;
-    if (empty($transvalue)) $nbempty++;
-    if ($action == 'search' && ($nbempty > 999))    // 999 to disable this
-    {
-        setEventMessages($langs->trans("WarningAtLeastKeyOrTranslationRequired"), null, 'warnings');
-    } else {
-        // Search into dir of modules (the $modulesdir is already a list that loop on $conf->file->dol_document_root)
-        $i = 0;
-        foreach ($modulesdir as $keydir => $tmpsearchdir)
-        {
-        	$searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/'
+	if (empty($langcode) || $langcode == '-1') $nbempty++;
+	if (empty($transkey)) $nbempty++;
+	if (empty($transvalue)) $nbempty++;
+	if ($action == 'search' && ($nbempty > 999))    // 999 to disable this
+	{
+		setEventMessages($langs->trans("WarningAtLeastKeyOrTranslationRequired"), null, 'warnings');
+	} else {
+		// Search into dir of modules (the $modulesdir is already a list that loop on $conf->file->dol_document_root)
+		$i = 0;
+		foreach ($modulesdir as $keydir => $tmpsearchdir)
+		{
+			$searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/'
 
-        	// Directory of translation files
-        	$dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels
-        	$dir_lang_osencoded = dol_osencode($dir_lang);
+			// Directory of translation files
+			$dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels
+			$dir_lang_osencoded = dol_osencode($dir_lang);
 
-        	$filearray = dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder) == 'asc' ?SORT_ASC:SORT_DESC), 1);
-        	foreach ($filearray as $file)
-        	{
+			$filearray = dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder) == 'asc' ?SORT_ASC:SORT_DESC), 1);
+			foreach ($filearray as $file)
+			{
 				$tmpfile = preg_replace('/.lang/i', '', basename($file['name']));
 				$moduledirname = (basename(dirname(dirname($dir_lang))));
 
@@ -416,135 +416,135 @@ if ($mode == 'searchkey')
 				if ($result < 0) print 'Failed to load language file '.$tmpfile.'<br>'."\n";
 				else $nbtotaloffiles++;
 				//print 'After loading lang '.$langkey.', newlang has '.count($newlang->tab_translate).' records<br>'."\n";
-        	}
-        	$i++;
-        }
+			}
+			$i++;
+		}
 
-        // Now search into translation array
-        foreach ($newlang->tab_translate as $key => $val)
-        {
-            if ($transkey && !preg_match('/'.preg_quote($transkey, '/').'/i', $key)) continue;
-            if ($transvalue && !preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) continue;
-            $recordtoshow[$key] = $val;
-        }
-    }
+		// Now search into translation array
+		foreach ($newlang->tab_translate as $key => $val)
+		{
+			if ($transkey && !preg_match('/'.preg_quote($transkey, '/').'/i', $key)) continue;
+			if ($transvalue && !preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) continue;
+			$recordtoshow[$key] = $val;
+		}
+	}
 
-    //print '<br>';
-    $nbtotalofrecordswithoutfilters = count($newlang->tab_translate);
-    $nbtotalofrecords = count($recordtoshow);
-    $num = $limit + 1;
-    if (($offset + $num) > $nbtotalofrecords) $num = $limit;
+	//print '<br>';
+	$nbtotalofrecordswithoutfilters = count($newlang->tab_translate);
+	$nbtotalofrecords = count($recordtoshow);
+	$num = $limit + 1;
+	if (($offset + $num) > $nbtotalofrecords) $num = $limit;
 
-    //print 'param='.$param.' $_SERVER["PHP_SELF"]='.$_SERVER["PHP_SELF"].' num='.$num.' page='.$page.' nbtotalofrecords='.$nbtotalofrecords." sortfield=".$sortfield." sortorder=".$sortorder;
-    $title = $langs->trans("TranslationKeySearch");
-    if ($nbtotalofrecords > 0) $title .= ' <span class="opacitymedium colorblack paddingleft">('.$nbtotalofrecords.' / '.$nbtotalofrecordswithoutfilters.' - '.$nbtotaloffiles.' '.$langs->trans("Files").')</span>';
-    print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1);
+	//print 'param='.$param.' $_SERVER["PHP_SELF"]='.$_SERVER["PHP_SELF"].' num='.$num.' page='.$page.' nbtotalofrecords='.$nbtotalofrecords." sortfield=".$sortfield." sortorder=".$sortorder;
+	$title = $langs->trans("TranslationKeySearch");
+	if ($nbtotalofrecords > 0) $title .= ' <span class="opacitymedium colorblack paddingleft">('.$nbtotalofrecords.' / '.$nbtotalofrecordswithoutfilters.' - '.$nbtotaloffiles.' '.$langs->trans("Files").')</span>';
+	print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1);
 
-    print '<input type="hidden" id="action" name="action" value="search">';
-    print '<input type="hidden" id="mode" name="mode" value="'.$mode.'">';
+	print '<input type="hidden" id="action" name="action" value="search">';
+	print '<input type="hidden" id="mode" name="mode" value="'.$mode.'">';
 
 	print '<div class="div-table-responsive-no-min">';
-    print '<table class="noborder centpercent">';
-    print '<tr class="liste_titre">';
-    print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder);
-    print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder);
-    print_liste_field_titre("CurrentTranslationString", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder);
-    //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder);
-    print '<td align="center"></td>';
-    print "</tr>\n";
-
-    // Line to search new record
-    print "\n";
-
-    print '<tr class="oddeven"><td>';
-    //print $formadmin->select_language($langcode,'langcode',0,null,$langs->trans("All"),0,0,'',1);
-    print $formadmin->select_language($langcode, 'langcode', 0, null, 0, 0, 0, 'maxwidthonsmartphone', 1);
-    print '</td>'."\n";
-    print '<td>';
-    print '<input type="text" class="flat maxwidthonsmartphone" name="transkey" value="'.$transkey.'">';
-    print '</td><td>';
-    print '<input type="text" class="quatrevingtpercent" name="transvalue" value="'.$transvalue.'">';
-    // Limit to superadmin
-    /*if (! empty($conf->multicompany->enabled) && !$user->entity)
+	print '<table class="noborder centpercent">';
+	print '<tr class="liste_titre">';
+	print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder);
+	print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder);
+	print_liste_field_titre("CurrentTranslationString", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder);
+	//if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder);
+	print '<td align="center"></td>';
+	print "</tr>\n";
+
+	// Line to search new record
+	print "\n";
+
+	print '<tr class="oddeven"><td>';
+	//print $formadmin->select_language($langcode,'langcode',0,null,$langs->trans("All"),0,0,'',1);
+	print $formadmin->select_language($langcode, 'langcode', 0, null, 0, 0, 0, 'maxwidthonsmartphone', 1);
+	print '</td>'."\n";
+	print '<td>';
+	print '<input type="text" class="flat maxwidthonsmartphone" name="transkey" value="'.$transkey.'">';
+	print '</td><td>';
+	print '<input type="text" class="quatrevingtpercent" name="transvalue" value="'.$transvalue.'">';
+	// Limit to superadmin
+	/*if (! empty($conf->multicompany->enabled) && !$user->entity)
     {
         print '</td><td>';
         print '<input type="text" class="flat" size="1" name="entitysearch" value="'.$conf->entity.'">';
     }
     else
     {*/
-        print '<input type="hidden" name="entitysearch" value="'.$conf->entity.'">';
-    //}
-    print '</td>';
-    // Action column
-    print '<td class="nowrap right">';
-    $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
-    print $searchpicto;
-    print '</td>';
-    print '</tr>';
-
-    if ($sortfield == 'transkey' && strtolower($sortorder) == 'asc') ksort($recordtoshow);
-    if ($sortfield == 'transkey' && strtolower($sortorder) == 'desc') krsort($recordtoshow);
-    if ($sortfield == 'transvalue' && strtolower($sortorder) == 'asc') asort($recordtoshow);
-    if ($sortfield == 'transvalue' && strtolower($sortorder) == 'desc') arsort($recordtoshow);
-
-    // Show result
-    $i = 0;
-    foreach ($recordtoshow as $key => $val)
-    {
-        $i++;
-        if ($i <= $offset) continue;
-        if ($i > ($offset + $limit)) break;
-        print '<tr class="oddeven"><td>'.$langcode.'</td><td>'.$key.'</td><td>';
-        print dol_escape_htmltag($val);
-        print '</td><td class="right nowraponall">';
-        if (!empty($newlangfileonly->tab_translate[$key]))
-        {
-            if ($val != $newlangfileonly->tab_translate[$key])
-            {
-                // retrieve rowid
-                $sql = "SELECT rowid";
-                $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans";
-                $sql .= " WHERE transkey = '".$key."'";
-                $sql .= " AND entity IN (".getEntity('overwrite_trans').")";
-                dol_syslog("translation::select from table", LOG_DEBUG);
-                $result = $db->query($sql);
-                if ($result)
-                {
-                    $obj = $db->fetch_object($result);
-                }
-                print '<a class="editfielda reposition paddingrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$conf->entity.'&action=edit">'.img_edit().'</a>';
-                print ' ';
-                print '<a href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$conf->entity.'&action=delete&token='.newToken().'">'.img_delete().'</a>';
-                print '&nbsp;&nbsp;';
-                $htmltext = $langs->trans("OriginalValueWas", '<i>'.$newlangfileonly->tab_translate[$key].'</i>');
-                print $form->textwithpicto('', $htmltext, 1, 'info');
-            } elseif (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION))
-            {
-            	//print $key.'-'.$val;
-                print '<a class="reposition paddingrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=overwrite&amp;langcode='.$langcode.'&amp;transkey='.$key.'">'.img_edit_add($langs->trans("Overwrite")).'</a>';
-            }
-
-            if (!empty($conf->global->MAIN_FEATURES_LEVEL))
-            {
-            	$transifexlangfile = '$'; // $ means 'All'
-            	//$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key;
-            	$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?q=key%3A'.$key;
-
-            	print ' &nbsp; <a href="'.$transifexurl.'" target="transifex">'.img_picto($langs->trans('FixOnTransifex'), 'globe').'</a>';
-            }
-        } else {
-            $htmltext = $langs->trans("TransKeyWithoutOriginalValue", $key);
-            print $form->textwithpicto('', $htmltext, 1, 'warning');
-        }
-        /*if (! empty($conf->multicompany->enabled) && !$user->entity)
+		print '<input type="hidden" name="entitysearch" value="'.$conf->entity.'">';
+	//}
+	print '</td>';
+	// Action column
+	print '<td class="nowrap right">';
+	$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
+	print $searchpicto;
+	print '</td>';
+	print '</tr>';
+
+	if ($sortfield == 'transkey' && strtolower($sortorder) == 'asc') ksort($recordtoshow);
+	if ($sortfield == 'transkey' && strtolower($sortorder) == 'desc') krsort($recordtoshow);
+	if ($sortfield == 'transvalue' && strtolower($sortorder) == 'asc') asort($recordtoshow);
+	if ($sortfield == 'transvalue' && strtolower($sortorder) == 'desc') arsort($recordtoshow);
+
+	// Show result
+	$i = 0;
+	foreach ($recordtoshow as $key => $val)
+	{
+		$i++;
+		if ($i <= $offset) continue;
+		if ($i > ($offset + $limit)) break;
+		print '<tr class="oddeven"><td>'.$langcode.'</td><td>'.$key.'</td><td>';
+		print dol_escape_htmltag($val);
+		print '</td><td class="right nowraponall">';
+		if (!empty($newlangfileonly->tab_translate[$key]))
+		{
+			if ($val != $newlangfileonly->tab_translate[$key])
+			{
+				// retrieve rowid
+				$sql = "SELECT rowid";
+				$sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans";
+				$sql .= " WHERE transkey = '".$key."'";
+				$sql .= " AND entity IN (".getEntity('overwrite_trans').")";
+				dol_syslog("translation::select from table", LOG_DEBUG);
+				$result = $db->query($sql);
+				if ($result)
+				{
+					$obj = $db->fetch_object($result);
+				}
+				print '<a class="editfielda reposition paddingrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$conf->entity.'&action=edit">'.img_edit().'</a>';
+				print ' ';
+				print '<a href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$conf->entity.'&action=delete&token='.newToken().'">'.img_delete().'</a>';
+				print '&nbsp;&nbsp;';
+				$htmltext = $langs->trans("OriginalValueWas", '<i>'.$newlangfileonly->tab_translate[$key].'</i>');
+				print $form->textwithpicto('', $htmltext, 1, 'info');
+			} elseif (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION))
+			{
+				//print $key.'-'.$val;
+				print '<a class="reposition paddingrightonly" href="'.$_SERVER['PHP_SELF'].'?mode=overwrite&amp;langcode='.$langcode.'&amp;transkey='.$key.'">'.img_edit_add($langs->trans("Overwrite")).'</a>';
+			}
+
+			if (!empty($conf->global->MAIN_FEATURES_LEVEL))
+			{
+				$transifexlangfile = '$'; // $ means 'All'
+				//$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key;
+				$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?q=key%3A'.$key;
+
+				print ' &nbsp; <a href="'.$transifexurl.'" target="transifex">'.img_picto($langs->trans('FixOnTransifex'), 'globe').'</a>';
+			}
+		} else {
+			$htmltext = $langs->trans("TransKeyWithoutOriginalValue", $key);
+			print $form->textwithpicto('', $htmltext, 1, 'warning');
+		}
+		/*if (! empty($conf->multicompany->enabled) && !$user->entity)
         {
             print '<td>'.$val.'</td>';
         }*/
-        print '</td></tr>'."\n";
-    }
+		print '</td></tr>'."\n";
+	}
 
-    print '</table>';
-    print '</div>';
+	print '</table>';
+	print '</div>';
 }
 
 dol_fiche_end();

+ 397 - 397
htdocs/admin/website.php

@@ -124,252 +124,252 @@ $sourceList = array();
 // Actions add or modify a website
 if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
 {
-    $listfield = explode(',', $tabfield[$id]);
-    $listfieldinsert = explode(',', $tabfieldinsert[$id]);
-    $listfieldmodify = explode(',', $tabfieldinsert[$id]);
-    $listfieldvalue = explode(',', $tabfieldvalue[$id]);
-
-    // Check that all fields are filled
-    $ok = 1;
-    foreach ($listfield as $f => $value)
-    {
-    	if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == ''))
-	    {
-    	    $ok = 0;
-        	$fieldnamekey = $listfield[$f];
-	        setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors');
-	        break;
-    	} elseif ($value == 'ref' && !preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value]))
-	    {
+	$listfield = explode(',', $tabfield[$id]);
+	$listfieldinsert = explode(',', $tabfieldinsert[$id]);
+	$listfieldmodify = explode(',', $tabfieldinsert[$id]);
+	$listfieldvalue = explode(',', $tabfieldvalue[$id]);
+
+	// Check that all fields are filled
+	$ok = 1;
+	foreach ($listfield as $f => $value)
+	{
+		if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == ''))
+		{
+			$ok = 0;
+			$fieldnamekey = $listfield[$f];
+			setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors');
+			break;
+		} elseif ($value == 'ref' && !preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value]))
+		{
 			$ok = 0;
-    	    $fieldnamekey = $listfield[$f];
+			$fieldnamekey = $listfield[$f];
 			setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities($fieldnamekey)), null, 'errors');
 			break;
-	    }
-    }
-
-    // Clean parameters
-    if (!empty($_POST['ref']))
-    {
-    	$websitekey = strtolower($_POST['ref']);
-    }
-
-    // Si verif ok et action add, on ajoute la ligne
-    if ($ok && GETPOST('actionadd', 'alpha'))
-    {
-        if ($tabrowid[$id])
-        {
-            // Recupere id libre pour insertion
-            $newid = 0;
-            $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id];
-            $result = $db->query($sql);
-            if ($result)
-            {
-                $obj = $db->fetch_object($result);
-                $newid = ($obj->newid + 1);
-            } else {
-                dol_print_error($db);
-            }
-        }
-
-        /* $website=new Website($db);
+		}
+	}
+
+	// Clean parameters
+	if (!empty($_POST['ref']))
+	{
+		$websitekey = strtolower($_POST['ref']);
+	}
+
+	// Si verif ok et action add, on ajoute la ligne
+	if ($ok && GETPOST('actionadd', 'alpha'))
+	{
+		if ($tabrowid[$id])
+		{
+			// Recupere id libre pour insertion
+			$newid = 0;
+			$sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id];
+			$result = $db->query($sql);
+			if ($result)
+			{
+				$obj = $db->fetch_object($result);
+				$newid = ($obj->newid + 1);
+			} else {
+				dol_print_error($db);
+			}
+		}
+
+		/* $website=new Website($db);
         $website->ref=
         $website->description=
         $website->virtualhost=
         $website->create($user); */
 
-        // Add new entry
-        $sql = "INSERT INTO ".$tabname[$id]." (";
-        // List of fields
-        if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert))
-        	$sql .= $tabrowid[$id].",";
-        $sql .= $tabfieldinsert[$id];
-        $sql .= ",status)";
-        $sql .= " VALUES(";
-
-        // List of values
-        if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert))
-        	$sql .= $newid.",";
-        $i = 0;
-        foreach ($listfieldinsert as $f => $value)
-        {
-            if ($value == 'entity') {
-            	$_POST[$listfieldvalue[$i]] = $conf->entity;
-            }
-            if ($value == 'ref') {
-            	$_POST[$listfieldvalue[$i]] = strtolower($_POST[$listfieldvalue[$i]]);
-            }
-            if ($i) $sql .= ",";
-            if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null";
-            else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
-            $i++;
-        }
-        $sql .= ",1)";
-
-        dol_syslog("actionadd", LOG_DEBUG);
-        $result = $db->query($sql);
-        if ($result)	// Add is ok
-        {
-            setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
-        	unset($_POST); // Clean $_POST array, we keep only
-        } else {
-            if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
-                setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors');
-            } else {
-                dol_print_error($db);
-            }
-        }
-    }
-
-    // Si verif ok et action modify, on modifie la ligne
-    if ($ok && GETPOST('actionmodify', 'alpha'))
-    {
-        if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
-
-        $db->begin();
-
-        $website = new Website($db);
-        $rowid = GETPOST('rowid', 'int');
-        $website->fetch($rowid);
-
-        // Modify entry
-        $sql = "UPDATE ".$tabname[$id]." SET ";
-        // Modifie valeur des champs
-        if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify))
-        {
-            $sql .= $tabrowid[$id]."=";
-            $sql .= "'".$db->escape($rowid)."', ";
-        }
-        $i = 0;
-        foreach ($listfieldmodify as $field)
-        {
-            if ($field == 'entity') {
-            	$_POST[$listfieldvalue[$i]] = $conf->entity;
-            }
-            if ($i) $sql .= ",";
-            $sql .= $field."=";
-            if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null";
-            else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
-            $i++;
-        }
-        $sql .= " WHERE ".$rowidcol." = ".((int) $rowid);
-
-        dol_syslog("actionmodify", LOG_DEBUG);
-        //print $sql;
-        $resql = $db->query($sql);
-        if ($resql)
-        {
-            $newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09'));
-            if ($newname != $website->ref)
-            {
-	            $srcfile = DOL_DATA_ROOT.'/website/'.$website->ref;
-	            $destfile = DOL_DATA_ROOT.'/website/'.$newname;
-
-            	if (dol_is_dir($destfile))
-            	{
-            		$error++;
-            		setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors');
-            	} else {
-	                @rename($srcfile, $destfile);
-
-		            // We must now rename $website->ref into $newname inside files
-		            $arrayreplacement = array($website->ref.'/htmlheader.html' => $newname.'/htmlheader.html');
-		            $listofilestochange = dol_dir_list($destfile, 'files', 0, '\.php$');
+		// Add new entry
+		$sql = "INSERT INTO ".$tabname[$id]." (";
+		// List of fields
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert))
+			$sql .= $tabrowid[$id].",";
+		$sql .= $tabfieldinsert[$id];
+		$sql .= ",status)";
+		$sql .= " VALUES(";
+
+		// List of values
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert))
+			$sql .= $newid.",";
+		$i = 0;
+		foreach ($listfieldinsert as $f => $value)
+		{
+			if ($value == 'entity') {
+				$_POST[$listfieldvalue[$i]] = $conf->entity;
+			}
+			if ($value == 'ref') {
+				$_POST[$listfieldvalue[$i]] = strtolower($_POST[$listfieldvalue[$i]]);
+			}
+			if ($i) $sql .= ",";
+			if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null";
+			else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			$i++;
+		}
+		$sql .= ",1)";
+
+		dol_syslog("actionadd", LOG_DEBUG);
+		$result = $db->query($sql);
+		if ($result)	// Add is ok
+		{
+			setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
+			unset($_POST); // Clean $_POST array, we keep only
+		} else {
+			if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
+				setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors');
+			} else {
+				dol_print_error($db);
+			}
+		}
+	}
+
+	// Si verif ok et action modify, on modifie la ligne
+	if ($ok && GETPOST('actionmodify', 'alpha'))
+	{
+		if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+
+		$db->begin();
+
+		$website = new Website($db);
+		$rowid = GETPOST('rowid', 'int');
+		$website->fetch($rowid);
+
+		// Modify entry
+		$sql = "UPDATE ".$tabname[$id]." SET ";
+		// Modifie valeur des champs
+		if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify))
+		{
+			$sql .= $tabrowid[$id]."=";
+			$sql .= "'".$db->escape($rowid)."', ";
+		}
+		$i = 0;
+		foreach ($listfieldmodify as $field)
+		{
+			if ($field == 'entity') {
+				$_POST[$listfieldvalue[$i]] = $conf->entity;
+			}
+			if ($i) $sql .= ",";
+			$sql .= $field."=";
+			if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null";
+			else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'";
+			$i++;
+		}
+		$sql .= " WHERE ".$rowidcol." = ".((int) $rowid);
+
+		dol_syslog("actionmodify", LOG_DEBUG);
+		//print $sql;
+		$resql = $db->query($sql);
+		if ($resql)
+		{
+			$newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09'));
+			if ($newname != $website->ref)
+			{
+				$srcfile = DOL_DATA_ROOT.'/website/'.$website->ref;
+				$destfile = DOL_DATA_ROOT.'/website/'.$newname;
+
+				if (dol_is_dir($destfile))
+				{
+					$error++;
+					setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors');
+				} else {
+					@rename($srcfile, $destfile);
+
+					// We must now rename $website->ref into $newname inside files
+					$arrayreplacement = array($website->ref.'/htmlheader.html' => $newname.'/htmlheader.html');
+					$listofilestochange = dol_dir_list($destfile, 'files', 0, '\.php$');
 					foreach ($listofilestochange as $key => $value)
-		            {
-		            	dolReplaceInFile($value['fullname'], $arrayreplacement);
-		            }
-            	}
-            }
-        } else {
-        	$error++;
-            setEventMessages($db->lasterror(), null, 'errors');
-        }
-
-        if (!$error)
-        {
-        	$db->commit();
-        } else {
-        	$db->rollback();
-        }
-    }
-    //$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
+					{
+						dolReplaceInFile($value['fullname'], $arrayreplacement);
+					}
+				}
+			}
+		} else {
+			$error++;
+			setEventMessages($db->lasterror(), null, 'errors');
+		}
+
+		if (!$error)
+		{
+			$db->commit();
+		} else {
+			$db->rollback();
+		}
+	}
+	//$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
 }
 
 if (GETPOST('actioncancel', 'alpha'))
 {
-    //$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
+	//$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
 }
 
 if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
 {
-    if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
-
-    $website = new Website($db);
-    $website->fetch($rowid);
-
-    if ($website->id > 0)
-    {
-    	$sql = "DELETE from ".MAIN_DB_PREFIX."website_account WHERE fk_website = ".((int) $rowid);
-    	$result = $db->query($sql);
-
-    	$sql = "DELETE from ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $rowid);
-    	$result = $db->query($sql);
-
-    	$sql = "DELETE from ".MAIN_DB_PREFIX."website_extrafields WHERE fk_object = ".((int) $rowid);
-    	$result = $db->query($sql);
-
-    	$sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $rowid);
-	    $result = $db->query($sql);
-	    if (!$result)
-	    {
-	        if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
-	        {
-	            setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
-	        } else {
-	            dol_print_error($db);
-	        }
-	    }
-
-	    if ($website->ref)
-	    {
-	    	dol_delete_dir_recursive($conf->website->dir_output.'/'.$website->ref);
-	    }
-    } else {
-    	dol_print_error($db, 'Failed to load website with id '.$rowid);
-    }
+	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+
+	$website = new Website($db);
+	$website->fetch($rowid);
+
+	if ($website->id > 0)
+	{
+		$sql = "DELETE from ".MAIN_DB_PREFIX."website_account WHERE fk_website = ".((int) $rowid);
+		$result = $db->query($sql);
+
+		$sql = "DELETE from ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $rowid);
+		$result = $db->query($sql);
+
+		$sql = "DELETE from ".MAIN_DB_PREFIX."website_extrafields WHERE fk_object = ".((int) $rowid);
+		$result = $db->query($sql);
+
+		$sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $rowid);
+		$result = $db->query($sql);
+		if (!$result)
+		{
+			if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
+			{
+				setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
+			} else {
+				dol_print_error($db);
+			}
+		}
+
+		if ($website->ref)
+		{
+			dol_delete_dir_recursive($conf->website->dir_output.'/'.$website->ref);
+		}
+	} else {
+		dol_print_error($db, 'Failed to load website with id '.$rowid);
+	}
 }
 
 // activate
 if ($action == $acts[0])
 {
-    if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
 
-    if ($rowid) {
-        $sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid = ".((int) $rowid);
-    }
+	if ($rowid) {
+		$sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid = ".((int) $rowid);
+	}
 
-    $result = $db->query($sql);
-    if (!$result)
-    {
-        dol_print_error($db);
-    }
+	$result = $db->query($sql);
+	if (!$result)
+	{
+		dol_print_error($db);
+	}
 }
 
 // disable
 if ($action == $acts[1])
 {
-    if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
+	if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; }
 
-    if ($rowid) {
-        $sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid = ".((int) $rowid);
-    }
+	if ($rowid) {
+		$sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid = ".((int) $rowid);
+	}
 
-    $result = $db->query($sql);
-    if (!$result)
-    {
-        dol_print_error($db);
-    }
+	$result = $db->query($sql);
+	if (!$result)
+	{
+		dol_print_error($db);
+	}
 }
 
 
@@ -411,7 +411,7 @@ print "<br>\n";
 // Confirmation de la suppression de la ligne
 if ($action == 'delete')
 {
-    print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid, $langs->trans('DeleteWebsite'), $langs->trans('ConfirmDeleteWebsite'), 'confirm_delete', '', 0, 1, 220);
+	print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid, $langs->trans('DeleteWebsite'), $langs->trans('ConfirmDeleteWebsite'), 'confirm_delete', '', 0, 1, 220);
 }
 //var_dump($elementList);
 
@@ -420,205 +420,205 @@ if ($action == 'delete')
  */
 if ($id)
 {
-    // Complete requete recherche valeurs avec critere de tri
-    $sql = $tabsql[$id];
-    $sql .= $db->order($sortfield, $sortorder);
-    $sql .= $db->plimit($limit + 1, $offset);
-    //print $sql;
-
-    $fieldlist = explode(',', $tabfield[$id]);
-
-    print '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    print '<table class="noborder centpercent">';
-
-    // Form to add a new line
-    if ($tabname[$id])
-    {
-        $alabelisused = 0;
-        $var = false;
-
-        $fieldlist = explode(',', $tabfield[$id]);
-
-        // Line for title
-        print '<tr class="liste_titre">';
-        foreach ($fieldlist as $field => $value)
-        {
-            // Determine le nom du champ par rapport aux noms possibles
-            // dans les dictionnaires de donnees
-            $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut
-            $valuetoshow = $langs->trans($valuetoshow); // try to translate
-            $align = '';
-            if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); }
-            if ($valuetoshow != '')
-            {
-                print '<td class="'.$align.'">';
-            	if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1, $valuetoshow).'</a>';
-            	elseif (!empty($tabhelp[$id][$value]))
-           		{
-           			if ($value == 'virtualhost') print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual');
-           			else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]);
-           		} else print $valuetoshow;
-                print '</td>';
-            }
-            if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1;
-        }
-
-        print '<td colspan="4">';
-        print '</td>';
-        print '</tr>';
-
-        // Line to enter new values
-        print "<tr ".$bcnd[$var].">";
-
-        $obj = new stdClass();
-        // If data was already input, we define them in obj to populate input fields.
-        if (GETPOST('actionadd', 'alpha'))
-        {
-            foreach ($fieldlist as $key=>$val)
-            {
-                if (GETPOST($val, 'alpha'))
-                	$obj->$val = GETPOST($val);
-            }
-        }
-
-        fieldListWebsites($fieldlist, $obj, $tabname[$id], 'add');
-
-        print '<td colspan="3" class="right">';
-        if ($action != 'edit')
-        {
-        	print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
-        }
-        print '</td>';
-        print "</tr>";
-
-        $colspan = count($fieldlist) + 2;
-    }
-
-    print '</table>';
-    print '</form>';
-
-
-    // List of websites in database
-    $resql = $db->query($sql);
-    if ($resql)
-    {
-        $num = $db->num_rows($resql);
-        $i = 0;
-        if ($num)
-        {
-            print '<br>';
-
-            print '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">';
-            print '<input type="hidden" name="token" value="'.newToken().'">';
-            print '<input type="hidden" name="page" value="'.$page.'">';
-            print '<input type="hidden" name="rowid" value="'.$rowid.'">';
-
-            print '<table class="noborder centpercent">';
-
-            // Title of lines
-            print '<tr class="liste_titre">';
-            foreach ($fieldlist as $field => $value)
-            {
-                // Determine le nom du champ par rapport aux noms possibles
-                // dans les dictionnaires de donnees
-                $showfield = 1; // Par defaut
-                $align = "left";
-                $sortable = 1;
-                $valuetoshow = '';
-                /*
+	// Complete requete recherche valeurs avec critere de tri
+	$sql = $tabsql[$id];
+	$sql .= $db->order($sortfield, $sortorder);
+	$sql .= $db->plimit($limit + 1, $offset);
+	//print $sql;
+
+	$fieldlist = explode(',', $tabfield[$id]);
+
+	print '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<table class="noborder centpercent">';
+
+	// Form to add a new line
+	if ($tabname[$id])
+	{
+		$alabelisused = 0;
+		$var = false;
+
+		$fieldlist = explode(',', $tabfield[$id]);
+
+		// Line for title
+		print '<tr class="liste_titre">';
+		foreach ($fieldlist as $field => $value)
+		{
+			// Determine le nom du champ par rapport aux noms possibles
+			// dans les dictionnaires de donnees
+			$valuetoshow = ucfirst($fieldlist[$field]); // Par defaut
+			$valuetoshow = $langs->trans($valuetoshow); // try to translate
+			$align = '';
+			if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); }
+			if ($valuetoshow != '')
+			{
+				print '<td class="'.$align.'">';
+				if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1, $valuetoshow).'</a>';
+				elseif (!empty($tabhelp[$id][$value]))
+		   		{
+		   			if ($value == 'virtualhost') print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual');
+		   			else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]);
+		   		} else print $valuetoshow;
+				print '</td>';
+			}
+			if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1;
+		}
+
+		print '<td colspan="4">';
+		print '</td>';
+		print '</tr>';
+
+		// Line to enter new values
+		print "<tr ".$bcnd[$var].">";
+
+		$obj = new stdClass();
+		// If data was already input, we define them in obj to populate input fields.
+		if (GETPOST('actionadd', 'alpha'))
+		{
+			foreach ($fieldlist as $key=>$val)
+			{
+				if (GETPOST($val, 'alpha'))
+					$obj->$val = GETPOST($val);
+			}
+		}
+
+		fieldListWebsites($fieldlist, $obj, $tabname[$id], 'add');
+
+		print '<td colspan="3" class="right">';
+		if ($action != 'edit')
+		{
+			print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
+		}
+		print '</td>';
+		print "</tr>";
+
+		$colspan = count($fieldlist) + 2;
+	}
+
+	print '</table>';
+	print '</form>';
+
+
+	// List of websites in database
+	$resql = $db->query($sql);
+	if ($resql)
+	{
+		$num = $db->num_rows($resql);
+		$i = 0;
+		if ($num)
+		{
+			print '<br>';
+
+			print '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">';
+			print '<input type="hidden" name="token" value="'.newToken().'">';
+			print '<input type="hidden" name="page" value="'.$page.'">';
+			print '<input type="hidden" name="rowid" value="'.$rowid.'">';
+
+			print '<table class="noborder centpercent">';
+
+			// Title of lines
+			print '<tr class="liste_titre">';
+			foreach ($fieldlist as $field => $value)
+			{
+				// Determine le nom du champ par rapport aux noms possibles
+				// dans les dictionnaires de donnees
+				$showfield = 1; // Par defaut
+				$align = "left";
+				$sortable = 1;
+				$valuetoshow = '';
+				/*
                 $tmparray=getLabelOfField($fieldlist[$field]);
                 $showfield=$tmp['showfield'];
                 $valuetoshow=$tmp['valuetoshow'];
                 $align=$tmp['align'];
                 $sortable=$tmp['sortable'];
 				*/
-                $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut
-                $valuetoshow = $langs->trans($valuetoshow); // try to translate
-                if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); }
-                if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); }
-                if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); }
-
-                // Affiche nom du champ
-                if ($showfield)
-                {
-                    print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder);
-                }
-            }
+				$valuetoshow = ucfirst($fieldlist[$field]); // Par defaut
+				$valuetoshow = $langs->trans($valuetoshow); // try to translate
+				if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); }
+				if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); }
+				if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); }
+
+				// Affiche nom du champ
+				if ($showfield)
+				{
+					print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder);
+				}
+			}
 
 			print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "status", ($page ? 'page='.$page.'&' : ''), "", 'align="center"', $sortfield, $sortorder);
-            print getTitleFieldOfList('');
-            print getTitleFieldOfList('');
-            print '</tr>';
-
-            // Lines with values
-            while ($i < $num)
-            {
-                $obj = $db->fetch_object($resql);
-                //print_r($obj);
-                print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
-                if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code)))
-                {
-                    $tmpaction = 'edit';
-                    $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
-                    $reshook = $hookmanager->executeHooks('editWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
-                    $error = $hookmanager->error; $errors = $hookmanager->errors;
-
-                    if (empty($reshook)) fieldListWebsites($fieldlist, $obj, $tabname[$id], 'edit');
-
-                    print '<td colspan="3" class="right"><a name="'.(!empty($obj->rowid) ? $obj->rowid : $obj->code).'">&nbsp;</a><input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
-                    print '&nbsp;<input type="submit" class="button" name="actioncancel" value="'.$langs->trans("Cancel").'"></td>';
-                } else {
-	              	$tmpaction = 'view';
-                    $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
-                    $reshook = $hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
-
-                    $error = $hookmanager->error; $errors = $hookmanager->errors;
-
-                    if (empty($reshook))
-                    {
-                        foreach ($fieldlist as $field => $value)
-                        {
-                            $showfield = 1;
-                        	$align = "left";
-                        	$fieldname = $fieldlist[$field];
-                            $valuetoshow = $obj->$fieldname;
+			print getTitleFieldOfList('');
+			print getTitleFieldOfList('');
+			print '</tr>';
+
+			// Lines with values
+			while ($i < $num)
+			{
+				$obj = $db->fetch_object($resql);
+				//print_r($obj);
+				print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
+				if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code)))
+				{
+					$tmpaction = 'edit';
+					$parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
+					$reshook = $hookmanager->executeHooks('editWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
+					$error = $hookmanager->error; $errors = $hookmanager->errors;
+
+					if (empty($reshook)) fieldListWebsites($fieldlist, $obj, $tabname[$id], 'edit');
+
+					print '<td colspan="3" class="right"><a name="'.(!empty($obj->rowid) ? $obj->rowid : $obj->code).'">&nbsp;</a><input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
+					print '&nbsp;<input type="submit" class="button" name="actioncancel" value="'.$langs->trans("Cancel").'"></td>';
+				} else {
+				  	$tmpaction = 'view';
+					$parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
+					$reshook = $hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
+
+					$error = $hookmanager->error; $errors = $hookmanager->errors;
+
+					if (empty($reshook))
+					{
+						foreach ($fieldlist as $field => $value)
+						{
+							$showfield = 1;
+							$align = "left";
+							$fieldname = $fieldlist[$field];
+							$valuetoshow = $obj->$fieldname;
 
 							// Show value for field
 							if ($showfield) print '<td align="'.$align.'">'.$valuetoshow.'</td>';
-                        }
-                    }
+						}
+					}
 
-                    // Can an entry be erased or disabled ?
-                    $iserasable = 1; $isdisable = 1; // true by default
-                    if ($obj->status) $iserasable = 0; // We can't delete a website on. Disable it first.
+					// Can an entry be erased or disabled ?
+					$iserasable = 1; $isdisable = 1; // true by default
+					if ($obj->status) $iserasable = 0; // We can't delete a website on. Disable it first.
 
-                    $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&amp;code='.(!empty($obj->code) ?urlencode($obj->code) : '').'&amp;';
+					$url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&amp;code='.(!empty($obj->code) ?urlencode($obj->code) : '').'&amp;';
 
-                    // Active
-                    print '<td align="center" class="nowrap">';
-                    print '<a class="reposition" href="'.$url.'action='.$acts[($obj->status ? 1 : 0)].'">'.$actl[($obj->status ? 1 : 0)].'</a>';
-                    print "</td>";
+					// Active
+					print '<td align="center" class="nowrap">';
+					print '<a class="reposition" href="'.$url.'action='.$acts[($obj->status ? 1 : 0)].'">'.$actl[($obj->status ? 1 : 0)].'</a>';
+					print "</td>";
 
-                    // Modify link
-                    print '<td align="center"><a class="reposition" href="'.$url.'action=edit&token='.newToken().'">'.img_edit().'</a></td>';
+					// Modify link
+					print '<td align="center"><a class="reposition" href="'.$url.'action=edit&token='.newToken().'">'.img_edit().'</a></td>';
 
-                    // Delete link
-                    if ($iserasable) print '<td align="center"><a class="reposition" href="'.$url.'action=delete&token='.newToken().'">'.img_delete().'</a></td>';
-                    else print '<td class="center">'.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').'</td>';
+					// Delete link
+					if ($iserasable) print '<td align="center"><a class="reposition" href="'.$url.'action=delete&token='.newToken().'">'.img_delete().'</a></td>';
+					else print '<td class="center">'.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').'</td>';
 
-                    print "</tr>\n";
-                }
-                $i++;
-            }
+					print "</tr>\n";
+				}
+				$i++;
+			}
 
-            print '</table>';
+			print '</table>';
 
-            print '</form>';
-        }
-    } else {
-        dol_print_error($db);
-    }
+			print '</form>';
+		}
+	} else {
+		dol_print_error($db);
+	}
 }
 
 dol_fiche_end();
@@ -649,7 +649,7 @@ function fieldListWebsites($fieldlist, $obj = '', $tabname = '', $context = '')
 
 	foreach ($fieldlist as $field => $value)
 	{
-	    $fieldname = $fieldlist[$field];
+		$fieldname = $fieldlist[$field];
 		if ($fieldlist[$field] == 'lang')
 		{
 			print '<td>';

+ 1859 - 1859
htdocs/api/class/api_setup.class.php

@@ -35,1865 +35,1865 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php';
  */
 class Setup extends DolibarrApi
 {
-    private $translations = null;
-
-    /**
-     * Constructor
-     */
-    public function __construct()
-    {
-        global $db;
-        $this->db = $db;
-    }
-
-    /**
-     * Get the list of ordering methods.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number {@min 0}
-     * @param int       $active     Payment type is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'OrderByWWW')"
-     *
-     * @url     GET dictionary/ordering_methods
-     *
-     * @return array [List of ordering methods]
-     *
-     * @throws RestException 400
-     */
-    public function getOrderingMethods($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-
-        if (!DolibarrApiAccess::$user->rights->commande->lire) {
-        	throw new RestException(401);
-        }
-
-        $sql = "SELECT rowid, code, libelle as label, module";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method as t";
-        $sql .= " WHERE t.active = ".$active;
-        // Add sql filters
-        if ($sqlfilters)
-        {
-            if (!DolibarrApi::_checkFilters($sqlfilters))
-            {
-                throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters);
-            }
-            $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
-            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(400, $this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of payments types.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number {@min 0}
-     * @param int       $active     Payment type is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')"
-     *
-     * @url     GET dictionary/payment_types
-     *
-     * @return array [List of payment types]
-     *
-     * @throws RestException 400
-     */
-    public function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-
-        if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) {
-        	throw new RestException(401);
-        }
-
-        $sql = "SELECT id, code, type, libelle as label, module";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement as t";
-        $sql .= " WHERE t.entity IN (".getEntity('c_paiement').")";
-        $sql .= " AND t.active = ".$active;
-        // Add sql filters
-        if ($sqlfilters)
-        {
-            if (!DolibarrApi::_checkFilters($sqlfilters))
-            {
-                throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters);
-            }
-              $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
-            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(400, $this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of states/provinces.
-     *
-     * The names of the states will be translated to the given language if
-     * the $lang parameter is provided. The value of $lang must be a language
-     * code supported by Dolibarr, for example 'en_US' or 'fr_FR'.
-     * The returned list is sorted by state ID.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param string    $filter     To filter the countries by name
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array                List of countries
-     *
-     * @url     GET dictionary/states
-     *
-     * @throws RestException
-     */
-    public function getListOfStates($sortfield = "code_departement", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $sqlfilters = '')
-    {
-        $list = array();
-
-        // Note: The filter is not applied in the SQL request because it must
-        // be applied to the translated names, not to the names in database.
-        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_departements as t";
-        $sql .= " WHERE 1 = 1";
-        // Add sql filters
-        if ($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).")";
-        }
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $obj = $this->db->fetch_object($result);
-                $state = new Cstate($this->db);
-                if ($state->fetch($obj->rowid) > 0) {
-                    if (empty($filter) || stripos($state->label, $filter) !== false) {
-                        $list[] = $this->_cleanObjectDatas($state);
-                    }
-                }
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of states');
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get state by ID.
-     *
-     * @param int       $id        ID of state
-     * @return array 			   Array of cleaned object properties
-     *
-     * @url     GET dictionary/states/{id}
-     *
-     * @throws RestException
-     */
-    public function getStateByID($id)
-    {
-        return $this->_fetchCstate($id, '');
-    }
-
-    /**
-     * Get state by Code.
-     *
-     * @param string    $code      Code of state
-     * @return array 			   Array of cleaned object properties
-     *
-     * @url     GET dictionary/states/byCode/{code}
-     *
-     * @throws RestException
-     */
-    public function getStateByCode($code)
-    {
-        return $this->_fetchCstate('', $code);
-    }
-
-    /**
-     * Get the list of countries.
-     *
-     * The names of the countries will be translated to the given language if
-     * the $lang parameter is provided. The value of $lang must be a language
-     * code supported by Dolibarr, for example 'en_US' or 'fr_FR'.
-     * The returned list is sorted by country ID.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param string    $filter     To filter the countries by name
-     * @param string    $lang       Code of the language the label of the countries must be translated to
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array                List of countries
-     *
-     * @url     GET dictionary/countries
-     *
-     * @throws RestException
-     */
-    public function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '')
-    {
-        $list = array();
-
-        // Note: The filter is not applied in the SQL request because it must
-        // be applied to the translated names, not to the names in database.
-        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t";
-        $sql .= " WHERE 1 = 1";
-        // Add sql filters
-        if ($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).")";
-        }
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $obj = $this->db->fetch_object($result);
-                $country = new Ccountry($this->db);
-                if ($country->fetch($obj->rowid) > 0) {
-                    // Translate the name of the country if needed
-                    // and then apply the filter if there is one.
-                    $this->translateLabel($country, $lang, 'Country');
-
-                    if (empty($filter) || stripos($country->label, $filter) !== false) {
-                        $list[] = $this->_cleanObjectDatas($country);
-                    }
-                }
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of countries');
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get country by ID.
-     *
-     * @param int       $id        ID of country
-     * @param string    $lang      Code of the language the name of the
-     *                             country must be translated to
-     * @return array 			   Array of cleaned object properties
-     *
-     * @url     GET dictionary/countries/{id}
-     *
-     * @throws RestException
-     */
-    public function getCountryByID($id, $lang = '')
-    {
-        return $this->_fetchCcountry($id, '', '', $lang);
-    }
-
-    /**
-     * Get country by Code.
-     *
-     * @param string    $code      Code of country
-     * @param string    $lang      Code of the language the name of the
-     *                             country must be translated to
-     * @return array 			   Array of cleaned object properties
-     *
-     * @url     GET dictionary/countries/byCode/{code}
-     *
-     * @throws RestException
-     */
-    public function getCountryByCode($code, $lang = '')
-    {
-        return $this->_fetchCcountry('', $code, '', $lang);
-    }
-
-    /**
-     * Get country by Iso.
-     *
-     * @param string    $iso       ISO of country
-     * @param string    $lang      Code of the language the name of the
-     *                             country must be translated to
-     * @return array 			   Array of cleaned object properties
-     *
-     * @url     GET dictionary/countries/byISO/{iso}
-     *
-     * @throws RestException
-     */
-    public function getCountryByISO($iso, $lang = '')
-    {
-        return $this->_fetchCcountry('', '', $iso, $lang);
-    }
-
-    /**
-    * Get state.
-    *
-    * @param int       $id        ID of state
-    * @param string    $code      Code of state
-    * @return array 			   Array of cleaned object properties
-    *
-    * @throws RestException
-    */
-    private function _fetchCstate($id, $code = '')
-    {
-        $state = new Cstate($this->db);
-
-        $result = $state->fetch($id, $code);
-        if ($result < 0) {
-            throw new RestException(503, 'Error when retrieving state : '.$state->error);
-        } elseif ($result == 0) {
-            throw new RestException(404, 'State not found');
-        }
-
-        return $this->_cleanObjectDatas($state);
-    }
-
-    /**
-    * Get country.
-    *
-    * @param int       $id        ID of country
-    * @param string    $code      Code of country
-    * @param string    $iso       ISO of country
-    * @param string    $lang      Code of the language the name of the
-    *                             country must be translated to
-    * @return array 			   Array of cleaned object properties
-    *
-    * @throws RestException
-    */
-    private function _fetchCcountry($id, $code = '', $iso = '', $lang = '')
-    {
-        $country = new Ccountry($this->db);
-
-        $result = $country->fetch($id, $code, $iso);
-        if ($result < 0) {
-            throw new RestException(503, 'Error when retrieving country : '.$country->error);
-        } elseif ($result == 0) {
-            throw new RestException(404, 'country not found');
-        }
-
-        $this->translateLabel($country, $lang, 'Country');
-
-        return $this->_cleanObjectDatas($country);
-    }
-
-    /**
-     * Get the list of delivery times.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number {@min 0}
-     * @param int       $active     Delivery times is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters SQL criteria to filter with.
-     *
-     * @url     GET dictionary/availability
-     *
-     * @return array [List of availability]
-     *
-     * @throws RestException 400
-     */
-    public function getAvailability($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-
-        if (!DolibarrApiAccess::$user->rights->commande->lire) {
-        	throw new RestException(401);
-        }
-
-        $sql = "SELECT rowid, code, label";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_availability as t";
-        $sql .= " WHERE t.active = ".$active;
-        // Add sql filters
-        if ($sqlfilters)
-        {
-            if (!DolibarrApi::_checkFilters($sqlfilters))
-            {
-                throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters);
-            }
-                  $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
-            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(400, $this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
-    /**
-     * Clean sensible object datas
-     *
-     * @param object    $object    Object to clean
-     * @return array 				Array of cleaned object properties
-     */
-    protected function _cleanObjectDatas($object)
-    {
-        // phpcs:enable
-        $object = parent::_cleanObjectDatas($object);
-
-        unset($object->error);
-        unset($object->errors);
-
-        return $object;
-    }
-
-    /**
-     * Translate the name of the object to the given language.
-     *
-     * @param object   $object    Object with label to translate
-     * @param string   $lang      Code of the language the name of the object must be translated to
-     * @param string   $prefix 	  Prefix for translation key
-     *
-     * @return void
-     */
-    private function translateLabel($object, $lang, $prefix = 'Country')
-    {
-        if (!empty($lang)) {
-            // Load the translations if this is a new language.
-            if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) {
-                global $conf;
-                $this->translations = new Translate('', $conf);
-                $this->translations->setDefaultLang($lang);
-                $this->translations->load('dict');
-            }
-            if ($object->code) {
-                $key = $prefix.$object->code;
-
-                $translation = $this->translations->trans($key);
-                if ($translation != $key) {
-                    $object->label = html_entity_decode($translation);
-                }
-            }
-        }
-    }
-
-    /**
-     * Get the list of shipment methods.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param int       $active     Payment term is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     *
-     * @return array List of shipment methods
-     *
-     * @url     GET dictionary/shipment_methods
-     *
-     * @throws RestException
-     */
-    public function getListOfShipmentMethods($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-        $sql = "SELECT t.rowid, t.code, t.libelle, t.description, t.tracking";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t";
-        $sql .= " WHERE t.active = ".$active;
-        // Add sql filters
-        if ($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).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of shipment methods : '.$this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of events types.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param string    $type       To filter on type of event
-     * @param string    $module     To filter on module events
-     * @param int       $active     Event's type is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array				List of events types
-     *
-     * @url     GET dictionary/event_types
-     *
-     * @throws RestException
-     */
-    public function getListOfEventTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-
-        $sql = "SELECT id, code, type, libelle as label, module";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t";
-        $sql .= " WHERE t.active = ".$active;
-        if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'";
-        if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
-        // Add sql filters
-        if ($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).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-
-    /**
-     * Get the list of Expense Report types.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param string    $module     To filter on module
-     * @param int       $active     Event's type is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array				List of expense report types
-     *
-     * @url     GET dictionary/expensereport_types
-     *
-     * @throws RestException
-     */
-    public function getListOfExpenseReportsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '')
-    {
-    	$list = array();
-
-    	$sql = "SELECT id, code, label, accountancy_code, active, module, position";
-    	$sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as t";
-    	$sql .= " WHERE t.active = ".$active;
-    	if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
-    	// Add sql filters
-    	if ($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).")";
-    	}
-
-
-    	$sql .= $this->db->order($sortfield, $sortorder);
-
-    	if ($limit) {
-    		if ($page < 0) {
-    			$page = 0;
-    		}
-    		$offset = $limit * $page;
-
-    		$sql .= $this->db->plimit($limit, $offset);
-    	}
-
-    	$result = $this->db->query($sql);
-
-    	if ($result) {
-    		$num = $this->db->num_rows($result);
-    		$min = min($num, ($limit <= 0 ? $num : $limit));
-    		for ($i = 0; $i < $min; $i++) {
-    			$list[] = $this->db->fetch_object($result);
-    		}
-    	} else {
-    		throw new RestException(503, 'Error when retrieving list of expense report types : '.$this->db->lasterror());
-    	}
-
-    	return $list;
-    }
-
-
-    /**
-     * Get the list of contacts types.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param string    $type       To filter on type of contact
-     * @param string    $module     To filter on module contacts
-     * @param int       $active     Contact's type is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array	  List of Contacts types
-     *
-     * @url     GET dictionary/contact_types
-     *
-     * @throws RestException
-     */
-    public function getListOfContactTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-
-        $sql = "SELECT rowid, code, element as type, libelle as label, source, module, position";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as t";
-        $sql .= " WHERE t.active = ".$active;
-        if ($type) $sql .= " AND type LIKE '%".$this->db->escape($type)."%'";
-        if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
-        // Add sql filters
-        if ($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).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of contacts types : '.$this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of civilities.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param string    $module     To filter on module events
-     * @param int       $active     Civility is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array		List of civility types
-     *
-     * @url     GET dictionary/civilities
-     *
-     * @throws RestException
-     */
-    public function getListOfCivilities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-
-        $sql = "SELECT rowid, code, label, module";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_civility as t";
-        $sql .= " WHERE t.active = ".$active;
-        if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
-        // Add sql filters
-        if ($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).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of civility : '.$this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of currencies.
-     *
-     * @param int       $multicurrency  Multicurrency rates (0: no multicurrency, 1: last rate, 2: all rates) {@min 0} {@max 2}
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param int       $active     Payment term is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array				List of currencies
-     *
-     * @url     GET dictionary/currencies
-     *
-     * @throws RestException
-     */
-    public function getListOfCurrencies($multicurrency = 0, $sortfield = "code_iso", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-        $sql = "SELECT t.code_iso, t.label, t.unicode";
-        if (!empty($multicurrency)) $sql .= " , cr.date_sync, cr.rate ";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies as t";
-        if (!empty($multicurrency)) {
-            $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso";
-            $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)";
-        }
-        $sql .= " WHERE t.active = ".$active;
-        if (!empty($multicurrency)) {
-            $sql .= " AND m.entity IN (".getEntity('multicurrency').")";
-            if (!empty($multicurrency) && $multicurrency != 2) {
-                $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.rowid)";
-            }
-        }
-
-        // Add sql filters
-        if ($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).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of currency : '.$this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of extra fields.
-     *
-     * @param string	$sortfield	Sort field
-     * @param string	$sortorder	Sort order
-     * @param string    $type       Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...)
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')"
-     * @return array				List of extra fields
-     *
-     * @url     GET extrafields
-     *
-     * @throws RestException
-     */
-    public function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '')
-    {
-        $list = array();
-
-        if (!DolibarrApiAccess::$user->admin) {
-        	throw new RestException(401, 'Only an admin user can get list of extrafields');
-        }
-
-        if ($type == 'thirdparty') $type = 'societe';
-        if ($type == 'contact') $type = 'socpeople';
-
-        $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed";
-        $sql .= " FROM ".MAIN_DB_PREFIX."extrafields as t";
-        $sql .= " WHERE t.entity IN (".getEntity('extrafields').")";
-        if (!empty($type)) $sql .= " AND t.elementtype = '".$this->db->escape($type)."'";
-        // Add sql filters
-        if ($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).")";
-        }
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        $resql = $this->db->query($sql);
-        if ($resql)
-        {
-        	if ($this->db->num_rows($resql))
-        	{
-        		while ($tab = $this->db->fetch_object($resql))
-        		{
-        			// New usage
-        			$list[$tab->elementtype][$tab->name]['type'] = $tab->type;
-        			$list[$tab->elementtype][$tab->name]['label'] = $tab->label;
-        			$list[$tab->elementtype][$tab->name]['size'] = $tab->size;
-        			$list[$tab->elementtype][$tab->name]['elementtype'] = $tab->elementtype;
-        			$list[$tab->elementtype][$tab->name]['default'] = $tab->fielddefault;
-        			$list[$tab->elementtype][$tab->name]['computed'] = $tab->fieldcomputed;
-        			$list[$tab->elementtype][$tab->name]['unique'] = $tab->fieldunique;
-        			$list[$tab->elementtype][$tab->name]['required'] = $tab->fieldrequired;
-        			$list[$tab->elementtype][$tab->name]['param'] = ($tab->param ? unserialize($tab->param) : '');
-        			$list[$tab->elementtype][$tab->name]['pos'] = $tab->pos;
-        			$list[$tab->elementtype][$tab->name]['alwayseditable'] = $tab->alwayseditable;
-        			$list[$tab->elementtype][$tab->name]['perms'] = $tab->perms;
-        			$list[$tab->elementtype][$tab->name]['list'] = $tab->list;
-        		}
-        	}
-        } else {
-            throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror());
-        }
-
-        if (!count($list))
-        {
-        	throw new RestException(404, 'No extrafield found');
-        }
-
-        return $list;
-    }
-
-
-    /**
-     * Get the list of towns.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param string    $zipcode    To filter on zipcode
-     * @param string    $town       To filter on city name
-     * @param int       $active     Payment term is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array				List of towns
-     *
-     * @url     GET dictionary/towns
-     *
-     * @throws RestException
-     */
-    public function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-
-        $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_ziptown as t";
-        $sql .= " AND t.active = ".$active;
-        if ($zipcode) $sql .= " AND t.zip LIKE '%".$this->db->escape($zipcode)."%'";
-        if ($town)    $sql .= " AND t.town LIKE '%".$this->db->escape($town)."%'";
-        // Add sql filters
-        if ($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).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of payments terms.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number {@min 0}
-     * @param int       $active     Payment term is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')"
-     *
-     * @url     GET dictionary/payment_terms
-     *
-     * @return array List of payment terms
-     *
-     * @throws RestException 400
-     */
-    public function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-
-        if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) {
-        	throw new RestException(401);
-        }
-
-        $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t";
-        $sql .= " WHERE t.entity IN (".getEntity('c_payment_term').")";
-        $sql .= " AND t.active = ".$active;
-        // Add sql filters
-        if ($sqlfilters)
-        {
-            if (!DolibarrApi::_checkFilters($sqlfilters))
-            {
-                throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters);
-            }
-                $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
-            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(400, $this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of shipping methods.
-     *
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number {@min 0}
-     * @param int       $active     Shipping methodsm is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')"
-     *
-     * @url     GET dictionary/shipping_methods
-     *
-     * @return array List of shipping methods
-     *
-     * @throws RestException 400
-     */
-    public function getShippingModes($limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-
-        $sql = "SELECT rowid as id, code, libelle as label, description, tracking, module";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t";
-        $sql .= " WHERE t.entity IN (".getEntity('c_shipment_mode').")";
-        $sql .= " AND t.active = ".$active;
-        // Add sql filters
-        if ($sqlfilters)
-        {
-            if (!DolibarrApi::_checkFilters($sqlfilters))
-            {
-                throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters);
-            }
-                $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
-            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
-        }
-
-
-        //$sql.= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(400, $this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of measuring units.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param int       $active     Measuring unit is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array				List of measuring unit
-     *
-     * @url     GET dictionary/units
-     *
-     * @throws RestException
-     */
-    public function getListOfMeasuringUnits($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-        $list = array();
-        //TODO link with multicurrency module
-        $sql = "SELECT t.rowid, t.code, t.label,t.short_label, t.active, t.scale, t.unit_type";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t";
-        $sql .= " WHERE t.active = ".$active;
-        // Add sql filters
-        if ($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).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of measuring units: '.$this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-    /**
-     * Get the list of social networks.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param int       $active     Social network is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array				List of social networks
-     *
-     * @url     GET dictionary/socialnetworks
-     *
-     * @throws RestException
-     */
-    public function getListOfsocialNetworks($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-        global $conf;
-
-        if (empty($conf->socialnetworks->enabled)) {
-            throw new RestException(400, 'API not available: this dictionary is not enabled by setup');
-        }
+	private $translations = null;
+
+	/**
+	 * Constructor
+	 */
+	public function __construct()
+	{
+		global $db;
+		$this->db = $db;
+	}
+
+	/**
+	 * Get the list of ordering methods.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number {@min 0}
+	 * @param int       $active     Payment type is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'OrderByWWW')"
+	 *
+	 * @url     GET dictionary/ordering_methods
+	 *
+	 * @return array [List of ordering methods]
+	 *
+	 * @throws RestException 400
+	 */
+	public function getOrderingMethods($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		if (!DolibarrApiAccess::$user->rights->commande->lire) {
+			throw new RestException(401);
+		}
+
+		$sql = "SELECT rowid, code, libelle as label, module";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_input_method as t";
+		$sql .= " WHERE t.active = ".$active;
+		// Add sql filters
+		if ($sqlfilters)
+		{
+			if (!DolibarrApi::_checkFilters($sqlfilters))
+			{
+				throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters);
+			}
+			$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
+			$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(400, $this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of payments types.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number {@min 0}
+	 * @param int       $active     Payment type is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')"
+	 *
+	 * @url     GET dictionary/payment_types
+	 *
+	 * @return array [List of payment types]
+	 *
+	 * @throws RestException 400
+	 */
+	public function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) {
+			throw new RestException(401);
+		}
+
+		$sql = "SELECT id, code, type, libelle as label, module";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_paiement as t";
+		$sql .= " WHERE t.entity IN (".getEntity('c_paiement').")";
+		$sql .= " AND t.active = ".$active;
+		// Add sql filters
+		if ($sqlfilters)
+		{
+			if (!DolibarrApi::_checkFilters($sqlfilters))
+			{
+				throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters);
+			}
+			  $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
+			$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(400, $this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of states/provinces.
+	 *
+	 * The names of the states will be translated to the given language if
+	 * the $lang parameter is provided. The value of $lang must be a language
+	 * code supported by Dolibarr, for example 'en_US' or 'fr_FR'.
+	 * The returned list is sorted by state ID.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param string    $filter     To filter the countries by name
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array                List of countries
+	 *
+	 * @url     GET dictionary/states
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfStates($sortfield = "code_departement", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $sqlfilters = '')
+	{
+		$list = array();
+
+		// Note: The filter is not applied in the SQL request because it must
+		// be applied to the translated names, not to the names in database.
+		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_departements as t";
+		$sql .= " WHERE 1 = 1";
+		// Add sql filters
+		if ($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).")";
+		}
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$obj = $this->db->fetch_object($result);
+				$state = new Cstate($this->db);
+				if ($state->fetch($obj->rowid) > 0) {
+					if (empty($filter) || stripos($state->label, $filter) !== false) {
+						$list[] = $this->_cleanObjectDatas($state);
+					}
+				}
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of states');
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get state by ID.
+	 *
+	 * @param int       $id        ID of state
+	 * @return array 			   Array of cleaned object properties
+	 *
+	 * @url     GET dictionary/states/{id}
+	 *
+	 * @throws RestException
+	 */
+	public function getStateByID($id)
+	{
+		return $this->_fetchCstate($id, '');
+	}
+
+	/**
+	 * Get state by Code.
+	 *
+	 * @param string    $code      Code of state
+	 * @return array 			   Array of cleaned object properties
+	 *
+	 * @url     GET dictionary/states/byCode/{code}
+	 *
+	 * @throws RestException
+	 */
+	public function getStateByCode($code)
+	{
+		return $this->_fetchCstate('', $code);
+	}
+
+	/**
+	 * Get the list of countries.
+	 *
+	 * The names of the countries will be translated to the given language if
+	 * the $lang parameter is provided. The value of $lang must be a language
+	 * code supported by Dolibarr, for example 'en_US' or 'fr_FR'.
+	 * The returned list is sorted by country ID.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param string    $filter     To filter the countries by name
+	 * @param string    $lang       Code of the language the label of the countries must be translated to
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array                List of countries
+	 *
+	 * @url     GET dictionary/countries
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '')
+	{
+		$list = array();
+
+		// Note: The filter is not applied in the SQL request because it must
+		// be applied to the translated names, not to the names in database.
+		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t";
+		$sql .= " WHERE 1 = 1";
+		// Add sql filters
+		if ($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).")";
+		}
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$obj = $this->db->fetch_object($result);
+				$country = new Ccountry($this->db);
+				if ($country->fetch($obj->rowid) > 0) {
+					// Translate the name of the country if needed
+					// and then apply the filter if there is one.
+					$this->translateLabel($country, $lang, 'Country');
+
+					if (empty($filter) || stripos($country->label, $filter) !== false) {
+						$list[] = $this->_cleanObjectDatas($country);
+					}
+				}
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of countries');
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get country by ID.
+	 *
+	 * @param int       $id        ID of country
+	 * @param string    $lang      Code of the language the name of the
+	 *                             country must be translated to
+	 * @return array 			   Array of cleaned object properties
+	 *
+	 * @url     GET dictionary/countries/{id}
+	 *
+	 * @throws RestException
+	 */
+	public function getCountryByID($id, $lang = '')
+	{
+		return $this->_fetchCcountry($id, '', '', $lang);
+	}
+
+	/**
+	 * Get country by Code.
+	 *
+	 * @param string    $code      Code of country
+	 * @param string    $lang      Code of the language the name of the
+	 *                             country must be translated to
+	 * @return array 			   Array of cleaned object properties
+	 *
+	 * @url     GET dictionary/countries/byCode/{code}
+	 *
+	 * @throws RestException
+	 */
+	public function getCountryByCode($code, $lang = '')
+	{
+		return $this->_fetchCcountry('', $code, '', $lang);
+	}
+
+	/**
+	 * Get country by Iso.
+	 *
+	 * @param string    $iso       ISO of country
+	 * @param string    $lang      Code of the language the name of the
+	 *                             country must be translated to
+	 * @return array 			   Array of cleaned object properties
+	 *
+	 * @url     GET dictionary/countries/byISO/{iso}
+	 *
+	 * @throws RestException
+	 */
+	public function getCountryByISO($iso, $lang = '')
+	{
+		return $this->_fetchCcountry('', '', $iso, $lang);
+	}
+
+	/**
+	 * Get state.
+	 *
+	 * @param int       $id        ID of state
+	 * @param string    $code      Code of state
+	 * @return array 			   Array of cleaned object properties
+	 *
+	 * @throws RestException
+	 */
+	private function _fetchCstate($id, $code = '')
+	{
+		$state = new Cstate($this->db);
+
+		$result = $state->fetch($id, $code);
+		if ($result < 0) {
+			throw new RestException(503, 'Error when retrieving state : '.$state->error);
+		} elseif ($result == 0) {
+			throw new RestException(404, 'State not found');
+		}
+
+		return $this->_cleanObjectDatas($state);
+	}
+
+	/**
+	 * Get country.
+	 *
+	 * @param int       $id        ID of country
+	 * @param string    $code      Code of country
+	 * @param string    $iso       ISO of country
+	 * @param string    $lang      Code of the language the name of the
+	 *                             country must be translated to
+	 * @return array 			   Array of cleaned object properties
+	 *
+	 * @throws RestException
+	 */
+	private function _fetchCcountry($id, $code = '', $iso = '', $lang = '')
+	{
+		$country = new Ccountry($this->db);
+
+		$result = $country->fetch($id, $code, $iso);
+		if ($result < 0) {
+			throw new RestException(503, 'Error when retrieving country : '.$country->error);
+		} elseif ($result == 0) {
+			throw new RestException(404, 'country not found');
+		}
+
+		$this->translateLabel($country, $lang, 'Country');
+
+		return $this->_cleanObjectDatas($country);
+	}
+
+	/**
+	 * Get the list of delivery times.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number {@min 0}
+	 * @param int       $active     Delivery times is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters SQL criteria to filter with.
+	 *
+	 * @url     GET dictionary/availability
+	 *
+	 * @return array [List of availability]
+	 *
+	 * @throws RestException 400
+	 */
+	public function getAvailability($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		if (!DolibarrApiAccess::$user->rights->commande->lire) {
+			throw new RestException(401);
+		}
+
+		$sql = "SELECT rowid, code, label";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_availability as t";
+		$sql .= " WHERE t.active = ".$active;
+		// Add sql filters
+		if ($sqlfilters)
+		{
+			if (!DolibarrApi::_checkFilters($sqlfilters))
+			{
+				throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters);
+			}
+				  $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
+			$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(400, $this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
+	/**
+	 * Clean sensible object datas
+	 *
+	 * @param object    $object    Object to clean
+	 * @return array 				Array of cleaned object properties
+	 */
+	protected function _cleanObjectDatas($object)
+	{
+		// phpcs:enable
+		$object = parent::_cleanObjectDatas($object);
+
+		unset($object->error);
+		unset($object->errors);
+
+		return $object;
+	}
+
+	/**
+	 * Translate the name of the object to the given language.
+	 *
+	 * @param object   $object    Object with label to translate
+	 * @param string   $lang      Code of the language the name of the object must be translated to
+	 * @param string   $prefix 	  Prefix for translation key
+	 *
+	 * @return void
+	 */
+	private function translateLabel($object, $lang, $prefix = 'Country')
+	{
+		if (!empty($lang)) {
+			// Load the translations if this is a new language.
+			if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) {
+				global $conf;
+				$this->translations = new Translate('', $conf);
+				$this->translations->setDefaultLang($lang);
+				$this->translations->load('dict');
+			}
+			if ($object->code) {
+				$key = $prefix.$object->code;
+
+				$translation = $this->translations->trans($key);
+				if ($translation != $key) {
+					$object->label = html_entity_decode($translation);
+				}
+			}
+		}
+	}
+
+	/**
+	 * Get the list of shipment methods.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param int       $active     Payment term is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 *
+	 * @return array List of shipment methods
+	 *
+	 * @url     GET dictionary/shipment_methods
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfShipmentMethods($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+		$sql = "SELECT t.rowid, t.code, t.libelle, t.description, t.tracking";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t";
+		$sql .= " WHERE t.active = ".$active;
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of shipment methods : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of events types.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param string    $type       To filter on type of event
+	 * @param string    $module     To filter on module events
+	 * @param int       $active     Event's type is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array				List of events types
+	 *
+	 * @url     GET dictionary/event_types
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfEventTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		$sql = "SELECT id, code, type, libelle as label, module";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t";
+		$sql .= " WHERE t.active = ".$active;
+		if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'";
+		if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+
+	/**
+	 * Get the list of Expense Report types.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param string    $module     To filter on module
+	 * @param int       $active     Event's type is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array				List of expense report types
+	 *
+	 * @url     GET dictionary/expensereport_types
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfExpenseReportsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		$sql = "SELECT id, code, label, accountancy_code, active, module, position";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as t";
+		$sql .= " WHERE t.active = ".$active;
+		if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of expense report types : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+
+	/**
+	 * Get the list of contacts types.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param string    $type       To filter on type of contact
+	 * @param string    $module     To filter on module contacts
+	 * @param int       $active     Contact's type is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array	  List of Contacts types
+	 *
+	 * @url     GET dictionary/contact_types
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfContactTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		$sql = "SELECT rowid, code, element as type, libelle as label, source, module, position";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as t";
+		$sql .= " WHERE t.active = ".$active;
+		if ($type) $sql .= " AND type LIKE '%".$this->db->escape($type)."%'";
+		if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of contacts types : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of civilities.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param string    $module     To filter on module events
+	 * @param int       $active     Civility is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array		List of civility types
+	 *
+	 * @url     GET dictionary/civilities
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfCivilities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '')
+	{
+		$list = array();
 
+		$sql = "SELECT rowid, code, label, module";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_civility as t";
+		$sql .= " WHERE t.active = ".$active;
+		if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of civility : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of currencies.
+	 *
+	 * @param int       $multicurrency  Multicurrency rates (0: no multicurrency, 1: last rate, 2: all rates) {@min 0} {@max 2}
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param int       $active     Payment term is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array				List of currencies
+	 *
+	 * @url     GET dictionary/currencies
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfCurrencies($multicurrency = 0, $sortfield = "code_iso", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
 		$list = array();
-        //TODO link with multicurrency module
-        $sql = "SELECT t.rowid, t.entity, t.code, t.label, t.url, t.icon, t.active";
-        $sql .= " FROM ".MAIN_DB_PREFIX."c_socialnetworks as t";
-        $sql .= " WHERE t.entity IN (".getEntity('c_socialnetworks').")";
-        $sql .= " AND t.active = ".$active;
-        // Add sql filters
-        if ($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).")";
-        }
-
-
-        $sql .= $this->db->order($sortfield, $sortorder);
-
-        if ($limit) {
-            if ($page < 0) {
-                $page = 0;
-            }
-            $offset = $limit * $page;
-
-            $sql .= $this->db->plimit($limit, $offset);
-        }
-
-        $result = $this->db->query($sql);
-
-        if ($result) {
-            $num = $this->db->num_rows($result);
-            $min = min($num, ($limit <= 0 ? $num : $limit));
-            for ($i = 0; $i < $min; $i++) {
-                $list[] = $this->db->fetch_object($result);
-            }
-        } else {
-            throw new RestException(503, 'Error when retrieving list of social networks: '.$this->db->lasterror());
-        }
-
-        return $list;
-    }
-
-     /**
-     * Get the list of tickets categories.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param int       $active     Payment term is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array				List of ticket categories
-     *
-     * @url     GET dictionary/ticket_categories
-     *
-     * @throws RestException
-     */
-    public function getTicketsCategories($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-    	$list = array();
-
-    	$sql = "SELECT rowid, code, pos,  label, use_default, description";
-    	$sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t";
-        $sql .= " WHERE t.active = ".$active;
-    	// Add sql filters
-    	if ($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).")";
-    	}
-
-
-    	$sql .= $this->db->order($sortfield, $sortorder);
-
-    	if ($limit) {
-    		if ($page < 0) {
-    			$page = 0;
-    		}
-    		$offset = $limit * $page;
-
-    		$sql .= $this->db->plimit($limit, $offset);
-    	}
-
-    	$result = $this->db->query($sql);
-
-    	if ($result) {
-    		$num = $this->db->num_rows($result);
-    		$min = min($num, ($limit <= 0 ? $num : $limit));
-    		for ($i = 0; $i < $min; $i++) {
-    			$list[] = $this->db->fetch_object($result);
-    		}
-    	} else {
-    		throw new RestException(503, 'Error when retrieving list of ticket categories : '.$this->db->lasterror());
-    	}
-
-    	return $list;
-    }
-
-    /**
-     * Get the list of tickets severity.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param int       $active     Payment term is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array				List of ticket severities
-     *
-     * @url     GET dictionary/ticket_severities
-     *
-     * @throws RestException
-     */
-    public function getTicketsSeverities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-    	$list = array();
-
-    	$sql = "SELECT rowid, code, pos,  label, use_default, color, description";
-    	$sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t";
-        $sql .= " WHERE t.active = ".$active;
-    	// Add sql filters
-    	if ($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).")";
-    	}
-
-
-    	$sql .= $this->db->order($sortfield, $sortorder);
-
-    	if ($limit) {
-    		if ($page < 0) {
-    			$page = 0;
-    		}
-    		$offset = $limit * $page;
-
-    		$sql .= $this->db->plimit($limit, $offset);
-    	}
-
-    	$result = $this->db->query($sql);
-
-    	if ($result) {
-    		$num = $this->db->num_rows($result);
-    		$min = min($num, ($limit <= 0 ? $num : $limit));
-    		for ($i = 0; $i < $min; $i++) {
-    			$list[] = $this->db->fetch_object($result);
-    		}
-    	} else {
-    		throw new RestException(503, 'Error when retrieving list of ticket severities : '.$this->db->lasterror());
-    	}
-
-    	return $list;
-    }
-
-    /**
-     * Get the list of tickets types.
-     *
-     * @param string    $sortfield  Sort field
-     * @param string    $sortorder  Sort order
-     * @param int       $limit      Number of items per page
-     * @param int       $page       Page number (starting from zero)
-     * @param int       $active     Payment term is active or not {@min 0} {@max 1}
-     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
-     * @return array				List of ticket types
-     *
-     * @url     GET dictionary/ticket_types
-     *
-     * @throws RestException
-     */
-    public function getTicketsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
-    {
-    	$list = array();
-
-    	$sql = "SELECT rowid, code, pos,  label, use_default, description";
-    	$sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t";
-        $sql .= " WHERE t.active = ".(int) $active;
-    	// if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'";
-    	// if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
-    	// Add sql filters
-    	if ($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).")";
-    	}
-
-
-    	$sql .= $this->db->order($sortfield, $sortorder);
-
-    	if ($limit) {
-    		if ($page < 0) {
-    			$page = 0;
-    		}
-    		$offset = $limit * $page;
-
-    		$sql .= $this->db->plimit($limit, $offset);
-    	}
-
-    	$result = $this->db->query($sql);
-
-    	if ($result) {
-    		$num = $this->db->num_rows($result);
-    		$min = min($num, ($limit <= 0 ? $num : $limit));
-    		for ($i = 0; $i < $min; $i++) {
-    			$list[] = $this->db->fetch_object($result);
-    		}
-    	} else {
-    		throw new RestException(503, 'Error when retrieving list of ticket types : '.$this->db->lasterror());
-    	}
-
-    	return $list;
-    }
-
-    /**
-     * Get properties of company
-     *
-     * @url	GET /company
-     *
-     * @return  array|mixed Data without useless information
-     *
-     */
-    public function getCompany()
-    {
-        global $mysoc;
-
-        return $this->_cleanObjectDatas($mysoc);
-    }
-
-
-    /**
-     * Get value of a setup variables
-     *
-     * Note that conf variables that stores security key or password hashes can't be loaded with API.
-     *
-     * @param	string			$constantname	Name of conf variable to get
-     * @return  array|mixed 				Data without useless information
-     *
-     * @url     GET conf/{constantname}
-     *
-     * @throws RestException 403 Forbidden
-     * @throws RestException 404 Error Bad or unknown value for constantname
-     */
-    public function getConf($constantname)
-    {
-    	global $conf;
-
-    	if (!DolibarrApiAccess::$user->admin
-    		&& (empty($conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ) || DolibarrApiAccess::$user->login != $conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ)) {
-    		throw new RestException(403, 'Error API open to admin users only or to the users with logins defined into constant API_LOGINS_ALLOWED_FOR_CONST_READ');
-    	}
-
-    	if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) {
-    		throw new RestException(404, 'Error Bad or unknown value for constantname');
-    	}
-    	if (isASecretKey($constantname)) {
-    		throw new RestException(403, 'Forbidden. This parameter cant be read with APIs');
-    	}
-
-    	return $conf->global->$constantname;
-    }
-
-    /**
-     * Do a test of integrity for files and setup.
-     *
-     * @param string	$target			Can be 'local' or 'default' or Url of the signatures file to use for the test. Must be reachable by the tested Dolibarr.
-     * @return array					Result of file and setup integrity check
-     *
-     * @url     GET checkintegrity
-     *
-     * @throws RestException 404 Signature file not found
-     * @throws RestException 500 Technical error
-     * @throws RestException 503 Forbidden
-     */
-    public function getCheckIntegrity($target)
-    {
-    	global $langs, $conf;
-
-    	if (!DolibarrApiAccess::$user->admin
-    		&& (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK))
-    	{
-    		throw new RestException(503, 'Error API open to admin users only or to the users with logins defined into constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK');
-    	}
-
-    	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-    	require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
-
-    	$langs->load("admin");
-
-    	$outexpectedchecksum = '';
-    	$outcurrentchecksum = '';
-
-    	// Modified or missing files
-    	$file_list = array('missing' => array(), 'updated' => array());
-
-    	// Local file to compare to
-    	$xmlshortfile = GETPOST('xmlshortfile') ?GETPOST('xmlshortfile') : '/install/filelist-'.DOL_VERSION.'.xml';
-    	$xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile;
-    	// Remote file to compare to
-    	$xmlremote = ($target == 'default' ? '' : $target);
-    	if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL;
-    	$param = 'MAIN_FILECHECK_URL_'.DOL_VERSION;
-    	if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param;
-    	if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml';
-
-    	if ($target == 'local')
-    	{
-    		if (dol_is_file($xmlfile))
-    		{
-    			$xml = simplexml_load_file($xmlfile);
-    		} else {
-    			throw new RestException(500, $langs->trans('XmlNotFound').': '.$xmlfile);
-    		}
-    	} else {
-    		$xmlarray = getURLContent($xmlremote);
-
-    		// Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...)
-    		if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404')
-    		{
-    			$xmlfile = $xmlarray['content'];
-    			//print "xmlfilestart".$xmlfile."endxmlfile";
-    			$xml = simplexml_load_string($xmlfile);
-    		} else {
-    			$errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg'];
-    			throw new RestException(500, $errormsg);
-    		}
-    	}
-
-
-
-    	if ($xml)
-    	{
-    		$checksumconcat = array();
-    		$file_list = array();
-    		$out = '';
-
-    		// Forced constants
-    		if (is_object($xml->dolibarr_constants[0]))
-    		{
-    			$out .= load_fiche_titre($langs->trans("ForcedConstants"));
-
-    			$out .= '<div class="div-table-responsive-no-min">';
-    			$out .= '<table class="noborder">';
-    			$out .= '<tr class="liste_titre">';
-    			$out .= '<td>#</td>';
-    			$out .= '<td>'.$langs->trans("Constant").'</td>';
-    			$out .= '<td class="center">'.$langs->trans("ExpectedValue").'</td>';
-    			$out .= '<td class="center">'.$langs->trans("Value").'</td>';
-    			$out .= '</tr>'."\n";
-
-    			$i = 0;
-    			foreach ($xml->dolibarr_constants[0]->constant as $constant)    // $constant is a simpleXMLElement
-    			{
-    				$constname = $constant['name'];
-    				$constvalue = (string) $constant;
-    				$constvalue = (empty($constvalue) ? '0' : $constvalue);
-    				// Value found
-    				$value = '';
-    				if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname;
-    				$valueforchecksum = (empty($value) ? '0' : $value);
-
-    				$checksumconcat[] = $valueforchecksum;
-
-    				$i++;
-    				$out .= '<tr class="oddeven">';
-    				$out .= '<td>'.$i.'</td>'."\n";
-    				$out .= '<td>'.$constname.'</td>'."\n";
-    				$out .= '<td class="center">'.$constvalue.'</td>'."\n";
-    				$out .= '<td class="center">'.$valueforchecksum.'</td>'."\n";
-    				$out .= "</tr>\n";
-    			}
-
-    			if ($i == 0)
-    			{
-    				$out .= '<tr class="oddeven"><td colspan="4" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
-    			}
-    			$out .= '</table>';
-    			$out .= '</div>';
-
-    			$out .= '<br>';
-    		}
-
-    		// Scan htdocs
-    		if (is_object($xml->dolibarr_htdocs_dir[0]))
-    		{
-    			//var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit;
-    			$includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']);
-
-    			// Defined qualified files (must be same than into generate_filelist_xml.php)
-    			$regextoinclude = '\.(php|php3|php4|php5|phtml|phps|phar|inc|css|scss|html|xml|js|json|tpl|jpg|jpeg|png|gif|ico|sql|lang|txt|yml|bak|md|mp3|mp4|wav|mkv|z|gz|zip|rar|tar|less|svg|eot|woff|woff2|ttf|manifest)$';
-    			$regextoexclude = '('.($includecustom ? '' : 'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs
-    			$scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude);
-
-    			// Fill file_list with files in signature, new files, modified files
-    			$ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list
-    			// Complete with list of new files
-    			foreach ($scanfiles as $keyfile => $valfile)
-    			{
-    				$tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']);
-    				if (!in_array($tmprelativefilename, $file_list['insignature']))
-    				{
-    					$md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file
-    					$file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile);
-    				}
-    			}
-
-    			// Files missings
-    			$out .= load_fiche_titre($langs->trans("FilesMissing"));
-
-    			$out .= '<div class="div-table-responsive-no-min">';
-    			$out .= '<table class="noborder">';
-    			$out .= '<tr class="liste_titre">';
-    			$out .= '<td>#</td>';
-    			$out .= '<td>'.$langs->trans("Filename").'</td>';
-    			$out .= '<td class="center">'.$langs->trans("ExpectedChecksum").'</td>';
-    			$out .= '</tr>'."\n";
-    			$tmpfilelist = dol_sort_array($file_list['missing'], 'filename');
-    			if (is_array($tmpfilelist) && count($tmpfilelist))
-    			{
-    				$i = 0;
-    				foreach ($tmpfilelist as $file)
-    				{
-    					$i++;
-    					$out .= '<tr class="oddeven">';
-    					$out .= '<td>'.$i.'</td>'."\n";
-    					$out .= '<td>'.$file['filename'].'</td>'."\n";
-    					$out .= '<td class="center">'.$file['expectedmd5'].'</td>'."\n";
-    					$out .= "</tr>\n";
-    				}
-    			} else {
-    				$out .= '<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
-    			}
-    			$out .= '</table>';
-    			$out .= '</div>';
-
-    			$out .= '<br>';
-
-    			// Files modified
-    			$out .= load_fiche_titre($langs->trans("FilesModified"));
-
-    			$totalsize = 0;
-    			$out .= '<div class="div-table-responsive-no-min">';
-    			$out .= '<table class="noborder">';
-    			$out .= '<tr class="liste_titre">';
-    			$out .= '<td>#</td>';
-    			$out .= '<td>'.$langs->trans("Filename").'</td>';
-    			$out .= '<td class="center">'.$langs->trans("ExpectedChecksum").'</td>';
-    			$out .= '<td class="center">'.$langs->trans("CurrentChecksum").'</td>';
-    			$out .= '<td class="right">'.$langs->trans("Size").'</td>';
-    			$out .= '<td class="right">'.$langs->trans("DateModification").'</td>';
-    			$out .= '</tr>'."\n";
-    			$tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename');
-    			if (is_array($tmpfilelist2) && count($tmpfilelist2))
-    			{
-    				$i = 0;
-    				foreach ($tmpfilelist2 as $file)
-    				{
-    					$i++;
-    					$out .= '<tr class="oddeven">';
-    					$out .= '<td>'.$i.'</td>'."\n";
-    					$out .= '<td>'.$file['filename'].'</td>'."\n";
-    					$out .= '<td class="center">'.$file['expectedmd5'].'</td>'."\n";
-    					$out .= '<td class="center">'.$file['md5'].'</td>'."\n";
-    					$size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']);
-    					$totalsize += $size;
-    					$out .= '<td class="right">'.dol_print_size($size).'</td>'."\n";
-    					$out .= '<td class="right">'.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'</td>'."\n";
-    					$out .= "</tr>\n";
-    				}
-    				$out .= '<tr class="liste_total">';
-    				$out .= '<td></td>'."\n";
-    				$out .= '<td>'.$langs->trans("Total").'</td>'."\n";
-    				$out .= '<td align="center"></td>'."\n";
-    				$out .= '<td align="center"></td>'."\n";
-    				$out .= '<td class="right">'.dol_print_size($totalsize).'</td>'."\n";
-    				$out .= '<td class="right"></td>'."\n";
-    				$out .= "</tr>\n";
-    			} else {
-    				$out .= '<tr class="oddeven"><td colspan="5" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
-    			}
-    			$out .= '</table>';
-    			$out .= '</div>';
-
-    			$out .= '<br>';
-
-    			// Files added
-    			$out .= load_fiche_titre($langs->trans("FilesAdded"));
-
-    			$totalsize = 0;
-    			$out .= '<div class="div-table-responsive-no-min">';
-    			$out .= '<table class="noborder">';
-    			$out .= '<tr class="liste_titre">';
-    			$out .= '<td>#</td>';
-    			$out .= '<td>'.$langs->trans("Filename").'</td>';
-    			$out .= '<td class="center">'.$langs->trans("ExpectedChecksum").'</td>';
-    			$out .= '<td class="center">'.$langs->trans("CurrentChecksum").'</td>';
-    			$out .= '<td class="right">'.$langs->trans("Size").'</td>';
-    			$out .= '<td class="right">'.$langs->trans("DateModification").'</td>';
-    			$out .= '</tr>'."\n";
-    			$tmpfilelist3 = dol_sort_array($file_list['added'], 'filename');
-    			if (is_array($tmpfilelist3) && count($tmpfilelist3))
-    			{
-    				$i = 0;
-    				foreach ($tmpfilelist3 as $file)
-    				{
-    					$i++;
-    					$out .= '<tr class="oddeven">';
-    					$out .= '<td>'.$i.'</td>'."\n";
-    					$out .= '<td>'.$file['filename'].'</td>'."\n";
-    					$out .= '<td class="center">'.$file['expectedmd5'].'</td>'."\n";
-    					$out .= '<td class="center">'.$file['md5'].'</td>'."\n";
-    					$size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']);
-    					$totalsize += $size;
-    					$out .= '<td class="right">'.dol_print_size($size).'</td>'."\n";
-    					$out .= '<td class="right">'.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'</td>'."\n";
-    					$out .= "</tr>\n";
-    				}
-    				$out .= '<tr class="liste_total">';
-    				$out .= '<td></td>'."\n";
-    				$out .= '<td>'.$langs->trans("Total").'</td>'."\n";
-    				$out .= '<td align="center"></td>'."\n";
-    				$out .= '<td align="center"></td>'."\n";
-    				$out .= '<td class="right">'.dol_print_size($totalsize).'</td>'."\n";
-    				$out .= '<td class="right"></td>'."\n";
-    				$out .= "</tr>\n";
-    			} else {
-    				$out .= '<tr class="oddeven"><td colspan="5" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
-    			}
-    			$out .= '</table>';
-    			$out .= '</div>';
-
-
-    			// Show warning
-    			if (empty($tmpfilelist) && empty($tmpfilelist2) && empty($tmpfilelist3))
-    			{
-    				//setEventMessages($langs->trans("FileIntegrityIsStrictlyConformedWithReference"), null, 'mesgs');
-    			} else {
-    				//setEventMessages($langs->trans("FileIntegritySomeFilesWereRemovedOrModified"), null, 'warnings');
-    			}
-    		} else {
-    			throw new RestException(500, 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile);
-    		}
-
-
-    		// Scan scripts
-
-
-    		asort($checksumconcat); // Sort list of checksum
-    		//var_dump($checksumconcat);
-    		$checksumget = md5(join(',', $checksumconcat));
-    		$checksumtoget = trim((string) $xml->dolibarr_htdocs_dir_checksum);
-
-    		$outexpectedchecksum = ($checksumtoget ? $checksumtoget : $langs->trans("Unknown"));
-    		if ($checksumget == $checksumtoget)
-    		{
-    			if (count($file_list['added']))
-    			{
-    				$resultcode = 'warning';
-    				$resultcomment = 'FileIntegrityIsOkButFilesWereAdded';
-    				//$outcurrentchecksum =  $checksumget.' - <span class="'.$resultcode.'">'.$langs->trans("FileIntegrityIsOkButFilesWereAdded").'</span>';
-    				$outcurrentchecksum = $checksumget;
-    			} else {
-    				$resultcode = 'ok';
-    				$resultcomment = 'Success';
-    				//$outcurrentchecksum = '<span class="'.$resultcode.'">'.$checksumget.'</span>';
-    				$outcurrentchecksum = $checksumget;
-    			}
-    		} else {
-    			$resultcode = 'error';
-    			$resultcomment = 'Error';
-    			//$outcurrentchecksum = '<span class="'.$resultcode.'">'.$checksumget.'</span>';
-    			$outcurrentchecksum = $checksumget;
-    		}
-    	} else {
-    		throw new RestException(404, 'No signature file known');
-    	}
-
-    	return array('resultcode'=>$resultcode, 'resultcomment'=>$resultcomment, 'expectedchecksum'=> $outexpectedchecksum, 'currentchecksum'=> $outcurrentchecksum, 'out'=>$out);
-    }
+		$sql = "SELECT t.code_iso, t.label, t.unicode";
+		if (!empty($multicurrency)) $sql .= " , cr.date_sync, cr.rate ";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_currencies as t";
+		if (!empty($multicurrency)) {
+			$sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso";
+			$sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)";
+		}
+		$sql .= " WHERE t.active = ".$active;
+		if (!empty($multicurrency)) {
+			$sql .= " AND m.entity IN (".getEntity('multicurrency').")";
+			if (!empty($multicurrency) && $multicurrency != 2) {
+				$sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.rowid)";
+			}
+		}
+
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of currency : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of extra fields.
+	 *
+	 * @param string	$sortfield	Sort field
+	 * @param string	$sortorder	Sort order
+	 * @param string    $type       Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...)
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')"
+	 * @return array				List of extra fields
+	 *
+	 * @url     GET extrafields
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '')
+	{
+		$list = array();
+
+		if (!DolibarrApiAccess::$user->admin) {
+			throw new RestException(401, 'Only an admin user can get list of extrafields');
+		}
+
+		if ($type == 'thirdparty') $type = 'societe';
+		if ($type == 'contact') $type = 'socpeople';
+
+		$sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed";
+		$sql .= " FROM ".MAIN_DB_PREFIX."extrafields as t";
+		$sql .= " WHERE t.entity IN (".getEntity('extrafields').")";
+		if (!empty($type)) $sql .= " AND t.elementtype = '".$this->db->escape($type)."'";
+		// Add sql filters
+		if ($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).")";
+		}
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		$resql = $this->db->query($sql);
+		if ($resql)
+		{
+			if ($this->db->num_rows($resql))
+			{
+				while ($tab = $this->db->fetch_object($resql))
+				{
+					// New usage
+					$list[$tab->elementtype][$tab->name]['type'] = $tab->type;
+					$list[$tab->elementtype][$tab->name]['label'] = $tab->label;
+					$list[$tab->elementtype][$tab->name]['size'] = $tab->size;
+					$list[$tab->elementtype][$tab->name]['elementtype'] = $tab->elementtype;
+					$list[$tab->elementtype][$tab->name]['default'] = $tab->fielddefault;
+					$list[$tab->elementtype][$tab->name]['computed'] = $tab->fieldcomputed;
+					$list[$tab->elementtype][$tab->name]['unique'] = $tab->fieldunique;
+					$list[$tab->elementtype][$tab->name]['required'] = $tab->fieldrequired;
+					$list[$tab->elementtype][$tab->name]['param'] = ($tab->param ? unserialize($tab->param) : '');
+					$list[$tab->elementtype][$tab->name]['pos'] = $tab->pos;
+					$list[$tab->elementtype][$tab->name]['alwayseditable'] = $tab->alwayseditable;
+					$list[$tab->elementtype][$tab->name]['perms'] = $tab->perms;
+					$list[$tab->elementtype][$tab->name]['list'] = $tab->list;
+				}
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror());
+		}
+
+		if (!count($list))
+		{
+			throw new RestException(404, 'No extrafield found');
+		}
+
+		return $list;
+	}
+
+
+	/**
+	 * Get the list of towns.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param string    $zipcode    To filter on zipcode
+	 * @param string    $town       To filter on city name
+	 * @param int       $active     Payment term is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array				List of towns
+	 *
+	 * @url     GET dictionary/towns
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		$sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_ziptown as t";
+		$sql .= " AND t.active = ".$active;
+		if ($zipcode) $sql .= " AND t.zip LIKE '%".$this->db->escape($zipcode)."%'";
+		if ($town)    $sql .= " AND t.town LIKE '%".$this->db->escape($town)."%'";
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of payments terms.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number {@min 0}
+	 * @param int       $active     Payment term is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')"
+	 *
+	 * @url     GET dictionary/payment_terms
+	 *
+	 * @return array List of payment terms
+	 *
+	 * @throws RestException 400
+	 */
+	public function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) {
+			throw new RestException(401);
+		}
+
+		$sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t";
+		$sql .= " WHERE t.entity IN (".getEntity('c_payment_term').")";
+		$sql .= " AND t.active = ".$active;
+		// Add sql filters
+		if ($sqlfilters)
+		{
+			if (!DolibarrApi::_checkFilters($sqlfilters))
+			{
+				throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters);
+			}
+				$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
+			$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(400, $this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of shipping methods.
+	 *
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number {@min 0}
+	 * @param int       $active     Shipping methodsm is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')"
+	 *
+	 * @url     GET dictionary/shipping_methods
+	 *
+	 * @return array List of shipping methods
+	 *
+	 * @throws RestException 400
+	 */
+	public function getShippingModes($limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		$sql = "SELECT rowid as id, code, libelle as label, description, tracking, module";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t";
+		$sql .= " WHERE t.entity IN (".getEntity('c_shipment_mode').")";
+		$sql .= " AND t.active = ".$active;
+		// Add sql filters
+		if ($sqlfilters)
+		{
+			if (!DolibarrApi::_checkFilters($sqlfilters))
+			{
+				throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters);
+			}
+				$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
+			$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
+		}
+
+
+		//$sql.= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(400, $this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of measuring units.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param int       $active     Measuring unit is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array				List of measuring unit
+	 *
+	 * @url     GET dictionary/units
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfMeasuringUnits($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+		//TODO link with multicurrency module
+		$sql = "SELECT t.rowid, t.code, t.label,t.short_label, t.active, t.scale, t.unit_type";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_units as t";
+		$sql .= " WHERE t.active = ".$active;
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of measuring units: '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of social networks.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param int       $active     Social network is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array				List of social networks
+	 *
+	 * @url     GET dictionary/socialnetworks
+	 *
+	 * @throws RestException
+	 */
+	public function getListOfsocialNetworks($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		global $conf;
+
+		if (empty($conf->socialnetworks->enabled)) {
+			throw new RestException(400, 'API not available: this dictionary is not enabled by setup');
+		}
+
+		$list = array();
+		//TODO link with multicurrency module
+		$sql = "SELECT t.rowid, t.entity, t.code, t.label, t.url, t.icon, t.active";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_socialnetworks as t";
+		$sql .= " WHERE t.entity IN (".getEntity('c_socialnetworks').")";
+		$sql .= " AND t.active = ".$active;
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of social networks: '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	 /**
+	  * Get the list of tickets categories.
+	  *
+	  * @param string    $sortfield  Sort field
+	  * @param string    $sortorder  Sort order
+	  * @param int       $limit      Number of items per page
+	  * @param int       $page       Page number (starting from zero)
+	  * @param int       $active     Payment term is active or not {@min 0} {@max 1}
+	  * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	  * @return array				List of ticket categories
+	  *
+	  * @url     GET dictionary/ticket_categories
+	  *
+	  * @throws RestException
+	  */
+	public function getTicketsCategories($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		$sql = "SELECT rowid, code, pos,  label, use_default, description";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t";
+		$sql .= " WHERE t.active = ".$active;
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of ticket categories : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of tickets severity.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param int       $active     Payment term is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array				List of ticket severities
+	 *
+	 * @url     GET dictionary/ticket_severities
+	 *
+	 * @throws RestException
+	 */
+	public function getTicketsSeverities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		$sql = "SELECT rowid, code, pos,  label, use_default, color, description";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t";
+		$sql .= " WHERE t.active = ".$active;
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of ticket severities : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get the list of tickets types.
+	 *
+	 * @param string    $sortfield  Sort field
+	 * @param string    $sortorder  Sort order
+	 * @param int       $limit      Number of items per page
+	 * @param int       $page       Page number (starting from zero)
+	 * @param int       $active     Payment term is active or not {@min 0} {@max 1}
+	 * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
+	 * @return array				List of ticket types
+	 *
+	 * @url     GET dictionary/ticket_types
+	 *
+	 * @throws RestException
+	 */
+	public function getTicketsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
+	{
+		$list = array();
+
+		$sql = "SELECT rowid, code, pos,  label, use_default, description";
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t";
+		$sql .= " WHERE t.active = ".(int) $active;
+		// if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'";
+		// if ($module)    $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'";
+		// Add sql filters
+		if ($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).")";
+		}
+
+
+		$sql .= $this->db->order($sortfield, $sortorder);
+
+		if ($limit) {
+			if ($page < 0) {
+				$page = 0;
+			}
+			$offset = $limit * $page;
+
+			$sql .= $this->db->plimit($limit, $offset);
+		}
+
+		$result = $this->db->query($sql);
+
+		if ($result) {
+			$num = $this->db->num_rows($result);
+			$min = min($num, ($limit <= 0 ? $num : $limit));
+			for ($i = 0; $i < $min; $i++) {
+				$list[] = $this->db->fetch_object($result);
+			}
+		} else {
+			throw new RestException(503, 'Error when retrieving list of ticket types : '.$this->db->lasterror());
+		}
+
+		return $list;
+	}
+
+	/**
+	 * Get properties of company
+	 *
+	 * @url	GET /company
+	 *
+	 * @return  array|mixed Data without useless information
+	 *
+	 */
+	public function getCompany()
+	{
+		global $mysoc;
+
+		return $this->_cleanObjectDatas($mysoc);
+	}
+
+
+	/**
+	 * Get value of a setup variables
+	 *
+	 * Note that conf variables that stores security key or password hashes can't be loaded with API.
+	 *
+	 * @param	string			$constantname	Name of conf variable to get
+	 * @return  array|mixed 				Data without useless information
+	 *
+	 * @url     GET conf/{constantname}
+	 *
+	 * @throws RestException 403 Forbidden
+	 * @throws RestException 404 Error Bad or unknown value for constantname
+	 */
+	public function getConf($constantname)
+	{
+		global $conf;
+
+		if (!DolibarrApiAccess::$user->admin
+			&& (empty($conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ) || DolibarrApiAccess::$user->login != $conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ)) {
+			throw new RestException(403, 'Error API open to admin users only or to the users with logins defined into constant API_LOGINS_ALLOWED_FOR_CONST_READ');
+		}
+
+		if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) {
+			throw new RestException(404, 'Error Bad or unknown value for constantname');
+		}
+		if (isASecretKey($constantname)) {
+			throw new RestException(403, 'Forbidden. This parameter cant be read with APIs');
+		}
+
+		return $conf->global->$constantname;
+	}
+
+	/**
+	 * Do a test of integrity for files and setup.
+	 *
+	 * @param string	$target			Can be 'local' or 'default' or Url of the signatures file to use for the test. Must be reachable by the tested Dolibarr.
+	 * @return array					Result of file and setup integrity check
+	 *
+	 * @url     GET checkintegrity
+	 *
+	 * @throws RestException 404 Signature file not found
+	 * @throws RestException 500 Technical error
+	 * @throws RestException 503 Forbidden
+	 */
+	public function getCheckIntegrity($target)
+	{
+		global $langs, $conf;
+
+		if (!DolibarrApiAccess::$user->admin
+			&& (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK))
+		{
+			throw new RestException(503, 'Error API open to admin users only or to the users with logins defined into constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK');
+		}
+
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
+
+		$langs->load("admin");
+
+		$outexpectedchecksum = '';
+		$outcurrentchecksum = '';
+
+		// Modified or missing files
+		$file_list = array('missing' => array(), 'updated' => array());
+
+		// Local file to compare to
+		$xmlshortfile = GETPOST('xmlshortfile') ?GETPOST('xmlshortfile') : '/install/filelist-'.DOL_VERSION.'.xml';
+		$xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile;
+		// Remote file to compare to
+		$xmlremote = ($target == 'default' ? '' : $target);
+		if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL;
+		$param = 'MAIN_FILECHECK_URL_'.DOL_VERSION;
+		if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param;
+		if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml';
+
+		if ($target == 'local')
+		{
+			if (dol_is_file($xmlfile))
+			{
+				$xml = simplexml_load_file($xmlfile);
+			} else {
+				throw new RestException(500, $langs->trans('XmlNotFound').': '.$xmlfile);
+			}
+		} else {
+			$xmlarray = getURLContent($xmlremote);
+
+			// Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...)
+			if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404')
+			{
+				$xmlfile = $xmlarray['content'];
+				//print "xmlfilestart".$xmlfile."endxmlfile";
+				$xml = simplexml_load_string($xmlfile);
+			} else {
+				$errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg'];
+				throw new RestException(500, $errormsg);
+			}
+		}
+
+
+
+		if ($xml)
+		{
+			$checksumconcat = array();
+			$file_list = array();
+			$out = '';
+
+			// Forced constants
+			if (is_object($xml->dolibarr_constants[0]))
+			{
+				$out .= load_fiche_titre($langs->trans("ForcedConstants"));
+
+				$out .= '<div class="div-table-responsive-no-min">';
+				$out .= '<table class="noborder">';
+				$out .= '<tr class="liste_titre">';
+				$out .= '<td>#</td>';
+				$out .= '<td>'.$langs->trans("Constant").'</td>';
+				$out .= '<td class="center">'.$langs->trans("ExpectedValue").'</td>';
+				$out .= '<td class="center">'.$langs->trans("Value").'</td>';
+				$out .= '</tr>'."\n";
+
+				$i = 0;
+				foreach ($xml->dolibarr_constants[0]->constant as $constant)    // $constant is a simpleXMLElement
+				{
+					$constname = $constant['name'];
+					$constvalue = (string) $constant;
+					$constvalue = (empty($constvalue) ? '0' : $constvalue);
+					// Value found
+					$value = '';
+					if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname;
+					$valueforchecksum = (empty($value) ? '0' : $value);
+
+					$checksumconcat[] = $valueforchecksum;
+
+					$i++;
+					$out .= '<tr class="oddeven">';
+					$out .= '<td>'.$i.'</td>'."\n";
+					$out .= '<td>'.$constname.'</td>'."\n";
+					$out .= '<td class="center">'.$constvalue.'</td>'."\n";
+					$out .= '<td class="center">'.$valueforchecksum.'</td>'."\n";
+					$out .= "</tr>\n";
+				}
+
+				if ($i == 0)
+				{
+					$out .= '<tr class="oddeven"><td colspan="4" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
+				}
+				$out .= '</table>';
+				$out .= '</div>';
+
+				$out .= '<br>';
+			}
+
+			// Scan htdocs
+			if (is_object($xml->dolibarr_htdocs_dir[0]))
+			{
+				//var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit;
+				$includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']);
+
+				// Defined qualified files (must be same than into generate_filelist_xml.php)
+				$regextoinclude = '\.(php|php3|php4|php5|phtml|phps|phar|inc|css|scss|html|xml|js|json|tpl|jpg|jpeg|png|gif|ico|sql|lang|txt|yml|bak|md|mp3|mp4|wav|mkv|z|gz|zip|rar|tar|less|svg|eot|woff|woff2|ttf|manifest)$';
+				$regextoexclude = '('.($includecustom ? '' : 'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs
+				$scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude);
+
+				// Fill file_list with files in signature, new files, modified files
+				$ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list
+				// Complete with list of new files
+				foreach ($scanfiles as $keyfile => $valfile)
+				{
+					$tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']);
+					if (!in_array($tmprelativefilename, $file_list['insignature']))
+					{
+						$md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file
+						$file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile);
+					}
+				}
+
+				// Files missings
+				$out .= load_fiche_titre($langs->trans("FilesMissing"));
+
+				$out .= '<div class="div-table-responsive-no-min">';
+				$out .= '<table class="noborder">';
+				$out .= '<tr class="liste_titre">';
+				$out .= '<td>#</td>';
+				$out .= '<td>'.$langs->trans("Filename").'</td>';
+				$out .= '<td class="center">'.$langs->trans("ExpectedChecksum").'</td>';
+				$out .= '</tr>'."\n";
+				$tmpfilelist = dol_sort_array($file_list['missing'], 'filename');
+				if (is_array($tmpfilelist) && count($tmpfilelist))
+				{
+					$i = 0;
+					foreach ($tmpfilelist as $file)
+					{
+						$i++;
+						$out .= '<tr class="oddeven">';
+						$out .= '<td>'.$i.'</td>'."\n";
+						$out .= '<td>'.$file['filename'].'</td>'."\n";
+						$out .= '<td class="center">'.$file['expectedmd5'].'</td>'."\n";
+						$out .= "</tr>\n";
+					}
+				} else {
+					$out .= '<tr class="oddeven"><td colspan="3" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
+				}
+				$out .= '</table>';
+				$out .= '</div>';
+
+				$out .= '<br>';
+
+				// Files modified
+				$out .= load_fiche_titre($langs->trans("FilesModified"));
+
+				$totalsize = 0;
+				$out .= '<div class="div-table-responsive-no-min">';
+				$out .= '<table class="noborder">';
+				$out .= '<tr class="liste_titre">';
+				$out .= '<td>#</td>';
+				$out .= '<td>'.$langs->trans("Filename").'</td>';
+				$out .= '<td class="center">'.$langs->trans("ExpectedChecksum").'</td>';
+				$out .= '<td class="center">'.$langs->trans("CurrentChecksum").'</td>';
+				$out .= '<td class="right">'.$langs->trans("Size").'</td>';
+				$out .= '<td class="right">'.$langs->trans("DateModification").'</td>';
+				$out .= '</tr>'."\n";
+				$tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename');
+				if (is_array($tmpfilelist2) && count($tmpfilelist2))
+				{
+					$i = 0;
+					foreach ($tmpfilelist2 as $file)
+					{
+						$i++;
+						$out .= '<tr class="oddeven">';
+						$out .= '<td>'.$i.'</td>'."\n";
+						$out .= '<td>'.$file['filename'].'</td>'."\n";
+						$out .= '<td class="center">'.$file['expectedmd5'].'</td>'."\n";
+						$out .= '<td class="center">'.$file['md5'].'</td>'."\n";
+						$size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']);
+						$totalsize += $size;
+						$out .= '<td class="right">'.dol_print_size($size).'</td>'."\n";
+						$out .= '<td class="right">'.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'</td>'."\n";
+						$out .= "</tr>\n";
+					}
+					$out .= '<tr class="liste_total">';
+					$out .= '<td></td>'."\n";
+					$out .= '<td>'.$langs->trans("Total").'</td>'."\n";
+					$out .= '<td align="center"></td>'."\n";
+					$out .= '<td align="center"></td>'."\n";
+					$out .= '<td class="right">'.dol_print_size($totalsize).'</td>'."\n";
+					$out .= '<td class="right"></td>'."\n";
+					$out .= "</tr>\n";
+				} else {
+					$out .= '<tr class="oddeven"><td colspan="5" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
+				}
+				$out .= '</table>';
+				$out .= '</div>';
+
+				$out .= '<br>';
+
+				// Files added
+				$out .= load_fiche_titre($langs->trans("FilesAdded"));
+
+				$totalsize = 0;
+				$out .= '<div class="div-table-responsive-no-min">';
+				$out .= '<table class="noborder">';
+				$out .= '<tr class="liste_titre">';
+				$out .= '<td>#</td>';
+				$out .= '<td>'.$langs->trans("Filename").'</td>';
+				$out .= '<td class="center">'.$langs->trans("ExpectedChecksum").'</td>';
+				$out .= '<td class="center">'.$langs->trans("CurrentChecksum").'</td>';
+				$out .= '<td class="right">'.$langs->trans("Size").'</td>';
+				$out .= '<td class="right">'.$langs->trans("DateModification").'</td>';
+				$out .= '</tr>'."\n";
+				$tmpfilelist3 = dol_sort_array($file_list['added'], 'filename');
+				if (is_array($tmpfilelist3) && count($tmpfilelist3))
+				{
+					$i = 0;
+					foreach ($tmpfilelist3 as $file)
+					{
+						$i++;
+						$out .= '<tr class="oddeven">';
+						$out .= '<td>'.$i.'</td>'."\n";
+						$out .= '<td>'.$file['filename'].'</td>'."\n";
+						$out .= '<td class="center">'.$file['expectedmd5'].'</td>'."\n";
+						$out .= '<td class="center">'.$file['md5'].'</td>'."\n";
+						$size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']);
+						$totalsize += $size;
+						$out .= '<td class="right">'.dol_print_size($size).'</td>'."\n";
+						$out .= '<td class="right">'.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'</td>'."\n";
+						$out .= "</tr>\n";
+					}
+					$out .= '<tr class="liste_total">';
+					$out .= '<td></td>'."\n";
+					$out .= '<td>'.$langs->trans("Total").'</td>'."\n";
+					$out .= '<td align="center"></td>'."\n";
+					$out .= '<td align="center"></td>'."\n";
+					$out .= '<td class="right">'.dol_print_size($totalsize).'</td>'."\n";
+					$out .= '<td class="right"></td>'."\n";
+					$out .= "</tr>\n";
+				} else {
+					$out .= '<tr class="oddeven"><td colspan="5" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
+				}
+				$out .= '</table>';
+				$out .= '</div>';
+
+
+				// Show warning
+				if (empty($tmpfilelist) && empty($tmpfilelist2) && empty($tmpfilelist3))
+				{
+					//setEventMessages($langs->trans("FileIntegrityIsStrictlyConformedWithReference"), null, 'mesgs');
+				} else {
+					//setEventMessages($langs->trans("FileIntegritySomeFilesWereRemovedOrModified"), null, 'warnings');
+				}
+			} else {
+				throw new RestException(500, 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile);
+			}
+
+
+			// Scan scripts
+
+
+			asort($checksumconcat); // Sort list of checksum
+			//var_dump($checksumconcat);
+			$checksumget = md5(join(',', $checksumconcat));
+			$checksumtoget = trim((string) $xml->dolibarr_htdocs_dir_checksum);
+
+			$outexpectedchecksum = ($checksumtoget ? $checksumtoget : $langs->trans("Unknown"));
+			if ($checksumget == $checksumtoget)
+			{
+				if (count($file_list['added']))
+				{
+					$resultcode = 'warning';
+					$resultcomment = 'FileIntegrityIsOkButFilesWereAdded';
+					//$outcurrentchecksum =  $checksumget.' - <span class="'.$resultcode.'">'.$langs->trans("FileIntegrityIsOkButFilesWereAdded").'</span>';
+					$outcurrentchecksum = $checksumget;
+				} else {
+					$resultcode = 'ok';
+					$resultcomment = 'Success';
+					//$outcurrentchecksum = '<span class="'.$resultcode.'">'.$checksumget.'</span>';
+					$outcurrentchecksum = $checksumget;
+				}
+			} else {
+				$resultcode = 'error';
+				$resultcomment = 'Error';
+				//$outcurrentchecksum = '<span class="'.$resultcode.'">'.$checksumget.'</span>';
+				$outcurrentchecksum = $checksumget;
+			}
+		} else {
+			throw new RestException(404, 'No signature file known');
+		}
+
+		return array('resultcode'=>$resultcode, 'resultcomment'=>$resultcomment, 'expectedchecksum'=> $outexpectedchecksum, 'currentchecksum'=> $outcurrentchecksum, 'out'=>$out);
+	}
 }

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

@@ -111,21 +111,21 @@ print '</td>';
 if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines') {
 	print '<td class="linecoledit center">';
 	$coldisplay++;
-    if (($line->info_bits & 2) == 2 || !empty($disableedit)) {
-    } else {
-        print '<a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=editline&amp;lineid='.$line->id.'">'.img_edit().'</a>';
-    }
-    print '</td>';
-
-    print '<td class="linecoldelete center">';
-    $coldisplay++;
-    if (($line->fk_prev_id == null) && empty($disableremove)) {
-        //La suppression n'est autorisée que si il n'y a pas de ligne dans une précédente situation
-        print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=deleteline&amp;token='.newToken().'&amp;lineid='.$line->id.'">';
-        print img_delete();
-        print '</a>';
-    }
-    print '</td>';
+	if (($line->info_bits & 2) == 2 || !empty($disableedit)) {
+	} else {
+		print '<a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=editline&amp;lineid='.$line->id.'">'.img_edit().'</a>';
+	}
+	print '</td>';
+
+	print '<td class="linecoldelete center">';
+	$coldisplay++;
+	if (($line->fk_prev_id == null) && empty($disableremove)) {
+		//La suppression n'est autorisée que si il n'y a pas de ligne dans une précédente situation
+		print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=deleteline&amp;token='.newToken().'&amp;lineid='.$line->id.'">';
+		print img_delete();
+		print '</a>';
+	}
+	print '</td>';
 
 	if ($num > 1 && $conf->browser->layout != 'phone' && empty($disablemove)) {
 		print '<td class="linecolmove tdlineupdown center">';
@@ -146,14 +146,14 @@ if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines') {
 		$coldisplay++;
 	}
 } else {
-    print '<td colspan="3"></td>';
-    $coldisplay = $coldisplay + 3;
+	print '<td colspan="3"></td>';
+	$coldisplay = $coldisplay + 3;
 }
 
 if ($action == 'selectlines') {
-    print '<td class="linecolcheck center">';
-    print '<input type="checkbox" class="linecheckbox" name="line_checkbox['.($i + 1).']" value="'.$line->id.'" >';
-    print '</td>';
+	print '<td class="linecolcheck center">';
+	print '<input type="checkbox" class="linecheckbox" name="line_checkbox['.($i + 1).']" value="'.$line->id.'" >';
+	print '</td>';
 }
 
 print '</tr>';

+ 82 - 82
htdocs/categories/photos.php

@@ -44,8 +44,8 @@ $confirm = GETPOST('confirm');
 
 if ($id == '' && $label == '')
 {
-    dol_print_error('', 'Missing parameter id');
-    exit();
+	dol_print_error('', 'Missing parameter id');
+	exit();
 }
 
 // Security check
@@ -70,34 +70,34 @@ if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backwar
 
 if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sendit"] && !empty($conf->global->MAIN_UPLOAD_DOC))
 {
-    if ($object->id) {
-        $file = $_FILES['userfile'];
-        if (is_array($file['name']) && count($file['name']) > 0)
-        {
-            foreach ($file['name'] as $i => $name)
-            {
-                if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i]))
-                {
-                    setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles'));
-                    unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]);
-                }
-            }
-        }
-
-        if (!empty($file['tmp_name'])) {
-            $object->add_photo($upload_dir, $file);
-        }
-    }
+	if ($object->id) {
+		$file = $_FILES['userfile'];
+		if (is_array($file['name']) && count($file['name']) > 0)
+		{
+			foreach ($file['name'] as $i => $name)
+			{
+				if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i]))
+				{
+					setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles'));
+					unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]);
+				}
+			}
+		}
+
+		if (!empty($file['tmp_name'])) {
+			$object->add_photo($upload_dir, $file);
+		}
+	}
 }
 
 if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer)
 {
-    $object->delete_photo($upload_dir."/".$_GET["file"]);
+	$object->delete_photo($upload_dir."/".$_GET["file"]);
 }
 
 if ($action == 'addthumb' && $_GET["file"])
 {
-    $object->addThumbs($upload_dir."/".$_GET["file"]);
+	$object->addThumbs($upload_dir."/".$_GET["file"]);
 }
 
 
@@ -126,7 +126,7 @@ if ($object->id)
 	$ways = $object->print_all_ways(" &gt;&gt; ", '', 1);
 	foreach ($ways as $way)
 	{
-	    $morehtmlref .= $way."<br>\n";
+		$morehtmlref .= $way."<br>\n";
 	}
 	$morehtmlref .= '</div>';
 
@@ -137,7 +137,7 @@ if ($object->id)
 	*/
 	if ($action == 'delete')
 	{
-	    print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1);
+		print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1);
 	}
 
 	print '<br>';
@@ -159,7 +159,7 @@ if ($object->id)
 	print '</td></tr>';
 
 	print "</table>\n";
-    print '</div>';
+	print '</div>';
 
 	dol_fiche_end();
 
@@ -213,62 +213,62 @@ if ($object->id)
 
 		if (is_array($listofphoto) && count($listofphoto))
 		{
-    		print '<br>';
-            print '<table width="100%" valign="top" align="center">';
-
-    		foreach ($listofphoto as $key => $obj)
-    		{
-    			$nbphoto++;
-
-    			if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print '<tr align=center valign=middle border=1>';
-    			if ($nbbyrow) print '<td width="'.ceil(100 / $nbbyrow).'%" class="photo">';
-
-    			print '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart=category&entity='.$object->entity.'&file='.urlencode($pdir.$obj['photo']).'" alt="Taille origine" target="_blank">';
-
-    			// Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine
-    			if ($obj['photo_vignette'])
-    			{
-    				$filename = $obj['photo_vignette'];
-    			} else {
-    				$filename = $obj['photo'];
-    			}
-
-    			// Nom affiche
-    			$viewfilename = $obj['photo'];
-
-    			// Taille de l'image
-    			$object->get_image_size($dir.$filename);
-    			$imgWidth = ($object->imgWidth < $maxWidth) ? $object->imgWidth : $maxWidth;
-    			$imgHeight = ($object->imgHeight < $maxHeight) ? $object->imgHeight : $maxHeight;
-
-    			print '<img border="0" width="'.$imgWidth.'" height="'.$imgHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=category&entity='.$object->entity.'&file='.urlencode($pdir.$filename).'">';
-
-    			print '</a>';
-    			print '<br>'.$viewfilename;
-    			print '<br>';
-
-    			// On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
-    			if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight))
-    			{
-    				print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addthumb&amp;type='.$type.'&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
-    			}
-    			if ($user->rights->categorie->creer)
-    			{
-    				print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'&amp;type='.$type.'&amp;file='.urlencode($pdir.$viewfilename).'">';
-    				print img_delete().'</a>';
-    			}
-    			if ($nbbyrow) print '</td>';
-    			if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print '</tr>';
-    		}
-
-    		// Ferme tableau
-    		while ($nbphoto % $nbbyrow)
-    		{
-    			print '<td width="'.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
-    			$nbphoto++;
-    		}
-
-    		print '</table>';
+			print '<br>';
+			print '<table width="100%" valign="top" align="center">';
+
+			foreach ($listofphoto as $key => $obj)
+			{
+				$nbphoto++;
+
+				if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print '<tr align=center valign=middle border=1>';
+				if ($nbbyrow) print '<td width="'.ceil(100 / $nbbyrow).'%" class="photo">';
+
+				print '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart=category&entity='.$object->entity.'&file='.urlencode($pdir.$obj['photo']).'" alt="Taille origine" target="_blank">';
+
+				// Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine
+				if ($obj['photo_vignette'])
+				{
+					$filename = $obj['photo_vignette'];
+				} else {
+					$filename = $obj['photo'];
+				}
+
+				// Nom affiche
+				$viewfilename = $obj['photo'];
+
+				// Taille de l'image
+				$object->get_image_size($dir.$filename);
+				$imgWidth = ($object->imgWidth < $maxWidth) ? $object->imgWidth : $maxWidth;
+				$imgHeight = ($object->imgHeight < $maxHeight) ? $object->imgHeight : $maxHeight;
+
+				print '<img border="0" width="'.$imgWidth.'" height="'.$imgHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=category&entity='.$object->entity.'&file='.urlencode($pdir.$filename).'">';
+
+				print '</a>';
+				print '<br>'.$viewfilename;
+				print '<br>';
+
+				// On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
+				if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight))
+				{
+					print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=addthumb&amp;type='.$type.'&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
+				}
+				if ($user->rights->categorie->creer)
+				{
+					print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'&amp;type='.$type.'&amp;file='.urlencode($pdir.$viewfilename).'">';
+					print img_delete().'</a>';
+				}
+				if ($nbbyrow) print '</td>';
+				if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print '</tr>';
+			}
+
+			// Ferme tableau
+			while ($nbphoto % $nbbyrow)
+			{
+				print '<td width="'.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
+				$nbphoto++;
+			}
+
+			print '</table>';
 		}
 
 		if ($nbphoto < 1)
@@ -277,7 +277,7 @@ if ($object->id)
 		}
 	}
 } else {
-    print $langs->trans("ErrorUnknown");
+	print $langs->trans("ErrorUnknown");
 }
 
 // End of page

+ 74 - 74
htdocs/categories/traduction.php

@@ -83,43 +83,43 @@ $cancel != $langs->trans("Cancel") &&
 	$current_lang = $langs->getDefaultLang();
 
 	// check parameters
-    $forcelangprod = GETPOST('forcelangprod', 'alpha');
-    $libelle = GETPOST('libelle', 'alpha');
-    $desc = GETPOST('desc', 'restricthtml');
-
-    if (empty($forcelangprod)) {
-        $error++;
-        $object->errors[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Translation'));
-    }
-
-    if (!$error) {
-        if (empty($libelle)) {
-            $error++;
-            $object->errors[] = $langs->trans('Language_'.$forcelangprod).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label'));
-        }
-
-        if (!$error) {
-            // update de l'objet
-            if ($forcelangprod == $current_lang) {
-                $object->label = $libelle;
-                $object->description = dol_htmlcleanlastbr($desc);
-            } else {
-                $object->multilangs[$forcelangprod]["label"] = $libelle;
-                $object->multilangs[$forcelangprod]["description"] = dol_htmlcleanlastbr($desc);
-            }
-
-            // sauvegarde en base
-            $res = $object->setMultiLangs($user);
-            if ($res < 0) $error++;
-        }
-    }
-
-    if ($error) {
-        $action = 'add';
-        setEventMessages($object->error, $object->errors, 'errors');
-    } else {
-        $action = '';
-    }
+	$forcelangprod = GETPOST('forcelangprod', 'alpha');
+	$libelle = GETPOST('libelle', 'alpha');
+	$desc = GETPOST('desc', 'restricthtml');
+
+	if (empty($forcelangprod)) {
+		$error++;
+		$object->errors[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Translation'));
+	}
+
+	if (!$error) {
+		if (empty($libelle)) {
+			$error++;
+			$object->errors[] = $langs->trans('Language_'.$forcelangprod).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label'));
+		}
+
+		if (!$error) {
+			// update de l'objet
+			if ($forcelangprod == $current_lang) {
+				$object->label = $libelle;
+				$object->description = dol_htmlcleanlastbr($desc);
+			} else {
+				$object->multilangs[$forcelangprod]["label"] = $libelle;
+				$object->multilangs[$forcelangprod]["description"] = dol_htmlcleanlastbr($desc);
+			}
+
+			// sauvegarde en base
+			$res = $object->setMultiLangs($user);
+			if ($res < 0) $error++;
+		}
+	}
+
+	if ($error) {
+		$action = 'add';
+		setEventMessages($object->error, $object->errors, 'errors');
+	} else {
+		$action = '';
+	}
 }
 
 // Validation de l'edition
@@ -132,13 +132,13 @@ $cancel != $langs->trans("Cancel") &&
 
 	foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet
 	{
-        $libelle = GETPOST('libelle-'.$key, 'alpha');
-        $desc = GETPOST('desc-'.$key);
+		$libelle = GETPOST('libelle-'.$key, 'alpha');
+		$desc = GETPOST('desc-'.$key);
 
-        if (empty($libelle)) {
-            $error++;
-            $object->errors[] = $langs->trans('Language_'.$key).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label'));
-        }
+		if (empty($libelle)) {
+			$error++;
+			$object->errors[] = $langs->trans('Language_'.$key).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label'));
+		}
 
 		if ($key == $current_lang) {
 			$object->label       = $libelle;
@@ -149,17 +149,17 @@ $cancel != $langs->trans("Cancel") &&
 		}
 	}
 
-    if (!$error) {
-        $res = $object->setMultiLangs($user);
-        if ($res < 0)   $error++;
-    }
-
-    if ($error) {
-        $action = 'edit';
-        setEventMessages($object->error, $object->errors, 'errors');
-    } else {
-        $action = '';
-    }
+	if (!$error) {
+		$res = $object->setMultiLangs($user);
+		if ($res < 0)   $error++;
+	}
+
+	if ($error) {
+		$action = 'edit';
+		setEventMessages($object->error, $object->errors, 'errors');
+	} else {
+		$action = '';
+	}
 }
 
 
@@ -181,10 +181,10 @@ $head = categories_prepare_head($object, $type);
 $cnt_trans = 0;
 if (!empty($object->multilangs))
 {
-    foreach ($object->multilangs as $key => $value)
-    {
-        $cnt_trans++;
-    }
+	foreach ($object->multilangs as $key => $value)
+	{
+		$cnt_trans++;
+	}
 }
 
 dol_fiche_head($head, 'translation', $langs->trans($title), -1, 'category');
@@ -195,7 +195,7 @@ $object->ref = $object->label;
 $morehtmlref = '<br><div class="refidno"><a href="'.DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type.'">'.$langs->trans("Root").'</a> >> ';
 $ways = $object->print_all_ways(" &gt;&gt; ", '', 1);
 foreach ($ways as $way) {
-    $morehtmlref .= $way."<br>\n";
+	$morehtmlref .= $way."<br>\n";
 }
 $morehtmlref .= '</div>';
 
@@ -238,11 +238,11 @@ print "\n<div class=\"tabsAction\">\n";
 
 if ($action == '')
 {
-    if ($user->rights->produit->creer || $user->rights->service->creer)
-    {
-        print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=add&id='.$object->id.'&type='.$type.'">'.$langs->trans('Add').'</a>';
-        if ($cnt_trans > 0) print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&id='.$object->id.'&type='.$type.'">'.$langs->trans('Update').'</a>';
-    }
+	if ($user->rights->produit->creer || $user->rights->service->creer)
+	{
+		print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=add&id='.$object->id.'&type='.$type.'">'.$langs->trans('Add').'</a>';
+		if ($cnt_trans > 0) print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&id='.$object->id.'&type='.$type.'">'.$langs->trans('Update').'</a>';
+	}
 }
 
 print "\n</div>\n";
@@ -258,20 +258,20 @@ if ($action == 'edit')
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="vedit">';
 	print '<input type="hidden" name="id" value="'.$object->id.'">';
-    print '<input type="hidden" name="type" value="'.$type.'">';
+	print '<input type="hidden" name="type" value="'.$type.'">';
 
 	if (!empty($object->multilangs))
 	{
 		foreach ($object->multilangs as $key => $value)
 		{
-		    print "<br><b><u>".$langs->trans('Language_'.$key)." :</u></b><br>";
+			print "<br><b><u>".$langs->trans('Language_'.$key)." :</u></b><br>";
 			print '<table class="border centpercent">';
 
 			// Label
-            $libelle = (GETPOST('libelle-'.$key, 'alpha') ? GETPOST('libelle-'.$key, 'alpha') : $object->multilangs[$key]['label']);
+			$libelle = (GETPOST('libelle-'.$key, 'alpha') ? GETPOST('libelle-'.$key, 'alpha') : $object->multilangs[$key]['label']);
 			print '<tr><td class="titlefield fieldrequired">'.$langs->trans('Label').'</td><td><input name="libelle-'.$key.'" size="40" value="'.$libelle.'"></td></tr>';
 			// Desc
-            $desc = (GETPOST('desc-'.$key) ? GETPOST('desc-'.$key) : $object->multilangs[$key]['description']);
+			$desc = (GETPOST('desc-'.$key) ? GETPOST('desc-'.$key) : $object->multilangs[$key]['description']);
 			print '<tr><td class="tdtop">'.$langs->trans('Description').'</td><td>';
 			$doleditor = new DolEditor("desc-$key", $desc, '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%');
 			$doleditor->Create();
@@ -293,20 +293,20 @@ if ($action == 'edit')
 	print '</form>';
 } elseif ($action != 'add')
 {
-    if ($cnt_trans) print '<div class="underbanner clearboth"></div>';
+	if ($cnt_trans) print '<div class="underbanner clearboth"></div>';
 
-    if (!empty($object->multilangs))
+	if (!empty($object->multilangs))
 	{
 		foreach ($object->multilangs as $key => $value)
 		{
-		    $s = picto_from_langcode($key);
+			$s = picto_from_langcode($key);
 			print '<table class="border centpercent">';
 			print '<tr class="liste_titre"><td colspan="2">'.($s ? $s.' ' : '')." <b>".$langs->trans('Language_'.$key).":</b> ".'<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'&langtodelete='.$key.'&type='.$type.'">'.img_delete('', '').'</a></td></tr>';
 			print '<tr><td class="titlefield">'.$langs->trans('Label').'</td><td>'.$object->multilangs[$key]["label"].'</td></tr>';
 			print '<tr><td>'.$langs->trans('Description').'</td><td>'.$object->multilangs[$key]["description"].'</td></tr>';
 			if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION))
 			{
-                print '<tr><td>'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')</td><td>'.$object->multilangs[$key]["other"].'</td></tr>';
+				print '<tr><td>'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')</td><td>'.$object->multilangs[$key]["other"].'</td></tr>';
 			}
 			print '</table>';
 		}
@@ -329,11 +329,11 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service
 	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="vadd">';
 	print '<input type="hidden" name="id" value="'.$id.'">';
-    print '<input type="hidden" name="type" value="'.$type.'">';
+	print '<input type="hidden" name="type" value="'.$type.'">';
 
 	print '<table class="border centpercent">';
 	print '<tr><td class="titlefield fieldrequired">'.$langs->trans('Translation').'</td><td>';
-    print $formadmin->select_language(GETPOST('forcelangprod', 'alpha'), 'forcelangprod', 0, $object->multilangs);
+	print $formadmin->select_language(GETPOST('forcelangprod', 'alpha'), 'forcelangprod', 0, $object->multilangs);
 	print '</td></tr>';
 	print '<tr><td class="fieldrequired">'.$langs->trans('Label').'</td>';
 	print '<td><input name="libelle" class="minwidth200 maxwidth300" value="'.GETPOST('libelle', 'alpha').'"></td></tr>';

+ 337 - 337
htdocs/comm/card.php

@@ -138,12 +138,12 @@ if (empty($reshook))
 	}
 
 	// customer preferred shipping method
-    if ($action == 'setshippingmethod' && $user->rights->societe->creer)
-    {
-        $object->fetch($id);
-        $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int'));
-        if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
-    }
+	if ($action == 'setshippingmethod' && $user->rights->societe->creer)
+	{
+		$object->fetch($id);
+		$result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int'));
+		if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
+	}
 
 	// assujetissement a la TVA
 	if ($action == 'setassujtva' && $user->rights->societe->creer)
@@ -191,31 +191,31 @@ if (empty($reshook))
 	}
 
 	// Set sales representatives
-    if ($action == 'set_salesrepresentatives' && $user->rights->societe->creer)
+	if ($action == 'set_salesrepresentatives' && $user->rights->societe->creer)
 	{
 		$object->fetch($id);
 		$result = $object->setSalesRep(GETPOST('commercial', 'array'));
 	}
 
 	if ($action == 'update_extras') {
-        $object->fetch($id);
+		$object->fetch($id);
 
-        $object->oldcopy = dol_clone($object);
+		$object->oldcopy = dol_clone($object);
 
-        // Fill array 'array_options' with data from update form
-        $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
-        if ($ret < 0) $error++;
-        if (!$error)
-        {
-        	$result = $object->insertExtraFields('COMPANY_MODIFY');
+		// Fill array 'array_options' with data from update form
+		$ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
+		if ($ret < 0) $error++;
+		if (!$error)
+		{
+			$result = $object->insertExtraFields('COMPANY_MODIFY');
 			if ($result < 0)
 			{
 				setEventMessages($object->error, $object->errors, 'errors');
 				$error++;
 			}
-        }
-        if ($error) $action = 'edit_extras';
-    }
+		}
+		if ($error) $action = 'edit_extras';
+	}
 }
 
 
@@ -249,11 +249,11 @@ if ($object->id > 0)
 
 	$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-    dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
+	dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
 
 	print '<div class="fichecenter"><div class="fichehalfleft">';
 
-    print '<div class="underbanner clearboth"></div>';
+	print '<div class="underbanner clearboth"></div>';
 	print '<table class="border centpercent tableforfield">';
 
 	// Prospect/Customer
@@ -262,16 +262,16 @@ if ($object->id > 0)
 	print '</td></tr>';
 
 	// Prefix
-    if (!empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
-    {
-        print '<tr><td>'.$langs->trans("Prefix").'</td><td>';
-	    print ($object->prefix_comm ? $object->prefix_comm : '&nbsp;');
-	    print '</td></tr>';
-    }
+	if (!empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
+	{
+		print '<tr><td>'.$langs->trans("Prefix").'</td><td>';
+		print ($object->prefix_comm ? $object->prefix_comm : '&nbsp;');
+		print '</td></tr>';
+	}
 
 	if ($object->client)
 	{
-        $langs->load("compta");
+		$langs->load("compta");
 
 		print '<tr><td>';
 		print $langs->trans('CustomerCode').'</td><td>';
@@ -386,64 +386,64 @@ if ($object->id > 0)
 	// Relative discounts (Discounts-Drawbacks-Rebates)
 	if ($isCustomer)
 	{
-    	print '<tr><td class="nowrap">';
-    	print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
-    	print $langs->trans("CustomerRelativeDiscountShort");
-    	print '<td><td class="right">';
-    	if ($user->rights->societe->creer && !$user->socid > 0)
-    	{
-    		print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$object->id.'">'.img_edit($langs->trans("Modify")).'</a>';
-    	}
-    	print '</td></tr></table>';
-    	print '</td><td>'.($object->remise_percent ? '<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$object->id.'">'.$object->remise_percent.'%</a>' : '').'</td>';
-    	print '</tr>';
-
-    	// Absolute discounts (Discounts-Drawbacks-Rebates)
-    	print '<tr><td class="nowrap">';
-    	print '<table width="100%" class="nobordernopadding">';
-    	print '<tr><td class="nowrap">';
-    	print $langs->trans("CustomerAbsoluteDiscountShort");
-    	print '<td><td class="right">';
-    	if ($user->rights->societe->creer && !$user->socid > 0)
-    	{
-    		print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.img_edit($langs->trans("Modify")).'</a>';
-    	}
-    	print '</td></tr></table>';
-    	print '</td>';
-    	print '<td>';
-    	$amount_discount = $object->getAvailableDiscounts();
-    	if ($amount_discount < 0) dol_print_error($db, $object->error);
-    	if ($amount_discount > 0) print '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).'</a>';
-    	//else print $langs->trans("DiscountNone");
-    	print '</td>';
-    	print '</tr>';
+		print '<tr><td class="nowrap">';
+		print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
+		print $langs->trans("CustomerRelativeDiscountShort");
+		print '<td><td class="right">';
+		if ($user->rights->societe->creer && !$user->socid > 0)
+		{
+			print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$object->id.'">'.img_edit($langs->trans("Modify")).'</a>';
+		}
+		print '</td></tr></table>';
+		print '</td><td>'.($object->remise_percent ? '<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$object->id.'">'.$object->remise_percent.'%</a>' : '').'</td>';
+		print '</tr>';
+
+		// Absolute discounts (Discounts-Drawbacks-Rebates)
+		print '<tr><td class="nowrap">';
+		print '<table width="100%" class="nobordernopadding">';
+		print '<tr><td class="nowrap">';
+		print $langs->trans("CustomerAbsoluteDiscountShort");
+		print '<td><td class="right">';
+		if ($user->rights->societe->creer && !$user->socid > 0)
+		{
+			print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.img_edit($langs->trans("Modify")).'</a>';
+		}
+		print '</td></tr></table>';
+		print '</td>';
+		print '<td>';
+		$amount_discount = $object->getAvailableDiscounts();
+		if ($amount_discount < 0) dol_print_error($db, $object->error);
+		if ($amount_discount > 0) print '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).'</a>';
+		//else print $langs->trans("DiscountNone");
+		print '</td>';
+		print '</tr>';
 	}
 
 	// Max outstanding bill
 	if ($object->client)
 	{
-	    print '<tr class="nowrap">';
-	    print '<td>';
-	    print $form->editfieldkey("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer);
-	    print '</td><td>';
-	    $limit_field_type = (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount';
-	    print $form->editfieldval("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer, $limit_field_type, ($object->outstanding_limit != '' ? price($object->outstanding_limit) : ''));
-	    print '</td>';
-	    print '</tr>';
+		print '<tr class="nowrap">';
+		print '<td>';
+		print $form->editfieldkey("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer);
+		print '</td><td>';
+		$limit_field_type = (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount';
+		print $form->editfieldval("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer, $limit_field_type, ($object->outstanding_limit != '' ? price($object->outstanding_limit) : ''));
+		print '</td>';
+		print '</tr>';
 	}
 
 	if ($object->client)
 	{
 		if (!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT))
 		{
-		    print '<!-- Minimim amount for orders -->'."\n";
-		    print '<tr class="nowrap">';
-		    print '<td>';
-		    print $form->editfieldkey("OrderMinAmount", 'order_min_amount', $object->order_min_amount, $object, $user->rights->societe->creer);
-		    print '</td><td>';
-		    print $form->editfieldval("OrderMinAmount", 'order_min_amount', $object->order_min_amount, $object, $user->rights->societe->creer, $limit_field_type, ($object->order_min_amount != '' ? price($object->order_min_amount) : ''));
-		    print '</td>';
-		    print '</tr>';
+			print '<!-- Minimim amount for orders -->'."\n";
+			print '<tr class="nowrap">';
+			print '<td>';
+			print $form->editfieldkey("OrderMinAmount", 'order_min_amount', $object->order_min_amount, $object, $user->rights->societe->creer);
+			print '</td><td>';
+			print $form->editfieldval("OrderMinAmount", 'order_min_amount', $object->order_min_amount, $object, $user->rights->societe->creer, $limit_field_type, ($object->order_min_amount != '' ? price($object->order_min_amount) : ''));
+			print '</td>';
+			print '</tr>';
 		}
 	}
 
@@ -468,24 +468,24 @@ if ($object->id > 0)
 		print '</tr>';
 	}
 
-    // Preferred shipping Method
-    if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) {
-        print '<tr><td class="nowrap">';
-        print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
-        print $langs->trans('SendingMethod');
-        print '<td>';
-        if (($action != 'editshipping') && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editshipping&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
-        print '</tr></table>';
-        print '</td><td>';
-        if ($action == 'editshipping')
-        {
-            $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1);
-        } else {
-            $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'none');
-        }
-        print "</td>";
-        print '</tr>';
-    }
+	// Preferred shipping Method
+	if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) {
+		print '<tr><td class="nowrap">';
+		print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
+		print $langs->trans('SendingMethod');
+		print '<td>';
+		if (($action != 'editshipping') && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editshipping&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
+		print '</tr></table>';
+		print '</td><td>';
+		if ($action == 'editshipping')
+		{
+			$form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1);
+		} else {
+			$form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'none');
+		}
+		print "</td>";
+		print '</tr>';
+	}
 
 	// Categories
 	if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) {
@@ -500,70 +500,70 @@ if ($object->id > 0)
 	$parameters = array('socid'=>$object->id);
 	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
-    // Sales representative
+	// Sales representative
 	include DOL_DOCUMENT_ROOT.'/societe/tpl/linesalesrepresentative.tpl.php';
 
-    // Module Adherent
-    if (!empty($conf->adherent->enabled))
-    {
-        $langs->load("members");
-        $langs->load("users");
-
-        print '<tr><td class="titlefield">'.$langs->trans("LinkedToDolibarrMember").'</td>';
-        print '<td>';
-        $adh = new Adherent($db);
-        $result = $adh->fetch('', '', $object->id);
-        if ($result > 0)
-        {
-            $adh->ref = $adh->getFullName($langs);
-            print $adh->getNomUrl(1);
-        } else {
-            print '<span class="opacitymedium">'.$langs->trans("ThirdpartyNotLinkedToMember").'</span>';
-        }
-        print '</td>';
-        print "</tr>\n";
-    }
+	// Module Adherent
+	if (!empty($conf->adherent->enabled))
+	{
+		$langs->load("members");
+		$langs->load("users");
+
+		print '<tr><td class="titlefield">'.$langs->trans("LinkedToDolibarrMember").'</td>';
+		print '<td>';
+		$adh = new Adherent($db);
+		$result = $adh->fetch('', '', $object->id);
+		if ($result > 0)
+		{
+			$adh->ref = $adh->getFullName($langs);
+			print $adh->getNomUrl(1);
+		} else {
+			print '<span class="opacitymedium">'.$langs->trans("ThirdpartyNotLinkedToMember").'</span>';
+		}
+		print '</td>';
+		print "</tr>\n";
+	}
 
 	print "</table>";
 
 	// Prospection level and status
 	if ($object->client == 2 || $object->client == 3)
 	{
-    	print '<br>';
-
-    	print '<div class="underbanner clearboth"></div>';
-    	print '<table class="border centpercent tableforfield">';
-
-	    // Level of prospection
-	    print '<tr><td class="titlefield nowrap">';
-	    print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
-	    print $langs->trans('ProspectLevel');
-	    print '<td>';
-	    if ($action != 'editlevel' && $user->rights->societe->creer) print '<td class="right"><a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=editlevel&amp;socid='.$object->id.'">'.img_edit($langs->trans('Modify'), 1).'</a></td>';
-	    print '</tr></table>';
-	    print '</td><td>';
-	    if ($action == 'editlevel')
-	    {
-	        $formcompany->form_prospect_level($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->fk_prospectlevel, 'prospect_level_id', 1);
-	    } else {
-	        print $object->getLibProspLevel();
-	    }
-        print "</td>";
-        print '</tr>';
-
-        // Status of prospection
-        $object->loadCacheOfProspStatus();
-        print '<tr><td>'.$langs->trans("StatusProsp").'</td><td>'.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']);
-        print ' &nbsp; &nbsp; ';
-        print '<div class="floatright">';
-        foreach ($object->cacheprospectstatus as $key => $val)
-        {
+		print '<br>';
+
+		print '<div class="underbanner clearboth"></div>';
+		print '<table class="border centpercent tableforfield">';
+
+		// Level of prospection
+		print '<tr><td class="titlefield nowrap">';
+		print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
+		print $langs->trans('ProspectLevel');
+		print '<td>';
+		if ($action != 'editlevel' && $user->rights->societe->creer) print '<td class="right"><a class="editfielda reposition" href="'.$_SERVER["PHP_SELF"].'?action=editlevel&amp;socid='.$object->id.'">'.img_edit($langs->trans('Modify'), 1).'</a></td>';
+		print '</tr></table>';
+		print '</td><td>';
+		if ($action == 'editlevel')
+		{
+			$formcompany->form_prospect_level($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->fk_prospectlevel, 'prospect_level_id', 1);
+		} else {
+			print $object->getLibProspLevel();
+		}
+		print "</td>";
+		print '</tr>';
+
+		// Status of prospection
+		$object->loadCacheOfProspStatus();
+		print '<tr><td>'.$langs->trans("StatusProsp").'</td><td>'.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']);
+		print ' &nbsp; &nbsp; ';
+		print '<div class="floatright">';
+		foreach ($object->cacheprospectstatus as $key => $val)
+		{
 			$titlealt = 'default';
 			if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label'];
 			if ($object->stcomm_id != $val['id']) print '<a class="pictosubstatus reposition" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'&stcomm='.$val['code'].'&action=setstcomm&token='.newToken().'">'.img_action($titlealt, $val['code'], $val['picto']).'</a>';
 		}
-        print '</div></td></tr>';
-        print "</table>";
+		print '</div></td></tr>';
+		print "</table>";
 	}
 
 	print '</div><div class="fichehalfright"><div class="ficheaddleft">';
@@ -670,9 +670,9 @@ if ($object->id > 0)
 		$langs->load("propal");
 
 		$sql = "SELECT s.nom, s.rowid, p.rowid as propalid, p.fk_statut, p.total_ht";
-        $sql .= ", p.tva as total_tva";
-        $sql .= ", p.total as total_ttc";
-        $sql .= ", p.ref, p.ref_client, p.remise";
+		$sql .= ", p.tva as total_tva";
+		$sql .= ", p.total as total_ttc";
+		$sql .= ", p.ref, p.ref_client, p.remise";
 		$sql .= ", p.datep as dp, p.fin_validite as date_limit";
 		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c";
 		$sql .= " WHERE p.fk_soc = s.rowid AND p.fk_statut = c.id";
@@ -686,17 +686,17 @@ if ($object->id > 0)
 			$propal_static = new Propal($db);
 
 			$num = $db->num_rows($resql);
-            if ($num > 0)
-            {
-            	print '<div class="div-table-responsive-no-min">';
-            	print '<table class="noborder centpercent lastrecordtable">';
-
-                print '<tr class="liste_titre">';
-    			print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastPropals", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/comm/propal/list.php?socid='.$object->id.'">'.$langs->trans("AllPropals").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>';
-                print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/comm/propal/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
-    			print '</tr></table></td>';
-    			print '</tr>';
-            }
+			if ($num > 0)
+			{
+				print '<div class="div-table-responsive-no-min">';
+				print '<table class="noborder centpercent lastrecordtable">';
+
+				print '<tr class="liste_titre">';
+				print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastPropals", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/comm/propal/list.php?socid='.$object->id.'">'.$langs->trans("AllPropals").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>';
+				print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/comm/propal/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
+				print '</tr></table></td>';
+				print '</tr>';
+			}
 
 			$i = 0;
 			while ($i < $num && $i < $MAXLIST)
@@ -704,17 +704,17 @@ if ($object->id > 0)
 				$objp = $db->fetch_object($resql);
 
 				print '<tr class="oddeven">';
-                print '<td class="nowrap">';
-                $propal_static->id = $objp->propalid;
-                $propal_static->ref = $objp->ref;
-                $propal_static->ref_client = $objp->ref_client;
-                $propal_static->total_ht = $objp->total_ht;
-                $propal_static->total_tva = $objp->total_tva;
-                $propal_static->total_ttc = $objp->total_ttc;
-                print $propal_static->getNomUrl(1);
-                if (($db->jdate($objp->date_limit) < ($now - $conf->propal->cloture->warning_delay)) && $objp->fk_statut == $propal_static::STATUS_VALIDATED) {
-                    print " ".img_warning();
-                }
+				print '<td class="nowrap">';
+				$propal_static->id = $objp->propalid;
+				$propal_static->ref = $objp->ref;
+				$propal_static->ref_client = $objp->ref_client;
+				$propal_static->total_ht = $objp->total_ht;
+				$propal_static->total_tva = $objp->total_tva;
+				$propal_static->total_ttc = $objp->total_ttc;
+				print $propal_static->getNomUrl(1);
+				if (($db->jdate($objp->date_limit) < ($now - $conf->propal->cloture->warning_delay)) && $objp->fk_statut == $propal_static::STATUS_VALIDATED) {
+					print " ".img_warning();
+				}
 				print '</td><td class="right" width="80px">'.dol_print_date($db->jdate($objp->dp), 'day')."</td>\n";
 				print '<td class="right" style="min-width: 60px">'.price($objp->total_ht).'</td>';
 				print '<td class="right" style="min-width: 60px" class="nowrap">'.$propal_static->LibStatut($objp->fk_statut, 5).'</td></tr>';
@@ -737,12 +737,12 @@ if ($object->id > 0)
 	 */
 	if (!empty($conf->commande->enabled) && $user->rights->commande->lire)
 	{
-        $sql = "SELECT s.nom, s.rowid";
-        $sql .= ", c.rowid as cid, c.total_ht";
-        $sql .= ", c.tva as total_tva";
-        $sql .= ", c.total_ttc";
-        $sql .= ", c.ref, c.ref_client, c.fk_statut, c.facture";
-        $sql .= ", c.date_commande as dc";
+		$sql = "SELECT s.nom, s.rowid";
+		$sql .= ", c.rowid as cid, c.total_ht";
+		$sql .= ", c.tva as total_tva";
+		$sql .= ", c.total_ttc";
+		$sql .= ", c.ref, c.ref_client, c.fk_statut, c.facture";
+		$sql .= ", c.date_commande as dc";
 		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
 		$sql .= " WHERE c.fk_soc = s.rowid ";
 		$sql .= " AND s.rowid = ".$object->id;
@@ -795,8 +795,8 @@ if ($object->id > 0)
 				$commande_static->billed = $objp->billed;
 
 				print '<tr class="oddeven">';
-                print '<td class="nowrap">';
-                print $commande_static->getNomUrl(1);
+				print '<td class="nowrap">';
+				print $commande_static->getNomUrl(1);
 				print '</td><td class="right" width="80px">'.dol_print_date($db->jdate($objp->dc), 'day')."</td>\n";
 				print '<td class="right" style="min-width: 60px">'.price($objp->total_ht).'</td>';
 				print '<td class="right" style="min-width: 60px" class="nowrap">'.$commande_static->LibStatut($objp->fk_statut, $objp->facture, 5).'</td></tr>';
@@ -814,78 +814,78 @@ if ($object->id > 0)
 		}
 	}
 
-    /*
+	/*
      *   Latest shipments
      */
-    if (!empty($conf->expedition->enabled) && $user->rights->expedition->lire)
-    {
-        $sql = 'SELECT e.rowid as id';
-        $sql .= ', e.ref';
-        $sql .= ', e.date_creation';
-        $sql .= ', e.fk_statut as statut';
-        $sql .= ', s.nom';
-        $sql .= ', s.rowid as socid';
-        $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."expedition as e";
-        $sql .= " WHERE e.fk_soc = s.rowid AND s.rowid = ".$object->id;
-        $sql .= " AND e.entity IN (".getEntity('expedition').")";
-        $sql .= ' GROUP BY e.rowid';
-        $sql .= ', e.ref';
-        $sql .= ', e.date_creation';
-        $sql .= ', e.fk_statut';
-        $sql .= ', s.nom';
-        $sql .= ', s.rowid';
-        $sql .= " ORDER BY e.date_creation DESC";
-
-        $resql = $db->query($sql);
-        if ($resql)
-        {
-        	$sendingstatic = new Expedition($db);
-
-        	$num = $db->num_rows($resql);
-            if ($num > 0) {
-            	print '<div class="div-table-responsive-no-min">';
-            	print '<table class="noborder centpercent lastrecordtable">';
-
-                print '<tr class="liste_titre">';
-                print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastSendings", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/expedition/list.php?socid='.$object->id.'">'.$langs->trans("AllSendings").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>';
-                print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/expedition/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
-                print '</tr></table></td>';
-                print '</tr>';
-            }
-
-            $i = 0;
-            while ($i < $num && $i < $MAXLIST)
-            {
-                $objp = $db->fetch_object($resql);
-
-                $sendingstatic->id = $objp->id;
-                $sendingstatic->ref = $objp->ref;
-
-                print '<tr class="oddeven">';
-                print '<td class="nowrap">';
-                print $sendingstatic->getNomUrl(1);
-                print '</td>';
-                if ($objp->date_creation > 0) {
-                    print '<td class="right" width="80px">'.dol_print_date($db->jdate($objp->date_creation), 'day').'</td>';
-                } else {
-                    print '<td class="right"><b>!!!</b></td>';
-                }
-
-                print '<td class="nowrap right" width="100" >'.$sendingstatic->LibStatut($objp->statut, 5).'</td>';
-                print "</tr>\n";
-                $i++;
-            }
-            $db->free($resql);
-
-            if ($num > 0)
-            {
-                print "</table>";
-                print '</div>';
-            }
-        } else {
-            dol_print_error($db);
-        }
-    }
+	if (!empty($conf->expedition->enabled) && $user->rights->expedition->lire)
+	{
+		$sql = 'SELECT e.rowid as id';
+		$sql .= ', e.ref';
+		$sql .= ', e.date_creation';
+		$sql .= ', e.fk_statut as statut';
+		$sql .= ', s.nom';
+		$sql .= ', s.rowid as socid';
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."expedition as e";
+		$sql .= " WHERE e.fk_soc = s.rowid AND s.rowid = ".$object->id;
+		$sql .= " AND e.entity IN (".getEntity('expedition').")";
+		$sql .= ' GROUP BY e.rowid';
+		$sql .= ', e.ref';
+		$sql .= ', e.date_creation';
+		$sql .= ', e.fk_statut';
+		$sql .= ', s.nom';
+		$sql .= ', s.rowid';
+		$sql .= " ORDER BY e.date_creation DESC";
+
+		$resql = $db->query($sql);
+		if ($resql)
+		{
+			$sendingstatic = new Expedition($db);
+
+			$num = $db->num_rows($resql);
+			if ($num > 0) {
+				print '<div class="div-table-responsive-no-min">';
+				print '<table class="noborder centpercent lastrecordtable">';
+
+				print '<tr class="liste_titre">';
+				print '<td colspan="4"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastSendings", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/expedition/list.php?socid='.$object->id.'">'.$langs->trans("AllSendings").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>';
+				print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/expedition/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
+				print '</tr></table></td>';
+				print '</tr>';
+			}
+
+			$i = 0;
+			while ($i < $num && $i < $MAXLIST)
+			{
+				$objp = $db->fetch_object($resql);
+
+				$sendingstatic->id = $objp->id;
+				$sendingstatic->ref = $objp->ref;
+
+				print '<tr class="oddeven">';
+				print '<td class="nowrap">';
+				print $sendingstatic->getNomUrl(1);
+				print '</td>';
+				if ($objp->date_creation > 0) {
+					print '<td class="right" width="80px">'.dol_print_date($db->jdate($objp->date_creation), 'day').'</td>';
+				} else {
+					print '<td class="right"><b>!!!</b></td>';
+				}
+
+				print '<td class="nowrap right" width="100" >'.$sendingstatic->LibStatut($objp->statut, 5).'</td>';
+				print "</tr>\n";
+				$i++;
+			}
+			$db->free($resql);
+
+			if ($num > 0)
+			{
+				print "</table>";
+				print '</div>';
+			}
+		} else {
+			dol_print_error($db);
+		}
+	}
 
 	/*
 	 * Latest contracts
@@ -910,7 +910,7 @@ if ($object->id > 0)
 				print '<div class="div-table-responsive-no-min">';
 				print '<table class="noborder centpercent lastrecordtable">';
 
-			    print '<tr class="liste_titre">';
+				print '<tr class="liste_titre">';
 				print '<td colspan="5"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastContracts", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td>';
 				print '<td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->id.'">'.$langs->trans("AllContracts").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>';
 				//print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/contract/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"),'stats').'</a></td>';
@@ -987,7 +987,7 @@ if ($object->id > 0)
 				print '<div class="div-table-responsive-no-min">';
 				print '<table class="noborder centpercent lastrecordtable">';
 
-			    print '<tr class="liste_titre">';
+				print '<tr class="liste_titre">';
 				print '<td colspan="3"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastInterventions", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/fichinter/list.php?socid='.$object->id.'">'.$langs->trans("AllInterventions").'<span class="badge marginleftonlyshort">'.$num.'</span></td>';
 				print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/fichinter/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
 				print '</tr></table></td>';
@@ -1000,11 +1000,11 @@ if ($object->id > 0)
 				$objp = $db->fetch_object($resql);
 
 				$fichinter_static->id = $objp->id;
-                $fichinter_static->statut = $objp->fk_statut;
+				$fichinter_static->statut = $objp->fk_statut;
 
 				print '<tr class="oddeven">';
 				print '<td class="nowrap"><a href="'.DOL_URL_ROOT.'/fichinter/card.php?id='.$objp->id.'">'.img_object($langs->trans("ShowPropal"), "propal").' '.$objp->ref.'</a></td>'."\n";
-                //print '<td class="right" width="80px">'.dol_print_date($db->jdate($objp->startdate)).'</td>'."\n";
+				//print '<td class="right" width="80px">'.dol_print_date($db->jdate($objp->startdate)).'</td>'."\n";
 				print '<td class="right" style="min-width: 60px">'.convertSecondToTime($objp->duration).'</td>'."\n";
 				print '<td class="nowrap right" style="min-width: 60px">'.$fichinter_static->getLibStatut(5).'</td>'."\n";
 				print '</tr>';
@@ -1130,10 +1130,10 @@ if ($object->id > 0)
 	 */
 	if (!empty($conf->facture->enabled) && $user->rights->facture->lire)
 	{
-        $sql = 'SELECT f.rowid as facid, f.ref, f.type';
-        $sql .= ', f.total as total_ht';
-        $sql .= ', f.tva as total_tva';
-        $sql .= ', f.total_ttc';
+		$sql = 'SELECT f.rowid as facid, f.ref, f.type';
+		$sql .= ', f.total as total_ht';
+		$sql .= ', f.tva as total_tva';
+		$sql .= ', f.total_ttc';
 		$sql .= ', f.datef as df, f.datec as dc, f.paye as paye, f.fk_statut as statut';
 		$sql .= ', s.nom, s.rowid as socid';
 		$sql .= ', SUM(pf.amount) as am';
@@ -1159,7 +1159,7 @@ if ($object->id > 0)
 
 				print '<tr class="liste_titre">';
 				print '<td colspan="5"><table width="100%" class="nobordernopadding"><tr><td>'.$langs->trans("LastCustomersBills", ($num <= $MAXLIST ? "" : $MAXLIST)).'</td><td class="right"><a class="notasortlink" href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->id.'">'.$langs->trans("AllBills").'<span class="badge marginleftonlyshort">'.$num.'</span></a></td>';
-                print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/compta/facture/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
+				print '<td width="20px" class="right"><a href="'.DOL_URL_ROOT.'/compta/facture/stats/index.php?socid='.$object->id.'">'.img_picto($langs->trans("Statistics"), 'stats').'</a></td>';
 				print '</tr></table></td>';
 				print '</tr>';
 			}
@@ -1192,9 +1192,9 @@ if ($object->id > 0)
 
 				if (!empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES))
 				{
-    				print '<td class="right" style="min-width: 60px">';
-    				print price($objp->total_ttc);
-    				print '</td>';
+					print '<td class="right" style="min-width: 60px">';
+					print price($objp->total_ttc);
+					print '</td>';
 				}
 
 				print '<td class="nowrap right" style="min-width: 60px">'.($facturestatic->LibStatut($objp->paye, $objp->statut, 5, $objp->am)).'</td>';
@@ -1228,79 +1228,79 @@ if ($object->id > 0)
 	$parameters = array();
 	$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
 
-    if (empty($reshook))
-    {
-        if ($object->status != 1)
-        {
-            print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("ThirdPartyIsClosed")).'" href="#">'.$langs->trans("ThirdPartyIsClosed").'</a></div>';
-        }
-
-    	if (!empty($conf->propal->enabled) && $user->rights->propal->creer && $object->status == 1)
-    	{
-    		$langs->load("propal");
-    		print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/comm/propal/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddProp").'</a></div>';
-    	}
-
-    	if (!empty($conf->commande->enabled) && $user->rights->commande->creer && $object->status == 1)
-    	{
-    		$langs->load("orders");
-    		print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddOrder").'</a></div>';
-    	}
-
-    	if ($user->rights->contrat->creer && $object->status == 1)
-    	{
-    		$langs->load("contracts");
-    		print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/contrat/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddContract").'</a></div>';
-    	}
-
-    	if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer && $object->status == 1)
-    	{
-    		$langs->load("fichinter");
-    		print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/fichinter/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddIntervention").'</a></div>';
-    	}
-
-    	// Add invoice
-    	if ($user->socid == 0)
-    	{
-    		if (!empty($conf->deplacement->enabled) && $object->status == 1)
-    		{
-    			$langs->load("trips");
-    			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/deplacement/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddTrip").'</a></div>';
-    		}
-
-    		if (!empty($conf->facture->enabled) && $object->status == 1)
-    		{
-    			if (empty($user->rights->facture->creer))
-    			{
-    			    print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("NotAllowed")).'" href="#">'.$langs->trans("AddBill").'</a></div>';
-    			} else {
-    				$langs->loadLangs(array("orders", "bills"));
-
-    				if (!empty($conf->commande->enabled))
-    				{
-    				    if ($object->client != 0 && $object->client != 2) {
-    					    if (!empty($orders2invoice) && $orders2invoice > 0) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$object->id.'&search_billed=0&autoselectall=1">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>';
-    					    else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("NoOrdersToInvoice")).'" href="#">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>';
-    				    } else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("ThirdPartyMustBeEditAsCustomer")).'" href="#">'.$langs->trans("AddBill").'</a></div>';
-    				}
-
-    				if ($object->client != 0 && $object->client != 2) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddBill").'</a></div>';
-    				else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("ThirdPartyMustBeEditAsCustomer")).'" href="#">'.$langs->trans("AddBill").'</a></div>';
-    			}
-    		}
-    	}
-
-    	// Add action
-    	if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1)
-    	{
-    		if ($user->rights->agenda->myactions->create)
-    		{
-    			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddAction").'</a></div>';
-    		} else {
-    			print '<div class="inline-block divButAction"><a class="butAction" title="'.dol_escape_js($langs->trans("NotAllowed")).'" href="#">'.$langs->trans("AddAction").'</a></div>';
-    		}
-    	}
-    }
+	if (empty($reshook))
+	{
+		if ($object->status != 1)
+		{
+			print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("ThirdPartyIsClosed")).'" href="#">'.$langs->trans("ThirdPartyIsClosed").'</a></div>';
+		}
+
+		if (!empty($conf->propal->enabled) && $user->rights->propal->creer && $object->status == 1)
+		{
+			$langs->load("propal");
+			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/comm/propal/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddProp").'</a></div>';
+		}
+
+		if (!empty($conf->commande->enabled) && $user->rights->commande->creer && $object->status == 1)
+		{
+			$langs->load("orders");
+			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddOrder").'</a></div>';
+		}
+
+		if ($user->rights->contrat->creer && $object->status == 1)
+		{
+			$langs->load("contracts");
+			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/contrat/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddContract").'</a></div>';
+		}
+
+		if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer && $object->status == 1)
+		{
+			$langs->load("fichinter");
+			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/fichinter/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddIntervention").'</a></div>';
+		}
+
+		// Add invoice
+		if ($user->socid == 0)
+		{
+			if (!empty($conf->deplacement->enabled) && $object->status == 1)
+			{
+				$langs->load("trips");
+				print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/deplacement/card.php?socid='.$object->id.'&amp;action=create">'.$langs->trans("AddTrip").'</a></div>';
+			}
+
+			if (!empty($conf->facture->enabled) && $object->status == 1)
+			{
+				if (empty($user->rights->facture->creer))
+				{
+					print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("NotAllowed")).'" href="#">'.$langs->trans("AddBill").'</a></div>';
+				} else {
+					$langs->loadLangs(array("orders", "bills"));
+
+					if (!empty($conf->commande->enabled))
+					{
+						if ($object->client != 0 && $object->client != 2) {
+							if (!empty($orders2invoice) && $orders2invoice > 0) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$object->id.'&search_billed=0&autoselectall=1">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>';
+							else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("NoOrdersToInvoice")).'" href="#">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>';
+						} else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("ThirdPartyMustBeEditAsCustomer")).'" href="#">'.$langs->trans("AddBill").'</a></div>';
+					}
+
+					if ($object->client != 0 && $object->client != 2) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddBill").'</a></div>';
+					else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("ThirdPartyMustBeEditAsCustomer")).'" href="#">'.$langs->trans("AddBill").'</a></div>';
+				}
+			}
+		}
+
+		// Add action
+		if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1)
+		{
+			if ($user->rights->agenda->myactions->create)
+			{
+				print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddAction").'</a></div>';
+			} else {
+				print '<div class="inline-block divButAction"><a class="butAction" title="'.dol_escape_js($langs->trans("NotAllowed")).'" href="#">'.$langs->trans("AddAction").'</a></div>';
+			}
+		}
+	}
 
 	print '</div>';
 
@@ -1310,14 +1310,14 @@ if ($object->id > 0)
 		show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id);
 	}
 
-    if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB))
-    {
-        print load_fiche_titre($langs->trans("ActionsOnCompany"), '', '');
+	if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB))
+	{
+		print load_fiche_titre($langs->trans("ActionsOnCompany"), '', '');
 
-        // List of todo actions
+		// List of todo actions
 		show_actions_todo($conf, $langs, $db, $object);
 
-        // List of done actions
+		// List of done actions
 		show_actions_done($conf, $langs, $db, $object);
 	}
 } else {

+ 290 - 290
htdocs/comm/propal/class/api_proposals.class.php

@@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  */
 class Proposals extends DolibarrApi
 {
-    /**
+	/**
 	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
 	 */
 	static $FIELDS = array(
@@ -65,60 +65,60 @@ class Proposals extends DolibarrApi
 	 */
 	public function get($id, $contact_list = 1)
 	{
-        return $this->_fetch($id, '', '', $contact_list);
+		return $this->_fetch($id, '', '', $contact_list);
+	}
+
+	/**
+	 * Get properties of an proposal object by ref
+	 *
+	 * Return an array with proposal informations
+	 *
+	 * @param       string		$ref			Ref of object
+	 * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @url GET    ref/{ref}
+	 *
+	 * @throws 	RestException
+	 */
+	public function getByRef($ref, $contact_list = 1)
+	{
+		return $this->_fetch('', $ref, '', $contact_list);
+	}
+
+	/**
+	 * Get properties of an proposal object by ref_ext
+	 *
+	 * Return an array with proposal informations
+	 *
+	 * @param       string		$ref_ext			External reference of object
+	 * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @url GET    ref_ext/{ref_ext}
+	 *
+	 * @throws 	RestException
+	 */
+	public function getByRefExt($ref_ext, $contact_list = 1)
+	{
+		return $this->_fetch('', '', $ref_ext, $contact_list);
 	}
 
-    /**
-     * Get properties of an proposal object by ref
-     *
-     * Return an array with proposal informations
-     *
-     * @param       string		$ref			Ref of object
-     * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
-     * @return 	array|mixed data without useless information
-     *
-     * @url GET    ref/{ref}
-     *
-     * @throws 	RestException
-     */
-    public function getByRef($ref, $contact_list = 1)
-    {
-        return $this->_fetch('', $ref, '', $contact_list);
-    }
-
-    /**
-     * Get properties of an proposal object by ref_ext
-     *
-     * Return an array with proposal informations
-     *
-     * @param       string		$ref_ext			External reference of object
-     * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
-     * @return 	array|mixed data without useless information
-     *
-     * @url GET    ref_ext/{ref_ext}
-     *
-     * @throws 	RestException
-     */
-    public function getByRefExt($ref_ext, $contact_list = 1)
-    {
-        return $this->_fetch('', '', $ref_ext, $contact_list);
-    }
-
-    /**
-     * Get properties of an proposal object
-     *
-     * Return an array with proposal informations
-     *
-     * @param       int         $id             ID of order
+	/**
+	 * Get properties of an proposal object
+	 *
+	 * Return an array with proposal informations
+	 *
+	 * @param       int         $id             ID of order
 	 * @param		string		$ref			Ref of object
 	 * @param		string		$ref_ext		External reference of object
-     * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
-     * @return 	array|mixed data without useless information
-     *
-     * @throws 	RestException
-     */
-    private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1)
-    {
+	 * @param       int         $contact_list  0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id
+	 * @return 	array|mixed data without useless information
+	 *
+	 * @throws 	RestException
+	 */
+	private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1)
+	{
 		if (!DolibarrApiAccess::$user->rights->propal->lire) {
 			throw new RestException(401);
 		}
@@ -151,8 +151,8 @@ class Proposals extends DolibarrApi
 	 * @param string    $sqlfilters         Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')"
 	 * @return  array                       Array of order objects
 	 */
-    public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
-    {
+	public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
+	{
 		global $db, $conf;
 
 		$obj_ret = array();
@@ -201,8 +201,8 @@ class Proposals extends DolibarrApi
 			$sql .= $this->db->plimit($limit + 1, $offset);
 		}
 
-        dol_syslog("API Rest request");
-        $result = $this->db->query($sql);
+		dol_syslog("API Rest request");
+		$result = $this->db->query($sql);
 
 		if ($result)
 		{
@@ -235,13 +235,13 @@ class Proposals extends DolibarrApi
 	 * @param   array   $request_data   Request data
 	 * @return  int     ID of proposal
 	 */
-    public function post($request_data = null)
-    {
-        if (!DolibarrApiAccess::$user->rights->propal->creer) {
-            throw new RestException(401, "Insuffisant rights");
-        }
-        // Check mandatory fields
-        $result = $this->_validate($request_data);
+	public function post($request_data = null)
+	{
+		if (!DolibarrApiAccess::$user->rights->propal->creer) {
+			throw new RestException(401, "Insuffisant rights");
+		}
+		// Check mandatory fields
+		$result = $this->_validate($request_data);
 
 		foreach ($request_data as $field => $value) {
 			$this->propal->$field = $value;
@@ -258,7 +258,7 @@ class Proposals extends DolibarrApi
 		}
 
 		return $this->propal->id;
-    }
+	}
 
 	/**
 	 * Get lines of a commercial proposal
@@ -269,26 +269,26 @@ class Proposals extends DolibarrApi
 	 *
 	 * @return int
 	 */
-    public function getLines($id)
-    {
-        if (!DolibarrApiAccess::$user->rights->propal->lire) {
-            throw new RestException(401);
-        }
+	public function getLines($id)
+	{
+		if (!DolibarrApiAccess::$user->rights->propal->lire) {
+			throw new RestException(401);
+		}
 
-	    $result = $this->propal->fetch($id);
-	    if (!$result) {
-		    throw new RestException(404, 'Commercial Proposal not found');
-	    }
+		$result = $this->propal->fetch($id);
+		if (!$result) {
+			throw new RestException(404, 'Commercial Proposal not found');
+		}
 
 		if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
-		    throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
-	    }
-	    $this->propal->getLinesArray();
-	    $result = array();
-	    foreach ($this->propal->lines as $line) {
-		    array_push($result, $this->_cleanObjectDatas($line));
-	    }
-	    return $result;
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+		}
+		$this->propal->getLinesArray();
+		$result = array();
+		foreach ($this->propal->lines as $line) {
+			array_push($result, $this->_cleanObjectDatas($line));
+		}
+		return $result;
 	}
 
 	/**
@@ -309,50 +309,50 @@ class Proposals extends DolibarrApi
 
 		$result = $this->propal->fetch($id);
 		if (!$result) {
-		    throw new RestException(404, 'Commercial Proposal not found');
+			throw new RestException(404, 'Commercial Proposal not found');
 		}
 
 		if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
 		}
 
-        $request_data = (object) $request_data;
-
-        $updateRes = $this->propal->addline(
-                        $request_data->desc,
-                        $request_data->subprice,
-                        $request_data->qty,
-                        $request_data->tva_tx,
-                        $request_data->localtax1_tx,
-                        $request_data->localtax2_tx,
-                        $request_data->fk_product,
-                        $request_data->remise_percent,
-                        'HT',
-                        0,
-                        $request_data->info_bits,
-                        $request_data->product_type,
-                        $request_data->rang,
-                        $request_data->special_code,
-      					$request_data->fk_parent_line,
-                        $request_data->fk_fournprice,
-                        $request_data->pa_ht,
-                        $request_data->label,
-                        $request_data->date_start,
-                        $request_data->date_end,
-                        $request_data->array_options,
-                        $request_data->fk_unit,
-                        $request_data->origin,
-                        $request_data->origin_id,
-                        $request_data->multicurrency_subprice,
-                        $request_data->fk_remise_except
-        );
-
-        if ($updateRes > 0) {
-            return $updateRes;
-        } else {
-            throw new RestException(400, $this->propal->error);
-        }
-    }
+		$request_data = (object) $request_data;
+
+		$updateRes = $this->propal->addline(
+						$request_data->desc,
+						$request_data->subprice,
+						$request_data->qty,
+						$request_data->tva_tx,
+						$request_data->localtax1_tx,
+						$request_data->localtax2_tx,
+						$request_data->fk_product,
+						$request_data->remise_percent,
+						'HT',
+						0,
+						$request_data->info_bits,
+						$request_data->product_type,
+						$request_data->rang,
+						$request_data->special_code,
+	  					$request_data->fk_parent_line,
+						$request_data->fk_fournprice,
+						$request_data->pa_ht,
+						$request_data->label,
+						$request_data->date_start,
+						$request_data->date_end,
+						$request_data->array_options,
+						$request_data->fk_unit,
+						$request_data->origin,
+						$request_data->origin_id,
+						$request_data->multicurrency_subprice,
+						$request_data->fk_remise_except
+		);
+
+		if ($updateRes > 0) {
+			return $updateRes;
+		} else {
+			throw new RestException(400, $this->propal->error);
+		}
+	}
 
 	/**
 	 * Update a line of given commercial proposal
@@ -388,37 +388,37 @@ class Proposals extends DolibarrApi
 	  		throw new RestException(404, 'Proposal line not found');
 	  	}
 
-        $updateRes = $this->propal->updateline(
-            $lineid,
-            isset($request_data->subprice) ? $request_data->subprice : $propalline->subprice,
-            isset($request_data->qty) ? $request_data->qty : $propalline->qty,
-            isset($request_data->remise_percent) ? $request_data->remise_percent : $propalline->remise_percent,
-            isset($request_data->tva_tx) ? $request_data->tva_tx : $propalline->tva_tx,
-            isset($request_data->localtax1_tx) ? $request_data->localtax1_tx : $propalline->localtax1_tx,
-            isset($request_data->localtax2_tx) ? $request_data->localtax2_tx : $propalline->localtax2_tx,
-            isset($request_data->desc) ? $request_data->desc : $propalline->desc,
-            'HT',
-            isset($request_data->info_bits) ? $request_data->info_bits : $propalline->info_bits,
-            isset($request_data->special_code) ? $request_data->special_code : $propalline->special_code,
-            isset($request_data->fk_parent_line) ? $request_data->fk_parent_line : $propalline->fk_parent_line,
-            0,
-            isset($request_data->fk_fournprice) ? $request_data->fk_fournprice : $propalline->fk_fournprice,
-            isset($request_data->pa_ht) ? $request_data->pa_ht : $propalline->pa_ht,
-            isset($request_data->label) ? $request_data->label : $propalline->label,
-            isset($request_data->product_type) ? $request_data->product_type : $propalline->product_type,
-            isset($request_data->date_start) ? $request_data->date_start : $propalline->date_start,
-            isset($request_data->date_end) ? $request_data->date_end : $propalline->date_end,
-            isset($request_data->array_options) ? $request_data->array_options : $propalline->array_options,
-            isset($request_data->fk_unit) ? $request_data->fk_unit : $propalline->fk_unit,
-            isset($request_data->multicurrency_subprice) ? $request_data->multicurrency_subprice : $propalline->subprice
-        );
-
-	    if ($updateRes > 0) {
-		    $result = $this->get($id);
-		    unset($result->line);
-		    return $this->_cleanObjectDatas($result);
-	    }
-	    return false;
+		$updateRes = $this->propal->updateline(
+			$lineid,
+			isset($request_data->subprice) ? $request_data->subprice : $propalline->subprice,
+			isset($request_data->qty) ? $request_data->qty : $propalline->qty,
+			isset($request_data->remise_percent) ? $request_data->remise_percent : $propalline->remise_percent,
+			isset($request_data->tva_tx) ? $request_data->tva_tx : $propalline->tva_tx,
+			isset($request_data->localtax1_tx) ? $request_data->localtax1_tx : $propalline->localtax1_tx,
+			isset($request_data->localtax2_tx) ? $request_data->localtax2_tx : $propalline->localtax2_tx,
+			isset($request_data->desc) ? $request_data->desc : $propalline->desc,
+			'HT',
+			isset($request_data->info_bits) ? $request_data->info_bits : $propalline->info_bits,
+			isset($request_data->special_code) ? $request_data->special_code : $propalline->special_code,
+			isset($request_data->fk_parent_line) ? $request_data->fk_parent_line : $propalline->fk_parent_line,
+			0,
+			isset($request_data->fk_fournprice) ? $request_data->fk_fournprice : $propalline->fk_fournprice,
+			isset($request_data->pa_ht) ? $request_data->pa_ht : $propalline->pa_ht,
+			isset($request_data->label) ? $request_data->label : $propalline->label,
+			isset($request_data->product_type) ? $request_data->product_type : $propalline->product_type,
+			isset($request_data->date_start) ? $request_data->date_start : $propalline->date_start,
+			isset($request_data->date_end) ? $request_data->date_end : $propalline->date_end,
+			isset($request_data->array_options) ? $request_data->array_options : $propalline->array_options,
+			isset($request_data->fk_unit) ? $request_data->fk_unit : $propalline->fk_unit,
+			isset($request_data->multicurrency_subprice) ? $request_data->multicurrency_subprice : $propalline->subprice
+		);
+
+		if ($updateRes > 0) {
+			$result = $this->get($id);
+			unset($result->line);
+			return $this->_cleanObjectDatas($result);
+		}
+		return false;
 	}
 
 	/**
@@ -432,13 +432,13 @@ class Proposals extends DolibarrApi
 	 *
 	 * @return int
 	 *
-     * @throws RestException 401
-     * @throws RestException 404
+	 * @throws RestException 401
+	 * @throws RestException 404
 	 */
-    public function deleteLine($id, $lineid)
-    {
+	public function deleteLine($id, $lineid)
+	{
 		if (!DolibarrApiAccess::$user->rights->propal->creer) {
-            throw new RestException(401);
+			throw new RestException(401);
 		}
 
 		$result = $this->propal->fetch($id);
@@ -460,7 +460,7 @@ class Proposals extends DolibarrApi
 		}
 	}
 
-    /**
+	/**
 	 * Add a contact type of given commercial proposal
 	 *
 	 * @param int    $id             Id of commercial proposal to update
@@ -471,66 +471,66 @@ class Proposals extends DolibarrApi
 	 *
 	 * @return int
 	 *
-     * @throws RestException 401
-     * @throws RestException 404
+	 * @throws RestException 401
+	 * @throws RestException 404
 	 */
-    public function postContact($id, $contactid, $type)
-    {
-        if (!DolibarrApiAccess::$user->rights->propal->creer) {
-            throw new RestException(401);
-        }
+	public function postContact($id, $contactid, $type)
+	{
+		if (!DolibarrApiAccess::$user->rights->propal->creer) {
+			throw new RestException(401);
+		}
 
-        $result = $this->propal->fetch($id);
+		$result = $this->propal->fetch($id);
 
 		if (!$result) {
 			throw new RestException(404, 'Proposal not found');
 		}
 
-        if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) {
-            throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER');
-        }
+		if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) {
+			throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER');
+		}
 
-        if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
+		if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
 		}
 
-        $result = $this->propal->add_contact($contactid, $type, 'external');
+		$result = $this->propal->add_contact($contactid, $type, 'external');
 
-        if (!$result) {
-            throw new RestException(500, 'Error when added the contact');
-        }
+		if (!$result) {
+			throw new RestException(500, 'Error when added the contact');
+		}
 
-        return $this->propal;
-    }
+		return $this->propal;
+	}
 
-     /**
-	 * Delete a contact type of given commercial proposal
-	 *
-	 * @param int    $id             Id of commercial proposal to update
-	 * @param int    $contactid      Row key of the contact in the array contact_ids.
-	 * @param string $type           Type of the contact (BILLING, SHIPPING, CUSTOMER).
-	 *
-	 * @url	DELETE {id}/contact/{contactid}/{type}
-	 *
-	 * @return int
-	 *
-     * @throws RestException 401
-     * @throws RestException 404
-     * @throws RestException 500
-	 */
-    public function deleteContact($id, $contactid, $type)
-    {
-        if (!DolibarrApiAccess::$user->rights->propal->creer) {
-            throw new RestException(401);
-        }
+	 /**
+	  * Delete a contact type of given commercial proposal
+	  *
+	  * @param int    $id             Id of commercial proposal to update
+	  * @param int    $contactid      Row key of the contact in the array contact_ids.
+	  * @param string $type           Type of the contact (BILLING, SHIPPING, CUSTOMER).
+	  *
+	  * @url	DELETE {id}/contact/{contactid}/{type}
+	  *
+	  * @return int
+	  *
+	  * @throws RestException 401
+	  * @throws RestException 404
+	  * @throws RestException 500
+	  */
+	public function deleteContact($id, $contactid, $type)
+	{
+		if (!DolibarrApiAccess::$user->rights->propal->creer) {
+			throw new RestException(401);
+		}
 
-        $result = $this->propal->fetch($id);
+		$result = $this->propal->fetch($id);
 
 		if (!$result) {
 			throw new RestException(404, 'Proposal not found');
 		}
 
-        if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
+		if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
 			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
 		}
 
@@ -547,7 +547,7 @@ class Proposals extends DolibarrApi
 		}
 
 		return $this->_cleanObjectDatas($this->propal);
-    }
+	}
 
 	/**
 	 * Update commercial proposal general fields (won't touch lines of commercial proposal)
@@ -556,12 +556,12 @@ class Proposals extends DolibarrApi
 	 * @param array $request_data   Datas
 	 *
 	 * @return int
-     */
-    public function put($id, $request_data = null)
-    {
-        if (!DolibarrApiAccess::$user->rights->propal->creer) {
-            throw new RestException(401);
-        }
+	 */
+	public function put($id, $request_data = null)
+	{
+		if (!DolibarrApiAccess::$user->rights->propal->creer) {
+			throw new RestException(401);
+		}
 
 		$result = $this->propal->fetch($id);
 		if (!$result) {
@@ -631,14 +631,14 @@ class Proposals extends DolibarrApi
 	}
 
 	/**
-	* Set a proposal to draft
-	*
-	* @param   int     $id             Order ID
-	*
-	* @url POST    {id}/settodraft
-	*
-	* @return  array
-	*/
+	 * Set a proposal to draft
+	 *
+	 * @param   int     $id             Order ID
+	 *
+	 * @url POST    {id}/settodraft
+	 *
+	 * @return  array
+	 */
 	public function settodraft($id)
 	{
 		if (!DolibarrApiAccess::$user->rights->propal->creer) {
@@ -690,14 +690,14 @@ class Proposals extends DolibarrApi
 	 * @url POST    {id}/validate
 	 *
 	 * @throws RestException 304
-     * @throws RestException 401
-     * @throws RestException 404
-     * @throws RestException 500
-     *
-     * @return array
-     */
-    public function validate($id, $notrigger = 0)
-    {
+	 * @throws RestException 401
+	 * @throws RestException 404
+	 * @throws RestException 500
+	 *
+	 * @return array
+	 */
+	public function validate($id, $notrigger = 0)
+	{
 		if (!DolibarrApiAccess::$user->rights->propal->creer) {
 			throw new RestException(401);
 		}
@@ -718,19 +718,19 @@ class Proposals extends DolibarrApi
 			throw new RestException(500, 'Error when validating Commercial Proposal: '.$this->propal->error);
 		}
 
-        $result = $this->propal->fetch($id);
-        if (!$result) {
-            throw new RestException(404, 'Commercial Proposal not found');
-        }
+		$result = $this->propal->fetch($id);
+		if (!$result) {
+			throw new RestException(404, 'Commercial Proposal not found');
+		}
 
-        if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
-            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
-        }
+		if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+		}
 
-        $this->propal->fetchObjectLinked();
+		$this->propal->fetchObjectLinked();
 
-        return $this->_cleanObjectDatas($this->propal);
-    }
+		return $this->_cleanObjectDatas($this->propal);
+	}
 
 	/**
 	 * Close (Accept or refuse) a quote / commercial proposal
@@ -780,47 +780,47 @@ class Proposals extends DolibarrApi
 		return $this->_cleanObjectDatas($this->propal);
 	}
 
-    /**
-     * Set a commercial proposal billed. Could be also called setbilled
-     *
-     * @param   int     $id             Commercial proposal ID
-     *
-     * @url POST    {id}/setinvoiced
-     *
-     * @return  array
-     */
-    public function setinvoiced($id)
-    {
-        if (!DolibarrApiAccess::$user->rights->propal->creer) {
-            throw new RestException(401);
-        }
-        $result = $this->propal->fetch($id);
-        if (!$result) {
-            throw new RestException(404, 'Commercial Proposal not found');
-        }
-
-        if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
-            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
-        }
-
-        $result = $this->propal->classifyBilled(DolibarrApiAccess::$user);
-        if ($result < 0) {
-            throw new RestException(500, 'Error : '.$this->propal->error);
-        }
-
-        $result = $this->propal->fetch($id);
-        if (!$result) {
-            throw new RestException(404, 'Proposal not found');
-        }
-
-        if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
-            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
-        }
-
-        $this->propal->fetchObjectLinked();
-
-        return $this->_cleanObjectDatas($this->propal);
-    }
+	/**
+	 * Set a commercial proposal billed. Could be also called setbilled
+	 *
+	 * @param   int     $id             Commercial proposal ID
+	 *
+	 * @url POST    {id}/setinvoiced
+	 *
+	 * @return  array
+	 */
+	public function setinvoiced($id)
+	{
+		if (!DolibarrApiAccess::$user->rights->propal->creer) {
+			throw new RestException(401);
+		}
+		$result = $this->propal->fetch($id);
+		if (!$result) {
+			throw new RestException(404, 'Commercial Proposal not found');
+		}
+
+		if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+		}
+
+		$result = $this->propal->classifyBilled(DolibarrApiAccess::$user);
+		if ($result < 0) {
+			throw new RestException(500, 'Error : '.$this->propal->error);
+		}
+
+		$result = $this->propal->fetch($id);
+		if (!$result) {
+			throw new RestException(404, 'Proposal not found');
+		}
+
+		if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) {
+			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+		}
+
+		$this->propal->fetchObjectLinked();
+
+		return $this->_cleanObjectDatas($this->propal);
+	}
 
 
 	/**
@@ -842,25 +842,25 @@ class Proposals extends DolibarrApi
 	}
 
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
-    /**
-     * Clean sensible object datas
-     *
-     * @param   object  $object    Object to clean
-     * @return    array    Array of cleaned object properties
-     */
-    protected function _cleanObjectDatas($object)
-    {
-        // phpcs:enable
-        $object = parent::_cleanObjectDatas($object);
-
-        unset($object->note);
-        unset($object->name);
-        unset($object->lastname);
-        unset($object->firstname);
-        unset($object->civility_id);
-        unset($object->address);
-
-        return $object;
-    }
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
+	/**
+	 * Clean sensible object datas
+	 *
+	 * @param   object  $object    Object to clean
+	 * @return    array    Array of cleaned object properties
+	 */
+	protected function _cleanObjectDatas($object)
+	{
+		// phpcs:enable
+		$object = parent::_cleanObjectDatas($object);
+
+		unset($object->note);
+		unset($object->name);
+		unset($object->lastname);
+		unset($object->firstname);
+		unset($object->civility_id);
+		unset($object->address);
+
+		return $object;
+	}
 }

+ 6 - 6
htdocs/commande/class/api_orders.class.php

@@ -573,13 +573,13 @@ class Orders extends DolibarrApi
 		 $contacts = $this->commande->liste_contact();
 
 		foreach ($contacts as $contact) {
-            if ($contact['id'] == $contactid && $contact['code'] == $type) {
-		        $result = $this->commande->delete_contact($contact['rowid']);
+			if ($contact['id'] == $contactid && $contact['code'] == $type) {
+				$result = $this->commande->delete_contact($contact['rowid']);
 
-		        if (!$result) {
-                    throw new RestException(500, 'Error when deleted the contact');
-                }
-		    }
+				if (!$result) {
+					throw new RestException(500, 'Error when deleted the contact');
+				}
+			}
 		}
 
 		return array(

File diff suppressed because it is too large
+ 601 - 601
htdocs/compta/bank/bankentries_list.php


+ 404 - 404
htdocs/compta/deplacement/card.php

@@ -31,7 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
 if (!empty($conf->projet->enabled))
 {
-    require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
+	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
 }
 
 // Load translation files required by the page
@@ -62,138 +62,138 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include,
 
 if ($action == 'validate' && $user->rights->deplacement->creer)
 {
-    $object->fetch($id);
-    if ($object->statut == Deplacement::STATUS_DRAFT)
-    {
-        $result = $object->setStatut(1);
-        if ($result > 0)
-        {
-            header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
-            exit;
-        } else {
-	        setEventMessages($object->error, $object->errors, 'errors');
-        }
-    }
+	$object->fetch($id);
+	if ($object->statut == Deplacement::STATUS_DRAFT)
+	{
+		$result = $object->setStatut(1);
+		if ($result > 0)
+		{
+			header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+			exit;
+		} else {
+			setEventMessages($object->error, $object->errors, 'errors');
+		}
+	}
 } elseif ($action == 'classifyrefunded' && $user->rights->deplacement->creer)
 {
-    $object->fetch($id);
-    if ($object->statut == Deplacement::STATUS_VALIDATED)
-    {
-        $result = $object->setStatut(Deplacement::STATUS_REFUNDED);
-        if ($result > 0)
-        {
-            header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
-            exit;
-        } else {
-	        setEventMessages($object->error, $object->errors, 'errors');
-        }
-    }
+	$object->fetch($id);
+	if ($object->statut == Deplacement::STATUS_VALIDATED)
+	{
+		$result = $object->setStatut(Deplacement::STATUS_REFUNDED);
+		if ($result > 0)
+		{
+			header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+			exit;
+		} else {
+			setEventMessages($object->error, $object->errors, 'errors');
+		}
+	}
 } elseif ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->deplacement->supprimer)
 {
-    $result = $object->delete($id);
-    if ($result >= 0)
-    {
-        header("Location: index.php");
-        exit;
-    } else {
-	    setEventMessages($object->error, $object->errors, 'errors');
-    }
+	$result = $object->delete($id);
+	if ($result >= 0)
+	{
+		header("Location: index.php");
+		exit;
+	} else {
+		setEventMessages($object->error, $object->errors, 'errors');
+	}
 } elseif ($action == 'add' && $user->rights->deplacement->creer)
 {
-    if (!GETPOST('cancel', 'alpha'))
-    {
-        $error = 0;
-
-        $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
-        $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount
-        $object->type = GETPOST('type', 'alpha');
-        $object->socid = (int) GETPOST('socid', 'int');
-        $object->fk_user = (int) GETPOST('fk_user', 'int');
-        $object->note_private = GETPOST('note_private', 'alpha');
-        $object->note_public = GETPOST('note_public', 'alpha');
-        $object->statut = Deplacement::STATUS_DRAFT;
-
-        if (!$object->date)
-        {
-	        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
-            $error++;
-        }
-        if ($object->type == '-1')
-        {
-	        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
-            $error++;
-        }
-        if (!($object->fk_user > 0))
-        {
-	        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Person")), null, 'errors');
-            $error++;
-        }
-
-        if (!$error)
-        {
-            $id = $object->create($user);
-
-            if ($id > 0)
-            {
-                header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
-                exit;
-            } else {
-	            setEventMessages($object->error, $object->errors, 'errors');
-                $action = 'create';
-            }
-        } else {
-            $action = 'create';
-        }
-    } else {
-        header("Location: index.php");
-        exit;
-    }
+	if (!GETPOST('cancel', 'alpha'))
+	{
+		$error = 0;
+
+		$object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
+		$object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount
+		$object->type = GETPOST('type', 'alpha');
+		$object->socid = (int) GETPOST('socid', 'int');
+		$object->fk_user = (int) GETPOST('fk_user', 'int');
+		$object->note_private = GETPOST('note_private', 'alpha');
+		$object->note_public = GETPOST('note_public', 'alpha');
+		$object->statut = Deplacement::STATUS_DRAFT;
+
+		if (!$object->date)
+		{
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
+			$error++;
+		}
+		if ($object->type == '-1')
+		{
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
+			$error++;
+		}
+		if (!($object->fk_user > 0))
+		{
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Person")), null, 'errors');
+			$error++;
+		}
+
+		if (!$error)
+		{
+			$id = $object->create($user);
+
+			if ($id > 0)
+			{
+				header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+				exit;
+			} else {
+				setEventMessages($object->error, $object->errors, 'errors');
+				$action = 'create';
+			}
+		} else {
+			$action = 'create';
+		}
+	} else {
+		header("Location: index.php");
+		exit;
+	}
 } // Update record
 elseif ($action == 'update' && $user->rights->deplacement->creer)
 {
-    if (!GETPOST('cancel', 'alpha'))
-    {
-        $result = $object->fetch($id);
-
-        $object->date			= dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
-        $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount
-        $object->type			= GETPOST('type', 'alpha');
-        $object->socid = (int) GETPOST('socid', 'int');
-        $object->fk_user = (int) GETPOST('fk_user', 'int');
-        $object->note_private = GETPOST('note_private', 'alpha');
-        $object->note_public = GETPOST('note_public', 'alpha');
-
-        $result = $object->update($user);
-
-        if ($result > 0)
-        {
-            header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
-            exit;
-        } else {
-	        setEventMessages($object->error, $object->errors, 'errors');
-        }
-    } else {
-        header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
-        exit;
-    }
+	if (!GETPOST('cancel', 'alpha'))
+	{
+		$result = $object->fetch($id);
+
+		$object->date			= dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
+		$object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount
+		$object->type			= GETPOST('type', 'alpha');
+		$object->socid = (int) GETPOST('socid', 'int');
+		$object->fk_user = (int) GETPOST('fk_user', 'int');
+		$object->note_private = GETPOST('note_private', 'alpha');
+		$object->note_public = GETPOST('note_public', 'alpha');
+
+		$result = $object->update($user);
+
+		if ($result > 0)
+		{
+			header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+			exit;
+		} else {
+			setEventMessages($object->error, $object->errors, 'errors');
+		}
+	} else {
+		header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+		exit;
+	}
 } // Set into a project
 elseif ($action == 'classin' && $user->rights->deplacement->creer)
 {
-    $object->fetch($id);
-    $result = $object->setProject(GETPOST('projectid', 'int'));
-    if ($result < 0) dol_print_error($db, $object->error);
+	$object->fetch($id);
+	$result = $object->setProject(GETPOST('projectid', 'int'));
+	if ($result < 0) dol_print_error($db, $object->error);
 } // Set fields
 elseif ($action == 'setdated' && $user->rights->deplacement->creer)
 {
-    $dated = dol_mktime(GETPOST('datedhour', 'int'), GETPOST('datedmin', 'int'), GETPOST('datedsec', 'int'), GETPOST('datedmonth', 'int'), GETPOST('datedday', 'int'), GETPOST('datedyear', 'int'));
-    $object->fetch($id);
-    $result = $object->setValueFrom('dated', $dated, '', '', 'date', '', $user, 'DEPLACEMENT_MODIFY');
-    if ($result < 0) dol_print_error($db, $object->error);
+	$dated = dol_mktime(GETPOST('datedhour', 'int'), GETPOST('datedmin', 'int'), GETPOST('datedsec', 'int'), GETPOST('datedmonth', 'int'), GETPOST('datedday', 'int'), GETPOST('datedyear', 'int'));
+	$object->fetch($id);
+	$result = $object->setValueFrom('dated', $dated, '', '', 'date', '', $user, 'DEPLACEMENT_MODIFY');
+	if ($result < 0) dol_print_error($db, $object->error);
 } elseif ($action == 'setkm' && $user->rights->deplacement->creer)
 {
-    $object->fetch($id);
-    $result = $object->setValueFrom('km', GETPOST('km', 'int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY');
-    if ($result < 0) dol_print_error($db, $object->error);
+	$object->fetch($id);
+	$result = $object->setValueFrom('km', GETPOST('km', 'int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY');
+	if ($result < 0) dol_print_error($db, $object->error);
 }
 
 
@@ -210,327 +210,327 @@ $form = new Form($db);
 */
 if ($action == 'create')
 {
-    //WYSIWYG Editor
-    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+	//WYSIWYG Editor
+	require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
 
-    print load_fiche_titre($langs->trans("NewTrip"));
+	print load_fiche_titre($langs->trans("NewTrip"));
 
-    $datec = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
+	$datec = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
 
-    print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n";
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    print '<input type="hidden" name="action" value="add">';
+	print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n";
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="action" value="add">';
 
-    print '<table class="border centpercent">';
+	print '<table class="border centpercent">';
 
-    print "<tr>";
-    print '<td class="fieldrequired">'.$langs->trans("Type").'</td><td>';
-    $form->select_type_fees(GETPOST('type', 'int'), 'type', 1);
-    print '</td></tr>';
+	print "<tr>";
+	print '<td class="fieldrequired">'.$langs->trans("Type").'</td><td>';
+	$form->select_type_fees(GETPOST('type', 'int'), 'type', 1);
+	print '</td></tr>';
 
-    print "<tr>";
-    print '<td class="fieldrequired">'.$langs->trans("Person").'</td><td>';
-    print $form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
-    print '</td></tr>';
+	print "<tr>";
+	print '<td class="fieldrequired">'.$langs->trans("Person").'</td><td>';
+	print $form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
+	print '</td></tr>';
 
-    print "<tr>";
-    print '<td class="fieldrequired">'.$langs->trans("Date").'</td><td>';
-    print $form->selectDate($datec ? $datec : -1, '', '', '', '', 'add', 1, 1);
-    print '</td></tr>';
+	print "<tr>";
+	print '<td class="fieldrequired">'.$langs->trans("Date").'</td><td>';
+	print $form->selectDate($datec ? $datec : -1, '', '', '', '', 'add', 1, 1);
+	print '</td></tr>';
 
-    // Km
-    print '<tr><td class="fieldrequired">'.$langs->trans("FeesKilometersOrAmout").'</td><td><input name="km" size="10" value="'.GETPOST("km").'"></td></tr>';
+	// Km
+	print '<tr><td class="fieldrequired">'.$langs->trans("FeesKilometersOrAmout").'</td><td><input name="km" size="10" value="'.GETPOST("km").'"></td></tr>';
 
-    // Company
-    print "<tr>";
-    print '<td>'.$langs->trans("CompanyVisited").'</td><td>';
-    print $form->select_company(GETPOST('socid', 'int'), 'socid', '', 1);
-    print '</td></tr>';
+	// Company
+	print "<tr>";
+	print '<td>'.$langs->trans("CompanyVisited").'</td><td>';
+	print $form->select_company(GETPOST('socid', 'int'), 'socid', '', 1);
+	print '</td></tr>';
 
-    // Public note
-    print '<tr>';
-    print '<td class="tdtop">'.$langs->trans('NotePublic').'</td>';
-    print '<td>';
+	// Public note
+	print '<tr>';
+	print '<td class="tdtop">'.$langs->trans('NotePublic').'</td>';
+	print '<td>';
 
-    $doleditor = new DolEditor('note_public', GETPOST('note_public', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%');
-    print $doleditor->Create(1);
+	$doleditor = new DolEditor('note_public', GETPOST('note_public', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%');
+	print $doleditor->Create(1);
 
-    print '</td></tr>';
+	print '</td></tr>';
 
-    // Private note
-    if (empty($user->socid))
-    {
-        print '<tr>';
-        print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>';
-        print '<td>';
+	// Private note
+	if (empty($user->socid))
+	{
+		print '<tr>';
+		print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>';
+		print '<td>';
 
-        $doleditor = new DolEditor('note_private', GETPOST('note_private', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%');
-        print $doleditor->Create(1);
+		$doleditor = new DolEditor('note_private', GETPOST('note_private', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%');
+		print $doleditor->Create(1);
 
-        print '</td></tr>';
-    }
+		print '</td></tr>';
+	}
 
-    // Other attributes
-    $parameters = array();
-    $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-    print $hookmanager->resPrint;
+	// Other attributes
+	$parameters = array();
+	$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+	print $hookmanager->resPrint;
 
-    print '</table>';
+	print '</table>';
 
-    print '<br><div class="center">';
+	print '<br><div class="center">';
 	print '<input class="button" type="submit" value="'.$langs->trans("Save").'">';
 	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-    print '<input class="button" type="submit" name="cancel" value="'.$langs->trans("Cancel").'">';
+	print '<input class="button" type="submit" name="cancel" value="'.$langs->trans("Cancel").'">';
 	print '</div>';
 
-    print '</form>';
+	print '</form>';
 } elseif ($id)
 {
-    $result = $object->fetch($id);
-    if ($result > 0)
-    {
-        $head = trip_prepare_head($object);
-
-        dol_fiche_head($head, 'card', $langs->trans("TripCard"), 0, 'trip');
-
-        if ($action == 'edit' && $user->rights->deplacement->creer)
-        {
-            //WYSIWYG Editor
-            require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-
-            $soc = new Societe($db);
-            if ($object->socid)
-            {
-                $soc->fetch($object->socid);
-            }
-
-            print '<form name="update" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n";
-            print '<input type="hidden" name="token" value="'.newToken().'">';
-            print '<input type="hidden" name="action" value="update">';
-            print '<input type="hidden" name="id" value="'.$id.'">';
-
-            print '<table class="border centpercent">';
-
-            // Ref
-            print "<tr>";
-            print '<td class="titlefield">'.$langs->trans("Ref").'</td><td>';
-            print $object->ref;
-            print '</td></tr>';
-
-            // Type
-            print "<tr>";
-            print '<td class="fieldrequired">'.$langs->trans("Type").'</td><td>';
-            $form->select_type_fees(GETPOST('type', 'int') ?GETPOST('type', 'int') : $object->type, 'type', 0);
-            print '</td></tr>';
-
-            // Who
-            print "<tr>";
-            print '<td class="fieldrequired">'.$langs->trans("Person").'</td><td>';
-            print $form->select_dolusers(GETPOST('fk_user', 'int') ?GETPOST('fk_user', 'int') : $object->fk_user, 'fk_user', 0, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
-            print '</td></tr>';
-
-            // Date
-            print '<tr><td class="fieldrequired">'.$langs->trans("Date").'</td><td>';
-            print $form->selectDate($object->date, '', 0, 0, 0, 'update', 1, 0);
-            print '</td></tr>';
-
-            // Km
-            print '<tr><td class="fieldrequired">'.$langs->trans("FeesKilometersOrAmout").'</td><td>';
-            print '<input name="km" class="flat" size="10" value="'.$object->km.'">';
-            print '</td></tr>';
-
-            // Where
-            print "<tr>";
-            print '<td>'.$langs->trans("CompanyVisited").'</td><td>';
-            print $form->select_company($soc->id, 'socid', '', 1);
-            print '</td></tr>';
-
-            // Public note
-            print '<tr><td class="tdtop">'.$langs->trans("NotePublic").'</td>';
-            print '<td>';
-
-            $doleditor = new DolEditor('note_public', $object->note_public, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%');
-            print $doleditor->Create(1);
-
-            print "</td></tr>";
-
-            // Private note
-            if (empty($user->socid))
-            {
-                print '<tr><td class="tdtop">'.$langs->trans("NotePrivate").'</td>';
-                print '<td>';
-
-                $doleditor = new DolEditor('note_private', $object->note_private, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%');
-                print $doleditor->Create(1);
-
-                print "</td></tr>";
-            }
-
-            // Other attributes
-            $parameters = array();
-            $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-            print $hookmanager->resPrint;
-
-            print '</table>';
-
-            print '<br><div class="center">';
+	$result = $object->fetch($id);
+	if ($result > 0)
+	{
+		$head = trip_prepare_head($object);
+
+		dol_fiche_head($head, 'card', $langs->trans("TripCard"), 0, 'trip');
+
+		if ($action == 'edit' && $user->rights->deplacement->creer)
+		{
+			//WYSIWYG Editor
+			require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+
+			$soc = new Societe($db);
+			if ($object->socid)
+			{
+				$soc->fetch($object->socid);
+			}
+
+			print '<form name="update" action="'.$_SERVER["PHP_SELF"].'" method="POST">'."\n";
+			print '<input type="hidden" name="token" value="'.newToken().'">';
+			print '<input type="hidden" name="action" value="update">';
+			print '<input type="hidden" name="id" value="'.$id.'">';
+
+			print '<table class="border centpercent">';
+
+			// Ref
+			print "<tr>";
+			print '<td class="titlefield">'.$langs->trans("Ref").'</td><td>';
+			print $object->ref;
+			print '</td></tr>';
+
+			// Type
+			print "<tr>";
+			print '<td class="fieldrequired">'.$langs->trans("Type").'</td><td>';
+			$form->select_type_fees(GETPOST('type', 'int') ?GETPOST('type', 'int') : $object->type, 'type', 0);
+			print '</td></tr>';
+
+			// Who
+			print "<tr>";
+			print '<td class="fieldrequired">'.$langs->trans("Person").'</td><td>';
+			print $form->select_dolusers(GETPOST('fk_user', 'int') ?GETPOST('fk_user', 'int') : $object->fk_user, 'fk_user', 0, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
+			print '</td></tr>';
+
+			// Date
+			print '<tr><td class="fieldrequired">'.$langs->trans("Date").'</td><td>';
+			print $form->selectDate($object->date, '', 0, 0, 0, 'update', 1, 0);
+			print '</td></tr>';
+
+			// Km
+			print '<tr><td class="fieldrequired">'.$langs->trans("FeesKilometersOrAmout").'</td><td>';
+			print '<input name="km" class="flat" size="10" value="'.$object->km.'">';
+			print '</td></tr>';
+
+			// Where
+			print "<tr>";
+			print '<td>'.$langs->trans("CompanyVisited").'</td><td>';
+			print $form->select_company($soc->id, 'socid', '', 1);
+			print '</td></tr>';
+
+			// Public note
+			print '<tr><td class="tdtop">'.$langs->trans("NotePublic").'</td>';
+			print '<td>';
+
+			$doleditor = new DolEditor('note_public', $object->note_public, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%');
+			print $doleditor->Create(1);
+
+			print "</td></tr>";
+
+			// Private note
+			if (empty($user->socid))
+			{
+				print '<tr><td class="tdtop">'.$langs->trans("NotePrivate").'</td>';
+				print '<td>';
+
+				$doleditor = new DolEditor('note_private', $object->note_private, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%');
+				print $doleditor->Create(1);
+
+				print "</td></tr>";
+			}
+
+			// Other attributes
+			$parameters = array();
+			$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+			print $hookmanager->resPrint;
+
+			print '</table>';
+
+			print '<br><div class="center">';
 			print '<input type="submit" class="button" value="'.$langs->trans("Save").'">';
 			print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-            print '<input type="submit" name="cancel" class="button" value="'.$langs->trans("Cancel").'">';
-            print '</div>';
+			print '<input type="submit" name="cancel" class="button" value="'.$langs->trans("Cancel").'">';
+			print '</div>';
 
-            print '</form>';
+			print '</form>';
 
-            print '</div>';
-        } else {
-            /*
+			print '</div>';
+		} else {
+			/*
              * Confirm delete trip
              */
-            if ($action == 'delete')
-            {
-                print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteTrip"), $langs->trans("ConfirmDeleteTrip"), "confirm_delete");
-            }
-
-            $soc = new Societe($db);
-            if ($object->socid) $soc->fetch($object->socid);
-
-            print '<table class="border centpercent">';
-
-            $linkback = '<a href="'.DOL_URL_ROOT.'/compta/deplacement/list.php'.(!empty($socid) ? '?socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
-
-            // Ref
-            print '<tr><td width="25%">'.$langs->trans("Ref").'</td><td>';
-            print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', '');
-            print '</td></tr>';
-
-	        $form->load_cache_types_fees();
-
-	        // Type
-            print '<tr><td>';
-            print $form->editfieldkey("Type", 'type', $langs->trans($object->type), $object, $user->rights->deplacement->creer, 'select:types_fees');
-            print '</td><td>';
-            print $form->editfieldval("Type", 'type', $form->cache_types_fees[$object->type], $object, $user->rights->deplacement->creer, 'select:types_fees');
-            print '</td></tr>';
-
-            // Who
-            print '<tr><td>'.$langs->trans("Person").'</td><td>';
-            $userfee = new User($db);
-            $userfee->fetch($object->fk_user);
-            print $userfee->getNomUrl(1);
-            print '</td></tr>';
-
-            // Date
-            print '<tr><td>';
-            print $form->editfieldkey("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker');
-            print '</td><td>';
-            print $form->editfieldval("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker');
-            print '</td></tr>';
-
-            // Km/Price
-            print '<tr><td class="tdtop">';
-            print $form->editfieldkey("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6');
-            print '</td><td>';
-            print $form->editfieldval("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6');
-            print "</td></tr>";
-
-            // Where
-            print '<tr><td>'.$langs->trans("CompanyVisited").'</td>';
-            print '<td>';
-            if ($soc->id) print $soc->getNomUrl(1);
-            print '</td></tr>';
-
-            // Project
-            if (!empty($conf->projet->enabled))
-            {
-                $langs->load('projects');
-                print '<tr>';
-                print '<td>';
-
-                print '<table class="nobordernopadding" width="100%"><tr><td>';
-                print $langs->trans('Project');
-                print '</td>';
-                if ($action != 'classify' && $user->rights->deplacement->creer)
-                {
-                    print '<td class="right"><a href="'.$_SERVER["PHP_SELF"].'?action=classify&amp;id='.$object->id.'">';
-                    print img_edit($langs->trans('SetProject'), 1);
-                    print '</a></td>';
-                }
-                print '</tr></table>';
-                print '</td><td colspan="3">';
-                if ($action == 'classify')
-                {
-                    $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1);
-                } else {
-                    $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0);
-                }
-                print '</td>';
-                print '</tr>';
-            }
-
-            // Statut
-            print '<tr><td>'.$langs->trans("Status").'</td><td>'.$object->getLibStatut(4).'</td></tr>';
-
-        	// Other attributes
-        	$parameters = array('socid'=>$object->id);
-        	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
-
-            print "</table><br>";
-
-            // Notes
-            $blocname = 'notes';
-            $title = $langs->trans('Notes');
-            include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
-
-            print '</div>';
-
-            /*
+			if ($action == 'delete')
+			{
+				print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteTrip"), $langs->trans("ConfirmDeleteTrip"), "confirm_delete");
+			}
+
+			$soc = new Societe($db);
+			if ($object->socid) $soc->fetch($object->socid);
+
+			print '<table class="border centpercent">';
+
+			$linkback = '<a href="'.DOL_URL_ROOT.'/compta/deplacement/list.php'.(!empty($socid) ? '?socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+			// Ref
+			print '<tr><td width="25%">'.$langs->trans("Ref").'</td><td>';
+			print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', '');
+			print '</td></tr>';
+
+			$form->load_cache_types_fees();
+
+			// Type
+			print '<tr><td>';
+			print $form->editfieldkey("Type", 'type', $langs->trans($object->type), $object, $user->rights->deplacement->creer, 'select:types_fees');
+			print '</td><td>';
+			print $form->editfieldval("Type", 'type', $form->cache_types_fees[$object->type], $object, $user->rights->deplacement->creer, 'select:types_fees');
+			print '</td></tr>';
+
+			// Who
+			print '<tr><td>'.$langs->trans("Person").'</td><td>';
+			$userfee = new User($db);
+			$userfee->fetch($object->fk_user);
+			print $userfee->getNomUrl(1);
+			print '</td></tr>';
+
+			// Date
+			print '<tr><td>';
+			print $form->editfieldkey("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker');
+			print '</td><td>';
+			print $form->editfieldval("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker');
+			print '</td></tr>';
+
+			// Km/Price
+			print '<tr><td class="tdtop">';
+			print $form->editfieldkey("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6');
+			print '</td><td>';
+			print $form->editfieldval("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6');
+			print "</td></tr>";
+
+			// Where
+			print '<tr><td>'.$langs->trans("CompanyVisited").'</td>';
+			print '<td>';
+			if ($soc->id) print $soc->getNomUrl(1);
+			print '</td></tr>';
+
+			// Project
+			if (!empty($conf->projet->enabled))
+			{
+				$langs->load('projects');
+				print '<tr>';
+				print '<td>';
+
+				print '<table class="nobordernopadding" width="100%"><tr><td>';
+				print $langs->trans('Project');
+				print '</td>';
+				if ($action != 'classify' && $user->rights->deplacement->creer)
+				{
+					print '<td class="right"><a href="'.$_SERVER["PHP_SELF"].'?action=classify&amp;id='.$object->id.'">';
+					print img_edit($langs->trans('SetProject'), 1);
+					print '</a></td>';
+				}
+				print '</tr></table>';
+				print '</td><td colspan="3">';
+				if ($action == 'classify')
+				{
+					$form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1);
+				} else {
+					$form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0);
+				}
+				print '</td>';
+				print '</tr>';
+			}
+
+			// Statut
+			print '<tr><td>'.$langs->trans("Status").'</td><td>'.$object->getLibStatut(4).'</td></tr>';
+
+			// Other attributes
+			$parameters = array('socid'=>$object->id);
+			include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
+
+			print "</table><br>";
+
+			// Notes
+			$blocname = 'notes';
+			$title = $langs->trans('Notes');
+			include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
+
+			print '</div>';
+
+			/*
              * Barre d'actions
              */
 
-            print '<div class="tabsAction">';
-
-            if ($object->statut < Deplacement::STATUS_REFUNDED) 	// if not refunded
-            {
-	            if ($user->rights->deplacement->creer)
-	            {
-	                print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$id.'">'.$langs->trans('Modify').'</a>';
-	            } else {
-	                print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans('Modify').'</a>';
-	            }
-            }
-
-            if ($object->statut == Deplacement::STATUS_DRAFT) 	// if draft
-            {
-                if ($user->rights->deplacement->creer)
-                {
-                    print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=validate&id='.$id.'">'.$langs->trans('Validate').'</a>';
-                } else {
-                    print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans('Validate').'</a>';
-                }
-            }
-
-            if ($object->statut == Deplacement::STATUS_VALIDATED) 	// if validated
-            {
-                if ($user->rights->deplacement->creer)
-                {
-                    print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=classifyrefunded&id='.$id.'">'.$langs->trans('ClassifyRefunded').'</a>';
-                } else {
-                    print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans('ClassifyRefunded').'</a>';
-                }
-            }
-
-            if ($user->rights->deplacement->supprimer)
-            {
-                print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$id.'">'.$langs->trans('Delete').'</a>';
-            } else {
-                print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans('Delete').'</a>';
-            }
-
-            print '</div>';
-        }
-    } else {
-        dol_print_error($db);
-    }
+			print '<div class="tabsAction">';
+
+			if ($object->statut < Deplacement::STATUS_REFUNDED) 	// if not refunded
+			{
+				if ($user->rights->deplacement->creer)
+				{
+					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&id='.$id.'">'.$langs->trans('Modify').'</a>';
+				} else {
+					print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans('Modify').'</a>';
+				}
+			}
+
+			if ($object->statut == Deplacement::STATUS_DRAFT) 	// if draft
+			{
+				if ($user->rights->deplacement->creer)
+				{
+					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=validate&id='.$id.'">'.$langs->trans('Validate').'</a>';
+				} else {
+					print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans('Validate').'</a>';
+				}
+			}
+
+			if ($object->statut == Deplacement::STATUS_VALIDATED) 	// if validated
+			{
+				if ($user->rights->deplacement->creer)
+				{
+					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=classifyrefunded&id='.$id.'">'.$langs->trans('ClassifyRefunded').'</a>';
+				} else {
+					print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans('ClassifyRefunded').'</a>';
+				}
+			}
+
+			if ($user->rights->deplacement->supprimer)
+			{
+				print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$id.'">'.$langs->trans('Delete').'</a>';
+			} else {
+				print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans('Delete').'</a>';
+			}
+
+			print '</div>';
+		}
+	} else {
+		dol_print_error($db);
+	}
 }
 
 // End of page

+ 2 - 2
htdocs/contact/list.php

@@ -165,7 +165,7 @@ foreach ($object->fields as $key => $val)
 }
 
 // Add none object fields for "search in all"
-if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))	{
+if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) {
 	$fieldstosearchall['s.nom'] = "ThirdParty";
 }
 
@@ -186,7 +186,7 @@ foreach ($object->fields as $key => $val) {
 
 // Add none object fields to fields for list
 $arrayfields['country.code_iso'] = array('label'=>"Country", 'position'=>22, 'checked'=>0);
-if (empty($conf->global->SOCIETE_DISABLE_CONTACTS))	{
+if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) {
 	$arrayfields['s.nom'] = array('label'=>"ThirdParty", 'position'=>25, 'checked'=>1);
 }
 

+ 422 - 422
htdocs/core/boxes/box_activity.php

@@ -30,413 +30,413 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php';
  */
 class box_activity extends ModeleBoxes
 {
-    public $boxcode = "activity";
-    public $boximg = "object_bill";
-    public $boxlabel = 'BoxGlobalActivity';
-    public $depends = array("facture");
-
-    /**
-     * @var DoliDB Database handler.
-     */
-    public $db;
-
-    public $param;
-    public $enabled = 1;
-
-    public $info_box_head = array();
-    public $info_box_contents = array();
-
-
-    /**
-     *  Constructor
-     *
-     *  @param  DoliDB  $db         Database handler
-     *  @param  string  $param      More parameters
-     */
-    public function __construct($db, $param)
-    {
-        global $conf, $user;
-
-        $this->db = $db;
-
-        // FIXME: Pb into some status
-        $this->enabled = ($conf->global->MAIN_FEATURES_LEVEL); // Not enabled by default due to bugs (see previous comments)
-
-        $this->hidden = !((!empty($conf->facture->enabled) && $user->rights->facture->lire)
-            || (!empty($conf->commande->enabled) && $user->rights->commande->lire)
-            || (!empty($conf->propal->enabled) && $user->rights->propale->lire)
-            );
-    }
-
-    /**
-     *  Charge les donnees en memoire pour affichage ulterieur
-     *
-     *  @param  int     $max        Maximum number of records to load
-     *  @return void
-     */
-    public function loadBox($max = 5)
-    {
-        global $conf, $user, $langs;
-
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
-        include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-
-        $totalnb = 0;
-        $line = 0;
-        $cachetime = 3600;
-        $fileid = '-e'.$conf->entity.'-u'.$user->id.'-s'.$user->socid.'-r'.($user->rights->societe->client->voir ? '1' : '0').'.cache';
-        $now = dol_now();
-        $nbofperiod = 3;
-
-        if (!empty($conf->global->MAIN_BOX_ACTIVITY_DURATION)) $nbofperiod = $conf->global->MAIN_BOX_ACTIVITY_DURATION;
-        $textHead = $langs->trans("Activity").' - '.$langs->trans("LastXMonthRolling", $nbofperiod);
-        $this->info_box_head = array(
-            'text' => $textHead,
-            'limit'=> dol_strlen($textHead),
-        );
-
-        // compute the year limit to show
-        $tmpdate = dol_time_plus_duree(dol_now(), -1 * $nbofperiod, "m");
-
-
-        // list the summary of the propals
-        if (!empty($conf->propal->enabled) && $user->rights->propale->lire)
-        {
-        	include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
-        	$propalstatic = new Propal($this->db);
-
-        	$cachedir = DOL_DATA_ROOT.'/propale/temp';
-        	$filename = '/boxactivity-propal'.$fileid;
-        	$refresh = dol_cache_refresh($cachedir, $filename, $cachetime);
-        	$data = array();
-        	if ($refresh)
-        	{
-        		$sql = "SELECT p.fk_statut, SUM(p.total) as Mnttot, COUNT(*) as nb";
-        		$sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p";
-        		if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-        		$sql .= ")";
-        		$sql .= " WHERE p.entity IN (".getEntity('propal').")";
-        		$sql .= " AND p.fk_soc = s.rowid";
-        		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 .= " AND p.datep >= '".$this->db->idate($tmpdate)."'";
-        		$sql .= " AND p.date_cloture IS NULL"; // just unclosed
-        		$sql .= " GROUP BY p.fk_statut";
-        		$sql .= " ORDER BY p.fk_statut DESC";
-
-        		$result = $this->db->query($sql);
-        		if ($result)
-        		{
-        			$num = $this->db->num_rows($result);
-
-        			$j = 0;
-        			while ($j < $num) {
-        				$data[$j] = $this->db->fetch_object($result);
-        				$j++;
-        			}
-        			if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) {
-        				dol_filecache($cachedir, $filename, $data);
-        			}
-        			$this->db->free($result);
-        		} else {
-        			dol_print_error($this->db);
-        		}
-        	} else {
-        		$data = dol_readcachefile($cachedir, $filename);
-        	}
-
-        	if (!empty($data))
-        	{
-        		$j = 0;
-        		while ($j < count($data))
-        		{
-        			$this->info_box_contents[$line][0] = array(
-                        'td' => 'class="left" width="16"',
-                        'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&amp;leftmenu=propals&amp;search_status=".$data[$j]->fk_statut,
-                        'tooltip' => $langs->trans("Proposals")."&nbsp;".$propalstatic->LibStatut($data[$j]->fk_statut, 0),
-                        'logo' => 'object_propal'
-        			);
-
-        			$this->info_box_contents[$line][1] = array(
-                        'td' => '',
-                        'text' => $langs->trans("Proposals")."&nbsp;".$propalstatic->LibStatut($data[$j]->fk_statut, 0),
-        			);
-
-        			$this->info_box_contents[$line][2] = array(
-                        'td' => 'class="right"',
-                        'text' => $data[$j]->nb,
-                        'tooltip' => $langs->trans("Proposals")."&nbsp;".$propalstatic->LibStatut($data[$j]->fk_statut, 0),
-                        'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&amp;leftmenu=propals&amp;search_status=".$data[$j]->fk_statut,
-        			);
-        			$totalnb += $data[$j]->nb;
-
-        			$this->info_box_contents[$line][3] = array(
-                        'td' => 'class="nowraponall right"',
-                        'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency),
-        			);
-        			$this->info_box_contents[$line][4] = array(
-                        'td' => 'class="right" width="18"',
-                        'text' => $propalstatic->LibStatut($data[$j]->fk_statut, 3),
-        			);
-
-        			$line++;
-        			$j++;
-        		}
-        	}
-        }
-
-        // list the summary of the orders
-        if (!empty($conf->commande->enabled) && $user->rights->commande->lire) {
-            include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
-            $commandestatic = new Commande($this->db);
-
-            $langs->load("orders");
-
-            $cachedir = DOL_DATA_ROOT.'/commande/temp';
-            $filename = '/boxactivity-order'.$fileid;
-            $refresh = dol_cache_refresh($cachedir, $filename, $cachetime);
-            $data = array();
-
-            if ($refresh) {
-                $sql = "SELECT c.fk_statut, sum(c.total_ttc) as Mnttot, count(*) as nb";
-                $sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
-                if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-                $sql .= ")";
-        		$sql .= " WHERE c.entity IN (".getEntity('commande').")";
-                $sql .= " AND c.fk_soc = s.rowid";
-                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 .= " AND c.date_commande >= '".$this->db->idate($tmpdate)."'";
-                $sql .= " GROUP BY c.fk_statut";
-                $sql .= " ORDER BY c.fk_statut DESC";
-
-                $result = $this->db->query($sql);
-                if ($result) {
-                    $num = $this->db->num_rows($result);
-                    $j = 0;
-                    while ($j < $num) {
-                        $data[$j] = $this->db->fetch_object($result);
-                        $j++;
-                    }
-                    if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) {
-                        dol_filecache($cachedir, $filename, $data);
-                    }
-                    $this->db->free($result);
-                } else {
-                    dol_print_error($this->db);
-                }
-            } else {
-                $data = dol_readcachefile($cachedir, $filename);
-            }
-
-            if (!empty($data)) {
-                $j = 0;
-                while ($j < count($data)) {
-                    $this->info_box_contents[$line][0] = array(
-                        'td' => 'class="left" width="16"',
-                        'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&amp;leftmenu=orders&amp;search_status=".$data[$j]->fk_statut,
-                        'tooltip' => $langs->trans("Orders")."&nbsp;".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0),
-                        'logo' => 'object_order',
-                    );
-
-                    $this->info_box_contents[$line][1] = array(
-                        'td' => '',
-                        'text' =>$langs->trans("Orders")."&nbsp;".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0),
-                    );
-
-                    $this->info_box_contents[$line][2] = array(
-                        'td' => 'class="right"',
-                        'text' => $data[$j]->nb,
-                        'tooltip' => $langs->trans("Orders")."&nbsp;".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0),
-                        'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&amp;leftmenu=orders&amp;search_status=".$data[$j]->fk_statut,
-                    );
-                    $totalnb += $data[$j]->nb;
-
-                    $this->info_box_contents[$line][3] = array(
-                        'td' => 'class="nowraponall right"',
-                        'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency),
-                    );
-                    $this->info_box_contents[$line][4] = array(
-                        'td' => 'class="right" width="18"',
-                        'text' => $commandestatic->LibStatut($data[$j]->fk_statut, 0, 3),
-                    );
-
-                    $line++;
-                    $j++;
-                }
-            }
-        }
-
-
-        // list the summary of the bills
-        if (!empty($conf->facture->enabled) && $user->rights->facture->lire)
-        {
-        	include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
-        	$facturestatic = new Facture($this->db);
-
-        	// part 1
-        	$cachedir = DOL_DATA_ROOT.'/facture/temp';
-        	$filename = '/boxactivity-invoice'.$fileid;
-
-        	$refresh = dol_cache_refresh($cachedir, $filename, $cachetime);
-        	$data = array();
-        	if ($refresh)
-        	{
-        		$sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb";
-        		$sql .= " FROM (".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f";
-        		if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-        		$sql .= ")";
-        		$sql .= " WHERE f.entity IN (".getEntity('invoice').')';
-        		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 .= " AND f.fk_soc = s.rowid";
-        		$sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=1";
-        		$sql .= " GROUP BY f.fk_statut";
-        		$sql .= " ORDER BY f.fk_statut DESC";
-
-        		$result = $this->db->query($sql);
-        		if ($result) {
-        			$num = $this->db->num_rows($result);
-        			$j = 0;
-        			while ($j < $num) {
-        				$data[$j] = $this->db->fetch_object($result);
-        				$j++;
-        			}
-        			if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) {
-        				dol_filecache($cachedir, $filename, $data);
-        			}
-        			$this->db->free($result);
-        		} else {
-        			dol_print_error($this->db);
-        		}
-        	} else {
-        		$data = dol_readcachefile($cachedir, $filename);
-        	}
-
-        	if (!empty($data)) {
-        		$j = 0;
-        		while ($j < count($data)) {
-        			$billurl = "search_status=2&amp;paye=1&amp;year=".$data[$j]->annee;
-        			$this->info_box_contents[$line][0] = array(
-                        'td' => 'class="left" width="16"',
-                        'tooltip' => $langs->trans('Bills').'&nbsp;'.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0),
-                        'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&amp;mainmenu=accountancy&amp;leftmenu=customers_bills",
-                        'logo' => 'bill',
-        			);
-
-        			$this->info_box_contents[$line][1] = array(
-                        'td' => '',
-                        'text' => $langs->trans("Bills")."&nbsp;".$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0)." ".$data[$j]->annee,
-        			);
-
-        			$this->info_box_contents[$line][2] = array(
-                        'td' => 'class="right"',
-                        'tooltip' => $langs->trans('Bills').'&nbsp;'.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0),
-                        'text' => $data[$j]->nb,
-                        'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&amp;mainmenu=accountancy&amp;leftmenu=customers_bills",
-        			);
-
-        			$this->info_box_contents[$line][3] = array(
-                        'td' => 'class="nowraponall right"',
-                        'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency)
-        			);
-
-        			// We add only for the current year
-       				$totalnb += $data[$j]->nb;
-
-        			$this->info_box_contents[$line][4] = array(
-                        'td' => 'class="right" width="18"',
-                        'text' => $facturestatic->LibStatut(1, $data[$j]->fk_statut, 3),
-        			);
-        			$line++;
-        			$j++;
-        		}
-        		if (count($data) == 0)
-        			$this->info_box_contents[$line][0] = array(
-                        'td' => 'class="center"',
-                        'text'=>$langs->trans("NoRecordedInvoices"),
-        			);
-        	}
-
-        	// part 2
-        	$cachedir = DOL_DATA_ROOT.'/facture/temp';
-        	$filename = '/boxactivity-invoice2'.$fileid;
-
-        	$refresh = dol_cache_refresh($cachedir, $filename, $cachetime);
-
-        	$data = array();
-        	if ($refresh) {
-        		$sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb";
-        		$sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f";
-        		$sql .= " WHERE f.entity IN (".getEntity('invoice').')';
-        		$sql .= " AND f.fk_soc = s.rowid";
-        		$sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=0";
-        		$sql .= " GROUP BY f.fk_statut";
-        		$sql .= " ORDER BY f.fk_statut DESC";
-
-        		$result = $this->db->query($sql);
-        		if ($result) {
-        			$num = $this->db->num_rows($result);
-        			$j = 0;
-        			while ($j < $num) {
-        				$data[$j] = $this->db->fetch_object($result);
-        				$j++;
-        			}
-        			if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) {
-        				dol_filecache($cachedir, $filename, $data);
-        			}
-        			$this->db->free($result);
-        		} else {
-        			dol_print_error($this->db);
-        		}
-        	} else {
-        		$data = dol_readcachefile($cachedir, $filename);
-        	}
-
-        	if (!empty($data)) {
-        		$alreadypaid = -1;
-
-        		$j = 0;
-        		while ($j < count($data)) {
-        			$billurl = "search_status=".$data[$j]->fk_statut."&amp;paye=0";
-        			$this->info_box_contents[$line][0] = array(
-                        'td' => 'class="left" width="16"',
-                        'tooltip' => $langs->trans('Bills').'&nbsp;'.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0),
-                        'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&amp;mainmenu=accountancy&amp;leftmenu=customers_bills",
-                        'logo' => 'bill',
-        			);
-
-        			$this->info_box_contents[$line][1] = array(
-                        'td' => '',
-                        'text' => $langs->trans("Bills")."&nbsp;".$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0),
-        			);
-
-        			$this->info_box_contents[$line][2] = array(
-                        'td' => 'class="right"',
-                        'text' => $data[$j]->nb,
-                        'tooltip' => $langs->trans('Bills').'&nbsp;'.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0),
-                        'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&amp;mainmenu=accountancy&amp;leftmenu=customers_bills",
-        			);
-        			$totalnb += $data[$j]->nb;
-        			$this->info_box_contents[$line][3] = array(
-                        'td' => 'class="nowraponall right"',
-                        'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency),
-        			);
-        			$this->info_box_contents[$line][4] = array(
-                        'td' => 'class="right" width="18"',
-                        'text' => $facturestatic->LibStatut(0, $data[$j]->fk_statut, 3, $alreadypaid),
-        			);
-        			$line++;
-        			$j++;
-        		}
-        		if (count($data) == 0) {
-        			$this->info_box_contents[$line][0] = array(
-                        'td' => 'class="center"',
-                        'text'=>$langs->trans("NoRecordedInvoices"),
-                    );
-                }
-        	}
-        }
+	public $boxcode = "activity";
+	public $boximg = "object_bill";
+	public $boxlabel = 'BoxGlobalActivity';
+	public $depends = array("facture");
+
+	/**
+	 * @var DoliDB Database handler.
+	 */
+	public $db;
+
+	public $param;
+	public $enabled = 1;
+
+	public $info_box_head = array();
+	public $info_box_contents = array();
+
+
+	/**
+	 *  Constructor
+	 *
+	 *  @param  DoliDB  $db         Database handler
+	 *  @param  string  $param      More parameters
+	 */
+	public function __construct($db, $param)
+	{
+		global $conf, $user;
+
+		$this->db = $db;
+
+		// FIXME: Pb into some status
+		$this->enabled = ($conf->global->MAIN_FEATURES_LEVEL); // Not enabled by default due to bugs (see previous comments)
+
+		$this->hidden = !((!empty($conf->facture->enabled) && $user->rights->facture->lire)
+			|| (!empty($conf->commande->enabled) && $user->rights->commande->lire)
+			|| (!empty($conf->propal->enabled) && $user->rights->propale->lire)
+			);
+	}
+
+	/**
+	 *  Charge les donnees en memoire pour affichage ulterieur
+	 *
+	 *  @param  int     $max        Maximum number of records to load
+	 *  @return void
+	 */
+	public function loadBox($max = 5)
+	{
+		global $conf, $user, $langs;
+
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+		$totalnb = 0;
+		$line = 0;
+		$cachetime = 3600;
+		$fileid = '-e'.$conf->entity.'-u'.$user->id.'-s'.$user->socid.'-r'.($user->rights->societe->client->voir ? '1' : '0').'.cache';
+		$now = dol_now();
+		$nbofperiod = 3;
+
+		if (!empty($conf->global->MAIN_BOX_ACTIVITY_DURATION)) $nbofperiod = $conf->global->MAIN_BOX_ACTIVITY_DURATION;
+		$textHead = $langs->trans("Activity").' - '.$langs->trans("LastXMonthRolling", $nbofperiod);
+		$this->info_box_head = array(
+			'text' => $textHead,
+			'limit'=> dol_strlen($textHead),
+		);
+
+		// compute the year limit to show
+		$tmpdate = dol_time_plus_duree(dol_now(), -1 * $nbofperiod, "m");
+
+
+		// list the summary of the propals
+		if (!empty($conf->propal->enabled) && $user->rights->propale->lire)
+		{
+			include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
+			$propalstatic = new Propal($this->db);
+
+			$cachedir = DOL_DATA_ROOT.'/propale/temp';
+			$filename = '/boxactivity-propal'.$fileid;
+			$refresh = dol_cache_refresh($cachedir, $filename, $cachetime);
+			$data = array();
+			if ($refresh)
+			{
+				$sql = "SELECT p.fk_statut, SUM(p.total) as Mnttot, COUNT(*) as nb";
+				$sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p";
+				if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+				$sql .= ")";
+				$sql .= " WHERE p.entity IN (".getEntity('propal').")";
+				$sql .= " AND p.fk_soc = s.rowid";
+				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 .= " AND p.datep >= '".$this->db->idate($tmpdate)."'";
+				$sql .= " AND p.date_cloture IS NULL"; // just unclosed
+				$sql .= " GROUP BY p.fk_statut";
+				$sql .= " ORDER BY p.fk_statut DESC";
+
+				$result = $this->db->query($sql);
+				if ($result)
+				{
+					$num = $this->db->num_rows($result);
+
+					$j = 0;
+					while ($j < $num) {
+						$data[$j] = $this->db->fetch_object($result);
+						$j++;
+					}
+					if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) {
+						dol_filecache($cachedir, $filename, $data);
+					}
+					$this->db->free($result);
+				} else {
+					dol_print_error($this->db);
+				}
+			} else {
+				$data = dol_readcachefile($cachedir, $filename);
+			}
+
+			if (!empty($data))
+			{
+				$j = 0;
+				while ($j < count($data))
+				{
+					$this->info_box_contents[$line][0] = array(
+						'td' => 'class="left" width="16"',
+						'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&amp;leftmenu=propals&amp;search_status=".$data[$j]->fk_statut,
+						'tooltip' => $langs->trans("Proposals")."&nbsp;".$propalstatic->LibStatut($data[$j]->fk_statut, 0),
+						'logo' => 'object_propal'
+					);
+
+					$this->info_box_contents[$line][1] = array(
+						'td' => '',
+						'text' => $langs->trans("Proposals")."&nbsp;".$propalstatic->LibStatut($data[$j]->fk_statut, 0),
+					);
+
+					$this->info_box_contents[$line][2] = array(
+						'td' => 'class="right"',
+						'text' => $data[$j]->nb,
+						'tooltip' => $langs->trans("Proposals")."&nbsp;".$propalstatic->LibStatut($data[$j]->fk_statut, 0),
+						'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&amp;leftmenu=propals&amp;search_status=".$data[$j]->fk_statut,
+					);
+					$totalnb += $data[$j]->nb;
+
+					$this->info_box_contents[$line][3] = array(
+						'td' => 'class="nowraponall right"',
+						'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency),
+					);
+					$this->info_box_contents[$line][4] = array(
+						'td' => 'class="right" width="18"',
+						'text' => $propalstatic->LibStatut($data[$j]->fk_statut, 3),
+					);
+
+					$line++;
+					$j++;
+				}
+			}
+		}
+
+		// list the summary of the orders
+		if (!empty($conf->commande->enabled) && $user->rights->commande->lire) {
+			include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
+			$commandestatic = new Commande($this->db);
+
+			$langs->load("orders");
+
+			$cachedir = DOL_DATA_ROOT.'/commande/temp';
+			$filename = '/boxactivity-order'.$fileid;
+			$refresh = dol_cache_refresh($cachedir, $filename, $cachetime);
+			$data = array();
+
+			if ($refresh) {
+				$sql = "SELECT c.fk_statut, sum(c.total_ttc) as Mnttot, count(*) as nb";
+				$sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c";
+				if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+				$sql .= ")";
+				$sql .= " WHERE c.entity IN (".getEntity('commande').")";
+				$sql .= " AND c.fk_soc = s.rowid";
+				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 .= " AND c.date_commande >= '".$this->db->idate($tmpdate)."'";
+				$sql .= " GROUP BY c.fk_statut";
+				$sql .= " ORDER BY c.fk_statut DESC";
+
+				$result = $this->db->query($sql);
+				if ($result) {
+					$num = $this->db->num_rows($result);
+					$j = 0;
+					while ($j < $num) {
+						$data[$j] = $this->db->fetch_object($result);
+						$j++;
+					}
+					if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) {
+						dol_filecache($cachedir, $filename, $data);
+					}
+					$this->db->free($result);
+				} else {
+					dol_print_error($this->db);
+				}
+			} else {
+				$data = dol_readcachefile($cachedir, $filename);
+			}
+
+			if (!empty($data)) {
+				$j = 0;
+				while ($j < count($data)) {
+					$this->info_box_contents[$line][0] = array(
+						'td' => 'class="left" width="16"',
+						'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&amp;leftmenu=orders&amp;search_status=".$data[$j]->fk_statut,
+						'tooltip' => $langs->trans("Orders")."&nbsp;".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0),
+						'logo' => 'object_order',
+					);
+
+					$this->info_box_contents[$line][1] = array(
+						'td' => '',
+						'text' =>$langs->trans("Orders")."&nbsp;".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0),
+					);
+
+					$this->info_box_contents[$line][2] = array(
+						'td' => 'class="right"',
+						'text' => $data[$j]->nb,
+						'tooltip' => $langs->trans("Orders")."&nbsp;".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0),
+						'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&amp;leftmenu=orders&amp;search_status=".$data[$j]->fk_statut,
+					);
+					$totalnb += $data[$j]->nb;
+
+					$this->info_box_contents[$line][3] = array(
+						'td' => 'class="nowraponall right"',
+						'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency),
+					);
+					$this->info_box_contents[$line][4] = array(
+						'td' => 'class="right" width="18"',
+						'text' => $commandestatic->LibStatut($data[$j]->fk_statut, 0, 3),
+					);
+
+					$line++;
+					$j++;
+				}
+			}
+		}
+
+
+		// list the summary of the bills
+		if (!empty($conf->facture->enabled) && $user->rights->facture->lire)
+		{
+			include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+			$facturestatic = new Facture($this->db);
+
+			// part 1
+			$cachedir = DOL_DATA_ROOT.'/facture/temp';
+			$filename = '/boxactivity-invoice'.$fileid;
+
+			$refresh = dol_cache_refresh($cachedir, $filename, $cachetime);
+			$data = array();
+			if ($refresh)
+			{
+				$sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb";
+				$sql .= " FROM (".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f";
+				if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+				$sql .= ")";
+				$sql .= " WHERE f.entity IN (".getEntity('invoice').')';
+				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 .= " AND f.fk_soc = s.rowid";
+				$sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=1";
+				$sql .= " GROUP BY f.fk_statut";
+				$sql .= " ORDER BY f.fk_statut DESC";
+
+				$result = $this->db->query($sql);
+				if ($result) {
+					$num = $this->db->num_rows($result);
+					$j = 0;
+					while ($j < $num) {
+						$data[$j] = $this->db->fetch_object($result);
+						$j++;
+					}
+					if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) {
+						dol_filecache($cachedir, $filename, $data);
+					}
+					$this->db->free($result);
+				} else {
+					dol_print_error($this->db);
+				}
+			} else {
+				$data = dol_readcachefile($cachedir, $filename);
+			}
+
+			if (!empty($data)) {
+				$j = 0;
+				while ($j < count($data)) {
+					$billurl = "search_status=2&amp;paye=1&amp;year=".$data[$j]->annee;
+					$this->info_box_contents[$line][0] = array(
+						'td' => 'class="left" width="16"',
+						'tooltip' => $langs->trans('Bills').'&nbsp;'.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0),
+						'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&amp;mainmenu=accountancy&amp;leftmenu=customers_bills",
+						'logo' => 'bill',
+					);
+
+					$this->info_box_contents[$line][1] = array(
+						'td' => '',
+						'text' => $langs->trans("Bills")."&nbsp;".$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0)." ".$data[$j]->annee,
+					);
+
+					$this->info_box_contents[$line][2] = array(
+						'td' => 'class="right"',
+						'tooltip' => $langs->trans('Bills').'&nbsp;'.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0),
+						'text' => $data[$j]->nb,
+						'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&amp;mainmenu=accountancy&amp;leftmenu=customers_bills",
+					);
+
+					$this->info_box_contents[$line][3] = array(
+						'td' => 'class="nowraponall right"',
+						'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency)
+					);
+
+					// We add only for the current year
+	   				$totalnb += $data[$j]->nb;
+
+					$this->info_box_contents[$line][4] = array(
+						'td' => 'class="right" width="18"',
+						'text' => $facturestatic->LibStatut(1, $data[$j]->fk_statut, 3),
+					);
+					$line++;
+					$j++;
+				}
+				if (count($data) == 0)
+					$this->info_box_contents[$line][0] = array(
+						'td' => 'class="center"',
+						'text'=>$langs->trans("NoRecordedInvoices"),
+					);
+			}
+
+			// part 2
+			$cachedir = DOL_DATA_ROOT.'/facture/temp';
+			$filename = '/boxactivity-invoice2'.$fileid;
+
+			$refresh = dol_cache_refresh($cachedir, $filename, $cachetime);
+
+			$data = array();
+			if ($refresh) {
+				$sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb";
+				$sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f";
+				$sql .= " WHERE f.entity IN (".getEntity('invoice').')';
+				$sql .= " AND f.fk_soc = s.rowid";
+				$sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=0";
+				$sql .= " GROUP BY f.fk_statut";
+				$sql .= " ORDER BY f.fk_statut DESC";
+
+				$result = $this->db->query($sql);
+				if ($result) {
+					$num = $this->db->num_rows($result);
+					$j = 0;
+					while ($j < $num) {
+						$data[$j] = $this->db->fetch_object($result);
+						$j++;
+					}
+					if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) {
+						dol_filecache($cachedir, $filename, $data);
+					}
+					$this->db->free($result);
+				} else {
+					dol_print_error($this->db);
+				}
+			} else {
+				$data = dol_readcachefile($cachedir, $filename);
+			}
+
+			if (!empty($data)) {
+				$alreadypaid = -1;
+
+				$j = 0;
+				while ($j < count($data)) {
+					$billurl = "search_status=".$data[$j]->fk_statut."&amp;paye=0";
+					$this->info_box_contents[$line][0] = array(
+						'td' => 'class="left" width="16"',
+						'tooltip' => $langs->trans('Bills').'&nbsp;'.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0),
+						'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&amp;mainmenu=accountancy&amp;leftmenu=customers_bills",
+						'logo' => 'bill',
+					);
+
+					$this->info_box_contents[$line][1] = array(
+						'td' => '',
+						'text' => $langs->trans("Bills")."&nbsp;".$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0),
+					);
+
+					$this->info_box_contents[$line][2] = array(
+						'td' => 'class="right"',
+						'text' => $data[$j]->nb,
+						'tooltip' => $langs->trans('Bills').'&nbsp;'.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0),
+						'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&amp;mainmenu=accountancy&amp;leftmenu=customers_bills",
+					);
+					$totalnb += $data[$j]->nb;
+					$this->info_box_contents[$line][3] = array(
+						'td' => 'class="nowraponall right"',
+						'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency),
+					);
+					$this->info_box_contents[$line][4] = array(
+						'td' => 'class="right" width="18"',
+						'text' => $facturestatic->LibStatut(0, $data[$j]->fk_statut, 3, $alreadypaid),
+					);
+					$line++;
+					$j++;
+				}
+				if (count($data) == 0) {
+					$this->info_box_contents[$line][0] = array(
+						'td' => 'class="center"',
+						'text'=>$langs->trans("NoRecordedInvoices"),
+					);
+				}
+			}
+		}
 
 		// Add the sum in the bottom of the boxes
 		$this->info_box_contents[$line][0] = array('tr' => 'class="liste_total_wrap"');
@@ -444,19 +444,19 @@ class box_activity extends ModeleBoxes
 		$this->info_box_contents[$line][2] = array('td' => 'class="liste_total right" ', 'text' => $totalnb);
 		$this->info_box_contents[$line][3] = array('td' => 'class="liste_total right" ', 'text' => '');
 		$this->info_box_contents[$line][4] = array('td' => 'class="liste_total right" ', 'text' => "");
-    }
-
-
-    /**
-     *  Method to show box
-     *
-     *  @param	array	$head       Array with properties of box title
-     *  @param  array	$contents   Array with properties of box lines
-     *  @param	int		$nooutput	No print, only return string
-     *  @return	string
-     */
-    public function showBox($head = null, $contents = null, $nooutput = 0)
-    {
-        return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput);
-    }
+	}
+
+
+	/**
+	 *  Method to show box
+	 *
+	 *  @param	array	$head       Array with properties of box title
+	 *  @param  array	$contents   Array with properties of box lines
+	 *  @param	int		$nooutput	No print, only return string
+	 *  @return	string
+	 */
+	public function showBox($head = null, $contents = null, $nooutput = 0)
+	{
+		return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput);
+	}
 }

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

@@ -40,199 +40,199 @@ abstract class CommonDocGenerator
 	 */
 	public $error = '';
 
-    /**
-     * @var string[]    Array of error strings
-     */
-    public $errors = array();
+	/**
+	 * @var string[]    Array of error strings
+	 */
+	public $errors = array();
 
 	/**
-     * @var DoliDB Database handler.
-     */
+	 * @var DoliDB Database handler.
+	 */
 	protected $db;
 
-    /**
-     * @var Extrafields object
-     */
+	/**
+	 * @var Extrafields object
+	 */
 	public $extrafieldsCache;
 
 	/**
 	 *	Constructor
 	 *
 	 *  @param		DoliDB		$db      Database handler
-	*/
-    public function __construct($db)
-    {
-        $this->db = $db;
-    }
-
-
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
-    /**
-     * Define array with couple substitution key => substitution value
-     *
-     * @param   User		$user           User
-     * @param   Translate	$outputlangs    Language object for output
-     * @return	array						Array of substitution key->code
-     */
-    public function get_substitutionarray_user($user, $outputlangs)
-    {
-        // phpcs:enable
-        global $conf;
-
-        $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo;
-
-        return array(
-            'myuser_lastname'=>$user->lastname,
-            'myuser_firstname'=>$user->firstname,
-            'myuser_fullname'=>$user->getFullName($outputlangs, 1),
-            'myuser_login'=>$user->login,
-            'myuser_phone'=>$user->office_phone,
-       		'myuser_address'=>$user->address,
-       		'myuser_zip'=>$user->zip,
-       		'myuser_town'=>$user->town,
-       		'myuser_country'=>$user->country,
-        	'myuser_country_code'=>$user->country_code,
-       		'myuser_state'=>$user->state,
-        	'myuser_state_code'=>$user->state_code,
-        	'myuser_fax'=>$user->office_fax,
-            'myuser_mobile'=>$user->user_mobile,
-            'myuser_email'=>$user->email,
-        	'myuser_logo'=>$logotouse,
-        	'myuser_job'=>$user->job,
-            'myuser_web'=>''	// url not exist in $user object
-        );
-    }
-
-
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
-    /**
-     * Define array with couple substitution key => substitution value
-     *
-     * @param   Societe		$mysoc			Object thirdparty
-     * @param   Translate	$outputlangs    Language object for output
-     * @return	array						Array of substitution key->code
-     */
-    public function get_substitutionarray_mysoc($mysoc, $outputlangs)
-    {
-        // phpcs:enable
-        global $conf;
-
-        if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code))
-        {
-            $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code);
-        }
-        if (empty($mysoc->country) && !empty($mysoc->country_code))
-        {
-        	$mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
-        }
-        if (empty($mysoc->state) && !empty($mysoc->state_code))
-        {
-        	$mysoc->state = getState($mysoc->state_code, 0);
-        }
-
-        $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small;
-
-        return array(
-            'mycompany_logo'=>$logotouse,
-            'mycompany_name'=>$mysoc->name,
-            'mycompany_email'=>$mysoc->email,
-            'mycompany_phone'=>$mysoc->phone,
-            'mycompany_fax'=>$mysoc->fax,
-            'mycompany_address'=>$mysoc->address,
-            'mycompany_zip'=>$mysoc->zip,
-            'mycompany_town'=>$mysoc->town,
-            'mycompany_country'=>$mysoc->country,
-            'mycompany_country_code'=>$mysoc->country_code,
-            'mycompany_state'=>$mysoc->state,
-            'mycompany_state_code'=>$mysoc->state_code,
-        	'mycompany_web'=>$mysoc->url,
-            'mycompany_juridicalstatus'=>$mysoc->forme_juridique,
-            'mycompany_managers'=>$mysoc->managers,
-            'mycompany_capital'=>$mysoc->capital,
-            'mycompany_barcode'=>$mysoc->barcode,
-            'mycompany_idprof1'=>$mysoc->idprof1,
-            'mycompany_idprof2'=>$mysoc->idprof2,
-            'mycompany_idprof3'=>$mysoc->idprof3,
-            'mycompany_idprof4'=>$mysoc->idprof4,
-            'mycompany_idprof5'=>$mysoc->idprof5,
-            'mycompany_idprof6'=>$mysoc->idprof6,
-        	'mycompany_vatnumber'=>$mysoc->tva_intra,
+	 */
+	public function __construct($db)
+	{
+		$this->db = $db;
+	}
+
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 * Define array with couple substitution key => substitution value
+	 *
+	 * @param   User		$user           User
+	 * @param   Translate	$outputlangs    Language object for output
+	 * @return	array						Array of substitution key->code
+	 */
+	public function get_substitutionarray_user($user, $outputlangs)
+	{
+		// phpcs:enable
+		global $conf;
+
+		$logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo;
+
+		return array(
+			'myuser_lastname'=>$user->lastname,
+			'myuser_firstname'=>$user->firstname,
+			'myuser_fullname'=>$user->getFullName($outputlangs, 1),
+			'myuser_login'=>$user->login,
+			'myuser_phone'=>$user->office_phone,
+	   		'myuser_address'=>$user->address,
+	   		'myuser_zip'=>$user->zip,
+	   		'myuser_town'=>$user->town,
+	   		'myuser_country'=>$user->country,
+			'myuser_country_code'=>$user->country_code,
+	   		'myuser_state'=>$user->state,
+			'myuser_state_code'=>$user->state_code,
+			'myuser_fax'=>$user->office_fax,
+			'myuser_mobile'=>$user->user_mobile,
+			'myuser_email'=>$user->email,
+			'myuser_logo'=>$logotouse,
+			'myuser_job'=>$user->job,
+			'myuser_web'=>''	// url not exist in $user object
+		);
+	}
+
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 * Define array with couple substitution key => substitution value
+	 *
+	 * @param   Societe		$mysoc			Object thirdparty
+	 * @param   Translate	$outputlangs    Language object for output
+	 * @return	array						Array of substitution key->code
+	 */
+	public function get_substitutionarray_mysoc($mysoc, $outputlangs)
+	{
+		// phpcs:enable
+		global $conf;
+
+		if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code))
+		{
+			$mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code);
+		}
+		if (empty($mysoc->country) && !empty($mysoc->country_code))
+		{
+			$mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
+		}
+		if (empty($mysoc->state) && !empty($mysoc->state_code))
+		{
+			$mysoc->state = getState($mysoc->state_code, 0);
+		}
+
+		$logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small;
+
+		return array(
+			'mycompany_logo'=>$logotouse,
+			'mycompany_name'=>$mysoc->name,
+			'mycompany_email'=>$mysoc->email,
+			'mycompany_phone'=>$mysoc->phone,
+			'mycompany_fax'=>$mysoc->fax,
+			'mycompany_address'=>$mysoc->address,
+			'mycompany_zip'=>$mysoc->zip,
+			'mycompany_town'=>$mysoc->town,
+			'mycompany_country'=>$mysoc->country,
+			'mycompany_country_code'=>$mysoc->country_code,
+			'mycompany_state'=>$mysoc->state,
+			'mycompany_state_code'=>$mysoc->state_code,
+			'mycompany_web'=>$mysoc->url,
+			'mycompany_juridicalstatus'=>$mysoc->forme_juridique,
+			'mycompany_managers'=>$mysoc->managers,
+			'mycompany_capital'=>$mysoc->capital,
+			'mycompany_barcode'=>$mysoc->barcode,
+			'mycompany_idprof1'=>$mysoc->idprof1,
+			'mycompany_idprof2'=>$mysoc->idprof2,
+			'mycompany_idprof3'=>$mysoc->idprof3,
+			'mycompany_idprof4'=>$mysoc->idprof4,
+			'mycompany_idprof5'=>$mysoc->idprof5,
+			'mycompany_idprof6'=>$mysoc->idprof6,
+			'mycompany_vatnumber'=>$mysoc->tva_intra,
 			'mycompany_object'=>$mysoc->object,
-            'mycompany_note_private'=>$mysoc->note_private,
-            //'mycompany_note_public'=>$mysoc->note_public,        // Only private not exists for "mysoc" but both for thirdparties
-        );
-    }
-
-
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
-    /**
-     * Define array with couple substitution key => substitution value
-     *
-     * @param	Societe		$object			Object
-     * @param   Translate	$outputlangs    Language object for output
-     * @param   string		$array_key	    Name of the key for return array
-     * @return	array						Array of substitution key->code
-     */
-    public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company')
-    {
-        // phpcs:enable
-        global $conf, $extrafields;
-
-        if (empty($object->country) && !empty($object->country_code))
-        {
-        	$object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code);
-        }
-        if (empty($object->state) && !empty($object->state_code))
-        {
-        	$object->state = getState($object->state_code, 0);
-        }
-
-        $array_thirdparty = array(
-            'company_name'=>$object->name,
-	        'company_name_alias' => $object->name_alias,
-            'company_email'=>$object->email,
-            'company_phone'=>$object->phone,
-            'company_fax'=>$object->fax,
-            'company_address'=>$object->address,
-            'company_zip'=>$object->zip,
-            'company_town'=>$object->town,
-            'company_country'=>$object->country,
-        	'company_country_code'=>$object->country_code,
-            'company_state'=>$object->state,
-        	'company_state_code'=>$object->state_code,
-        	'company_web'=>$object->url,
-            'company_barcode'=>$object->barcode,
-            'company_vatnumber'=>$object->tva_intra,
-            'company_customercode'=>$object->code_client,
-            'company_suppliercode'=>$object->code_fournisseur,
-            'company_customeraccountancycode'=>$object->code_compta,
-            'company_supplieraccountancycode'=>$object->code_compta_fournisseur,
-            'company_juridicalstatus'=>$object->forme_juridique,
-            'company_outstanding_limit'=>$object->outstanding_limit,
-            'company_capital'=>$object->capital,
-            'company_idprof1'=>$object->idprof1,
-            'company_idprof2'=>$object->idprof2,
-            'company_idprof3'=>$object->idprof3,
-            'company_idprof4'=>$object->idprof4,
-            'company_idprof5'=>$object->idprof5,
-            'company_idprof6'=>$object->idprof6,
-            'company_note_public'=>$object->note_public,
-            'company_note_private'=>$object->note_private,
-        	'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''),
-        	'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '')
-        );
-
-	    // Retrieve extrafields
-	    if (is_array($object->array_options) && count($object->array_options))
-	    {
-		    $object->fetch_optionals();
-
-		    $array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs);
-	    }
+			'mycompany_note_private'=>$mysoc->note_private,
+			//'mycompany_note_public'=>$mysoc->note_public,        // Only private not exists for "mysoc" but both for thirdparties
+		);
+	}
+
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 * Define array with couple substitution key => substitution value
+	 *
+	 * @param	Societe		$object			Object
+	 * @param   Translate	$outputlangs    Language object for output
+	 * @param   string		$array_key	    Name of the key for return array
+	 * @return	array						Array of substitution key->code
+	 */
+	public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company')
+	{
+		// phpcs:enable
+		global $conf, $extrafields;
+
+		if (empty($object->country) && !empty($object->country_code))
+		{
+			$object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code);
+		}
+		if (empty($object->state) && !empty($object->state_code))
+		{
+			$object->state = getState($object->state_code, 0);
+		}
+
+		$array_thirdparty = array(
+			'company_name'=>$object->name,
+			'company_name_alias' => $object->name_alias,
+			'company_email'=>$object->email,
+			'company_phone'=>$object->phone,
+			'company_fax'=>$object->fax,
+			'company_address'=>$object->address,
+			'company_zip'=>$object->zip,
+			'company_town'=>$object->town,
+			'company_country'=>$object->country,
+			'company_country_code'=>$object->country_code,
+			'company_state'=>$object->state,
+			'company_state_code'=>$object->state_code,
+			'company_web'=>$object->url,
+			'company_barcode'=>$object->barcode,
+			'company_vatnumber'=>$object->tva_intra,
+			'company_customercode'=>$object->code_client,
+			'company_suppliercode'=>$object->code_fournisseur,
+			'company_customeraccountancycode'=>$object->code_compta,
+			'company_supplieraccountancycode'=>$object->code_compta_fournisseur,
+			'company_juridicalstatus'=>$object->forme_juridique,
+			'company_outstanding_limit'=>$object->outstanding_limit,
+			'company_capital'=>$object->capital,
+			'company_idprof1'=>$object->idprof1,
+			'company_idprof2'=>$object->idprof2,
+			'company_idprof3'=>$object->idprof3,
+			'company_idprof4'=>$object->idprof4,
+			'company_idprof5'=>$object->idprof5,
+			'company_idprof6'=>$object->idprof6,
+			'company_note_public'=>$object->note_public,
+			'company_note_private'=>$object->note_private,
+			'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''),
+			'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '')
+		);
+
+		// Retrieve extrafields
+		if (is_array($object->array_options) && count($object->array_options))
+		{
+			$object->fetch_optionals();
+
+			$array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs);
+		}
 		return $array_thirdparty;
 	}
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
 	 * Define array with couple substitution key => substitution value
 	 *
@@ -241,9 +241,9 @@ abstract class CommonDocGenerator
 	 * @param   string		$array_key	    Name of the key for return array
 	 * @return	array 						Array of substitution key->code
 	 */
-    public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object')
-    {
-        // phpcs:enable
+	public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object')
+	{
+		// phpcs:enable
 		global $conf, $extrafields;
 
 		if (empty($object->country) && !empty($object->country_code))
@@ -285,67 +285,67 @@ abstract class CommonDocGenerator
 			$array_key.'_civility' => $object->civility,
 		);
 
-	    // Retrieve extrafields
-	    if (is_array($object->array_options) && count($object->array_options))
-	    {
-		    $object->fetch_optionals();
+		// Retrieve extrafields
+		if (is_array($object->array_options) && count($object->array_options))
+		{
+			$object->fetch_optionals();
 
-		    $array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs);
-	    }
+			$array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs);
+		}
 		return $array_contact;
 	}
 
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
-    /**
-     * Define array with couple substitution key => substitution value
-     *
-     * @param   Translate	$outputlangs    Language object for output
-     * @return	array						Array of substitution key->code
-     */
-    public function get_substitutionarray_other($outputlangs)
-    {
-        // phpcs:enable
-    	global $conf;
-
-    	$now = dol_now('gmt'); // gmt
-    	$array_other = array(
-    	    // Date in default language
-    	    'current_date'=>dol_print_date($now, 'day', 'tzuser'),
-    	    'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'),
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 * Define array with couple substitution key => substitution value
+	 *
+	 * @param   Translate	$outputlangs    Language object for output
+	 * @return	array						Array of substitution key->code
+	 */
+	public function get_substitutionarray_other($outputlangs)
+	{
+		// phpcs:enable
+		global $conf;
+
+		$now = dol_now('gmt'); // gmt
+		$array_other = array(
+			// Date in default language
+			'current_date'=>dol_print_date($now, 'day', 'tzuser'),
+			'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'),
    			'current_server_date'=>dol_print_date($now, 'day', 'tzserver'),
    			'current_server_datehour'=>dol_print_date($now, 'dayhour', 'tzserver'),
-    	    // Date in requested output language
-    	    'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs),
+			// Date in requested output language
+			'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs),
    			'current_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzuser', $outputlangs),
    			'current_server_date_locale'=>dol_print_date($now, 'day', 'tzserver', $outputlangs),
    			'current_server_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzserver', $outputlangs),
-    	);
+		);
 
 
-    	foreach ($conf->global as $key => $val)
-    	{
-    		if (isASecretKey($key)) $newval = '*****forbidden*****';
-    		else $newval = $val;
-    		$array_other['__['.$key.']__'] = $newval;
-    	}
+		foreach ($conf->global as $key => $val)
+		{
+			if (isASecretKey($key)) $newval = '*****forbidden*****';
+			else $newval = $val;
+			$array_other['__['.$key.']__'] = $newval;
+		}
 
-    	return $array_other;
-    }
+		return $array_other;
+	}
 
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
 	 * Define array with couple substitution key => substitution value
 	 *
 	 * @param   Object			$object             Main object to use as data source
 	 * @param   Translate		$outputlangs        Lang object to use for output
-     * @param   string		    $array_key	        Name of the key for return array
+	 * @param   string		    $array_key	        Name of the key for return array
 	 * @return	array								Array of substitution
 	 */
 	public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object')
 	{
-        // phpcs:enable
+		// phpcs:enable
 		global $conf, $extrafields;
 
 		$sumpayed = $sumdeposit = $sumcreditnote = '';
@@ -381,11 +381,11 @@ abstract class CommonDocGenerator
 		$array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)),
 		$array_key.'_source_invoice_ref'=>$invoice_source->ref,
 		// Dates
-        $array_key.'_hour'=>dol_print_date($date, 'hour'),
+		$array_key.'_hour'=>dol_print_date($date, 'hour'),
 		$array_key.'_date'=>dol_print_date($date, 'day'),
 		$array_key.'_date_rfc'=>dol_print_date($date, 'dayrfc'),
 		$array_key.'_date_limit'=>(!empty($object->date_lim_reglement) ?dol_print_date($object->date_lim_reglement, 'day') : ''),
-	    $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''),
+		$array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''),
 		$array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
 		$array_key.'_date_modification'=>(!empty($object->date_modification) ?dol_print_date($object->date_modification, 'day') : ''),
 		$array_key.'_date_validation'=>(!empty($object->date_validation) ?dol_print_date($object->date_validation, 'dayhour') : ''),
@@ -397,7 +397,7 @@ abstract class CommonDocGenerator
 		$array_key.'_payment_term_code'=>$object->cond_reglement_code,
 		$array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) != 'PaymentCondition'.$object->cond_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) : ($object->cond_reglement_doc ? $object->cond_reglement_doc : $object->cond_reglement)),
 
-        $array_key.'_incoterms'=>(method_exists($object, 'display_incoterms') ? $object->display_incoterms() : ''),
+		$array_key.'_incoterms'=>(method_exists($object, 'display_incoterms') ? $object->display_incoterms() : ''),
 
 		$array_key.'_bank_iban'=>$bank_account->iban,
 		$array_key.'_bank_bic'=>$bank_account->bic,
@@ -416,8 +416,8 @@ abstract class CommonDocGenerator
 
 		$array_key.'_multicurrency_code' => price2num($object->multicurrency_code),
 		$array_key.'_multicurrency_tx' => price2num($object->multicurrency_tx),
-	    $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht),
-	    $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva),
+		$array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht),
+		$array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva),
 		$array_key.'_multicurrency_total_ttc' => price2num($object->multicurrency_total_ttc),
 		$array_key.'_multicurrency_total_ht_locale' => price($object->multicurrency_total_ht, 0, $outputlangs),
 		$array_key.'_multicurrency_total_tva_locale' => price($object->multicurrency_total_tva, 0, $outputlangs),
@@ -472,11 +472,11 @@ abstract class CommonDocGenerator
 			$totalUp = 0;
 			foreach ($object->lines as $line)
 			{
-			    // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility
+				// $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility
 				if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx] = 0;
 				$resarray[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
 				$resarray[$array_key.'_total_vat_locale_'.$line->tva_tx] = price($resarray[$array_key.'_total_vat_'.$line->tva_tx]);
-			    // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example)
+				// $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example)
 				$vatformated = vatrate($line->tva_tx);
 				if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated] = 0;
 				$resarray[$array_key.'_total_vat_'.$vatformated] += $line->total_tva;
@@ -514,7 +514,7 @@ abstract class CommonDocGenerator
 		return $resarray;
 	}
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
 	 *	Define array with couple substitution key => substitution value
 	 *
@@ -525,7 +525,7 @@ abstract class CommonDocGenerator
 	 */
 	public function get_substitutionarray_lines($line, $outputlangs, $linenumber = 0)
 	{
-        // phpcs:enable
+		// phpcs:enable
 		global $conf;
 
 		$resarray = array(
@@ -537,9 +537,9 @@ abstract class CommonDocGenerator
 			'line_product_type'=>$line->product_type,
 			'line_desc'=>$line->desc,
 			'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits),
-		    'line_localtax1_rate'=>vatrate($line->localtax1_tx),
-		    'line_localtax2_rate'=>vatrate($line->localtax1_tx),
-		    'line_up'=>price2num($line->subprice),
+			'line_localtax1_rate'=>vatrate($line->localtax1_tx),
+			'line_localtax2_rate'=>vatrate($line->localtax1_tx),
+			'line_up'=>price2num($line->subprice),
 			'line_up_locale'=>price($line->subprice, 0, $outputlangs),
 			'line_total_up'=>price2num($line->subprice * $line->qty),
 			'line_total_up_locale'=>price($line->subprice * $line->qty, 0, $outputlangs),
@@ -551,31 +551,31 @@ abstract class CommonDocGenerator
 			'line_price_ht_locale'=>price($line->total_ht, 0, $outputlangs),
 			'line_price_ttc_locale'=>price($line->total_ttc, 0, $outputlangs),
 			'line_price_vat_locale'=>price($line->total_tva, 0, $outputlangs),
-		    // Dates
+			// Dates
 			'line_date_start'=>dol_print_date($line->date_start, 'day'),
 			'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzserver', $outputlangs),
-		    'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'),
-		    'line_date_end'=>dol_print_date($line->date_end, 'day'),
-		    'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs),
-		    'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'),
-
-		    'line_multicurrency_code' => price2num($line->multicurrency_code),
-		    'line_multicurrency_subprice' => price2num($line->multicurrency_subprice),
-		    'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht),
-		    'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva),
-		    'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc),
-		    'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs),
-		    'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs),
-		    'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs),
-		    'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs),
+			'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'),
+			'line_date_end'=>dol_print_date($line->date_end, 'day'),
+			'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs),
+			'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'),
+
+			'line_multicurrency_code' => price2num($line->multicurrency_code),
+			'line_multicurrency_subprice' => price2num($line->multicurrency_subprice),
+			'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht),
+			'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva),
+			'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc),
+			'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs),
+			'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs),
+			'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs),
+			'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs),
 		);
 
-        // Units
+		// Units
 		if ($conf->global->PRODUCT_USE_UNITS)
 		{
-		      $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long'));
-		      $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short'));
-        }
+			  $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long'));
+			  $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short'));
+		}
 
 		// Retrieve extrafields
 		$extrafieldkey = $line->table_element;
@@ -585,14 +585,14 @@ abstract class CommonDocGenerator
 		$extrafields->fetch_name_optionals_label($extrafieldkey, true);
 		$line->fetch_optionals();
 
-        $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs);
+		$resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs);
 
-        // Check if the current line belongs to a supplier order
-        if (get_class($line) == 'CommandeFournisseurLigne')
-        {
-            // Add the product supplier extrafields to the substitutions
-            $extrafields->fetch_name_optionals_label("product_fournisseur_price");
-            $extralabels = $extrafields->attributes["product_fournisseur_price"]['label'];
+		// Check if the current line belongs to a supplier order
+		if (get_class($line) == 'CommandeFournisseurLigne')
+		{
+			// Add the product supplier extrafields to the substitutions
+			$extrafields->fetch_name_optionals_label("product_fournisseur_price");
+			$extralabels = $extrafields->attributes["product_fournisseur_price"]['label'];
 
 			if (!empty($extralabels) && is_array($extralabels))
 			{
@@ -619,7 +619,7 @@ abstract class CommonDocGenerator
 					}
 				}
 			}
-        }
+		}
 
 		// Load product data optional fields to the line -> enables to use "line_options_{extrafield}"
 		if (isset($line->fk_product) && $line->fk_product > 0)
@@ -633,158 +633,158 @@ abstract class CommonDocGenerator
 		return $resarray;
 	}
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
-    /**
-     * Define array with couple substitution key => substitution value
-     *
-     * @param   Expedition		$object             Main object to use as data source
-     * @param   Translate		$outputlangs        Lang object to use for output
-     * @param   array			$array_key	        Name of the key for return array
-     * @return	array								Array of substitution
-     */
-    public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object')
-    {
-        // phpcs:enable
-    	global $conf, $extrafields;
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 * Define array with couple substitution key => substitution value
+	 *
+	 * @param   Expedition		$object             Main object to use as data source
+	 * @param   Translate		$outputlangs        Lang object to use for output
+	 * @param   array			$array_key	        Name of the key for return array
+	 * @return	array								Array of substitution
+	 */
+	public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object')
+	{
+		// phpcs:enable
+		global $conf, $extrafields;
 		dol_include_once('/core/lib/product.lib.php');
 		$object->list_delivery_methods($object->shipping_method_id);
 		$calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth);
 
-    	$array_shipment = array(
-	    	$array_key.'_id'=>$object->id,
-	    	$array_key.'_ref'=>$object->ref,
-	    	$array_key.'_ref_ext'=>$object->ref_ext,
-	    	$array_key.'_ref_customer'=>$object->ref_customer,
-	    	$array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'),
-	    	$array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'),
-	    	$array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
-	    	$array_key.'_total_ht'=>price($object->total_ht),
-	    	$array_key.'_total_vat'=>price($object->total_tva),
-	    	$array_key.'_total_ttc'=>price($object->total_ttc),
-	    	$array_key.'_total_discount_ht' => price($object->getTotalDiscount()),
-	    	$array_key.'_note_private'=>$object->note_private,
-	    	$array_key.'_note'=>$object->note_public,
-	    	$array_key.'_tracking_number'=>$object->tracking_number,
-	    	$array_key.'_tracking_url'=>$object->tracking_url,
-	    	$array_key.'_shipping_method'=>$object->listmeths[0]['libelle'],
-    		$array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units),
-    		$array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units),
-    		$array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units),
-    		$array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units),
-	    	$array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'),
-    	);
-
-    	// Add vat by rates
-    	foreach ($object->lines as $line)
-    	{
-    		if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0;
-    		$array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
-    	}
-
-	    // Retrieve extrafields
-	    if (is_array($object->array_options) && count($object->array_options))
-	    {
-		    $object->fetch_optionals();
-
-		    $array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs);
-	    }
-
-    	return $array_shipment;
-    }
-
-
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
-    /**
-     *  Define array with couple substitution key => substitution value
-     *
-     *	@param  ExpeditionLigne	$line				Object line
-     *	@param  Translate		$outputlangs        Lang object to use for output
-     *	@return	array								Substitution array
-     */
-    public function get_substitutionarray_shipment_lines($line, $outputlangs)
-    {
-        // phpcs:enable
-        global $conf;
-        dol_include_once('/core/lib/product.lib.php');
-
-        $resarray = array(
-	    	'line_fulldesc'=>doc_getlinedesc($line, $outputlangs),
-	    	'line_product_ref'=>$line->product_ref,
-	    	'line_product_label'=>$line->product_label,
-	    	'line_desc'=>$line->desc,
-	    	'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits),
-	    	'line_up'=>price($line->subprice),
-            'line_total_up'=>price($line->subprice * $line->qty),
-	    	'line_qty'=>$line->qty,
-	    	'line_qty_shipped'=>$line->qty_shipped,
-	    	'line_qty_asked'=>$line->qty_asked,
-	    	'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''),
-	    	'line_price_ht'=>price($line->total_ht),
-	    	'line_price_ttc'=>price($line->total_ttc),
-	    	'line_price_vat'=>price($line->total_tva),
-        	'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units),
-        	'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units),
-        	'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units),
-        	'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units),
-    	);
-
-        // Retrieve extrafields
-        $extrafieldkey = $line->element;
-        $array_key = "line";
-        require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-        $extrafields = new ExtraFields($this->db);
-        $extrafields->fetch_name_optionals_label($extrafieldkey, true);
-        $line->fetch_optionals();
-
-        $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs);
-
-        return $resarray;
-    }
-
-
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
-    /**
-     * Define array with couple substitution key => substitution value
-     *
-     * @param   Object		$object    		Dolibarr Object
-     * @param   Translate	$outputlangs    Language object for output
-     * @param   boolean		$recursive    	Want to fetch child array or child object
-     * @return	array						Array of substitution key->code
-     */
-    public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true)
-    {
-        // phpcs:enable
-        $array_other = array();
-        if (!empty($object)) {
-            foreach ($object as $key => $value) {
-                if (!empty($value)) {
-                    if (!is_array($value) && !is_object($value)) {
-                        $array_other['object_'.$key] = $value;
-                    }
-                    if (is_array($value) && $recursive) {
-                        $array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false);
-                    }
-                }
-            }
-        }
-        return $array_other;
-    }
-
-
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
-    /**
-     *	Fill array with couple extrafield key => extrafield value
-     *
-     *	@param  Object			$object				Object with extrafields (must have $object->array_options filled)
-     *	@param  array			$array_to_fill      Substitution array
-     *  @param  Extrafields		$extrafields        Extrafields object
-     *  @param  string			$array_key	        Prefix for name of the keys into returned array
-     *  @param  Translate		$outputlangs        Lang object to use for output
-     *	@return	array								Substitution array
-     */
-    public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs)
-    {
-        // phpcs:enable
+		$array_shipment = array(
+			$array_key.'_id'=>$object->id,
+			$array_key.'_ref'=>$object->ref,
+			$array_key.'_ref_ext'=>$object->ref_ext,
+			$array_key.'_ref_customer'=>$object->ref_customer,
+			$array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'),
+			$array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'),
+			$array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
+			$array_key.'_total_ht'=>price($object->total_ht),
+			$array_key.'_total_vat'=>price($object->total_tva),
+			$array_key.'_total_ttc'=>price($object->total_ttc),
+			$array_key.'_total_discount_ht' => price($object->getTotalDiscount()),
+			$array_key.'_note_private'=>$object->note_private,
+			$array_key.'_note'=>$object->note_public,
+			$array_key.'_tracking_number'=>$object->tracking_number,
+			$array_key.'_tracking_url'=>$object->tracking_url,
+			$array_key.'_shipping_method'=>$object->listmeths[0]['libelle'],
+			$array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units),
+			$array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units),
+			$array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units),
+			$array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units),
+			$array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'),
+		);
+
+		// Add vat by rates
+		foreach ($object->lines as $line)
+		{
+			if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0;
+			$array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
+		}
+
+		// Retrieve extrafields
+		if (is_array($object->array_options) && count($object->array_options))
+		{
+			$object->fetch_optionals();
+
+			$array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs);
+		}
+
+		return $array_shipment;
+	}
+
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 *  Define array with couple substitution key => substitution value
+	 *
+	 *	@param  ExpeditionLigne	$line				Object line
+	 *	@param  Translate		$outputlangs        Lang object to use for output
+	 *	@return	array								Substitution array
+	 */
+	public function get_substitutionarray_shipment_lines($line, $outputlangs)
+	{
+		// phpcs:enable
+		global $conf;
+		dol_include_once('/core/lib/product.lib.php');
+
+		$resarray = array(
+			'line_fulldesc'=>doc_getlinedesc($line, $outputlangs),
+			'line_product_ref'=>$line->product_ref,
+			'line_product_label'=>$line->product_label,
+			'line_desc'=>$line->desc,
+			'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits),
+			'line_up'=>price($line->subprice),
+			'line_total_up'=>price($line->subprice * $line->qty),
+			'line_qty'=>$line->qty,
+			'line_qty_shipped'=>$line->qty_shipped,
+			'line_qty_asked'=>$line->qty_asked,
+			'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''),
+			'line_price_ht'=>price($line->total_ht),
+			'line_price_ttc'=>price($line->total_ttc),
+			'line_price_vat'=>price($line->total_tva),
+			'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units),
+			'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units),
+			'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units),
+			'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units),
+		);
+
+		// Retrieve extrafields
+		$extrafieldkey = $line->element;
+		$array_key = "line";
+		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+		$extrafields = new ExtraFields($this->db);
+		$extrafields->fetch_name_optionals_label($extrafieldkey, true);
+		$line->fetch_optionals();
+
+		$resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs);
+
+		return $resarray;
+	}
+
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 * Define array with couple substitution key => substitution value
+	 *
+	 * @param   Object		$object    		Dolibarr Object
+	 * @param   Translate	$outputlangs    Language object for output
+	 * @param   boolean		$recursive    	Want to fetch child array or child object
+	 * @return	array						Array of substitution key->code
+	 */
+	public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true)
+	{
+		// phpcs:enable
+		$array_other = array();
+		if (!empty($object)) {
+			foreach ($object as $key => $value) {
+				if (!empty($value)) {
+					if (!is_array($value) && !is_object($value)) {
+						$array_other['object_'.$key] = $value;
+					}
+					if (is_array($value) && $recursive) {
+						$array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false);
+					}
+				}
+			}
+		}
+		return $array_other;
+	}
+
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 *	Fill array with couple extrafield key => extrafield value
+	 *
+	 *	@param  Object			$object				Object with extrafields (must have $object->array_options filled)
+	 *	@param  array			$array_to_fill      Substitution array
+	 *  @param  Extrafields		$extrafields        Extrafields object
+	 *  @param  string			$array_key	        Prefix for name of the keys into returned array
+	 *  @param  Translate		$outputlangs        Lang object to use for output
+	 *	@return	array								Substitution array
+	 */
+	public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs)
+	{
+		// phpcs:enable
 		global $conf;
 
 		if (is_array($extrafields->attributes[$object->table_element]['label'])) {
@@ -875,671 +875,671 @@ abstract class CommonDocGenerator
 	 * @param	int		$hidebottom		Hide bottom
 	 * @return	void
 	 */
-    public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0)
-    {
-        if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y);
-        $pdf->line($x + $l, $y, $x + $l, $y + $h);
-        if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h);
-        $pdf->line($x, $y + $h, $x, $y);
-    }
-
-
-    /**
-     *  uasort callback function to Sort columns fields
-     *
-     *  @param	array			$a    			PDF lines array fields configs
-     *  @param	array			$b    			PDF lines array fields configs
-     *  @return	int								Return compare result
-     */
-    public function columnSort($a, $b)
-    {
-        if (empty($a['rank'])) { $a['rank'] = 0; }
-        if (empty($b['rank'])) { $b['rank'] = 0; }
-        if ($a['rank'] == $b['rank']) {
-            return 0;
-        }
-        return ($a['rank'] > $b['rank']) ? -1 : 1;
-    }
-
-    /**
-     *   	Prepare Array Column Field
-     *
-     *   	@param	object			$object				common object
-     *   	@param	Translate		$outputlangs		langs
-     *      @param	int				$hidedetails		Do not show line details
-     *      @param	int				$hidedesc			Do not show desc
-     *      @param	int				$hideref			Do not show ref
-     *      @return	null
-     */
-    public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
-    {
-        global $conf;
-
-        $this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref);
-
-
-        // Sorting
-        uasort($this->cols, array($this, 'columnSort'));
-
-        // Positionning
-        $curX = $this->page_largeur - $this->marge_droite; // start from right
-
-        // Array width
-        $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche;
-
-        // Count flexible column
-        $totalDefinedColWidth = 0;
-        $countFlexCol = 0;
-        foreach ($this->cols as $colKey =>& $colDef)
-        {
-            if (!$this->getColumnStatus($colKey)) continue; // continue if disabled
-
-            if (!empty($colDef['scale'])) {
-                // In case of column width is defined by percentage
-                $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100);
-            }
-
-            if (empty($colDef['width'])) {
-                $countFlexCol++;
-            } else {
-                $totalDefinedColWidth += $colDef['width'];
-            }
-        }
-
-        foreach ($this->cols as $colKey =>& $colDef)
-        {
-            // setting empty conf with default
-            if (!empty($colDef['title'])) {
-                $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']);
-            } else {
-                $colDef['title'] = $this->defaultTitlesFieldsStyle;
-            }
-
-            // setting empty conf with default
-            if (!empty($colDef['content'])) {
-                $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']);
-            } else {
-                $colDef['content'] = $this->defaultContentsFieldsStyle;
-            }
-
-            if ($this->getColumnStatus($colKey))
-            {
-                // In case of flexible column
-                if (empty($colDef['width'])) {
-                    $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol;
-                }
-
-                // Set positions
-                $lastX = $curX;
-                $curX = $lastX - $colDef['width'];
-                $colDef['xStartPos'] = $curX;
-                $colDef['xEndPos']   = $lastX;
-            }
-        }
-    }
-
-    /**
-     *  get column content width from column key
-     *
-     *  @param	string      $colKey     the column key
-     *  @return	float                   width in mm
-     */
-    public function getColumnContentWidth($colKey)
-    {
-        $colDef = $this->cols[$colKey];
-        return  $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1];
-    }
-
-
-    /**
-     *  get column content X (abscissa) left position from column key
-     *
-     *  @param	string    $colKey    		the column key
-     *  @return	float      X position in mm
-     */
-    public function getColumnContentXStart($colKey)
-    {
-        $colDef = $this->cols[$colKey];
-        return  $colDef['xStartPos'] + $colDef['content']['padding'][3];
-    }
-
-    /**
-     *   	get column position rank from column key
-     *
-     *   	@param	string		$colKey    		the column key
-     *      @return	int         rank on success and -1 on error
-     */
-    public function getColumnRank($colKey)
-    {
-        if (!isset($this->cols[$colKey]['rank'])) return -1;
-        return  $this->cols[$colKey]['rank'];
-    }
-
-    /**
-     *  get column position rank from column key
-     *
-     *  @param	string		$newColKey    	the new column key
-     *  @param	array		$defArray    	a single column definition array
-     *  @param	string		$targetCol    	target column used to place the new column beside
-     *  @param	bool		$insertAfterTarget    	insert before or after target column ?
-     *  @return	int         new rank on success and -1 on error
-     */
-    public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false)
-    {
-        // prepare wanted rank
-        $rank = -1;
-
-        // try to get rank from target column
-        if (!empty($targetCol)) {
-            $rank = $this->getColumnRank($targetCol);
-            if ($rank >= 0 && $insertAfterTarget) { $rank++; }
-        }
-
-        // get rank from new column definition
-        if ($rank < 0 && !empty($defArray['rank'])) {
-            $rank = $defArray['rank'];
-        }
-
-        // error: no rank
-        if ($rank < 0) { return -1; }
-
-        foreach ($this->cols as $colKey =>& $colDef)
-        {
-            if ($rank <= $colDef['rank'])
-            {
-                $colDef['rank'] = $colDef['rank'] + 1;
-            }
-        }
-
-        $defArray['rank'] = $rank;
-        $this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys
-
-        return $rank;
-    }
-
-
-    /**
-     *  print standard column content
-     *
-     *  @param	TCPDF		    $pdf    	pdf object
-     *  @param	float		$curY    	curent Y position
-     *  @param	string		$colKey    	the column key
-     *  @param	string		$columnText   column text
-     *  @return	null
-     */
-    public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '')
-    {
-        global $hookmanager;
-
-        $parameters = array(
-            'curY' => &$curY,
-            'columnText' => $columnText,
-            'colKey' => $colKey,
-            'pdf' => &$pdf,
-        );
-        $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;
-            $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position
-            $colDef = $this->cols[$colKey];
-            // save curent cell padding
+	public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0)
+	{
+		if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y);
+		$pdf->line($x + $l, $y, $x + $l, $y + $h);
+		if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h);
+		$pdf->line($x, $y + $h, $x, $y);
+	}
+
+
+	/**
+	 *  uasort callback function to Sort columns fields
+	 *
+	 *  @param	array			$a    			PDF lines array fields configs
+	 *  @param	array			$b    			PDF lines array fields configs
+	 *  @return	int								Return compare result
+	 */
+	public function columnSort($a, $b)
+	{
+		if (empty($a['rank'])) { $a['rank'] = 0; }
+		if (empty($b['rank'])) { $b['rank'] = 0; }
+		if ($a['rank'] == $b['rank']) {
+			return 0;
+		}
+		return ($a['rank'] > $b['rank']) ? -1 : 1;
+	}
+
+	/**
+	 *   	Prepare Array Column Field
+	 *
+	 *   	@param	object			$object				common object
+	 *   	@param	Translate		$outputlangs		langs
+	 *      @param	int				$hidedetails		Do not show line details
+	 *      @param	int				$hidedesc			Do not show desc
+	 *      @param	int				$hideref			Do not show ref
+	 *      @return	null
+	 */
+	public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
+	{
+		global $conf;
+
+		$this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref);
+
+
+		// Sorting
+		uasort($this->cols, array($this, 'columnSort'));
+
+		// Positionning
+		$curX = $this->page_largeur - $this->marge_droite; // start from right
+
+		// Array width
+		$arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche;
+
+		// Count flexible column
+		$totalDefinedColWidth = 0;
+		$countFlexCol = 0;
+		foreach ($this->cols as $colKey =>& $colDef)
+		{
+			if (!$this->getColumnStatus($colKey)) continue; // continue if disabled
+
+			if (!empty($colDef['scale'])) {
+				// In case of column width is defined by percentage
+				$colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100);
+			}
+
+			if (empty($colDef['width'])) {
+				$countFlexCol++;
+			} else {
+				$totalDefinedColWidth += $colDef['width'];
+			}
+		}
+
+		foreach ($this->cols as $colKey =>& $colDef)
+		{
+			// setting empty conf with default
+			if (!empty($colDef['title'])) {
+				$colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']);
+			} else {
+				$colDef['title'] = $this->defaultTitlesFieldsStyle;
+			}
+
+			// setting empty conf with default
+			if (!empty($colDef['content'])) {
+				$colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']);
+			} else {
+				$colDef['content'] = $this->defaultContentsFieldsStyle;
+			}
+
+			if ($this->getColumnStatus($colKey))
+			{
+				// In case of flexible column
+				if (empty($colDef['width'])) {
+					$colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol;
+				}
+
+				// Set positions
+				$lastX = $curX;
+				$curX = $lastX - $colDef['width'];
+				$colDef['xStartPos'] = $curX;
+				$colDef['xEndPos']   = $lastX;
+			}
+		}
+	}
+
+	/**
+	 *  get column content width from column key
+	 *
+	 *  @param	string      $colKey     the column key
+	 *  @return	float                   width in mm
+	 */
+	public function getColumnContentWidth($colKey)
+	{
+		$colDef = $this->cols[$colKey];
+		return  $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1];
+	}
+
+
+	/**
+	 *  get column content X (abscissa) left position from column key
+	 *
+	 *  @param	string    $colKey    		the column key
+	 *  @return	float      X position in mm
+	 */
+	public function getColumnContentXStart($colKey)
+	{
+		$colDef = $this->cols[$colKey];
+		return  $colDef['xStartPos'] + $colDef['content']['padding'][3];
+	}
+
+	/**
+	 *   	get column position rank from column key
+	 *
+	 *   	@param	string		$colKey    		the column key
+	 *      @return	int         rank on success and -1 on error
+	 */
+	public function getColumnRank($colKey)
+	{
+		if (!isset($this->cols[$colKey]['rank'])) return -1;
+		return  $this->cols[$colKey]['rank'];
+	}
+
+	/**
+	 *  get column position rank from column key
+	 *
+	 *  @param	string		$newColKey    	the new column key
+	 *  @param	array		$defArray    	a single column definition array
+	 *  @param	string		$targetCol    	target column used to place the new column beside
+	 *  @param	bool		$insertAfterTarget    	insert before or after target column ?
+	 *  @return	int         new rank on success and -1 on error
+	 */
+	public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false)
+	{
+		// prepare wanted rank
+		$rank = -1;
+
+		// try to get rank from target column
+		if (!empty($targetCol)) {
+			$rank = $this->getColumnRank($targetCol);
+			if ($rank >= 0 && $insertAfterTarget) { $rank++; }
+		}
+
+		// get rank from new column definition
+		if ($rank < 0 && !empty($defArray['rank'])) {
+			$rank = $defArray['rank'];
+		}
+
+		// error: no rank
+		if ($rank < 0) { return -1; }
+
+		foreach ($this->cols as $colKey =>& $colDef)
+		{
+			if ($rank <= $colDef['rank'])
+			{
+				$colDef['rank'] = $colDef['rank'] + 1;
+			}
+		}
+
+		$defArray['rank'] = $rank;
+		$this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys
+
+		return $rank;
+	}
+
+
+	/**
+	 *  print standard column content
+	 *
+	 *  @param	TCPDF		    $pdf    	pdf object
+	 *  @param	float		$curY    	curent Y position
+	 *  @param	string		$colKey    	the column key
+	 *  @param	string		$columnText   column text
+	 *  @return	null
+	 */
+	public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '')
+	{
+		global $hookmanager;
+
+		$parameters = array(
+			'curY' => &$curY,
+			'columnText' => $columnText,
+			'colKey' => $colKey,
+			'pdf' => &$pdf,
+		);
+		$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;
+			$pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position
+			$colDef = $this->cols[$colKey];
+			// save curent cell padding
 			$curentCellPaddinds = $pdf->getCellPaddings();
-            // set cell padding with column content definition
+			// set cell padding with column content definition
 			$pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]);
-            $pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']);
+			$pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']);
 
-            // restore cell padding
+			// restore cell padding
 			$pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
-        }
-    }
-
-
-    /**
-     *  print description column content
-     *
-     *  @param	TCPDF		$pdf    	pdf object
-     *  @param	float		$curY    	curent Y position
-     *  @param	string		$colKey    	the column key
-     *  @param  object      $object CommonObject
-     *  @param  int         $i  the $object->lines array key
-     *  @param  Translate $outputlangs    Output language
-     *  @param  int $hideref hide ref
-     *  @param  int $hidedesc hide desc
-     *  @param  int $issupplierline if object need supplier product
-     *  @return null
-     */
-    public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0)
+		}
+	}
+
+
+	/**
+	 *  print description column content
+	 *
+	 *  @param	TCPDF		$pdf    	pdf object
+	 *  @param	float		$curY    	curent Y position
+	 *  @param	string		$colKey    	the column key
+	 *  @param  object      $object CommonObject
+	 *  @param  int         $i  the $object->lines array key
+	 *  @param  Translate $outputlangs    Output language
+	 *  @param  int $hideref hide ref
+	 *  @param  int $hidedesc hide desc
+	 *  @param  int $issupplierline if object need supplier product
+	 *  @return null
+	 */
+	public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0)
+	{
+		// load desc col params
+		$colDef = $this->cols[$colKey];
+		// save curent cell padding
+		$curentCellPaddinds = $pdf->getCellPaddings();
+		// set cell padding with column content definition
+		$pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]);
+
+		// line description
+		pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline);
+		$posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0];
+
+		// restore cell padding
+		$pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
+
+		// Display extrafield if needed
+		$params = array(
+			'display'         => 'list',
+			'printableEnable' => array(3),
+			'printableEnableNotEmpty' => array(4)
+		);
+		$extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params);
+		if (!empty($extrafieldDesc)) {
+			$this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc);
+		}
+	}
+
+	/**
+	 *  get extrafield content for pdf writeHtmlCell compatibility
+	 *  usage for PDF line columns and object note block
+	 *
+	 *  @param	object		$object     common object
+	 *  @param	string		$extrafieldKey    	the extrafield key
+	 *  @return	string
+	 */
+	public function getExtrafieldContent($object, $extrafieldKey)
+	{
+		global $hookmanager;
+
+		if (empty($object->table_element)) { return; }
+
+		$extrafieldsKeyPrefix = "options_";
+
+		// Cleanup extrafield key to remove prefix if present
+		$pos = strpos($extrafieldKey, $extrafieldsKeyPrefix);
+		if ($pos === 0) {
+			$extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix));
+		}
+
+		$extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey;
+
+
+		// Load extrafiels if not allready does
+		if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); }
+		if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); }
+		$extrafields = $this->extrafieldsCache;
+
+		$extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element);
+
+		// TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ...
+		if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') {
+			// for lack of anything better we cleanup all html tags
+			$extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent);
+		}
+
+		$parameters = array(
+			'object' => $object,
+			'extrafields' => $extrafields,
+			'extrafieldKey' => $extrafieldKey,
+			'extrafieldOutputContent' =>& $extrafieldOutputContent
+		);
+		$reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook
+		if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+		if ($reshook)
+		{
+			$extrafieldOutputContent = $hookmanager->resPrint;
+		}
+
+		return $extrafieldOutputContent;
+	}
+
+
+	/**
+	 *  display extrafields columns content
+	 *
+	 *  @param	object		$object    	line of common object
+	 *  @param Translate $outputlangs    Output language
+	 *  @param array $params    array of additionals parameters
+	 *  @return	double  max y value
+	 */
+	public function getExtrafieldsInHtml($object, $outputlangs, $params = array())
 	{
-        // load desc col params
-        $colDef = $this->cols[$colKey];
-        // save curent cell padding
-        $curentCellPaddinds = $pdf->getCellPaddings();
-        // set cell padding with column content definition
-        $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]);
-
-        // line description
-        pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline);
-        $posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0];
-
-        // restore cell padding
-        $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
-
-        // Display extrafield if needed
-        $params = array(
-            'display'         => 'list',
-            'printableEnable' => array(3),
-            'printableEnableNotEmpty' => array(4)
-        );
-        $extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params);
-        if (!empty($extrafieldDesc)) {
-            $this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc);
-        }
-    }
-
-    /**
-     *  get extrafield content for pdf writeHtmlCell compatibility
-     *  usage for PDF line columns and object note block
-     *
-     *  @param	object		$object     common object
-     *  @param	string		$extrafieldKey    	the extrafield key
-     *  @return	string
-     */
-    public function getExtrafieldContent($object, $extrafieldKey)
-    {
-        global $hookmanager;
-
-        if (empty($object->table_element)) { return; }
-
-        $extrafieldsKeyPrefix = "options_";
-
-        // Cleanup extrafield key to remove prefix if present
-        $pos = strpos($extrafieldKey, $extrafieldsKeyPrefix);
-        if ($pos === 0) {
-            $extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix));
-        }
-
-        $extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey;
-
-
-        // Load extrafiels if not allready does
-        if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); }
-        if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); }
-        $extrafields = $this->extrafieldsCache;
-
-        $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element);
-
-        // TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ...
-        if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') {
-            // for lack of anything better we cleanup all html tags
-            $extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent);
-        }
-
-        $parameters = array(
-            'object' => $object,
-            'extrafields' => $extrafields,
-            'extrafieldKey' => $extrafieldKey,
-            'extrafieldOutputContent' =>& $extrafieldOutputContent
-        );
-        $reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook
-        if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
-        if ($reshook)
-        {
-            $extrafieldOutputContent = $hookmanager->resPrint;
-        }
-
-        return $extrafieldOutputContent;
-    }
-
-
-    /**
-     *  display extrafields columns content
-     *
-     *  @param	object		$object    	line of common object
-     *  @param Translate $outputlangs    Output language
-     *  @param array $params    array of additionals parameters
-     *  @return	double  max y value
-     */
-    public function getExtrafieldsInHtml($object, $outputlangs, $params = array())
-    {
-        global $hookmanager;
-
-        if (empty($object->table_element)) {
-            return;
-        }
-
-        // Load extrafiels if not allready does
-        if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); }
-        if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); }
-        $extrafields = $this->extrafieldsCache;
-
-        $defaultParams = array(
-            'style'         => '',
-            'display'         => 'auto', // auto, table, list
-            'printableEnable' => array(1),
-            'printableEnableNotEmpty' => array(2),
-
-            'table'         => array(
-                'maxItemsInRow' => 2,
-                'cellspacing'   => 0,
-                'cellpadding'   => 0,
-                'border'        => 0,
-                'labelcolwidth' => '25%',
-                'arrayOfLineBreakType' => array('text', 'html')
-            ),
-
-            'list'         => array(
-                'separator' => '<br/>'
-            ),
-
-            'auto'         => array(
-                'list' => 0, // 0 for default
-                'table' => 4 // if there more than x extrafield to display
-            ),
-        );
-
-        $params = $params + $defaultParams;
-
-
-        /**
-         * @var $extrafields ExtraFields
-         */
-
-        $html = '';
-        $fields = array();
-
-        if (is_array($extrafields->attributes[$object->table_element]['label'])) {
-            foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label)
-            {
-                // Enable extrafield ?
-                $enabled = 0;
-                $disableOnEmpty = 0;
-                if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) {
-                    $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]);
-                    if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) {
-                        $enabled = 1;
-                    }
-
-                    if (in_array($printable, $params['printableEnableNotEmpty'])) {
-                        $disableOnEmpty = 1;
-                    }
-                }
-
-                if (empty($enabled)) {
-                    continue;
-                }
-
-                $field = new stdClass();
-                $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]);
-                $field->content = $this->getExtrafieldContent($object, $key);
-                $field->label = $outputlangs->transnoentities($label);
-                $field->type = $extrafields->attributes[$object->table_element]['type'][$key];
-
-                // dont display if empty
-                if ($disableOnEmpty && empty($field->content)) {
-                    continue;
-                }
-
-                $fields[] = $field;
-            }
-        }
-
-        if (!empty($fields))
-        {
-            // Sort extrafields by rank
-            uasort($fields, function ($a, $b) {
-                return  ($a->rank > $b->rank) ? 1 : -1;
+		global $hookmanager;
+
+		if (empty($object->table_element)) {
+			return;
+		}
+
+		// Load extrafiels if not allready does
+		if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); }
+		if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); }
+		$extrafields = $this->extrafieldsCache;
+
+		$defaultParams = array(
+			'style'         => '',
+			'display'         => 'auto', // auto, table, list
+			'printableEnable' => array(1),
+			'printableEnableNotEmpty' => array(2),
+
+			'table'         => array(
+				'maxItemsInRow' => 2,
+				'cellspacing'   => 0,
+				'cellpadding'   => 0,
+				'border'        => 0,
+				'labelcolwidth' => '25%',
+				'arrayOfLineBreakType' => array('text', 'html')
+			),
+
+			'list'         => array(
+				'separator' => '<br/>'
+			),
+
+			'auto'         => array(
+				'list' => 0, // 0 for default
+				'table' => 4 // if there more than x extrafield to display
+			),
+		);
+
+		$params = $params + $defaultParams;
+
+
+		/**
+		 * @var $extrafields ExtraFields
+		 */
+
+		$html = '';
+		$fields = array();
+
+		if (is_array($extrafields->attributes[$object->table_element]['label'])) {
+			foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label)
+			{
+				// Enable extrafield ?
+				$enabled = 0;
+				$disableOnEmpty = 0;
+				if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) {
+					$printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]);
+					if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) {
+						$enabled = 1;
+					}
+
+					if (in_array($printable, $params['printableEnableNotEmpty'])) {
+						$disableOnEmpty = 1;
+					}
+				}
+
+				if (empty($enabled)) {
+					continue;
+				}
+
+				$field = new stdClass();
+				$field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]);
+				$field->content = $this->getExtrafieldContent($object, $key);
+				$field->label = $outputlangs->transnoentities($label);
+				$field->type = $extrafields->attributes[$object->table_element]['type'][$key];
+
+				// dont display if empty
+				if ($disableOnEmpty && empty($field->content)) {
+					continue;
+				}
+
+				$fields[] = $field;
+			}
+		}
+
+		if (!empty($fields))
+		{
+			// Sort extrafields by rank
+			uasort($fields, function ($a, $b) {
+				return  ($a->rank > $b->rank) ? 1 : -1;
 			});
 
-            // define some HTML content with style
-            $html .= !empty($params['style']) ? '<style>'.$params['style'].'</style>' : '';
-
-            // auto select display format
-            if ($params['display'] == 'auto') {
-                $lastNnumbItems = 0;
-                foreach ($params['auto'] as $display => $numbItems) {
-                    if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) {
-                        $lastNnumbItems = $numbItems;
-                        $params['display'] = $display;
-                    }
-                }
-            }
-
-            if ($params['display'] == 'list') {
-                // Display in list format
-                $i = 0;
-                foreach ($fields as $field) {
-                    $html .= !empty($i) ? $params['list']['separator'] : '';
-                    $html .= '<strong>'.$field->label.' : </strong>';
-                    $html .= $field->content;
-                    $i++;
-                }
-            } elseif ($params['display'] == 'table') {
-                // Display in table format
-                $html .= '<table class="extrafield-table" cellspacing="'.$params['table']['cellspacing'].'" cellpadding="'.$params['table']['cellpadding'].'" border="'.$params['table']['border'].'">';
-
-                $html .= "<tr>";
-                $itemsInRow = 0;
-                $maxItemsInRow = $params['table']['maxItemsInRow'];
-                foreach ($fields as $field) {
-                    //$html.= !empty($html)?'<br/>':'';
-                    if ($itemsInRow >= $maxItemsInRow) {
-                        // start a new line
-                        $html .= "</tr><tr>";
-                        $itemsInRow = 0;
-                    }
-
-                    // for some type we need line break
-                    if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) {
-                        if ($itemsInRow > 0) {
-                            // close table row and empty cols
-                            for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) {
-                                $html .= "<td ></td><td></td>";
-                            }
-                            $html .= "</tr>";
-
-                            // start a new line
-                            $html .= "<tr>";
-                        }
-
-                        $itemsInRow = $maxItemsInRow;
-                        $html .= '<td colspan="'.($maxItemsInRow * 2 - 1).'">';
-                        $html .= '<strong>'.$field->label.' :</strong> ';
-                        $html .= $field->content;
-                        $html .= "</td>";
-                    } else {
-                        $itemsInRow++;
-                        $html .= '<td width="'.$params['table']['labelcolwidth'].'" class="extrafield-label">';
-                        $html .= '<strong>'.$field->label.' :</strong>';
-                        $html .= "</td>";
-
-
-                        $html .= '<td  class="extrafield-content">';
-                        $html .= $field->content;
-                        $html .= "</td>";
-                    }
-                }
-                $html .= "</tr>";
-
-                $html .= '</table>';
-            }
-        }
-
-        return $html;
-    }
-
-
-    /**
-     *  get column status from column key
-     *
-     *  @param	string			$colKey    		the column key
-     *  @return	float      width in mm
-     */
-    public function getColumnStatus($colKey)
-    {
-        if (!empty($this->cols[$colKey]['status'])) {
-            return true;
-        } else return  false;
-    }
-
-    /**
-     * Print standard column content
-     *
-     * @param TCPDI	    $pdf            Pdf object
-     * @param float     $tab_top        Tab top position
-     * @param float     $tab_height     Default tab height
-     * @param Translate $outputlangs    Output language
-     * @param int       $hidetop        Hide top
-     * @return float                    Height of col tab titles
-     */
-    public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0)
-    {
-        global $hookmanager, $conf;
-
-        foreach ($this->cols as $colKey => $colDef) {
-            $parameters = array(
-                'colKey' => $colKey,
-                'pdf' => $pdf,
-                'outputlangs' => $outputlangs,
-                'tab_top' => $tab_top,
-                'tab_height' => $tab_height,
-                'hidetop' => $hidetop
-            );
-
-            $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook
-            if ($reshook < 0) {
-                setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
-            } elseif (empty($reshook)) {
-                if (!$this->getColumnStatus($colKey)) continue;
-
-                // get title label
-                $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']);
-
-                // Add column separator
-                if (!empty($colDef['border-left'])) {
-                    $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height);
-                }
-
-                if (empty($hidetop)) {
-                    // save curent cell padding
-                    $curentCellPaddinds = $pdf->getCellPaddings();
-
-                    // Add space for lines (more if we need to show a second alternative language)
-                    global $outputlangsbis;
-                    if (is_object($outputlangsbis)) {
-                        // set cell padding with column title definition
-                        $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5);
-                    } else {
-                        // set cell padding with column title definition
-                        $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]);
-                    }
-
-                    $pdf->SetXY($colDef['xStartPos'], $tab_top);
-                    $textWidth = $colDef['width'];
-                    $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']);
-
-                    // Add variant of translation if $outputlangsbis is an object
-                    if (is_object($outputlangsbis) && trim($colDef['title']['label'])) {
-                        $pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]);
-                    	$pdf->SetXY($colDef['xStartPos'], $pdf->GetY());
-                    	$textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']);
-                    	$pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']);
-                    }
-
-                    $this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight);
-
-                    // restore cell padding
-                    $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
-                }
-            }
-        }
-
-        return $this->tabTitleHeight;
-    }
-
-
-
-    /**
-     *  Define Array Column Field for extrafields
-     *
-     *  @param	object			$object    		common object det
-     *  @param	Translate		$outputlangs    langs
-     *  @param	int			   $hidedetails		Do not show line details
-     *  @return	null
-     */
-    public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0)
-    {
-        global $conf;
-
-        if (!empty($hidedetails)) {
-            return;
-        }
-
-        if (empty($object->table_element)) {
-            return;
-        }
-
-        // Load extrafiels if not allready does
-        if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); }
-        if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); }
-        $extrafields = $this->extrafieldsCache;
-
-
-        if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) {
-            foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label)
-            {
-                // Dont display separator yet even is set to be displayed (not compatible yet)
-                if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate')
-                {
-                    continue;
-                }
-
-                // Enable extrafield ?
-                $enabled = 0;
-                if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) {
-                    $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]);
-                    if ($printable === 1 || $printable === 2) {
-                        $enabled = 1;
-                    }
-                    // Note : if $printable === 3 or 4 so, it's displayed after line description not in cols
-                }
-
-                if (!$enabled) { continue; } // don't wast resourses if we don't need them...
-
-                // Load language if required
-                if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]);
-
-                // TODO : add more extrafield customisation capacities for PDF like width, rank...
-
-                // set column definition
-                $def = array(
-                    'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]),
-                    'width' => 25, // in mm
-                    'status' => boolval($enabled),
-                    'title' => array(
-                        'label' => $outputlangs->transnoentities($label)
-                    ),
-                    'content' => array(
-                        'align' => 'C'
-                    ),
-                    'border-left' => true, // add left line separator
-                );
-
-                $alignTypeRight = array('double', 'int', 'price');
-                if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) {
-                    $def['content']['align'] = 'R';
-                }
-
-                $alignTypeLeft = array('text', 'html');
-                if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) {
-                    $def['content']['align'] = 'L';
-                }
-
-
-                // for extrafields we use rank of extrafield to place it on PDF
-                $this->insertNewColumnDef("options_".$key, $def);
-            }
-        }
-    }
+			// define some HTML content with style
+			$html .= !empty($params['style']) ? '<style>'.$params['style'].'</style>' : '';
+
+			// auto select display format
+			if ($params['display'] == 'auto') {
+				$lastNnumbItems = 0;
+				foreach ($params['auto'] as $display => $numbItems) {
+					if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) {
+						$lastNnumbItems = $numbItems;
+						$params['display'] = $display;
+					}
+				}
+			}
+
+			if ($params['display'] == 'list') {
+				// Display in list format
+				$i = 0;
+				foreach ($fields as $field) {
+					$html .= !empty($i) ? $params['list']['separator'] : '';
+					$html .= '<strong>'.$field->label.' : </strong>';
+					$html .= $field->content;
+					$i++;
+				}
+			} elseif ($params['display'] == 'table') {
+				// Display in table format
+				$html .= '<table class="extrafield-table" cellspacing="'.$params['table']['cellspacing'].'" cellpadding="'.$params['table']['cellpadding'].'" border="'.$params['table']['border'].'">';
+
+				$html .= "<tr>";
+				$itemsInRow = 0;
+				$maxItemsInRow = $params['table']['maxItemsInRow'];
+				foreach ($fields as $field) {
+					//$html.= !empty($html)?'<br/>':'';
+					if ($itemsInRow >= $maxItemsInRow) {
+						// start a new line
+						$html .= "</tr><tr>";
+						$itemsInRow = 0;
+					}
+
+					// for some type we need line break
+					if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) {
+						if ($itemsInRow > 0) {
+							// close table row and empty cols
+							for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) {
+								$html .= "<td ></td><td></td>";
+							}
+							$html .= "</tr>";
+
+							// start a new line
+							$html .= "<tr>";
+						}
+
+						$itemsInRow = $maxItemsInRow;
+						$html .= '<td colspan="'.($maxItemsInRow * 2 - 1).'">';
+						$html .= '<strong>'.$field->label.' :</strong> ';
+						$html .= $field->content;
+						$html .= "</td>";
+					} else {
+						$itemsInRow++;
+						$html .= '<td width="'.$params['table']['labelcolwidth'].'" class="extrafield-label">';
+						$html .= '<strong>'.$field->label.' :</strong>';
+						$html .= "</td>";
+
+
+						$html .= '<td  class="extrafield-content">';
+						$html .= $field->content;
+						$html .= "</td>";
+					}
+				}
+				$html .= "</tr>";
+
+				$html .= '</table>';
+			}
+		}
+
+		return $html;
+	}
+
+
+	/**
+	 *  get column status from column key
+	 *
+	 *  @param	string			$colKey    		the column key
+	 *  @return	float      width in mm
+	 */
+	public function getColumnStatus($colKey)
+	{
+		if (!empty($this->cols[$colKey]['status'])) {
+			return true;
+		} else return  false;
+	}
+
+	/**
+	 * Print standard column content
+	 *
+	 * @param TCPDI	    $pdf            Pdf object
+	 * @param float     $tab_top        Tab top position
+	 * @param float     $tab_height     Default tab height
+	 * @param Translate $outputlangs    Output language
+	 * @param int       $hidetop        Hide top
+	 * @return float                    Height of col tab titles
+	 */
+	public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0)
+	{
+		global $hookmanager, $conf;
+
+		foreach ($this->cols as $colKey => $colDef) {
+			$parameters = array(
+				'colKey' => $colKey,
+				'pdf' => $pdf,
+				'outputlangs' => $outputlangs,
+				'tab_top' => $tab_top,
+				'tab_height' => $tab_height,
+				'hidetop' => $hidetop
+			);
+
+			$reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook
+			if ($reshook < 0) {
+				setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+			} elseif (empty($reshook)) {
+				if (!$this->getColumnStatus($colKey)) continue;
+
+				// get title label
+				$colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']);
+
+				// Add column separator
+				if (!empty($colDef['border-left'])) {
+					$pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height);
+				}
+
+				if (empty($hidetop)) {
+					// save curent cell padding
+					$curentCellPaddinds = $pdf->getCellPaddings();
+
+					// Add space for lines (more if we need to show a second alternative language)
+					global $outputlangsbis;
+					if (is_object($outputlangsbis)) {
+						// set cell padding with column title definition
+						$pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5);
+					} else {
+						// set cell padding with column title definition
+						$pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]);
+					}
+
+					$pdf->SetXY($colDef['xStartPos'], $tab_top);
+					$textWidth = $colDef['width'];
+					$pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']);
+
+					// Add variant of translation if $outputlangsbis is an object
+					if (is_object($outputlangsbis) && trim($colDef['title']['label'])) {
+						$pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]);
+						$pdf->SetXY($colDef['xStartPos'], $pdf->GetY());
+						$textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']);
+						$pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']);
+					}
+
+					$this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight);
+
+					// restore cell padding
+					$pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']);
+				}
+			}
+		}
+
+		return $this->tabTitleHeight;
+	}
+
+
+
+	/**
+	 *  Define Array Column Field for extrafields
+	 *
+	 *  @param	object			$object    		common object det
+	 *  @param	Translate		$outputlangs    langs
+	 *  @param	int			   $hidedetails		Do not show line details
+	 *  @return	null
+	 */
+	public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0)
+	{
+		global $conf;
+
+		if (!empty($hidedetails)) {
+			return;
+		}
+
+		if (empty($object->table_element)) {
+			return;
+		}
+
+		// Load extrafiels if not allready does
+		if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); }
+		if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); }
+		$extrafields = $this->extrafieldsCache;
+
+
+		if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) {
+			foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label)
+			{
+				// Dont display separator yet even is set to be displayed (not compatible yet)
+				if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate')
+				{
+					continue;
+				}
+
+				// Enable extrafield ?
+				$enabled = 0;
+				if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) {
+					$printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]);
+					if ($printable === 1 || $printable === 2) {
+						$enabled = 1;
+					}
+					// Note : if $printable === 3 or 4 so, it's displayed after line description not in cols
+				}
+
+				if (!$enabled) { continue; } // don't wast resourses if we don't need them...
+
+				// Load language if required
+				if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]);
+
+				// TODO : add more extrafield customisation capacities for PDF like width, rank...
+
+				// set column definition
+				$def = array(
+					'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]),
+					'width' => 25, // in mm
+					'status' => boolval($enabled),
+					'title' => array(
+						'label' => $outputlangs->transnoentities($label)
+					),
+					'content' => array(
+						'align' => 'C'
+					),
+					'border-left' => true, // add left line separator
+				);
+
+				$alignTypeRight = array('double', 'int', 'price');
+				if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) {
+					$def['content']['align'] = 'R';
+				}
+
+				$alignTypeLeft = array('text', 'html');
+				if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) {
+					$def['content']['align'] = 'L';
+				}
+
+
+				// for extrafields we use rank of extrafield to place it on PDF
+				$this->insertNewColumnDef("options_".$key, $def);
+			}
+		}
+	}
 }

+ 127 - 127
htdocs/core/class/hookmanager.class.php

@@ -30,9 +30,9 @@
 class HookManager
 {
 	/**
-     * @var DoliDB Database handler.
-     */
-    public $db;
+	 * @var DoliDB Database handler.
+	 */
+	public $db;
 
 	/**
 	 * @var string Error code (or message)
@@ -44,18 +44,18 @@ class HookManager
 	 */
 	public $errors = array();
 
-    // Context hookmanager was created for ('thirdpartycard', 'thirdpartydao', ...)
-    public $contextarray = array();
+	// Context hookmanager was created for ('thirdpartycard', 'thirdpartydao', ...)
+	public $contextarray = array();
 
 	// Array with instantiated classes
-    public $hooks = array();
+	public $hooks = array();
 
 	// Array result
-    public $resArray = array();
+	public $resArray = array();
 	// Printable result
-    public $resPrint = '';
+	public $resPrint = '';
 	// Nb of qualified hook ran
-    public $resNbOfHooks = 0;
+	public $resNbOfHooks = 0;
 
 	/**
 	 * Constructor
@@ -84,9 +84,9 @@ class HookManager
 		global $conf;
 
 		// Test if there is hooks to manage
-        if (!is_array($conf->modules_parts['hooks']) || empty($conf->modules_parts['hooks'])) return;
+		if (!is_array($conf->modules_parts['hooks']) || empty($conf->modules_parts['hooks'])) return;
 
-        // For backward compatibility
+		// For backward compatibility
 		if (!is_array($arraycontext)) $arraycontext = array($arraycontext);
 
 		$this->contextarray = array_unique(array_merge($arraycontext, $this->contextarray)); // All contexts are concatenated
@@ -130,29 +130,29 @@ class HookManager
 		return 1;
 	}
 
-    /**
-     *  Execute hooks (if they were initialized) for the given method
-     *
-     *  @param		string	$method			Name of method hooked ('doActions', 'printSearchForm', 'showInputField', ...)
-     *  @param		array	$parameters		Array of parameters
-     *  @param		Object	$object			Object to use hooks on
-     *  @param		string	$action			Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...)
-     *  @return		mixed					For 'addreplace' hooks (doActions, formConfirm, formObjectOptions, pdf_xxx,...): 	Return 0 if we want to keep standard actions, >0 if we want to stop/replace standard actions, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller.
-     *                                      For 'output' hooks (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...):	Return 0, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller.
-     *                                      All types can also return some values into an array ->results that will be finaly merged into this->resArray for caller.
-     *                                      $this->error or this->errors are also defined by class called by this function if error.
-     */
+	/**
+	 *  Execute hooks (if they were initialized) for the given method
+	 *
+	 *  @param		string	$method			Name of method hooked ('doActions', 'printSearchForm', 'showInputField', ...)
+	 *  @param		array	$parameters		Array of parameters
+	 *  @param		Object	$object			Object to use hooks on
+	 *  @param		string	$action			Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...)
+	 *  @return		mixed					For 'addreplace' hooks (doActions, formConfirm, formObjectOptions, pdf_xxx,...): 	Return 0 if we want to keep standard actions, >0 if we want to stop/replace standard actions, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller.
+	 *                                      For 'output' hooks (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...):	Return 0, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller.
+	 *                                      All types can also return some values into an array ->results that will be finaly merged into this->resArray for caller.
+	 *                                      $this->error or this->errors are also defined by class called by this function if error.
+	 */
 	public function executeHooks($method, $parameters = array(), &$object = '', &$action = '')
 	{
-        if (!is_array($this->hooks) || empty($this->hooks)) return 0;	// No hook available, do nothing.
+		if (!is_array($this->hooks) || empty($this->hooks)) return 0;	// No hook available, do nothing.
 
-        $parameters['context'] = join(':', $this->contextarray);
-        //dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']);
+		$parameters['context'] = join(':', $this->contextarray);
+		//dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']);
 
-        // Define type of hook ('output' or 'addreplace').
-        // TODO Remove hooks with type 'output'. All hooks must be converted into 'addreplace' hooks.
-        $hooktype = 'output';
-        if (in_array(
+		// Define type of hook ('output' or 'addreplace').
+		// TODO Remove hooks with type 'output'. All hooks must be converted into 'addreplace' hooks.
+		$hooktype = 'output';
+		if (in_array(
 			$method,
 			array(
 				'addCalendarChoice',
@@ -172,33 +172,33 @@ class HookManager
 				'formattachOptions',
 				'formBuilddocLineOptions',
 				'formatNotificationMessage',
-			    'formConfirm',
+				'formConfirm',
 				'getAccessForbiddenMessage',
 				'getDirList',
 				'getFormMail',
 				'getFormatedCustomerRef',
-			    'getFormatedSupplierRef',
+				'getFormatedSupplierRef',
 				'getIdProfUrl',
 				'getInputIdProf',
 				'moveUploadedFile',
 				'moreHtmlStatus',
 				'pdf_build_address',
 				'pdf_writelinedesc',
-			    'pdf_getlinenum',
-			    'pdf_getlineref',
-			    'pdf_getlineref_supplier',
-			    'pdf_getlinevatrate',
-			    'pdf_getlineupexcltax',
-			    'pdf_getlineupwithtax',
-			    'pdf_getlineqty',
-			    'pdf_getlineqty_asked',
-			    'pdf_getlineqty_shipped',
-			    'pdf_getlineqty_keeptoship',
-			    'pdf_getlineunit',
-			    'pdf_getlineremisepercent',
-			    'pdf_getlineprogress',
-			    'pdf_getlinetotalexcltax',
-			    'pdf_getlinetotalwithtax',
+				'pdf_getlinenum',
+				'pdf_getlineref',
+				'pdf_getlineref_supplier',
+				'pdf_getlinevatrate',
+				'pdf_getlineupexcltax',
+				'pdf_getlineupwithtax',
+				'pdf_getlineqty',
+				'pdf_getlineqty_asked',
+				'pdf_getlineqty_shipped',
+				'pdf_getlineqty_keeptoship',
+				'pdf_getlineunit',
+				'pdf_getlineremisepercent',
+				'pdf_getlineprogress',
+				'pdf_getlinetotalexcltax',
+				'pdf_getlinetotalwithtax',
 				'paymentsupplierinvoices',
 				'printAddress',
 				'printEmail',
@@ -213,88 +213,88 @@ class HookManager
 				'showLinkToObjectBlock',
 				'setContentSecurityPolicy',
 				'setHtmlTitle',
-                'completeTabsHead'
+				'completeTabsHead'
 				)
 			)) $hooktype = 'addreplace';
 
-        // Init return properties
-        $this->resPrint = ''; $this->resArray = array(); $this->resNbOfHooks = 0;
-
-        // Loop on each hook to qualify modules that have declared context
-        $modulealreadyexecuted = array();
-        $resaction = 0; $error = 0;
-        foreach ($this->hooks as $context => $modules)    // $this->hooks is an array with context as key and value is an array of modules that handle this context
-        {
-            if (!empty($modules))
-            {
-                foreach ($modules as $module => $actionclassinstance)
-                {
-                	//print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."<br>\n";
-
-                    // test to avoid running twice a hook, when a module implements several active contexts
-                    if (in_array($module, $modulealreadyexecuted)) continue;
-
-                	// jump to next module/class if method does not exist
-                    if (!method_exists($actionclassinstance, $method)) continue;
-
-                    $this->resNbOfHooks++;
-
-                    $modulealreadyexecuted[$module] = $module; // Use the $currentcontext in method to avoid running twice
-
-                    // Clean class (an error may have been set from a previous call of another method for same module/hook)
-                    $actionclassinstance->error = 0;
-                    $actionclassinstance->errors = array();
-
-                    dol_syslog(get_class($this)."::executeHooks Qualified hook found (hooktype=".$hooktype."). We call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", action=".$action." context=".$context, LOG_DEBUG);
-
-                    // Add current context to avoid method execution in bad context, you can add this test in your method : eg if($currentcontext != 'formfile') return;
-                    $parameters['currentcontext'] = $context;
-                    // Hooks that must return int (hooks with type 'addreplace')
-                    if ($hooktype == 'addreplace')
-                    {
-                    	$resaction += $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example)
-                    	if ($resaction < 0 || !empty($actionclassinstance->error) || (!empty($actionclassinstance->errors) && count($actionclassinstance->errors) > 0))
-                    	{
-                    		$error++;
-                    		$this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors);
-                    		dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR);
-                    	}
-
-                    	if (isset($actionclassinstance->results) && is_array($actionclassinstance->results))  $this->resArray = array_merge($this->resArray, $actionclassinstance->results);
-                    	if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints;
-                    }
-                    // Generic hooks that return a string or array (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...)
-                    else {
-                    	// TODO. this test should be done into the method of hook by returning nothing
-                    	if (is_array($parameters) && !empty($parameters['special_code']) && $parameters['special_code'] > 3 && $parameters['special_code'] != $actionclassinstance->module_number) continue;
-
-                    	//dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG);
-                    	$resaction = $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example)
-
-                    	if (!empty($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results);
-                    	if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints;
-                    	if (is_numeric($resaction) && $resaction < 0)
-                    	{
-                    	    $error++;
-                    	    $this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors);
-                    	    dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR);
-                    	}
-                    	// TODO dead code to remove (do not enable this, but fix hook instead): result must not be a string but an int. you must use $actionclassinstance->resprints to return a string
-                    	if (!is_array($resaction) && !is_numeric($resaction))
-                    	{
-                    		dol_syslog('Error: Bug into hook '.$method.' of module class '.get_class($actionclassinstance).'. Method must not return a string but an int (0=OK, 1=Replace, -1=KO) and set string into ->resprints', LOG_ERR);
-                    		if (empty($actionclassinstance->resprints)) { $this->resPrint .= $resaction; $resaction = 0; }
-                    	}
-                    }
-
-                    //print "After hook  ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."<br>\n";
-
-                    unset($actionclassinstance->results);
-                    unset($actionclassinstance->resprints);
-                }
-            }
-        }
-
-        return ($error ? -1 : $resaction);
+		// Init return properties
+		$this->resPrint = ''; $this->resArray = array(); $this->resNbOfHooks = 0;
+
+		// Loop on each hook to qualify modules that have declared context
+		$modulealreadyexecuted = array();
+		$resaction = 0; $error = 0;
+		foreach ($this->hooks as $context => $modules)    // $this->hooks is an array with context as key and value is an array of modules that handle this context
+		{
+			if (!empty($modules))
+			{
+				foreach ($modules as $module => $actionclassinstance)
+				{
+					//print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."<br>\n";
+
+					// test to avoid running twice a hook, when a module implements several active contexts
+					if (in_array($module, $modulealreadyexecuted)) continue;
+
+					// jump to next module/class if method does not exist
+					if (!method_exists($actionclassinstance, $method)) continue;
+
+					$this->resNbOfHooks++;
+
+					$modulealreadyexecuted[$module] = $module; // Use the $currentcontext in method to avoid running twice
+
+					// Clean class (an error may have been set from a previous call of another method for same module/hook)
+					$actionclassinstance->error = 0;
+					$actionclassinstance->errors = array();
+
+					dol_syslog(get_class($this)."::executeHooks Qualified hook found (hooktype=".$hooktype."). We call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", action=".$action." context=".$context, LOG_DEBUG);
+
+					// Add current context to avoid method execution in bad context, you can add this test in your method : eg if($currentcontext != 'formfile') return;
+					$parameters['currentcontext'] = $context;
+					// Hooks that must return int (hooks with type 'addreplace')
+					if ($hooktype == 'addreplace')
+					{
+						$resaction += $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example)
+						if ($resaction < 0 || !empty($actionclassinstance->error) || (!empty($actionclassinstance->errors) && count($actionclassinstance->errors) > 0))
+						{
+							$error++;
+							$this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors);
+							dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR);
+						}
+
+						if (isset($actionclassinstance->results) && is_array($actionclassinstance->results))  $this->resArray = array_merge($this->resArray, $actionclassinstance->results);
+						if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints;
+					}
+					// Generic hooks that return a string or array (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...)
+					else {
+						// TODO. this test should be done into the method of hook by returning nothing
+						if (is_array($parameters) && !empty($parameters['special_code']) && $parameters['special_code'] > 3 && $parameters['special_code'] != $actionclassinstance->module_number) continue;
+
+						//dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG);
+						$resaction = $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example)
+
+						if (!empty($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results);
+						if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints;
+						if (is_numeric($resaction) && $resaction < 0)
+						{
+							$error++;
+							$this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors);
+							dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR);
+						}
+						// TODO dead code to remove (do not enable this, but fix hook instead): result must not be a string but an int. you must use $actionclassinstance->resprints to return a string
+						if (!is_array($resaction) && !is_numeric($resaction))
+						{
+							dol_syslog('Error: Bug into hook '.$method.' of module class '.get_class($actionclassinstance).'. Method must not return a string but an int (0=OK, 1=Replace, -1=KO) and set string into ->resprints', LOG_ERR);
+							if (empty($actionclassinstance->resprints)) { $this->resPrint .= $resaction; $resaction = 0; }
+						}
+					}
+
+					//print "After hook  ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."<br>\n";
+
+					unset($actionclassinstance->results);
+					unset($actionclassinstance->resprints);
+				}
+			}
+		}
+
+		return ($error ? -1 : $resaction);
 	}
 }

File diff suppressed because it is too large
+ 666 - 666
htdocs/core/class/html.formother.class.php


+ 19 - 19
htdocs/core/lib/ecm.lib.php

@@ -146,30 +146,30 @@ function ecm_prepare_head_fm($object)
  */
 function ecm_admin_prepare_head()
 {
-    global $langs, $conf;
-    $langs->load("ecm");
+	global $langs, $conf;
+	$langs->load("ecm");
 
-    $h = 0;
-    $head = array();
+	$h = 0;
+	$head = array();
 
-    $head[$h][0] = DOL_URL_ROOT."/admin/ecm.php";
-    $head[$h][1] = $langs->trans("Setup");
-    $head[$h][2] = 'ecm';
-    $h++;
+	$head[$h][0] = DOL_URL_ROOT."/admin/ecm.php";
+	$head[$h][1] = $langs->trans("Setup");
+	$head[$h][2] = 'ecm';
+	$h++;
 
-    $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_files_extrafields.php';
-    $head[$h][1] = $langs->trans("ExtraFieldsEcmFiles");
-    $head[$h][2] = 'attributes_ecm_files';
-    $h++;
+	$head[$h][0] = DOL_URL_ROOT.'/admin/ecm_files_extrafields.php';
+	$head[$h][1] = $langs->trans("ExtraFieldsEcmFiles");
+	$head[$h][2] = 'attributes_ecm_files';
+	$h++;
 
-    $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_directories_extrafields.php';
-    $head[$h][1] = $langs->trans("ExtraFieldsEcmDirectories");
-    $head[$h][2] = 'attributes_ecm_directories';
-    $h++;
+	$head[$h][0] = DOL_URL_ROOT.'/admin/ecm_directories_extrafields.php';
+	$head[$h][1] = $langs->trans("ExtraFieldsEcmDirectories");
+	$head[$h][2] = 'attributes_ecm_directories';
+	$h++;
 
-    complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin');
+	complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin');
 
-    complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin', 'remove');
+	complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin', 'remove');
 
-    return $head;
+	return $head;
 }

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

@@ -1533,7 +1533,7 @@ function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesess
 			$nbok = 0;
 			for ($i = 0; $i < $nbfile; $i++)
 			{
-				if (empty($TFile['name'][$i])) continue;		// For example, when submitting a form with no file name
+				if (empty($TFile['name'][$i])) continue; // For example, when submitting a form with no file name
 
 				// Define $destfull (path to file including filename) and $destfile (only filename)
 				$destfull = $upload_dir."/".$TFile['name'][$i];
@@ -2053,7 +2053,7 @@ function dol_uncompress($inputfile, $outputdir)
 			for ($i = 0; $i < $zip->numFiles; $i++) {
 				if (preg_match('/\.\./', $zip->getNameIndex($i))) {
 					dol_syslog("Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING);
-					continue;	// Discard the file
+					continue; // Discard the file
 				}
 				$zip->extractTo($outputdir.'/', array($zip->getNameIndex($i)));
 			}

+ 10 - 10
htdocs/core/lib/functions.lib.php

@@ -84,8 +84,8 @@ function getEntity($element, $shared = 1, $currentobject = null)
 
 	// fix different element names (France to English)
 	switch ($element) {
-		case 'contrat':			$element = 'contract';			break;	// "/contrat/class/contrat.class.php"
-		case 'order_supplier':	$element = 'supplier_order';	break;	// "/fourn/class/fournisseur.commande.class.php"
+		case 'contrat':			$element = 'contract'; break; // "/contrat/class/contrat.class.php"
+		case 'order_supplier':	$element = 'supplier_order'; break; // "/fourn/class/fournisseur.commande.class.php"
 	}
 
 	if (is_object($mc))
@@ -1404,7 +1404,7 @@ function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab
 		$tabsname = $moretabssuffix;
 		if (empty($tabsname)) { $tabsname = str_replace("@", "", $picto); }
 		$out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
-		$out .= '<a href="#" class="tab moretab inline-block tabunactive">'.$langs->trans("More").'... ('.$nbintab.')</a>';	// Do not use "reposition" class in the "More".
+		$out .= '<a href="#" class="tab moretab inline-block tabunactive">'.$langs->trans("More").'... ('.$nbintab.')</a>'; // Do not use "reposition" class in the "More".
 		$out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
 		$out .= $outmore;
 		$out .= '</div>';
@@ -1415,7 +1415,7 @@ function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab
 		$out .= "$('#moretabs".$tabsname."').mouseenter( function() {
 			var x = this.offsetLeft, y = this.offsetTop;
 			console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
-			if ((window.innerWidth - x) < ".($widthofpopup+10).") {
+			if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
 				$('#moretabsList".$tabsname."').css('".$right."','8px');
 			}
 			$('#moretabsList".$tabsname."').css('".$left."','auto');
@@ -2808,7 +2808,7 @@ function getUserRemoteIP()
 			$ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here
 		}
 	} else {
-		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];	// value is clean here
+		$ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here
 	}
 	return $ip;
 }
@@ -4048,7 +4048,7 @@ function dol_print_error($db = '', $error = '', $errors = null)
 	}
 
 	// Return a http error code if possible
-	if (! headers_sent()) {
+	if (!headers_sent()) {
 		http_response_code(500);
 	}
 
@@ -7833,7 +7833,7 @@ function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
 					$numnewcrit = price2num($newcrit);
 					if (is_numeric($numnewcrit))
 					{
-						$newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit);	// should be a numeric
+						$newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric
 					} else {
 						$newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
 					}
@@ -7841,7 +7841,7 @@ function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
 				}
 			} elseif ($mode == 2 || $mode == -2)
 			{
-				$crit = preg_replace('/[^0-9,]/', '', $crit);	// ID are always integer
+				$crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
 				$newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
 				$newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
 				if ($mode == -2) $newres .= ' OR '.$field.' IS NULL';
@@ -8979,8 +8979,8 @@ function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
 
 	if ($method == -1) {
 		$method = 0;
-		if (! empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1;
-		if (! empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2;
+		if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1;
+		if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2;
 	}
 
 	// Be sure we don't have output buffering enabled to have readfile working correctly

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

@@ -29,30 +29,30 @@
 function payment_prepare_head(Paiement $object)
 {
 
-    global $langs, $conf;
+	global $langs, $conf;
 
-    $h = 0;
-    $head = array();
+	$h = 0;
+	$head = array();
 
-    $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$object->id;
-    $head[$h][1] = $langs->trans("Payment");
-    $head[$h][2] = 'payment';
-    $h++;
+	$head[$h][0] = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$object->id;
+	$head[$h][1] = $langs->trans("Payment");
+	$head[$h][2] = 'payment';
+	$h++;
 
-    // Show more tabs from modules
-    // Entries must be declared in modules descriptor with line
-    // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
-    // $this->tabs = array('entity:-tabname);   												to remove a tab
-    complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment');
+	// Show more tabs from modules
+	// Entries must be declared in modules descriptor with line
+	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
+	// $this->tabs = array('entity:-tabname);   												to remove a tab
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment');
 
-    $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/info.php?id='.$object->id;
-    $head[$h][1] = $langs->trans("Info");
-    $head[$h][2] = 'info';
-    $h++;
+	$head[$h][0] = DOL_URL_ROOT.'/compta/paiement/info.php?id='.$object->id;
+	$head[$h][1] = $langs->trans("Info");
+	$head[$h][2] = 'info';
+	$h++;
 
-    complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment', 'remove');
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment', 'remove');
 
-    return $head;
+	return $head;
 }
 
 /**
@@ -64,30 +64,30 @@ function payment_prepare_head(Paiement $object)
  */
 function bankline_prepare_head($id)
 {
-    global $langs, $conf;
+	global $langs, $conf;
 
-    $h = 0;
-    $head = array();
+	$h = 0;
+	$head = array();
 
-    $head[$h][0] = DOL_URL_ROOT.'/compta/bank/line.php?rowid='.$id;
-    $head[$h][1] = $langs->trans('BankTransaction');
-    $head[$h][2] = 'bankline';
-    $h++;
+	$head[$h][0] = DOL_URL_ROOT.'/compta/bank/line.php?rowid='.$id;
+	$head[$h][1] = $langs->trans('BankTransaction');
+	$head[$h][2] = 'bankline';
+	$h++;
 
-    // Show more tabs from modules
-    // Entries must be declared in modules descriptor with line
-    // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
-    // $this->tabs = array('entity:-tabname);   												to remove a tab
-    complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline');
+	// Show more tabs from modules
+	// Entries must be declared in modules descriptor with line
+	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
+	// $this->tabs = array('entity:-tabname);   												to remove a tab
+	complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline');
 
-    $head[$h][0] = DOL_URL_ROOT.'/compta/bank/info.php?rowid='.$id;
-    $head[$h][1] = $langs->trans("Info");
-    $head[$h][2] = 'info';
-    $h++;
+	$head[$h][0] = DOL_URL_ROOT.'/compta/bank/info.php?rowid='.$id;
+	$head[$h][1] = $langs->trans("Info");
+	$head[$h][2] = 'info';
+	$h++;
 
-    complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline', 'remove');
+	complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline', 'remove');
 
-    return $head;
+	return $head;
 }
 
 /**
@@ -109,11 +109,11 @@ function payment_supplier_prepare_head(Paiement $object)
 	$head[$h][2] = 'payment';
 	$h++;
 
-    // Show more tabs from modules
-    // Entries must be declared in modules descriptor with line
-    // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
-    // $this->tabs = array('entity:-tabname);   												to remove a tab
-    complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment_supplier');
+	// Show more tabs from modules
+	// Entries must be declared in modules descriptor with line
+	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
+	// $this->tabs = array('entity:-tabname);   												to remove a tab
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment_supplier');
 
 	$head[$h][0] = DOL_URL_ROOT.'/fourn/paiement/info.php?id='.$object->id;
 	$head[$h][1] = $langs->trans('Info');
@@ -170,7 +170,7 @@ function showOnlinePaymentUrl($type, $ref)
 	global $langs;
 
 	// Load translation files required by the page
-    $langs->loadLangs(array('payment', 'stripe'));
+	$langs->loadLangs(array('payment', 'stripe'));
 
 	$servicename = $langs->transnoentitiesnoconv('Online');
 
@@ -194,7 +194,7 @@ function showOnlinePaymentUrl($type, $ref)
  */
 function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag = 'your_tag', $localorexternal = 0)
 {
-    global $conf, $dolibarr_main_url_root;
+	global $conf, $dolibarr_main_url_root;
 
 	$ref = str_replace(' ', '', $ref);
 	$out = '';
@@ -209,7 +209,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
 
 	if ($type == 'free')
 	{
-	    $out = $urltouse.'/public/payment/newpayment.php?amount='.($mode ? '<font color="#666666">' : '').$amount.($mode ? '</font>' : '').'&tag='.($mode ? '<font color="#666666">' : '').$freetag.($mode ? '</font>' : '');
+		$out = $urltouse.'/public/payment/newpayment.php?amount='.($mode ? '<font color="#666666">' : '').$amount.($mode ? '</font>' : '').'&tag='.($mode ? '<font color="#666666">' : '').$freetag.($mode ? '</font>' : '');
 		if (!empty($conf->global->PAYMENT_SECURITY_TOKEN))
 		{
 			if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN;
@@ -218,7 +218,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
 		//if ($mode) $out.='&noidempotency=1';
 	} elseif ($type == 'order')
 	{
-	    $out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '<font color="#666666">' : '');
+		$out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '<font color="#666666">' : '');
 		if ($mode == 1) $out .= 'order_ref';
 		if ($mode == 0) $out .= urlencode($ref);
 		$out .= ($mode ? '</font>' : '');
@@ -234,7 +234,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
 		}
 	} elseif ($type == 'invoice')
 	{
-	    $out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '<font color="#666666">' : '');
+		$out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '<font color="#666666">' : '');
 		if ($mode == 1) $out .= 'invoice_ref';
 		if ($mode == 0) $out .= urlencode($ref);
 		$out .= ($mode ? '</font>' : '');
@@ -250,7 +250,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
 		}
 	} elseif ($type == 'contractline')
 	{
-	    $out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '<font color="#666666">' : '');
+		$out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '<font color="#666666">' : '');
 		if ($mode == 1) $out .= 'contractline_ref';
 		if ($mode == 0) $out .= urlencode($ref);
 		$out .= ($mode ? '</font>' : '');
@@ -266,7 +266,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
 		}
 	} elseif ($type == 'member' || $type == 'membersubscription')
 	{
-	    $out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '<font color="#666666">' : '');
+		$out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '<font color="#666666">' : '');
 		if ($mode == 1) $out .= 'member_ref';
 		if ($mode == 0) $out .= urlencode($ref);
 		$out .= ($mode ? '</font>' : '');
@@ -283,7 +283,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
 	}
 	if ($type == 'donation')
 	{
-	    $out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '<font color="#666666">' : '');
+		$out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '<font color="#666666">' : '');
 		if ($mode == 1) $out .= 'donation_ref';
 		if ($mode == 0) $out .= urlencode($ref);
 		$out .= ($mode ? '</font>' : '');
@@ -319,82 +319,82 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag
  */
 function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0, $suffix = '', $object = null)
 {
-    global $conf;
-
-    // Juridical status
-    $line1 = "";
-    if ($fromcompany->forme_juridique_code)
-    {
-        $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code);
-    }
-    // Capital
-    if ($fromcompany->capital)
-    {
-        $line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency);
-    }
-    // Prof Id 1
-    if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2))
-    {
-        $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code);
-        if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
-        $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1;
-    }
-    // Prof Id 2
-    if ($fromcompany->idprof2)
-    {
-        $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code);
-        if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
-        $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2;
-    }
-
-    // Second line of company infos
-    $line2 = "";
-    // Prof Id 3
-    if ($fromcompany->idprof3)
-    {
-        $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code);
-        if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
-        $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3;
-    }
-    // Prof Id 4
-    if ($fromcompany->idprof4)
-    {
-        $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code);
-        if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
-        $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4;
-    }
-    // IntraCommunautary VAT
-    if ($fromcompany->tva_intra != '')
-    {
-        $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra;
-    }
-
-    print '<br>';
-
-    print '<div class="center">'."\n";
-    if ($addformmessage)
-    {
-    	print '<!-- object = '.$object->element.' -->';
-    	print '<br>';
-
-    	$parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix;
-    	if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
-    	elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM);
-
-    	// Add other message if VAT exists
-    	if ($object->total_vat != 0 || $object->total_tva != 0)
-    	{
-    		$parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix;
-    		if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
-    		elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT);
-    	}
-    }
-
-    print '<font style="font-size: 10px;"><br><hr>'."\n";
-    print $fromcompany->name.'<br>';
-    print $line1;
-    if (strlen($line1.$line2) > 50) print '<br>';
-    else print ' - ';
-    print $line2;
-    print '</font></div>'."\n";
+	global $conf;
+
+	// Juridical status
+	$line1 = "";
+	if ($fromcompany->forme_juridique_code)
+	{
+		$line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code);
+	}
+	// Capital
+	if ($fromcompany->capital)
+	{
+		$line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency);
+	}
+	// Prof Id 1
+	if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2))
+	{
+		$field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code);
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+		$line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1;
+	}
+	// Prof Id 2
+	if ($fromcompany->idprof2)
+	{
+		$field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code);
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+		$line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2;
+	}
+
+	// Second line of company infos
+	$line2 = "";
+	// Prof Id 3
+	if ($fromcompany->idprof3)
+	{
+		$field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code);
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+		$line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3;
+	}
+	// Prof Id 4
+	if ($fromcompany->idprof4)
+	{
+		$field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code);
+		if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1];
+		$line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4;
+	}
+	// IntraCommunautary VAT
+	if ($fromcompany->tva_intra != '')
+	{
+		$line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra;
+	}
+
+	print '<br>';
+
+	print '<div class="center">'."\n";
+	if ($addformmessage)
+	{
+		print '<!-- object = '.$object->element.' -->';
+		print '<br>';
+
+		$parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix;
+		if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
+		elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM);
+
+		// Add other message if VAT exists
+		if ($object->total_vat != 0 || $object->total_tva != 0)
+		{
+			$parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix;
+			if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform);
+			elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT);
+		}
+	}
+
+	print '<font style="font-size: 10px;"><br><hr>'."\n";
+	print $fromcompany->name.'<br>';
+	print $line1;
+	if (strlen($line1.$line2) > 50) print '<br>';
+	else print ' - ';
+	print $line2;
+	print '</font></div>'."\n";
 }

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

@@ -122,7 +122,7 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P')
 		define('K_SMALL_RATIO', 2 / 3);
 		define('K_THAI_TOPCHARS', true);
 		define('K_TCPDF_CALLS_IN_HTML', true);
-		if (! empty($conf->global->TCPDF_THROW_ERRORS_INSTEAD_OF_DIE)) {
+		if (!empty($conf->global->TCPDF_THROW_ERRORS_INSTEAD_OF_DIE)) {
 			define('K_TCPDF_THROW_EXCEPTION_ERROR', true);
 		} else {
 			define('K_TCPDF_THROW_EXCEPTION_ERROR', false);
@@ -2140,11 +2140,11 @@ function pdf_getLinkedObjects($object, $outputlangs)
 			    if (empty($object->linkedObjects['commande']) && $object->element != 'commande')	// There is not already a link to order and object is not the order, so we show also info with order
 			    {
 			        $elementobject->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
-			        if (! empty($elementobject->linkedObjectsIds['commande'])){
+			        if (!empty($elementobject->linkedObjectsIds['commande'])) {
 						include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
 						$order = new Commande($db);
 						$ret = $order->fetch(reset($elementobject->linkedObjectsIds['commande']));
-						if ($ret < 1) { $order=null; }
+						if ($ret < 1) { $order = null; }
 					}
 			    }
 			    if (!is_object($order))

+ 18 - 18
htdocs/core/modules/modCommande.class.php

@@ -265,16 +265,16 @@ class modCommande extends DolibarrModules
 		if (empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .= ' AND sc.fk_user = '.(empty($user) ? 0 : $user->id);
 		// Imports
 		//--------
-		$r=0;
+		$r = 0;
 		//Import Order Header
 
 		$r++;
-		$this->import_code[$r] = 'commande_' . $r;
+		$this->import_code[$r] = 'commande_'.$r;
 		$this->import_label[$r] = 'Sales Orders';
 		$this->import_icon[$r] = $this->picto;
 		$this->import_entities_array[$r] = [];
-		$this->import_tables_array[$r] = ['c' => MAIN_DB_PREFIX . 'commande', 'extra' => MAIN_DB_PREFIX . 'commande_extrafields'];
-		$this->import_tables_creator_array[$r] = ['c' => 'fk_user_author'];	// Fields to store import user id
+		$this->import_tables_array[$r] = ['c' => MAIN_DB_PREFIX.'commande', 'extra' => MAIN_DB_PREFIX.'commande_extrafields'];
+		$this->import_tables_creator_array[$r] = ['c' => 'fk_user_author']; // Fields to store import user id
 		$this->import_fields_array[$r] = [
 			'c.ref'               => 'Document Ref*',
 			'c.ref_client'        => 'RefCustomer',
@@ -299,7 +299,7 @@ class modCommande extends DolibarrModules
 			'c.model_pdf'         => 'Model'
 		];
 
-		if (! empty($conf->multicurrency->enabled)) {
+		if (!empty($conf->multicurrency->enabled)) {
 			$this->import_fields_array[$r]['c.multicurrency_code']      = 'Currency';
 			$this->import_fields_array[$r]['c.multicurrency_tx']        = 'CurrencyRate';
 			$this->import_fields_array[$r]['c.multicurrency_total_ht']  = 'MulticurrencyAmountHT';
@@ -309,23 +309,23 @@ class modCommande extends DolibarrModules
 
 		// Add extra fields
 		$import_extrafield_sample = [];
-		$sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'commande' AND entity IN (0, " . $conf->entity . ")";
+		$sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'commande' AND entity IN (0, ".$conf->entity.")";
 		$resql = $this->db->query($sql);
 
 		if ($resql) {
 			while ($obj = $this->db->fetch_object($resql)) {
-				$fieldname = 'extra.' . $obj->name;
+				$fieldname = 'extra.'.$obj->name;
 				$fieldlabel = ucfirst($obj->label);
-				$this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : '');
+				$this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : '');
 				$import_extrafield_sample[$fieldname] = $fieldlabel;
 			}
 		}
 		// End add extra fields
 
-		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'commande'];
+		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'commande'];
 		$this->import_regex_array[$r] = [
 			'c.ref' => '(CPV\d{4}-\d{4}|CO\d{4}-\d{4}|PROV.{1,32}$)',
-			'c.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency'
+			'c.multicurrency_code' => 'code@'.MAIN_DB_PREFIX.'multicurrency'
 		];
 
 		$this->import_updatekeys_array[$r] = ['c.ref' => 'Ref'];
@@ -359,7 +359,7 @@ class modCommande extends DolibarrModules
 		$this->import_label[$r] = 'Order Details';
 		$this->import_icon[$r] = $this->picto;
 		$this->import_entities_array[$r] = [];
-		$this->import_tables_array[$r] = ['cd' => MAIN_DB_PREFIX . 'commandedet', 'extra' => MAIN_DB_PREFIX . 'commandedet_extrafields'];
+		$this->import_tables_array[$r] = ['cd' => MAIN_DB_PREFIX.'commandedet', 'extra' => MAIN_DB_PREFIX.'commandedet_extrafields'];
 		$this->import_fields_array[$r] = [
 			'cd.fk_commande'    => 'Document Ref*',
 			'cd.fk_parent_line' => 'PrParentLine',
@@ -382,7 +382,7 @@ class modCommande extends DolibarrModules
 			'cd.rang'           => 'LinePosition'
 		];
 
-		if (! empty($conf->multicurrency->enabled)) {
+		if (!empty($conf->multicurrency->enabled)) {
 			$this->import_fields_array[$r]['cd.multicurrency_code'] = 'Currency';
 			$this->import_fields_array[$r]['cd.multicurrency_subprice'] = 'CurrencyRate';
 			$this->import_fields_array[$r]['cd.multicurrency_total_ht'] = 'MulticurrencyAmountHT';
@@ -391,22 +391,22 @@ class modCommande extends DolibarrModules
 		}
 
 		// Add extra fields
-		$sql="SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'commandedet' AND entity IN (0, " . $conf->entity . ")";
+		$sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'commandedet' AND entity IN (0, ".$conf->entity.")";
 		$resql = $this->db->query($sql);
 		if ($resql) {
 			while ($obj = $this->db->fetch_object($resql)) {
-				$fieldname = 'extra.' . $obj->name;
+				$fieldname = 'extra.'.$obj->name;
 				$fieldlabel = ucfirst($obj->label);
-				$this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : '');
+				$this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : '');
 			}
 		}
 		// End add extra fields
 
-		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'commandedet'];
+		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'commandedet'];
 		$this->import_regex_array[$r] = [
 			'cd.product_type'       => '[0|1]$',
-			'cd.fk_product'         => 'rowid@' . MAIN_DB_PREFIX . 'product',
-			'cd.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency'
+			'cd.fk_product'         => 'rowid@'.MAIN_DB_PREFIX.'product',
+			'cd.multicurrency_code' => 'code@'.MAIN_DB_PREFIX.'multicurrency'
 		];
 		$this->import_updatekeys_array[$r] = ['cd.fk_commande' => 'Sales Order Id', 'cd.fk_product' => 'Product Id'];
 		$this->import_convertvalue_array[$r] = [

+ 29 - 29
htdocs/core/modules/modFournisseur.class.php

@@ -63,12 +63,12 @@ class modFournisseur extends DolibarrModules
 
 		// Data directories to create when module is enabled
 		$this->dirs = array(
-            "/fournisseur/temp",
-            "/fournisseur/commande",
-            "/fournisseur/commande/temp",
-            "/fournisseur/facture",
-            "/fournisseur/facture/temp"
-        );
+			"/fournisseur/temp",
+			"/fournisseur/commande",
+			"/fournisseur/commande/temp",
+			"/fournisseur/facture",
+			"/fournisseur/facture/temp"
+		);
 
 		// Dependencies
 		$this->depends = array("modSociete");
@@ -299,7 +299,7 @@ class modFournisseur extends DolibarrModules
 			'p.ref'=>'ProductRef', 'p.label'=>'ProductLabel', 'p.accountancy_code_buy'=>'ProductAccountancyBuyCode', 'project.rowid'=>'ProjectId',
 			'project.ref'=>'ProjectRef', 'project.title'=>'ProjectLabel'
 		);
-		if (! empty($conf->multicurrency->enabled))
+		if (!empty($conf->multicurrency->enabled))
 		{
 			$this->export_fields_array[$r]['f.multicurrency_code'] = 'Currency';
 			$this->export_fields_array[$r]['f.multicurrency_tx'] = 'CurrencyRate';
@@ -434,7 +434,7 @@ class modFournisseur extends DolibarrModules
 			'f.fk_statut'=>'InvoiceStatus', 'f.note_public'=>"InvoiceNote", 'p.rowid'=>'PaymentId', 'pf.amount'=>'AmountPayment',
 			'p.datep'=>'DatePayment', 'p.num_paiement'=>'PaymentNumber', 'p.fk_bank'=>'IdTransaction', 'project.rowid'=>'ProjectId', 'project.ref'=>'ProjectRef', 'project.title'=>'ProjectLabel'
 		);
-		if (! empty($conf->multicurrency->enabled))
+		if (!empty($conf->multicurrency->enabled))
 		{
 			$this->export_fields_array[$r]['f.multicurrency_code'] = 'Currency';
 			$this->export_fields_array[$r]['f.multicurrency_tx'] = 'CurrencyRate';
@@ -528,7 +528,7 @@ class modFournisseur extends DolibarrModules
 			'fd.total_tva'=>"LineTotalVAT", 'fd.product_type'=>'TypeOfLineServiceOrProduct', 'fd.ref'=>'RefSupplier', 'fd.fk_product'=>'ProductId',
 			'p.ref'=>'ProductRef', 'p.label'=>'ProductLabel', 'project.rowid'=>'ProjectId', 'project.ref'=>'ProjectRef', 'project.title'=>'ProjectLabel'
 		);
-		if (! empty($conf->multicurrency->enabled))
+		if (!empty($conf->multicurrency->enabled))
 		{
 			$this->export_fields_array[$r]['f.multicurrency_code'] = 'Currency';
 			$this->export_fields_array[$r]['f.multicurrency_tx'] = 'CurrencyRate';
@@ -654,15 +654,15 @@ class modFournisseur extends DolibarrModules
 
 		//Import Supplier Invoice
 		//--------
-		$r=0;
+		$r = 0;
 
 		$r++;
-		$this->import_code[$r] = $this->rights_class . '_' . $r;
-		$this->import_label[$r] = "Supplier Invoice";	// Translation key
+		$this->import_code[$r] = $this->rights_class.'_'.$r;
+		$this->import_label[$r] = "Supplier Invoice"; // Translation key
 		$this->import_icon[$r] = $this->picto;
-		$this->import_entities_array[$r] = [];		// We define here only fields that use another icon that the one defined into import_icon
-		$this->import_tables_array[$r] = ['f' => MAIN_DB_PREFIX . 'facture_fourn', 'extra' => MAIN_DB_PREFIX . 'facture_fourn_extrafields'];
-		$this->import_tables_creator_array[$r] = ['f' => 'fk_user_author'];	// Fields to store import user id
+		$this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon
+		$this->import_tables_array[$r] = ['f' => MAIN_DB_PREFIX.'facture_fourn', 'extra' => MAIN_DB_PREFIX.'facture_fourn_extrafields'];
+		$this->import_tables_creator_array[$r] = ['f' => 'fk_user_author']; // Fields to store import user id
 		$this->import_fields_array[$r] = [
 			'f.ref' => 'InvoiceRef*',
 			'f.ref_supplier' => 'RefSupplier',
@@ -697,19 +697,19 @@ class modFournisseur extends DolibarrModules
 		}
 		// Add extra fields
 		$import_extrafield_sample = [];
-		$sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'facture_fourn' AND entity IN (0, " . $conf->entity . ")";
+		$sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'facture_fourn' AND entity IN (0, ".$conf->entity.")";
 		$resql = $this->db->query($sql);
 		if ($resql) {
 			while ($obj = $this->db->fetch_object($resql)) {
-				$fieldname = 'extra.' . $obj->name;
+				$fieldname = 'extra.'.$obj->name;
 				$fieldlabel = ucfirst($obj->label);
-				$this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : '');
+				$this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : '');
 				$import_extrafield_sample[$fieldname] = $fieldlabel;
 			}
 		}
 		// End add extra fields
-		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'facture_fourn'];
-		$this->import_regex_array[$r] = ['f.ref' => '(SI\d{4}-\d{4}|PROV.{1,32}$)', 'f.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency'];
+		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'facture_fourn'];
+		$this->import_regex_array[$r] = ['f.ref' => '(SI\d{4}-\d{4}|PROV.{1,32}$)', 'f.multicurrency_code' => 'code@'.MAIN_DB_PREFIX.'multicurrency'];
 		$import_sample = [
 			'f.ref' => '(PROV001)',
 			'f.ref_supplier' => 'Supplier1',
@@ -751,10 +751,10 @@ class modFournisseur extends DolibarrModules
 		//Import Supplier Invoice Lines
 		$r++;
 		$this->import_code[$r] = $this->rights_class.'_'.$r;
-		$this->import_label[$r] = "Supplier Invoice Lines";	// Translation key
+		$this->import_label[$r] = "Supplier Invoice Lines"; // Translation key
 		$this->import_icon[$r] = $this->picto;
-		$this->import_entities_array[$r] = [];		// We define here only fields that use another icon that the one defined into import_icon
-		$this->import_tables_array[$r] = ['fd' => MAIN_DB_PREFIX . 'facture_fourn_det', 'extra' => MAIN_DB_PREFIX . 'facture_fourn_det_extrafields'];
+		$this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon
+		$this->import_tables_array[$r] = ['fd' => MAIN_DB_PREFIX.'facture_fourn_det', 'extra' => MAIN_DB_PREFIX.'facture_fourn_det_extrafields'];
 		$this->import_fields_array[$r] = [
 			'fd.fk_facture_fourn' => 'InvoiceRef*',
 			'fd.fk_parent_line' => 'FacParentLine',
@@ -784,19 +784,19 @@ class modFournisseur extends DolibarrModules
 		}
 		// Add extra fields
 		$import_extrafield_sample = [];
-		$sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'facture_fourn_det' AND entity IN (0, " . $conf->entity . ")";
+		$sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'facture_fourn_det' AND entity IN (0, ".$conf->entity.")";
 		$resql = $this->db->query($sql);
 		if ($resql) {
 			while ($obj = $this->db->fetch_object($resql)) {
-				$fieldname = 'extra.' . $obj->name;
+				$fieldname = 'extra.'.$obj->name;
 				$fieldlabel = ucfirst($obj->label);
-				$this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : '');
+				$this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : '');
 				$import_extrafield_sample[$fieldname] = $fieldlabel;
 			}
 		}
 		// End add extra fields
-		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'facture_fourn_det'];
-		$this->import_regex_array[$r] = ['fd.product_type' => '[0|1]$', 'fd.fk_product' => 'rowid@' . MAIN_DB_PREFIX . 'product', 'fd.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency'];
+		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'facture_fourn_det'];
+		$this->import_regex_array[$r] = ['fd.product_type' => '[0|1]$', 'fd.fk_product' => 'rowid@'.MAIN_DB_PREFIX.'product', 'fd.multicurrency_code' => 'code@'.MAIN_DB_PREFIX.'multicurrency'];
 		$import_sample = [
 			'fd.fk_facture_fourn' => '(PROV001)',
 			'fd.fk_parent_line' => '',
@@ -835,7 +835,7 @@ class modFournisseur extends DolibarrModules
 	 *		The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
 	 *		It also creates data directories
 	 *
-     *      @param      string	$options    Options when enabling module ('', 'noboxes')
+	 *      @param      string	$options    Options when enabling module ('', 'noboxes')
 	 *      @return     int             	1 if OK, 0 if KO
 	 */
 	public function init($options = '')

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

@@ -33,155 +33,155 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
  */
 class modMrp extends DolibarrModules
 {
-    /**
-     * Constructor. Define names, constants, directories, boxes, permissions
-     *
-     * @param DoliDB $db Database handler
-     */
-    public function __construct($db)
-    {
-        global $langs, $conf;
-        $this->db = $db;
+	/**
+	 * Constructor. Define names, constants, directories, boxes, permissions
+	 *
+	 * @param DoliDB $db Database handler
+	 */
+	public function __construct($db)
+	{
+		global $langs, $conf;
+		$this->db = $db;
 
-        // Id for module (must be unique).
-        // Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id).
-        $this->numero = 660;
-        // Key text used to identify module (for permissions, menus, etc...)
-        $this->rights_class = 'mrp';
-        // Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...'
-        // It is used to group modules by family in module setup page
-        $this->family = "products";
-        // Module position in the family on 2 digits ('01', '10', '20', ...)
-        $this->module_position = '66';
-        // Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this)
-        //$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily")));
-        // Module label (no space allowed), used if translation string 'ModuleMrpName' not found (Mrp is name of module).
-        $this->name = preg_replace('/^mod/i', '', get_class($this));
-        // Module description, used if translation string 'ModuleMrpDesc' not found (Mrp is name of module).
-        $this->description = "Module to Manage Manufacturing Orders (MO)";
-        // Used only if file README.md and README-LL.md not found.
-        $this->descriptionlong = "Module to Manage Manufacturing Orders (MO)";
-        // Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated' or a version string like 'x.y.z'
-        $this->version = 'dolibarr';
-        // Url to the file with your last numberversion of this module
-        //$this->url_last_version = 'http://www.example.com/versionmodule.txt';
+		// Id for module (must be unique).
+		// Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id).
+		$this->numero = 660;
+		// Key text used to identify module (for permissions, menus, etc...)
+		$this->rights_class = 'mrp';
+		// Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...'
+		// It is used to group modules by family in module setup page
+		$this->family = "products";
+		// Module position in the family on 2 digits ('01', '10', '20', ...)
+		$this->module_position = '66';
+		// Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this)
+		//$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily")));
+		// Module label (no space allowed), used if translation string 'ModuleMrpName' not found (Mrp is name of module).
+		$this->name = preg_replace('/^mod/i', '', get_class($this));
+		// Module description, used if translation string 'ModuleMrpDesc' not found (Mrp is name of module).
+		$this->description = "Module to Manage Manufacturing Orders (MO)";
+		// Used only if file README.md and README-LL.md not found.
+		$this->descriptionlong = "Module to Manage Manufacturing Orders (MO)";
+		// Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated' or a version string like 'x.y.z'
+		$this->version = 'dolibarr';
+		// Url to the file with your last numberversion of this module
+		//$this->url_last_version = 'http://www.example.com/versionmodule.txt';
 
-        // Key used in llx_const table to save module status enabled/disabled (where MRP is value of property name of module in uppercase)
-        $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
-        // 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';
-        // 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)
-            'triggers' => 0,
-            // Set this to 1 if module has its own login method file (core/login)
-            'login' => 0,
-            // Set this to 1 if module has its own substitution function file (core/substitutions)
-            'substitutions' => 0,
-            // Set this to 1 if module has its own menus handler directory (core/menus)
-            'menus' => 0,
-            // Set this to 1 if module overwrite template dir (core/tpl)
-            'tpl' => 0,
-            // Set this to 1 if module has its own barcode directory (core/modules/barcode)
-            'barcode' => 0,
-            // Set this to 1 if module has its own models directory (core/modules/xxx)
-            'models' => 0,
-            // Set this to 1 if module has its own theme directory (theme)
-            'theme' => 0,
-            // Set this to relative path of css file if module has its own css file
-            'css' => array(
-                //    '/mrp/css/mrp.css.php',
-            ),
-            // Set this to relative path of js file if module must load a js on all pages
-            'js' => array(
-                //   '/mrp/js/mrp.js.php',
-            ),
-            // 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 to 'all'
-            'hooks' => array(
-                //   'data' => array(
-                //       'hookcontext1',
-                //       'hookcontext2',
-                //   ),
-                //   'entity' => '0',
-            ),
-            // Set this to 1 if features of module are opened to external users
-            'moduleforexternal' => 0,
-        );
-        // Data directories to create when module is enabled.
-        // Example: this->dirs = array("/mrp/temp","/mrp/subdir");
-        $this->dirs = array("/mrp/temp");
-        // Config pages. Put here list of php page, stored into mrp/admin directory, to use to setup module.
-        $this->config_page_url = array("mrp.php");
-        // Dependencies
-        // A condition to hide module
-        $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->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->automatic_activation = array('FR'=>'MrpWasAutomaticallyActivatedBecauseOfYourCountryChoice');
-        //$this->always_enabled = true;								// If true, can't be disabled
+		// Key used in llx_const table to save module status enabled/disabled (where MRP is value of property name of module in uppercase)
+		$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
+		// 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';
+		// 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)
+			'triggers' => 0,
+			// Set this to 1 if module has its own login method file (core/login)
+			'login' => 0,
+			// Set this to 1 if module has its own substitution function file (core/substitutions)
+			'substitutions' => 0,
+			// Set this to 1 if module has its own menus handler directory (core/menus)
+			'menus' => 0,
+			// Set this to 1 if module overwrite template dir (core/tpl)
+			'tpl' => 0,
+			// Set this to 1 if module has its own barcode directory (core/modules/barcode)
+			'barcode' => 0,
+			// Set this to 1 if module has its own models directory (core/modules/xxx)
+			'models' => 0,
+			// Set this to 1 if module has its own theme directory (theme)
+			'theme' => 0,
+			// Set this to relative path of css file if module has its own css file
+			'css' => array(
+				//    '/mrp/css/mrp.css.php',
+			),
+			// Set this to relative path of js file if module must load a js on all pages
+			'js' => array(
+				//   '/mrp/js/mrp.js.php',
+			),
+			// 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 to 'all'
+			'hooks' => array(
+				//   'data' => array(
+				//       'hookcontext1',
+				//       'hookcontext2',
+				//   ),
+				//   'entity' => '0',
+			),
+			// Set this to 1 if features of module are opened to external users
+			'moduleforexternal' => 0,
+		);
+		// Data directories to create when module is enabled.
+		// Example: this->dirs = array("/mrp/temp","/mrp/subdir");
+		$this->dirs = array("/mrp/temp");
+		// Config pages. Put here list of php page, stored into mrp/admin directory, to use to setup module.
+		$this->config_page_url = array("mrp.php");
+		// Dependencies
+		// A condition to hide module
+		$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->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->automatic_activation = array('FR'=>'MrpWasAutomaticallyActivatedBecauseOfYourCountryChoice');
+		//$this->always_enabled = true;								// If true, can't be disabled
 
-        // Constants
-        // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive)
-        // Example: $this->const=array(1 => array('MRP_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1),
-        //                             2 => array('MRP_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1)
-        // );
-        $this->const = array(
-        	1=>array('MRP_MO_ADDON_PDF', 'chaine', 'alpha', 'Name of PDF model of MO', 0),
-        	2=>array('MRP_MO_ADDON', 'chaine', 'mod_mo_standard', 'Name of numbering rules of MO', 0),
-        	3=>array('MRP_MO_ADDON_PDF_ODT_PATH', 'chaine', 'DOL_DATA_ROOT/doctemplates/mrps', '', 0)
-        );
+		// Constants
+		// List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive)
+		// Example: $this->const=array(1 => array('MRP_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1),
+		//                             2 => array('MRP_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1)
+		// );
+		$this->const = array(
+			1=>array('MRP_MO_ADDON_PDF', 'chaine', 'alpha', 'Name of PDF model of MO', 0),
+			2=>array('MRP_MO_ADDON', 'chaine', 'mod_mo_standard', 'Name of numbering rules of MO', 0),
+			3=>array('MRP_MO_ADDON_PDF_ODT_PATH', 'chaine', 'DOL_DATA_ROOT/doctemplates/mrps', '', 0)
+		);
 
-        // Some keys to add into the overwriting translation tables
-        /*$this->overwrite_translation = array(
+		// Some keys to add into the overwriting translation tables
+		/*$this->overwrite_translation = array(
             'en_US:ParentCompany'=>'Parent company or reseller',
             '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
-        $this->tabs = array();
-        // Example:
-        // $this->tabs[] = array('data'=>'objecttype:+tabname1:Title1:mylangfile@mrp:$user->rights->mrp->read:/mrp/mynewtab1.php?id=__ID__');  					// To add a new tab identified by code tabname1
-        // $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@mrp:$user->rights->othermodule->read:/mrp/mynewtab2.php?id=__ID__',  	// To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key.
-        // $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove');                                                     										// To remove an existing tab identified by code tabname
-        //
-        // Where objecttype can be
-        // 'categories_x'	  to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member)
-        // 'contact'          to add a tab in contact view
-        // 'contract'         to add a tab in contract view
-        // 'group'            to add a tab in group view
-        // 'intervention'     to add a tab in intervention view
-        // 'invoice'          to add a tab in customer invoice view
-        // 'invoice_supplier' to add a tab in supplier invoice view
-        // 'member'           to add a tab in fundation member view
-        // 'opensurveypoll'	  to add a tab in opensurvey poll view
-        // 'order'            to add a tab in customer order view
-        // 'order_supplier'   to add a tab in supplier order view
-        // 'payment'		  to add a tab in payment view
-        // 'payment_supplier' to add a tab in supplier payment view
-        // 'product'          to add a tab in product view
-        // 'propal'           to add a tab in propal view
-        // 'project'          to add a tab in project view
-        // 'stock'            to add a tab in stock view
-        // 'thirdparty'       to add a tab in third party view
-        // 'user'             to add a tab in user view
+		// Array to add new pages in new tabs
+		$this->tabs = array();
+		// Example:
+		// $this->tabs[] = array('data'=>'objecttype:+tabname1:Title1:mylangfile@mrp:$user->rights->mrp->read:/mrp/mynewtab1.php?id=__ID__');  					// To add a new tab identified by code tabname1
+		// $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@mrp:$user->rights->othermodule->read:/mrp/mynewtab2.php?id=__ID__',  	// To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key.
+		// $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove');                                                     										// To remove an existing tab identified by code tabname
+		//
+		// Where objecttype can be
+		// 'categories_x'	  to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member)
+		// 'contact'          to add a tab in contact view
+		// 'contract'         to add a tab in contract view
+		// 'group'            to add a tab in group view
+		// 'intervention'     to add a tab in intervention view
+		// 'invoice'          to add a tab in customer invoice view
+		// 'invoice_supplier' to add a tab in supplier invoice view
+		// 'member'           to add a tab in fundation member view
+		// 'opensurveypoll'	  to add a tab in opensurvey poll view
+		// 'order'            to add a tab in customer order view
+		// 'order_supplier'   to add a tab in supplier order view
+		// 'payment'		  to add a tab in payment view
+		// 'payment_supplier' to add a tab in supplier payment view
+		// 'product'          to add a tab in product view
+		// 'propal'           to add a tab in propal view
+		// 'project'          to add a tab in project view
+		// 'stock'            to add a tab in stock view
+		// 'thirdparty'       to add a tab in third party view
+		// 'user'             to add a tab in user view
 
-        // Dictionaries
-        $this->dictionaries = array();
-        /* Example:
+		// Dictionaries
+		$this->dictionaries = array();
+		/* Example:
         $this->dictionaries=array(
             'langs'=>'mylangfile@mrp',
             // List of tables we want to see into dictonnary editor
@@ -205,68 +205,68 @@ class modMrp extends DolibarrModules
         );
         */
 
-        // Boxes/Widgets
-        // Add here list of php file(s) stored in mrp/core/boxes that contains a class to show a widget.
-        $this->boxes = array(
-            0 => array('file' => 'box_mos.php', 'note' => '', 'enabledbydefaulton' => 'Home')
-        );
+		// Boxes/Widgets
+		// Add here list of php file(s) stored in mrp/core/boxes that contains a class to show a widget.
+		$this->boxes = array(
+			0 => array('file' => 'box_mos.php', 'note' => '', 'enabledbydefaulton' => 'Home')
+		);
 
-        // Cronjobs (List of cron jobs entries to add when module is enabled)
-        // unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week
-        $this->cronjobs = array(
-            //  0 => array(
-            //      'label' => 'MyJob label',
-            //      'jobtype' => 'method',
-            //      'class' => '/mrp/class/mo.class.php',
-            //      'objectname' => 'Mo',
-            //      'method' => 'doScheduledJob',
-            //      'parameters' => '',
-            //      'comment' => 'Comment',
-            //      'frequency' => 2,
-            //      'unitfrequency' => 3600,
-            //      'status' => 0,
-            //      'test' => '$conf->mrp->enabled',
-            //      'priority' => 50,
-            //  ),
-        );
-        // Example: $this->cronjobs=array(
-        //    0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'$conf->mrp->enabled', 'priority'=>50),
-        //    1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'$conf->mrp->enabled', 'priority'=>50)
-        // );
+		// Cronjobs (List of cron jobs entries to add when module is enabled)
+		// unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week
+		$this->cronjobs = array(
+			//  0 => array(
+			//      'label' => 'MyJob label',
+			//      'jobtype' => 'method',
+			//      'class' => '/mrp/class/mo.class.php',
+			//      'objectname' => 'Mo',
+			//      'method' => 'doScheduledJob',
+			//      'parameters' => '',
+			//      'comment' => 'Comment',
+			//      'frequency' => 2,
+			//      'unitfrequency' => 3600,
+			//      'status' => 0,
+			//      'test' => '$conf->mrp->enabled',
+			//      'priority' => 50,
+			//  ),
+		);
+		// Example: $this->cronjobs=array(
+		//    0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'$conf->mrp->enabled', 'priority'=>50),
+		//    1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'$conf->mrp->enabled', 'priority'=>50)
+		// );
 
-        // Permissions provided by this module
-        $this->rights = array();
-        $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)
-        $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)
-        $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)
-        $r++;
-        /* END MODULEBUILDER PERMISSIONS */
+		// Permissions provided by this module
+		$this->rights = array();
+		$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)
+		$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)
+		$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)
+		$r++;
+		/* END MODULEBUILDER PERMISSIONS */
 
-        // Main menu entries to add
-        $this->menu = array();
-        $r = 0;
-        // Add here entries to declare new menus
-        /* BEGIN MODULEBUILDER TOPMENU */
+		// Main menu entries to add
+		$this->menu = array();
+		$r = 0;
+		// Add here entries to declare new menus
+		/* BEGIN MODULEBUILDER TOPMENU */
 		/* END MODULEBUILDER LEFTMENU MO */
 
-        // Exports profiles provided by this module
-        $r = 1;
-        /* BEGIN MODULEBUILDER EXPORT MO */
-        /*
+		// Exports profiles provided by this module
+		$r = 1;
+		/* BEGIN MODULEBUILDER EXPORT MO */
+		/*
         $langs->load("mrp");
         $this->export_code[$r]=$this->rights_class.'_'.$r;
         $this->export_label[$r]='MoLines';	// Translation key (used only if key ExportDataset_xxx_z not found)
@@ -281,12 +281,12 @@ class modMrp extends DolibarrModules
         $this->export_sql_end[$r] .=' WHERE 1 = 1';
         $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('mo').')';
         $r++; */
-        /* END MODULEBUILDER EXPORT MO */
+		/* END MODULEBUILDER EXPORT MO */
 
-        // Imports profiles provided by this module
-        $r = 1;
-        /* BEGIN MODULEBUILDER IMPORT MO */
-        /*
+		// Imports profiles provided by this module
+		$r = 1;
+		/* BEGIN MODULEBUILDER IMPORT MO */
+		/*
          $langs->load("mrp");
          $this->export_code[$r]=$this->rights_class.'_'.$r;
          $this->export_label[$r]='MoLines';	// Translation key (used only if key ExportDataset_xxx_z not found)
@@ -301,75 +301,75 @@ class modMrp extends DolibarrModules
          $this->export_sql_end[$r] .=' WHERE 1 = 1';
          $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('mo').')';
          $r++; */
-        /* END MODULEBUILDER IMPORT MO */
-    }
+		/* END MODULEBUILDER IMPORT MO */
+	}
 
-    /**
-     *  Function called when module is enabled.
-     *  The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
-     *  It also creates data directories
-     *
-     *  @param      string  $options    Options when enabling module ('', 'noboxes')
-     *  @return     int             	1 if OK, 0 if KO
-     */
-    public function init($options = '')
-    {
-    	global $conf, $langs;
+	/**
+	 *  Function called when module is enabled.
+	 *  The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
+	 *  It also creates data directories
+	 *
+	 *  @param      string  $options    Options when enabling module ('', 'noboxes')
+	 *  @return     int             	1 if OK, 0 if KO
+	 */
+	public function init($options = '')
+	{
+		global $conf, $langs;
 
-        $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')
+		$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
-        //include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
-        //$extrafields = new ExtraFields($this->db);
-        //$result1=$extrafields->addExtraField('myattr1', "New Attr 1 label", 'boolean', 1,  3, 'thirdparty',   0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
-        //$result2=$extrafields->addExtraField('myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project',      0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
-        //$result3=$extrafields->addExtraField('myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
-        //$result4=$extrafields->addExtraField('myattr4', "New Attr 4 label", 'select',  1,  3, 'thirdparty',   0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1,'', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
-        //$result5=$extrafields->addExtraField('myattr5', "New Attr 5 label", 'text',    1, 10, 'user',         0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
+		// Create extrafields during init
+		//include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
+		//$extrafields = new ExtraFields($this->db);
+		//$result1=$extrafields->addExtraField('myattr1', "New Attr 1 label", 'boolean', 1,  3, 'thirdparty',   0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
+		//$result2=$extrafields->addExtraField('myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project',      0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
+		//$result3=$extrafields->addExtraField('myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
+		//$result4=$extrafields->addExtraField('myattr4', "New Attr 4 label", 'select',  1,  3, 'thirdparty',   0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1,'', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
+		//$result5=$extrafields->addExtraField('myattr5', "New Attr 5 label", 'text',    1, 10, 'user',         0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled');
 
-        // Permissions
-        $this->remove($options);
+		// Permissions
+		$this->remove($options);
 
-        $sql = array();
+		$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';
+		// ODT template
+		$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))
-        {
-        	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-        	dol_mkdir($dirodt);
-        	$result = dol_copy($src, $dest, 0, 0);
-        	if ($result < 0)
-        	{
-        		$langs->load("errors");
-        		$this->error = $langs->trans('ErrorFailToCopyFile', $src, $dest);
-        		return 0;
-        	}
-        }
+		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);
+			if ($result < 0)
+			{
+				$langs->load("errors");
+				$this->error = $langs->trans('ErrorFailToCopyFile', $src, $dest);
+				return 0;
+			}
+		}
 
-        $sql = array(
-        	//"DELETE FROM ".MAIN_DB_PREFIX."document_model WHERE nom = '".$this->db->escape('standard')."' AND type = 'mo' AND entity = ".$conf->entity,
-        	//"INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES('".$this->db->escape('standard')."', 'mo', ".$conf->entity.")"
-        );
+		$sql = array(
+			//"DELETE FROM ".MAIN_DB_PREFIX."document_model WHERE nom = '".$this->db->escape('standard')."' AND type = 'mo' AND entity = ".$conf->entity,
+			//"INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES('".$this->db->escape('standard')."', 'mo', ".$conf->entity.")"
+		);
 
-        return $this->_init($sql, $options);
-    }
+		return $this->_init($sql, $options);
+	}
 
-    /**
-     *  Function called when module is disabled.
-     *  Remove from database constants, boxes and permissions from Dolibarr database.
-     *  Data directories are not deleted
-     *
-     *  @param      string	$options    Options when enabling module ('', 'noboxes')
-     *  @return     int                 1 if OK, 0 if KO
-     */
-    public function remove($options = '')
-    {
-        $sql = array();
-        return $this->_remove($sql, $options);
-    }
+	/**
+	 *  Function called when module is disabled.
+	 *  Remove from database constants, boxes and permissions from Dolibarr database.
+	 *  Data directories are not deleted
+	 *
+	 *  @param      string	$options    Options when enabling module ('', 'noboxes')
+	 *  @return     int                 1 if OK, 0 if KO
+	 */
+	public function remove($options = '')
+	{
+		$sql = array();
+		return $this->_remove($sql, $options);
+	}
 }

+ 17 - 17
htdocs/core/modules/modPropale.class.php

@@ -262,11 +262,11 @@ class modPropale extends DolibarrModules
 
 		$r++;
 		$this->import_code[$r] = $this->rights_class.'_'.$r;
-		$this->import_label[$r] = 'Proposals';	// Translation key
+		$this->import_label[$r] = 'Proposals'; // Translation key
 		$this->import_icon[$r] = $this->picto;
-		$this->import_entities_array[$r] = [];		// We define here only fields that use another icon that the one defined into import_icon
-		$this->import_tables_array[$r] = ['c' => MAIN_DB_PREFIX . 'propal', 'extra' => MAIN_DB_PREFIX . 'propal_extrafields'];
-		$this->import_tables_creator_array[$r] = ['c'=>'fk_user_author'];	// Fields to store import user id
+		$this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon
+		$this->import_tables_array[$r] = ['c' => MAIN_DB_PREFIX.'propal', 'extra' => MAIN_DB_PREFIX.'propal_extrafields'];
+		$this->import_tables_creator_array[$r] = ['c'=>'fk_user_author']; // Fields to store import user id
 		$this->import_fields_array[$r] = [
 			'c.ref' => 'Document Ref*',
 			'c.ref_client' => 'RefCustomer',
@@ -282,7 +282,7 @@ class modPropale extends DolibarrModules
 			'c.date_livraison' => 'DeliveryDate',
 			'c.fk_user_valid' => 'ValidatedById'
 		];
-		if (! empty($conf->multicurrency->enabled)) {
+		if (!empty($conf->multicurrency->enabled)) {
 			$this->import_fields_array[$r]['c.multicurrency_code'] = 'Currency';
 			$this->import_fields_array[$r]['c.multicurrency_tx'] = 'CurrencyRate';
 			$this->import_fields_array[$r]['c.multicurrency_total_ht'] = 'MulticurrencyAmountHT';
@@ -291,18 +291,18 @@ class modPropale extends DolibarrModules
 		}
 		// Add extra fields
 		$import_extrafield_sample = [];
-		$sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'propal' AND entity IN (0, " . $conf->entity . ")";
+		$sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'propal' AND entity IN (0, ".$conf->entity.")";
 		$resql = $this->db->query($sql);
 		if ($resql) {
 			while ($obj = $this->db->fetch_object($resql)) {
-				$fieldname = 'extra.' . $obj->name;
+				$fieldname = 'extra.'.$obj->name;
 				$fieldlabel = ucfirst($obj->label);
-				$this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : '');
+				$this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : '');
 				$import_extrafield_sample[$fieldname] = $fieldlabel;
 			}
 		}
 		// End add extra fields
-		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'propal'];
+		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'propal'];
 		$this->import_regex_array[$r] = ['c.ref' => '[^ ]'];
 		$import_sample = [
 			'c.ref' => 'PROV0077',
@@ -339,12 +339,12 @@ class modPropale extends DolibarrModules
 		//Import Proposal Lines
 		$r++;
 		$this->import_code[$r] = $this->rights_class.'line_'.$r;
-		$this->import_label[$r] = "ProposalLine";	// Translation key
+		$this->import_label[$r] = "ProposalLine"; // Translation key
 		$this->import_icon[$r] = $this->picto;
-		$this->import_entities_array[$r] = [];		// We define here only fields that use another icon that the one defined into import_icon
+		$this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon
 		$this->import_tables_array[$r] = [
-			'cd' => MAIN_DB_PREFIX . 'propaldet',
-			'extra' => MAIN_DB_PREFIX . 'propaldet_extrafields'
+			'cd' => MAIN_DB_PREFIX.'propaldet',
+			'extra' => MAIN_DB_PREFIX.'propaldet_extrafields'
 		];
 		$this->import_fields_array[$r] = [
 			'cd.fk_propal' => 'Document Ref*',
@@ -366,7 +366,7 @@ class modPropale extends DolibarrModules
 			'cd.date_end' => 'End Date',
 			'cd.buy_price_ht' => 'LineBuyPriceHT'
 		];
-		if (! empty($conf->multicurrency->enabled)) {
+		if (!empty($conf->multicurrency->enabled)) {
 			$this->import_fields_array[$r]['cd.multicurrency_code'] = 'Currency';
 			$this->import_fields_array[$r]['cd.multicurrency_subprice'] = 'CurrencyRate';
 			$this->import_fields_array[$r]['cd.multicurrency_total_ht'] = 'MulticurrencyAmountHT';
@@ -379,14 +379,14 @@ class modPropale extends DolibarrModules
 		$resql = $this->db->query($sql);
 		if ($resql) {
 			while ($obj = $this->db->fetch_object($resql)) {
-				$fieldname = 'extra.' . $obj->name;
+				$fieldname = 'extra.'.$obj->name;
 				$fieldlabel = ucfirst($obj->label);
-				$this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : '');
+				$this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : '');
 				$import_extrafield_sample[$fieldname] = $fieldlabel;
 			}
 		}
 		// End add extra fields
-		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'propaldet'];
+		$this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'propaldet'];
 		$this->import_regex_array[$r] = ['cd.product_type' => '[0|1]$'];
 		$import_sample = [
 			'cd.fk_propal' => 'PROV(0001)',

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

@@ -30,54 +30,54 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
 class modWebServicesClient extends DolibarrModules
 {
 
-    /**
+	/**
 	 *   Constructor. Define names, constants, directories, boxes, permissions
 	 *
 	 *   @param      DoliDB		$db      Database handler
-     */
-    public function __construct($db)
-    {
-        $this->db = $db;
-        $this->numero = 2660;
+	 */
+	public function __construct($db)
+	{
+		$this->db = $db;
+		$this->numero = 2660;
 
-        $this->family = "interface";
-        $this->module_position = '25';
-        // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
-        $this->name = preg_replace('/^mod/i', '', get_class($this));
-        $this->description = "Enable the web service client to call external supplier web services";
+		$this->family = "interface";
+		$this->module_position = '25';
+		// Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
+		$this->name = preg_replace('/^mod/i', '', get_class($this));
+		$this->description = "Enable the web service client to call external supplier web services";
 		// Possible values for version are: 'development', 'experimental', 'dolibarr' or version
-        $this->version = 'experimental';
-        // Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase)
-        $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
-        // Name of image file used for this module.
-        $this->picto = 'technic';
+		$this->version = 'experimental';
+		// Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase)
+		$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
+		// Name of image file used for this module.
+		$this->picto = 'technic';
 
-        // Data directories to create when module is enabled
-        $this->dirs = array();
+		// Data directories to create when module is enabled
+		$this->dirs = array();
 
-        // Config pages
-        //$this->config_page_url = array();
+		// Config pages
+		//$this->config_page_url = array();
 
-        // Dependencies
-        $this->hidden = false; // A condition to hide module
+		// Dependencies
+		$this->hidden = false; // A condition to hide module
 		$this->depends = array(); // List of module class names as string that must be enabled if this module is enabled
 		$this->requiredby = array(); // List of module ids to disable if this one is disabled
 		$this->conflictwith = array(); // List of module class names as string this module is in conflict with
 		$this->phpmin = array(5, 4); // Minimum version of PHP required by module
-        $this->langfiles = array("other");
+		$this->langfiles = array("other");
 
-        // Constants
-        $this->const = array();
+		// Constants
+		$this->const = array();
 
-        // New pages on tabs
-        $this->tabs = array();
+		// New pages on tabs
+		$this->tabs = array();
 
-        // Boxes
-        $this->boxes = array();
+		// Boxes
+		$this->boxes = array();
 
-        // Permissions
-        $this->rights = array();
-        $this->rights_class = 'syncsupplierwebservices';
-        $r = 0;
-    }
+		// Permissions
+		$this->rights = array();
+		$this->rights_class = 'syncsupplierwebservices';
+		$r = 0;
+	}
 }

+ 468 - 468
htdocs/core/modules/printing/printgcp.modules.php

@@ -35,478 +35,478 @@ use OAuth\OAuth2\Service\Google;
  */
 class printing_printgcp extends PrintingDriver
 {
-    public $name = 'printgcp';
-    public $desc = 'PrintGCPDesc';
-
-    /**
-     * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
-     */
-    public $picto = 'printer';
-    public $active = 'PRINTING_PRINTGCP';
-    public $conf = array();
-    public $google_id = '';
-    public $google_secret = '';
-
-    /**
-     * @var string Error code (or message)
-     */
-    public $error = '';
-
-    /**
-     * @var string[] Error codes (or messages)
-     */
-    public $errors = array();
-
-    /**
-     * @var DoliDB Database handler.
-     */
-    public $db;
-
-    private $OAUTH_SERVICENAME_GOOGLE = 'Google';
-
-    const LOGIN_URL = 'https://accounts.google.com/o/oauth2/token';
-    const PRINTERS_SEARCH_URL = 'https://www.google.com/cloudprint/search';
-    const PRINTERS_GET_JOBS = 'https://www.google.com/cloudprint/jobs';
-    const PRINT_URL = 'https://www.google.com/cloudprint/submit';
-
-    /**
-     *  Constructor
-     *
-     *  @param      DoliDB      $db      Database handler
-     */
-    public function __construct($db)
-    {
-        global $conf, $langs, $dolibarr_main_url_root;
-
-        // Define $urlwithroot
-        $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
-        $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
-        //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
-
-        $this->db = $db;
-
-        if (!$conf->oauth->enabled) {
-            $this->conf[] = array(
-                'varname'=>'PRINTGCP_INFO',
-                'info'=>$langs->transnoentitiesnoconv("WarningModuleNotActive", "OAuth"),
-                'type'=>'info',
-            );
-        } else {
-            $this->google_id = $conf->global->OAUTH_GOOGLE_ID;
-            $this->google_secret = $conf->global->OAUTH_GOOGLE_SECRET;
-            // Token storage
-            $storage = new DoliStorage($this->db, $this->conf);
-            //$storage->clearToken($this->OAUTH_SERVICENAME_GOOGLE);
-            // Setup the credentials for the requests
-            $credentials = new Credentials(
-                $this->google_id,
-                $this->google_secret,
-                $urlwithroot.'/core/modules/oauth/google_oauthcallback.php'
-            );
-            $access = ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? 'HasAccessToken' : 'NoAccessToken');
-            $serviceFactory = new \OAuth\ServiceFactory();
-            $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
-            $token_ok = true;
-            try {
-                $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
-            } catch (Exception $e) {
-                $this->errors[] = $e->getMessage();
-                $token_ok = false;
-            }
-            //var_dump($this->errors);exit;
-
-            $expire = false;
-            // Is token expired or will token expire in the next 30 seconds
-            if ($token_ok) {
-                $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
-            }
-
-            // Token expired so we refresh it
-            if ($token_ok && $expire) {
-                try {
-                    // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
-                    $refreshtoken = $token->getRefreshToken();
-                    $token = $apiService->refreshAccessToken($token);
-                    $token->setRefreshToken($refreshtoken);
-                    $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
-                } catch (Exception $e) {
-                    $this->errors[] = $e->getMessage();
-                }
-            }
-            if ($this->google_id != '' && $this->google_secret != '') {
-                $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthConfigured', 'type'=>'info');
-                $this->conf[] = array(
-                    'varname'=>'PRINTGCP_TOKEN_ACCESS',
-                    'info'=>$access,
-                    'type'=>'info',
-                    'renew'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'),
-                    'delete'=>($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp') : '')
-                );
-                if ($token_ok) {
-                    $expiredat = '';
-
-                    $refreshtoken = $token->getRefreshToken();
-
-                    $endoflife = $token->getEndOfLife();
-
-                    if ($endoflife == $token::EOL_NEVER_EXPIRES)
-                    {
-                        $expiredat = $langs->trans("Never");
-                    } elseif ($endoflife == $token::EOL_UNKNOWN)
-                    {
-                        $expiredat = $langs->trans("Unknown");
-                    } else {
-                        $expiredat = dol_print_date($endoflife, "dayhour");
-                    }
-
-                    $this->conf[] = array('varname'=>'TOKEN_REFRESH', 'info'=>((!empty($refreshtoken)) ? 'Yes' : 'No'), 'type'=>'info');
-                    $this->conf[] = array('varname'=>'TOKEN_EXPIRED', 'info'=>($expire ? 'Yes' : 'No'), 'type'=>'info');
-                    $this->conf[] = array('varname'=>'TOKEN_EXPIRE_AT', 'info'=>($expiredat), 'type'=>'info');
-                }
-                /*
+	public $name = 'printgcp';
+	public $desc = 'PrintGCPDesc';
+
+	/**
+	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
+	 */
+	public $picto = 'printer';
+	public $active = 'PRINTING_PRINTGCP';
+	public $conf = array();
+	public $google_id = '';
+	public $google_secret = '';
+
+	/**
+	 * @var string Error code (or message)
+	 */
+	public $error = '';
+
+	/**
+	 * @var string[] Error codes (or messages)
+	 */
+	public $errors = array();
+
+	/**
+	 * @var DoliDB Database handler.
+	 */
+	public $db;
+
+	private $OAUTH_SERVICENAME_GOOGLE = 'Google';
+
+	const LOGIN_URL = 'https://accounts.google.com/o/oauth2/token';
+	const PRINTERS_SEARCH_URL = 'https://www.google.com/cloudprint/search';
+	const PRINTERS_GET_JOBS = 'https://www.google.com/cloudprint/jobs';
+	const PRINT_URL = 'https://www.google.com/cloudprint/submit';
+
+	/**
+	 *  Constructor
+	 *
+	 *  @param      DoliDB      $db      Database handler
+	 */
+	public function __construct($db)
+	{
+		global $conf, $langs, $dolibarr_main_url_root;
+
+		// Define $urlwithroot
+		$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
+		$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
+		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
+
+		$this->db = $db;
+
+		if (!$conf->oauth->enabled) {
+			$this->conf[] = array(
+				'varname'=>'PRINTGCP_INFO',
+				'info'=>$langs->transnoentitiesnoconv("WarningModuleNotActive", "OAuth"),
+				'type'=>'info',
+			);
+		} else {
+			$this->google_id = $conf->global->OAUTH_GOOGLE_ID;
+			$this->google_secret = $conf->global->OAUTH_GOOGLE_SECRET;
+			// Token storage
+			$storage = new DoliStorage($this->db, $this->conf);
+			//$storage->clearToken($this->OAUTH_SERVICENAME_GOOGLE);
+			// Setup the credentials for the requests
+			$credentials = new Credentials(
+				$this->google_id,
+				$this->google_secret,
+				$urlwithroot.'/core/modules/oauth/google_oauthcallback.php'
+			);
+			$access = ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? 'HasAccessToken' : 'NoAccessToken');
+			$serviceFactory = new \OAuth\ServiceFactory();
+			$apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
+			$token_ok = true;
+			try {
+				$token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
+			} catch (Exception $e) {
+				$this->errors[] = $e->getMessage();
+				$token_ok = false;
+			}
+			//var_dump($this->errors);exit;
+
+			$expire = false;
+			// Is token expired or will token expire in the next 30 seconds
+			if ($token_ok) {
+				$expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
+			}
+
+			// Token expired so we refresh it
+			if ($token_ok && $expire) {
+				try {
+					// il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
+					$refreshtoken = $token->getRefreshToken();
+					$token = $apiService->refreshAccessToken($token);
+					$token->setRefreshToken($refreshtoken);
+					$storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
+				} catch (Exception $e) {
+					$this->errors[] = $e->getMessage();
+				}
+			}
+			if ($this->google_id != '' && $this->google_secret != '') {
+				$this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthConfigured', 'type'=>'info');
+				$this->conf[] = array(
+					'varname'=>'PRINTGCP_TOKEN_ACCESS',
+					'info'=>$access,
+					'type'=>'info',
+					'renew'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'),
+					'delete'=>($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp') : '')
+				);
+				if ($token_ok) {
+					$expiredat = '';
+
+					$refreshtoken = $token->getRefreshToken();
+
+					$endoflife = $token->getEndOfLife();
+
+					if ($endoflife == $token::EOL_NEVER_EXPIRES)
+					{
+						$expiredat = $langs->trans("Never");
+					} elseif ($endoflife == $token::EOL_UNKNOWN)
+					{
+						$expiredat = $langs->trans("Unknown");
+					} else {
+						$expiredat = dol_print_date($endoflife, "dayhour");
+					}
+
+					$this->conf[] = array('varname'=>'TOKEN_REFRESH', 'info'=>((!empty($refreshtoken)) ? 'Yes' : 'No'), 'type'=>'info');
+					$this->conf[] = array('varname'=>'TOKEN_EXPIRED', 'info'=>($expire ? 'Yes' : 'No'), 'type'=>'info');
+					$this->conf[] = array('varname'=>'TOKEN_EXPIRE_AT', 'info'=>($expiredat), 'type'=>'info');
+				}
+				/*
                 if ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE)) {
                     $this->conf[] = array('varname'=>'PRINTGCP_AUTHLINK', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'authlink');
                     $this->conf[] = array('varname'=>'DELETE_TOKEN', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'delete');
                 } else {
                     $this->conf[] = array('varname'=>'PRINTGCP_AUTHLINK', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'authlink');
                 }*/
-            } else {
-                $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthNotConfigured', 'type'=>'info');
-            }
-        }
-        // do not display submit button
-        $this->conf[] = array('enabled'=>0, 'type'=>'submit');
-    }
-
-    /**
-     *  Return list of available printers
-     *
-     *  @return  int                     0 if OK, >0 if KO
-     */
-    public function listAvailablePrinters()
-    {
-        global $conf, $langs;
-        $error = 0;
-        $langs->load('printing');
-
-        $html = '<tr class="liste_titre">';
-        $html .= '<td>'.$langs->trans('GCP_Name').'</td>';
-        $html .= '<td>'.$langs->trans('GCP_displayName').'</td>';
-        $html .= '<td>'.$langs->trans('GCP_Id').'</td>';
-        $html .= '<td>'.$langs->trans('GCP_OwnerName').'</td>';
-        $html .= '<td>'.$langs->trans('GCP_State').'</td>';
-        $html .= '<td>'.$langs->trans('GCP_connectionStatus').'</td>';
-        $html .= '<td>'.$langs->trans('GCP_Type').'</td>';
-        $html .= '<td class="center">'.$langs->trans("Select").'</td>';
-        $html .= '</tr>'."\n";
-        $list = $this->getlistAvailablePrinters();
-        //$html.= '<td><pre>'.print_r($list,true).'</pre></td>';
-        foreach ($list['available'] as $printer_det)
-        {
-            $html .= '<tr class="oddeven">';
-            $html .= '<td>'.$printer_det['name'].'</td>';
-            $html .= '<td>'.$printer_det['displayName'].'</td>';
-            $html .= '<td>'.$printer_det['id'].'</td>'; // id to identify printer to use
-            $html .= '<td>'.$printer_det['ownerName'].'</td>';
-            $html .= '<td>'.$printer_det['status'].'</td>';
-            $html .= '<td>'.$langs->trans('STATE_'.$printer_det['connectionStatus']).'</td>';
-            $html .= '<td>'.$langs->trans('TYPE_'.$printer_det['type']).'</td>';
-            // Defaut
-            $html .= '<td class="center">';
-            if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id'])
-            {
-                $html .= img_picto($langs->trans("Default"), 'on');
-            } else $html .= '<a href="'.$_SERVER["PHP_SELF"].'?action=setvalue&amp;token='.newToken().'&amp;mode=test&amp;varname=PRINTING_GCP_DEFAULT&amp;driver=printgcp&amp;value='.urlencode($printer_det['id']).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
-            $html .= '</td>';
-            $html .= '</tr>'."\n";
-        }
-        $this->resprint = $html;
-        return $error;
-    }
-
-
-    /**
-     *  Return list of available printers
-     *
-     *  @return array      list of printers
-     */
-    public function getlistAvailablePrinters()
-    {
-        $ret = array();
-        // Token storage
-        $storage = new DoliStorage($this->db, $this->conf);
-        // Setup the credentials for the requests
-        $credentials = new Credentials(
-            $this->google_id,
-            $this->google_secret,
-            DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php'
-        );
-        $serviceFactory = new \OAuth\ServiceFactory();
-        $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
-        // Check if we have auth token
-        $token_ok = true;
-        try {
-            $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
-        } catch (Exception $e) {
-            $this->errors[] = $e->getMessage();
-            $token_ok = false;
-        }
-        $expire = false;
-        // Is token expired or will token expire in the next 30 seconds
-        if ($token_ok) {
-            $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
-        }
-
-        // Token expired so we refresh it
-        if ($token_ok && $expire) {
-            try {
-                // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
-                $refreshtoken = $token->getRefreshToken();
-                $token = $apiService->refreshAccessToken($token);
-                $token->setRefreshToken($refreshtoken);
-                $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
-            } catch (Exception $e) {
-                $this->errors[] = $e->getMessage();
-            }
-        }
-        // Send a request with api
-        try {
-            $response = $apiService->request(self::PRINTERS_SEARCH_URL);
-        } catch (Exception $e) {
-            $this->errors[] = $e->getMessage();
-            print '<pre>'.print_r($e->getMessage(), true).'</pre>';
-        }
-        //print '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
-        $responsedata = json_decode($response, true);
-        $printers = $responsedata['printers'];
-        // Check if we have printers?
-        if (count($printers) == 0) {
-            // We dont have printers so return blank array
-            $ret['available'] = array();
-        } else {
-            // We have printers so returns printers as array
-            $ret['available'] = $printers;
-        }
-        return $ret;
-    }
-
-    /**
-     *  Print selected file
-     *
-     * @param   string      $file       file
-     * @param   string      $module     module
-     * @param   string      $subdir     subdir for file
-     * @return  int                     0 if OK, >0 if KO
-     */
-    public function printFile($file, $module, $subdir = '')
-    {
-        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-
-        global $conf, $user;
-        $error = 0;
-
-        $fileprint = $conf->{$module}->dir_output;
-        if ($subdir != '') {
-            $fileprint .= '/'.$subdir;
-        }
-        $fileprint .= '/'.$file;
-        $mimetype = dol_mimetype($fileprint);
-        // select printer uri for module order, propal,...
-        $sql = "SELECT rowid, printer_id, copy FROM ".MAIN_DB_PREFIX."printing WHERE module='".$this->db->escape($module)."' AND driver='printgcp' AND userid=".$user->id;
-        $result = $this->db->query($sql);
-        if ($result)
-        {
-            $obj = $this->db->fetch_object($result);
-            if ($obj)
-            {
-                $printer_id = $obj->printer_id;
-            } else {
-                if (!empty($conf->global->PRINTING_GCP_DEFAULT))
-                {
-                    $printer_id = $conf->global->PRINTING_GCP_DEFAULT;
-                } else {
-                    $this->errors[] = 'NoDefaultPrinterDefined';
-                    $error++;
-                    return $error;
-                }
-            }
-        } else {
-            dol_print_error($this->db);
-        }
-
-        $ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype);
-        $this->error = 'PRINTGCP: '.$ret['errormessage'];
-        if ($ret['status'] != 1) {
-            $error++;
-        }
-        return $error;
-    }
-
-    /**
-     *  Sends document to the printer
-     *
-     *  @param  string      $printerid      Printer id returned by Google Cloud Print
-     *  @param  string      $printjobtitle  Job Title
-     *  @param  string      $filepath       File Path to be send to Google Cloud Print
-     *  @param  string      $contenttype    File content type by example application/pdf, image/png
-     *  @return array                       status array
-     */
-    public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype)
-    {
-        // Check if printer id
-        if (empty($printerid)) {
-            return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'No provided printer ID');
-        }
-        // Open the file which needs to be print
-        $handle = fopen($filepath, "rb");
-        if (!$handle) {
-            return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'Could not read the file.');
-        }
-        // Read file content
-        $contents = fread($handle, filesize($filepath));
-        fclose($handle);
-        // Prepare post fields for sending print
-        $post_fields = array(
-            'printerid' => $printerid,
-            'title' => $printjobtitle,
-            'contentTransferEncoding' => 'base64',
-            'content' => base64_encode($contents), // encode file content as base64
-            'contentType' => $contenttype,
-        );
-        // Dolibarr Token storage
-        $storage = new DoliStorage($this->db, $this->conf);
-        // Setup the credentials for the requests
-        $credentials = new Credentials(
-            $this->google_id,
-            $this->google_secret,
-            DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google'
-        );
-        $serviceFactory = new \OAuth\ServiceFactory();
-        $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
-
-        // Check if we have auth token and refresh it
-        $token_ok = true;
-        try {
-            $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
-        } catch (Exception $e) {
-            $this->errors[] = $e->getMessage();
-            $token_ok = false;
-        }
-        if ($token_ok) {
-            try {
-                // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
-                $refreshtoken = $token->getRefreshToken();
-                $token = $apiService->refreshAccessToken($token);
-                $token->setRefreshToken($refreshtoken);
-                $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
-            } catch (Exception $e) {
-                $this->errors[] = $e->getMessage();
-            }
-        }
-
-        // Send a request with api
-        $response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true);
-        //print '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
-        return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']);
-    }
-
-
-    /**
-     *  List jobs print
-     *
-     *  @return  int                     0 if OK, >0 if KO
-     */
-    public function listJobs()
-    {
-        global $conf, $langs;
-
-        $error = 0;
-        $html = '';
-        // Token storage
-        $storage = new DoliStorage($this->db, $this->conf);
-        // Setup the credentials for the requests
-        $credentials = new Credentials(
-            $this->google_id,
-            $this->google_secret,
-            DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php'
-        );
-        $serviceFactory = new \OAuth\ServiceFactory();
-        $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
-        // Check if we have auth token
-        $token_ok = true;
-        try {
-            $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
-        } catch (Exception $e) {
-            $this->errors[] = $e->getMessage();
-            $token_ok = false;
-            $error++;
-        }
-        $expire = false;
-        // Is token expired or will token expire in the next 30 seconds
-        if ($token_ok) {
-            $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
-        }
-
-        // Token expired so we refresh it
-        if ($token_ok && $expire) {
-            try {
-                // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
-                $refreshtoken = $token->getRefreshToken();
-                $token = $apiService->refreshAccessToken($token);
-                $token->setRefreshToken($refreshtoken);
-                $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
-            } catch (Exception $e) {
-                $this->errors[] = $e->getMessage();
-                $error++;
-            }
-        }
-        // Getting Jobs
-        // Send a request with api
-        try {
-            $response = $apiService->request(self::PRINTERS_GET_JOBS);
-        } catch (Exception $e) {
-            $this->errors[] = $e->getMessage();
-            $error++;
-        }
-        $responsedata = json_decode($response, true);
-        //$html .= '<pre>'.print_r($responsedata,true).'</pre>';
-        $html .= '<div class="div-table-responsive">';
-        $html .= '<table width="100%" class="noborder">';
-        $html .= '<tr class="liste_titre">';
-        $html .= '<td>'.$langs->trans("Id").'</td>';
-        $html .= '<td>'.$langs->trans("Date").'</td>';
-        $html .= '<td>'.$langs->trans("Owner").'</td>';
-        $html .= '<td>'.$langs->trans("Printer").'</td>';
-        $html .= '<td>'.$langs->trans("Filename").'</td>';
-        $html .= '<td>'.$langs->trans("Status").'</td>';
-        $html .= '<td>'.$langs->trans("Cancel").'</td>';
-        $html .= '</tr>'."\n";
-
-        $jobs = $responsedata['jobs'];
-        //$html .= '<pre>'.print_r($jobs['0'],true).'</pre>';
-        if (is_array($jobs)) {
-            foreach ($jobs as $value) {
-                $html .= '<tr class="oddeven">';
-                $html .= '<td>'.$value['id'].'</td>';
-                $dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour');
-                $html .= '<td>'.$dates.'</td>';
-                $html .= '<td>'.$value['ownerId'].'</td>';
-                $html .= '<td>'.$value['printerName'].'</td>';
-                $html .= '<td>'.$value['title'].'</td>';
-                $html .= '<td>'.$value['status'].'</td>';
-                $html .= '<td>&nbsp;</td>';
-                $html .= '</tr>';
-            }
-        } else {
-                $html .= '<tr class="oddeven">';
-                $html .= '<td colspan="7" class="opacitymedium">'.$langs->trans("None").'</td>';
-                $html .= '</tr>';
-        }
-        $html .= '</table>';
-        $html .= '</div>';
-
-        $this->resprint = $html;
-
-        return $error;
-    }
+			} else {
+				$this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthNotConfigured', 'type'=>'info');
+			}
+		}
+		// do not display submit button
+		$this->conf[] = array('enabled'=>0, 'type'=>'submit');
+	}
+
+	/**
+	 *  Return list of available printers
+	 *
+	 *  @return  int                     0 if OK, >0 if KO
+	 */
+	public function listAvailablePrinters()
+	{
+		global $conf, $langs;
+		$error = 0;
+		$langs->load('printing');
+
+		$html = '<tr class="liste_titre">';
+		$html .= '<td>'.$langs->trans('GCP_Name').'</td>';
+		$html .= '<td>'.$langs->trans('GCP_displayName').'</td>';
+		$html .= '<td>'.$langs->trans('GCP_Id').'</td>';
+		$html .= '<td>'.$langs->trans('GCP_OwnerName').'</td>';
+		$html .= '<td>'.$langs->trans('GCP_State').'</td>';
+		$html .= '<td>'.$langs->trans('GCP_connectionStatus').'</td>';
+		$html .= '<td>'.$langs->trans('GCP_Type').'</td>';
+		$html .= '<td class="center">'.$langs->trans("Select").'</td>';
+		$html .= '</tr>'."\n";
+		$list = $this->getlistAvailablePrinters();
+		//$html.= '<td><pre>'.print_r($list,true).'</pre></td>';
+		foreach ($list['available'] as $printer_det)
+		{
+			$html .= '<tr class="oddeven">';
+			$html .= '<td>'.$printer_det['name'].'</td>';
+			$html .= '<td>'.$printer_det['displayName'].'</td>';
+			$html .= '<td>'.$printer_det['id'].'</td>'; // id to identify printer to use
+			$html .= '<td>'.$printer_det['ownerName'].'</td>';
+			$html .= '<td>'.$printer_det['status'].'</td>';
+			$html .= '<td>'.$langs->trans('STATE_'.$printer_det['connectionStatus']).'</td>';
+			$html .= '<td>'.$langs->trans('TYPE_'.$printer_det['type']).'</td>';
+			// Defaut
+			$html .= '<td class="center">';
+			if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id'])
+			{
+				$html .= img_picto($langs->trans("Default"), 'on');
+			} else $html .= '<a href="'.$_SERVER["PHP_SELF"].'?action=setvalue&amp;token='.newToken().'&amp;mode=test&amp;varname=PRINTING_GCP_DEFAULT&amp;driver=printgcp&amp;value='.urlencode($printer_det['id']).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
+			$html .= '</td>';
+			$html .= '</tr>'."\n";
+		}
+		$this->resprint = $html;
+		return $error;
+	}
+
+
+	/**
+	 *  Return list of available printers
+	 *
+	 *  @return array      list of printers
+	 */
+	public function getlistAvailablePrinters()
+	{
+		$ret = array();
+		// Token storage
+		$storage = new DoliStorage($this->db, $this->conf);
+		// Setup the credentials for the requests
+		$credentials = new Credentials(
+			$this->google_id,
+			$this->google_secret,
+			DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php'
+		);
+		$serviceFactory = new \OAuth\ServiceFactory();
+		$apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
+		// Check if we have auth token
+		$token_ok = true;
+		try {
+			$token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
+		} catch (Exception $e) {
+			$this->errors[] = $e->getMessage();
+			$token_ok = false;
+		}
+		$expire = false;
+		// Is token expired or will token expire in the next 30 seconds
+		if ($token_ok) {
+			$expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
+		}
+
+		// Token expired so we refresh it
+		if ($token_ok && $expire) {
+			try {
+				// il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
+				$refreshtoken = $token->getRefreshToken();
+				$token = $apiService->refreshAccessToken($token);
+				$token->setRefreshToken($refreshtoken);
+				$storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
+			} catch (Exception $e) {
+				$this->errors[] = $e->getMessage();
+			}
+		}
+		// Send a request with api
+		try {
+			$response = $apiService->request(self::PRINTERS_SEARCH_URL);
+		} catch (Exception $e) {
+			$this->errors[] = $e->getMessage();
+			print '<pre>'.print_r($e->getMessage(), true).'</pre>';
+		}
+		//print '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
+		$responsedata = json_decode($response, true);
+		$printers = $responsedata['printers'];
+		// Check if we have printers?
+		if (count($printers) == 0) {
+			// We dont have printers so return blank array
+			$ret['available'] = array();
+		} else {
+			// We have printers so returns printers as array
+			$ret['available'] = $printers;
+		}
+		return $ret;
+	}
+
+	/**
+	 *  Print selected file
+	 *
+	 * @param   string      $file       file
+	 * @param   string      $module     module
+	 * @param   string      $subdir     subdir for file
+	 * @return  int                     0 if OK, >0 if KO
+	 */
+	public function printFile($file, $module, $subdir = '')
+	{
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+		global $conf, $user;
+		$error = 0;
+
+		$fileprint = $conf->{$module}->dir_output;
+		if ($subdir != '') {
+			$fileprint .= '/'.$subdir;
+		}
+		$fileprint .= '/'.$file;
+		$mimetype = dol_mimetype($fileprint);
+		// select printer uri for module order, propal,...
+		$sql = "SELECT rowid, printer_id, copy FROM ".MAIN_DB_PREFIX."printing WHERE module='".$this->db->escape($module)."' AND driver='printgcp' AND userid=".$user->id;
+		$result = $this->db->query($sql);
+		if ($result)
+		{
+			$obj = $this->db->fetch_object($result);
+			if ($obj)
+			{
+				$printer_id = $obj->printer_id;
+			} else {
+				if (!empty($conf->global->PRINTING_GCP_DEFAULT))
+				{
+					$printer_id = $conf->global->PRINTING_GCP_DEFAULT;
+				} else {
+					$this->errors[] = 'NoDefaultPrinterDefined';
+					$error++;
+					return $error;
+				}
+			}
+		} else {
+			dol_print_error($this->db);
+		}
+
+		$ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype);
+		$this->error = 'PRINTGCP: '.$ret['errormessage'];
+		if ($ret['status'] != 1) {
+			$error++;
+		}
+		return $error;
+	}
+
+	/**
+	 *  Sends document to the printer
+	 *
+	 *  @param  string      $printerid      Printer id returned by Google Cloud Print
+	 *  @param  string      $printjobtitle  Job Title
+	 *  @param  string      $filepath       File Path to be send to Google Cloud Print
+	 *  @param  string      $contenttype    File content type by example application/pdf, image/png
+	 *  @return array                       status array
+	 */
+	public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype)
+	{
+		// Check if printer id
+		if (empty($printerid)) {
+			return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'No provided printer ID');
+		}
+		// Open the file which needs to be print
+		$handle = fopen($filepath, "rb");
+		if (!$handle) {
+			return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'Could not read the file.');
+		}
+		// Read file content
+		$contents = fread($handle, filesize($filepath));
+		fclose($handle);
+		// Prepare post fields for sending print
+		$post_fields = array(
+			'printerid' => $printerid,
+			'title' => $printjobtitle,
+			'contentTransferEncoding' => 'base64',
+			'content' => base64_encode($contents), // encode file content as base64
+			'contentType' => $contenttype,
+		);
+		// Dolibarr Token storage
+		$storage = new DoliStorage($this->db, $this->conf);
+		// Setup the credentials for the requests
+		$credentials = new Credentials(
+			$this->google_id,
+			$this->google_secret,
+			DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google'
+		);
+		$serviceFactory = new \OAuth\ServiceFactory();
+		$apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
+
+		// Check if we have auth token and refresh it
+		$token_ok = true;
+		try {
+			$token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
+		} catch (Exception $e) {
+			$this->errors[] = $e->getMessage();
+			$token_ok = false;
+		}
+		if ($token_ok) {
+			try {
+				// il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
+				$refreshtoken = $token->getRefreshToken();
+				$token = $apiService->refreshAccessToken($token);
+				$token->setRefreshToken($refreshtoken);
+				$storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
+			} catch (Exception $e) {
+				$this->errors[] = $e->getMessage();
+			}
+		}
+
+		// Send a request with api
+		$response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true);
+		//print '<tr><td><pre>'.print_r($response, true).'</pre></td></tr>';
+		return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']);
+	}
+
+
+	/**
+	 *  List jobs print
+	 *
+	 *  @return  int                     0 if OK, >0 if KO
+	 */
+	public function listJobs()
+	{
+		global $conf, $langs;
+
+		$error = 0;
+		$html = '';
+		// Token storage
+		$storage = new DoliStorage($this->db, $this->conf);
+		// Setup the credentials for the requests
+		$credentials = new Credentials(
+			$this->google_id,
+			$this->google_secret,
+			DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php'
+		);
+		$serviceFactory = new \OAuth\ServiceFactory();
+		$apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array());
+		// Check if we have auth token
+		$token_ok = true;
+		try {
+			$token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE);
+		} catch (Exception $e) {
+			$this->errors[] = $e->getMessage();
+			$token_ok = false;
+			$error++;
+		}
+		$expire = false;
+		// Is token expired or will token expire in the next 30 seconds
+		if ($token_ok) {
+			$expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30));
+		}
+
+		// Token expired so we refresh it
+		if ($token_ok && $expire) {
+			try {
+				// il faut sauvegarder le refresh token car google ne le donne qu'une seule fois
+				$refreshtoken = $token->getRefreshToken();
+				$token = $apiService->refreshAccessToken($token);
+				$token->setRefreshToken($refreshtoken);
+				$storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token);
+			} catch (Exception $e) {
+				$this->errors[] = $e->getMessage();
+				$error++;
+			}
+		}
+		// Getting Jobs
+		// Send a request with api
+		try {
+			$response = $apiService->request(self::PRINTERS_GET_JOBS);
+		} catch (Exception $e) {
+			$this->errors[] = $e->getMessage();
+			$error++;
+		}
+		$responsedata = json_decode($response, true);
+		//$html .= '<pre>'.print_r($responsedata,true).'</pre>';
+		$html .= '<div class="div-table-responsive">';
+		$html .= '<table width="100%" class="noborder">';
+		$html .= '<tr class="liste_titre">';
+		$html .= '<td>'.$langs->trans("Id").'</td>';
+		$html .= '<td>'.$langs->trans("Date").'</td>';
+		$html .= '<td>'.$langs->trans("Owner").'</td>';
+		$html .= '<td>'.$langs->trans("Printer").'</td>';
+		$html .= '<td>'.$langs->trans("Filename").'</td>';
+		$html .= '<td>'.$langs->trans("Status").'</td>';
+		$html .= '<td>'.$langs->trans("Cancel").'</td>';
+		$html .= '</tr>'."\n";
+
+		$jobs = $responsedata['jobs'];
+		//$html .= '<pre>'.print_r($jobs['0'],true).'</pre>';
+		if (is_array($jobs)) {
+			foreach ($jobs as $value) {
+				$html .= '<tr class="oddeven">';
+				$html .= '<td>'.$value['id'].'</td>';
+				$dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour');
+				$html .= '<td>'.$dates.'</td>';
+				$html .= '<td>'.$value['ownerId'].'</td>';
+				$html .= '<td>'.$value['printerName'].'</td>';
+				$html .= '<td>'.$value['title'].'</td>';
+				$html .= '<td>'.$value['status'].'</td>';
+				$html .= '<td>&nbsp;</td>';
+				$html .= '</tr>';
+			}
+		} else {
+				$html .= '<tr class="oddeven">';
+				$html .= '<td colspan="7" class="opacitymedium">'.$langs->trans("None").'</td>';
+				$html .= '</tr>';
+		}
+		$html .= '</table>';
+		$html .= '</div>';
+
+		$this->resprint = $html;
+
+		return $error;
+	}
 }

+ 49 - 49
htdocs/core/tpl/bloc_comment.tpl.php

@@ -38,21 +38,21 @@ print "</tr>\n";
 
 if ($action !== 'editcomment')
 {
-    print '<tr class="oddeven">';
+	print '<tr class="oddeven">';
 
-    // Description
-    print '<td colspan="3">';
+	// Description
+	print '<td colspan="3">';
 
-    $desc = GETPOST('comment_description');
+	$desc = GETPOST('comment_description');
 
-    $doleditor = new DolEditor('comment_description', $desc, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%');
-    print $doleditor->Create(1);
+	$doleditor = new DolEditor('comment_description', $desc, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%');
+	print $doleditor->Create(1);
 
-    print '</td>';
+	print '</td>';
 
-    print '<td class="center">';
-    print '<input type="submit" class="button" value="'.$langs->trans("Add").'">';
-    print '</td></tr>';
+	print '<td class="center">';
+	print '<input type="submit" class="button" value="'.$langs->trans("Add").'">';
+	print '</td></tr>';
 }
 
 print '</table></form>';
@@ -96,47 +96,47 @@ if (!empty($object->comments))
 		print '<div class="comment-cell comment-right">';
 		print '<div class="comment-table width100p">';
 
-        if ($action === 'editcomment' && $comment->id == $idcomment)
-        {
-            print '<form method="POST" action="'.$varpage.'?id='.$object->id.'">';
-            print '<input type="hidden" name="token" value="'.newToken().'">';
-            print '<input type="hidden" name="action" value="updatecomment">';
-            print '<input type="hidden" name="id" value="'.$object->id.'">';
-            print '<input type="hidden" name="idcomment" value="'.$idcomment.'">';
-            print '<input type="hidden" name="withproject" value="'.$withproject.'">';
-        }
-
-        print '<div class="comment-description comment-cell">';
-        if ($action === 'editcomment' && $comment->id == $idcomment)
-        {
-            $doleditor = new DolEditor('comment_description', $comment->description, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%');
-            print $doleditor->Create(1);
-        } else {
-            print $comment->description;
-        }
+		if ($action === 'editcomment' && $comment->id == $idcomment)
+		{
+			print '<form method="POST" action="'.$varpage.'?id='.$object->id.'">';
+			print '<input type="hidden" name="token" value="'.newToken().'">';
+			print '<input type="hidden" name="action" value="updatecomment">';
+			print '<input type="hidden" name="id" value="'.$object->id.'">';
+			print '<input type="hidden" name="idcomment" value="'.$idcomment.'">';
+			print '<input type="hidden" name="withproject" value="'.$withproject.'">';
+		}
+
+		print '<div class="comment-description comment-cell">';
+		if ($action === 'editcomment' && $comment->id == $idcomment)
+		{
+			$doleditor = new DolEditor('comment_description', $comment->description, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%');
+			print $doleditor->Create(1);
+		} else {
+			print $comment->description;
+		}
 		print '</div>'; // End comment-description
 
-        if ($action === 'editcomment' && $comment->id == $idcomment)
-        {
-            print '<input name="update" type="submit" class="button" value="'.$langs->trans("Update").'">';
-            print '<input name="cancel" type="submit" class="button" value="'.$langs->trans("Cancel").'">';
-
-            print '</form>';
-        } else {
-            if ($fk_user == $user->id || $user->admin == 1)
-            {
-                print '<a class="comment-edit comment-cell" href="'.$varpage.'?action=editcomment&token='.newToken().'&id='.$id.'&withproject=1&idcomment='.$comment->id.'#comment" title="'.$langs->trans('Edit').'">';
-                print img_picto('', 'edit.png');
-                print '</a>';
-            }
-            if (($first && $fk_user == $user->id) || $user->admin == 1) {
-                print '<a class="comment-delete comment-cell" href="'.$varpage.'?action=deletecomment&token='.newToken().'&id='.$id.'&withproject=1&idcomment='.$comment->id.'" title="'.$langs->trans('Delete').'">';
-                print img_picto('', 'delete.png');
-                print '</a>';
-            }
-        }
-
-        print '</div>'; // End comment-table
+		if ($action === 'editcomment' && $comment->id == $idcomment)
+		{
+			print '<input name="update" type="submit" class="button" value="'.$langs->trans("Update").'">';
+			print '<input name="cancel" type="submit" class="button" value="'.$langs->trans("Cancel").'">';
+
+			print '</form>';
+		} else {
+			if ($fk_user == $user->id || $user->admin == 1)
+			{
+				print '<a class="comment-edit comment-cell" href="'.$varpage.'?action=editcomment&token='.newToken().'&id='.$id.'&withproject=1&idcomment='.$comment->id.'#comment" title="'.$langs->trans('Edit').'">';
+				print img_picto('', 'edit.png');
+				print '</a>';
+			}
+			if (($first && $fk_user == $user->id) || $user->admin == 1) {
+				print '<a class="comment-delete comment-cell" href="'.$varpage.'?action=deletecomment&token='.newToken().'&id='.$id.'&withproject=1&idcomment='.$comment->id.'" title="'.$langs->trans('Delete').'">';
+				print img_picto('', 'delete.png');
+				print '</a>';
+			}
+		}
+
+		print '</div>'; // End comment-table
 		print '</div>'; // End comment-right
 		print '</div>'; // End comment
 

+ 1 - 1
htdocs/ecm/class/ecmdirectory.class.php

@@ -35,7 +35,7 @@ class EcmDirectory extends CommonObject
 	/**
 	 * @var string Name of table without prefix where object is stored
 	 */
-	public $table_element='ecm_directories';
+	public $table_element = 'ecm_directories';
 
 	/**
 	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png

+ 91 - 91
htdocs/ecm/file_card.php

@@ -44,8 +44,8 @@ $socid = GETPOST("socid", "int");
 // Security check
 if ($user->socid > 0)
 {
-    $action = '';
-    $socid = $user->socid;
+	$action = '';
+	$socid = $user->socid;
 }
 
 $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
@@ -62,14 +62,14 @@ if (!$sortfield) $sortfield = "label";
 $section = GETPOST("section", 'alpha');
 if (!$section)
 {
-    dol_print_error('', 'Error, section parameter missing');
-    exit;
+	dol_print_error('', 'Error, section parameter missing');
+	exit;
 }
 $urlfile = GETPOST("urlfile");
 if (!$urlfile)
 {
-    dol_print_error('', "ErrorParamNotDefined");
-    exit;
+	dol_print_error('', "ErrorParamNotDefined");
+	exit;
 }
 
 // Load ecm object
@@ -77,8 +77,8 @@ $ecmdir = new EcmDirectory($db);
 $result = $ecmdir->fetch(GETPOST("section", 'alpha'));
 if (!$result > 0)
 {
-    dol_print_error($db, $ecmdir->error);
-    exit;
+	dol_print_error($db, $ecmdir->error);
+	exit;
 }
 $relativepath = $ecmdir->getRelativePath();
 $upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
@@ -114,67 +114,67 @@ if ($result < 0)
 
 if ($cancel)
 {
-    $action = '';
-    if ($backtopage)
-    {
-        header("Location: ".$backtopage);
-        exit;
-    } else {
-    	header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'&section='.urlencode($section).($module ? '&module='.urlencode($module) : ''));
-        exit;
-    }
+	$action = '';
+	if ($backtopage)
+	{
+		header("Location: ".$backtopage);
+		exit;
+	} else {
+		header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'&section='.urlencode($section).($module ? '&module='.urlencode($module) : ''));
+		exit;
+	}
 }
 
 // Rename file
 if ($action == 'update')
 {
-    $error = 0;
+	$error = 0;
 
-    $oldlabel = GETPOST('urlfile', 'alpha');
-    $newlabel = dol_sanitizeFileName(GETPOST('label', 'alpha'));
+	$oldlabel = GETPOST('urlfile', 'alpha');
+	$newlabel = dol_sanitizeFileName(GETPOST('label', 'alpha'));
 	$shareenabled = GETPOST('shareenabled', 'alpha');
 
-    //$db->begin();
-
-    $olddir = $ecmdir->getRelativePath(0); // Relative to ecm
-    $olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document
-    $newdirrelativetodocument = 'ecm/'.$olddir;
-    $olddir = $conf->ecm->dir_output.'/'.$olddir;
-    $newdir = $olddir;
-
-    $oldfile = $olddir.$oldlabel;
-    $newfile = $newdir.$newlabel;
-    $newfileformove = $newfile;
-    // If old file end with .noexe, new file must also end with .noexe
-    if (preg_match('/\.noexe$/', $oldfile) && ! preg_match('/\.noexe$/', $newfileformove)) {
-    	$newfileformove .= '.noexe';
-    }
-    //var_dump($oldfile);var_dump($newfile);exit;
-
-    // Now we update index of file
-    $db->begin();
-    //print $oldfile.' - '.$newfile;
-    if ($newlabel != $oldlabel)
-    {
-    	$result = dol_move($oldfile, $newfileformove); // This include update of database
-        if (!$result)
-        {
-            $langs->load('errors');
-            setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors');
-            $error++;
-        }
-
-        // Reload object after the move
-        $result = $object->fetch(0, '', $newdirrelativetodocument.$newlabel);
-        if ($result < 0)
-        {
-        	dol_print_error($db, $object->error, $object->errors);
-        	exit;
-        }
-    }
-
-    if (!$error)
-    {
+	//$db->begin();
+
+	$olddir = $ecmdir->getRelativePath(0); // Relative to ecm
+	$olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document
+	$newdirrelativetodocument = 'ecm/'.$olddir;
+	$olddir = $conf->ecm->dir_output.'/'.$olddir;
+	$newdir = $olddir;
+
+	$oldfile = $olddir.$oldlabel;
+	$newfile = $newdir.$newlabel;
+	$newfileformove = $newfile;
+	// If old file end with .noexe, new file must also end with .noexe
+	if (preg_match('/\.noexe$/', $oldfile) && ! preg_match('/\.noexe$/', $newfileformove)) {
+		$newfileformove .= '.noexe';
+	}
+	//var_dump($oldfile);var_dump($newfile);exit;
+
+	// Now we update index of file
+	$db->begin();
+	//print $oldfile.' - '.$newfile;
+	if ($newlabel != $oldlabel)
+	{
+		$result = dol_move($oldfile, $newfileformove); // This include update of database
+		if (!$result)
+		{
+			$langs->load('errors');
+			setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors');
+			$error++;
+		}
+
+		// Reload object after the move
+		$result = $object->fetch(0, '', $newdirrelativetodocument.$newlabel);
+		if ($result < 0)
+		{
+			dol_print_error($db, $object->error, $object->errors);
+			exit;
+		}
+	}
+
+	if (!$error)
+	{
 		if ($shareenabled)
 		{
 			require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
@@ -217,23 +217,23 @@ if ($action == 'update')
 				setEventMessages($object->error, $object->errors, 'warnings');
 			}
 		}
-    }
-
-    if (!$error)
-    {
-        $db->commit();
-
-        $urlfile = $newlabel;
-        // If old file end with .noexe, new file must also end with .noexe
-        if (preg_match('/\.noexe$/', $newfileformove)) {
-        	$urlfile .= '.noexe';
-        }
-
-        header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'&section='.urlencode($section));
-        exit;
-    } else {
-        $db->rollback();
-    }
+	}
+
+	if (!$error)
+	{
+		$db->commit();
+
+		$urlfile = $newlabel;
+		// If old file end with .noexe, new file must also end with .noexe
+		if (preg_match('/\.noexe$/', $newfileformove)) {
+			$urlfile .= '.noexe';
+		}
+
+		header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'&section='.urlencode($section));
+		exit;
+	} else {
+		$db->rollback();
+	}
 }
 
 
@@ -381,7 +381,7 @@ if (!empty($object->share))
 }
 print '</td>';
 print '</tr>';
-print $object->showOptionals($extrafields, ($action == 'edit'?'edit':'view'));
+print $object->showOptionals($extrafields, ($action == 'edit' ? 'edit' : 'view'));
 print '</table>';
 print '</div>';
 
@@ -392,20 +392,20 @@ dol_fiche_end();
 
 if ($action == 'edit')
 {
-    print '<div class="center">';
-    print '<input type="submit" class="button" name="submit" value="'.$langs->trans("Save").'">';
-    print ' &nbsp; &nbsp; ';
-    print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
-    print '</div>';
+	print '<div class="center">';
+	print '<input type="submit" class="button" name="submit" value="'.$langs->trans("Save").'">';
+	print ' &nbsp; &nbsp; ';
+	print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
+	print '</div>';
 
-    print '</form>';
+	print '</form>';
 }
 
 
 // Confirmation de la suppression d'une ligne categorie
 if ($action == 'delete_file')
 {
-    print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1);
+	print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1);
 }
 
 if ($action != 'edit')
@@ -413,11 +413,11 @@ if ($action != 'edit')
 	// Actions buttons
 	print '<div class="tabsAction">';
 
-    if ($user->rights->ecm->setup)
-    {
-        print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&section='.urlencode($section).'&urlfile='.urlencode($urlfile).'">'.$langs->trans('Edit').'</a>';
-    }
-    /*
+	if ($user->rights->ecm->setup)
+	{
+		print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&section='.urlencode($section).'&urlfile='.urlencode($urlfile).'">'.$langs->trans('Edit').'</a>';
+	}
+	/*
 	if ($user->rights->ecm->setup)
 	{
 		print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=delete_file&token='.newToken().'&section='.$section.'&urlfile='.urlencode($urlfile).'">'.$langs->trans('Delete').'</a>';

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

@@ -405,7 +405,7 @@ class ExpenseReport extends CommonObject
 		$this->id = 0;
 		$this->ref = '';
 		$this->status = 0;
-		$this->fk_statut = 0;	// deprecated
+		$this->fk_statut = 0; // deprecated
 
 		// Clear fields
 		$this->fk_user_author     = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
@@ -1353,7 +1353,7 @@ class ExpenseReport extends CommonObject
 			$sql .= ' WHERE rowid = '.$this->id;
 			if ($this->db->query($sql))
 			{
-				$this->fk_statut = 99;	// deprecated
+				$this->fk_statut = 99; // deprecated
 				$this->status = 99;
 				$this->fk_user_refuse = $fuser->id;
 				$this->detail_refuse = $details;

+ 271 - 271
htdocs/fichinter/card.php

@@ -202,16 +202,16 @@ if (empty($reshook))
 		}
 	} elseif ($action == 'add' && $user->rights->ficheinter->creer)
 	{
-	    $object->socid = $socid;
-	    $object->duration = GETPOST('duration', 'int');
-	    $object->fk_project		= GETPOST('projectid', 'int');
-	    $object->fk_contrat		= GETPOST('contratid', 'int');
-	    $object->author = $user->id;
-	    $object->description	= GETPOST('description', 'restricthtml');
-	    $object->ref = $ref;
-	    $object->model_pdf = GETPOST('model', 'alpha');
-	    $object->note_private = GETPOST('note_private', 'restricthtml');
-	    $object->note_public = GETPOST('note_public', 'restricthtml');
+		$object->socid = $socid;
+		$object->duration = GETPOST('duration', 'int');
+		$object->fk_project		= GETPOST('projectid', 'int');
+		$object->fk_contrat		= GETPOST('contratid', 'int');
+		$object->author = $user->id;
+		$object->description	= GETPOST('description', 'restricthtml');
+		$object->ref = $ref;
+		$object->model_pdf = GETPOST('model', 'alpha');
+		$object->note_private = GETPOST('note_private', 'restricthtml');
+		$object->note_public = GETPOST('note_public', 'restricthtml');
 
 		if ($object->socid > 0)
 		{
@@ -251,7 +251,7 @@ if (empty($reshook))
 				$extrafields = new ExtraFields($db);
 				$array_options = $extrafields->getOptionalsFromPost($object->table_element);
 
-		        $object->array_options = $array_options;
+				$object->array_options = $array_options;
 
 				$id = $object->create($user);
 
@@ -356,12 +356,12 @@ if (empty($reshook))
 
 									$result = $object->addline(
 										$user,
-				                        $id,
-				                        $desc,
-							            $date_intervention,
-		                 				$duration,
-		                 				$array_options
-				                    );
+										$id,
+										$desc,
+										$date_intervention,
+						 				$duration,
+						 				$array_options
+									);
 
 									if ($result < 0)
 									{
@@ -371,44 +371,44 @@ if (empty($reshook))
 								}
 							}
 						}
-		            } else {
+					} else {
 						$mesg = $srcobject->error;
-		                $error++;
-		            }
-		        } else {
+						$error++;
+					}
+				} else {
 					$mesg = $object->error;
-		            $error++;
-		        }
-		    } else {
-		    	// Fill array 'array_options' with data from add form
-		    	$ret = $extrafields->setOptionalsFromPost(null, $object);
-		    	if ($ret < 0) {
-		    		$error++;
-		    		$action = 'create';
-		    	}
-
-		    	if (!$error)
-		    	{
-		    		// Extrafields
-		    		$array_options = $extrafields->getOptionalsFromPost($object->table_element);
-
-		    		$object->array_options = $array_options;
-
-		    		$result = $object->create($user);
-		    		if ($result > 0)
-		    		{
-		    			$id = $result; // Force raffraichissement sur fiche venant d'etre cree
-		    		} else {
-		    			$langs->load("errors");
-		    			setEventMessages($object->error, $object->errors, 'errors');
-		    			$action = 'create';
-		    		}
-		    	}
-	        }
-	    } else {
+					$error++;
+				}
+			} else {
+				// Fill array 'array_options' with data from add form
+				$ret = $extrafields->setOptionalsFromPost(null, $object);
+				if ($ret < 0) {
+					$error++;
+					$action = 'create';
+				}
+
+				if (!$error)
+				{
+					// Extrafields
+					$array_options = $extrafields->getOptionalsFromPost($object->table_element);
+
+					$object->array_options = $array_options;
+
+					$result = $object->create($user);
+					if ($result > 0)
+					{
+						$id = $result; // Force raffraichissement sur fiche venant d'etre cree
+					} else {
+						$langs->load("errors");
+						setEventMessages($object->error, $object->errors, 'errors');
+						$action = 'create';
+					}
+				}
+			}
+		} else {
 			$mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty"));
-	        $action = 'create';
-	    }
+			$action = 'create';
+		}
 	} elseif ($action == 'update' && $user->rights->ficheinter->creer)
 	{
 		$object->socid = $socid;
@@ -482,14 +482,14 @@ if (empty($reshook))
 			$extrafields->fetch_name_optionals_label($object->table_element_line);
 			$array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
 
-        	$result = $object->addline(
+			$result = $object->addline(
 				$user,
-	            $id,
-	            $desc,
-	            $date_intervention,
-	            $duration,
-	            $array_options
-	        );
+				$id,
+				$desc,
+				$date_intervention,
+				$duration,
+				$array_options
+			);
 
 			// Define output language
 			$outputlangs = $langs;
@@ -545,14 +545,14 @@ if (empty($reshook))
 	// Classify Done
 	elseif ($action == 'classifydone' && $user->rights->ficheinter->creer)
 	{
-	    $result = $object->setStatut(3);
-	    if ($result > 0)
-	    {
-	        header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
-	        exit;
-	    } else {
-	        setEventMessages($object->error, $object->errors, 'errors');
-	    }
+		$result = $object->setStatut(3);
+		if ($result > 0)
+		{
+			header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
+			exit;
+		} else {
+			setEventMessages($object->error, $object->errors, 'errors');
+		}
 	}
 
 	// Reopen
@@ -591,9 +591,9 @@ if (empty($reshook))
 		$date_inter = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int'));
 		$duration = convertTime2Seconds(GETPOST('durationhour', 'int'), GETPOST('durationmin', 'int'));
 
-	    $objectline->datei = $date_inter;
-	    $objectline->desc = $desc;
-	    $objectline->duration = $duration;
+		$objectline->datei = $date_inter;
+		$objectline->desc = $desc;
+		$objectline->duration = $duration;
 
 		// Extrafields
 		$extrafields->fetch_name_optionals_label($object->table_element_line);
@@ -601,11 +601,11 @@ if (empty($reshook))
 		$objectline->array_options = $array_options;
 
 		$result = $objectline->update($user);
-	    if ($result < 0)
-	    {
-	        dol_print_error($db);
-	        exit;
-	    }
+		if ($result < 0)
+		{
+			dol_print_error($db);
+			exit;
+		}
 
 		// Define output language
 		$outputlangs = $langs;
@@ -817,11 +817,11 @@ if ($action == 'create')
 			$subelement = $regs[2];
 		}
 
-        if ($element == 'project')
-        {
-            $projectid = GETPOST('originid', 'int');
-        } else {
-            // For compatibility
+		if ($element == 'project')
+		{
+			$projectid = GETPOST('originid', 'int');
+		} else {
+			// For compatibility
 			if ($element == 'order' || $element == 'commande') {
 				$element = $subelement = 'commande';
 			}
@@ -904,20 +904,20 @@ if ($action == 'create')
 
 			$langs->load("project");
 
-            print '<tr><td>'.$langs->trans("Project").'</td><td>';
-            /* Fix: If a project must be linked to any companies (suppliers or not), project must be not be set as limited to customer but must be not linked to any particular thirdparty
+			print '<tr><td>'.$langs->trans("Project").'</td><td>';
+			/* Fix: If a project must be linked to any companies (suppliers or not), project must be not be set as limited to customer but must be not linked to any particular thirdparty
             if ($societe->fournisseur==1)
             	$numprojet=select_projects(-1,$_POST["projectid"],'projectid');
             else
             	$numprojet=select_projects($societe->id,$_POST["projectid"],'projectid');
             	*/
-            $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid');
-            if ($numprojet == 0)
-            {
-                print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddProject").'"></span></a>';
-            }
-            print '</td></tr>';
-        }
+			$numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid');
+			if ($numprojet == 0)
+			{
+				print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddProject").'"></span></a>';
+			}
+			print '</td></tr>';
+		}
 
 		// Contract
 		if ($conf->contrat->enabled)
@@ -932,53 +932,53 @@ if ($action == 'create')
 			print '</td></tr>';
 		}
 
-        // Model
-        print '<tr>';
-        print '<td>'.$langs->trans("DefaultModel").'</td>';
-        print '<td>';
-        $liste = ModelePDFFicheinter::liste_modeles($db);
-        print $form->selectarray('model', $liste, $conf->global->FICHEINTER_ADDON_PDF);
-        print "</td></tr>";
-
-        // Public note
-        print '<tr>';
-        print '<td class="tdtop">'.$langs->trans('NotePublic').'</td>';
-        print '<td>';
-        $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
-        print $doleditor->Create(1);
-        //print '<textarea name="note_public" cols="80" rows="'.ROWS_3.'">'.$note_public.'</textarea>';
-        print '</td></tr>';
-
-        // Private note
-        if (empty($user->socid))
-        {
-        	print '<tr>';
-        	print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>';
-        	print '<td>';
-        	$doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
-        	print $doleditor->Create(1);
-        	//print '<textarea name="note_private" cols="80" rows="'.ROWS_3.'">'.$note_private.'</textarea>';
-        	print '</td></tr>';
-        }
-
-        // Other attributes
-        $parameters = array();
-        $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-        print $hookmanager->resPrint;
-        if (empty($reshook))
+		// Model
+		print '<tr>';
+		print '<td>'.$langs->trans("DefaultModel").'</td>';
+		print '<td>';
+		$liste = ModelePDFFicheinter::liste_modeles($db);
+		print $form->selectarray('model', $liste, $conf->global->FICHEINTER_ADDON_PDF);
+		print "</td></tr>";
+
+		// Public note
+		print '<tr>';
+		print '<td class="tdtop">'.$langs->trans('NotePublic').'</td>';
+		print '<td>';
+		$doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
+		print $doleditor->Create(1);
+		//print '<textarea name="note_public" cols="80" rows="'.ROWS_3.'">'.$note_public.'</textarea>';
+		print '</td></tr>';
+
+		// Private note
+		if (empty($user->socid))
+		{
+			print '<tr>';
+			print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>';
+			print '<td>';
+			$doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
+			print $doleditor->Create(1);
+			//print '<textarea name="note_private" cols="80" rows="'.ROWS_3.'">'.$note_private.'</textarea>';
+			print '</td></tr>';
+		}
+
+		// Other attributes
+		$parameters = array();
+		$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+		print $hookmanager->resPrint;
+		if (empty($reshook))
 		{
 			print $object->showOptionals($extrafields, 'edit');
 		}
 
-        // Show link to origin object
-        if (!empty($origin) && !empty($originid) && is_object($objectsrc))
-        {
-        	$newclassname = $classname;
-        	if ($newclassname == 'Propal') $newclassname = 'CommercialProposal';
-        	print '<tr><td>'.$langs->trans($newclassname).'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>';
+		// Show link to origin object
+		if (!empty($origin) && !empty($originid) && is_object($objectsrc))
+		{
+			$newclassname = $classname;
+			if ($newclassname == 'Propal') $newclassname = 'CommercialProposal';
+			print '<tr><td>'.$langs->trans($newclassname).'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>';
 
-        	// Amount
-        	/* Hide amount because we only copy services so amount may differ than source
+			// Amount
+			/* Hide amount because we only copy services so amount may differ than source
         	print '<tr><td>' . $langs->trans('AmountHT') . '</td><td>' . price($objectsrc->total_ht) . '</td></tr>';
         	print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td>' . price($objectsrc->total_tva) . "</td></tr>";
         	if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) 		// Localtax1 RE
@@ -1000,14 +1000,14 @@ if ($action == 'create')
         		print '<tr><td>' . $langs->trans('MulticurrencyAmountTTC') . '</td><td>' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>";
         	}
         	*/
-        }
+		}
 
-        print '</table>';
+		print '</table>';
 
-	    if (is_object($objectsrc))
-	    {
-	        print '<input type="hidden" name="origin"         value="'.$objectsrc->element.'">';
-	        print '<input type="hidden" name="originid"       value="'.$objectsrc->id.'">';
+		if (is_object($objectsrc))
+		{
+			print '<input type="hidden" name="origin"         value="'.$objectsrc->element.'">';
+			print '<input type="hidden" name="originid"       value="'.$objectsrc->id.'">';
 		} elseif ($origin == 'project' && !empty($projectid)) {
 			print '<input type="hidden" name="projectid" value="'.$projectid.'">';
 		}
@@ -1016,8 +1016,8 @@ if ($action == 'create')
 
 		print '<div class="center">';
 		print '<input type="submit" class="button" value="'.$langs->trans("CreateDraftIntervention").'">';
-    	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-    	print '<input type="button" class="button" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
+		print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+		print '<input type="button" class="button" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
 		print '</div>';
 
 		print '</form>';
@@ -1058,8 +1058,8 @@ if ($action == 'create')
 		print '<div class="center">';
 		print '<input type="hidden" name="action" value="create">';
 		print '<input type="submit" class="button" value="'.$langs->trans("CreateDraftIntervention").'">';
-    	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
-    	print '<input type="button" class="button" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
+		print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
+		print '<input type="button" class="button" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
 		print '</div>';
 
 		print '</form>';
@@ -1172,46 +1172,46 @@ if ($action == 'create')
 	// Project
 	if (!empty($conf->projet->enabled))
 	{
-	    $langs->load("projects");
-	    $morehtmlref .= '<br>'.$langs->trans('Project').' ';
-	    if ($user->rights->ficheinter->creer)
-	    {
-            if ($action != 'classify') {
-                $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($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
-                $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
-                $morehtmlref .= '</form>';
-            } else {
-                $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
-            }
-	    } else {
-	        if (!empty($object->fk_project)) {
-	            $proj = new Project($db);
-	            $proj->fetch($object->fk_project);
-	            $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
-	            $morehtmlref .= $proj->ref;
-	            $morehtmlref .= '</a>';
-	        } else {
-	            $morehtmlref .= '';
-	        }
-	    }
+		$langs->load("projects");
+		$morehtmlref .= '<br>'.$langs->trans('Project').' ';
+		if ($user->rights->ficheinter->creer)
+		{
+			if ($action != 'classify') {
+				$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($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+				$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+				$morehtmlref .= '</form>';
+			} else {
+				$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+			}
+		} else {
+			if (!empty($object->fk_project)) {
+				$proj = new Project($db);
+				$proj->fetch($object->fk_project);
+				$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
+				$morehtmlref .= $proj->ref;
+				$morehtmlref .= '</a>';
+			} else {
+				$morehtmlref .= '';
+			}
+		}
 	}
 	$morehtmlref .= '</div>';
 
-    dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
 
 
-    print '<div class="fichecenter">';
-    print '<div class="fichehalfleft">';
-    print '<div class="underbanner clearboth"></div>';
+	print '<div class="fichecenter">';
+	print '<div class="fichehalfleft">';
+	print '<div class="underbanner clearboth"></div>';
 
-    print '<table class="border tableforfield" width="100%">';
+	print '<table class="border tableforfield" width="100%">';
 
 	if (!empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES))
 	{
@@ -1269,47 +1269,47 @@ if ($action == 'create')
 			$formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1, 1);
 		} else {
 			if ($object->fk_contrat)
-            {
-                $contratstatic = new Contrat($db);
-                $contratstatic->fetch($object->fk_contrat);
-                //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
-                print $contratstatic->getNomUrl(0, '', 1);
-            } else {
-                print "&nbsp;";
-            }
+			{
+				$contratstatic = new Contrat($db);
+				$contratstatic->fetch($object->fk_contrat);
+				//print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
+				print $contratstatic->getNomUrl(0, '', 1);
+			} else {
+				print "&nbsp;";
+			}
 		}
 		print '</td>';
 		print '</tr>';
 	}
 
-    // Other attributes
-    $cols = 2;
-    include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
+	// Other attributes
+	$cols = 2;
+	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
 
-    print '</table>';
+	print '</table>';
 
-    print '</div>';
-    print '<div class="fichehalfright">';
-    print '<div class="ficheaddleft">';
-    print '<div class="underbanner clearboth"></div>';
+	print '</div>';
+	print '<div class="fichehalfright">';
+	print '<div class="ficheaddleft">';
+	print '<div class="underbanner clearboth"></div>';
 
-    print '<table class="border tableforfield centpercent">';
+	print '<table class="border tableforfield centpercent">';
 
-    if (empty($conf->global->FICHINTER_DISABLE_DETAILS))
-    {
-        // Duration
-        print '<tr><td class="titlefield">'.$langs->trans("TotalDuration").'</td>';
-        print '<td>'.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'</td>';
-        print '</tr>';
-    }
+	if (empty($conf->global->FICHINTER_DISABLE_DETAILS))
+	{
+		// Duration
+		print '<tr><td class="titlefield">'.$langs->trans("TotalDuration").'</td>';
+		print '<td>'.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'</td>';
+		print '</tr>';
+	}
 
 	print "</table>";
 
 	print '</div>';
-    print '</div>';
-    print '</div>';
+	print '</div>';
+	print '</div>';
 
-    print '<div class="clearboth"></div><br>';
+	print '<div class="clearboth"></div><br>';
 
 
 	if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
@@ -1464,25 +1464,25 @@ if ($action == 'create')
 
 					// Date d'intervention
 					print '<td class="center nowrap">';
-                    if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) {
-                        print $form->selectDate($db->jdate($objp->date_intervention), 'di', 0, 0, 0, "date_intervention");
-                    } else {
-                        print $form->selectDate($db->jdate($objp->date_intervention), 'di', 1, 1, 0, "date_intervention");
-                    }
+					if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) {
+						print $form->selectDate($db->jdate($objp->date_intervention), 'di', 0, 0, 0, "date_intervention");
+					} else {
+						print $form->selectDate($db->jdate($objp->date_intervention), 'di', 1, 1, 0, "date_intervention");
+					}
+					print '</td>';
+
+					// Duration
+					print '<td class="right">';
+					if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) {
+						$selectmode = 'select';
+						if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION))
+							$selectmode = 'text';
+						$form->select_duration('duration', $objp->duree, 0, $selectmode);
+					}
 					print '</td>';
 
-                    // Duration
-                    print '<td class="right">';
-                    if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) {
-                        $selectmode = 'select';
-                        if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION))
-                            $selectmode = 'text';
-                        $form->select_duration('duration', $objp->duree, 0, $selectmode);
-                    }
-                    print '</td>';
-
-                    print '<td class="center" colspan="5" valign="center">';
-                    print '<input type="submit" class="button buttongen marginbottomonly" name="save" value="'.$langs->trans("Save").'">';
+					print '<td class="center" colspan="5" valign="center">';
+					print '<input type="submit" class="button buttongen marginbottomonly" name="save" value="'.$langs->trans("Save").'">';
 					print '<input type="submit" class="button buttongen marginbottomonly" name="cancel" value="'.$langs->trans("Cancel").'"></td>';
 					print '</tr>'."\n";
 
@@ -1514,13 +1514,13 @@ if ($action == 'create')
 						print '<td width="5" class="center linecolnum"></td>';
 					}
 
-    				print '<td>';
-    				print '<a name="add"></a>'; // ancre
-    				print $langs->trans('Description').'</td>';
-    				print '<td class="center">'.$langs->trans('Date').'</td>';
-    				print '<td class="right">'.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').'</td>';
-      				print '<td colspan="3">&nbsp;</td>';
-    				print "</tr>\n";
+					print '<td>';
+					print '<a name="add"></a>'; // ancre
+					print $langs->trans('Description').'</td>';
+					print '<td class="center">'.$langs->trans('Date').'</td>';
+					print '<td class="right">'.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').'</td>';
+	  				print '<td colspan="3">&nbsp;</td>';
+					print "</tr>\n";
 				}
 
 				print '<tr class="oddeven nohover">'."\n";
@@ -1530,43 +1530,43 @@ if ($action == 'create')
 					print '<td class="center linecolnum">'.($i + 1).'</td>';
 				}
 
-                print '<td>';
-                // editeur wysiwyg
-                if (empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) {
-                    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-                    $doleditor = new DolEditor('np_desc', GETPOST('np_desc', 'restricthtml'), '', 100, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%');
-                    $doleditor->Create();
-                }
-                print '</td>';
-
-                // Date intervention
-                print '<td class="center nowrap">';
+				print '<td>';
+				// editeur wysiwyg
+				if (empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) {
+					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+					$doleditor = new DolEditor('np_desc', GETPOST('np_desc', 'restricthtml'), '', 100, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%');
+					$doleditor->Create();
+				}
+				print '</td>';
+
+				// Date intervention
+				print '<td class="center nowrap">';
 				$now = dol_now();
 				$timearray = dol_getdate($now);
 				if (!GETPOST('diday', 'int')) {
-                    $timewithnohour = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']);
-                } else {
-                    $timewithnohour = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int'));
-                }
-                if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) {
-                    print $form->selectDate($timewithnohour, 'di', 0, 0, 0, "addinter");
-                } else {
-                    print $form->selectDate($timewithnohour, 'di', 1, 1, 0, "addinter");
-                }
+					$timewithnohour = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']);
+				} else {
+					$timewithnohour = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int'));
+				}
+				if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) {
+					print $form->selectDate($timewithnohour, 'di', 0, 0, 0, "addinter");
+				} else {
+					print $form->selectDate($timewithnohour, 'di', 1, 1, 0, "addinter");
+				}
+				print '</td>';
+
+				// Duration
+				print '<td class="right">';
+				if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) {
+					$selectmode = 'select';
+					if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) {
+						$selectmode = 'text';
+					}
+					$form->select_duration('duration', (!GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) ? 3600 : (60 * 60 * GETPOST('durationhour', 'int') + 60 * GETPOST('durationmin', 'int')), 0, $selectmode);
+				}
 				print '</td>';
 
-                // Duration
-                print '<td class="right">';
-                if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) {
-                    $selectmode = 'select';
-                    if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) {
-                        $selectmode = 'text';
-                    }
-                    $form->select_duration('duration', (!GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) ? 3600 : (60 * 60 * GETPOST('durationhour', 'int') + 60 * GETPOST('durationmin', 'int')), 0, $selectmode);
-                }
-                print '</td>';
-
-                print '<td class="center" valign="middle" colspan="3"><input type="submit" class="button" value="'.$langs->trans('Add').'" name="addline"></td>';
+				print '<td class="center" valign="middle" colspan="3"><input type="submit" class="button" value="'.$langs->trans('Add').'" name="addline"></td>';
 				print '</tr>';
 
 				//Line extrafield
@@ -1601,22 +1601,22 @@ if ($action == 'create')
 
 	$parameters = array();
 	$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
-		                                                                                          // modified by hook
+																								  // modified by hook
 	if (empty($reshook))
 	{
 		if ($user->socid == 0)
 		{
-            if ($action != 'editdescription' && ($action != 'presend')) {
-                // Validate
-                if ($object->statut == Fichinter::STATUS_DRAFT && (count($object->lines) > 0 || !empty($conf->global->FICHINTER_DISABLE_DETAILS))) {
-                    if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->validate)) {
-                        print '<div class="inline-block divButAction"><a class="butAction" href="card.php?id='.$object->id.'&action=validate"';
-                        print '>'.$langs->trans("Validate").'</a></div>';
-                    }
-                }
-
-                // Modify
-                if ($object->statut == Fichinter::STATUS_VALIDATED && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->unvalidate)))
+			if ($action != 'editdescription' && ($action != 'presend')) {
+				// Validate
+				if ($object->statut == Fichinter::STATUS_DRAFT && (count($object->lines) > 0 || !empty($conf->global->FICHINTER_DISABLE_DETAILS))) {
+					if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->validate)) {
+						print '<div class="inline-block divButAction"><a class="butAction" href="card.php?id='.$object->id.'&action=validate"';
+						print '>'.$langs->trans("Validate").'</a></div>';
+					}
+				}
+
+				// Modify
+				if ($object->statut == Fichinter::STATUS_VALIDATED && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->unvalidate)))
 				{
 					print '<div class="inline-block divButAction"><a class="butAction" href="card.php?id='.$object->id.'&action=modify">';
 					if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) print $langs->trans("Modify");
@@ -1684,7 +1684,7 @@ if ($action == 'create')
 				}
 
 				// Done
-            	if (empty($conf->global->FICHINTER_CLASSIFY_BILLED) && $object->statut > Fichinter::STATUS_DRAFT && $object->statut < Fichinter::STATUS_CLOSED)
+				if (empty($conf->global->FICHINTER_CLASSIFY_BILLED) && $object->statut > Fichinter::STATUS_DRAFT && $object->statut < Fichinter::STATUS_CLOSED)
 				{
 					print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifydone">'.$langs->trans("InterventionClassifyDone").'</a></div>';
 				}

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

@@ -702,7 +702,7 @@ class FactureFournisseur extends CommonInvoice
 				$this->note_private			= $obj->note_private;
 				$this->note_public = $obj->note_public;
 				$this->model_pdf = $obj->model_pdf;
-				$this->modelpdf = $obj->model_pdf;	// deprecated
+				$this->modelpdf = $obj->model_pdf; // deprecated
 				$this->import_key = $obj->import_key;
 
 				//Incoterms
@@ -827,7 +827,7 @@ class FactureFournisseur extends CommonInvoice
 
 					// Accountancy
 					$line->code_ventilation = $obj->fk_code_ventilation;
-					$line->fk_accounting_account	= $obj->fk_code_ventilation;
+					$line->fk_accounting_account = $obj->fk_code_ventilation;
 
 					// Multicurrency
 					$line->fk_multicurrency = $obj->fk_multicurrency;

+ 21 - 21
htdocs/fourn/commande/list.php

@@ -364,30 +364,30 @@ if (empty($reshook))
 							{
 								$fk_parent_line = 0;
 							}
-                            $result = $objecttmp->addline(
+							$result = $objecttmp->addline(
 								$desc,
 								$lines[$i]->subprice,
 								$lines[$i]->tva_tx,
 								$lines[$i]->localtax1_tx,
 								$lines[$i]->localtax2_tx,
-                            	$lines[$i]->qty,
-                            	$lines[$i]->fk_product,
+								$lines[$i]->qty,
+								$lines[$i]->fk_product,
 								$lines[$i]->remise_percent,
 								$date_start,
 								$date_end,
 								0,
 								$lines[$i]->info_bits,
-                            	'HT',
-                            	$product_type,
-                            	$lines[$i]->rang,
-                            	false,
-                            	$lines[$i]->array_options,
-                            	$lines[$i]->fk_unit,
-                            	$objecttmp->origin_id,
-                            	$lines[$i]->pa_ht,
-                            	$lines[$i]->ref_supplier,
-                            	$lines[$i]->special_code,
-                            	$fk_parent_line
+								'HT',
+								$product_type,
+								$lines[$i]->rang,
+								false,
+								$lines[$i]->array_options,
+								$lines[$i]->fk_unit,
+								$objecttmp->origin_id,
+								$lines[$i]->pa_ht,
+								$lines[$i]->ref_supplier,
+								$lines[$i]->special_code,
+								$fk_parent_line
 							);
 							if ($result > 0)
 							{
@@ -686,7 +686,7 @@ if ($resql)
 	$arrayofmassactions = array(
 		'generate_doc'=>$langs->trans("ReGeneratePDF"),
 		'builddoc'=>$langs->trans("PDFMerge"),
-	    'presend'=>$langs->trans("SendByMail"),
+		'presend'=>$langs->trans("SendByMail"),
 	);
 	if ($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier");
 	if ($user->rights->fournisseur->commande->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
@@ -1293,14 +1293,14 @@ if ($resql)
 
 	$db->free($resql);
 
-    $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;
+	$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>'."\n";
-    print '</div>';
+	print '</table>'."\n";
+	print '</div>';
 
-    print '</form>'."\n";
+	print '</form>'."\n";
 
 	$hidegeneratedfilelistifempty = 1;
 	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0;

+ 276 - 276
htdocs/fourn/facture/card.php

@@ -153,21 +153,21 @@ if (empty($reshook))
 	// Action clone object
 	if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd)
 	{
-	    $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid.
-
-	    if (GETPOST('newsupplierref', 'alphanohtml')) $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml');
-	    $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
-
-	    $result = $objectutil->createFromClone($user, $id);
-        if ($result > 0)
-        {
-        	header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
-        	exit;
-        } else {
-        	$langs->load("errors");
-        	setEventMessages($objectutil->error, $objectutil->errors, 'errors');
-        	$action = '';
-        }
+		$objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid.
+
+		if (GETPOST('newsupplierref', 'alphanohtml')) $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml');
+		$objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
+
+		$result = $objectutil->createFromClone($user, $id);
+		if ($result > 0)
+		{
+			header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
+			exit;
+		} else {
+			$langs->load("errors");
+			setEventMessages($objectutil->error, $objectutil->errors, 'errors');
+			$action = '';
+		}
 	}	elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
 		$idwarehouse = GETPOST('idwarehouse');
 
@@ -1041,7 +1041,7 @@ if (empty($reshook))
 		$object->fetch($id);
 		$object->fetch_thirdparty();
 
-        $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
+		$tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
 
 		if (GETPOST('price_ht') != '')
 		{
@@ -1077,17 +1077,17 @@ if (empty($reshook))
 		$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
 		$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
 
-	    // Define info_bits
-	    $info_bits = 0;
-	    if (preg_match('/\*/', $tva_tx))
-	    	$info_bits |= 0x01;
+		// Define info_bits
+		$info_bits = 0;
+		if (preg_match('/\*/', $tva_tx))
+			$info_bits |= 0x01;
 
-	    // Define vat_rate
-	    $tva_tx = str_replace('*', '', $tva_tx);
-        $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
-        $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
+		// Define vat_rate
+		$tva_tx = str_replace('*', '', $tva_tx);
+		$localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
+		$localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
 
-        $remise_percent = GETPOST('remise_percent');
+		$remise_percent = GETPOST('remise_percent');
 		$pu_ht_devise = GETPOST('multicurrency_subprice');
 
 		// Extrafields Lines
@@ -1100,12 +1100,12 @@ if (empty($reshook))
 			}
 		}
 
-        $result = $object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha'));
-        if ($result >= 0)
-        {
-            unset($_POST['label']);
-            unset($_POST['fourn_ref']);
-            unset($_POST['date_starthour']);
+		$result = $object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha'));
+		if ($result >= 0)
+		{
+			unset($_POST['label']);
+			unset($_POST['fourn_ref']);
+			unset($_POST['date_starthour']);
 			unset($_POST['date_startmin']);
 			unset($_POST['date_startsec']);
 			unset($_POST['date_startday']);
@@ -1250,7 +1250,7 @@ if (empty($reshook))
 
 				// if we use supplier description of the products
 				if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) {
-				    $desc = $productsupplier->desc_supplier;
+					$desc = $productsupplier->desc_supplier;
 				} else $desc = $productsupplier->description;
 
 				if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
@@ -1301,8 +1301,8 @@ if (empty($reshook))
 					$array_options,
 					$productsupplier->fk_unit,
 					0,
-                    $pu_ht_devise,
-                    $ref_supplier,
+					$pu_ht_devise,
+					$ref_supplier,
 					''
 				);
 			}
@@ -1430,34 +1430,34 @@ if (empty($reshook))
 
 		if (!$ventilExportCompta)
 		{
-		    // On verifie si aucun paiement n'a ete effectue
+			// On verifie si aucun paiement n'a ete effectue
 			if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED)
-		    {
-	            $idwarehouse = GETPOST('idwarehouse');
-
-	            $object->fetch_thirdparty();
-
-	            $qualified_for_stock_change = 0;
-	            if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
-	            {
-	                $qualified_for_stock_change = $object->hasProductsOrServices(2);
-	            } else {
-	                $qualified_for_stock_change = $object->hasProductsOrServices(1);
-	            }
-
-	            // Check parameters
-	            if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
-	            {
-	                $langs->load("stocks");
-	                if (!$idwarehouse || $idwarehouse == -1)
-	                {
-	                    $error++;
-	                    setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
-	                    $action = '';
-	                }
-	            }
-
-	            $object->setDraft($user, $idwarehouse);
+			{
+				$idwarehouse = GETPOST('idwarehouse');
+
+				$object->fetch_thirdparty();
+
+				$qualified_for_stock_change = 0;
+				if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
+				{
+					$qualified_for_stock_change = $object->hasProductsOrServices(2);
+				} else {
+					$qualified_for_stock_change = $object->hasProductsOrServices(1);
+				}
+
+				// Check parameters
+				if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
+				{
+					$langs->load("stocks");
+					if (!$idwarehouse || $idwarehouse == -1)
+					{
+						$error++;
+						setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
+						$action = '';
+					}
+				}
+
+				$object->setDraft($user, $idwarehouse);
 
 				// Define output language
 				if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
@@ -1771,9 +1771,9 @@ if ($action == 'create')
 	print '</td></tr>';
 
 	// Ref supplier
-    print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="ref_supplier" value="'.(isset($_POST['ref_supplier']) ? $_POST['ref_supplier'] : $objectsrc->ref_supplier).'" type="text"';
-    if ($societe->id > 0) print ' autofocus';
-    print '></td>';
+	print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="ref_supplier" value="'.(isset($_POST['ref_supplier']) ? $_POST['ref_supplier'] : $objectsrc->ref_supplier).'" type="text"';
+	if ($societe->id > 0) print ' autofocus';
+	print '></td>';
 	print '</tr>';
 
 	print '<tr><td class="tdtop fieldrequired">'.$langs->trans('Type').'</td><td>';
@@ -2059,7 +2059,7 @@ if ($action == 'create')
 	$doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ?GETPOST('note_public', 'restricthtml') : $note_public), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
 	print $doleditor->Create(1);
 	print '</td>';
-    // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
+	// print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
 	print '</tr>';
 
 	// Private note
@@ -2241,8 +2241,8 @@ if ($action == 'create')
 		{
 			// Create an array for form
 			$formquestion = array(
-			    array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier),
-			    array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
+				array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier),
+				array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
 			);
 			// Ask confirmation to clone
 			$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250);
@@ -2279,59 +2279,59 @@ if ($action == 'create')
 				$qualified_for_stock_change = $object->hasProductsOrServices(1);
 			}
 
-            if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
-            {
-                $langs->load("stocks");
-                require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
-                $formproduct = new FormProduct($db);
-                $warehouse = new Entrepot($db);
-                $warehouse_array = $warehouse->list_array();
-                if (count($warehouse_array) == 1) {
-                    $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
-                    $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
-                } else {
-                    $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
-                    $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
-                }
-                $formquestion = array(
-                    array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
-                );
-            }
+			if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
+			{
+				$langs->load("stocks");
+				require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+				$formproduct = new FormProduct($db);
+				$warehouse = new Entrepot($db);
+				$warehouse_array = $warehouse->list_array();
+				if (count($warehouse_array) == 1) {
+					$label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
+					$value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
+				} else {
+					$label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
+					$value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
+				}
+				$formquestion = array(
+					array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
+				);
+			}
 
 			$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1);
-        }
+		}
 
-        // Confirmation edit (back to draft)
-        if ($action == 'edit')
-        {
-            $formquestion = array();
+		// Confirmation edit (back to draft)
+		if ($action == 'edit')
+		{
+			$formquestion = array();
 
-            $qualified_for_stock_change = 0;
-            if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
-            {
-                $qualified_for_stock_change = $object->hasProductsOrServices(2);
-            } else {
-                $qualified_for_stock_change = $object->hasProductsOrServices(1);
-            }
-            if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
-            {
-                $langs->load("stocks");
-                require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
-                $formproduct = new FormProduct($db);
-                $warehouse = new Entrepot($db);
-                $warehouse_array = $warehouse->list_array();
-                if (count($warehouse_array) == 1) {
-                    $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
-                    $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
-                } else {
-                    $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
-                    $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
-                }
-                $formquestion = array(
-                    array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
-                );
-            }
-            $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1);
+			$qualified_for_stock_change = 0;
+			if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
+			{
+				$qualified_for_stock_change = $object->hasProductsOrServices(2);
+			} else {
+				$qualified_for_stock_change = $object->hasProductsOrServices(1);
+			}
+			if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
+			{
+				$langs->load("stocks");
+				require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
+				$formproduct = new FormProduct($db);
+				$warehouse = new Entrepot($db);
+				$warehouse_array = $warehouse->list_array();
+				if (count($warehouse_array) == 1) {
+					$label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
+					$value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
+				} else {
+					$label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
+					$value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
+				}
+				$formquestion = array(
+					array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
+				);
+			}
+			$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1);
 		}
 
 		// Confirmation set paid
@@ -2369,109 +2369,109 @@ if ($action == 'create')
 		print $formconfirm;
 
 
-        // Supplier invoice card
-        $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
-
-    	$morehtmlref = '<div class="refidno">';
-    	// Ref supplier
-    	$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1);
-    	$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1);
-    	// Thirdparty
-    	$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
-    	if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
-    	// Project
-    	if (!empty($conf->projet->enabled))
-    	{
-    	    $langs->load("projects");
-    	    $morehtmlref .= '<br>'.$langs->trans('Project').' ';
-    	    if ($usercancreate)
-    	    {
-                if ($action != 'classify') {
-                    $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((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
-                    $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
-                    $morehtmlref .= '</form>';
-                } else {
-                    $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
-                }
-    	    } else {
-    	        if (!empty($object->fk_project)) {
-    	            $proj = new Project($db);
-    	            $proj->fetch($object->fk_project);
-    	            $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
-    	            $morehtmlref .= $proj->ref;
-    	            $morehtmlref .= '</a>';
-    	        } else {
-    	            $morehtmlref .= '';
-    	        }
-    	    }
-    	}
-    	$morehtmlref .= '</div>';
-
-    	$object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
-
-    	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
-
-    	print '<div class="fichecenter">';
-    	print '<div class="fichehalfleft">';
-    	print '<div class="underbanner clearboth"></div>';
-
-    	print '<table class="border tableforfield" width="100%">';
-
-        // Type
-        print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>';
-        print $object->getLibType();
-        if ($object->type == FactureFournisseur::TYPE_REPLACEMENT)
-        {
-            $facreplaced = new FactureFournisseur($db);
-            $facreplaced->fetch($object->fk_facture_source);
-            print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')';
-        }
-        if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE)
-        {
-            $facusing = new FactureFournisseur($db);
-            $facusing->fetch($object->fk_facture_source);
-            print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')';
-        }
-
-        $facidavoir = $object->getListIdAvoirFromInvoice();
-        if (count($facidavoir) > 0)
-        {
-            print ' ('.$langs->transnoentities("InvoiceHasAvoir");
-            $i = 0;
-            foreach ($facidavoir as $id)
-            {
-                if ($i == 0) print ' ';
-                else print ',';
-                $facavoir = new FactureFournisseur($db);
-                $facavoir->fetch($id);
-                print $facavoir->getNomUrl(1);
-            }
-            print ')';
-        }
-        if (isset($facidnext) && $facidnext > 0)
-        {
-            $facthatreplace = new FactureFournisseur($db);
-            $facthatreplace->fetch($facidnext);
-            print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')';
-        }
-        if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) {
-            $discount = new DiscountAbsolute($db);
-            $result = $discount->fetch(0, 0, $object->id);
-            if ($result > 0) {
-                print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).'<br>';
-            }
-        }
-        print '</td></tr>';
-
-
-        // Relative and absolute discounts
+		// Supplier invoice card
+		$linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+		$morehtmlref = '<div class="refidno">';
+		// Ref supplier
+		$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1);
+		$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1);
+		// Thirdparty
+		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
+		if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
+		// Project
+		if (!empty($conf->projet->enabled))
+		{
+			$langs->load("projects");
+			$morehtmlref .= '<br>'.$langs->trans('Project').' ';
+			if ($usercancreate)
+			{
+				if ($action != 'classify') {
+					$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((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+					$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+					$morehtmlref .= '</form>';
+				} else {
+					$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+				}
+			} else {
+				if (!empty($object->fk_project)) {
+					$proj = new Project($db);
+					$proj->fetch($object->fk_project);
+					$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
+					$morehtmlref .= $proj->ref;
+					$morehtmlref .= '</a>';
+				} else {
+					$morehtmlref .= '';
+				}
+			}
+		}
+		$morehtmlref .= '</div>';
+
+		$object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
+
+		dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+		print '<div class="fichecenter">';
+		print '<div class="fichehalfleft">';
+		print '<div class="underbanner clearboth"></div>';
+
+		print '<table class="border tableforfield" width="100%">';
+
+		// Type
+		print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>';
+		print $object->getLibType();
+		if ($object->type == FactureFournisseur::TYPE_REPLACEMENT)
+		{
+			$facreplaced = new FactureFournisseur($db);
+			$facreplaced->fetch($object->fk_facture_source);
+			print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')';
+		}
+		if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE)
+		{
+			$facusing = new FactureFournisseur($db);
+			$facusing->fetch($object->fk_facture_source);
+			print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')';
+		}
+
+		$facidavoir = $object->getListIdAvoirFromInvoice();
+		if (count($facidavoir) > 0)
+		{
+			print ' ('.$langs->transnoentities("InvoiceHasAvoir");
+			$i = 0;
+			foreach ($facidavoir as $id)
+			{
+				if ($i == 0) print ' ';
+				else print ',';
+				$facavoir = new FactureFournisseur($db);
+				$facavoir->fetch($id);
+				print $facavoir->getNomUrl(1);
+			}
+			print ')';
+		}
+		if (isset($facidnext) && $facidnext > 0)
+		{
+			$facthatreplace = new FactureFournisseur($db);
+			$facthatreplace->fetch($facidnext);
+			print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')';
+		}
+		if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) {
+			$discount = new DiscountAbsolute($db);
+			$result = $discount->fetch(0, 0, $object->id);
+			if ($result > 0) {
+				print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).'<br>';
+			}
+		}
+		print '</td></tr>';
+
+
+		// Relative and absolute discounts
 		print '<!-- Discounts --><tr><td>'.$langs->trans('Discounts');
 		print '</td><td>';
 
@@ -2482,18 +2482,18 @@ if ($action == 'create')
 
 		print '</td></tr>';
 
-        // Label
-        print '<tr>';
-        print '<td>'.$form->editfieldkey("Label", 'label', $object->label, $object, ($usercancreate)).'</td>';
-        print '<td>'.$form->editfieldval("Label", 'label', $object->label, $object, ($usercancreate)).'</td>';
-        print '</tr>';
+		// Label
+		print '<tr>';
+		print '<td>'.$form->editfieldkey("Label", 'label', $object->label, $object, ($usercancreate)).'</td>';
+		print '<td>'.$form->editfieldval("Label", 'label', $object->label, $object, ($usercancreate)).'</td>';
+		print '</tr>';
 
-	    $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0);
+		$form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0);
 
-        // Date
-        print '<tr><td>'.$form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker').'</td><td colspan="3">';
-        print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker');
-        print '</td>';
+		// Date
+		print '<tr><td>'.$form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker').'</td><td colspan="3">';
+		print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker');
+		print '</td>';
 
 		// Default terms of the settlement
 		$langs->load('bills');
@@ -3033,7 +3033,7 @@ if ($action == 'create')
 																									  // modified by hook
 			if (empty($reshook))
 			{
-			    // Modify a validated invoice with no payments
+				// Modify a validated invoice with no payments
 				if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate)
 				{
 					// We check if lines of invoice are not already transfered into accountancy
@@ -3078,17 +3078,17 @@ if ($action == 'create')
 					}
 				}
 
-	            // Make payments
-	            if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0)
-	            {
-	                print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create'.($object->fk_account > 0 ? '&amp;accountid='.$object->fk_account : '').'">'.$langs->trans('DoPayment').'</a></div>'; // must use facid because id is for payment id not invoice
-	            }
+				// Make payments
+				if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0)
+				{
+					print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create'.($object->fk_account > 0 ? '&amp;accountid='.$object->fk_account : '').'">'.$langs->trans('DoPayment').'</a></div>'; // must use facid because id is for payment id not invoice
+				}
 
-	            // Classify paid
-	            if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0)
-	            {
-	                print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid"';
-	                print '>'.$langs->trans('ClassifyPaid').'</a></div>';
+				// Classify paid
+				if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0)
+				{
+					print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid"';
+					print '>'.$langs->trans('ClassifyPaid').'</a></div>';
 
 					//print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a>';
 				}
@@ -3124,21 +3124,21 @@ if ($action == 'create')
 					}
 				}
 
-	            // Validate
-	            if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT)
-	            {
-	                if (count($object->lines))
-	                {
+				// Validate
+				if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT)
+				{
+					if (count($object->lines))
+					{
 						if ($usercanvalidate)
-	                    {
-	                        print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid"';
-	                        print '>'.$langs->trans('Validate').'</a></div>';
-	                    } else {
-	                        print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'"';
-	                        print '>'.$langs->trans('Validate').'</a></div>';
-	                    }
-	                }
-	            }
+						{
+							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid"';
+							print '>'.$langs->trans('Validate').'</a></div>';
+						} else {
+							print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'"';
+							print '>'.$langs->trans('Validate').'</a></div>';
+						}
+					}
+				}
 
 				// Create event
 				/*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) 	// Add hidden condition because this is not a "workflow" action so should appears somewhere else on page.
@@ -3161,30 +3161,30 @@ if ($action == 'create')
 					}
 				}
 
-	            // Delete
+				// Delete
 				$isErasable = $object->is_erasable();
 				if ($action != 'confirm_edit' && ($user->rights->fournisseur->facture->supprimer || ($usercancreate && $isErasable == 1)))	// isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions)
-	            {
-	            	//var_dump($isErasable);
-	            	if ($isErasable == -4) {
-	            		print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a></div>';
-	            	} elseif ($isErasable == -3) {	// Should never happen with supplier invoice
-	            		print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastSituationInvoice").'">'.$langs->trans('Delete').'</a></div>';
-	            	} elseif ($isErasable == -2) {	// Should never happen with supplier invoice
-	            		print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInvoice").'">'.$langs->trans('Delete').'</a></div>';
-	            	} elseif ($isErasable == -1) {
-	            		print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Delete').'</a></div>';
-	            	} elseif ($isErasable <= 0)	// Any other cases
-	            	{
-	            		print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a></div>';
-	            	} else {
-    	                print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>';
-                    }
-	            }
-	            print '</div>';
-
-	            if ($action != 'confirm_edit')
-	            {
+				{
+					//var_dump($isErasable);
+					if ($isErasable == -4) {
+						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a></div>';
+					} elseif ($isErasable == -3) {	// Should never happen with supplier invoice
+						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastSituationInvoice").'">'.$langs->trans('Delete').'</a></div>';
+					} elseif ($isErasable == -2) {	// Should never happen with supplier invoice
+						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInvoice").'">'.$langs->trans('Delete').'</a></div>';
+					} elseif ($isErasable == -1) {
+						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Delete').'</a></div>';
+					} elseif ($isErasable <= 0)	// Any other cases
+					{
+						print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a></div>';
+					} else {
+						print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>';
+					}
+				}
+				print '</div>';
+
+				if ($action != 'confirm_edit')
+				{
 					print '<div class="fichecenter"><div class="fichehalfleft">';
 
 					/*

+ 51 - 51
htdocs/fourn/facture/document.php

@@ -94,56 +94,56 @@ if ($object->id > 0)
 
 	$totalpaye = $object->getSommePaiement();
 
-    $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
-
-    $morehtmlref = '<div class="refidno">';
-    // Ref supplier
-    $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
-    $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1);
-    // Thirdparty
-    $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
-    if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
-    // Project
-    if (!empty($conf->projet->enabled))
-    {
-    	$langs->load("projects");
-    	$morehtmlref .= '<br>'.$langs->trans('Project').' ';
-    	if ($user->rights->facture->creer)
-    	{
-    		if ($action != 'classify')
-    			//$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
-    			$morehtmlref .= ' : ';
-    		if ($action == 'classify') {
-    			//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
-    			$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
-    			$morehtmlref .= '<input type="hidden" name="action" value="classin">';
-    			$morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
-    			$morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
-    			$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
-    			$morehtmlref .= '</form>';
-    		} else {
-    			$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
-    		}
-    	} else {
-    		if (!empty($object->fk_project)) {
-    			$proj = new Project($db);
-    			$proj->fetch($object->fk_project);
-    			$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
-    			$morehtmlref .= $proj->ref;
-    			$morehtmlref .= '</a>';
-    		} else {
-    			$morehtmlref .= '';
-    		}
-    	}
-    }
-    $morehtmlref .= '</div>';
-
-    $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
-
-    dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0);
-
-    print '<div class="fichecenter">';
-    print '<div class="underbanner clearboth"></div>';
+	$linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+
+	$morehtmlref = '<div class="refidno">';
+	// Ref supplier
+	$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
+	$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1);
+	// Thirdparty
+	$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
+	if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
+	// Project
+	if (!empty($conf->projet->enabled))
+	{
+		$langs->load("projects");
+		$morehtmlref .= '<br>'.$langs->trans('Project').' ';
+		if ($user->rights->facture->creer)
+		{
+			if ($action != 'classify')
+				//$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
+				$morehtmlref .= ' : ';
+			if ($action == 'classify') {
+				//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+				$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+				$morehtmlref .= '<input type="hidden" name="action" value="classin">';
+				$morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
+				$morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
+				$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
+				$morehtmlref .= '</form>';
+			} else {
+				$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+			}
+		} else {
+			if (!empty($object->fk_project)) {
+				$proj = new Project($db);
+				$proj->fetch($object->fk_project);
+				$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
+				$morehtmlref .= $proj->ref;
+				$morehtmlref .= '</a>';
+			} else {
+				$morehtmlref .= '';
+			}
+		}
+	}
+	$morehtmlref .= '</div>';
+
+	$object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
+
+	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0);
+
+	print '<div class="fichecenter">';
+	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);
@@ -271,7 +271,7 @@ if ($object->id > 0)
 		if ($res) break;
 	}
 } else {
-    print $langs->trans('ErrorUnknown');
+	print $langs->trans('ErrorUnknown');
 }
 
 // End of page

+ 131 - 131
htdocs/hrm/index.php

@@ -96,42 +96,42 @@ print '<div class="fichecenter"><div class="fichethirdleft">';
 
 if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS))     // This is useless due to the global search combo
 {
-    if (!empty($conf->holiday->enabled) && $user->rights->holiday->read)
-    {
-    	$langs->load("holiday");
-        $listofsearchfields['search_holiday'] = array('text'=>'TitreRequestCP');
-    }
-    if (!empty($conf->deplacement->enabled) && $user->rights->deplacement->lire)
-    {
-    	$langs->load("trips");
-        $listofsearchfields['search_deplacement'] = array('text'=>'ExpenseReport');
-    }
-    if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire)
-    {
-    	$langs->load("trips");
-        $listofsearchfields['search_expensereport'] = array('text'=>'ExpenseReport');
-    }
-    if (count($listofsearchfields))
-    {
-    	print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">';
-    	print '<input type="hidden" name="token" value="'.newToken().'">';
-        print '<div class="div-table-responsive-no-min">';
-    	print '<table class="noborder nohover centpercent">';
-    	$i = 0;
-    	foreach ($listofsearchfields as $key => $value)
-    	{
-    		if ($i == 0) print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>';
-    		print '<tr '.$bc[false].'>';
-    		print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>';
-    		if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>';
-    		print '</tr>';
-    		$i++;
-    	}
-    	print '</table>';
-        print '</div>';
-    	print '</form>';
-    	print '<br>';
-    }
+	if (!empty($conf->holiday->enabled) && $user->rights->holiday->read)
+	{
+		$langs->load("holiday");
+		$listofsearchfields['search_holiday'] = array('text'=>'TitreRequestCP');
+	}
+	if (!empty($conf->deplacement->enabled) && $user->rights->deplacement->lire)
+	{
+		$langs->load("trips");
+		$listofsearchfields['search_deplacement'] = array('text'=>'ExpenseReport');
+	}
+	if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire)
+	{
+		$langs->load("trips");
+		$listofsearchfields['search_expensereport'] = array('text'=>'ExpenseReport');
+	}
+	if (count($listofsearchfields))
+	{
+		print '<form method="post" action="'.DOL_URL_ROOT.'/core/search.php">';
+		print '<input type="hidden" name="token" value="'.newToken().'">';
+		print '<div class="div-table-responsive-no-min">';
+		print '<table class="noborder nohover centpercent">';
+		$i = 0;
+		foreach ($listofsearchfields as $key => $value)
+		{
+			if ($i == 0) print '<tr class="liste_titre"><td colspan="3">'.$langs->trans("Search").'</td></tr>';
+			print '<tr '.$bc[false].'>';
+			print '<td class="nowrap"><label for="'.$key.'">'.$langs->trans($value["text"]).'</label></td><td><input type="text" class="flat inputsearch" name="'.$key.'" id="'.$key.'" size="18"></td>';
+			if ($i == 0) print '<td rowspan="'.count($listofsearchfields).'"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td>';
+			print '</tr>';
+			$i++;
+		}
+		print '</table>';
+		print '</div>';
+		print '</form>';
+		print '<br>';
+	}
 }
 
 
@@ -141,26 +141,26 @@ if (!empty($conf->holiday->enabled))
 	{
 		$user_id = $user->id;
 
-        print '<div class="div-table-responsive-no-min">';
-	    print '<table class="noborder nohover centpercent">';
-	    print '<tr class="liste_titre"><th colspan="3">'.$langs->trans("Holidays").'</th></tr>';
-	    print '<tr class="oddeven">';
-	    print '<td colspan="3">';
-
-	    $out = '';
-	    $typeleaves = $holiday->getTypes(1, 1);
-	    foreach ($typeleaves as $key => $val)
-	    {
-	    	$nb_type = $holiday->getCPforUser($user->id, $val['rowid']);
-	    	$nb_holiday += $nb_type;
-	    	$out .= ' - '.$val['label'].': <strong>'.($nb_type ?price2num($nb_type) : 0).'</strong><br>';
-	    }
-	    print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'<br>';
-	    print $out;
-
-	    print '</td>';
-	    print '</tr>';
-	    print '</table></div><br>';
+		print '<div class="div-table-responsive-no-min">';
+		print '<table class="noborder nohover centpercent">';
+		print '<tr class="liste_titre"><th colspan="3">'.$langs->trans("Holidays").'</th></tr>';
+		print '<tr class="oddeven">';
+		print '<td colspan="3">';
+
+		$out = '';
+		$typeleaves = $holiday->getTypes(1, 1);
+		foreach ($typeleaves as $key => $val)
+		{
+			$nb_type = $holiday->getCPforUser($user->id, $val['rowid']);
+			$nb_holiday += $nb_type;
+			$out .= ' - '.$val['label'].': <strong>'.($nb_type ?price2num($nb_type) : 0).'</strong><br>';
+		}
+		print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'<br>';
+		print $out;
+
+		print '</td>';
+		print '</tr>';
+		print '</table></div><br>';
 	} elseif (!is_numeric($conf->global->HOLIDAY_HIDE_BALANCE))
 	{
 		print $langs->trans($conf->global->HOLIDAY_HIDE_BALANCE).'<br>';
@@ -175,80 +175,80 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
 // Latest leave requests
 if (!empty($conf->holiday->enabled) && $user->rights->holiday->read)
 {
-    $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.photo, u.statut as user_status,";
-    $sql .= " x.rowid, x.rowid as ref, x.fk_type, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.tms as dm, 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 x.entity = ".$conf->entity;
-    if (empty($user->rights->holiday->read_all)) $sql .= ' AND x.fk_user IN ('.join(',', $childids).')';
-    //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND x.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
-    //if (!empty($socid)) $sql.= " AND x.fk_soc = ".$socid;
-    $sql .= $db->order("x.tms", "DESC");
-    $sql .= $db->plimit($max, 0);
-
-    $result = $db->query($sql);
-    if ($result)
-    {
-        $var = false;
-        $num = $db->num_rows($result);
-
-        $holidaystatic = new Holiday($db);
-        $userstatic = new User($db);
-
-        $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->trans("Afternoon"));
-        $typeleaves = $holidaystatic->getTypes(1, -1);
-
-        $i = 0;
-
-        print '<div class="div-table-responsive-no-min">';
-        print '<table class="noborder centpercent">';
-        print '<tr class="liste_titre">';
-        print '<th colspan="3">'.$langs->trans("BoxTitleLastLeaveRequests", min($max, $num)).'</th>';
-        print '<th>'.$langs->trans("from").'</th>';
-        print '<th>'.$langs->trans("to").'</th>';
-        print '<th class="right" colspan="2"><a href="'.DOL_URL_ROOT.'/holiday/list.php?sortfield=cp.tms&sortorder=DESC">'.$langs->trans("FullList").'</th>';
-        print '</tr>';
-        if ($num)
-        {
-            while ($i < $num && $i < $max)
-            {
-                $obj = $db->fetch_object($result);
-
-                $holidaystatic->id = $obj->rowid;
-                $holidaystatic->ref = $obj->ref;
-                $holidaystatic->statut = $obj->status;
-
-                $userstatic->id = $obj->uid;
-                $userstatic->lastname = $obj->lastname;
-                $userstatic->firstname = $obj->firstname;
-                $userstatic->login = $obj->login;
-                $userstatic->photo = $obj->photo;
-                $userstatic->email = $obj->email;
-                $userstatic->statut = $obj->user_status;
-
-                print '<tr class="oddeven">';
-                print '<td class="nowraponall">'.$holidaystatic->getNomUrl(1).'</td>';
-                print '<td class="tdoverflowmax150">'.$userstatic->getNomUrl(-1, 'leave').'</td>';
-                print '<td>'.$typeleaves[$obj->fk_type]['label'].'</td>';
-
-                $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning';
-                $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon';
-
-                print '<td>'.dol_print_date($db->jdate($obj->date_start), 'day').' <span class="opacitymedium">'.$langs->trans($listhalfday[$starthalfday]).'</span>';
-                print '<td>'.dol_print_date($db->jdate($obj->date_end), 'day').' <span class="opacitymedium">'.$langs->trans($listhalfday[$endhalfday]).'</span>';
-                print '<td class="right">'.dol_print_date($db->jdate($obj->dm), 'day').'</td>';
-                print '<td class="right nowrap" width="16">'.$holidaystatic->LibStatut($obj->status, 3).'</td>';
-                print '</tr>';
-
-                $i++;
-            }
-        } else {
-            print '<tr class="oddeven"><td colspan="7" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
-        }
-        print '</table>';
-        print '</div>';
-        print '<br>';
-    } else dol_print_error($db);
+	$sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.photo, u.statut as user_status,";
+	$sql .= " x.rowid, x.rowid as ref, x.fk_type, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.tms as dm, 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 x.entity = ".$conf->entity;
+	if (empty($user->rights->holiday->read_all)) $sql .= ' AND x.fk_user IN ('.join(',', $childids).')';
+	//if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND x.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
+	//if (!empty($socid)) $sql.= " AND x.fk_soc = ".$socid;
+	$sql .= $db->order("x.tms", "DESC");
+	$sql .= $db->plimit($max, 0);
+
+	$result = $db->query($sql);
+	if ($result)
+	{
+		$var = false;
+		$num = $db->num_rows($result);
+
+		$holidaystatic = new Holiday($db);
+		$userstatic = new User($db);
+
+		$listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->trans("Afternoon"));
+		$typeleaves = $holidaystatic->getTypes(1, -1);
+
+		$i = 0;
+
+		print '<div class="div-table-responsive-no-min">';
+		print '<table class="noborder centpercent">';
+		print '<tr class="liste_titre">';
+		print '<th colspan="3">'.$langs->trans("BoxTitleLastLeaveRequests", min($max, $num)).'</th>';
+		print '<th>'.$langs->trans("from").'</th>';
+		print '<th>'.$langs->trans("to").'</th>';
+		print '<th class="right" colspan="2"><a href="'.DOL_URL_ROOT.'/holiday/list.php?sortfield=cp.tms&sortorder=DESC">'.$langs->trans("FullList").'</th>';
+		print '</tr>';
+		if ($num)
+		{
+			while ($i < $num && $i < $max)
+			{
+				$obj = $db->fetch_object($result);
+
+				$holidaystatic->id = $obj->rowid;
+				$holidaystatic->ref = $obj->ref;
+				$holidaystatic->statut = $obj->status;
+
+				$userstatic->id = $obj->uid;
+				$userstatic->lastname = $obj->lastname;
+				$userstatic->firstname = $obj->firstname;
+				$userstatic->login = $obj->login;
+				$userstatic->photo = $obj->photo;
+				$userstatic->email = $obj->email;
+				$userstatic->statut = $obj->user_status;
+
+				print '<tr class="oddeven">';
+				print '<td class="nowraponall">'.$holidaystatic->getNomUrl(1).'</td>';
+				print '<td class="tdoverflowmax150">'.$userstatic->getNomUrl(-1, 'leave').'</td>';
+				print '<td>'.$typeleaves[$obj->fk_type]['label'].'</td>';
+
+				$starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning';
+				$endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon';
+
+				print '<td>'.dol_print_date($db->jdate($obj->date_start), 'day').' <span class="opacitymedium">'.$langs->trans($listhalfday[$starthalfday]).'</span>';
+				print '<td>'.dol_print_date($db->jdate($obj->date_end), 'day').' <span class="opacitymedium">'.$langs->trans($listhalfday[$endhalfday]).'</span>';
+				print '<td class="right">'.dol_print_date($db->jdate($obj->dm), 'day').'</td>';
+				print '<td class="right nowrap" width="16">'.$holidaystatic->LibStatut($obj->status, 3).'</td>';
+				print '</tr>';
+
+				$i++;
+			}
+		} else {
+			print '<tr class="oddeven"><td colspan="7" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
+		}
+		print '</table>';
+		print '</div>';
+		print '<br>';
+	} else dol_print_error($db);
 }
 
 
@@ -298,7 +298,7 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire)
 				$userstatic->id = $obj->uid;
 				$userstatic->lastname = $obj->lastname;
 				$userstatic->firstname = $obj->firstname;
-                $userstatic->email = $obj->email;
+				$userstatic->email = $obj->email;
 				$userstatic->login = $obj->login;
 				$userstatic->statut = $obj->user_status;
 				$userstatic->photo = $obj->photo;

File diff suppressed because it is too large
+ 550 - 550
htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php


+ 263 - 263
htdocs/mrp/mo_card.php

@@ -107,75 +107,75 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
 
 if (empty($reshook))
 {
-    $error = 0;
-
-    $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1);
-
-    if (empty($backtopage) || ($cancel && empty($id))) {
-    	if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
-	    	if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist;
-    		else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__');
-    	}
-    }
-    if ($cancel && !empty($backtopageforcancel)) {
-    	$backtopage = $backtopageforcancel;
-    }
-
-    $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record
-
-    // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen
-    include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
-
-    // Actions when linking object each other
-    include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
-
-    // Actions when printing a doc from card
-    include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
-
-    // Actions to send emails
-    $triggersendname = 'MO_SENTBYMAIL';
-    $autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO';
-    $trackid = 'mo'.$object->id;
-    include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
-
-    // Action to move up and down lines of object
-    //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php';	// Must be include, not include_once
-
-    if ($action == 'set_thirdparty' && $permissiontoadd)
-    {
-    	$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY');
-    }
-    if ($action == 'classin' && $permissiontoadd)
-    {
-    	$object->setProject(GETPOST('projectid', 'int'));
-    }
-
-    // Action close produced
-    if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd)
-    {
-    	$result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
-    	if ($result >= 0)
-    	{
-    		// Define output language
-    		if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
-    		{
-    			$outputlangs = $langs;
-    			$newlang = '';
-    			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
-    			if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
-    			if (!empty($newlang)) {
-    				$outputlangs = new Translate("", $conf);
-    				$outputlangs->setDefaultLang($newlang);
-    			}
-    			$model = $object->model_pdf;
-    			$ret = $object->fetch($id); // Reload to get new records
-
-    			$object->generateDocument($model, $outputlangs, 0, 0, 0);
-    		}
-    	} else {
-    		setEventMessages($object->error, $object->errors, 'errors');
-    	}
-    }
+	$error = 0;
+
+	$backurlforlist = dol_buildpath('/mrp/mo_list.php', 1);
+
+	if (empty($backtopage) || ($cancel && empty($id))) {
+		if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
+			if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist;
+			else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__');
+		}
+	}
+	if ($cancel && !empty($backtopageforcancel)) {
+		$backtopage = $backtopageforcancel;
+	}
+
+	$triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record
+
+	// Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen
+	include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
+
+	// Actions when linking object each other
+	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
+
+	// Actions when printing a doc from card
+	include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
+
+	// Actions to send emails
+	$triggersendname = 'MO_SENTBYMAIL';
+	$autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO';
+	$trackid = 'mo'.$object->id;
+	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
+
+	// Action to move up and down lines of object
+	//include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php';	// Must be include, not include_once
+
+	if ($action == 'set_thirdparty' && $permissiontoadd)
+	{
+		$object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY');
+	}
+	if ($action == 'classin' && $permissiontoadd)
+	{
+		$object->setProject(GETPOST('projectid', 'int'));
+	}
+
+	// Action close produced
+	if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd)
+	{
+		$result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED');
+		if ($result >= 0)
+		{
+			// Define output language
+			if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+			{
+				$outputlangs = $langs;
+				$newlang = '';
+				if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+				if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
+				if (!empty($newlang)) {
+					$outputlangs = new Translate("", $conf);
+					$outputlangs->setDefaultLang($newlang);
+				}
+				$model = $object->model_pdf;
+				$ret = $object->fetch($id); // Reload to get new records
+
+				$object->generateDocument($model, $outputlangs, 0, 0, 0);
+			}
+		} else {
+			setEventMessages($object->error, $object->errors, 'errors');
+		}
+	}
 }
 
 
@@ -317,7 +317,7 @@ if (($id || $ref) && $action == 'edit')
 	print load_fiche_titre($langs->trans("MO"), '', 'mrp');
 
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="update">';
 	print '<input type="hidden" name="id" value="'.$object->id.'">';
 	if ($backtopage) print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
@@ -360,7 +360,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	// Confirmation to delete
 	if ($action == 'delete')
 	{
-	    $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1);
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1);
 	}
 	// Confirmation to delete line
 	if ($action == 'deleteline')
@@ -439,32 +439,32 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	// Project
 	if (!empty($conf->projet->enabled))
 	{
-	    $langs->load("projects");
-	    $morehtmlref .= '<br>'.$langs->trans('Project').' ';
-	    if ($permissiontoadd)
-	    {
-	        if ($action != 'classify')
-	            $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
-            if ($action == 'classify') {
-                //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1);
-                $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
-                $morehtmlref .= '<input type="hidden" name="action" value="classin">';
-                $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
-                $morehtmlref .= $formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 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->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1);
-	        }
-	    } else {
-	        if (!empty($object->fk_project)) {
-	            $proj = new Project($db);
-	            $proj->fetch($object->fk_project);
-	            $morehtmlref .= ' : '.$proj->getNomUrl();
-	        } else {
-	            $morehtmlref .= '';
-	        }
-	    }
+		$langs->load("projects");
+		$morehtmlref .= '<br>'.$langs->trans('Project').' ';
+		if ($permissiontoadd)
+		{
+			if ($action != 'classify')
+				$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
+			if ($action == 'classify') {
+				//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1);
+				$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
+				$morehtmlref .= '<input type="hidden" name="action" value="classin">';
+				$morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
+				$morehtmlref .= $formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 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->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1);
+			}
+		} else {
+			if (!empty($object->fk_project)) {
+				$proj = new Project($db);
+				$proj->fetch($object->fk_project);
+				$morehtmlref .= ' : '.$proj->getNomUrl();
+			} else {
+				$morehtmlref .= '';
+			}
+		}
 	}
 	$morehtmlref .= '</div>';
 
@@ -501,167 +501,167 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 
 	if (!empty($object->table_element_line))
 	{
-    	// Show object lines
+		// Show object lines
 		//$result = $object->getLinesArray();
 		$object->fetchLines();
 
-    	print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#addline' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">
+		print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#addline' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">
     	<input type="hidden" name="token" value="' . newToken().'">
     	<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
     	<input type="hidden" name="mode" value="">
     	<input type="hidden" name="id" value="' . $object->id.'">
     	';
 
-    	/*if (!empty($conf->use_javascript_ajax) && $object->status == 0) {
+		/*if (!empty($conf->use_javascript_ajax) && $object->status == 0) {
     	    include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
     	}*/
 
-    	if (!empty($object->lines))
-    	{
-    		print '<div class="div-table-responsive-no-min">';
-    		print '<table id="tablelines" class="noborder noshadow" width="100%">';
-
-    		print '<tr class="liste_titre">';
-    		print '<td class="liste_titre">'.$langs->trans("Summary").'</td>';
-    		print '<td></td>';
-    		print '</tr>';
-
-    		print '<tr class="oddeven">';
-    		print '<td>'.$langs->trans("ProductsToConsume").'</td>';
-    		print '<td>';
-    		if (!empty($object->lines))
-    		{
-    			$i = 0;
-    			foreach ($object->lines as $line) {
-    				if ($line->role == 'toconsume') {
-    					if ($i) print ', ';
-    					$tmpproduct = new Product($db);
-    					$tmpproduct->fetch($line->fk_product);
-    					print $tmpproduct->getNomUrl(1);
-    					$i++;
-    				}
-    			}
-    		}
-    		print '</td>';
-    		print '</tr>';
-
-    		print '<tr class="oddeven">';
-    		print '<td>'.$langs->trans("ProductsToProduce").'</td>';
-    		print '<td>';
-    		if (!empty($object->lines))
-    		{
-    			$i = 0;
-    			foreach ($object->lines as $line) {
-    				if ($line->role == 'toproduce') {
-    					if ($i) print ', ';
-    					$tmpproduct = new Product($db);
-    					$tmpproduct->fetch($line->fk_product);
-    					print $tmpproduct->getNomUrl(1);
-    					$i++;
-    				}
-    			}
-    		}
-    		print '</td>';
-    		print '</tr>';
-
-    	    print '</table>';
-    	    print '</div>';
-    	}
-
-    	print "</form>\n";
+		if (!empty($object->lines))
+		{
+			print '<div class="div-table-responsive-no-min">';
+			print '<table id="tablelines" class="noborder noshadow" width="100%">';
+
+			print '<tr class="liste_titre">';
+			print '<td class="liste_titre">'.$langs->trans("Summary").'</td>';
+			print '<td></td>';
+			print '</tr>';
+
+			print '<tr class="oddeven">';
+			print '<td>'.$langs->trans("ProductsToConsume").'</td>';
+			print '<td>';
+			if (!empty($object->lines))
+			{
+				$i = 0;
+				foreach ($object->lines as $line) {
+					if ($line->role == 'toconsume') {
+						if ($i) print ', ';
+						$tmpproduct = new Product($db);
+						$tmpproduct->fetch($line->fk_product);
+						print $tmpproduct->getNomUrl(1);
+						$i++;
+					}
+				}
+			}
+			print '</td>';
+			print '</tr>';
+
+			print '<tr class="oddeven">';
+			print '<td>'.$langs->trans("ProductsToProduce").'</td>';
+			print '<td>';
+			if (!empty($object->lines))
+			{
+				$i = 0;
+				foreach ($object->lines as $line) {
+					if ($line->role == 'toproduce') {
+						if ($i) print ', ';
+						$tmpproduct = new Product($db);
+						$tmpproduct->fetch($line->fk_product);
+						print $tmpproduct->getNomUrl(1);
+						$i++;
+					}
+				}
+			}
+			print '</td>';
+			print '</tr>';
+
+			print '</table>';
+			print '</div>';
+		}
+
+		print "</form>\n";
 	}
 
 
 	// Buttons for actions
 
 	if ($action != 'presend' && $action != 'editline') {
-    	print '<div class="tabsAction">'."\n";
-    	$parameters = array();
-    	$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-    	if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
-
-    	if (empty($reshook))
-    	{
-    	    // Send
-    		//if (empty($user->socid)) {
-    		//	print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a>'."\n";
-    		//}
-
-    		// Back to draft
-    		if ($object->status == $object::STATUS_VALIDATED)
-    		{
-	    		if ($permissiontoadd)
-	    		{
-	    			// TODO Add test that production has not started
-	    			print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>';
-	    		}
-    		}
-
-            // Modify
-    		if ($object->status == $object::STATUS_DRAFT) {
-	    		if ($permissiontoadd)
-	    		{
-	    			print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n";
-	    		} else {
-	    			print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n";
-	    		}
-    		}
-
-    		// Validate
-    		if ($object->status == $object::STATUS_DRAFT)
-    		{
-	    		if ($permissiontoadd)
-	    		{
-	    			if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0))
-	    		    {
-	    		        print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate">'.$langs->trans("Validate").'</a>';
-	    		    } else {
-	    		    	$langs->load("errors");
-	    		        print '<a class="butActionRefused" href="" title="'.$langs->trans("ErrorAddAtLeastOneLineFirst").'">'.$langs->trans("Validate").'</a>';
-	    		    }
-	    		}
-    		}
-
-    		// Clone
-    		if ($permissiontoadd)
-    		{
-    			print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->fk_soc.'&action=clone&object=mo">'.$langs->trans("ToClone").'</a>';
-    		}
-
-    		// Cancel - Reopen
-    		if ($permissiontoadd)
-    		{
-    			if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS)
-    			{
-    				$arrayproduced = $object->fetchLinesLinked('produced', 0);
-    				$nbProduced = 0;
-    				foreach ($arrayproduced as $lineproduced) {
-    					$nbProduced += $lineproduced['qty'];
-    				}
-    				if ($nbProduced > 0) {	// If production has started, we can close it
-    					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_produced&confirm=yes">'.$langs->trans("Close").'</a>'."\n";
-    				} else {
-    					print '<a class="butActionRefused" href="#" title="'.$langs->trans("GoOnTabProductionToProduceFirst", $langs->transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").'</a>'."\n";
-    				}
-
-    				print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").'</a>'."\n";
-    			}
-
-    			if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED)
-    			{
-    				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("ReOpen").'</a>'."\n";
-    			}
-    		}
-
-    		// Delete (need delete permission, or if draft, just need create/modify permission)
-    		if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd))
-    		{
-    			print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n";
-    		} else {
-    			print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";
-    		}
-    	}
-    	print '</div>'."\n";
+		print '<div class="tabsAction">'."\n";
+		$parameters = array();
+		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+		if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+
+		if (empty($reshook))
+		{
+			// Send
+			//if (empty($user->socid)) {
+			//	print '<a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=presend&mode=init#formmailbeforetitle">' . $langs->trans('SendMail') . '</a>'."\n";
+			//}
+
+			// Back to draft
+			if ($object->status == $object::STATUS_VALIDATED)
+			{
+				if ($permissiontoadd)
+				{
+					// TODO Add test that production has not started
+					print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes">'.$langs->trans("SetToDraft").'</a>';
+				}
+			}
+
+			// Modify
+			if ($object->status == $object::STATUS_DRAFT) {
+				if ($permissiontoadd)
+				{
+					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n";
+				} else {
+					print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n";
+				}
+			}
+
+			// Validate
+			if ($object->status == $object::STATUS_DRAFT)
+			{
+				if ($permissiontoadd)
+				{
+					if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0))
+					{
+						print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=validate">'.$langs->trans("Validate").'</a>';
+					} else {
+						$langs->load("errors");
+						print '<a class="butActionRefused" href="" title="'.$langs->trans("ErrorAddAtLeastOneLineFirst").'">'.$langs->trans("Validate").'</a>';
+					}
+				}
+			}
+
+			// Clone
+			if ($permissiontoadd)
+			{
+				print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->fk_soc.'&action=clone&object=mo">'.$langs->trans("ToClone").'</a>';
+			}
+
+			// Cancel - Reopen
+			if ($permissiontoadd)
+			{
+				if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS)
+				{
+					$arrayproduced = $object->fetchLinesLinked('produced', 0);
+					$nbProduced = 0;
+					foreach ($arrayproduced as $lineproduced) {
+						$nbProduced += $lineproduced['qty'];
+					}
+					if ($nbProduced > 0) {	// If production has started, we can close it
+						print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_produced&confirm=yes">'.$langs->trans("Close").'</a>'."\n";
+					} else {
+						print '<a class="butActionRefused" href="#" title="'.$langs->trans("GoOnTabProductionToProduceFirst", $langs->transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").'</a>'."\n";
+					}
+
+					print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").'</a>'."\n";
+				}
+
+				if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED)
+				{
+					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_reopen&confirm=yes">'.$langs->trans("ReOpen").'</a>'."\n";
+				}
+			}
+
+			// Delete (need delete permission, or if draft, just need create/modify permission)
+			if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd))
+			{
+				print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n";
+			} else {
+				print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";
+			}
+		}
+		print '</div>'."\n";
 	}
 
 
@@ -672,37 +672,37 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 
 	if ($action != 'presend')
 	{
-	    print '<div class="fichecenter"><div class="fichehalfleft">';
-	    print '<a name="builddoc"></a>'; // ancre
+		print '<div class="fichecenter"><div class="fichehalfleft">';
+		print '<a name="builddoc"></a>'; // ancre
 
-	    // Documents
-	    $objref = dol_sanitizeFileName($object->ref);
-	    $relativepath = $objref.'/'.$objref.'.pdf';
-	    $filedir = $conf->mrp->dir_output.'/'.$objref;
-	    $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
-	    $genallowed = $user->rights->mrp->read; // If you can read, you can build the PDF to read content
-	    $delallowed = $user->rights->mrp->create; // If you can create/edit, you can remove a file on card
-	    print $formfile->showdocuments('mrp:mo', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang);
+		// Documents
+		$objref = dol_sanitizeFileName($object->ref);
+		$relativepath = $objref.'/'.$objref.'.pdf';
+		$filedir = $conf->mrp->dir_output.'/'.$objref;
+		$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
+		$genallowed = $user->rights->mrp->read; // If you can read, you can build the PDF to read content
+		$delallowed = $user->rights->mrp->create; // If you can create/edit, you can remove a file on card
+		print $formfile->showdocuments('mrp:mo', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang);
 
-	    // Show links to link elements
-	    $linktoelem = $form->showLinkToObjectBlock($object, null, array('mo'));
-	    $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
+		// Show links to link elements
+		$linktoelem = $form->showLinkToObjectBlock($object, null, array('mo'));
+		$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
 
 
-	    print '</div><div class="fichehalfright"><div class="ficheaddleft">';
+		print '</div><div class="fichehalfright"><div class="ficheaddleft">';
 
-	    $MAXEVENT = 10;
+		$MAXEVENT = 10;
 
-	    $morehtmlright = '<a href="'.dol_buildpath('/mrp/mo_agenda.php', 1).'?id='.$object->id.'">';
-	    $morehtmlright .= $langs->trans("SeeAll");
-	    $morehtmlright .= '</a>';
+		$morehtmlright = '<a href="'.dol_buildpath('/mrp/mo_agenda.php', 1).'?id='.$object->id.'">';
+		$morehtmlright .= $langs->trans("SeeAll");
+		$morehtmlright .= '</a>';
 
-	    // List of actions on element
-	    include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
-	    $formactions = new FormActions($db);
-	    $somethingshown = $formactions->showactions($object, 'mo', $socid, 1, '', $MAXEVENT, '', $morehtmlright);
+		// List of actions on element
+		include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
+		$formactions = new FormActions($db);
+		$somethingshown = $formactions->showactions($object, 'mo', $socid, 1, '', $MAXEVENT, '', $morehtmlright);
 
-	    print '</div></div></div>';
+		print '</div></div></div>';
 	}
 
 	//Select mail models is same action as presend

+ 249 - 249
htdocs/product/admin/dynamic_prices.php

@@ -42,17 +42,17 @@ if (!$user->admin) accessforbidden();
 //Objects
 $price_globals = new PriceGlobalVariable($db);
 if ($action == 'edit_variable') {
-    $res = $price_globals->fetch($selection);
-    if ($res < 1) {
-        setEventMessages($price_globals->error, $price_globals->errors, 'errors');
-    }
+	$res = $price_globals->fetch($selection);
+	if ($res < 1) {
+		setEventMessages($price_globals->error, $price_globals->errors, 'errors');
+	}
 }
 $price_updaters = new PriceGlobalVariableUpdater($db);
 if ($action == 'edit_updater') {
-    $res = $price_updaters->fetch($selection);
-    if ($res < 1) {
-        setEventMessages($price_updaters->error, $price_updaters->errors, 'errors');
-    }
+	$res = $price_updaters->fetch($selection);
+	if ($res < 1) {
+		setEventMessages($price_updaters->error, $price_updaters->errors, 'errors');
+	}
 }
 
 
@@ -61,84 +61,84 @@ if ($action == 'edit_updater') {
  */
 
 if (!empty($action) && empty($cancel)) {
-    //Global variable actions
-    if ($action == 'create_variable' || $action == 'edit_variable') {
-        $price_globals->code = GETPOSTISSET('code') ?GETPOST('code', 'alpha') : $price_globals->code;
-        $price_globals->description = GETPOSTISSET('description') ?GETPOST('description', 'restricthtml') : $price_globals->description;
-        $price_globals->value = GETPOSTISSET('value') ?GETPOST('value', 'int') : $price_globals->value;
-        //Check if record already exists only when saving
-        if (!empty($save)) {
-            foreach ($price_globals->listGlobalVariables() as $entry) {
-                if ($price_globals->id != $entry->id && dol_strtolower($price_globals->code) == dol_strtolower($entry->code)) {
-                    setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors');
-                    $save = null;
-                }
-            }
-        }
-    }
-    if ($action == 'create_variable' && !empty($save)) {
-        $res = $price_globals->create($user);
-        if ($res > 0) {
-            $action = '';
-        } else {
-            setEventMessages($price_globals->error, $price_globals->errors, 'errors');
-        }
-    } elseif ($action == 'edit_variable' && !empty($save)) {
-        $res = $price_globals->update($user);
-        if ($res > 0) {
-            $action = '';
-        } else {
-            setEventMessages($price_globals->error, $price_globals->errors, 'errors');
-        }
-    } elseif ($action == 'delete_variable') {
-        $res = $price_globals->delete($selection, $user);
-        if ($res > 0) {
-            $action = '';
-        } else {
-            setEventMessages($price_globals->error, $price_globals->errors, 'errors');
-        }
-    }
+	//Global variable actions
+	if ($action == 'create_variable' || $action == 'edit_variable') {
+		$price_globals->code = GETPOSTISSET('code') ?GETPOST('code', 'alpha') : $price_globals->code;
+		$price_globals->description = GETPOSTISSET('description') ?GETPOST('description', 'restricthtml') : $price_globals->description;
+		$price_globals->value = GETPOSTISSET('value') ?GETPOST('value', 'int') : $price_globals->value;
+		//Check if record already exists only when saving
+		if (!empty($save)) {
+			foreach ($price_globals->listGlobalVariables() as $entry) {
+				if ($price_globals->id != $entry->id && dol_strtolower($price_globals->code) == dol_strtolower($entry->code)) {
+					setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors');
+					$save = null;
+				}
+			}
+		}
+	}
+	if ($action == 'create_variable' && !empty($save)) {
+		$res = $price_globals->create($user);
+		if ($res > 0) {
+			$action = '';
+		} else {
+			setEventMessages($price_globals->error, $price_globals->errors, 'errors');
+		}
+	} elseif ($action == 'edit_variable' && !empty($save)) {
+		$res = $price_globals->update($user);
+		if ($res > 0) {
+			$action = '';
+		} else {
+			setEventMessages($price_globals->error, $price_globals->errors, 'errors');
+		}
+	} elseif ($action == 'delete_variable') {
+		$res = $price_globals->delete($selection, $user);
+		if ($res > 0) {
+			$action = '';
+		} else {
+			setEventMessages($price_globals->error, $price_globals->errors, 'errors');
+		}
+	}
 
-    //Updaters actions
-    if ($action == 'create_updater' || $action == 'edit_updater') {
-        $price_updaters->type = GETPOSTISSET('type') ? GETPOST('type', 'int') : $price_updaters->type;
-        $price_updaters->description = GETPOSTISSET('description') ? GETPOST('description', 'restricthtml') : $price_updaters->description;
-        $price_updaters->parameters = GETPOSTISSET('parameters') ? GETPOST('parameters', 'alphanohtml') : $price_updaters->parameters;
-        $price_updaters->fk_variable = GETPOSTISSET('fk_variable') ? GETPOST('fk_variable', 'int') : $price_updaters->fk_variable;
-        $price_updaters->update_interval = GETPOSTISSET('update_interval') ? GETPOST('update_interval', 'int') : $price_updaters->update_interval;
-    }
-    if ($action == 'create_updater' && !empty($save)) {
-        //Verify if process() works
-        $res = $price_updaters->process();
-        if ($res > 0) {
-            $res = $price_updaters->create($user);
-        }
-        if ($res > 0) {
-            $action = '';
-        } else {
-            setEventMessages($price_updaters->error, $price_updaters->errors, 'errors');
-        }
-    } elseif ($action == 'edit_updater' && !empty($save)) {
-        //Verify if process() works
-        $res = $price_updaters->process();
-        if ($res > 0) {
-            $res = $price_updaters->update($user);
-        }
-        if ($res > 0) {
-            $action = '';
-        } else {
-            setEventMessages($price_updaters->error, $price_updaters->errors, 'errors');
-        }
-    } elseif ($action == 'delete_updater') {
-        $res = $price_updaters->delete($selection, $user);
-        if ($res > 0) {
-            $action = '';
-        } else {
-            setEventMessages($price_updaters->error, $price_updaters->errors, 'errors');
-        }
-    }
+	//Updaters actions
+	if ($action == 'create_updater' || $action == 'edit_updater') {
+		$price_updaters->type = GETPOSTISSET('type') ? GETPOST('type', 'int') : $price_updaters->type;
+		$price_updaters->description = GETPOSTISSET('description') ? GETPOST('description', 'restricthtml') : $price_updaters->description;
+		$price_updaters->parameters = GETPOSTISSET('parameters') ? GETPOST('parameters', 'alphanohtml') : $price_updaters->parameters;
+		$price_updaters->fk_variable = GETPOSTISSET('fk_variable') ? GETPOST('fk_variable', 'int') : $price_updaters->fk_variable;
+		$price_updaters->update_interval = GETPOSTISSET('update_interval') ? GETPOST('update_interval', 'int') : $price_updaters->update_interval;
+	}
+	if ($action == 'create_updater' && !empty($save)) {
+		//Verify if process() works
+		$res = $price_updaters->process();
+		if ($res > 0) {
+			$res = $price_updaters->create($user);
+		}
+		if ($res > 0) {
+			$action = '';
+		} else {
+			setEventMessages($price_updaters->error, $price_updaters->errors, 'errors');
+		}
+	} elseif ($action == 'edit_updater' && !empty($save)) {
+		//Verify if process() works
+		$res = $price_updaters->process();
+		if ($res > 0) {
+			$res = $price_updaters->update($user);
+		}
+		if ($res > 0) {
+			$action = '';
+		} else {
+			setEventMessages($price_updaters->error, $price_updaters->errors, 'errors');
+		}
+	} elseif ($action == 'delete_updater') {
+		$res = $price_updaters->delete($selection, $user);
+		if ($res > 0) {
+			$action = '';
+		} else {
+			setEventMessages($price_updaters->error, $price_updaters->errors, 'errors');
+		}
+	}
 } elseif (!empty($cancel)) {
-    $action = '';
+	$action = '';
 }
 
 
@@ -159,171 +159,171 @@ print '<br>';
 //Global variables table
 if ($action != 'create_updater' && $action != 'edit_updater')
 {
-    print load_fiche_titre($langs->trans("GlobalVariables"), '', '');
+	print load_fiche_titre($langs->trans("GlobalVariables"), '', '');
 
-    print '<table summary="listofattributes" class="noborder centpercent">';
-    print '<tr class="liste_titre">';
-    print '<td>'.$langs->trans("Variable").'</td>';
-    print '<td>'.$langs->trans("Description").'</td>';
-    print '<td>'.$langs->trans("Value").'</td>';
-    print '<td width="80">&nbsp;</td>'; //Space for buttons
-    print '</tr>';
+	print '<table summary="listofattributes" class="noborder centpercent">';
+	print '<tr class="liste_titre">';
+	print '<td>'.$langs->trans("Variable").'</td>';
+	print '<td>'.$langs->trans("Description").'</td>';
+	print '<td>'.$langs->trans("Value").'</td>';
+	print '<td width="80">&nbsp;</td>'; //Space for buttons
+	print '</tr>';
 
-    $arrayglobalvars = $price_globals->listGlobalVariables();
-    if (!empty($arrayglobalvars))
-    {
-	    foreach ($arrayglobalvars as $i=>$entry) {
-	        $var = !$var;
-	        print '<tr class="oddeven">';
-	        print '<td>'.$entry->code.'</td>';
-	        print '<td>'.$entry->description.'</td>';
-	        print '<td>'.price($entry->value).'</td>';
-	        print '<td class="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit_variable&token='.newToken().'&selection='.$entry->id.'">'.img_edit().'</a> &nbsp;';
-	        print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_variable&token='.newToken().'&selection='.$entry->id.'">'.img_delete().'</a></td>';
-	        print '</tr>';
-	    }
-    } else {
-    	print '<tr colspan="7"><td class="opacitymedium">';
-    	print $langs->trans("None");
-    	print '</td></tr>';
-    }
-    print '</table>';
+	$arrayglobalvars = $price_globals->listGlobalVariables();
+	if (!empty($arrayglobalvars))
+	{
+		foreach ($arrayglobalvars as $i=>$entry) {
+			$var = !$var;
+			print '<tr class="oddeven">';
+			print '<td>'.$entry->code.'</td>';
+			print '<td>'.$entry->description.'</td>';
+			print '<td>'.price($entry->value).'</td>';
+			print '<td class="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit_variable&token='.newToken().'&selection='.$entry->id.'">'.img_edit().'</a> &nbsp;';
+			print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_variable&token='.newToken().'&selection='.$entry->id.'">'.img_delete().'</a></td>';
+			print '</tr>';
+		}
+	} else {
+		print '<tr colspan="7"><td class="opacitymedium">';
+		print $langs->trans("None");
+		print '</td></tr>';
+	}
+	print '</table>';
 
-    if (empty($action))
-    {
-        //Action Buttons
-        print '<div class="tabsAction">';
-        print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_variable">'.$langs->trans("AddVariable").'</a>';
-        print '</div>';
-        //Separator is only need for updaters table is showed after buttons
-        print '<br><br>';
-    }
+	if (empty($action))
+	{
+		//Action Buttons
+		print '<div class="tabsAction">';
+		print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_variable">'.$langs->trans("AddVariable").'</a>';
+		print '</div>';
+		//Separator is only need for updaters table is showed after buttons
+		print '<br><br>';
+	}
 }
 
 //Global variable editor
 if ($action == 'create_variable' || $action == 'edit_variable') {
-    //Form
-    print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    print '<input type="hidden" name="action" value="'.$action.'">';
-    print '<input type="hidden" name="selection" value="'.$selection.'">';
+	//Form
+	print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="action" value="'.$action.'">';
+	print '<input type="hidden" name="selection" value="'.$selection.'">';
 
-    //Table
-    print '<br><table summary="listofattributes" class="border centpercent">';
-    //Code
-    print '<tr>';
-    print '<td class="fieldrequired">'.$langs->trans("Variable").'</td>';
-    print '<td class="valeur"><input type="text" name="code" size="20" value="'.(empty($price_globals->code) ? '' : $price_globals->code).'"></td>';
-    print '</tr>';
-    //Description
-    print '<tr>';
-    print '<td>'.$langs->trans("Description").'</td>';
-    print '<td class="valeur"><input type="text" name="description" size="50" value="'.(empty($price_globals->description) ? '' : $price_globals->description).'"></td>';
-    print '</tr>';
-    //Value
-    print '<tr>';
-    print '<td class="fieldrequired">'.$langs->trans("Value").'</td>';
-    print '<td class="valeur"><input type="text" name="value" size="10" value="'.(empty($price_globals->value) ? '' : $price_globals->value).'"></td>';
-    print '</tr>';
-    print '</table>';
+	//Table
+	print '<br><table summary="listofattributes" class="border centpercent">';
+	//Code
+	print '<tr>';
+	print '<td class="fieldrequired">'.$langs->trans("Variable").'</td>';
+	print '<td class="valeur"><input type="text" name="code" size="20" value="'.(empty($price_globals->code) ? '' : $price_globals->code).'"></td>';
+	print '</tr>';
+	//Description
+	print '<tr>';
+	print '<td>'.$langs->trans("Description").'</td>';
+	print '<td class="valeur"><input type="text" name="description" size="50" value="'.(empty($price_globals->description) ? '' : $price_globals->description).'"></td>';
+	print '</tr>';
+	//Value
+	print '<tr>';
+	print '<td class="fieldrequired">'.$langs->trans("Value").'</td>';
+	print '<td class="valeur"><input type="text" name="value" size="10" value="'.(empty($price_globals->value) ? '' : $price_globals->value).'"></td>';
+	print '</tr>';
+	print '</table>';
 
-    //Form Buttons
-    print '<br><div class="center">';
-    print '<input type="submit" class="button" name="save" value="'.$langs->trans("Save").'"> &nbsp;';
-    print '<input type="submit" class="button" name="cancel" id="cancel" value="'.$langs->trans("Cancel").'">';
-    print '</div>';
-    print '</form>';
+	//Form Buttons
+	print '<br><div class="center">';
+	print '<input type="submit" class="button" name="save" value="'.$langs->trans("Save").'"> &nbsp;';
+	print '<input type="submit" class="button" name="cancel" id="cancel" value="'.$langs->trans("Cancel").'">';
+	print '</div>';
+	print '</form>';
 }
 
 // Updaters table
 if ($action != 'create_variable' && $action != 'edit_variable')
 {
-    print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', '');
+	print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', '');
 
-    print '<table summary="listofattributes" class="noborder centpercent">';
-    print '<tr class="liste_titre">';
-    print '<td>'.$langs->trans("VariableToUpdate").'</td>';
-    print '<td>'.$langs->trans("Description").'</td>';
-    print '<td>'.$langs->trans("Type").'</td>';
-    print '<td>'.$langs->trans("Parameters").'</td>';
-    print '<td>'.$langs->trans("UpdateInterval").'</td>';
-    print '<td>'.$langs->trans("LastUpdated").'</td>';
-    print '<td width="80">&nbsp;</td>'; //Space for buttons
-    print '</tr>';
+	print '<table summary="listofattributes" class="noborder centpercent">';
+	print '<tr class="liste_titre">';
+	print '<td>'.$langs->trans("VariableToUpdate").'</td>';
+	print '<td>'.$langs->trans("Description").'</td>';
+	print '<td>'.$langs->trans("Type").'</td>';
+	print '<td>'.$langs->trans("Parameters").'</td>';
+	print '<td>'.$langs->trans("UpdateInterval").'</td>';
+	print '<td>'.$langs->trans("LastUpdated").'</td>';
+	print '<td width="80">&nbsp;</td>'; //Space for buttons
+	print '</tr>';
 
-    $arraypriceupdaters = $price_updaters->listUpdaters();
-    if (!empty($arraypriceupdaters))
-    {
-	    foreach ($arraypriceupdaters as $i=>$entry) {
-	        $code = "";
-	        if ($entry->fk_variable > 0) {
-	            $res = $price_globals->fetch($entry->fk_variable);
-	            if ($res > 0) {
-	                $code = $price_globals->code;
-	            }
-	        }
-	        print '<tr>';
-	        print '<td>'.$code.'</td>';
-	        print '<td>'.$entry->description.'</td>';
-	        print '<td>'.$langs->trans("GlobalVariableUpdaterType".$entry->type).'</td>';
-	        print '<td style="max-width: 250px; word-wrap: break-word; white-space: pre-wrap;">'.$entry->parameters.'</td>';
-	        print '<td>'.$entry->update_interval.'</td>';
-	        print '<td>'.$entry->getLastUpdated().'</td>';
-	        print '<td class="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit_updater&selection='.$entry->id.'">'.img_edit().'</a> &nbsp;';
-	        print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_updater&token='.newToken().'&selection='.$entry->id.'">'.img_delete().'</a></td>';
-	        print '</tr>';
-	    }
-    } else {
-    	print '<tr><td colspan="7" class="opacitymedium">';
-    	print $langs->trans("None");
-    	print '</td></tr>';
-    }
-    print '</table>';
+	$arraypriceupdaters = $price_updaters->listUpdaters();
+	if (!empty($arraypriceupdaters))
+	{
+		foreach ($arraypriceupdaters as $i=>$entry) {
+			$code = "";
+			if ($entry->fk_variable > 0) {
+				$res = $price_globals->fetch($entry->fk_variable);
+				if ($res > 0) {
+					$code = $price_globals->code;
+				}
+			}
+			print '<tr>';
+			print '<td>'.$code.'</td>';
+			print '<td>'.$entry->description.'</td>';
+			print '<td>'.$langs->trans("GlobalVariableUpdaterType".$entry->type).'</td>';
+			print '<td style="max-width: 250px; word-wrap: break-word; white-space: pre-wrap;">'.$entry->parameters.'</td>';
+			print '<td>'.$entry->update_interval.'</td>';
+			print '<td>'.$entry->getLastUpdated().'</td>';
+			print '<td class="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit_updater&selection='.$entry->id.'">'.img_edit().'</a> &nbsp;';
+			print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_updater&token='.newToken().'&selection='.$entry->id.'">'.img_delete().'</a></td>';
+			print '</tr>';
+		}
+	} else {
+		print '<tr><td colspan="7" class="opacitymedium">';
+		print $langs->trans("None");
+		print '</td></tr>';
+	}
+	print '</table>';
 
-    if (empty($action))
-    {
-        //Action Buttons
-        print '<div class="tabsAction">';
-        print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_updater&token='.newToken().'">'.$langs->trans("AddUpdater").'</a>';
-        print '</div>';
-    }
+	if (empty($action))
+	{
+		//Action Buttons
+		print '<div class="tabsAction">';
+		print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=create_updater&token='.newToken().'">'.$langs->trans("AddUpdater").'</a>';
+		print '</div>';
+	}
 }
 
 //Updater editor
 if ($action == 'create_updater' || $action == 'edit_updater') {
-    //Form
-    print '<form id="updaterform" action="'.$_SERVER["PHP_SELF"].'" method="post">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    print '<input type="hidden" name="action" value="'.$action.'">';
-    print '<input type="hidden" name="selection" value="'.$selection.'">';
+	//Form
+	print '<form id="updaterform" action="'.$_SERVER["PHP_SELF"].'" method="post">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="action" value="'.$action.'">';
+	print '<input type="hidden" name="selection" value="'.$selection.'">';
 
-    //Table
-    print '<br><table summary="listofattributes" class="border centpercent">';
-    //Code
-    print '<tr>';
-    print '<td class="fieldrequired">'.$langs->trans("VariableToUpdate").'</td><td>';
-    $globals_list = array();
-    foreach ($price_globals->listGlobalVariables() as $entry) {
-        $globals_list[$entry->id] = $entry->code;
-    }
-    print $form->selectarray('fk_variable', $globals_list, (empty($price_updaters->fk_variable) ? 0 : $price_updaters->fk_variable));
-    print '</td></tr>';
-    //Description
-    print '<tr>';
-    print '<td>'.$langs->trans("Description").'</td>';
-    print '<td class="valeur"><input type="text" name="description" size="50" value="'.(empty($price_updaters->description) ? '' : $price_updaters->description).'"></td>';
-    print '</tr>';
-    //Type
-    print '<tr>';
-    print '<td class="fieldrequired">'.$langs->trans("Type").'</td><td>';
-    $type = empty($price_updaters->type) ? 0 : $price_updaters->type;
-    $type_list = array();
-    foreach ($price_updaters->types as $val) {
-        $type_list[$val] = $langs->trans("GlobalVariableUpdaterType".$val);
-    }
-    print $form->selectarray('type', $type_list, $type);
-    // This code submits form when type is changed
-    print '<script type="text/javascript">
+	//Table
+	print '<br><table summary="listofattributes" class="border centpercent">';
+	//Code
+	print '<tr>';
+	print '<td class="fieldrequired">'.$langs->trans("VariableToUpdate").'</td><td>';
+	$globals_list = array();
+	foreach ($price_globals->listGlobalVariables() as $entry) {
+		$globals_list[$entry->id] = $entry->code;
+	}
+	print $form->selectarray('fk_variable', $globals_list, (empty($price_updaters->fk_variable) ? 0 : $price_updaters->fk_variable));
+	print '</td></tr>';
+	//Description
+	print '<tr>';
+	print '<td>'.$langs->trans("Description").'</td>';
+	print '<td class="valeur"><input type="text" name="description" size="50" value="'.(empty($price_updaters->description) ? '' : $price_updaters->description).'"></td>';
+	print '</tr>';
+	//Type
+	print '<tr>';
+	print '<td class="fieldrequired">'.$langs->trans("Type").'</td><td>';
+	$type = empty($price_updaters->type) ? 0 : $price_updaters->type;
+	$type_list = array();
+	foreach ($price_updaters->types as $val) {
+		$type_list[$val] = $langs->trans("GlobalVariableUpdaterType".$val);
+	}
+	print $form->selectarray('type', $type_list, $type);
+	// This code submits form when type is changed
+	print '<script type="text/javascript">
         jQuery(document).ready(run);
         function run() {
             jQuery("#type").change(on_change);
@@ -332,29 +332,29 @@ if ($action == 'create_updater' || $action == 'edit_updater') {
             jQuery("#updaterform").submit();
         }
     </script>';
-    print '</td></tr>';
-    //Parameters
-    print '<tr>';
-    $help = $langs->trans("GlobalVariableUpdaterHelp".$type).'<br><b>'.$langs->trans("GlobalVariableUpdaterHelpFormat".$type).'</b>';
-    print '<td class="fieldrequired">'.$form->textwithpicto($langs->trans("Parameters"), $help, 1).'</td><td>';
-    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-    $doleditor = new DolEditor('parameters', empty($price_updaters->parameters) ? '' : $price_updaters->parameters, '', 300, '', '', false, false, false, ROWS_8, '90%');
-    $doleditor->Create();
-    print '</td></tr>';
-    print '</tr>';
-    //Interval
-    print '<tr>';
-    print '<td class="fieldrequired">'.$langs->trans("UpdateInterval").'</td>';
-    print '<td class="valeur"><input type="text" name="update_interval" size="10" value="'.(empty($price_updaters->update_interval) ? '' : $price_updaters->update_interval).'"></td>';
-    print '</tr>';
-    print '</table>';
+	print '</td></tr>';
+	//Parameters
+	print '<tr>';
+	$help = $langs->trans("GlobalVariableUpdaterHelp".$type).'<br><b>'.$langs->trans("GlobalVariableUpdaterHelpFormat".$type).'</b>';
+	print '<td class="fieldrequired">'.$form->textwithpicto($langs->trans("Parameters"), $help, 1).'</td><td>';
+	require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
+	$doleditor = new DolEditor('parameters', empty($price_updaters->parameters) ? '' : $price_updaters->parameters, '', 300, '', '', false, false, false, ROWS_8, '90%');
+	$doleditor->Create();
+	print '</td></tr>';
+	print '</tr>';
+	//Interval
+	print '<tr>';
+	print '<td class="fieldrequired">'.$langs->trans("UpdateInterval").'</td>';
+	print '<td class="valeur"><input type="text" name="update_interval" size="10" value="'.(empty($price_updaters->update_interval) ? '' : $price_updaters->update_interval).'"></td>';
+	print '</tr>';
+	print '</table>';
 
-    //Form Buttons
-    print '<br><div class="center">';
-    print '<input type="submit" class="button" name="save" value="'.$langs->trans("Save").'"> &nbsp;';
-    print '<input type="submit" class="button" name="cancel" id="cancel" value="'.$langs->trans("Cancel").'">';
-    print '</div>';
-    print '</form>';
+	//Form Buttons
+	print '<br><div class="center">';
+	print '<input type="submit" class="button" name="save" value="'.$langs->trans("Save").'"> &nbsp;';
+	print '<input type="submit" class="button" name="cancel" id="cancel" value="'.$langs->trans("Cancel").'">';
+	print '</div>';
+	print '</form>';
 }
 
 // End of page

+ 28 - 28
htdocs/product/card.php

@@ -301,8 +301,8 @@ if (empty($reshook))
 			$object->note_private          	 = dol_htmlcleanlastbr(GETPOST('note_private', 'restricthtml'));
 			$object->note               	 = $object->note_private; // deprecated
 			$object->customcode              = GETPOST('customcode', 'alphanohtml');
-	        $object->country_id = GETPOST('country_id', 'int');
-	        $object->state_id = GETPOST('state_id', 'int');
+			$object->country_id = GETPOST('country_id', 'int');
+			$object->state_id = GETPOST('state_id', 'int');
 			$object->duration_value     	 = $duration_value;
 			$object->duration_unit      	 = $duration_unit;
 			$object->fk_default_warehouse	 = GETPOST('fk_default_warehouse');
@@ -965,14 +965,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
 		$linkback = "";
 		print load_fiche_titre($title, $linkback, $picto);
 
-        // We set country_id, country_code and country for the selected country
-        $object->country_id = GETPOSTISSET('country_id') ? GETPOST('country_id', 'int') : null;
-        if ($object->country_id > 0)
-        {
-            $tmparray = getCountry($object->country_id, 'all');
-            $object->country_code = $tmparray['code'];
-            $object->country = $tmparray['label'];
-        }
+		// We set country_id, country_code and country for the selected country
+		$object->country_id = GETPOSTISSET('country_id') ? GETPOST('country_id', 'int') : null;
+		if ($object->country_id > 0)
+		{
+			$tmparray = getCountry($object->country_id, 'all');
+			$object->country_code = $tmparray['code'];
+			$object->country = $tmparray['label'];
+		}
 
 		dol_fiche_head('');
 
@@ -1151,26 +1151,26 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
 			// Origin country
 			print '<td>'.$langs->trans("CountryOrigin").'</td>';
 			print '<td>';
-            print img_picto('', 'globe-americas', 'class="paddingrightonly"');
-            print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 widthcentpercentminusx');
-            if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
+			print img_picto('', 'globe-americas', 'class="paddingrightonly"');
+			print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 widthcentpercentminusx');
+			if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
 			print '</td>';
 
-            // State
-            if (empty($conf->global->PRODUCT_DISABLE_STATE))
-            {
-            		if ($conf->browser->layout == 'phone') print '</tr><tr>';
-                if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2))
-                {
-                    print '<td>'.$form->editfieldkey('Region-StateOrigine', 'state_id', '', $object, 0).'</td><td colspan="3">';
-                } else {
-                    print '<td>'.$form->editfieldkey('StateOrigin', 'state_id', '', $object, 0).'</td><td colspan="3">';
-                }
+			// State
+			if (empty($conf->global->PRODUCT_DISABLE_STATE))
+			{
+					if ($conf->browser->layout == 'phone') print '</tr><tr>';
+				if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2))
+				{
+					print '<td>'.$form->editfieldkey('Region-StateOrigine', 'state_id', '', $object, 0).'</td><td colspan="3">';
+				} else {
+					print '<td>'.$form->editfieldkey('StateOrigin', 'state_id', '', $object, 0).'</td><td colspan="3">';
+				}
 
 				print $formcompany->select_state($object->state_id, $object->country_code);
-                print '</tr>';
-            }
-                print '</tr>';
+				print '</tr>';
+			}
+				print '</tr>';
 		}
 
 		// Other attributes
@@ -1616,7 +1616,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
 				// State
 				if (empty($conf->global->PRODUCT_DISABLE_STATE))
 				{
-            		if ($conf->browser->layout == 'phone') print '</tr><tr>';
+					if ($conf->browser->layout == 'phone') print '</tr><tr>';
 					if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2))
 					{
 						print '<td>'.$form->editfieldkey('Region-StateOrigine', 'state_id', '', $object, 0).'</td><td colspan="3">';
@@ -2389,7 +2389,7 @@ if ($action != 'create' && $action != 'edit' && $action != 'delete')
 	$objectref = dol_sanitizeFileName($object->ref);
 	$relativepath = $comref.'/'.$objectref.'.pdf';
 	if (!empty($conf->product->multidir_output[$object->entity])) {
-    	$filedir = $conf->product->multidir_output[$object->entity].'/'.$objectref; //Check repertories of current entities
+		$filedir = $conf->product->multidir_output[$object->entity].'/'.$objectref; //Check repertories of current entities
 	} else {
 		$filedir = $conf->product->dir_output.'/'.$objectref;
 	}

+ 1 - 1
htdocs/product/class/productcustomerprice.class.php

@@ -368,7 +368,7 @@ class Productcustomerprice extends CommonObject
 				} elseif ($key == 'prod.ref' || $key == 'prod.label') {
 					$sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\'';
 				} elseif ($key == 't.price' || $key == 't.price_ttc') {
-					$sql .= ' AND ' . $key . ' LIKE \'%' . price2num($value) . '%\'';
+					$sql .= ' AND '.$key.' LIKE \'%'.price2num($value).'%\'';
 				} else {
 					$sql .= ' AND '.$key.' = '.((int) $value);
 				}

File diff suppressed because it is too large
+ 429 - 429
htdocs/product/price.php


+ 3 - 3
htdocs/product/stock/replenish.php

@@ -630,7 +630,7 @@ if ($search_ref || $search_label || $sall || $salert || $draftorder || GETPOST('
 }
 
 if ($limit > 0 && $limit != $conf->liste_limit) {
-    $filters .= '&limit=' . urlencode($limit);
+    $filters .= '&limit='.urlencode($limit);
 }
 
 $param = (isset($type) ? '&type='.$type : '');
@@ -701,7 +701,7 @@ if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entre
 	print '<td class="liste_titre">&nbsp;</td>';
 }
 print '<td class="liste_titre right">';
-if (! empty($conf->global->STOCK_REPLENISH_ADD_CHECKBOX_INCLUDE_DRAFT_ORDER)) {
+if (!empty($conf->global->STOCK_REPLENISH_ADD_CHECKBOX_INCLUDE_DRAFT_ORDER)) {
 	print $langs->trans('IncludeAlsoDraftOrders').'&nbsp;<input type="checkbox" id="draftorder" name="draftorder" '.(!empty($draftchecked) ? $draftchecked : '').'>';
 }
 print '</td>';
@@ -768,7 +768,7 @@ while ($i < ($limit ? min($num, $limit) : $num))
 			}
 		}
 
-		$stockwarehouse=0;
+		$stockwarehouse = 0;
 		if ($usevirtualstock)
 		{
 			// If option to increase/decrease is not on an object validation, virtual stock may differs from physical stock.

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

@@ -178,7 +178,7 @@ class Project 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'=>-1, 'notnull'=>1, 'position'=>10),
 		'fk_soc' =>array('type'=>'integer', 'label'=>'Fk soc', 'enabled'=>1, 'visible'=>3, 'position'=>15),
 		'datec' =>array('type'=>'datetime', 'label'=>'DateCreationShort', 'enabled'=>1, 'visible'=>1, 'position'=>20),
@@ -577,7 +577,7 @@ class Project extends CommonObject
 				$this->opp_percent = $obj->opp_percent;
 				$this->budget_amount = $obj->budget_amount;
 				$this->model_pdf = $obj->model_pdf;
-				$this->modelpdf = $obj->model_pdf;	// deprecated
+				$this->modelpdf = $obj->model_pdf; // deprecated
 				$this->usage_opportunity = (int) $obj->usage_opportunity;
 				$this->usage_task = (int) $obj->usage_task;
 				$this->usage_bill_time = (int) $obj->usage_bill_time;

+ 65 - 65
htdocs/projet/list.php

@@ -228,47 +228,47 @@ if (empty($reshook))
 	$uploaddir = $conf->projet->dir_output;
 	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
 
-    // Close records
-    if (!$error && $massaction == 'close' && $user->rights->projet->creer)
-    {
-        $db->begin();
-
-        $objecttmp = new $objectclass($db);
-        $nbok = 0;
-        foreach ($toselect as $toselectid)
-        {
-            $result = $objecttmp->fetch($toselectid);
-            if ($result > 0)
-            {
-                $userWrite  = $object->restrictedProjectArea($user, 'write');
-                if ($userWrite > 0 && $objecttmp->statut == 1) {
-                    $result = $objecttmp->setClose($user);
-                    if ($result <= 0) {
-                        setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
-                        $error++;
-                        break;
-                    } else $nbok++;
-                } elseif ($userWrite <= 0) {
-                    setEventMessages($langs->trans("DontHavePermissionForCloseProject", $objecttmp->ref), null, 'warnings');
-                } else {
-                    setEventMessages($langs->trans("DontHaveTheValidateStatus", $objecttmp->ref), null, 'warnings');
-                }
-            } else {
-                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
-                $error++;
-                break;
-            }
-        }
-
-        if (!$error)
-        {
-            if ($nbok > 1) setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs');
-            else setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs');
-            $db->commit();
-        } else {
-            $db->rollback();
-        }
-    }
+	// Close records
+	if (!$error && $massaction == 'close' && $user->rights->projet->creer)
+	{
+		$db->begin();
+
+		$objecttmp = new $objectclass($db);
+		$nbok = 0;
+		foreach ($toselect as $toselectid)
+		{
+			$result = $objecttmp->fetch($toselectid);
+			if ($result > 0)
+			{
+				$userWrite  = $object->restrictedProjectArea($user, 'write');
+				if ($userWrite > 0 && $objecttmp->statut == 1) {
+					$result = $objecttmp->setClose($user);
+					if ($result <= 0) {
+						setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
+						$error++;
+						break;
+					} else $nbok++;
+				} elseif ($userWrite <= 0) {
+					setEventMessages($langs->trans("DontHavePermissionForCloseProject", $objecttmp->ref), null, 'warnings');
+				} else {
+					setEventMessages($langs->trans("DontHaveTheValidateStatus", $objecttmp->ref), null, 'warnings');
+				}
+			} else {
+				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
+				$error++;
+				break;
+			}
+		}
+
+		if (!$error)
+		{
+			if ($nbok > 1) setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs');
+			else setEventMessages($langs->trans("RecordsClosed", $nbok), null, 'mesgs');
+			$db->commit();
+		} else {
+			$db->rollback();
+		}
+	}
 }
 
 
@@ -447,8 +447,8 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
 // List of mass actions available
 $arrayofmassactions = array(
 	'generate_doc'=>$langs->trans("ReGeneratePDF"),
-    //'builddoc'=>$langs->trans("PDFMerge"),
-    //'presend'=>$langs->trans("SendByMail"),
+	//'builddoc'=>$langs->trans("PDFMerge"),
+	//'presend'=>$langs->trans("SendByMail"),
 );
 //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer");
 if ($user->rights->projet->creer) $arrayofmassactions['close'] = $langs->trans("Close");
@@ -474,8 +474,8 @@ print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
 $texthelp = '';
 if ($search_project_user == $user->id) $texthelp .= $langs->trans("MyProjectsDesc");
 else {
-    if ($user->rights->projet->all->lire && !$socid) $texthelp .= $langs->trans("ProjectsDesc");
-    else $texthelp .= $langs->trans("ProjectsPublicDesc");
+	if ($user->rights->projet->all->lire && !$socid) $texthelp .= $langs->trans("ProjectsDesc");
+	else $texthelp .= $langs->trans("ProjectsPublicDesc");
 }
 
 print_barre_liste($form->textwithpicto($title, $texthelp), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'project', 0, $newcardbutton, '', $limit, 0, 0, 1);
@@ -616,8 +616,8 @@ if (!empty($arrayfields['p.opp_percent']['checked']))
 }
 if (!empty($arrayfields['opp_weighted_amount']['checked']))
 {
-    print '<td class="liste_titre nowrap right">';
-    print '</td>';
+	print '<td class="liste_titre nowrap right">';
+	print '</td>';
 }
 if (!empty($arrayfields['p.budget_amount']['checked']))
 {
@@ -711,8 +711,8 @@ print "</tr>\n";
 
 $i = 0;
 $totalarray = array(
-    'nbfield' => 0,
-    'val' => array(),
+	'nbfield' => 0,
+	'val' => array(),
 );
 while ($i < min($num, $limit))
 {
@@ -732,9 +732,9 @@ while ($i < min($num, $limit))
 	$userAccess = $object->restrictedProjectArea($user); // why this ?
 	if ($userAccess >= 0)
 	{
-	    $socstatic->id = $obj->socid;
-	    $socstatic->name = $obj->name;
-	    $socstatic->email = $obj->email;
+		$socstatic->id = $obj->socid;
+		$socstatic->name = $obj->name;
+		$socstatic->email = $obj->email;
 
 		print '<tr class="oddeven">';
 
@@ -862,19 +862,19 @@ while ($i < min($num, $limit))
 			print '</td>';
 			if (!$i) $totalarray['nbfield']++;
 		}
-        // Opp weighted amount
-        if (!empty($arrayfields['opp_weighted_amount']['checked']))
-        {
-            if (!isset($totalarray['val']['opp_weighted_amount']))  $totalarray['val']['opp_weighted_amount'] = 0;
-            print '<td align="right">';
-            if ($obj->opp_weighted_amount) {
-                print price($obj->opp_weighted_amount, 1, $langs, 1, -1, -1, '');
-                $totalarray['val']['opp_weighted_amount'] += $obj->opp_weighted_amount;
-            }
-            print '</td>';
-            if (!$i) $totalarray['nbfield']++;
-            if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'opp_weighted_amount';
-        }
+		// Opp weighted amount
+		if (!empty($arrayfields['opp_weighted_amount']['checked']))
+		{
+			if (!isset($totalarray['val']['opp_weighted_amount']))  $totalarray['val']['opp_weighted_amount'] = 0;
+			print '<td align="right">';
+			if ($obj->opp_weighted_amount) {
+				print price($obj->opp_weighted_amount, 1, $langs, 1, -1, -1, '');
+				$totalarray['val']['opp_weighted_amount'] += $obj->opp_weighted_amount;
+			}
+			print '</td>';
+			if (!$i) $totalarray['nbfield']++;
+			if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'opp_weighted_amount';
+		}
 		// Budget
 		if (!empty($arrayfields['p.budget_amount']['checked']))
 		{

+ 145 - 145
htdocs/projet/tasks/task.php

@@ -86,7 +86,7 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer)
 	if (!$error)
 	{
 		$object->fetch($id, $ref);
-        $object->oldcopy = clone $object;
+		$object->oldcopy = clone $object;
 
 		$tmparray = explode('_', $_POST['task_parent']);
 		$task_parent = $tmparray[1];
@@ -110,7 +110,7 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->projet->creer)
 			$result = $object->update($user);
 			if ($result < 0)
 			{
-			    setEventMessages($object->error, $object->errors, 'errors');
+				setEventMessages($object->error, $object->errors, 'errors');
 			}
 		}
 	} else {
@@ -130,7 +130,7 @@ if ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->projet->s
 			header('Location: '.DOL_URL_ROOT.'/projet/tasks.php?restore_lastsearch_values=1&id='.$projectstatic->id.($withproject ? '&withproject=1' : ''));
 			exit;
 		} else {
-		    setEventMessages($object->error, $object->errors, 'errors');
+			setEventMessages($object->error, $object->errors, 'errors');
 			$action = '';
 		}
 	}
@@ -169,7 +169,7 @@ if ($action == 'builddoc' && $user->rights->projet->creer)
 	if ($result <= 0)
 	{
 		setEventMessages($object->error, $object->errors, 'errors');
-        $action = '';
+		$action = '';
 	}
 }
 
@@ -227,115 +227,115 @@ if ($id > 0 || !empty($ref))
 
 			// Project card
 
-            $linkback = '<a href="'.DOL_URL_ROOT.'/projet/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
-
-            $morehtmlref = '<div class="refidno">';
-            // Title
-            $morehtmlref .= $projectstatic->title;
-            // Thirdparty
-            if ($projectstatic->thirdparty->id > 0)
-            {
-                $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project');
-            }
-            $morehtmlref .= '</div>';
-
-            // Define a complementary filter for search of next/prev ref.
-            if (!$user->rights->projet->all->lire)
-            {
-                $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0);
-                $projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
-            }
-
-            dol_banner_tab($projectstatic, 'project_ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
-
-            print '<div class="fichecenter">';
-            print '<div class="fichehalfleft">';
-            print '<div class="underbanner clearboth"></div>';
-
-            print '<table class="border tableforfield centpercent">';
-
-            // Usage
-            print '<tr><td class="tdtop">';
-            print $langs->trans("Usage");
-            print '</td>';
-            print '<td>';
-            if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
-            {
-            	print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> ';
-            	$htmltext = $langs->trans("ProjectFollowOpportunity");
-            	print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
-            	print '<br>';
-            }
-            if (empty($conf->global->PROJECT_HIDE_TASKS))
-            {
-            	print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> ';
-            	$htmltext = $langs->trans("ProjectFollowTasks");
-            	print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
-            	print '<br>';
-            }
-            if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
-            {
-            	print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> ';
-            	$htmltext = $langs->trans("ProjectBillTimeDescription");
-            	print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
-            	print '<br>';
-            }
-            print '</td></tr>';
-
-            // Visibility
-            print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
-            if ($projectstatic->public) print $langs->trans('SharedProject');
-            else print $langs->trans('PrivateProject');
-            print '</td></tr>';
-
-            // Date start - end
-            print '<tr><td>'.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").'</td><td>';
-            $start = dol_print_date($projectstatic->date_start, 'day');
-            print ($start ? $start : '?');
-            $end = dol_print_date($projectstatic->date_end, 'day');
-            print ' - ';
-            print ($end ? $end : '?');
-            if ($projectstatic->hasDelay()) print img_warning("Late");
-            print '</td></tr>';
-
-            // Budget
-            print '<tr><td>'.$langs->trans("Budget").'</td><td>';
-            if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
-            print '</td></tr>';
-
-            // Other attributes
-            $cols = 2;
-            //include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
-
-            print '</table>';
-
-            print '</div>';
-
-            print '<div class="fichehalfright">';
-            print '<div class="ficheaddleft">';
-            print '<div class="underbanner clearboth"></div>';
-
-            print '<table class="border centpercent">';
-
-            // Description
-            print '<td class="titlefield tdtop">'.$langs->trans("Description").'</td><td>';
-            print nl2br($projectstatic->description);
-            print '</td></tr>';
-
-            // Categories
-            if ($conf->categorie->enabled) {
-                print '<tr><td class="valignmiddle">'.$langs->trans("Categories").'</td><td>';
-                print $form->showCategories($projectstatic->id, 'project', 1);
-                print "</td></tr>";
-            }
-
-            print '</table>';
-
-            print '</div>';
-            print '</div>';
-            print '</div>';
-
-            print '<div class="clearboth"></div>';
+			$linkback = '<a href="'.DOL_URL_ROOT.'/projet/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
+
+			$morehtmlref = '<div class="refidno">';
+			// Title
+			$morehtmlref .= $projectstatic->title;
+			// Thirdparty
+			if ($projectstatic->thirdparty->id > 0)
+			{
+				$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$projectstatic->thirdparty->getNomUrl(1, 'project');
+			}
+			$morehtmlref .= '</div>';
+
+			// Define a complementary filter for search of next/prev ref.
+			if (!$user->rights->projet->all->lire)
+			{
+				$objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0);
+				$projectstatic->next_prev_filter = " rowid in (".(count($objectsListId) ?join(',', array_keys($objectsListId)) : '0').")";
+			}
+
+			dol_banner_tab($projectstatic, 'project_ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+
+			print '<div class="fichecenter">';
+			print '<div class="fichehalfleft">';
+			print '<div class="underbanner clearboth"></div>';
+
+			print '<table class="border tableforfield centpercent">';
+
+			// Usage
+			print '<tr><td class="tdtop">';
+			print $langs->trans("Usage");
+			print '</td>';
+			print '<td>';
+			if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES))
+			{
+				print '<input type="checkbox" disabled name="usage_opportunity"'.(GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')).'"> ';
+				$htmltext = $langs->trans("ProjectFollowOpportunity");
+				print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
+				print '<br>';
+			}
+			if (empty($conf->global->PROJECT_HIDE_TASKS))
+			{
+				print '<input type="checkbox" disabled name="usage_task"'.(GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')).'"> ';
+				$htmltext = $langs->trans("ProjectFollowTasks");
+				print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
+				print '<br>';
+			}
+			if (!empty($conf->global->PROJECT_BILL_TIME_SPENT))
+			{
+				print '<input type="checkbox" disabled name="usage_bill_time"'.(GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')).'"> ';
+				$htmltext = $langs->trans("ProjectBillTimeDescription");
+				print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
+				print '<br>';
+			}
+			print '</td></tr>';
+
+			// Visibility
+			print '<tr><td class="titlefield">'.$langs->trans("Visibility").'</td><td>';
+			if ($projectstatic->public) print $langs->trans('SharedProject');
+			else print $langs->trans('PrivateProject');
+			print '</td></tr>';
+
+			// Date start - end
+			print '<tr><td>'.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").'</td><td>';
+			$start = dol_print_date($projectstatic->date_start, 'day');
+			print ($start ? $start : '?');
+			$end = dol_print_date($projectstatic->date_end, 'day');
+			print ' - ';
+			print ($end ? $end : '?');
+			if ($projectstatic->hasDelay()) print img_warning("Late");
+			print '</td></tr>';
+
+			// Budget
+			print '<tr><td>'.$langs->trans("Budget").'</td><td>';
+			if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency);
+			print '</td></tr>';
+
+			// Other attributes
+			$cols = 2;
+			//include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
+
+			print '</table>';
+
+			print '</div>';
+
+			print '<div class="fichehalfright">';
+			print '<div class="ficheaddleft">';
+			print '<div class="underbanner clearboth"></div>';
+
+			print '<table class="border centpercent">';
+
+			// Description
+			print '<td class="titlefield tdtop">'.$langs->trans("Description").'</td><td>';
+			print nl2br($projectstatic->description);
+			print '</td></tr>';
+
+			// Categories
+			if ($conf->categorie->enabled) {
+				print '<tr><td class="valignmiddle">'.$langs->trans("Categories").'</td><td>';
+				print $form->showCategories($projectstatic->id, 'project', 1);
+				print "</td></tr>";
+			}
+
+			print '</table>';
+
+			print '</div>';
+			print '</div>';
+			print '</div>';
+
+			print '<div class="clearboth"></div>';
 
 			dol_fiche_end();
 
@@ -440,7 +440,7 @@ if ($id > 0 || !empty($ref))
 			// Other options
 			$parameters = array();
 			$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-            print $hookmanager->resPrint;
+			print $hookmanager->resPrint;
 			if (empty($reshook))
 			{
 				print $object->showOptionals($extrafields, 'edit');
@@ -472,8 +472,8 @@ if ($id > 0 || !empty($ref))
 
 			if (!GETPOST('withproject') || empty($projectstatic->id))
 			{
-			    $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1);
-			    $object->next_prev_filter = " fk_projet in (".$projectsListId.")";
+				$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1);
+				$object->next_prev_filter = " fk_projet in (".$projectsListId.")";
 			} else $object->next_prev_filter = " fk_projet = ".$projectstatic->id;
 
 			$morehtmlref = '';
@@ -481,17 +481,17 @@ if ($id > 0 || !empty($ref))
 			// Project
 			if (empty($withproject))
 			{
-			    $morehtmlref .= '<div class="refidno">';
-			    $morehtmlref .= $langs->trans("Project").': ';
-			    $morehtmlref .= $projectstatic->getNomUrl(1);
-			    $morehtmlref .= '<br>';
-
-			    // Third party
-			    $morehtmlref .= $langs->trans("ThirdParty").': ';
-			    if (!empty($projectstatic->thirdparty)) {
-                    $morehtmlref .= $projectstatic->thirdparty->getNomUrl(1);
-			    }
-			    $morehtmlref .= '</div>';
+				$morehtmlref .= '<div class="refidno">';
+				$morehtmlref .= $langs->trans("Project").': ';
+				$morehtmlref .= $projectstatic->getNomUrl(1);
+				$morehtmlref .= '<br>';
+
+				// Third party
+				$morehtmlref .= $langs->trans("ThirdParty").': ';
+				if (!empty($projectstatic->thirdparty)) {
+					$morehtmlref .= $projectstatic->thirdparty->getNomUrl(1);
+				}
+				$morehtmlref .= '</div>';
 			}
 
 			dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, $param);
@@ -515,11 +515,11 @@ if ($id > 0 || !empty($ref))
 			// Date start - Date end
 			print '<tr><td class="titlefield">'.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").'</td><td colspan="3">';
 			$start = dol_print_date($object->date_start, 'dayhour');
-    		print ($start ? $start : '?');
+			print ($start ? $start : '?');
 			$end = dol_print_date($object->date_end, 'dayhour');
-    		print ' - ';
-    		print ($end ? $end : '?');
-    		if ($object->hasDelay()) print img_warning("Late");
+			print ' - ';
+			print ($end ? $end : '?');
+			if ($object->hasDelay()) print img_warning("Late");
 			print '</td></tr>';
 
 			// Planned workload
@@ -584,13 +584,13 @@ if ($id > 0 || !empty($ref))
 			 * Actions
  			 */
 
-		    print '<div class="tabsAction">';
+			print '<div class="tabsAction">';
 
-		    $parameters = array();
-		    $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
-		    // modified by hook
-		    if (empty($reshook))
-		    {
+			$parameters = array();
+			$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
+			// modified by hook
+			if (empty($reshook))
+			{
 				// Modify
 				if ($user->rights->projet->creer)
 				{
@@ -602,21 +602,21 @@ if ($id > 0 || !empty($ref))
 				// Delete
 				if ($user->rights->projet->supprimer)
 				{
-				    if (!$object->hasChildren() && !$object->hasTimeSpent())
-				    {
+					if (!$object->hasChildren() && !$object->hasTimeSpent())
+					{
 						print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'&amp;withproject='.$withproject.'">'.$langs->trans('Delete').'</a>';
-				    } else {
-				        print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("TaskHasChild").'">'.$langs->trans('Delete').'</a>';
-				    }
+					} else {
+						print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("TaskHasChild").'">'.$langs->trans('Delete').'</a>';
+					}
 				} else {
 					print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('Delete').'</a>';
 				}
 
 				print '</div>';
-		    }
+			}
 
-    		print '<div class="fichecenter"><div class="fichehalfleft">';
-    		print '<a name="builddoc"></a>'; // ancre
+			print '<div class="fichecenter"><div class="fichehalfleft">';
+			print '<a name="builddoc"></a>'; // ancre
 
 			/*
 			 * Documents generes

+ 20 - 20
htdocs/resource/card.php

@@ -257,7 +257,7 @@ if ($action == 'create' || $object->fetch($id, $ref) > 0)
 		// Other attributes
 		$parameters = array('objectsrc' => $objectsrc);
 		$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-        print $hookmanager->resPrint;
+		print $hookmanager->resPrint;
 		if (empty($reshook))
 		{
 			print $object->showOptionals($extrafields, 'edit');
@@ -279,27 +279,27 @@ if ($action == 'create' || $object->fetch($id, $ref) > 0)
 		$formconfirm = '';
 
 		// Confirm deleting resource line
-	    if ($action == 'delete')
-	    {
-	        $formconfirm = $form->formconfirm("card.php?&id=".$object->id, $langs->trans("DeleteResource"), $langs->trans("ConfirmDeleteResource"), "confirm_delete_resource", '', '', 1);
-	    }
+		if ($action == 'delete')
+		{
+			$formconfirm = $form->formconfirm("card.php?&id=".$object->id, $langs->trans("DeleteResource"), $langs->trans("ConfirmDeleteResource"), "confirm_delete_resource", '', '', 1);
+		}
 
-	    // Print form confirm
-	    print $formconfirm;
+		// Print form confirm
+		print $formconfirm;
 
 
-	    $linkback = '<a href="'.DOL_URL_ROOT.'/resource/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&id='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
+		$linkback = '<a href="'.DOL_URL_ROOT.'/resource/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&id='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 
 
-	    $morehtmlref = '<div class="refidno">';
-	    $morehtmlref .= '</div>';
+		$morehtmlref = '<div class="refidno">';
+		$morehtmlref .= '</div>';
 
 
-	    dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
+		dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
 
 
-	    print '<div class="fichecenter">';
-	    print '<div class="underbanner clearboth"></div>';
+		print '<div class="fichecenter">';
+		print '<div class="underbanner clearboth"></div>';
 
 		/*---------------------------------------
 		 * View object
@@ -365,13 +365,13 @@ if ($action == 'create' || $object->fetch($id, $ref) > 0)
 		}
 		if ($action != "delete" && $action != "create" && $action != "edit")
 		{
-		    // Delete resource
-		    if ($user->rights->resource->delete)
-		    {
-		        print '<div class="inline-block divButAction">';
-		        print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$id.'&amp;action=delete&amp;token='.newToken().'" class="butActionDelete">'.$langs->trans('Delete').'</a>';
-		        print '</div>';
-		    }
+			// Delete resource
+			if ($user->rights->resource->delete)
+			{
+				print '<div class="inline-block divButAction">';
+				print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$id.'&amp;action=delete&amp;token='.newToken().'" class="butActionDelete">'.$langs->trans('Delete').'</a>';
+				print '</div>';
+			}
 		}
 	}
 	print '</div>';

+ 41 - 41
htdocs/resource/list.php

@@ -108,7 +108,7 @@ $pageprev = $page - 1;
 $pagenext = $page + 1;
 
 if (!$user->rights->resource->read) {
-        accessforbidden();
+		accessforbidden();
 }
 $arrayfields = array(
 		't.ref' => array(
@@ -201,8 +201,8 @@ if ($ret == -1) {
 	$newcardbutton = '';
 	if ($user->rights->resource->write)
 	{
-        $newcardbutton .= dolGetButtonTitle($langs->trans('MenuResourceAdd'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/resource/card.php?action=create');
-    }
+		$newcardbutton .= dolGetButtonTitle($langs->trans('MenuResourceAdd'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/resource/card.php?action=create');
+	}
 
 	print_barre_liste($pagetitle, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $ret + 1, $nbtotalofrecords, 'object_resource', 0, $newcardbutton, '', $limit, 0, 0, 1);
 }
@@ -246,45 +246,45 @@ print "</tr>\n";
 if ($ret)
 {
 	foreach ($object->lines as $resource)
-    {
-        print '<tr class="oddeven">';
-
-        if (!empty($arrayfields['t.ref']['checked']))
-        {
-        	print '<td>';
-        	print $resource->getNomUrl(5);
-        	print '</td>';
-	        if (!$i) $totalarray['nbfield']++;
-        }
-
-        if (!empty($arrayfields['ty.label']['checked']))
-        {
-        	print '<td>';
-        	print $resource->type_label;
-        	print '</td>';
-	        if (!$i) $totalarray['nbfield']++;
-        }
-        // Extra fields
-        $obj = (Object) $resource->array_options;
-        include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
-
-        print '<td class="center">';
-        print '<a class="editfielda" href="./card.php?action=edit&token='.newToken().'&id='.$resource->id.'">';
-        print img_edit();
-        print '</a>';
-        print '&nbsp;';
-        print '<a href="./card.php?action=delete&token='.newToken().'&id='.$resource->id.'">';
-        print img_delete('', 'class="marginleftonly"');
-        print '</a>';
-        print '</td>';
-        if (!$i) $totalarray['nbfield']++;
-
-        print '</tr>';
-    }
+	{
+		print '<tr class="oddeven">';
+
+		if (!empty($arrayfields['t.ref']['checked']))
+		{
+			print '<td>';
+			print $resource->getNomUrl(5);
+			print '</td>';
+			if (!$i) $totalarray['nbfield']++;
+		}
+
+		if (!empty($arrayfields['ty.label']['checked']))
+		{
+			print '<td>';
+			print $resource->type_label;
+			print '</td>';
+			if (!$i) $totalarray['nbfield']++;
+		}
+		// Extra fields
+		$obj = (Object) $resource->array_options;
+		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
+
+		print '<td class="center">';
+		print '<a class="editfielda" href="./card.php?action=edit&token='.newToken().'&id='.$resource->id.'">';
+		print img_edit();
+		print '</a>';
+		print '&nbsp;';
+		print '<a href="./card.php?action=delete&token='.newToken().'&id='.$resource->id.'">';
+		print img_delete('', 'class="marginleftonly"');
+		print '</a>';
+		print '</td>';
+		if (!$i) $totalarray['nbfield']++;
+
+		print '</tr>';
+	}
 } else {
-    $colspan = 1;
-    foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; }
-    print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
+	$colspan = 1;
+	foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; }
+	print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
 }
 
 print '</table>';

File diff suppressed because it is too large
+ 572 - 572
htdocs/societe/card.php


+ 311 - 311
htdocs/societe/notify/card.php

@@ -72,57 +72,57 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
 
 if (empty($reshook))
 {
-    $error = 0;
+	$error = 0;
 
-    // Add a notification
-    if ($action == 'add')
-    {
-        if (empty($contactid))
-        {
-    	    setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Contact")), null, 'errors');
-            $error++;
-        }
-        if ($actionid <= 0)
-        {
-    	    setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Action")), null, 'errors');
-            $error++;
-        }
-
-        if (!$error)
-        {
-            $db->begin();
-
-            $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
-            $sql .= " WHERE fk_soc=".$socid." AND fk_contact=".$contactid." AND fk_action=".$actionid;
-            if ($db->query($sql))
-            {
-                $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_soc, fk_contact, fk_action)";
-                $sql .= " VALUES ('".$db->idate($now)."',".$socid.",".$contactid.",".$actionid.")";
-
-                if (!$db->query($sql))
-                {
-                    $error++;
-                    dol_print_error($db);
-                }
-            } else {
-                dol_print_error($db);
-            }
+	// Add a notification
+	if ($action == 'add')
+	{
+		if (empty($contactid))
+		{
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Contact")), null, 'errors');
+			$error++;
+		}
+		if ($actionid <= 0)
+		{
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Action")), null, 'errors');
+			$error++;
+		}
 
-            if (!$error)
-            {
-                $db->commit();
-            } else {
-                $db->rollback();
-            }
-        }
-    }
+		if (!$error)
+		{
+			$db->begin();
 
-    // Remove a notification
-    if ($action == 'delete')
-    {
-        $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def where rowid=".GETPOST('actid', 'int');
-        $db->query($sql);
-    }
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
+			$sql .= " WHERE fk_soc=".$socid." AND fk_contact=".$contactid." AND fk_action=".$actionid;
+			if ($db->query($sql))
+			{
+				$sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_soc, fk_contact, fk_action)";
+				$sql .= " VALUES ('".$db->idate($now)."',".$socid.",".$contactid.",".$actionid.")";
+
+				if (!$db->query($sql))
+				{
+					$error++;
+					dol_print_error($db);
+				}
+			} else {
+				dol_print_error($db);
+			}
+
+			if (!$error)
+			{
+				$db->commit();
+			} else {
+				$db->rollback();
+			}
+		}
+	}
+
+	// Remove a notification
+	if ($action == 'delete')
+	{
+		$sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def where rowid=".GETPOST('actid', 'int');
+		$db->query($sql);
+	}
 }
 
 
@@ -144,46 +144,46 @@ llxHeader('', $title, $help_url);
 
 if ($result > 0)
 {
-    $langs->load("other");
-
-    $head = societe_prepare_head($object);
+	$langs->load("other");
 
-    dol_fiche_head($head, 'notify', $langs->trans("ThirdParty"), -1, 'company');
+	$head = societe_prepare_head($object);
 
-    $linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
+	dol_fiche_head($head, 'notify', $langs->trans("ThirdParty"), -1, 'company');
 
-    dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
+	$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-    print '<div class="fichecenter">';
+	dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
 
-    print '<div class="underbanner clearboth"></div>';
-    print '<table class="border centpercent">';
+	print '<div class="fichecenter">';
 
-    // Prefix
-    if (!empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
-    {
-        print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>';
-    }
+	print '<div class="underbanner clearboth"></div>';
+	print '<table class="border centpercent">';
 
-    if ($object->client)
-    {
-        print '<tr><td class="titlefield">';
-        print $langs->trans('CustomerCode').'</td><td colspan="3">';
-        print $object->code_client;
-        if ($object->check_codeclient() <> 0) print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>';
-        print '</td></tr>';
-    }
+	// Prefix
+	if (!empty($conf->global->SOCIETE_USEPREFIX))  // Old not used prefix field
+	{
+		print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>';
+	}
 
-    if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire))
-    {
-        print '<tr><td class="titlefield">';
-        print $langs->trans('SupplierCode').'</td><td colspan="3">';
-        print $object->code_fournisseur;
-        if ($object->check_codefournisseur() <> 0) print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>';
-        print '</td></tr>';
-    }
+	if ($object->client)
+	{
+		print '<tr><td class="titlefield">';
+		print $langs->trans('CustomerCode').'</td><td colspan="3">';
+		print $object->code_client;
+		if ($object->check_codeclient() <> 0) print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>';
+		print '</td></tr>';
+	}
+
+	if (!empty($conf->fournisseur->enabled) && $object->fournisseur && !empty($user->rights->fournisseur->lire))
+	{
+		print '<tr><td class="titlefield">';
+		print $langs->trans('SupplierCode').'</td><td colspan="3">';
+		print $object->code_fournisseur;
+		if ($object->check_codefournisseur() <> 0) print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>';
+		print '</td></tr>';
+	}
 
-    /*print '<tr><td class="titlefield">'.$langs->trans("NbOfActiveNotifications").'</td>';   // Notification for this thirdparty
+	/*print '<tr><td class="titlefield">'.$langs->trans("NbOfActiveNotifications").'</td>';   // Notification for this thirdparty
     print '<td colspan="3">';
     $nbofrecipientemails=0;
     $notify=new Notify($db);
@@ -195,159 +195,159 @@ if ($result > 0)
     print $nbofrecipientemails;
     print '</td></tr>';*/
 
-    print '</table>';
+	print '</table>';
 
-    print '</div>';
+	print '</div>';
 
-    dol_fiche_end();
+	dol_fiche_end();
 
-    print "\n";
+	print "\n";
 
-    // Help
-    print '<div class="opacitymedium">';
-    print $langs->trans("NotificationsDesc");
-    print '<br>'.$langs->trans("NotificationsDescUser");
-    print '<br>'.$langs->trans("NotificationsDescContact");
-    print '<br>'.$langs->trans("NotificationsDescGlobal");
+	// Help
+	print '<div class="opacitymedium">';
+	print $langs->trans("NotificationsDesc");
+	print '<br>'.$langs->trans("NotificationsDescUser");
+	print '<br>'.$langs->trans("NotificationsDescContact");
+	print '<br>'.$langs->trans("NotificationsDescGlobal");
 	print '</div>';
 
-    print '<br><br>'."\n";
+	print '<br><br>'."\n";
 
 
-    // Add notification form
-    print load_fiche_titre($langs->trans("AddNewNotification"), '', '');
+	// Add notification form
+	print load_fiche_titre($langs->trans("AddNewNotification"), '', '');
 
-    print '<form action="'.$_SERVER["PHP_SELF"].'?socid='.$socid.'" method="post">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    print '<input type="hidden" name="action" value="add">';
+	print '<form action="'.$_SERVER["PHP_SELF"].'?socid='.$socid.'" method="post">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="action" value="add">';
 
-    $param = "&socid=".$socid;
+	$param = "&socid=".$socid;
 
-    // Line with titles
-    print '<table width="100%" class="noborder">';
-    print '<tr class="liste_titre">';
-    print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '"width="45%"', $sortfield, $sortorder);
-    print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '"width="35%"', $sortfield, $sortorder);
-    print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '"width="10%"', $sortfield, $sortorder);
-    print_liste_field_titre('');
+	// Line with titles
+	print '<table width="100%" class="noborder">';
+	print '<tr class="liste_titre">';
+	print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '"width="45%"', $sortfield, $sortorder);
+	print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '"width="35%"', $sortfield, $sortorder);
+	print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '"width="10%"', $sortfield, $sortorder);
+	print_liste_field_titre('');
 	print "</tr>\n";
 
-    $var = false;
-    $listofemails = $object->thirdparty_and_contact_email_array();
-    if (count($listofemails) > 0)
-    {
-        $actions = array();
+	$var = false;
+	$listofemails = $object->thirdparty_and_contact_email_array();
+	if (count($listofemails) > 0)
+	{
+		$actions = array();
 
-        // Load array of available notifications
-        $notificationtrigger = new InterfaceNotification($db);
-        $listofmanagedeventfornotification = $notificationtrigger->getListOfManagedEvents();
+		// Load array of available notifications
+		$notificationtrigger = new InterfaceNotification($db);
+		$listofmanagedeventfornotification = $notificationtrigger->getListOfManagedEvents();
 
-        foreach ($listofmanagedeventfornotification as $managedeventfornotification)
-        {
+		foreach ($listofmanagedeventfornotification as $managedeventfornotification)
+		{
  			$label = ($langs->trans("Notify_".$managedeventfornotification['code']) != "Notify_".$managedeventfornotification['code'] ? $langs->trans("Notify_".$managedeventfornotification['code']) : $managedeventfornotification['label']);
-            $actions[$managedeventfornotification['rowid']] = $label;
-        }
-        print '<tr class="oddeven nohover"><td class="maxwidthonsmartphone">';
-        print img_picto('', 'contact', '', false, 0, 0, '', 'paddingright').$form->selectarray("contactid", $listofemails, '', 0, 0, 0, '', 0, 0, 0, '', 'maxwidthonsmartphone');
-        print '</td>';
-        print '<td class="maxwidthonsmartphone">';
-        print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$form->selectarray("actionid", $actions, '', 1, 0, 0, '', 0, 0, 0, '', 'maxwidthonsmartphone');
-        print '</td>';
-        print '<td>';
-        $type = array('email'=>$langs->trans("EMail"));
-        print $form->selectarray("typeid", $type);
-        print '</td>';
-        print '<td class="right"><input type="submit" class="button" value="'.$langs->trans("Add").'"></td>';
-        print '</tr>';
-    } else {
-        print '<tr class="oddeven"><td colspan="4" class="opacitymedium">';
-        print $langs->trans("YouMustCreateContactFirst");
-        print '</td></tr>';
-    }
-
-    print '</table>';
-
-
-    print '</form>';
-    print '<br>';
-
-
-    // List of notifications enabled for contacts
-    $sql = "SELECT n.rowid, n.type,";
-    $sql .= " a.code, a.label,";
-    $sql .= " c.rowid as contactid, c.lastname, c.firstname, c.email";
-    $sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
-    $sql .= " ".MAIN_DB_PREFIX."notify_def as n,";
-    $sql .= " ".MAIN_DB_PREFIX."socpeople c";
-    $sql .= " WHERE a.rowid = n.fk_action";
-    $sql .= " AND c.rowid = n.fk_contact";
-    $sql .= " AND c.fk_soc = ".$object->id;
-
-    $resql = $db->query($sql);
-    if ($resql)
-    {
-        $num = $db->num_rows($resql);
-    } else {
-        dol_print_error($db);
-    }
-
-    // List of active notifications
-    print load_fiche_titre($langs->trans("ListOfActiveNotifications").' ('.$num.')', '', '');
-
-    // Line with titles
-    print '<table width="100%" class="noborder">';
-    print '<tr class="liste_titre">';
-    print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '"width="45%"', $sortfield, $sortorder);
-    print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '"width="35%"', $sortfield, $sortorder);
-    print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '"width="10%"', $sortfield, $sortorder);
-    print_liste_field_titre('', '', '');
-    print '</tr>';
+			$actions[$managedeventfornotification['rowid']] = $label;
+		}
+		print '<tr class="oddeven nohover"><td class="maxwidthonsmartphone">';
+		print img_picto('', 'contact', '', false, 0, 0, '', 'paddingright').$form->selectarray("contactid", $listofemails, '', 0, 0, 0, '', 0, 0, 0, '', 'maxwidthonsmartphone');
+		print '</td>';
+		print '<td class="maxwidthonsmartphone">';
+		print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$form->selectarray("actionid", $actions, '', 1, 0, 0, '', 0, 0, 0, '', 'maxwidthonsmartphone');
+		print '</td>';
+		print '<td>';
+		$type = array('email'=>$langs->trans("EMail"));
+		print $form->selectarray("typeid", $type);
+		print '</td>';
+		print '<td class="right"><input type="submit" class="button" value="'.$langs->trans("Add").'"></td>';
+		print '</tr>';
+	} else {
+		print '<tr class="oddeven"><td colspan="4" class="opacitymedium">';
+		print $langs->trans("YouMustCreateContactFirst");
+		print '</td></tr>';
+	}
+
+	print '</table>';
+
+
+	print '</form>';
+	print '<br>';
+
+
+	// List of notifications enabled for contacts
+	$sql = "SELECT n.rowid, n.type,";
+	$sql .= " a.code, a.label,";
+	$sql .= " c.rowid as contactid, c.lastname, c.firstname, c.email";
+	$sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
+	$sql .= " ".MAIN_DB_PREFIX."notify_def as n,";
+	$sql .= " ".MAIN_DB_PREFIX."socpeople c";
+	$sql .= " WHERE a.rowid = n.fk_action";
+	$sql .= " AND c.rowid = n.fk_contact";
+	$sql .= " AND c.fk_soc = ".$object->id;
+
+	$resql = $db->query($sql);
+	if ($resql)
+	{
+		$num = $db->num_rows($resql);
+	} else {
+		dol_print_error($db);
+	}
+
+	// List of active notifications
+	print load_fiche_titre($langs->trans("ListOfActiveNotifications").' ('.$num.')', '', '');
+
+	// Line with titles
+	print '<table width="100%" class="noborder">';
+	print '<tr class="liste_titre">';
+	print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '"width="45%"', $sortfield, $sortorder);
+	print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '"width="35%"', $sortfield, $sortorder);
+	print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '"width="10%"', $sortfield, $sortorder);
+	print_liste_field_titre('', '', '');
+	print '</tr>';
 
 	$langs->load("errors");
 	$langs->load("other");
 
-    if ($num)
-    {
-        $i = 0;
+	if ($num)
+	{
+		$i = 0;
 
-        $contactstatic = new Contact($db);
+		$contactstatic = new Contact($db);
 
-        while ($i < $num)
-        {
-            $obj = $db->fetch_object($resql);
+		while ($i < $num)
+		{
+			$obj = $db->fetch_object($resql);
 
-            $contactstatic->id = $obj->contact_id;
-            $contactstatic->lastname = $obj->lastname;
-            $contactstatic->firstname = $obj->firstname;
-            print '<tr class="oddeven"><td>'.$contactstatic->getNomUrl(1);
-            if ($obj->type == 'email')
-            {
-                if (isValidEmail($obj->email))
-                {
-                    print ' &lt;'.$obj->email.'&gt;';
-                } else {
-                    $langs->load("errors");
-                    print ' &nbsp; '.img_warning().' '.$langs->trans("ErrorBadEMail", $obj->email);
-                }
-            }
-            print '</td>';
-            print '<td>';
-            $label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
-            print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$label;
-            print '</td>';
-            print '<td>';
-            if ($obj->type == 'email') print $langs->trans("Email");
-            if ($obj->type == 'sms') print $langs->trans("SMS");
-            print '</td>';
-            print '<td class="right"><a href="card.php?socid='.$socid.'&action=delete&token='.newToken().'&actid='.$obj->rowid.'">'.img_delete().'</a></td>';
-            print '</tr>';
-            $i++;
-        }
-        $db->free($resql);
-    }
+			$contactstatic->id = $obj->contact_id;
+			$contactstatic->lastname = $obj->lastname;
+			$contactstatic->firstname = $obj->firstname;
+			print '<tr class="oddeven"><td>'.$contactstatic->getNomUrl(1);
+			if ($obj->type == 'email')
+			{
+				if (isValidEmail($obj->email))
+				{
+					print ' &lt;'.$obj->email.'&gt;';
+				} else {
+					$langs->load("errors");
+					print ' &nbsp; '.img_warning().' '.$langs->trans("ErrorBadEMail", $obj->email);
+				}
+			}
+			print '</td>';
+			print '<td>';
+			$label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
+			print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$label;
+			print '</td>';
+			print '<td>';
+			if ($obj->type == 'email') print $langs->trans("Email");
+			if ($obj->type == 'sms') print $langs->trans("SMS");
+			print '</td>';
+			print '<td class="right"><a href="card.php?socid='.$socid.'&action=delete&token='.newToken().'&actid='.$obj->rowid.'">'.img_delete().'</a></td>';
+			print '</tr>';
+			$i++;
+		}
+		$db->free($resql);
+	}
 
-    // List of notifications enabled for fixed email
-    /*
+	// List of notifications enabled for fixed email
+	/*
     foreach($conf->global as $key => $val)
     {
     	if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_(.*)/', $key, $reg)) continue;
@@ -389,7 +389,7 @@ if ($result > 0)
 		print '</tr>';
     }*/
 
-    /*if ($user->admin)
+	/*if ($user->admin)
     {
 	    $var = ! $var;
 		print '<tr class="oddeven"><td colspan="4">';
@@ -397,104 +397,104 @@ if ($result > 0)
 		print '</td></tr>';
     }*/
 
-    print '</table>';
+	print '</table>';
 
 
-    print '<br><br>'."\n";
+	print '<br><br>'."\n";
 
 
-    // List
-    $sql = "SELECT n.rowid, n.daten, n.email, n.objet_type as object_type, n.objet_id as object_id, n.type,";
-    $sql .= " c.rowid as id, c.lastname, c.firstname, c.email as contactemail,";
-    $sql .= " a.code, a.label";
-    $sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
-    $sql .= " ".MAIN_DB_PREFIX."notify as n ";
-    $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as c ON n.fk_contact = c.rowid";
-    $sql .= " WHERE a.rowid = n.fk_action";
-    $sql .= " AND n.fk_soc = ".$object->id;
-    $sql .= $db->order($sortfield, $sortorder);
+	// List
+	$sql = "SELECT n.rowid, n.daten, n.email, n.objet_type as object_type, n.objet_id as object_id, n.type,";
+	$sql .= " c.rowid as id, c.lastname, c.firstname, c.email as contactemail,";
+	$sql .= " a.code, a.label";
+	$sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
+	$sql .= " ".MAIN_DB_PREFIX."notify as n ";
+	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as c ON n.fk_contact = c.rowid";
+	$sql .= " WHERE a.rowid = n.fk_action";
+	$sql .= " AND n.fk_soc = ".$object->id;
+	$sql .= $db->order($sortfield, $sortorder);
 
-    // Count total nb of records
-    $nbtotalofrecords = '';
-    if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-    {
-        $result = $db->query($sql);
-        $nbtotalofrecords = $db->num_rows($result);
-        if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
-        {
-        	$page = 0;
-        	$offset = 0;
-        }
-    }
-
-    $sql .= $db->plimit($limit + 1, $offset);
-
-    $resql = $db->query($sql);
-    if ($resql)
-    {
-        $num = $db->num_rows($resql);
-    } else {
-        dol_print_error($db);
-    }
-
-    $param = '&socid='.$object->id;
-    if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
-    if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
-
-    print '<form method="post" action="'.$_SERVER["PHP_SELF"].'" name="formfilter">';
-    if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
-    print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
-    print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
-    print '<input type="hidden" name="page" value="'.$page.'">';
-    print '<input type="hidden" name="socid" value="'.$object->id.'">';
-
-    // List of active notifications
-    print_barre_liste($langs->trans("ListOfNotificationsDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit);
-
-    // Line with titles
-    print '<table width="100%" class="noborder">';
-    print '<tr class="liste_titre">';
-    print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '', $sortfield, $sortorder);
-    print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder);
-    print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '', $sortfield, $sortorder);
-    //print_liste_field_titre("Object",$_SERVER["PHP_SELF"],"",'',$param,'"',$sortfield,$sortorder);
-    print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "n.daten", '', $param, '', $sortfield, $sortorder, 'right ');
-    print '</tr>';
-
-    if ($num > 0)
-    {
-        $i = 0;
-
-        $contactstatic = new Contact($db);
-
-        while ($i < $num)
-        {
-            $obj = $db->fetch_object($resql);
+	// Count total nb of records
+	$nbtotalofrecords = '';
+	if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
+	{
+		$result = $db->query($sql);
+		$nbtotalofrecords = $db->num_rows($result);
+		if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
+		{
+			$page = 0;
+			$offset = 0;
+		}
+	}
+
+	$sql .= $db->plimit($limit + 1, $offset);
+
+	$resql = $db->query($sql);
+	if ($resql)
+	{
+		$num = $db->num_rows($resql);
+	} else {
+		dol_print_error($db);
+	}
+
+	$param = '&socid='.$object->id;
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
+	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
+
+	print '<form method="post" action="'.$_SERVER["PHP_SELF"].'" name="formfilter">';
+	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
+	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
+	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
+	print '<input type="hidden" name="page" value="'.$page.'">';
+	print '<input type="hidden" name="socid" value="'.$object->id.'">';
+
+	// List of active notifications
+	print_barre_liste($langs->trans("ListOfNotificationsDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit);
+
+	// Line with titles
+	print '<table width="100%" class="noborder">';
+	print '<tr class="liste_titre">';
+	print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '', $sortfield, $sortorder);
+	print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder);
+	print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '', $sortfield, $sortorder);
+	//print_liste_field_titre("Object",$_SERVER["PHP_SELF"],"",'',$param,'"',$sortfield,$sortorder);
+	print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "n.daten", '', $param, '', $sortfield, $sortorder, 'right ');
+	print '</tr>';
+
+	if ($num > 0)
+	{
+		$i = 0;
+
+		$contactstatic = new Contact($db);
+
+		while ($i < $num)
+		{
+			$obj = $db->fetch_object($resql);
 
-            print '<tr class="oddeven"><td>';
-            if ($obj->id > 0)
-            {
-	            $contactstatic->id = $obj->id;
-	            $contactstatic->lastname = $obj->lastname;
-	            $contactstatic->firstname = $obj->firstname;
-	            print $contactstatic->getNomUrl(1);
-	            print $obj->email ? ' &lt;'.$obj->email.'&gt;' : $langs->trans("NoMail");
-            } else {
+			print '<tr class="oddeven"><td>';
+			if ($obj->id > 0)
+			{
+				$contactstatic->id = $obj->id;
+				$contactstatic->lastname = $obj->lastname;
+				$contactstatic->firstname = $obj->firstname;
+				print $contactstatic->getNomUrl(1);
+				print $obj->email ? ' &lt;'.$obj->email.'&gt;' : $langs->trans("NoMail");
+			} else {
 				print $obj->email;
-            }
-            print '</td>';
-            print '<td>';
-            $label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
-            print $label;
-            print '</td>';
-            print '<td>';
-            if ($obj->type == 'email') print $langs->trans("Email");
-            if ($obj->type == 'sms') print $langs->trans("Sms");
-            print '</td>';
-            // TODO Add link to object here for other types
-            /*print '<td>';
+			}
+			print '</td>';
+			print '<td>';
+			$label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
+			print $label;
+			print '</td>';
+			print '<td>';
+			if ($obj->type == 'email') print $langs->trans("Email");
+			if ($obj->type == 'sms') print $langs->trans("Sms");
+			print '</td>';
+			// TODO Add link to object here for other types
+			/*print '<td>';
             if ($obj->object_type == 'order')
             {
 				$orderstatic->id=$obj->object_id;
@@ -502,19 +502,19 @@ if ($result > 0)
 				print $orderstatic->getNomUrl(1);
             }
            	print '</td>';*/
-            // print
-            print'<td class="right">'.dol_print_date($db->jdate($obj->daten), 'dayhour').'</td>';
-            print '</tr>';
-            $i++;
-        }
-        $db->free($resql);
-    } else {
-    	print '<tr><td colspan="4"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
-    }
+			// print
+			print'<td class="right">'.dol_print_date($db->jdate($obj->daten), 'dayhour').'</td>';
+			print '</tr>';
+			$i++;
+		}
+		$db->free($resql);
+	} else {
+		print '<tr><td colspan="4"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
+	}
 
-    print '</table>';
+	print '</table>';
 
-    print '</form>';
+	print '</form>';
 } else dol_print_error('', 'RecordNotFound');
 
 // End of page

+ 68 - 68
htdocs/societe/paymentmodes.php

@@ -550,12 +550,12 @@ if (empty($reshook))
 
 			$db->begin();
 
-            if (empty($newcu)) {
-                $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_account WHERE site = 'stripe' AND (site_account IS NULL or site_account = '' or site_account = '".$db->escape($site_account)."') AND fk_soc = ".$object->id." AND status = ".$servicestatus." AND entity = ".$conf->entity;
-            } else {
-                $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX."societe_account";
-                $sql .= " WHERE site = 'stripe' AND (site_account IS NULL or site_account = '' or site_account = '".$db->escape($site_account)."') AND fk_soc = ".$object->id." AND status = ".$servicestatus." AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
-            }
+			if (empty($newcu)) {
+				$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_account WHERE site = 'stripe' AND (site_account IS NULL or site_account = '' or site_account = '".$db->escape($site_account)."') AND fk_soc = ".$object->id." AND status = ".$servicestatus." AND entity = ".$conf->entity;
+			} else {
+				$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX."societe_account";
+				$sql .= " WHERE site = 'stripe' AND (site_account IS NULL or site_account = '' or site_account = '".$db->escape($site_account)."') AND fk_soc = ".$object->id." AND status = ".$servicestatus." AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
+			}
 
 			$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.
@@ -601,21 +601,21 @@ if (empty($reshook))
 
 			$db->begin();
 
-            if (empty($newsup)) {
-                $sql = "DELETE FROM ".MAIN_DB_PREFIX."oauth_token WHERE fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity;
-                // TODO Add site and site_account on oauth_token table
-                //$sql = "DELETE FROM ".MAIN_DB_PREFIX."oauth_token WHERE site = 'stripe' AND (site_account IS NULL or site_account = '".$db->escape($site_account)."') AND fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity;
-            } else {
-                try {
-                    $stripesup = \Stripe\Account::retrieve($db->escape(GETPOST('key_account_supplier', 'alpha')));
-                    $tokenstring['stripe_user_id'] = $stripesup->id;
-                    $tokenstring['type'] = $stripesup->type;
-                    $sql = "UPDATE ".MAIN_DB_PREFIX."oauth_token";
-                    $sql .= " SET tokenstring = '".dol_json_encode($tokenstring)."'";
-                    $sql .= " WHERE site = 'stripe' AND (site_account IS NULL or site_account = '".$db->escape($site_account)."') AND fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
-                    // TODO Add site and site_account on oauth_token table
-                    $sql .= " WHERE fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
-                } catch (Exception $e) {
+			if (empty($newsup)) {
+				$sql = "DELETE FROM ".MAIN_DB_PREFIX."oauth_token WHERE fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity;
+				// TODO Add site and site_account on oauth_token table
+				//$sql = "DELETE FROM ".MAIN_DB_PREFIX."oauth_token WHERE site = 'stripe' AND (site_account IS NULL or site_account = '".$db->escape($site_account)."') AND fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity;
+			} else {
+				try {
+					$stripesup = \Stripe\Account::retrieve($db->escape(GETPOST('key_account_supplier', 'alpha')));
+					$tokenstring['stripe_user_id'] = $stripesup->id;
+					$tokenstring['type'] = $stripesup->type;
+					$sql = "UPDATE ".MAIN_DB_PREFIX."oauth_token";
+					$sql .= " SET tokenstring = '".dol_json_encode($tokenstring)."'";
+					$sql .= " WHERE site = 'stripe' AND (site_account IS NULL or site_account = '".$db->escape($site_account)."') AND fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
+					// TODO Add site and site_account on oauth_token table
+					$sql .= " WHERE fk_soc = ".$object->id." AND service = '".$db->escape($service)."' AND entity = ".$conf->entity; // Keep = here for entity. Only 1 record must be modified !
+				} catch (Exception $e) {
 					$error++;
 					setEventMessages($e->getMessage(), null, 'errors');
 				}
@@ -625,14 +625,14 @@ if (empty($reshook))
 			$num = $db->num_rows($resql);
 			if (empty($num) && !empty($newsup))
 			{
-                try {
-                    $stripesup = \Stripe\Account::retrieve($db->escape(GETPOST('key_account_supplier', 'alpha')));
-                    $tokenstring['stripe_user_id'] = $stripesup->id;
-                    $tokenstring['type'] = $stripesup->type;
-                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token (service, fk_soc, entity, tokenstring)";
-                    $sql .= " VALUES ('".$db->escape($service)."', ".$object->id.", ".$conf->entity.", '".dol_json_encode($tokenstring)."')";
-                    // TODO Add site and site_account on oauth_token table
-                } catch (Exception $e) {
+				try {
+					$stripesup = \Stripe\Account::retrieve($db->escape(GETPOST('key_account_supplier', 'alpha')));
+					$tokenstring['stripe_user_id'] = $stripesup->id;
+					$tokenstring['type'] = $stripesup->type;
+					$sql = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token (service, fk_soc, entity, tokenstring)";
+					$sql .= " VALUES ('".$db->escape($service)."', ".$object->id.", ".$conf->entity.", '".dol_json_encode($tokenstring)."')";
+					// TODO Add site and site_account on oauth_token table
+				} catch (Exception $e) {
 					$error++;
 					setEventMessages($e->getMessage(), null, 'errors');
 				}
@@ -686,22 +686,22 @@ if (empty($reshook))
 			try {
 				if (preg_match('/pm_/', $source))
 				{
-                    $payment_method = \Stripe\PaymentMethod::retrieve($source, array("stripe_account" => $stripeacc));
-                    if ($payment_method)
-			        {
-					    $payment_method->detach();
-				    }
+					$payment_method = \Stripe\PaymentMethod::retrieve($source, array("stripe_account" => $stripeacc));
+					if ($payment_method)
+					{
+						$payment_method->detach();
+					}
 				} else {
-				    $cu = $stripe->customerStripe($object, $stripeacc, $servicestatus);
-				    $card = $cu->sources->retrieve("$source");
-				    if ($card) {
-					    // $card->detach();  Does not work with card_, only with src_
-					    if (method_exists($card, 'detach')) {
+					$cu = $stripe->customerStripe($object, $stripeacc, $servicestatus);
+					$card = $cu->sources->retrieve("$source");
+					if ($card) {
+						// $card->detach();  Does not work with card_, only with src_
+						if (method_exists($card, 'detach')) {
 							$card->detach();
 						} else {
 							$card->delete();
 						}
-				    }
+					}
 				}
 
 				$url = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id;
@@ -832,7 +832,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 			print $form->editfieldval("StripeCustomerId", 'key_account', $stripecu, $object, $permissiontowrite, 'string', '', null, null, '', 2, '', 'socid');
 			if (!empty($conf->stripe->enabled) && $stripecu && $action != 'editkey_account')
 			{
-			    $connect = '';
+				$connect = '';
 				if (!empty($stripeacc)) $connect = $stripeacc.'/';
 				$url = 'https://dashboard.stripe.com/'.$connect.'test/customers/'.$stripecu;
 				if ($servicestatus)
@@ -853,7 +853,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 			}
 			print '</td></tr>';
 		}
-    }
+	}
 
 	if ($object->fournisseur)
 	{
@@ -886,7 +886,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 		print $form->editfieldval("StripeConnectAccount", 'key_account_supplier', $stripesupplieracc, $object, $permissiontowrite, 'string', '', null, null, '', 2, '', 'socid');
 		if (!empty($conf->stripe->enabled) && $stripesupplieracc && $action != 'editkey_account_supplier')
 		{
-		    $connect = '';
+			$connect = '';
 
 			$url = 'https://dashboard.stripe.com/test/connect/accounts/'.$stripesupplieracc;
 			if ($servicestatus)
@@ -922,7 +922,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 		$morehtmlright = '';
 		if (!empty($conf->global->STRIPE_ALLOW_LOCAL_CARD))
 		{
-            $morehtmlright .= dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=createcard');
+			$morehtmlright .= dolGetButtonTitle($langs->trans('Add'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?socid='.$object->id.'&amp;action=createcard');
 		}
 		print load_fiche_titre($langs->trans('StripePaymentModes').($stripeacc ? ' (Stripe connection with StripeConnect account '.$stripeacc.')' : ' (Stripe connection with keys from Stripe module setup)'), $morehtmlright, 'stripe-s');
 
@@ -1038,9 +1038,9 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 							print $companypaymentmodetemp->stripe_card_ref;
 							if ($companypaymentmodetemp->stripe_card_ref)
 							{
-							    $connect = '';
-							    if (!empty($stripeacc)) $connect = $stripeacc.'/';
-							    $url = 'https://dashboard.stripe.com/'.$connect.'test/search?query='.$companypaymentmodetemp->stripe_card_ref;
+								$connect = '';
+								if (!empty($stripeacc)) $connect = $stripeacc.'/';
+								$url = 'https://dashboard.stripe.com/'.$connect.'test/search?query='.$companypaymentmodetemp->stripe_card_ref;
 								if ($servicestatus)
 								{
 									$url = 'https://dashboard.stripe.com/'.$connect.'search?query='.$companypaymentmodetemp->stripe_card_ref;
@@ -1138,8 +1138,8 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 				$url = 'https://dashboard.stripe.com/'.$connect.'test/search?query='.$src->id;
 				if ($servicestatus)
 				{
-				    //$url='https://dashboard.stripe.com/'.$connect.'sources/'.$src->id;
-				    $url = 'https://dashboard.stripe.com/'.$connect.'search?query='.$src->id;
+					//$url='https://dashboard.stripe.com/'.$connect.'sources/'.$src->id;
+					$url = 'https://dashboard.stripe.com/'.$connect.'search?query='.$src->id;
 				}
 				print " <a href='".$url."' target='_stripe'>".img_picto($langs->trans('ShowInStripe'), 'globe')."</a>";
 				print '</td>';
@@ -1266,30 +1266,30 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 		}
 		print "</table>";
 		print "</div>";
-        print '<br>';
+		print '<br>';
 	}
 
   	// List of Stripe payment modes
 	if (!empty($conf->stripe->enabled) && !empty($conf->stripeconnect->enabled) && !empty($stripesupplieracc))
 	{
-        print load_fiche_titre($langs->trans('StripeBalance').($stripesupplieracc ? ' (Stripe connection with StripeConnect account '.$stripesupplieracc.')' : ' (Stripe connection with keys from Stripe module setup)'), $morehtmlright, 'stripe-s');
-        $balance = \Stripe\Balance::retrieve(array("stripe_account" => $stripesupplieracc));
+		print load_fiche_titre($langs->trans('StripeBalance').($stripesupplieracc ? ' (Stripe connection with StripeConnect account '.$stripesupplieracc.')' : ' (Stripe connection with keys from Stripe module setup)'), $morehtmlright, 'stripe-s');
+		$balance = \Stripe\Balance::retrieve(array("stripe_account" => $stripesupplieracc));
 		print '<table class="liste centpercent">'."\n";
 		print '<tr class="liste_titre">';
 		print '<td>'.$langs->trans('Currency').'</td>';
 		print '<td>'.$langs->trans('Available').'</td>';
 		print '<td>'.$langs->trans('Pending').'</td>';
-        print '<td>'.$langs->trans('Total').'</td>';
-        print '</tr>';
+		print '<td>'.$langs->trans('Total').'</td>';
+		print '</tr>';
 
-        $currencybalance = array();
+		$currencybalance = array();
 		if (is_array($balance->available) && count($balance->available))
 		{
 			foreach ($balance->available as $cpt)
 			{
-		        $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;
+				$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 {
 					$currencybalance[$cpt->currency]['available'] = $cpt->amount;
 				}
@@ -1297,7 +1297,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 			}
 		}
 
-        if (is_array($balance->pending) && count($balance->pending))
+		if (is_array($balance->pending) && count($balance->pending))
 		{
 			foreach ($balance->pending as $cpt)
 			{
@@ -1308,7 +1308,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 					$currencybalance[$cpt->currency]['pending'] = $currencybalance[$cpt->currency]['available'] + $cpt->amount;
 				}
 			}
-        }
+		}
 
 		if (is_array($currencybalance))
 		{
@@ -1318,13 +1318,13 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 			}
 		}
 
-        print '</table>';
-        print '<br>';
+		print '</table>';
+		print '<br>';
 	}
 
 	// 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, 'bank');
 
@@ -1371,11 +1371,11 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
 				} elseif ($val == 'BankAccountNumberKey') {
 					$string .= $rib->cle_rib.' ';
 				}
-                // Already output after
-                // } elseif ($val == 'BIC') {
-                //     $string .= $rib->bic.' ';
-                // } elseif ($val == 'IBAN') {
-                //     $string .= $rib->iban.' ';*/
+				// Already output after
+				// } elseif ($val == 'BIC') {
+				//     $string .= $rib->bic.' ';
+				// } elseif ($val == 'IBAN') {
+				//     $string .= $rib->iban.' ';*/
 				//}
 			}
 			if (!empty($rib->label) && $rib->number) {

+ 215 - 215
htdocs/societe/price.php

@@ -71,112 +71,112 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
 
 if (empty($reshook))
 {
-    if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers
-    {
-        $search_prod = $search_label = $search_price = $search_price_ttc = '';
-    }
-
-    if ($action == 'add_customer_price_confirm' && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) {
-    	if (! (GETPOST('prodid', 'int') > 0)) {
-    		$error++;
-    		setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Product")), null, 'errors');
-    		$action = 'add_customer_price';
-    	}
-
-    	if (! $error) {
-	    	$update_child_soc = GETPOST('updatechildprice');
-
-	    	// add price by customer
-	    	$prodcustprice->fk_soc = $socid;
-	    	$prodcustprice->fk_product = GETPOST('prodid', 'int');
-	    	$prodcustprice->price = price2num(GETPOST("price"), 'MU');
-	    	$prodcustprice->price_min = price2num(GETPOST("price_min"), 'MU');
-	    	$prodcustprice->price_base_type = GETPOST("price_base_type", 'alpha');
-
-	    	$tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5'  or  '8.5*'  or  '8.5 (XXX)' or '8.5* (XXX)'
-
-	    	// We must define tva_tx, npr and local taxes
-	    	$vatratecode = '';
-	    	$tva_tx = preg_replace('/[^0-9\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot
-	    	$npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0;
-	    	$localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0';
-	    	// If value contains the unique code of vat line (new recommended method), we use it to find npr and local taxes
-	    	if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg))
-	    	{
-	    	    // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in update price.
-	    	    $vatratecode = $reg[1];
-	    	    // Get record from code
-	    	    $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
-	    	    $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
-	    	    $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'";
-	    	    $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1";
-	    	    $sql .= " AND t.code ='".$db->escape($vatratecode)."'";
-	    	    $resql = $db->query($sql);
-	    	    if ($resql)
-	    	    {
-	    	        $obj = $db->fetch_object($resql);
-	    	        $npr = $obj->recuperableonly;
-	    	        $localtax1 = $obj->localtax1;
-	    	        $localtax2 = $obj->localtax2;
-	    	        $localtax1_type = $obj->localtax1_type;
-	    	        $localtax2_type = $obj->localtax2_type;
-	    	    }
-	    	}
-
-	    	$prodcustprice->default_vat_code = $vatratecode;
-	    	$prodcustprice->tva_tx = $tva_tx;
-	    	$prodcustprice->recuperableonly = $npr;
-	    	$prodcustprice->localtax1_tx = $localtax1;
-	    	$prodcustprice->localtax2_tx = $localtax2;
-	    	$prodcustprice->localtax1_type = $localtax1_type;
-	    	$prodcustprice->localtax2_type = $localtax2_type;
-
-	    	$result = $prodcustprice->create($user, 0, $update_child_soc);
-
-	    	if ($result < 0) {
-	    		setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
-	    	} else {
-	    		setEventMessages($langs->trans('Save'), null, 'mesgs');
-	    	}
-
-	    	$action = '';
-    	}
-    }
-
-    if ($action == 'delete_customer_price' && ($user->rights->produit->creer || $user->rights->service->creer)) {
-    	// Delete price by customer
-    	$prodcustprice->id = GETPOST('lineid');
-    	$result = $prodcustprice->delete($user);
-
-    	if ($result < 0) {
-    		setEventMessages($prodcustprice->error, $prodcustprice->errors, 'mesgs');
-    	} else {
-    		setEventMessages($langs->trans('Delete'), null, 'errors');
-    	}
-    	$action = '';
-    }
-
-    if ($action == 'update_customer_price_confirm' && !$_POST ["cancel"] && ($user->rights->produit->creer || $user->rights->service->creer)) {
-    	$prodcustprice->fetch(GETPOST('lineid', 'int'));
-
-    	$update_child_soc = GETPOST('updatechildprice');
-
-    	// update price by customer
-    	$prodcustprice->price = price2num(GETPOST("price"), 'MU');
-    	$prodcustprice->price_min = price2num(GETPOST("price_min"), 'MU');
-    	$prodcustprice->price_base_type = GETPOST("price_base_type", 'alpha');
-    	$prodcustprice->tva_tx = str_replace('*', '', GETPOST("tva_tx"));
-    	$prodcustprice->recuperableonly = (preg_match('/\*/', GETPOST("tva_tx")) ? 1 : 0);
-
-    	$result = $prodcustprice->update($user, 0, $update_child_soc);
-    	if ($result < 0) {
-    		setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
-    	} else {
-    		setEventMessages($langs->trans('Save'), null, 'mesgs');
-    	}
-
-    	$action = '';
-    }
+	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers
+	{
+		$search_prod = $search_label = $search_price = $search_price_ttc = '';
+	}
+
+	if ($action == 'add_customer_price_confirm' && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) {
+		if (! (GETPOST('prodid', 'int') > 0)) {
+			$error++;
+			setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Product")), null, 'errors');
+			$action = 'add_customer_price';
+		}
+
+		if (! $error) {
+			$update_child_soc = GETPOST('updatechildprice');
+
+			// add price by customer
+			$prodcustprice->fk_soc = $socid;
+			$prodcustprice->fk_product = GETPOST('prodid', 'int');
+			$prodcustprice->price = price2num(GETPOST("price"), 'MU');
+			$prodcustprice->price_min = price2num(GETPOST("price_min"), 'MU');
+			$prodcustprice->price_base_type = GETPOST("price_base_type", 'alpha');
+
+			$tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5'  or  '8.5*'  or  '8.5 (XXX)' or '8.5* (XXX)'
+
+			// We must define tva_tx, npr and local taxes
+			$vatratecode = '';
+			$tva_tx = preg_replace('/[^0-9\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot
+			$npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0;
+			$localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0';
+			// If value contains the unique code of vat line (new recommended method), we use it to find npr and local taxes
+			if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg))
+			{
+				// We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in update price.
+				$vatratecode = $reg[1];
+				// Get record from code
+				$sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
+				$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
+				$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'";
+				$sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1";
+				$sql .= " AND t.code ='".$db->escape($vatratecode)."'";
+				$resql = $db->query($sql);
+				if ($resql)
+				{
+					$obj = $db->fetch_object($resql);
+					$npr = $obj->recuperableonly;
+					$localtax1 = $obj->localtax1;
+					$localtax2 = $obj->localtax2;
+					$localtax1_type = $obj->localtax1_type;
+					$localtax2_type = $obj->localtax2_type;
+				}
+			}
+
+			$prodcustprice->default_vat_code = $vatratecode;
+			$prodcustprice->tva_tx = $tva_tx;
+			$prodcustprice->recuperableonly = $npr;
+			$prodcustprice->localtax1_tx = $localtax1;
+			$prodcustprice->localtax2_tx = $localtax2;
+			$prodcustprice->localtax1_type = $localtax1_type;
+			$prodcustprice->localtax2_type = $localtax2_type;
+
+			$result = $prodcustprice->create($user, 0, $update_child_soc);
+
+			if ($result < 0) {
+				setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
+			} else {
+				setEventMessages($langs->trans('Save'), null, 'mesgs');
+			}
+
+			$action = '';
+		}
+	}
+
+	if ($action == 'delete_customer_price' && ($user->rights->produit->creer || $user->rights->service->creer)) {
+		// Delete price by customer
+		$prodcustprice->id = GETPOST('lineid');
+		$result = $prodcustprice->delete($user);
+
+		if ($result < 0) {
+			setEventMessages($prodcustprice->error, $prodcustprice->errors, 'mesgs');
+		} else {
+			setEventMessages($langs->trans('Delete'), null, 'errors');
+		}
+		$action = '';
+	}
+
+	if ($action == 'update_customer_price_confirm' && !$_POST ["cancel"] && ($user->rights->produit->creer || $user->rights->service->creer)) {
+		$prodcustprice->fetch(GETPOST('lineid', 'int'));
+
+		$update_child_soc = GETPOST('updatechildprice');
+
+		// update price by customer
+		$prodcustprice->price = price2num(GETPOST("price"), 'MU');
+		$prodcustprice->price_min = price2num(GETPOST("price_min"), 'MU');
+		$prodcustprice->price_base_type = GETPOST("price_base_type", 'alpha');
+		$prodcustprice->tva_tx = str_replace('*', '', GETPOST("tva_tx"));
+		$prodcustprice->recuperableonly = (preg_match('/\*/', GETPOST("tva_tx")) ? 1 : 0);
+
+		$result = $prodcustprice->update($user, 0, $update_child_soc);
+		if ($result < 0) {
+			setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
+		} else {
+			setEventMessages($langs->trans('Save'), null, 'mesgs');
+		}
+
+		$action = '';
+	}
 }
 
 
@@ -242,7 +242,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
 
 	$sortfield = GETPOST("sortfield", 'alpha');
 	$sortorder = GETPOST("sortorder", 'alpha');
-    $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
+	$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
 	$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
 	if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
 	$offset = $limit * $page;
@@ -262,15 +262,15 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
 		$filter ['prod.ref'] = $search_prod;
 	}
 
-	if (! empty($search_label)) {
+	if (!empty($search_label)) {
 		$filter ['prod.label'] = $search_label;
 	}
 
-	if (! empty($search_price)) {
+	if (!empty($search_price)) {
 		$filter ['t.price'] = $search_price;
 	}
 
-	if (! empty($search_price_ttc)) {
+	if (!empty($search_price_ttc)) {
 		$filter ['t.price_ttc'] = $search_price_ttc;
 	}
 
@@ -429,7 +429,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
 
 		print '<br></form>';
 	} elseif ($action == 'showlog_customer_price') {
-	    print '<br>';
+		print '<br>';
 		print '<!-- showlog_customer_price -->'."\n";
 
 		$filter = array(
@@ -503,7 +503,7 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
 		print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?socid='.$object->id.'">'.$langs->trans("Ok").'</a></div>';
 		print "\n</div><br>\n";
 	} else {
-        // View mode
+		// View mode
 
 		/* ************************************************************************** */
 		/*                                                                            */
@@ -519,118 +519,118 @@ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
 		print "\n</div>\n";
 
 
-        // Count total nb of records
-        $nbtotalofrecords = '';
-        if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-        {
-            $nbtotalofrecords = $prodcustprice->fetch_all('', '', 0, 0, $filter);
-        }
+		// Count total nb of records
+		$nbtotalofrecords = '';
+		if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
+		{
+			$nbtotalofrecords = $prodcustprice->fetch_all('', '', 0, 0, $filter);
+		}
 
-        $result = $prodcustprice->fetch_all($sortorder, $sortfield, $conf->liste_limit, $offset, $filter);
-        if ($result < 0)
-        {
-            setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
-        }
+		$result = $prodcustprice->fetch_all($sortorder, $sortfield, $conf->liste_limit, $offset, $filter);
+		if ($result < 0)
+		{
+			setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
+		}
 
-        $option = '&search_prod=' . $search_prod . '&id=' . $object->id . '&label=' . $search_label .'&price=' . $search_price . '&price_ttc=' . $search_price_ttc;
+		$option = '&search_prod=' . $search_prod . '&id=' . $object->id . '&label=' . $search_label .'&price=' . $search_price . '&price_ttc=' . $search_price_ttc;
 
-	    print '<!-- view specific price for each product -->'."\n";
+		print '<!-- view specific price for each product -->'."\n";
 
-	    print_barre_liste($langs->trans('PriceForEachProduct'), $page, $_SERVER['PHP_SELF'], $option, $sortfield, $sortorder, '', count($prodcustprice->lines), $nbtotalofrecords, '');
+		print_barre_liste($langs->trans('PriceForEachProduct'), $page, $_SERVER['PHP_SELF'], $option, $sortfield, $sortorder, '', count($prodcustprice->lines), $nbtotalofrecords, '');
 
-        print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">';
-        print '<input type="hidden" name="token" value="'.newToken().'">';
-        print '<input type="hidden" name="id" value="'.$object->id.'">';
+		print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">';
+		print '<input type="hidden" name="token" value="'.newToken().'">';
+		print '<input type="hidden" name="id" value="'.$object->id.'">';
 
-        print '<table class="noborder centpercent">';
+		print '<table class="noborder centpercent">';
 
-        print '<tr class="liste_titre">';
-        print '<td>' . $langs->trans("Ref") . '</td>';
+		print '<tr class="liste_titre">';
+		print '<td>' . $langs->trans("Ref") . '</td>';
 		print '<td>' . $langs->trans("Product") . '</td>';
-        print '<td>'.$langs->trans("AppliedPricesFrom").'</td>';
-        print '<td class="center">'.$langs->trans("PriceBase").'</td>';
-        print '<td class="right">'.$langs->trans("VAT").'</td>';
-        print '<td class="right">'.$langs->trans("HT").'</td>';
-        print '<td class="right">'.$langs->trans("TTC").'</td>';
-        print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("HT").'</td>';
-        print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("TTC").'</td>';
-        print '<td class="right">'.$langs->trans("ChangedBy").'</td>';
-        print '<td>&nbsp;</td>';
-        print '</tr>';
-
-        if (count($prodcustprice->lines) > 0 || $search_prod)
-        {
-            print '<tr class="liste_titre">';
+		print '<td>'.$langs->trans("AppliedPricesFrom").'</td>';
+		print '<td class="center">'.$langs->trans("PriceBase").'</td>';
+		print '<td class="right">'.$langs->trans("VAT").'</td>';
+		print '<td class="right">'.$langs->trans("HT").'</td>';
+		print '<td class="right">'.$langs->trans("TTC").'</td>';
+		print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("HT").'</td>';
+		print '<td class="right">'.$langs->trans("MinPrice").' '.$langs->trans("TTC").'</td>';
+		print '<td class="right">'.$langs->trans("ChangedBy").'</td>';
+		print '<td>&nbsp;</td>';
+		print '</tr>';
+
+		if (count($prodcustprice->lines) > 0 || $search_prod)
+		{
+			print '<tr class="liste_titre">';
 			print '<td class="liste_titre"><input type="text" class="flat" name="search_prod" value="'.$search_prod.'" size="20"></td>';
-            print '<td class="liste_titre" ><input type="text" class="flat" name="search_label" value="' . $search_label . '" size="20"></td>';
-            print '<td class="liste_titre" colspan="3">&nbsp;</td>';
-            print '<td class="liste_titre" align="right"><input type="text" class="flat" name="search_price" value="' . $search_price . '" size="10"></td>';
-            print '<td class="liste_titre" align="right"><input type="text" class="flat" name="search_price_ttc" value="' . $search_price_ttc . '" size="10"></td>';
-            print '<td class="liste_titre" colspan="3">&nbsp;</td>';
-            // Print the search button
-            print '<td class="liste_titre maxwidthsearch">';
-            $searchpicto = $form->showFilterAndCheckAddButtons(0);
-            print $searchpicto;
-            print '</td>';
-            print '</tr>';
-        }
-
-        if (count($prodcustprice->lines) > 0)
-        {
-            foreach ($prodcustprice->lines as $line)
-            {
-                print '<tr class="oddeven">';
-
-                $staticprod = new Product($db);
-                $staticprod->fetch($line->fk_product);
-
-                print "<td>".$staticprod->getNomUrl(1)."</td>";
-                print "<td>" . $staticprod->label ."</td>";
-                print "<td>".dol_print_date($line->datec, "dayhour")."</td>";
-
-                print '<td class="center">'.$langs->trans($line->price_base_type)."</td>";
-                print '<td class="right">'.vatrate($line->tva_tx.($line->default_vat_code ? ' ('.$line->default_vat_code.')' : ''), true, $line->recuperableonly)."</td>";
-                print '<td class="right">'.price($line->price)."</td>";
-                print '<td class="right">'.price($line->price_ttc)."</td>";
-                print '<td class="right">'.price($line->price_min).'</td>';
-                print '<td class="right">'.price($line->price_min_ttc).'</td>';
-
-                // User
-                $userstatic = new User($db);
-                $userstatic->fetch($line->fk_user);
-                print '<td class="right">';
-                print $userstatic->getLoginUrl(1);
-                print '</td>';
-
-                // Action
-                if ($user->rights->produit->creer || $user->rights->service->creer)
-                {
-                    print '<td class="right nowraponall">';
-                    print '<a class="paddingleftonly paddingrightonly" href="'.$_SERVER["PHP_SELF"].'?action=showlog_customer_price&amp;socid='.$object->id.'&amp;prodid='.$line->fk_product.'">';
-                    print img_info();
-                    print '</a>';
-                    print ' ';
-                    print '<a class="editfielda paddingleftonly paddingrightonly" href="'.$_SERVER["PHP_SELF"].'?action=edit_customer_price&amp;socid='.$object->id.'&amp;lineid='.$line->id.'">';
-                    print img_edit('default', 0, 'style="vertical-align: middle;"');
-                    print '</a>';
-                    print ' ';
-                    print '<a class="paddingleftonly paddingrightonly" href="'.$_SERVER["PHP_SELF"].'?action=delete_customer_price&amp;token='.newToken().'&amp;socid='.$object->id.'&amp;lineid='.$line->id.'">';
-                    print img_delete('default', 'style="vertical-align: middle;"');
-                    print '</a>';
-                    print '</td>';
-                }
-
-                print "</tr>\n";
-            }
-        } else {
-            $colspan = 9;
-            if ($user->rights->produit->supprimer || $user->rights->service->supprimer) $colspan += 1;
-            print '<tr class="oddeven"><td colspan="'.$colspan.'">'.$langs->trans('None').'</td></tr>';
-        }
-
-        print "</table>";
-
-        print "</form>";
+			print '<td class="liste_titre" ><input type="text" class="flat" name="search_label" value="' . $search_label . '" size="20"></td>';
+			print '<td class="liste_titre" colspan="3">&nbsp;</td>';
+			print '<td class="liste_titre" align="right"><input type="text" class="flat" name="search_price" value="' . $search_price . '" size="10"></td>';
+			print '<td class="liste_titre" align="right"><input type="text" class="flat" name="search_price_ttc" value="' . $search_price_ttc . '" size="10"></td>';
+			print '<td class="liste_titre" colspan="3">&nbsp;</td>';
+			// Print the search button
+			print '<td class="liste_titre maxwidthsearch">';
+			$searchpicto = $form->showFilterAndCheckAddButtons(0);
+			print $searchpicto;
+			print '</td>';
+			print '</tr>';
+		}
+
+		if (count($prodcustprice->lines) > 0)
+		{
+			foreach ($prodcustprice->lines as $line)
+			{
+				print '<tr class="oddeven">';
+
+				$staticprod = new Product($db);
+				$staticprod->fetch($line->fk_product);
+
+				print "<td>".$staticprod->getNomUrl(1)."</td>";
+				print "<td>" . $staticprod->label ."</td>";
+				print "<td>".dol_print_date($line->datec, "dayhour")."</td>";
+
+				print '<td class="center">'.$langs->trans($line->price_base_type)."</td>";
+				print '<td class="right">'.vatrate($line->tva_tx.($line->default_vat_code ? ' ('.$line->default_vat_code.')' : ''), true, $line->recuperableonly)."</td>";
+				print '<td class="right">'.price($line->price)."</td>";
+				print '<td class="right">'.price($line->price_ttc)."</td>";
+				print '<td class="right">'.price($line->price_min).'</td>';
+				print '<td class="right">'.price($line->price_min_ttc).'</td>';
+
+				// User
+				$userstatic = new User($db);
+				$userstatic->fetch($line->fk_user);
+				print '<td class="right">';
+				print $userstatic->getLoginUrl(1);
+				print '</td>';
+
+				// Action
+				if ($user->rights->produit->creer || $user->rights->service->creer)
+				{
+					print '<td class="right nowraponall">';
+					print '<a class="paddingleftonly paddingrightonly" href="'.$_SERVER["PHP_SELF"].'?action=showlog_customer_price&amp;socid='.$object->id.'&amp;prodid='.$line->fk_product.'">';
+					print img_info();
+					print '</a>';
+					print ' ';
+					print '<a class="editfielda paddingleftonly paddingrightonly" href="'.$_SERVER["PHP_SELF"].'?action=edit_customer_price&amp;socid='.$object->id.'&amp;lineid='.$line->id.'">';
+					print img_edit('default', 0, 'style="vertical-align: middle;"');
+					print '</a>';
+					print ' ';
+					print '<a class="paddingleftonly paddingrightonly" href="'.$_SERVER["PHP_SELF"].'?action=delete_customer_price&amp;token='.newToken().'&amp;socid='.$object->id.'&amp;lineid='.$line->id.'">';
+					print img_delete('default', 'style="vertical-align: middle;"');
+					print '</a>';
+					print '</td>';
+				}
+
+				print "</tr>\n";
+			}
+		} else {
+			$colspan = 9;
+			if ($user->rights->produit->supprimer || $user->rights->service->supprimer) $colspan += 1;
+			print '<tr class="oddeven"><td colspan="'.$colspan.'">'.$langs->trans('None').'</td></tr>';
+		}
+
+		print "</table>";
+
+		print "</form>";
 	}
 }
 

+ 4 - 4
htdocs/takepos/index.php

@@ -58,7 +58,7 @@ if ($setterminal > 0)
 	setcookie("takeposterminal", $setterminal, (time() + (86400 * 354)), '/', null, false, true); // Permanent takeposterminal var in a cookie
 }
 
-if ($setcurrency!="")
+if ($setcurrency != "")
 {
 	$_SESSION["takeposcustomercurrency"] = $setcurrency;
 }
@@ -812,7 +812,7 @@ if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
 			?>
 			</a>
 			<?php
-			if (!empty($conf->multicurrency->enabled)){
+			if (!empty($conf->multicurrency->enabled)) {
 				print '<a class="valignmiddle tdoverflowmax100 minwidth75" id="multicurrency" onclick="ModalBox(\'ModalCurrency\');" title=""><span class="fas fa-coins paddingrightonly"></span>'.$langs->trans("Currency").'</a>';
 			}
 			?>
@@ -850,10 +850,10 @@ if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
 	<div class="modal-content">
 		<div class="modal-header">
 		<span class="close" href="#" onclick="document.getElementById('ModalTerminal').style.display = 'none';">&times;</span>
-		<h3><?php print $langs->trans("TerminalSelect");?></h3>
+		<h3><?php print $langs->trans("TerminalSelect"); ?></h3>
 	</div>
 	<div class="modal-body">
-		<button type="button" class="block" onclick="location.href='index.php?setterminal=1'"><?php print $langs->trans("Terminal");?> 1</button>
+		<button type="button" class="block" onclick="location.href='index.php?setterminal=1'"><?php print $langs->trans("Terminal"); ?> 1</button>
 		<?php
 		for ($i = 2; $i <= $conf->global->TAKEPOS_NUM_TERMINALS; $i++)
 		{

+ 7 - 7
htdocs/takepos/invoice.php

@@ -253,7 +253,7 @@ if ($action == 'valid' && $user->rights->facture->creer)
 			if ($pay != "delayed") {
 				$payment->create($user);
 				$payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccount, '', '');
-				$remaintopay = $invoice->getRemainToPay();    // Recalculate remain to pay after the payment is recorded
+				$remaintopay = $invoice->getRemainToPay(); // Recalculate remain to pay after the payment is recorded
 			}
 		}
 
@@ -278,7 +278,7 @@ if ($action == 'history')
 	$invoice->fetch($placeid);
 }
 
-if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"]!="") {
+if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "") {
 	$invoice->setMulticurrencyCode($_SESSION["takeposcustomercurrency"]);
 }
 
@@ -737,7 +737,7 @@ function TakeposPrinting(id){
 
 function TakeposConnector(id){
 	console.log("TakeposConnector" + id);
-	$.get("ajax/ajax.php?action=printinvoiceticket&term=<?php echo $_SESSION["takeposterminal"];?>&id="+id, function(data, status){
+	$.get("ajax/ajax.php?action=printinvoiceticket&term=<?php echo $_SESSION["takeposterminal"]; ?>&id="+id, function(data, status){
         $.ajax({
 			type: "POST",
 			url: '<?php print $conf->global->TAKEPOS_PRINT_SERVER; ?>/printer/index.php',
@@ -902,12 +902,12 @@ if ($_SESSION["basiclayout"] != 1)
 	// In phone version only show when it is invoice page
 	if ($mobilepage == "invoice" || $mobilepage == "") {
 		print '<span id="linecolht-span-total" style="font-size:1.3em; font-weight: bold;">'.price($invoice->total_ttc, 1, '', 1, -1, -1, $conf->currency).'</span>';
-		if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"]!="" && $conf->currency!=$_SESSION["takeposcustomercurrency"]) {
+		if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
 			//Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
 			include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
 			$multicurrency = new MultiCurrency($db);
 			$multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
-			print '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">('.price($invoice->total_ttc*$multicurrency->rate->rate).' '.$_SESSION["takeposcustomercurrency"].')</span>';
+			print '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">('.price($invoice->total_ttc * $multicurrency->rate->rate).' '.$_SESSION["takeposcustomercurrency"].')</span>';
 		}
 		print '</td>';
 	}
@@ -1108,12 +1108,12 @@ if ($placeid > 0)
 				$htmlforlines .= '</td>';
 				$htmlforlines .= '<td class="right classfortooltip" title="'.$moreinfo.'">';
 				$htmlforlines .= price($line->total_ttc, 1, '', 1, -1, -1, $conf->currency);
-				if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"]!="" && $conf->currency!=$_SESSION["takeposcustomercurrency"]) {
+				if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
 					//Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
 					include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
 					$multicurrency = new MultiCurrency($db);
 					$multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
-					$htmlforlines .= '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">('.price($line->total_ttc*$multicurrency->rate->rate).' '.$_SESSION["takeposcustomercurrency"].')</span>';
+					$htmlforlines .= '<br><span id="linecolht-span-total" style="font-size:0.9em; font-style:italic;">('.price($line->total_ttc * $multicurrency->rate->rate).' '.$_SESSION["takeposcustomercurrency"].')</span>';
 				}
 				$htmlforlines .= '</td>';
 			}

+ 2 - 2
htdocs/takepos/pay.php

@@ -231,7 +231,7 @@ else print "var received=0;";
 <div style="position:relative; padding-top: 20px; left:5%; height:150px; width:90%;">
 
 <div class="paymentbordline paymentbordlinetotal">
-	<center><span class="takepospay"><font color="white"><?php echo $langs->trans('TotalTTC'); ?>: </font><span id="totaldisplay" class="colorwhite"><?php echo price($invoice->total_ttc, 1, '', 1, -1, -1, $invoice->multicurrency_code);?></span></span></center>
+	<center><span class="takepospay"><font color="white"><?php echo $langs->trans('TotalTTC'); ?>: </font><span id="totaldisplay" class="colorwhite"><?php echo price($invoice->total_ttc, 1, '', 1, -1, -1, $invoice->multicurrency_code); ?></span></span></center>
 </div>
 <?php if ($remaintopay != $invoice->total_ttc) { ?>
 <div class="paymentbordline paymentbordlineremain">
@@ -245,7 +245,7 @@ else print "var received=0;";
 	<center><span class="takepospay"><font color="white"><?php echo $langs->trans("Change"); ?>: </font><span class="change2 colorwhite"><?php echo price(0, 1, '', 1, -1, -1, $invoice->multicurrency_code); ?></span><input type="hidden" id="change2" class="change2" value="0"></span></center>
 </div>
 <?php
-if (! empty($conf->global->TAKEPOS_CAN_FORCE_BANK_ACCOUNT_DURING_PAYMENT)) {
+if (!empty($conf->global->TAKEPOS_CAN_FORCE_BANK_ACCOUNT_DURING_PAYMENT)) {
 	print '<div class="paymentbordline paddingtop paddingbottom">
 	<center>';
 	$filter = '';

+ 16 - 16
htdocs/takepos/receipt.php

@@ -91,7 +91,7 @@ if (!empty($hookmanager->resPrint)) {
 <br>
 <p class="left">
 <?php
-$constFreeText = 'TAKEPOS_HEADER' . $_SESSION['takeposterminal'];
+$constFreeText = 'TAKEPOS_HEADER'.$_SESSION['takeposterminal'];
 if (!empty($conf->global->TAKEPOS_HEADER) || !empty($conf->global->{$constFreeText}))
 {
 	$newfreetext = '';
@@ -127,8 +127,8 @@ if ($conf->global->TAKEPOS_SHOW_CUSTOMER)
 	<tr>
         <th class="center"><?php print $langs->trans("Label"); ?></th>
         <th class="right"><?php print $langs->trans("Qty"); ?></th>
-        <th class="right"><?php if ($gift!=1) print $langs->trans("Price"); ?></th>
-        <th class="right"><?php if ($gift!=1) print $langs->trans("TotalTTC"); ?></th>
+        <th class="right"><?php if ($gift != 1) print $langs->trans("Price"); ?></th>
+        <th class="right"><?php if ($gift != 1) print $langs->trans("TotalTTC"); ?></th>
 	</tr>
     </thead>
     <tbody>
@@ -142,8 +142,8 @@ if ($conf->global->TAKEPOS_SHOW_CUSTOMER)
         else echo $line->description; ?>
         </td>
         <td class="right"><?php echo $line->qty; ?></td>
-        <td class="right"><?php if ($gift!=1) echo price(price2num($line->total_ttc / $line->qty, 'MT'), 1); ?></td>
-        <td class="right"><?php if ($gift!=1) echo price($line->total_ttc, 1); ?></td>
+        <td class="right"><?php if ($gift != 1) echo price(price2num($line->total_ttc / $line->qty, 'MT'), 1); ?></td>
+        <td class="right"><?php if ($gift != 1) echo price($line->total_ttc, 1); ?></td>
     </tr>
         <?php
     }
@@ -153,8 +153,8 @@ if ($conf->global->TAKEPOS_SHOW_CUSTOMER)
 <br>
 <table class="right">
 <tr>
-    <th class="right"><?php if ($gift!=1) echo $langs->trans("TotalHT"); ?></th>
-    <td class="right"><?php if ($gift!=1) echo price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
+    <th class="right"><?php if ($gift != 1) echo $langs->trans("TotalHT"); ?></th>
+    <td class="right"><?php if ($gift != 1) echo price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
 </tr>
 <?php if ($conf->global->TAKEPOS_TICKET_VAT_GROUPPED) {
 	$vat_groups = array();
@@ -168,27 +168,27 @@ if ($conf->global->TAKEPOS_SHOW_CUSTOMER)
 	foreach ($vat_groups as $key => $val) {
 	    ?>
 	<tr>
-		<th align="right"><?php if ($gift!=1) echo $langs->trans("VAT").' '.vatrate($key, 1); ?></th>
-		<td align="right"><?php if ($gift!=1) echo price($val, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
+		<th align="right"><?php if ($gift != 1) echo $langs->trans("VAT").' '.vatrate($key, 1); ?></th>
+		<td align="right"><?php if ($gift != 1) echo price($val, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
 	</tr>
         <?php
 	}
 } else { ?>
 <tr>
-	<th class="right"><?php if ($gift!=1) echo $langs->trans("TotalVAT").'</th><td class="right">'.price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
+	<th class="right"><?php if ($gift != 1) 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 if ($gift!=1) echo ''.$langs->trans("TotalTTC").'</th><td class="right">'.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
+	<th class="right"><?php if ($gift != 1) echo ''.$langs->trans("TotalTTC").'</th><td class="right">'.price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency)."\n"; ?></td>
 </tr>
 <?php
-if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"]!="" && $conf->currency!=$_SESSION["takeposcustomercurrency"]) {
+if (!empty($conf->multicurrency->enabled) && $_SESSION["takeposcustomercurrency"] != "" && $conf->currency != $_SESSION["takeposcustomercurrency"]) {
 	//Only show customer currency if multicurrency module is enabled, if currency selected and if this currency selected is not the same as main currency
 	include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
 	$multicurrency = new MultiCurrency($db);
 	$multicurrency->fetch(0, $_SESSION["takeposcustomercurrency"]);
 	echo '<tr><th class="right">';
-	if ($gift!=1) echo ''.$langs->trans("TotalTTC").' '.$_SESSION["takeposcustomercurrency"].'</th><td class="right">'.price($object->total_ttc*$multicurrency->rate->rate, 1, '', 1, - 1, - 1, $_SESSION["takeposcustomercurrency"])."\n";
+	if ($gift != 1) echo ''.$langs->trans("TotalTTC").' '.$_SESSION["takeposcustomercurrency"].'</th><td class="right">'.price($object->total_ttc * $multicurrency->rate->rate, 1, '', 1, - 1, - 1, $_SESSION["takeposcustomercurrency"])."\n";
 	echo '</td></tr>';
 }
 
@@ -211,12 +211,12 @@ if ($conf->global->TAKEPOS_PRINT_PAYMENT_METHOD) {
 			echo $langs->transnoentitiesnoconv("PaymentTypeShort".$row->code);
 			echo '</td>';
 			echo '<td class="right">';
-			$amount_payment=($conf->multicurrency->enabled && $object->multicurrency_tx != 1) ? $row->multicurrency_amount : $row->amount;
+			$amount_payment = ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) ? $row->multicurrency_amount : $row->amount;
 			if ($row->code == "LIQ") $amount_payment = $amount_payment + $row->pos_change; // Show amount with excess received if is cash payment
 			echo price($amount_payment, 1, '', 1, - 1, - 1, $conf->currency);
 			echo '</td>';
 			echo '</tr>';
-			if ($row->code == "LIQ" && $row->pos_change>0) // Print change only in cash payments
+			if ($row->code == "LIQ" && $row->pos_change > 0) // Print change only in cash payments
 			{
 				echo '<tr>';
 				echo '<td class="right">';
@@ -238,7 +238,7 @@ if ($conf->global->TAKEPOS_PRINT_PAYMENT_METHOD) {
 <br>
 <br>
 <?php
-$constFreeText = 'TAKEPOS_FOOTER' . $_SESSION['takeposterminal'];
+$constFreeText = 'TAKEPOS_FOOTER'.$_SESSION['takeposterminal'];
 if (!empty($conf->global->TAKEPOS_FOOTER) || !empty($conf->global->{$constFreeText}))
 {
 	$newfreetext = '';

+ 24 - 24
htdocs/takepos/send.php

@@ -51,31 +51,31 @@ $invoice->fetch($facid);
 $customer = new Societe($db);
 $customer->fetch($invoice->socid);
 
-if ($action=="send")
+if ($action == "send")
 {
-    include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
-    include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
-    $formmail = new FormMail($db);
-    $outputlangs = new Translate('', $conf);
-    $model_id = $conf->global->TAKEPOS_EMAIL_TEMPLATE_INVOICE;
-    $arraydefaultmessage = $formmail->getEMailTemplate($db, 'facture_send', $user, $outputlangs, $model_id);
-    $subject = $arraydefaultmessage->topic;
-
-    ob_start(); // turn on output receipt
-    include 'receipt.php';
-    $receipt = ob_get_contents(); // get the contents of the output buffer
-    ob_end_clean();
-
-    $msg="<html>".$arraydefaultmessage->content."<br>".$receipt."</html>";
-    $sendto=$email;
-    $from=$mysoc->email;
-    $mail = new CMailFile($subject, $sendto, $from, $msg, array(), array(), array(), '', '', 0, 1);
-    if ($mail->error || $mail->errors) {
-        setEventMessages($mail->error, $mail->errors, 'errors');
-    } else {
-        $result = $mail->sendfile();
-    }
-    exit;
+	include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
+	include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
+	$formmail = new FormMail($db);
+	$outputlangs = new Translate('', $conf);
+	$model_id = $conf->global->TAKEPOS_EMAIL_TEMPLATE_INVOICE;
+	$arraydefaultmessage = $formmail->getEMailTemplate($db, 'facture_send', $user, $outputlangs, $model_id);
+	$subject = $arraydefaultmessage->topic;
+
+	ob_start(); // turn on output receipt
+	include 'receipt.php';
+	$receipt = ob_get_contents(); // get the contents of the output buffer
+	ob_end_clean();
+
+	$msg="<html>".$arraydefaultmessage->content."<br>".$receipt."</html>";
+	$sendto=$email;
+	$from=$mysoc->email;
+	$mail = new CMailFile($subject, $sendto, $from, $msg, array(), array(), array(), '', '', 0, 1);
+	if ($mail->error || $mail->errors) {
+		setEventMessages($mail->error, $mail->errors, 'errors');
+	} else {
+		$result = $mail->sendfile();
+	}
+	exit;
 }
 $arrayofcss = array('/takepos/css/pos.css.php');
 $arrayofjs  = array();

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

@@ -170,7 +170,7 @@ class User extends CommonObject
 
 	public $users = array(); // To store all tree of users hierarchy
 	public $parentof; // To store an array of all parents for all ids.
-	private $cache_childids;	// Cache array of already loaded childs
+	private $cache_childids; // Cache array of already loaded childs
 
 	public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
 
@@ -704,10 +704,10 @@ class User extends CommonObject
 			// avoid admin can remove his own important rights
 			if ($this->admin == 1)
 			{
-				$sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)";	// other users rights
-				$sql .= " AND id NOT IN (341, 342, 343, 344)";				// own rights
-				$sql .= " AND id NOT IN (351, 352, 353, 354)";				// groups rights
-				$sql .= " AND id NOT IN (358)";								// user export
+				$sql .= " AND id NOT IN (251, 252, 253, 254, 255, 256)"; // other users rights
+				$sql .= " AND id NOT IN (341, 342, 343, 344)"; // own rights
+				$sql .= " AND id NOT IN (351, 352, 353, 354)"; // groups rights
+				$sql .= " AND id NOT IN (358)"; // user export
 			}
 
 			$result = $this->db->query($sql);
@@ -1186,7 +1186,7 @@ class User extends CommonObject
 						return -5;
 					}
 
-					if (! empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER) && !empty($conf->global->STOCK_USERSTOCK_AUTOCREATE))
+					if (!empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER) && !empty($conf->global->STOCK_USERSTOCK_AUTOCREATE))
 					{
 						require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
 						$langs->load("stocks");

+ 24 - 24
htdocs/user/list.php

@@ -220,7 +220,7 @@ if (empty($reshook))
 		$search_date_creation = "";
 		$search_date_update = "";
 		$search_array_options = array();
-        $search_categ = 0;
+		$search_categ = 0;
 	}
 
 	// Mass actions
@@ -463,11 +463,11 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
 
 if (!empty($catid))
 {
-    print "<div id='ways'>";
-    $c = new Categorie($db);
-    $ways = $c->print_all_ways(' &gt; ', 'user/list.php');
-    print " &gt; ".$ways[0]."<br>\n";
-    print "</div><br>";
+	print "<div id='ways'>";
+	$c = new Categorie($db);
+	$ways = $c->print_all_ways(' &gt; ', 'user/list.php');
+	print " &gt; ".$ways[0]."<br>\n";
+	print "</div><br>";
 }
 
 if ($search_all)
@@ -484,10 +484,10 @@ $moreforfilter = '';
 // Filter on categories
 if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire)
 {
-    $moreforfilter .= '<div class="divsearchfield">';
-    $moreforfilter .= $langs->trans('Categories').': ';
-    $moreforfilter .= $formother->select_categories(Categorie::TYPE_USER, $search_categ, 'search_categ', 1);
-    $moreforfilter .= '</div>';
+	$moreforfilter .= '<div class="divsearchfield">';
+	$moreforfilter .= $langs->trans('Categories').': ';
+	$moreforfilter .= $formother->select_categories(Categorie::TYPE_USER, $search_categ, 'search_categ', 1);
+	$moreforfilter .= '</div>';
 }
 
 $parameters = array();
@@ -497,9 +497,9 @@ else $moreforfilter = $hookmanager->resPrint;
 
 if (!empty($moreforfilter))
 {
-    print '<div class="liste_titre liste_titre_bydiv centpercent">';
-    print $moreforfilter;
-    print '</div>';
+	print '<div class="liste_titre liste_titre_bydiv centpercent">';
+	print $moreforfilter;
+	print '</div>';
 }
 
 $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
@@ -693,29 +693,29 @@ while ($i < ($limit ? min($num, $limit) : $num))
 	}
 	if (!empty($arrayfields['u.firstname']['checked']))
 	{
-	    print '<td class="tdoverflowmax150">'.$obj->firstname.'</td>';
+		print '<td class="tdoverflowmax150">'.$obj->firstname.'</td>';
 		if (!$i) $totalarray['nbfield']++;
 	}
 	if (!empty($arrayfields['u.gender']['checked']))
 	{
-	    print '<td>';
-	    if ($obj->gender) print $langs->trans("Gender".$obj->gender);
-	    print '</td>';
+		print '<td>';
+		if ($obj->gender) print $langs->trans("Gender".$obj->gender);
+		print '</td>';
 		if (!$i) $totalarray['nbfield']++;
 	}
 	if (!empty($arrayfields['u.employee']['checked']))
 	{
-	    print '<td>'.yn($obj->employee).'</td>';
+		print '<td>'.yn($obj->employee).'</td>';
 		if (!$i) $totalarray['nbfield']++;
 	}
 	if (!empty($arrayfields['u.accountancy_code']['checked']))
 	{
-	    print '<td>'.$obj->accountancy_code.'</td>';
+		print '<td>'.$obj->accountancy_code.'</td>';
 		if (!$i) $totalarray['nbfield']++;
 	}
 	if (!empty($arrayfields['u.email']['checked']))
 	{
-	    print '<td>'.$obj->email.'</td>';
+		print '<td>'.$obj->email.'</td>';
 		if (!$i) $totalarray['nbfield']++;
 	}
 	if (!empty($arrayfields['u.api_key']['checked']))
@@ -774,7 +774,7 @@ while ($i < ($limit ? min($num, $limit) : $num))
 			$user2->admin = $obj->admin2;
 			$user2->email = $obj->email2;
 			$user2->socid = $obj->fk_soc2;
-            $user2->statut = $obj->statut2;
+			$user2->statut = $obj->statut2;
 			print $user2->getNomUrl(-1, '', 0, 0, 24, 0, '', '', 1);
 			if (!empty($conf->multicompany->enabled) && $obj->admin2 && !$obj->entity2)
 			{
@@ -826,9 +826,9 @@ while ($i < ($limit ? min($num, $limit) : $num))
 	// Status
 	if (!empty($arrayfields['u.statut']['checked']))
 	{
-	    $userstatic->statut = $obj->statut;
-	    print '<td class="center">'.$userstatic->getLibStatut(5).'</td>';
-	    if (!$i) $totalarray['nbfield']++;
+		$userstatic->statut = $obj->statut;
+		print '<td class="center">'.$userstatic->getLibStatut(5).'</td>';
+		if (!$i) $totalarray['nbfield']++;
 	}
 	// Action column
 	print '<td class="nowrap center">';

+ 281 - 281
htdocs/user/notify/card.php

@@ -63,48 +63,48 @@ $now = dol_now();
 // Add a notification
 if ($action == 'add')
 {
-    $error = 0;
+	$error = 0;
 
-    if ($actionid <= 0)
-    {
-	    setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Action")), null, 'errors');
-        $error++;
-    }
+	if ($actionid <= 0)
+	{
+		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Action")), null, 'errors');
+		$error++;
+	}
 
-    if (!$error)
-    {
-        $db->begin();
+	if (!$error)
+	{
+		$db->begin();
 
-        $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
-        $sql .= " WHERE fk_user=".$id." AND fk_action=".$actionid;
-        if ($db->query($sql))
-        {
-            $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_action)";
-            $sql .= " VALUES ('".$db->idate($now)."',".$id.",".$actionid.")";
+		$sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
+		$sql .= " WHERE fk_user=".$id." AND fk_action=".$actionid;
+		if ($db->query($sql))
+		{
+			$sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_action)";
+			$sql .= " VALUES ('".$db->idate($now)."',".$id.",".$actionid.")";
 
-            if (!$db->query($sql))
-            {
-                $error++;
-                dol_print_error($db);
-            }
-        } else {
-            dol_print_error($db);
-        }
-
-        if (!$error)
-        {
-            $db->commit();
-        } else {
-            $db->rollback();
-        }
-    }
+			if (!$db->query($sql))
+			{
+				$error++;
+				dol_print_error($db);
+			}
+		} else {
+			dol_print_error($db);
+		}
+
+		if (!$error)
+		{
+			$db->commit();
+		} else {
+			$db->rollback();
+		}
+	}
 }
 
 // Remove a notification
 if ($action == 'delete')
 {
-    $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def where rowid=".GETPOST("actid", "int");
-    $db->query($sql);
+	$sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def where rowid=".GETPOST("actid", "int");
+	$db->query($sql);
 }
 
 
@@ -127,32 +127,32 @@ llxHeader('', $title, $help_url);
 
 if ($result > 0)
 {
-    $langs->load("other");
+	$langs->load("other");
 
-    $head = user_prepare_head($object);
+	$head = user_prepare_head($object);
 
-    dol_fiche_head($head, 'notify', $langs->trans("User"), -1, 'user');
+	dol_fiche_head($head, 'notify', $langs->trans("User"), -1, 'user');
 
-    $linkback = '<a href="'.DOL_URL_ROOT.'/user/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
+	$linkback = '<a href="'.DOL_URL_ROOT.'/user/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
 
-    dol_banner_tab($object, 'id', $linkback, $user->rights->user->user->lire || $user->admin, 'rowid', 'ref', '', '', 0, '', '', 0, '');
+	dol_banner_tab($object, 'id', $linkback, $user->rights->user->user->lire || $user->admin, 'rowid', 'ref', '', '', 0, '', '', 0, '');
 
-    print '<div class="fichecenter">';
+	print '<div class="fichecenter">';
 
-    print '<div class="underbanner clearboth"></div>';
-    print '<table class="border centpercent tableforfield">';
+	print '<div class="underbanner clearboth"></div>';
+	print '<table class="border centpercent tableforfield">';
 
-    // Login
-    print '<tr><td class="titlefield">'.$langs->trans("Login").'</td>';
-    if (!empty($object->ldap_sid) && $object->statut == 0)
-    {
-        print '<td class="error">'.$langs->trans("LoginAccountDisableInDolibarr").'</td>';
-    } else {
-        print '<td>'.$object->login.'</td>';
-    }
-    print '</tr>'."\n";
+	// Login
+	print '<tr><td class="titlefield">'.$langs->trans("Login").'</td>';
+	if (!empty($object->ldap_sid) && $object->statut == 0)
+	{
+		print '<td class="error">'.$langs->trans("LoginAccountDisableInDolibarr").'</td>';
+	} else {
+		print '<td>'.$object->login.'</td>';
+	}
+	print '</tr>'."\n";
 
-    /*print '<tr><td class="titlefield">'.$langs->trans("NbOfActiveNotifications").'</td>';   // Notification for this thirdparty
+	/*print '<tr><td class="titlefield">'.$langs->trans("NbOfActiveNotifications").'</td>';   // Notification for this thirdparty
     print '<td colspan="3">';
     $nbofrecipientemails=0;
     $notify=new Notify($db);
@@ -164,164 +164,164 @@ if ($result > 0)
     print $nbofrecipientemails;
     print '</td></tr>';*/
 
-    print '</table>';
+	print '</table>';
 
-    print '</div>';
+	print '</div>';
 
-    dol_fiche_end();
+	dol_fiche_end();
 
-    print "\n";
+	print "\n";
 
-    // Help
-    print '<span class="opacitymedium">';
-    print '<br>'.$langs->trans("NotificationsDesc");
-    print '<br>'.$langs->trans("NotificationsDescUser");
-    print '<br>'.$langs->trans("NotificationsDescContact");
-    print '<br>'.$langs->trans("NotificationsDescGlobal");
-    print '</span>';
+	// Help
+	print '<span class="opacitymedium">';
+	print '<br>'.$langs->trans("NotificationsDesc");
+	print '<br>'.$langs->trans("NotificationsDescUser");
+	print '<br>'.$langs->trans("NotificationsDescContact");
+	print '<br>'.$langs->trans("NotificationsDescGlobal");
+	print '</span>';
 
-    print '<br><br><br>'."\n";
+	print '<br><br><br>'."\n";
 
 
-    // Add notification form
-    print load_fiche_titre($langs->trans("AddNewNotification"), '', '');
+	// Add notification form
+	print load_fiche_titre($langs->trans("AddNewNotification"), '', '');
 
-    print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$id.'" method="post">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    print '<input type="hidden" name="action" value="add">';
+	print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$id.'" method="post">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="action" value="add">';
 
-    $param = "&id=".$id;
+	$param = "&id=".$id;
 
-    // Line with titles
-    print '<table width="100%" class="noborder">';
-    print '<tr class="liste_titre">';
-    print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '"width="45%"', $sortfield, $sortorder);
-    print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '"width="35%"', $sortfield, $sortorder);
-    print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '"width="10%"', $sortfield, $sortorder);
-    print_liste_field_titre('');
+	// Line with titles
+	print '<table width="100%" class="noborder">';
+	print '<tr class="liste_titre">';
+	print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '"width="45%"', $sortfield, $sortorder);
+	print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '"width="35%"', $sortfield, $sortorder);
+	print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '"width="10%"', $sortfield, $sortorder);
+	print_liste_field_titre('');
 	print "</tr>\n";
 
 
-    // $listofemails=$object->thirdparty_and_contact_email_array();
-    if ($object->email)
-    {
-        $actions = array();
+	// $listofemails=$object->thirdparty_and_contact_email_array();
+	if ($object->email)
+	{
+		$actions = array();
 
-        // Load array of available notifications
-        $notificationtrigger = new InterfaceNotification($db);
-        $listofnotifiedevents = $notificationtrigger->getListOfManagedEvents();
+		// Load array of available notifications
+		$notificationtrigger = new InterfaceNotification($db);
+		$listofnotifiedevents = $notificationtrigger->getListOfManagedEvents();
 
-        foreach ($listofnotifiedevents as $notifiedevent)
-        {
+		foreach ($listofnotifiedevents as $notifiedevent)
+		{
  			$label = ($langs->trans("Notify_".$notifiedevent['code']) != "Notify_".$notifiedevent['code'] ? $langs->trans("Notify_".$notifiedevent['code']) : $notifiedevent['label']);
-            $actions[$notifiedevent['rowid']] = $label;
-        }
-        print '<tr class="oddeven nohover"><td>';
-        print $object->getNomUrl(1);
-        if (isValidEmail($object->email))
-        {
-            print ' &lt;'.$object->email.'&gt;';
-        } else {
-            $langs->load("errors");
-            print ' &nbsp; '.img_warning().' '.$langs->trans("ErrorBadEMail", $object->email);
-        }
-        print '</td>';
-        print '<td>';
-        print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$form->selectarray("actionid", $actions, '', 1);
-        print '</td>';
-        print '<td>';
-        $type = array('email'=>$langs->trans("EMail"));
-        print $form->selectarray("typeid", $type);
-        print '</td>';
-        print '<td class="right"><input type="submit" class="button" value="'.$langs->trans("Add").'"></td>';
-        print '</tr>';
-    } else {
-        print '<tr class="oddeven"><td colspan="4">';
-        print $langs->trans("YouMustAssignUserMailFirst");
-        print '</td></tr>';
-    }
-
-    print '</table>';
-
-    print '</form>';
-    print '<br>';
-
-    // List of notifications enabled for contacts
-    $sql = "SELECT n.rowid, n.type,";
-    $sql .= " a.code, a.label,";
-    $sql .= " c.rowid as userid, c.lastname, c.firstname, c.email";
-    $sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
-    $sql .= " ".MAIN_DB_PREFIX."notify_def as n,";
-    $sql .= " ".MAIN_DB_PREFIX."user c";
-    $sql .= " WHERE a.rowid = n.fk_action";
-    $sql .= " AND c.rowid = n.fk_user";
-    $sql .= " AND c.rowid = ".$object->id;
+			$actions[$notifiedevent['rowid']] = $label;
+		}
+		print '<tr class="oddeven nohover"><td>';
+		print $object->getNomUrl(1);
+		if (isValidEmail($object->email))
+		{
+			print ' &lt;'.$object->email.'&gt;';
+		} else {
+			$langs->load("errors");
+			print ' &nbsp; '.img_warning().' '.$langs->trans("ErrorBadEMail", $object->email);
+		}
+		print '</td>';
+		print '<td>';
+		print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$form->selectarray("actionid", $actions, '', 1);
+		print '</td>';
+		print '<td>';
+		$type = array('email'=>$langs->trans("EMail"));
+		print $form->selectarray("typeid", $type);
+		print '</td>';
+		print '<td class="right"><input type="submit" class="button" value="'.$langs->trans("Add").'"></td>';
+		print '</tr>';
+	} else {
+		print '<tr class="oddeven"><td colspan="4">';
+		print $langs->trans("YouMustAssignUserMailFirst");
+		print '</td></tr>';
+	}
 
-    $resql = $db->query($sql);
-    if ($resql)
-    {
-        $num = $db->num_rows($resql);
-    } else {
-        dol_print_error($db);
-    }
+	print '</table>';
+
+	print '</form>';
+	print '<br>';
+
+	// List of notifications enabled for contacts
+	$sql = "SELECT n.rowid, n.type,";
+	$sql .= " a.code, a.label,";
+	$sql .= " c.rowid as userid, c.lastname, c.firstname, c.email";
+	$sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
+	$sql .= " ".MAIN_DB_PREFIX."notify_def as n,";
+	$sql .= " ".MAIN_DB_PREFIX."user c";
+	$sql .= " WHERE a.rowid = n.fk_action";
+	$sql .= " AND c.rowid = n.fk_user";
+	$sql .= " AND c.rowid = ".$object->id;
+
+	$resql = $db->query($sql);
+	if ($resql)
+	{
+		$num = $db->num_rows($resql);
+	} else {
+		dol_print_error($db);
+	}
 
-    // List of active notifications
-    print load_fiche_titre($langs->trans("ListOfActiveNotifications").' ('.$num.')', '', '');
+	// List of active notifications
+	print load_fiche_titre($langs->trans("ListOfActiveNotifications").' ('.$num.')', '', '');
 
-    // Line with titles
-    print '<table width="100%" class="noborder">';
-    print '<tr class="liste_titre">';
-    print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '"width="45%"', $sortfield, $sortorder);
-    print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '"width="35%"', $sortfield, $sortorder);
-    print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '"width="10%"', $sortfield, $sortorder);
-    print_liste_field_titre('', '', '');
-    print '</tr>';
+	// Line with titles
+	print '<table width="100%" class="noborder">';
+	print '<tr class="liste_titre">';
+	print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '"width="45%"', $sortfield, $sortorder);
+	print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '"width="35%"', $sortfield, $sortorder);
+	print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '"width="10%"', $sortfield, $sortorder);
+	print_liste_field_titre('', '', '');
+	print '</tr>';
 
 	$langs->load("errors");
 	$langs->load("other");
 
-    if ($num)
-    {
-        $i = 0;
+	if ($num)
+	{
+		$i = 0;
 
-        $userstatic = new user($db);
+		$userstatic = new user($db);
 
-        while ($i < $num)
-        {
-            $obj = $db->fetch_object($resql);
+		while ($i < $num)
+		{
+			$obj = $db->fetch_object($resql);
 
-            $userstatic->id = $obj->userid;
-            $userstatic->lastname = $obj->lastname;
-            $userstatic->firstname = $obj->firstname;
-            print '<tr class="oddeven"><td>'.$userstatic->getNomUrl(1);
-            if ($obj->type == 'email')
-            {
-                if (isValidEmail($obj->email))
-                {
-                    print ' &lt;'.$obj->email.'&gt;';
-                } else {
-                    $langs->load("errors");
-                    print ' &nbsp; '.img_warning().' '.$langs->trans("ErrorBadEMail", $obj->email);
-                }
-            }
-            print '</td>';
-            print '<td>';
-            $label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
-            print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$label;
-            print '</td>';
-            print '<td>';
-            if ($obj->type == 'email') print $langs->trans("Email");
-            if ($obj->type == 'sms') print $langs->trans("SMS");
-            print '</td>';
-            print '<td class="right"><a href="card.php?id='.$id.'&amp;action=delete&amp;token='.newToken().'&amp;actid='.$obj->rowid.'">'.img_delete().'</a></td>';
-            print '</tr>';
-            $i++;
-        }
-        $db->free($resql);
+			$userstatic->id = $obj->userid;
+			$userstatic->lastname = $obj->lastname;
+			$userstatic->firstname = $obj->firstname;
+			print '<tr class="oddeven"><td>'.$userstatic->getNomUrl(1);
+			if ($obj->type == 'email')
+			{
+				if (isValidEmail($obj->email))
+				{
+					print ' &lt;'.$obj->email.'&gt;';
+				} else {
+					$langs->load("errors");
+					print ' &nbsp; '.img_warning().' '.$langs->trans("ErrorBadEMail", $obj->email);
+				}
+			}
+			print '</td>';
+			print '<td>';
+			$label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
+			print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$label;
+			print '</td>';
+			print '<td>';
+			if ($obj->type == 'email') print $langs->trans("Email");
+			if ($obj->type == 'sms') print $langs->trans("SMS");
+			print '</td>';
+			print '<td class="right"><a href="card.php?id='.$id.'&amp;action=delete&amp;token='.newToken().'&amp;actid='.$obj->rowid.'">'.img_delete().'</a></td>';
+			print '</tr>';
+			$i++;
+		}
+		$db->free($resql);
 	}
 
-    // List of notifications enabled for fixed email
-    /*
+	// List of notifications enabled for fixed email
+	/*
     foreach($conf->global as $key => $val)
     {
     	if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_(.*)/', $key, $reg)) continue;
@@ -362,7 +362,7 @@ if ($result > 0)
 		print '<td class="right">'.$langs->trans("SeeModuleSetup", $langs->transnoentitiesnoconv("Module600Name")).'</td>';
 		print '</tr>';
     }*/
-    /*if ($user->admin)
+	/*if ($user->admin)
     {
 	    $var = ! $var;
 		print '<tr class="oddeven"><td colspan="4">';
@@ -370,104 +370,104 @@ if ($result > 0)
 		print '</td></tr>';
     }*/
 
-    print '</table>';
-
+	print '</table>';
 
-    print '<br><br>'."\n";
 
+	print '<br><br>'."\n";
 
-    // List
-    $sql = "SELECT n.rowid, n.daten, n.email, n.objet_type as object_type, n.objet_id as object_id, n.type,";
-    $sql .= " c.rowid as id, c.lastname, c.firstname, c.email as contactemail,";
-    $sql .= " a.code, a.label";
-    $sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
-    $sql .= " ".MAIN_DB_PREFIX."notify as n";
-    $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as c ON n.fk_user = c.rowid";
-    $sql .= " WHERE a.rowid = n.fk_action";
-    $sql .= " AND n.fk_user = ".$object->id;
-    $sql .= $db->order($sortfield, $sortorder);
 
-    // Count total nb of records
-    $nbtotalofrecords = '';
-    if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
-    {
-        $result = $db->query($sql);
-        $nbtotalofrecords = $db->num_rows($result);
-        if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
-        {
-        	$page = 0;
-        	$offset = 0;
-        }
-    }
+	// List
+	$sql = "SELECT n.rowid, n.daten, n.email, n.objet_type as object_type, n.objet_id as object_id, n.type,";
+	$sql .= " c.rowid as id, c.lastname, c.firstname, c.email as contactemail,";
+	$sql .= " a.code, a.label";
+	$sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
+	$sql .= " ".MAIN_DB_PREFIX."notify as n";
+	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as c ON n.fk_user = c.rowid";
+	$sql .= " WHERE a.rowid = n.fk_action";
+	$sql .= " AND n.fk_user = ".$object->id;
+	$sql .= $db->order($sortfield, $sortorder);
 
-    $sql .= $db->plimit($limit + 1, $offset);
-
-    $resql = $db->query($sql);
-    if ($resql)
-    {
-        $num = $db->num_rows($resql);
-    } else {
-        dol_print_error($db);
-    }
+	// Count total nb of records
+	$nbtotalofrecords = '';
+	if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
+	{
+		$result = $db->query($sql);
+		$nbtotalofrecords = $db->num_rows($result);
+		if (($page * $limit) > $nbtotalofrecords)	// if total resultset is smaller then paging size (filtering), goto and load page 0
+		{
+			$page = 0;
+			$offset = 0;
+		}
+	}
 
-    $param = '&id='.$object->id;
-    if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
-    if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
-
-    print '<form method="post" action="'.$_SERVER["PHP_SELF"].'" name="formfilter">';
-    if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
-    print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
-    print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
-    print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
-    print '<input type="hidden" name="page" value="'.$page.'">';
-    print '<input type="hidden" name="id" value="'.$object->id.'">';
-
-    // List of notifications done
-    print_barre_liste($langs->trans("ListOfNotificationsDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit);
-
-    // Line with titles
-    print '<table width="100%" class="noborder">';
-    print '<tr class="liste_titre">';
-    print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '', $sortfield, $sortorder);
-    print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder);
-    print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '', $sortfield, $sortorder);
-    //print_liste_field_titre("Object",$_SERVER["PHP_SELF"],"",'',$param,'"',$sortfield,$sortorder);
-    print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "n.daten", '', $param, '', $sortfield, $sortorder, 'right ');
-    print '</tr>';
-
-    if ($num)
-    {
-        $i = 0;
+	$sql .= $db->plimit($limit + 1, $offset);
 
-        $userstatic = new User($db);
+	$resql = $db->query($sql);
+	if ($resql)
+	{
+		$num = $db->num_rows($resql);
+	} else {
+		dol_print_error($db);
+	}
 
-        while ($i < $num)
-        {
-            $obj = $db->fetch_object($resql);
+	$param = '&id='.$object->id;
+	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
+	if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
+
+	print '<form method="post" action="'.$_SERVER["PHP_SELF"].'" name="formfilter">';
+	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
+	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
+	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
+	print '<input type="hidden" name="page" value="'.$page.'">';
+	print '<input type="hidden" name="id" value="'.$object->id.'">';
+
+	// List of notifications done
+	print_barre_liste($langs->trans("ListOfNotificationsDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit);
+
+	// Line with titles
+	print '<table width="100%" class="noborder">';
+	print '<tr class="liste_titre">';
+	print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '', $sortfield, $sortorder);
+	print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder);
+	print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '', $sortfield, $sortorder);
+	//print_liste_field_titre("Object",$_SERVER["PHP_SELF"],"",'',$param,'"',$sortfield,$sortorder);
+	print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "n.daten", '', $param, '', $sortfield, $sortorder, 'right ');
+	print '</tr>';
+
+	if ($num)
+	{
+		$i = 0;
+
+		$userstatic = new User($db);
+
+		while ($i < $num)
+		{
+			$obj = $db->fetch_object($resql);
 
-            print '<tr class="oddeven"><td>';
-            if ($obj->id > 0)
-            {
-	            $userstatic->id = $obj->id;
-	            $userstatic->lastname = $obj->lastname;
-	            $userstatic->firstname = $obj->firstname;
-	            print $userstatic->getNomUrl(1);
-	            print $obj->email ? ' &lt;'.$obj->email.'&gt;' : $langs->trans("NoMail");
-            } else {
+			print '<tr class="oddeven"><td>';
+			if ($obj->id > 0)
+			{
+				$userstatic->id = $obj->id;
+				$userstatic->lastname = $obj->lastname;
+				$userstatic->firstname = $obj->firstname;
+				print $userstatic->getNomUrl(1);
+				print $obj->email ? ' &lt;'.$obj->email.'&gt;' : $langs->trans("NoMail");
+			} else {
 				print $obj->email;
-            }
-            print '</td>';
-            print '<td>';
-            $label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
-            print $label;
-            print '</td>';
-            print '<td>';
-            if ($obj->type == 'email') print $langs->trans("Email");
-            if ($obj->type == 'sms') print $langs->trans("Sms");
-            print '</td>';
-            // TODO Add link to object here for other types
-            /*print '<td>';
+			}
+			print '</td>';
+			print '<td>';
+			$label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
+			print $label;
+			print '</td>';
+			print '<td>';
+			if ($obj->type == 'email') print $langs->trans("Email");
+			if ($obj->type == 'sms') print $langs->trans("Sms");
+			print '</td>';
+			// TODO Add link to object here for other types
+			/*print '<td>';
             if ($obj->object_type == 'order')
             {
 				$orderstatic->id=$obj->object_id;
@@ -475,19 +475,19 @@ if ($result > 0)
 				print $orderstatic->getNomUrl(1);
             }
            	print '</td>';*/
-            // print
-            print'<td class="right">'.dol_print_date($db->jdate($obj->daten), 'dayhour').'</td>';
-            print '</tr>';
-            $i++;
-        }
-        $db->free($resql);
-    } else {
-    	print '<tr><td colspan="4"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
-    }
+			// print
+			print'<td class="right">'.dol_print_date($db->jdate($obj->daten), 'dayhour').'</td>';
+			print '</tr>';
+			$i++;
+		}
+		$db->free($resql);
+	} else {
+		print '<tr><td colspan="4"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
+	}
 
-    print '</table>';
+	print '</table>';
 
-    print '</form>';
+	print '</form>';
 } else dol_print_error('', 'RecordNotFound');
 
 // End of page

+ 71 - 71
htdocs/website/class/websitepage.class.php

@@ -52,8 +52,8 @@ class WebsitePage extends CommonObject
 
 
 	/**
-     * @var int ID
-     */
+	 * @var int ID
+	 */
 	public $fk_website;
 
 	public $pageurl;
@@ -106,14 +106,14 @@ class WebsitePage extends CommonObject
 	public $author_alias;
 
    	/**
-     * @var string path of external object
-     */
-    public $object_type;
+   	 * @var string path of external object
+   	 */
+	public $object_type;
 
-    /**
-     * @var string id of external object
-     */
-    public $fk_object;
+	/**
+	 * @var string id of external object
+	 */
+	public $fk_object;
 
 	const STATUS_DRAFT = 0;
 	const STATUS_VALIDATED = 1;
@@ -145,25 +145,25 @@ class WebsitePage extends CommonObject
 
 	// BEGIN MODULEBUILDER PROPERTIES
 	/**
-     * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
-     */
+	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
+	 */
 	public $fields = array(
-	    'rowid'          =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
+		'rowid'          =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
 		'pageurl'        =>array('type'=>'varchar(16)', 'label'=>'WEBSITE_PAGENAME', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Ref/alias of page'),
 		'aliasalt'       =>array('type'=>'varchar(255)', 'label'=>'AliasAlt', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'index'=>0, 'position'=>11, 'searchall'=>0, 'comment'=>'Alias alternative of page'),
 		'type_container' =>array('type'=>'varchar(16)', 'label'=>'Type', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'index'=>0, 'position'=>12, 'comment'=>'Type of container'),
 		'title'          =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'help'=>'UseTextBetween5And70Chars'),
-	    'description'    =>array('type'=>'varchar(255)', 'label'=>'Description', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1),
+		'description'    =>array('type'=>'varchar(255)', 'label'=>'Description', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1),
 		'image'          =>array('type'=>'varchar(255)', 'label'=>'Image', 'enabled'=>1, 'visible'=>1, 'position'=>32, 'searchall'=>0, 'help'=>'Relative path of media. Used if Type is "blogpost"'),
 		'keywords'       =>array('type'=>'varchar(255)', 'label'=>'Keywords', 'enabled'=>1, 'visible'=>1, 'position'=>45, 'searchall'=>0),
 		'lang'           =>array('type'=>'varchar(6)', 'label'=>'Lang', 'enabled'=>1, 'notnull'=>-1, 'visible'=>1, 'position'=>45, 'searchall'=>0),
 		//'status'        =>array('type'=>'integer',      'label'=>'Status',           'enabled'=>1, 'visible'=>1,  'index'=>true,   'position'=>1000),
-	    'fk_website'     =>array('type'=>'integer', 'label'=>'WebsiteId', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>40, 'searchall'=>0, 'foreignkey'=>'websitepage.rowid'),
-	    'fk_page'        =>array('type'=>'integer', 'label'=>'ParentPageId', 'enabled'=>1, 'visible'=>1, 'notnull'=>-1, 'position'=>45, 'searchall'=>0, 'foreignkey'=>'website.rowid'),
-	    'htmlheader'     =>array('type'=>'text', 'label'=>'HtmlHeader', 'enabled'=>1, 'visible'=>0, 'position'=>50, 'searchall'=>0),
-	    'content'        =>array('type'=>'mediumtext', 'label'=>'Content', 'enabled'=>1, 'visible'=>0, 'position'=>51, 'searchall'=>0),
+		'fk_website'     =>array('type'=>'integer', 'label'=>'WebsiteId', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>40, 'searchall'=>0, 'foreignkey'=>'websitepage.rowid'),
+		'fk_page'        =>array('type'=>'integer', 'label'=>'ParentPageId', 'enabled'=>1, 'visible'=>1, 'notnull'=>-1, 'position'=>45, 'searchall'=>0, 'foreignkey'=>'website.rowid'),
+		'htmlheader'     =>array('type'=>'text', 'label'=>'HtmlHeader', 'enabled'=>1, 'visible'=>0, 'position'=>50, 'searchall'=>0),
+		'content'        =>array('type'=>'mediumtext', 'label'=>'Content', 'enabled'=>1, 'visible'=>0, 'position'=>51, 'searchall'=>0),
 		'grabbed_from'   =>array('type'=>'varchar(255)', 'label'=>'GrabbedFrom', 'enabled'=>1, 'visible'=>1, 'index'=>1, 'position'=>400, 'comment'=>'URL page content was grabbed from'),
-	    'date_creation'  =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
+		'date_creation'  =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
 		'tms'            =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>501),
 		//'date_valid'    =>array('type'=>'datetime',     'label'=>'DateValidation',     'enabled'=>1, 'visible'=>-1, 'position'=>502),
 		'fk_user_creat'  =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'notnull'=>true, 'position'=>510),
@@ -172,7 +172,7 @@ class WebsitePage extends CommonObject
 		//'fk_user_valid' =>array('type'=>'integer',      'label'=>'UserValidation',        'enabled'=>1, 'visible'=>-1, 'position'=>512),
 		'import_key'     =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'index'=>1, 'position'=>1000, 'notnull'=>-1),
 		'object_type' => array('type' => 'varchar(255)','label' => 'ObjectType', 'enabled'=>1, 'visible'=>1, 'position'=>46, 'searchall'=>0, 'help'=>''),
-	    'fk_object' => array('type' => 'varchar(255)','label' => 'ObjectId', 'enabled'=>1, 'visible'=>1, 'position'=>47, 'searchall'=>0, 'help'=>'')
+		'fk_object' => array('type' => 'varchar(255)','label' => 'ObjectId', 'enabled'=>1, 'visible'=>1, 'position'=>47, 'searchall'=>0, 'help'=>'')
 	);
 	// END MODULEBUILDER PROPERTIES
 
@@ -274,7 +274,7 @@ class WebsitePage extends CommonObject
 		$sql .= " t.fk_user_modif,";
 		$sql .= " t.import_key,";
 		$sql .= " t.object_type,";
-        $sql .= " t.fk_object";
+		$sql .= " t.fk_object";
 		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
 		//$sql .= ' WHERE entity IN ('.getEntity('website').')';       // entity is on website level
 		$sql .= ' WHERE 1 = 1';
@@ -285,22 +285,22 @@ class WebsitePage extends CommonObject
 		else {
 			if ($id < 0) $sql .= ' AND t.rowid <> '.abs($id);
 			if (null !== $website_id) {
-			    $sql .= " AND t.fk_website = '".$this->db->escape($website_id)."'";
-			    if ($page) {
-			    	$pagetouse = $page;
-			    	$langtouse = '';
-			    	$tmppage = explode('/', $page);
-			    	if (!empty($tmppage[1])) {
-			    		$pagetouse = $tmppage[1];
-			    		if (strlen($tmppage[0])) $langtouse = $tmppage[0];
-			    	}
-			    	$sql .= " AND t.pageurl = '".$this->db->escape($pagetouse)."'";
-			    	if ($langtouse) $sql .= " AND t.lang = '".$this->db->escape($langtouse)."'";
-			    }
-			    if ($aliasalt)	$sql .= " AND (t.aliasalt LIKE '%,".$this->db->escape($aliasalt).",%' OR t.aliasalt LIKE '%, ".$this->db->escape($aliasalt).",%')";
+				$sql .= " AND t.fk_website = '".$this->db->escape($website_id)."'";
+				if ($page) {
+					$pagetouse = $page;
+					$langtouse = '';
+					$tmppage = explode('/', $page);
+					if (!empty($tmppage[1])) {
+						$pagetouse = $tmppage[1];
+						if (strlen($tmppage[0])) $langtouse = $tmppage[0];
+					}
+					$sql .= " AND t.pageurl = '".$this->db->escape($pagetouse)."'";
+					if ($langtouse) $sql .= " AND t.lang = '".$this->db->escape($langtouse)."'";
+				}
+				if ($aliasalt)	$sql .= " AND (t.aliasalt LIKE '%,".$this->db->escape($aliasalt).",%' OR t.aliasalt LIKE '%, ".$this->db->escape($aliasalt).",%')";
 			}
 		}
-        $sql .= $this->db->plimit(1);
+		$sql .= $this->db->plimit(1);
 
 		$resql = $this->db->query($sql);
 		if ($resql) {
@@ -334,7 +334,7 @@ class WebsitePage extends CommonObject
 				$this->fk_user_modif = $obj->fk_user_modif;
 				$this->import_key = $obj->import_key;
 				$this->object_type = $obj->object_type;
-                $this->fk_object = $obj->fk_object;
+				$this->fk_object = $obj->fk_object;
 			}
 			$this->db->free($resql);
 
@@ -392,7 +392,7 @@ class WebsitePage extends CommonObject
 		$sql .= " t.fk_user_modif,";
 		$sql .= " t.import_key,";
 		$sql .= " t.object_type,";
-        $sql .= " t.fk_object";
+		$sql .= " t.fk_object";
 		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
 		$sql .= ' WHERE t.fk_website = '.$websiteid;
 		// Manage filter
@@ -619,7 +619,7 @@ class WebsitePage extends CommonObject
 			}
 		}
 
-		if (! $error) {
+		if (!$error) {
 			return 1;
 		} else {
 			return -1;
@@ -712,43 +712,43 @@ class WebsitePage extends CommonObject
 	 *
 	 *	@param	int		$withpicto			Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
 	 *	@param	string	$option				On what the link point to
-     *  @param	integer	$notooltip			1=Disable tooltip
-     *  @param	int		$maxlen				Max length of visible user name
-     *  @param  string  $morecss            Add more css on link
+	 *  @param	integer	$notooltip			1=Disable tooltip
+	 *  @param	int		$maxlen				Max length of visible user name
+	 *  @param  string  $morecss            Add more css on link
 	 *	@return	string						String with URL
 	 */
 	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
 	{
 		global $langs, $conf, $db;
-        global $dolibarr_main_authentication, $dolibarr_main_demo;
-        global $menumanager;
-
-        $result = '';
-
-        $label = '<u>'.$langs->trans("Page").'</u>';
-        $label .= '<br>';
-        $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
-        $label .= '<b>'.$langs->trans('ID').':</b> '.$this->id.'<br>';
-        $label .= '<b>'.$langs->trans('Title').':</b> '.$this->title.'<br>';
-        $label .= '<b>'.$langs->trans('Language').':</b> '.$this->lang;
-
-        $url = DOL_URL_ROOT.'/website/index.php?websiteid='.$this->fk_website.'&pageid='.$this->id;
-
-        $linkclose = '';
-        if (empty($notooltip))
-        {
-        	if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
-        	{
-        		$label = $langs->trans("ShowMyObject");
-        		$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
-        	}
-        	$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
-        	$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
-        }
-        else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
-
-        $linkstart = '<a href="'.$url.'"';
-        $linkstart .= $linkclose.'>';
+		global $dolibarr_main_authentication, $dolibarr_main_demo;
+		global $menumanager;
+
+		$result = '';
+
+		$label = '<u>'.$langs->trans("Page").'</u>';
+		$label .= '<br>';
+		$label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref.'<br>';
+		$label .= '<b>'.$langs->trans('ID').':</b> '.$this->id.'<br>';
+		$label .= '<b>'.$langs->trans('Title').':</b> '.$this->title.'<br>';
+		$label .= '<b>'.$langs->trans('Language').':</b> '.$this->lang;
+
+		$url = DOL_URL_ROOT.'/website/index.php?websiteid='.$this->fk_website.'&pageid='.$this->id;
+
+		$linkclose = '';
+		if (empty($notooltip))
+		{
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+			{
+				$label = $langs->trans("ShowMyObject");
+				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+			}
+			$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+			$linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+		}
+		else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+
+		$linkstart = '<a href="'.$url.'"';
+		$linkstart .= $linkclose.'>';
 		$linkend = '</a>';
 
 		//$linkstart = $linkend = '';
@@ -772,7 +772,7 @@ class WebsitePage extends CommonObject
 		return $this->LibStatut($this->status, $mode);
 	}
 
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
 	 *  Renvoi le libelle d'un status donne
 	 *
@@ -782,7 +782,7 @@ class WebsitePage extends CommonObject
 	 */
 	public function LibStatut($status, $mode = 0)
 	{
-        // phpcs:enable
+		// phpcs:enable
 		global $langs;
 
 		if (empty($this->labelStatus) || empty($this->labelStatusShort))

+ 267 - 267
htdocs/website/index.php

@@ -130,10 +130,10 @@ if ($pageid < 0) $pageid = 0;
 if (($pageid > 0 || $pageref) && $action != 'addcontainer')
 {
 	$res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), $pageref);
-    if ($res == 0)
-    {
-        $res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), null, $pageref);
-    }
+	if ($res == 0)
+	{
+		$res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), null, $pageref);
+	}
 
 	// Check if pageid is inside the new website, if not we reset param pageid
 	if ($res >= 0 && $object->id > 0)
@@ -303,28 +303,28 @@ $permissiontodelete = $user->rights->website->delete;
 // Protections
 if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x'))
 {
-    $action = 'preview'; // To avoid to make an action on another page or another site when we click on button to select another site or page.
+	$action = 'preview'; // To avoid to make an action on another page or another site when we click on button to select another site or page.
 }
 if (GETPOST('refreshsite', 'alpha') || GETPOST('refreshsite.x', 'alpha') || GETPOST('refreshsite_x', 'alpha'))		// If we change the site, we reset the pageid and cancel addsite action.
 {
-    if ($action == 'addsite') $action = 'preview';
-    if ($action == 'updatesource') $action = 'preview';
-
-    $pageid = $object->fk_default_home;
-    if (empty($pageid))
-    {
-    	$array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl');
-    	if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors);
-    	$atleastonepage = (is_array($array) && count($array) > 0);
-
-    	$firstpageid = 0; $homepageid = 0;
-    	foreach ($array as $key => $valpage)
-    	{
-    		if (empty($firstpageid)) $firstpageid = $valpage->id;
-    		if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid = $valpage->id;
-    	}
-    	$pageid = ($homepageid ? $homepageid : $firstpageid); // We choose home page and if not defined yet, we take first page
-    }
+	if ($action == 'addsite') $action = 'preview';
+	if ($action == 'updatesource') $action = 'preview';
+
+	$pageid = $object->fk_default_home;
+	if (empty($pageid))
+	{
+		$array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl');
+		if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors);
+		$atleastonepage = (is_array($array) && count($array) > 0);
+
+		$firstpageid = 0; $homepageid = 0;
+		foreach ($array as $key => $valpage)
+		{
+			if (empty($firstpageid)) $firstpageid = $valpage->id;
+			if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid = $valpage->id;
+		}
+		$pageid = ($homepageid ? $homepageid : $firstpageid); // We choose home page and if not defined yet, we take first page
+	}
 }
 if (GETPOST('refreshpage', 'alpha') && !in_array($action, array('updatecss'))) $action = 'preview';
 
@@ -529,9 +529,9 @@ if ($action == 'addsite')
 	$db->begin();
 
 	if (GETPOST('virtualhost', 'alpha') && !preg_match('/^http/', GETPOST('virtualhost', 'alpha')))
-    {
-        $error++;
-        setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors');
+	{
+		$error++;
+		setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors');
 	}
 
 	if (!$error && !GETPOST('WEBSITE_REF', 'alpha'))
@@ -1278,54 +1278,54 @@ if ($action == 'updatecss')
 		{
 			$tmpvirtualhost = preg_replace('/\/$/', '', GETPOST('virtualhost', 'alpha'));
 			if ($tmpvirtualhost && !preg_match('/^http/', $tmpvirtualhost))
-    		{
-    		    $error++;
-    		    setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors');
-    		    $action = 'editcss';
-    		}
-
-    		if (!$error)
-    		{
-    			$arrayotherlang = explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml'));
-    			foreach ($arrayotherlang as $key => $val) {
-    				$arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only
-    			}
-
-    			$object->virtualhost = $tmpvirtualhost;
-    		    $object->lang = GETPOST('WEBSITE_LANG', 'aZ09');
-    		    $object->otherlang = join(',', $arrayotherlang);
-    		    $object->use_manifest = GETPOST('use_manifest', 'alpha');
-
-    		    $result = $object->update($user);
-        		if ($result < 0)
-        		{
-        		    $error++;
-        		    setEventMessages($object->error, $object->errors, 'errors');
-        		    $action = 'editcss';
-        		}
-    		}
+			{
+				$error++;
+				setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors');
+				$action = 'editcss';
+			}
+
+			if (!$error)
+			{
+				$arrayotherlang = explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml'));
+				foreach ($arrayotherlang as $key => $val) {
+					$arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only
+				}
+
+				$object->virtualhost = $tmpvirtualhost;
+				$object->lang = GETPOST('WEBSITE_LANG', 'aZ09');
+				$object->otherlang = join(',', $arrayotherlang);
+				$object->use_manifest = GETPOST('use_manifest', 'alpha');
+
+				$result = $object->update($user);
+				if ($result < 0)
+				{
+					$error++;
+					setEventMessages($object->error, $object->errors, 'errors');
+					$action = 'editcss';
+				}
+			}
 		}
 
 		if (!$error)
 		{
-    		// Save master.inc.php file
-    		dol_syslog("Save master file ".$filemaster);
+			// Save master.inc.php file
+			dol_syslog("Save master file ".$filemaster);
 
-    		dol_mkdir($pathofwebsite);
+			dol_mkdir($pathofwebsite);
 
-    		// Now generate the master.inc.php page
-    		$result = dolSaveMasterFile($filemaster);
-    		if (!$result)
-    		{
-    			$error++;
-    			setEventMessages('Failed to write file '.$filemaster, null, 'errors');
-    		}
+			// Now generate the master.inc.php page
+			$result = dolSaveMasterFile($filemaster);
+			if (!$result)
+			{
+				$error++;
+				setEventMessages('Failed to write file '.$filemaster, null, 'errors');
+			}
 
 
-    		// Html header file
-    		$htmlheadercontent = '';
+			// Html header file
+			$htmlheadercontent = '';
 
-    		/* We disable php code since htmlheader is never executed as an include but only read by fgets_content.
+			/* We disable php code since htmlheader is never executed as an include but only read by fgets_content.
     	    $htmlheadercontent.= "<?php // BEGIN PHP\n";
     	    $htmlheadercontent.= '$websitekey=basename(__DIR__);'."\n";
     	    $htmlheadercontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n";
@@ -1335,84 +1335,84 @@ if ($action == 'updatecss')
     	    // $htmlheadercontent.= "header('Content-type: text/html');\n";		// Not required. htmlheader.html is never call as a standalone page
     	    $htmlheadercontent.= "// END PHP ?>\n";*/
 
-    		$htmlheadercontent .= preg_replace(array('/<html>\n*/ims', '/<\/html>\n*/ims'), array('', ''), GETPOST('WEBSITE_HTML_HEADER', 'none'));
+			$htmlheadercontent .= preg_replace(array('/<html>\n*/ims', '/<\/html>\n*/ims'), array('', ''), GETPOST('WEBSITE_HTML_HEADER', 'none'));
 
-    		/*$htmlheadercontent.= "\n".'<?php // BEGIN PHP'."\n";
+			/*$htmlheadercontent.= "\n".'<?php // BEGIN PHP'."\n";
     	    $htmlheadercontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n";
     	    $htmlheadercontent.= "// END PHP ?>"."\n";*/
 
-    		$htmlheadercontent = trim($htmlheadercontent)."\n";
+			$htmlheadercontent = trim($htmlheadercontent)."\n";
 
-    		$result = dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent);
-    		if (!$result)
-    		{
-    			$error++;
-    			setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors');
-    		}
+			$result = dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent);
+			if (!$result)
+			{
+				$error++;
+				setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors');
+			}
 
 
-    		// Css file
-    		$csscontent = '';
+			// Css file
+			$csscontent = '';
 
-    		$csscontent .= "<?php // BEGIN PHP\n";
-    		$csscontent .= '$websitekey=basename(__DIR__);'."\n";
-    		$csscontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file.
-    		$csscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
-    		$csscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
-    		$csscontent .= "ob_start();\n";
-    		$csscontent .= "if (! headers_sent()) {	/* because file is included inline when in edit mode and we don't want warning */ \n";
-    		$csscontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
-    		$csscontent .= "header('Content-type: text/css');\n";
-    		$csscontent .= "}\n";
-    		$csscontent .= "// END PHP ?>\n";
+			$csscontent .= "<?php // BEGIN PHP\n";
+			$csscontent .= '$websitekey=basename(__DIR__);'."\n";
+			$csscontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file.
+			$csscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
+			$csscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
+			$csscontent .= "ob_start();\n";
+			$csscontent .= "if (! headers_sent()) {	/* because file is included inline when in edit mode and we don't want warning */ \n";
+			$csscontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
+			$csscontent .= "header('Content-type: text/css');\n";
+			$csscontent .= "}\n";
+			$csscontent .= "// END PHP ?>\n";
 
-    		$csscontent .= trim(GETPOST('WEBSITE_CSS_INLINE', 'none'))."\n";
+			$csscontent .= trim(GETPOST('WEBSITE_CSS_INLINE', 'none'))."\n";
 
-    		$csscontent .= '<?php // BEGIN PHP'."\n";
-    		$csscontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "css");'."\n";
-    		$csscontent .= "// END PHP ?>\n";
+			$csscontent .= '<?php // BEGIN PHP'."\n";
+			$csscontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "css");'."\n";
+			$csscontent .= "// END PHP ?>\n";
 
-    		dol_syslog("Save css content into ".$filecss);
+			dol_syslog("Save css content into ".$filecss);
 
-    		$result = dolSaveCssFile($filecss, $csscontent);
-    		if (!$result)
-    		{
-    			$error++;
-    			setEventMessages('Failed to write file '.$filecss, null, 'errors');
-    		}
+			$result = dolSaveCssFile($filecss, $csscontent);
+			if (!$result)
+			{
+				$error++;
+				setEventMessages('Failed to write file '.$filecss, null, 'errors');
+			}
 
 
-    		// Js file
-    		$jscontent = '';
+			// Js file
+			$jscontent = '';
 
-    		$jscontent .= "<?php // BEGIN PHP\n";
-    		$jscontent .= '$websitekey=basename(__DIR__);'."\n";
-    		$jscontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file.
-    		$jscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
-    		$jscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
-    		$jscontent .= "ob_start();\n";
-    		$jscontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
-    		$jscontent .= "header('Content-type: application/javascript');\n";
-    		$jscontent .= "// END PHP ?>\n";
+			$jscontent .= "<?php // BEGIN PHP\n";
+			$jscontent .= '$websitekey=basename(__DIR__);'."\n";
+			$jscontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file.
+			$jscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
+			$jscontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
+			$jscontent .= "ob_start();\n";
+			$jscontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
+			$jscontent .= "header('Content-type: application/javascript');\n";
+			$jscontent .= "// END PHP ?>\n";
 
-    		$jscontent .= trim(GETPOST('WEBSITE_JS_INLINE', 'none'))."\n";
+			$jscontent .= trim(GETPOST('WEBSITE_JS_INLINE', 'none'))."\n";
 
-    		$jscontent .= '<?php // BEGIN PHP'."\n";
-    		$jscontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "js");'."\n";
-    		$jscontent .= "// END PHP ?>\n";
+			$jscontent .= '<?php // BEGIN PHP'."\n";
+			$jscontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "js");'."\n";
+			$jscontent .= "// END PHP ?>\n";
 
-    		$result = dolSaveJsFile($filejs, $jscontent);
-    		if (!$result)
-    		{
-    			$error++;
-    			setEventMessages('Failed to write file '.$filejs, null, 'errors');
-    		}
+			$result = dolSaveJsFile($filejs, $jscontent);
+			if (!$result)
+			{
+				$error++;
+				setEventMessages('Failed to write file '.$filejs, null, 'errors');
+			}
 
 
-    		// Robot file
-    		$robotcontent = '';
+			// Robot file
+			$robotcontent = '';
 
-    		/*$robotcontent.= "<?php // BEGIN PHP\n";
+			/*$robotcontent.= "<?php // BEGIN PHP\n";
     	    $robotcontent.= '$websitekey=basename(__DIR__);'."\n";
     	    $robotcontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n";
     	    $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
@@ -1422,63 +1422,63 @@ if ($action == 'updatecss')
     	    $robotcontent.= "header('Content-type: text/css');\n";
     	    $robotcontent.= "// END PHP ?>\n";*/
 
-    		$robotcontent .= trim(GETPOST('WEBSITE_ROBOT', 'restricthtml'))."\n";
+			$robotcontent .= trim(GETPOST('WEBSITE_ROBOT', 'restricthtml'))."\n";
 
-    		/*$robotcontent.= "\n".'<?php // BEGIN PHP'."\n";
+			/*$robotcontent.= "\n".'<?php // BEGIN PHP'."\n";
     	    $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "robot");'."\n";
     	    $robotcontent.= "// END PHP ?>"."\n";*/
 
-    		$result = dolSaveRobotFile($filerobot, $robotcontent);
-    		if (!$result)
-    		{
-    			$error++;
-    			setEventMessages('Failed to write file '.$filerobot, null, 'errors');
-    		}
+			$result = dolSaveRobotFile($filerobot, $robotcontent);
+			if (!$result)
+			{
+				$error++;
+				setEventMessages('Failed to write file '.$filerobot, null, 'errors');
+			}
 
 
-    		// Htaccess file
-    		$htaccesscontent = '';
-    		$htaccesscontent .= trim(GETPOST('WEBSITE_HTACCESS', 'restricthtml'))."\n";
+			// Htaccess file
+			$htaccesscontent = '';
+			$htaccesscontent .= trim(GETPOST('WEBSITE_HTACCESS', 'restricthtml'))."\n";
 
-    		$result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent);
-    		if (!$result)
-    		{
-    			$error++;
-    			setEventMessages('Failed to write file '.$filehtaccess, null, 'errors');
-    		}
+			$result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent);
+			if (!$result)
+			{
+				$error++;
+				setEventMessages('Failed to write file '.$filehtaccess, null, 'errors');
+			}
 
 
-       		// manifest.json file
-       		$manifestjsoncontent = '';
+	   		// manifest.json file
+	   		$manifestjsoncontent = '';
 
-       		$manifestjsoncontent .= "<?php // BEGIN PHP\n";
-       		$manifestjsoncontent .= '$websitekey=basename(__DIR__);'."\n";
-       		$manifestjsoncontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file.
-       		$manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
-       		$manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
-       		$manifestjsoncontent .= "ob_start();\n";
-       		$manifestjsoncontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
-       		$manifestjsoncontent .= "header('Content-type: application/manifest+json');\n";
-       		$manifestjsoncontent .= "// END PHP ?>\n";
+	   		$manifestjsoncontent .= "<?php // BEGIN PHP\n";
+	   		$manifestjsoncontent .= '$websitekey=basename(__DIR__);'."\n";
+	   		$manifestjsoncontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file.
+	   		$manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
+	   		$manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
+	   		$manifestjsoncontent .= "ob_start();\n";
+	   		$manifestjsoncontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n";
+	   		$manifestjsoncontent .= "header('Content-type: application/manifest+json');\n";
+	   		$manifestjsoncontent .= "// END PHP ?>\n";
 
-       		$manifestjsoncontent .= trim(GETPOST('WEBSITE_MANIFEST_JSON', 'none'))."\n";
+	   		$manifestjsoncontent .= trim(GETPOST('WEBSITE_MANIFEST_JSON', 'none'))."\n";
 
-       		$manifestjsoncontent .= '<?php // BEGIN PHP'."\n";
-       		$manifestjsoncontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n";
-       		$manifestjsoncontent .= "// END PHP ?>\n";
+	   		$manifestjsoncontent .= '<?php // BEGIN PHP'."\n";
+	   		$manifestjsoncontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n";
+	   		$manifestjsoncontent .= "// END PHP ?>\n";
 
-       		$result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent);
-       		if (!$result)
-       		{
-       			$error++;
-       			setEventMessages('Failed to write file '.$filemanifestjson, null, 'errors');
-       		}
+	   		$result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent);
+	   		if (!$result)
+	   		{
+	   			$error++;
+	   			setEventMessages('Failed to write file '.$filemanifestjson, null, 'errors');
+	   		}
 
 
-       		// README.md file
-       		$readmecontent = '';
+	   		// README.md file
+	   		$readmecontent = '';
 
-       		/*$readmecontent.= "<?php // BEGIN PHP\n";
+	   		/*$readmecontent.= "<?php // BEGIN PHP\n";
        		$readmecontent.= '$websitekey=basename(__DIR__);'."\n";
        		$readmecontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded"."\n";	// For the css, we need to set path of master using the dirname of css file.
        		$readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
@@ -1488,42 +1488,42 @@ if ($action == 'updatecss')
        		$readmecontent.= "header('Content-type: application/manifest+json');\n";
        		$readmecontent.= "// END PHP ?>\n";*/
 
-       		$readmecontent .= trim(GETPOST('WEBSITE_README', 'restricthtml'))."\n";
+	   		$readmecontent .= trim(GETPOST('WEBSITE_README', 'restricthtml'))."\n";
 
-       		/*$readmecontent.= '<?php // BEGIN PHP'."\n";
+	   		/*$readmecontent.= '<?php // BEGIN PHP'."\n";
        		$readmecontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n";
        		$readmecontent.= "// END PHP ?>"."\n";*/
 
-       		$result = dolSaveReadme($filereadme, $readmecontent);
-       		if (!$result)
-       		{
-       			$error++;
-       			setEventMessages('Failed to write file '.$filereadme, null, 'errors');
-       		}
+	   		$result = dolSaveReadme($filereadme, $readmecontent);
+	   		if (!$result)
+	   		{
+	   			$error++;
+	   			setEventMessages('Failed to write file '.$filereadme, null, 'errors');
+	   		}
 
 
-       		// Save wrapper.php
+	   		// Save wrapper.php
 			$result = dolSaveIndexPage($pathofwebsite, '', '', $filewrapper);
 
 
-    		// Message if no error
-    		if (!$error)
-    		{
-    			setEventMessages($langs->trans("Saved"), null, 'mesgs');
-    		}
-
-    		if (!GETPOSTISSET('updateandstay'))	// If we click on "Save And Stay", we don not make the redirect
-    		{
-    			$action = 'preview';
-    			if ($backtopage)
-	    		{
-	    			header("Location: ".$backtopage);
-	    			exit;
-	    		}
-    		}
-    		else {
-    			$action = 'editcss';
-    		}
+			// Message if no error
+			if (!$error)
+			{
+				setEventMessages($langs->trans("Saved"), null, 'mesgs');
+			}
+
+			if (!GETPOSTISSET('updateandstay'))	// If we click on "Save And Stay", we don not make the redirect
+			{
+				$action = 'preview';
+				if ($backtopage)
+				{
+					header("Location: ".$backtopage);
+					exit;
+				}
+			}
+			else {
+				$action = 'editcss';
+			}
 		}
 	}
 }
@@ -1660,7 +1660,7 @@ if ($action == 'updatemeta')
 		$objectpage->fk_page = (GETPOST('pageidfortranslation', 'int') > 0 ? GETPOST('pageidfortranslation', 'int') : 0);
 		$objectpage->author_alias = trim(GETPOST('WEBSITE_AUTHORALIAS', 'alphanohtml'));
 		$objectpage->object_type = GETPOST('WEBSITE_OBJECTCLASS', 'alpha');
-        $objectpage->fk_object = GETPOST('WEBSITE_OBJECTID', 'aZ09');
+		$objectpage->fk_object = GETPOST('WEBSITE_OBJECTID', 'aZ09');
 
 		$newdatecreation = dol_mktime(GETPOST('datecreationhour', 'int'), GETPOST('datecreationmin', 'int'), GETPOST('datecreationsec', 'int'), GETPOST('datecreationmonth', 'int'), GETPOST('datecreationday', 'int'), GETPOST('datecreationyear', 'int'));
 		if ($newdatecreation) $objectpage->date_creation = $newdatecreation;
@@ -1932,35 +1932,35 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf
 
 			$objectpage->content = GETPOST('PAGE_CONTENT', 'none');
 
-            // Security analysis
+			// Security analysis
 			$phpfullcodestring = dolKeepOnlyPhpCode($objectpage->content);
 			//print dol_escape_htmltag($phpfullcodestring);exit;
-            $forbiddenphpcommands = array("exec", "passthru", "system", "shell_exec", "proc_open");
-            if (empty($conf->global->WEBSITE_PHP_ALLOW_WRITE))    // If option is not on, we disallow functions to write files
-            {
-                $forbiddenphpcommands = array_merge($forbiddenphpcommands, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask"));
-            }
-            foreach ($forbiddenphpcommands as $forbiddenphpcommand)
-            {
-                if (preg_match('/'.$forbiddenphpcommand.'\s*\(/ms', $phpfullcodestring))
-                {
-                    $error++;
-                    setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpcommand), null, 'errors');
-                    if ($action == 'updatesource') $action = 'editsource';
-                    if ($action == 'updatecontent') $action = 'editcontent';
-                }
-            }
-
-            if (empty($user->rights->website->writephp))
-            {
-                if ($phpfullcodestringold != $phpfullcodestring)
-                {
-                    $error++;
-                    setEventMessages($langs->trans("NotAllowedToAddDynamicContent"), null, 'errors');
-                    if ($action == 'updatesource') $action = 'editsource';
-                    if ($action == 'updatecontent') $action = 'editcontent';
-                }
-            }
+			$forbiddenphpcommands = array("exec", "passthru", "system", "shell_exec", "proc_open");
+			if (empty($conf->global->WEBSITE_PHP_ALLOW_WRITE))    // If option is not on, we disallow functions to write files
+			{
+				$forbiddenphpcommands = array_merge($forbiddenphpcommands, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask"));
+			}
+			foreach ($forbiddenphpcommands as $forbiddenphpcommand)
+			{
+				if (preg_match('/'.$forbiddenphpcommand.'\s*\(/ms', $phpfullcodestring))
+				{
+					$error++;
+					setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpcommand), null, 'errors');
+					if ($action == 'updatesource') $action = 'editsource';
+					if ($action == 'updatecontent') $action = 'editcontent';
+				}
+			}
+
+			if (empty($user->rights->website->writephp))
+			{
+				if ($phpfullcodestringold != $phpfullcodestring)
+				{
+					$error++;
+					setEventMessages($langs->trans("NotAllowedToAddDynamicContent"), null, 'errors');
+					if ($action == 'updatesource') $action = 'editsource';
+					if ($action == 'updatecontent') $action = 'editcontent';
+				}
+			}
 
 			// Clean data. We remove all the head section.
 			$objectpage->content = preg_replace('/<head>.*<\/head>/ims', '', $objectpage->content);
@@ -2434,28 +2434,28 @@ if (!GETPOST('hide_websitemenu'))
 		$htmltext = '';
 		if (empty($object->fk_default_home))
 		{
-		    $htmltext .= '<br><span class="error">'.$langs->trans("YouMustDefineTheHomePage").'</span><br><br>';
+			$htmltext .= '<br><span class="error">'.$langs->trans("YouMustDefineTheHomePage").'</span><br><br>';
 		}
 		elseif (empty($virtualurl))
 		{
-		    //$htmltext .= '<br><span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span><br><br>';
+			//$htmltext .= '<br><span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span><br><br>';
 		}
 		else {
-		    $htmltext .= '<br><center>'.$langs->trans("GoTo").' <a href="'.$virtualurl.'" target="_website">'.$virtualurl.'</a></center><br>';
+			$htmltext .= '<br><center>'.$langs->trans("GoTo").' <a href="'.$virtualurl.'" target="_website">'.$virtualurl.'</a></center><br>';
 		}
 		if (!empty($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER))
 		{
-		    $htmltext .= '<br>'.$langs->trans($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER);
+			$htmltext .= '<br>'.$langs->trans($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER);
 		}
 		else {
-    		$htmltext .= $langs->trans("SetHereVirtualHost", $dataroot);
-    		$htmltext .= '<br>';
-    		$htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT);
-    		$htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias');
-
-    		$examplewithapache = '#php_admin_value open_basedir /tmp/:'.DOL_DOCUMENT_ROOT.':'.DOL_DATA_ROOT.':/dev/urandom'."\n";
-    		$examplewithapache .= '<Directory "'.DOL_DOCUMENT_ROOT.'">'."\n";
-    		$examplewithapache .= 'AllowOverride FileInfo Options
+			$htmltext .= $langs->trans("SetHereVirtualHost", $dataroot);
+			$htmltext .= '<br>';
+			$htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT);
+			$htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website<br>'.DOL_DATA_ROOT.'/medias');
+
+			$examplewithapache = '#php_admin_value open_basedir /tmp/:'.DOL_DOCUMENT_ROOT.':'.DOL_DATA_ROOT.':/dev/urandom'."\n";
+			$examplewithapache .= '<Directory "'.DOL_DOCUMENT_ROOT.'">'."\n";
+			$examplewithapache .= 'AllowOverride FileInfo Options
     		Options       -Indexes -MultiViews -FollowSymLinks -ExecCGI
     		Require all granted
     		</Directory>
@@ -2470,14 +2470,14 @@ if (!GETPOST('hide_websitemenu'))
     		Require all granted
     		</Directory>';
 
-    		$htmltext .= '<br>'.$langs->trans("ExampleToUseInApacheVirtualHostConfig").':<br>';
-    		$htmltext .= '<div class="centpercent exampleapachesetup">'.dol_nl2br(dol_escape_htmltag($examplewithapache, 1, 1)).'</div>';
+			$htmltext .= '<br>'.$langs->trans("ExampleToUseInApacheVirtualHostConfig").':<br>';
+			$htmltext .= '<div class="centpercent exampleapachesetup">'.dol_nl2br(dol_escape_htmltag($examplewithapache, 1, 1)).'</div>';
 
-    		$htmltext .= '<br>';
-    		$htmltext .= $langs->trans("YouCanAlsoTestWithPHPS", $dataroot);
-    		$htmltext .= '<br>';
-    		$htmltext .= '<br>';
-    		$htmltext .= $langs->trans("YouCanAlsoDeployToAnotherWHP");
+			$htmltext .= '<br>';
+			$htmltext .= $langs->trans("YouCanAlsoTestWithPHPS", $dataroot);
+			$htmltext .= '<br>';
+			$htmltext .= '<br>';
+			$htmltext .= $langs->trans("YouCanAlsoDeployToAnotherWHP");
 		}
 		print $form->textwithpicto($linktotestonwebserver, $htmltext, 1, 'none', 'valignmiddle', 0, 3, 'helpvirtualhost');
 		print '</span>';
@@ -2818,14 +2818,14 @@ if (!GETPOST('hide_websitemenu'))
 			$htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource2", $url);
 			$htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSourceMore", $url);
 			$htmltext .= '<br>';
-            if ($conf->browser->layout == 'phone')
-            {
-                print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution');
-            }
-            else {
-            	//img_help(($tooltiptrigger != '' ? 2 : 1), $alt)
-            	print $form->textwithpicto($langs->trans("SyntaxHelp").' '.img_help(2, $langs->trans("SyntaxHelp")), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution');
-            }
+			if ($conf->browser->layout == 'phone')
+			{
+				print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution');
+			}
+			else {
+				//img_help(($tooltiptrigger != '' ? 2 : 1), $alt)
+				print $form->textwithpicto($langs->trans("SyntaxHelp").' '.img_help(2, $langs->trans("SyntaxHelp")), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution');
+			}
 		}
 		print '</span>'; // end websitehelp
 
@@ -3566,16 +3566,16 @@ if ($action == 'editmeta' || $action == 'createcontainer')
 	}
 
 	print '<tr><td class="titlefieldcreate">';
-    print 'ObjectClass';
-    print '</td><td>';
-    print '<input type="text" class="flat minwidth300" name="WEBSITE_OBJECTCLASS" placeholder="ClassName::/path/class/ObjectClass.class.php" >';
-    print '</td></tr>';
+	print 'ObjectClass';
+	print '</td><td>';
+	print '<input type="text" class="flat minwidth300" name="WEBSITE_OBJECTCLASS" placeholder="ClassName::/path/class/ObjectClass.class.php" >';
+	print '</td></tr>';
 
-    print '<tr><td class="titlefieldcreate">';
-    print 'ObjectID';
-    print '</td><td>';
-    print '<input type="text" class="flat minwidth300" name="WEBSITE_OBJECTID" >';
-    print '</td></tr>';
+	print '<tr><td class="titlefieldcreate">';
+	print 'ObjectID';
+	print '</td><td>';
+	print '<input type="text" class="flat minwidth300" name="WEBSITE_OBJECTID" >';
+	print '</td></tr>';
 
 
 	$fuser = new User($db);
@@ -3585,8 +3585,8 @@ if ($action == 'editmeta' || $action == 'createcontainer')
 	print '</td><td>';
 	if ($pageauthorid > 0)
 	{
-	    $fuser->fetch($pageauthorid);
-	    print $fuser->getNomUrl(1);
+		$fuser->fetch($pageauthorid);
+		print $fuser->getNomUrl(1);
 	} else {
 		print '<span class="opacitymedium">'.$langs->trans("Unknown").'</span>';
 	}
@@ -3607,17 +3607,17 @@ if ($action == 'editmeta' || $action == 'createcontainer')
 
 	if ($action != 'createcontainer')
 	{
-	    print '<tr><td>';
-	    print $langs->trans('UserModif');
-	    print '</td><td>';
-	    if ($pageusermodifid > 0)
-	    {
-	        $fuser->fetch($pageusermodifid);
-	        print $fuser->getNomUrl(1);
-	    }
-	    print '</td></tr>';
+		print '<tr><td>';
+		print $langs->trans('UserModif');
+		print '</td><td>';
+		if ($pageusermodifid > 0)
+		{
+			$fuser->fetch($pageusermodifid);
+			print $fuser->getNomUrl(1);
+		}
+		print '</td></tr>';
 
-	    print '<tr><td>';
+		print '<tr><td>';
 		print $langs->trans('DateModification');
 		print '</td><td>';
 		print dol_print_date($pagedatemodification, 'dayhour', 'tzuser');
@@ -4232,7 +4232,7 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa
 		// Change the contenteditable to "true" or "false" when mode Edit Inline is on or off
 		if (empty($conf->global->WEBSITE_EDITINLINE))
 		{
-		    // Remove the contenteditable="true"
+			// Remove the contenteditable="true"
 			$newcontent = preg_replace('/(div|section)(\s[^\>]*)contenteditable="true"/', '\1\2', $newcontent);
 		}
 		else {

+ 33 - 33
htdocs/website/websiteaccount_card.php

@@ -55,7 +55,7 @@ $search_all = GETPOST("search_all", 'alpha');
 $search = array();
 foreach ($object->fields as $key => $val)
 {
-    if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha');
+	if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha');
 }
 
 if (empty($action) && empty($id) && empty($ref)) $action = 'view';
@@ -198,7 +198,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 {
 	if ($object->fk_soc > 0 && empty($socid)) $socid = $object->fk_soc;
 
-    $res = $object->fetch_optionals();
+	$res = $object->fetch_optionals();
 
 	$head = websiteaccountPrepareHead($object);
 	dol_fiche_head($head, 'card', $langs->trans("WebsiteAccount"), -1, 'websiteaccount@website');
@@ -207,7 +207,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 
 	// Confirmation to delete
 	if ($action == 'delete') {
-	    $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteWebsiteAccount'), $langs->trans('ConfirmDeleteWebsiteAccount'), 'confirm_delete', '', 0, 1);
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteWebsiteAccount'), $langs->trans('ConfirmDeleteWebsiteAccount'), 'confirm_delete', '', 0, 1);
 	}
 
 	// Call Hook formConfirm
@@ -298,24 +298,24 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 
 	// Buttons for actions
 	if ($action != 'presend' && $action != 'editline') {
-    	print '<div class="tabsAction">'."\n";
-    	$parameters = array();
-    	$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-    	if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
-
-    	if (empty($reshook))
-    	{
-    	    // Send
-    		if (empty($user->socid)) {
-    			print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'."\n";
-    		}
-
-    		if ($user->rights->website->write)
-    		{
-    			print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n";
-    		}
-
-    		/*
+		print '<div class="tabsAction">'."\n";
+		$parameters = array();
+		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+		if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+
+		if (empty($reshook))
+		{
+			// Send
+			if (empty($user->socid)) {
+				print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'."\n";
+			}
+
+			if ($user->rights->website->write)
+			{
+				print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n";
+			}
+
+			/*
     		if ($user->rights->sellyoursaas->create)
     		{
     			if ($object->status == 1)
@@ -329,28 +329,28 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
     		}
     		*/
 
-    		if ($user->rights->website->delete)
-    		{
-    			print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n";
-    		}
-    	}
-    	print '</div>'."\n";
+			if ($user->rights->website->delete)
+			{
+				print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n";
+			}
+		}
+		print '</div>'."\n";
 	}
 
 
 	// Select mail models is same action as presend
 	if (GETPOST('modelselected')) {
-	    $action = 'presend';
+		$action = 'presend';
 	}
 
 	if ($action != 'presend')
 	{
-	    print '<div class="fichecenter"><div class="fichehalfleft">';
-	    print '<a name="builddoc"></a>'; // ancre
+		print '<div class="fichecenter"><div class="fichehalfleft">';
+		print '<a name="builddoc"></a>'; // ancre
 
-	    print '</div><div class="fichehalfright"><div class="ficheaddleft">';
+		print '</div><div class="fichehalfright"><div class="ficheaddleft">';
 
-	    /*
+		/*
 	    $MAXEVENT = 10;
 
 	    // List of actions on element
@@ -359,7 +359,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	    $somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT);
 	    */
 
-	    print '</div></div></div>';
+		print '</div></div></div>';
 	}
 
 	// Presend form

+ 71 - 71
htdocs/zapier/hook_card.php

@@ -82,31 +82,31 @@ $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action
 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
 
 if (empty($reshook)) {
-    $error = 0;
-
-    $permissiontoadd = $user->rights->mymodule->write;
-    $permissiontodelete = $user->rights->mymodule->delete || ($permissiontoadd && $object->status == 0);
-    $backurlforlist = dol_buildpath('/mymodule/myobject_list.php', 1);
-    if (empty($backtopage)) {
-        if (empty($id)) $backtopage = $backurlforlist;
-        else $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).($id > 0 ? $id : '__ID__');
-    }
-    $triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record
-
-    // Actions cancel, add, update, delete or clone
-    include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
-
-    // Actions when linking object each other
-    include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
-
-    // Actions when printing a doc from card
-    include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
-
-    // Actions to send emails
-    $triggersendname = 'MYOBJECT_SENTBYMAIL';
-    $autocopy = 'MAIN_MAIL_AUTOCOPY_MYOBJECT_TO';
-    $trackid = 'myobject'.$object->id;
-    include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
+	$error = 0;
+
+	$permissiontoadd = $user->rights->mymodule->write;
+	$permissiontodelete = $user->rights->mymodule->delete || ($permissiontoadd && $object->status == 0);
+	$backurlforlist = dol_buildpath('/mymodule/myobject_list.php', 1);
+	if (empty($backtopage)) {
+		if (empty($id)) $backtopage = $backurlforlist;
+		else $backtopage = dol_buildpath('/mymodule/myobject_card.php', 1).($id > 0 ? $id : '__ID__');
+	}
+	$triggermodname = 'MYMODULE_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record
+
+	// Actions cancel, add, update, delete or clone
+	include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
+
+	// Actions when linking object each other
+	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
+
+	// Actions when printing a doc from card
+	include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
+
+	// Actions to send emails
+	$triggersendname = 'MYOBJECT_SENTBYMAIL';
+	$autocopy = 'MAIN_MAIL_AUTOCOPY_MYOBJECT_TO';
+	$trackid = 'myobject'.$object->id;
+	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
 }
 
 
@@ -176,7 +176,7 @@ if (($id || $ref) && $action == 'edit') {
 	print load_fiche_titre($langs->trans("MyObject"));
 
 	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
-    print '<input type="hidden" name="token" value="'.newToken().'">';
+	print '<input type="hidden" name="token" value="'.newToken().'">';
 	print '<input type="hidden" name="action" value="update">';
 	print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
 	print '<input type="hidden" name="id" value="'.$object->id.'">';
@@ -204,7 +204,7 @@ if (($id || $ref) && $action == 'edit') {
 
 // Part to show record
 if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
-    $res = $object->fetch_optionals();
+	$res = $object->fetch_optionals();
 
 	$head = myobjectPrepareHead($object);
 	dol_fiche_head($head, 'card', $langs->trans("MyObject"), -1, 'myobject@mymodule');
@@ -213,7 +213,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 
 	// Confirmation to delete
 	if ($action == 'delete') {
-	    $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteMyObject'), 'confirm_delete', '', 0, 1);
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMyObject'), $langs->trans('ConfirmDeleteMyObject'), 'confirm_delete', '', 0, 1);
 	}
 
 	// Clone confirmation
@@ -226,7 +226,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	// Confirmation of action xxxx
 	if ($action == 'xxx') {
 		$formquestion = array();
-	    /*
+		/*
 		$forcecombo=0;
 		if ($conf->browser->name == 'ie') $forcecombo = 1;	// There is a bug in IE10 that make combo inside popup crazy
 	    $formquestion = array(
@@ -236,7 +236,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	        // array('type' => 'other',    'name' => 'idwarehouse',   'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
         );
 	    */
-	    $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220);
+		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220);
 	}
 
 	// Call Hook formConfirm
@@ -320,25 +320,25 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 
 	// Buttons for actions
 	if ($action != 'presend' && $action != 'editline') {
-    	print '<div class="tabsAction">'."\n";
-    	$parameters = array();
-    	$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
-    	if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
-
-    	if (empty($reshook)) {
-            // Modify
-    		if ($user->rights->mymodule->write) {
-    			print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n";
-    		} else {
-    			print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n";
-    		}
-
-    		// Clone
-    		if ($user->rights->mymodule->write) {
-    			print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object=order">'.$langs->trans("ToClone").'</a></div>';
-    		}
-
-    		/*
+		print '<div class="tabsAction">'."\n";
+		$parameters = array();
+		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+		if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+
+		if (empty($reshook)) {
+			// Modify
+			if ($user->rights->mymodule->write) {
+				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a>'."\n";
+			} else {
+				print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Modify').'</a>'."\n";
+			}
+
+			// Clone
+			if ($user->rights->mymodule->write) {
+				print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object=order">'.$langs->trans("ToClone").'</a></div>';
+			}
+
+			/*
     		if ($user->rights->mymodule->write)
     		{
     			if ($object->status == 1)
@@ -352,13 +352,13 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
     		}
     		*/
 
-    		if ($user->rights->mymodule->delete) {
-    			print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n";
-    		} else {
-    			print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";
-    		}
-    	}
-    	print '</div>'."\n";
+			if ($user->rights->mymodule->delete) {
+				print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'."\n";
+			} else {
+				print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans('Delete').'</a>'."\n";
+			}
+		}
+		print '</div>'."\n";
 	}
 
 
@@ -368,28 +368,28 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
 	}
 
 	if ($action != 'presend') {
-	    print '<div class="fichecenter"><div class="fichehalfleft">';
-	    print '<a name="builddoc"></a>'; // ancre
+		print '<div class="fichecenter"><div class="fichehalfleft">';
+		print '<a name="builddoc"></a>'; // ancre
 
-	    // Show links to link elements
-	    $linktoelem = $form->showLinkToObjectBlock($object, null, array('myobject'));
-	    $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
+		// Show links to link elements
+		$linktoelem = $form->showLinkToObjectBlock($object, null, array('myobject'));
+		$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
 
 
-	    print '</div><div class="fichehalfright"><div class="ficheaddleft">';
+		print '</div><div class="fichehalfright"><div class="ficheaddleft">';
 
-	    $MAXEVENT = 10;
+		$MAXEVENT = 10;
 
-	    $morehtmlright = '<a href="'.dol_buildpath('/mymodule/myobject_info.php', 1).'?id='.$object->id.'">';
-	    $morehtmlright .= $langs->trans("SeeAll");
-	    $morehtmlright .= '</a>';
+		$morehtmlright = '<a href="'.dol_buildpath('/mymodule/myobject_info.php', 1).'?id='.$object->id.'">';
+		$morehtmlright .= $langs->trans("SeeAll");
+		$morehtmlright .= '</a>';
 
-	    // List of actions on element
-	    include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
-	    $formactions = new FormActions($db);
-	    $somethingshown = $formactions->showactions($object, 'myobject', $socid, 1, '', $MAXEVENT, '', $morehtmlright);
+		// List of actions on element
+		include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
+		$formactions = new FormActions($db);
+		$somethingshown = $formactions->showactions($object, 'myobject', $socid, 1, '', $MAXEVENT, '', $morehtmlright);
 
-	    print '</div></div></div>';
+		print '</div></div></div>';
 	}
 
 	//Select mail models is same action as presend

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