From 6e75a3d203c269a3ca62a21d4b5ce72712a2fd99 Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@users.sourceforge.net>
Date: Wed, 1 Dec 2010 21:16:28 +0000
Subject: [PATCH] Restore work lost by savannah backup

---
 htdocs/adherents/class/cotisation.class.php   |   3 +-
 htdocs/admin/delais.php                       |  34 +-
 htdocs/admin/menus/menu.js.php                |   2 +-
 htdocs/cashdesk/index.php                     |   2 +-
 htdocs/cashdesk/sql/llx_pos_tmp.sql           |   2 +-
 htdocs/comm/action/fiche.php                  |   3 +-
 htdocs/comm/mailing/cibles.php                |   6 +-
 htdocs/comm/mailing/fiche.php                 |   6 +-
 htdocs/commande/index.php                     |  14 +-
 htdocs/compta/facture/class/facture.class.php |  59 +--
 .../class/bon-prelevement.class.php           |  16 +-
 htdocs/compta/prelevement/fiche.php           |   8 +-
 htdocs/compta/prelevement/ligne.php           |   2 +-
 htdocs/conf/conf.php.example                  |   5 +-
 htdocs/contact/class/contact.class.php        |   6 +-
 htdocs/contact/fiche.php                      |   2 +-
 htdocs/core/tpl/login.tpl.php                 |   2 +-
 htdocs/ecm/docfile.php                        |   2 +-
 htdocs/ecm/index.php                          |   4 +-
 .../fourn/class/fournisseur.facture.class.php |   2 +-
 htdocs/fourn/commande/fiche.php               |  17 +-
 htdocs/fourn/commande/index.php               | 160 +++++++-
 htdocs/fourn/facture/fiche.php                | 375 +++++++++++++++---
 htdocs/lib/company.lib.php                    |   6 +-
 htdocs/lib/databases/mssql.lib.php            |   2 +-
 htdocs/lib/databases/mysql.lib.php            |   2 +-
 htdocs/lib/databases/mysqli.lib.php           |   2 +-
 htdocs/lib/databases/pgsql.lib.php            |  22 +-
 htdocs/lib/functions.lib.php                  |  12 +-
 htdocs/lib/pdf.lib.php                        |  20 +-
 htdocs/webservices/admin/webservices.php      |  83 +++-
 htdocs/webservices/client.php                 |   7 +-
 scripts/emailings/mailing-send.php            |  13 +-
 33 files changed, 733 insertions(+), 168 deletions(-)

diff --git a/htdocs/adherents/class/cotisation.class.php b/htdocs/adherents/class/cotisation.class.php
index 58c8ec5aacb..dd5c6e11d49 100644
--- a/htdocs/adherents/class/cotisation.class.php
+++ b/htdocs/adherents/class/cotisation.class.php
@@ -67,10 +67,11 @@ class Cotisation extends CommonObject
 	 */
 	function create($userid)
 	{
+		global $langs;
 		// Check parameters
 		if ($this->datef <= $this->dateh)
 		{
-			$this->error="Error: Bad value for datef or dateh";
+			$this->error=$langs->trans("ErrorBadValueForDate");
 			return -1;
 		}
 
diff --git a/htdocs/admin/delais.php b/htdocs/admin/delais.php
index 2eae95790a1..6b1065c0ceb 100644
--- a/htdocs/admin/delais.php
+++ b/htdocs/admin/delais.php
@@ -52,6 +52,8 @@ if ( (isset($_POST["action"]) && $_POST["action"] == 'update'))
     if ($_POST["TransactionsToConciliate"]) dolibarr_set_const($db, "MAIN_DELAY_TRANSACTIONS_TO_CONCILIATE",$_POST["TransactionsToConciliate"],'chaine',0,'',$conf->entity);
     if ($_POST["ChequesToDeposit"]) dolibarr_set_const($db, "MAIN_DELAY_CHEQUES_TO_DEPOSIT",$_POST["ChequesToDeposit"],'chaine',0,'',$conf->entity);
     if ($_POST["Members"]) dolibarr_set_const($db, "MAIN_DELAY_MEMBERS",$_POST["Members"],'chaine',0,'',$conf->entity);
+
+    dolibarr_set_const($db, "MAIN_DISABLE_METEO",$_POST["MAIN_DISABLE_METEO"],'chaine',0,'',$conf->entity);
 }
 
 
@@ -178,6 +180,19 @@ if ((isset($_GET["action"]) && $_GET["action"] == 'edit'))
 
     print '</table>';
 
+    print '<br>';
+
+	// Show if meteo is enabled
+	print '<table class="noborder" width="100%">';
+	print '<tr class="liste_titre"><td>'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
+
+	$var=!$var;
+	print '<tr '.$bc[$var].'>';
+	print '<td>'.$langs->trans("MAIN_DISABLE_METEO").'</td><td>' .$form->selectyesno('MAIN_DISABLE_METEO',$conf->global->MAIN_DISABLE_METEO,1) . '</td></tr>';
+
+	print '</table>';
+
+	print '<br>';
 
     print '<br><center><input type="submit" class="button" value="'.$langs->trans("Save").'"></center>';
     print '<br>';
@@ -190,7 +205,7 @@ else
      * Affichage des parametres
      */
 
-    print '<table class="noborder" width="100%">';
+	print '<table class="noborder" width="100%">';
     print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("DelaysOfToleranceBeforeWarning").'</td><td>'.$langs->trans("Value").'</td></tr>';
     $var=true;
 
@@ -289,6 +304,20 @@ else
 
     print '</table>';
 
+	print '<br>';
+
+	// Show if meteo is enabled
+	print '<table class="noborder" width="100%">';
+	print '<tr class="liste_titre"><td>'.$langs->trans("Parameter").'</td><td>'.$langs->trans("Value").'</td></tr>';
+
+	$var=!$var;
+	print '<tr '.$bc[$var].'>';
+	print '<td>'.$langs->trans("MAIN_DISABLE_METEO").'</td><td>' . yn($conf->global->MAIN_DISABLE_METEO) . '</td></tr>';
+
+	print '</table>';
+
+	print '<br>';
+
     // Boutons d'action
     print '<div class="tabsAction">';
     print '<a class="butAction" href="delais.php?action=edit">'.$langs->trans("Modify").'</a>';
@@ -296,6 +325,9 @@ else
 
 }
 
+print '<br>';
+
+
 // Show logo for weather
 print $langs->trans("DescWeather").'<br>';
 
diff --git a/htdocs/admin/menus/menu.js.php b/htdocs/admin/menus/menu.js.php
index 46a8c71d927..0a26385fe1e 100644
--- a/htdocs/admin/menus/menu.js.php
+++ b/htdocs/admin/menus/menu.js.php
@@ -51,7 +51,7 @@ var MOZ = (!IE && !OPE) ? true : false;
 // -----------------------------------------------------
 // Fonction d'initialisation de l'arbre
 function arbre() {
-    // Choix de la balise contenant le texte. <strong> par defaut.
+    // Choix de la balise contenant le texte. (strong par defaut).
     balise = "STRONG";
     // Presentation de l'arbre au depart : deployee ('yes') ou fermee ('no')
     extend = "no";
diff --git a/htdocs/cashdesk/index.php b/htdocs/cashdesk/index.php
index 5df22e0b4d9..4a9d0fcc650 100644
--- a/htdocs/cashdesk/index.php
+++ b/htdocs/cashdesk/index.php
@@ -48,7 +48,7 @@ $usertxt=GETPOST('user','',1);
 $form=new Form($db);
 $formproduct=new FormProduct($db);
 
-$arrayofcss=array(DOL_URL_ROOT.'/cashdesk/css/style.css');
+$arrayofcss=array('/cashdesk/css/style.css');
 top_htmlhead('','',0,0,'',$arrayofcss);
 ?>
 
diff --git a/htdocs/cashdesk/sql/llx_pos_tmp.sql b/htdocs/cashdesk/sql/llx_pos_tmp.sql
index ed8e939ce70..51fad72bc84 100755
--- a/htdocs/cashdesk/sql/llx_pos_tmp.sql
+++ b/htdocs/cashdesk/sql/llx_pos_tmp.sql
@@ -19,7 +19,7 @@
 -- ===========================================================================
 
 CREATE TABLE llx_pos_tmp (
-  id integer NOT NULL auto_increment,
+  id integer NOT NULL AUTO_INCREMENT PRIMARY KEY,
   fk_article integer NOT NULL,
   qte real NOT NULL,
   fk_tva integer NOT NULL,
diff --git a/htdocs/comm/action/fiche.php b/htdocs/comm/action/fiche.php
index 13c03810ae8..7339189fcd5 100644
--- a/htdocs/comm/action/fiche.php
+++ b/htdocs/comm/action/fiche.php
@@ -3,6 +3,7 @@
  * Copyright (C) 2004-2010 Laurent Destailleur  <eldy@users.sourceforge.net>
  * Copyright (C) 2005      Simon TOSSER         <simon@kornog-computing.com>
  * Copyright (C) 2005-2009 Regis Houssin        <regis@dolibarr.fr>
+ * Copyright (C) 2010      Juanjo Menent        <jmenent@2byte.es>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -836,7 +837,7 @@ if ($id)
 
 		// Ref
 		print '<tr><td width="30%">'.$langs->trans("Ref").'</td><td colspan="3">';
-		print $html->showrefnav($act,'id','',1,'id','ref','');
+		print $html->showrefnav($act,'id','',($user->societe_id?0:1),'id','ref','');
 		print '</td></tr>';
 
 		// Type
diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php
index 6bdbae8d46c..d591dda1f15 100644
--- a/htdocs/comm/mailing/cibles.php
+++ b/htdocs/comm/mailing/cibles.php
@@ -21,7 +21,7 @@
 /**
  *       \file       htdocs/comm/mailing/cibles.php
  *       \ingroup    mailing
- *       \brief      Page des cibles de mailing
+ *       \brief      Page to define emailing targets
  *       \version    $Id$
  */
 
@@ -354,7 +354,7 @@ if ($mil->fetch($_REQUEST["id"]) >= 0)
 	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
 	print '<input type="hidden" name="id" value="'.$mil->id.'">';
 
-	$sql  = "SELECT mc.rowid, mc.nom, mc.prenom, mc.email, mc.other, mc.statut, mc.date_envoi, mc.url";
+	$sql  = "SELECT mc.rowid, mc.nom, mc.prenom, mc.email, mc.other, mc.statut, mc.date_envoi, mc.source_url, mc.source_id, mc.source_type";
 	$sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
 	$sql .= " WHERE mc.fk_mailing=".$mil->id;
 	if ($search_nom)    $sql.= " AND mc.nom    like '%".addslashes($search_nom)."%'";
@@ -439,7 +439,7 @@ if ($mil->fetch($_REQUEST["id"]) >= 0)
 				print '<td>'.$obj->nom.'</td>';
 				print '<td>'.$obj->prenom.'</td>';
 				print '<td>'.$obj->other.'</td>';
-				print '<td align="center">'.$obj->url.'</td>';
+				print '<td align="center">'.$obj->source_url.'</td>';
 
 				// Statut pour l'email destinataire (Attentioon != statut du mailing)
 				if ($obj->statut == 0)
diff --git a/htdocs/comm/mailing/fiche.php b/htdocs/comm/mailing/fiche.php
index b9a9dd9e363..3ef4e369575 100644
--- a/htdocs/comm/mailing/fiche.php
+++ b/htdocs/comm/mailing/fiche.php
@@ -131,7 +131,7 @@ if ($_REQUEST["action"] == 'sendallconfirmed' && $_REQUEST['confirm'] == 'yes')
 
 		// On choisit les mails non deja envoyes pour ce mailing (statut=0)
 		// ou envoyes en erreur (statut=-1)
-		$sql = "SELECT mc.rowid, mc.nom, mc.prenom, mc.email, mc.other";
+		$sql = "SELECT mc.rowid, mc.nom, mc.prenom, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type";
 		$sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
 		$sql .= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$id;
 
@@ -174,7 +174,7 @@ if ($_REQUEST["action"] == 'sendallconfirmed' && $_REQUEST['confirm'] == 'yes')
 					$other4=$other[3];
 					$other5=$other[4];
 					$substitutionarray=array(
-						'__ID__' => $obj->rowid,
+						'__ID__' => $obj->source_id,
 						'__EMAIL__' => $obj->email,
 						'__LASTNAME__' => $obj->nom,
 						'__FIRSTNAME__' => $obj->prenom,
@@ -616,7 +616,7 @@ if ($_GET["action"] == 'create')
 	print '<tr><td width="25%">'.$langs->trans("BackgroundColorByDefault").'</td><td colspan="3">';
 	$htmlother->select_color($_POST['bgcolor'],'bgcolor','new_mailing',0);
 	print '</td></tr>';
-	print '<tr><td width="25%" valign="top">'.$langs->trans("MailMessage").'<br>';
+	print '<tr><td width="25%" class="fieldrequired" valign="top">'.$langs->trans("MailMessage").'<br>';
 	print '<br><i>'.$langs->trans("CommonSubstitutions").':<br>';
 	foreach($substitutionarray as $key => $val)
 	{
diff --git a/htdocs/commande/index.php b/htdocs/commande/index.php
index 40741f148e8..733bf54e00b 100644
--- a/htdocs/commande/index.php
+++ b/htdocs/commande/index.php
@@ -34,7 +34,7 @@ if (!$user->rights->commande->lire) accessforbidden();
 
 $langs->load("orders");
 
-// S�curit� acc�s client
+// Security check
 $socid='';
 if ($_GET["socid"]) { $socid=$_GET["socid"]; }
 if ($user->societe_id > 0)
@@ -121,10 +121,11 @@ if ($conf->commande->enabled)
 print '</td><td valign="top" width="70%" class="notopnoleftnoright">';
 
 
+$max=5;
+
 /*
- * Last closes orders
+ * Last modified orders
  */
-$max=5;
 
 $sql = "SELECT c.rowid, c.ref, c.fk_statut, c.facture, s.nom, s.rowid as socid,";
 $sql.= " date_cloture as datec";
@@ -133,7 +134,7 @@ $sql.= ", ".MAIN_DB_PREFIX."societe as s";
 if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
 $sql.= " WHERE c.fk_soc = s.rowid";
 $sql.= " AND c.entity = ".$conf->entity;
-$sql.= " AND c.fk_statut > 2";
+//$sql.= " AND c.fk_statut > 2";
 if ($socid) $sql .= " AND c.fk_soc = ".$socid;
 if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
 $sql.= " ORDER BY c.tms DESC";
@@ -144,7 +145,7 @@ if ($resql)
 {
 	print '<table class="noborder" width="100%">';
 	print '<tr class="liste_titre">';
-	print '<td colspan="4">'.$langs->trans("LastClosedOrders",$max).'</td></tr>';
+	print '<td colspan="4">'.$langs->trans("LastModifiedOrders",$max).'</td></tr>';
 
 	$num = $db->num_rows($resql);
 	if ($num)
@@ -189,6 +190,7 @@ if ($resql)
 	}
 	print "</table><br>";
 }
+else dol_print_error($db);
 
 
 /*
@@ -259,6 +261,7 @@ if ($conf->commande->enabled)
 
 		print "</table><br>";
 	}
+	else dol_print_error($db);
 }
 
 /*
@@ -328,6 +331,7 @@ if ($conf->commande->enabled)
 		}
 		print "</table><br>";
 	}
+	else dol_print_error($db);
 }
 
 
diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php
index 4bdd5054899..2a2606d0a6c 100644
--- a/htdocs/compta/facture/class/facture.class.php
+++ b/htdocs/compta/facture/class/facture.class.php
@@ -50,15 +50,14 @@ class Facture extends CommonObject
 	var $fk_element = 'fk_facture';
 	var $ismultientitymanaged = 1;	// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
 
-	var $table;
-	var $tabledetail;
 	var $id;
 	//! Id client
 	var $socid;
 	//! Objet societe client (to load with fetch_client method)
 	var $client;
-	var $number;
 	var $author;
+	var $fk_user_author;
+	var $fk_user_valid;
 	//! Invoice date
 	var $date;				// Invoice date
 	var $date_creation;		// Creation date
@@ -80,15 +79,15 @@ class Facture extends CommonObject
 	//! 2=classified paid partially (close_code='discount_vat','badcustomer') or completely (close_code=null),
 	//! 3=classified abandoned and no payment done (close_code='badcustomer','abandon' ou 'replaced')
 	var $statut;
-	//! 1 if invoice paid COMPLETELY, 0 otherwise (ce champ ne devrait plus servir car insuffisant)
-	var $paye;
-	//! id of source invoice if replacement invoice or credit note
-	var $fk_facture_source;
 	//! Fermeture apres paiement partiel: discount_vat, badcustomer, abandon
 	//! Fermeture alors que aucun paiement: replaced (si remplace), abandon
 	var $close_code;
 	//! Commentaire si mis a paye sans paiement complet
 	var $close_note;
+	//! 1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code
+	var $paye;
+	//! id of source invoice if replacement invoice or credit note
+	var $fk_facture_source;
 	var $origin;
 	var $origin_id;
 	var $fk_project;
@@ -605,10 +604,10 @@ class Facture extends CommonObject
 
 
 	/**
-	 *	\brief      Get object and lines from database
-	 *	\param      rowid       id of object to load
-	 * 	\param		ref			Ref of invoice
-	 *	\return     int         >0 if OK, <0 if KO
+	 *	Get object and lines from database
+	 *	@param      rowid       id of object to load
+	 * 	@param		ref			Ref of invoice
+	 *	@return     int         >0 if OK, <0 if KO
 	 */
 	function fetch($rowid,$ref='')
 	{
@@ -682,8 +681,6 @@ class Facture extends CommonObject
 
 				$this->commande_id            = $obj->fk_commande;
 
-				$this->lignes                 = array();
-
 				if ($this->commande_id)
 				{
 					$sql = "SELECT ref";
@@ -705,6 +702,10 @@ class Facture extends CommonObject
 				/*
 				 * Lines
 				 */
+
+				$this->lignes = array();	// deprecated
+				$this->lines  = array();
+
 				$result=$this->fetch_lines();
 				if ($result < 0)
 				{
@@ -1640,7 +1641,7 @@ class Facture extends CommonObject
 	 * 		Add an invoice line into database (linked to product/service or not)
 	 * 		\param    	facid           	Id de la facture
 	 * 		\param    	desc            	Description de la ligne
-	 * 		\param    	pu_ht              	Prix unitaire HT
+	 * 		\param    	pu_ht              	Prix unitaire HT (> 0 even for credit note)
 	 * 		\param    	qty             	Quantite
 	 * 		\param    	txtva           	Taux de tva force, sinon -1
 	 * 		\param		txlocaltax1			Local tax 1 rate
@@ -1653,7 +1654,7 @@ class Facture extends CommonObject
 	 * 		\param    	info_bits			Bits de type de lignes
 	 *		\param    	fk_remise_except	Id remise
 	 *		\param		price_base_type		HT or TTC
-	 * 		\param    	pu_ttc             	Prix unitaire TTC
+	 * 		\param    	pu_ttc             	Prix unitaire TTC (> 0 even for credit note)
 	 * 		\param		type				Type of line (0=product, 1=service)
 	 *      \param      rang                Position of line
 	 *    	\return    	int             	>0 if OK, <0 if KO
@@ -1747,23 +1748,23 @@ class Facture extends CommonObject
 			$this->line->fk_product=$fk_product;
 			$this->line->product_type=$product_type;
 			$this->line->remise_percent=$remise_percent;
-			$this->line->subprice=$pu_ht;
+			$this->line->subprice=($this->type==2?-1:1)*$pu_ht;
 			$this->line->date_start=$date_start;
 			$this->line->date_end=$date_end;
 			$this->line->ventil=$ventil;
 			$this->line->rang=$rangtouse;
 			$this->line->info_bits=$info_bits;
 			$this->line->fk_remise_except=$fk_remise_except;
-			$this->line->total_ht=$total_ht;
-			$this->line->total_tva=$total_tva;
-			$this->line->total_localtax1=$total_localtax1;
-			$this->line->total_localtax2=$total_localtax2;
-			$this->line->total_ttc=$total_ttc;
+			$this->line->total_ht=($this->type==2?-1:1)*$total_ht;
+			$this->line->total_tva=($this->type==2?-1:1)*$total_tva;
+			$this->line->total_localtax1=($this->type==2?-1:1)*$total_localtax1;
+			$this->line->total_localtax2=($this->type==2?-1:1)*$total_localtax2;
+			$this->line->total_ttc=($this->type==2?-1:1)*$total_ttc;
 			$this->line->special_code=$special_code;
 
 			// \TODO Ne plus utiliser
-			$this->line->price=$price;
-			$this->line->remise=$remise;
+			$this->line->price=($this->type==2?-1:1)*$price;
+			$this->line->remise=($this->type==2?-1:1)*$remise;
 
 			$result=$this->line->insert();
 			if ($result > 0)
@@ -1797,7 +1798,7 @@ class Facture extends CommonObject
 	 *      Update a detail line
 	 *      @param     	rowid           Id of line to update
 	 *      @param     	desc            Description of line
-	 *      @param     	pu              Prix unitaire (HT ou TTC selon price_base_type)
+	 *      @param     	pu              Prix unitaire (HT ou TTC selon price_base_type) (> 0 even for credit note lines)
 	 *      @param     	qty             Quantity
 	 *      @param     	remise_percent  Pourcentage de remise de la ligne
 	 *      @param     	date_start      Date de debut de validite du service
@@ -1865,13 +1866,13 @@ class Facture extends CommonObject
 			$this->line->localtax1_tx		= $txlocaltax1;
 			$this->line->localtax2_tx		= $txlocaltax2;
 			$this->line->remise_percent		= $remise_percent;
-			$this->line->subprice			= $pu;
+			$this->line->subprice			= ($this->type==2?-1:1)*$pu;
 			$this->line->date_start			= $date_start;
 			$this->line->date_end			= $date_end;
-			$this->line->total_ht			= $total_ht;
-			$this->line->total_tva			= $total_tva;
-			$this->line->total_localtax1	= $total_localtax1;
-			$this->line->total_localtax2	= $total_localtax2;
+			$this->line->total_ht			= ($this->type==2?-1:1)*$total_ht;
+			$this->line->total_tva			= ($this->type==2?-1:1)*$total_tva;
+			$this->line->total_localtax1	= ($this->type==2?-1:1)*$total_localtax1;
+			$this->line->total_localtax2	= ($this->type==2?-1:1)*$total_localtax2;
 			$this->line->total_ttc			= $total_ttc;
 			$this->line->info_bits			= $info_bits;
 			$this->line->product_type		= $type;
diff --git a/htdocs/compta/prelevement/class/bon-prelevement.class.php b/htdocs/compta/prelevement/class/bon-prelevement.class.php
index 3d47fbadca3..9175e069954 100644
--- a/htdocs/compta/prelevement/class/bon-prelevement.class.php
+++ b/htdocs/compta/prelevement/class/bon-prelevement.class.php
@@ -379,6 +379,19 @@ class BonPrelevement extends CommonObject
                         $message.= "Date credit : ".dol_print_date($date,'dayhour');
 
                         $this->Notify($user, "cr", $subject, $message);
+                   
+                        // Update prelevement line 
+                        // TODO: Translate to ligne-prelevement.class.php
+                		$sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
+                		$sql.= " SET statut = 2";
+                		$sql.= " WHERE fk_prelevement_bons = ".$this->id;
+
+                		if (! $this->db->query($sql))
+                		{
+                    		dol_syslog("BonPrelevement::set_credite Erreur 1");
+                    		$error++;
+                		}
+            
                     }
                     else
                     {
@@ -466,6 +479,7 @@ class BonPrelevement extends CommonObject
              * Fin de la procedure
              *
              */
+        
             if ($error == 0)
             {
                 $this->db->commit();
@@ -504,7 +518,7 @@ class BonPrelevement extends CommonObject
         $sql.= " WHERE pn.action = '".$action."'";
         $sql.= " AND u.rowid = pn.fk_user";
         $sql.= " AND u.entity IN (0,".$conf->entity.")";
-
+        dol_syslog("BonPrelevement::Notify: ".$sql, LOG_CRIT);
         $resql = $this->db->query($sql);
         if ($resql)
         {
diff --git a/htdocs/compta/prelevement/fiche.php b/htdocs/compta/prelevement/fiche.php
index 085adfeaa13..7d6fcafc6e6 100644
--- a/htdocs/compta/prelevement/fiche.php
+++ b/htdocs/compta/prelevement/fiche.php
@@ -156,16 +156,16 @@ if ($_GET["id"])
 			$muser = new User($db);
 			$muser->fetch($bon->user_trans);
 
-			print '<tr><td width="20%">Date Transmission / Par</td><td>';
+			print '<tr><td width="20%">'.$langs->trans("TransData").'</td><td>';
 			print dol_print_date($bon->date_trans,'dayhour');
 			print ' / '.$muser->getFullName($langs).'</td></tr>';
-			print '<tr><td width="20%">Methode Transmission</td><td>';
+			print '<tr><td width="20%">'.$langs->trans("TransMetod").'</td><td>';
 			print $bon->methodes_trans[$bon->method_trans];
 			print '</td></tr>';
 		}
 		if($bon->date_credit <> 0)
 		{
-			print '<tr><td width="20%">Credit on</td><td>';
+			print '<tr><td width="20%">'.$langs->trans('CreditDate').'</td><td>';
 			print dol_print_date($bon->date_credit,'dayhour');
 			print '</td></tr>';
 		}
@@ -200,7 +200,7 @@ if ($_GET["id"])
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 			print '<input type="hidden" name="action" value="infocredit">';
 			print '<table class="border" width="100%">';
-			print '<tr><td width="20%">Cr�dit� le</td><td>';
+			print '<tr><td width="20%">'.$langs->trans('CreditDate').'</td><td>';
 			print $html->select_date('','','','','',"infocredit");
 			print '</td></tr>';
 			print '<tr><td colspan="2" align="center">';
diff --git a/htdocs/compta/prelevement/ligne.php b/htdocs/compta/prelevement/ligne.php
index 8c855520145..c1a8f3499ff 100644
--- a/htdocs/compta/prelevement/ligne.php
+++ b/htdocs/compta/prelevement/ligne.php
@@ -312,7 +312,7 @@ if ($_GET["id"])
 	if ($_GET["action"] == '')
 	{
 
-		if ($bon->credite == 1 && $lipre->statut == 2)
+		if ($bon->statut == 2 && $lipre->statut == 2)
 		{
 	  		print "<a class=\"butAction\" href=\"ligne.php?action=rejet&amp;id=$lipre->id\">".$langs->trans("StandingOrderReject")."</a>";
 		}
diff --git a/htdocs/conf/conf.php.example b/htdocs/conf/conf.php.example
index c95b3990a28..ebc3e7a9263 100644
--- a/htdocs/conf/conf.php.example
+++ b/htdocs/conf/conf.php.example
@@ -134,11 +134,14 @@ $dolibarr_main_db_collation='latin1_swedish_ci';
 # If value "ldap" is used, you must also set parameters dolibarr_main_auth_ldap_*
 # Default value: dolibarr
 # Possible values: Any values found in files in htdocs/includes/login directory after
-# the "function_" string and before the ".php" string.
+# the "function_" string and before the ".php" string. You can also separate several
+# values using a ",". In this case, Dolibarr will check login/pass for each value in 
+# order defined into value. However, note that this can't work with all values.
 # Examples:
 # $dolibarr_main_authentication='http';
 # $dolibarr_main_authentication='dolibarr';
 # $dolibarr_main_authentication='ldap';
+# $dolibarr_main_authentication='openid,dolibarr';
 #
 $dolibarr_main_authentication='dolibarr';
 
diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php
index b3821491bdd..ed58812dfc3 100644
--- a/htdocs/contact/class/contact.class.php
+++ b/htdocs/contact/class/contact.class.php
@@ -179,9 +179,9 @@ class Contact extends CommonObject
 
 	/**
 	 *      Update informations into database
-	 *      @param      id          	Id du contact a mettre a jour
-	 *      @param      user        	Objet utilisateur qui effectue la mise a jour
-	 *      @param      notrigger	    0=non, 1=oui
+	 *      @param      id          	Id of contact/address to update
+	 *      @param      user        	Objet user making change
+	 *      @param      notrigger	    0=no, 1=yesi
 	 *      @return     int         	<0 if KO, >0 if OK
 	 */
 	function update($id, $user=0, $notrigger=0)
diff --git a/htdocs/contact/fiche.php b/htdocs/contact/fiche.php
index 4b615ebbc45..05702e3463c 100644
--- a/htdocs/contact/fiche.php
+++ b/htdocs/contact/fiche.php
@@ -151,7 +151,7 @@ else
 			if ($id <= 0)
 			{
                 $error++;
-			    $errors=array($object->error);
+			    $errors=($object->error?array($object->error):$object->errors);
 				$_GET["action"] = $_POST["action"] = 'create';
 			}
 		}
diff --git a/htdocs/core/tpl/login.tpl.php b/htdocs/core/tpl/login.tpl.php
index fe677632094..0c8ef6fc4bc 100644
--- a/htdocs/core/tpl/login.tpl.php
+++ b/htdocs/core/tpl/login.tpl.php
@@ -80,7 +80,7 @@ function donnefocus() {
 
 <td valign="bottom"> &nbsp; <b><?php echo $langs->trans('Login'); ?></b> &nbsp; </td>
 <td valign="bottom" nowrap="nowrap">
-<input type="text" id="username" name="username" class="flat" size="15" maxlength="25" value="<?php echo $login; ?>" tabindex="1" /></td>
+<input type="text" id="username" name="username" class="flat" size="15" maxlength="40" value="<?php echo $login; ?>" tabindex="1" /></td>
 
 <td rowspan="<?php echo $rowspan; ?>" align="center" valign="top">
 <img alt="Logo" title="" src="<?php echo $urllogo; ?>" />
diff --git a/htdocs/ecm/docfile.php b/htdocs/ecm/docfile.php
index 7f80ebeb1f1..790acd14aaa 100644
--- a/htdocs/ecm/docfile.php
+++ b/htdocs/ecm/docfile.php
@@ -219,7 +219,7 @@ $userecm->fetch($ecmdir->fk_user_c);
 print $userecm->getNomUrl(1);
 print '</td></tr>';
 */
-print '<tr><td>'.$langs->trans("ECMCreationDate").'</td><td>';
+print '<tr><td>'.$langs->trans("ECMCreationDate").'</td><td>aa';
 print dol_print_date(dol_filemtime($fullpath),'dayhour');
 print '</td></tr>';
 /*print '<tr><td>'.$langs->trans("ECMDirectoryForFiles").'</td><td>';
diff --git a/htdocs/ecm/index.php b/htdocs/ecm/index.php
index a635c8f76fa..3aaeb916b1c 100644
--- a/htdocs/ecm/index.php
+++ b/htdocs/ecm/index.php
@@ -298,6 +298,8 @@ $morejs=array(
 "/includes/jquery/plugins/layout/jquery.layout-latest.js"
 );
 */
+$maxheightwin=660;
+
 $morehead="<style type=\"text/css\">
 html, body {
         width:      100%;
@@ -308,7 +310,7 @@ html, body {
     }
     #containerlayout {
         background: #999;
-        height:     660px;
+        height:     ".$maxheightwin."px;
         margin:     0 auto;
         width:      100%;
         min-width:  700px;
diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php
index f7cb04b6a24..1e6e6dca001 100644
--- a/htdocs/fourn/class/fournisseur.facture.class.php
+++ b/htdocs/fourn/class/fournisseur.facture.class.php
@@ -764,7 +764,7 @@ class FactureFournisseur extends Facture
 		}
 		else
 		{
-			$this->error=$ligne->error;
+			$this->error=$this->db->lasterror();
 			$this->db->rollback();
 			return -2;
 		}
diff --git a/htdocs/fourn/commande/fiche.php b/htdocs/fourn/commande/fiche.php
index 0406926fdc5..7ba49f39a94 100644
--- a/htdocs/fourn/commande/fiche.php
+++ b/htdocs/fourn/commande/fiche.php
@@ -107,7 +107,7 @@ if ($_GET['action'] == 'reopen' && $user->rights->fournisseur->commande->approuv
 }
 
 /*
- *	Ajout d'une	ligne produit dans la commande
+ *	Add a line into product
  */
 if ($_POST['action'] ==	'addline' && $user->rights->fournisseur->commande->creer)
 {
@@ -1294,12 +1294,27 @@ if ($id > 0 || ! empty($ref))
 					}
 				}
 
+				// Create bill
+				if ($conf->fournisseur->enabled && $commande->statut > 0)
+				{
+					if ($user->rights->fournisseur->facture->creer)
+					{
+						print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/fiche.php?action=create&amp;origin='.$commande->element.'&amp;originid='.$commande->id.'&amp;socid='.$commande->socid.'">'.$langs->trans("CreateBill").'</a>';
+					}
+
+					//if ($user->rights->fournisseur->commande->creer && $object->statut > 2)
+					//{
+					//	print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifybilled">'.$langs->trans("ClassifyBilled").'</a>';
+					//}
+				}
+
 				// Delete
 				if ($user->rights->fournisseur->commande->supprimer)
 				{
 					print '<a class="butActionDelete" href="fiche.php?id='.$commande->id.'&amp;action=delete">'.$langs->trans("Delete").'</a>';
 				}
 
+
 				print "</div>";
 			}
 
diff --git a/htdocs/fourn/commande/index.php b/htdocs/fourn/commande/index.php
index 797dfc5a082..67abdce1df6 100644
--- a/htdocs/fourn/commande/index.php
+++ b/htdocs/fourn/commande/index.php
@@ -26,6 +26,7 @@
  */
 
 require("../../main.inc.php");
+require_once(DOL_DOCUMENT_ROOT."/core/class/html.formfile.class.php");
 require_once(DOL_DOCUMENT_ROOT."/fourn/class/fournisseur.commande.class.php");
 require_once(DOL_DOCUMENT_ROOT."/contact/class/contact.class.php");
 
@@ -44,8 +45,9 @@ $langs->load("orders");
 
 llxHeader('',$langs->trans("SuppliersOrdersArea"));
 
-$commande = new CommandeFournisseur($db);
+$commandestatic = new CommandeFournisseur($db);
 $userstatic=new User($db);
+$formfile = new FormFile($db);
 
 print_barre_liste($langs->trans("SuppliersOrdersArea"), $page, "index.php", "", $sortfield, $sortorder, '', $num);
 
@@ -101,8 +103,8 @@ if ($resql)
       $var=!$var;
 
       print "<tr $bc[$var]>";
-      print '<td>'.$langs->trans($commande->statuts[$row[1]]).'</td>';
-      print '<td align="right"><a href="liste.php?statut='.$row[1].'">'.$row[0].' '.$commande->LibStatut($row[1],3).'</a></td>';
+      print '<td>'.$langs->trans($commandestatic->statuts[$row[1]]).'</td>';
+      print '<td align="right"><a href="liste.php?statut='.$row[1].'">'.$row[0].' '.$commandestatic->LibStatut($row[1],3).'</a></td>';
 
       print "</tr>\n";
       $i++;
@@ -158,9 +160,9 @@ if ($conf->fournisseur->enabled)
 }
 
 
-print '</td><td width="70%" valign="top" class="notopnoleft">';
-
-
+/*
+ * List of users allowed
+ */
 $sql = "SELECT u.rowid, u.name, u.firstname";
 $sql.= " FROM ".MAIN_DB_PREFIX."user as u,";
 $sql.= " ".MAIN_DB_PREFIX."user_rights as ur";
@@ -199,7 +201,7 @@ if ($resql)
       print "</tr>\n";
       $i++;
     }
-  print "</table>";
+  print "</table><br>";
   $db->free($resql);
 }
 else
@@ -207,6 +209,150 @@ else
   dol_print_error($db);
 }
 
+
+print '</td><td width="70%" valign="top" class="notopnoleft">';
+
+
+/*
+ * Last modified orders
+ */
+$max=5;
+
+$sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom, s.rowid as socid,";
+$sql.= " date_cloture as datec";
+$sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
+$sql.= ", ".MAIN_DB_PREFIX."societe as s";
+if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+$sql.= " WHERE c.fk_soc = s.rowid";
+$sql.= " AND c.entity = ".$conf->entity;
+//$sql.= " AND c.fk_statut > 2";
+if ($socid) $sql .= " AND c.fk_soc = ".$socid;
+if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
+$sql.= " ORDER BY c.tms DESC";
+$sql.= $db->plimit($max, 0);
+
+$resql=$db->query($sql);
+if ($resql)
+{
+	print '<table class="noborder" width="100%">';
+	print '<tr class="liste_titre">';
+	print '<td colspan="4">'.$langs->trans("LastModifiedOrders",$max).'</td></tr>';
+
+	$num = $db->num_rows($resql);
+	if ($num)
+	{
+		$i = 0;
+		$var = True;
+		while ($i < $num)
+		{
+			$var=!$var;
+			$obj = $db->fetch_object($resql);
+
+			print "<tr $bc[$var]>";
+			print '<td width="20%" nowrap="nowrap">';
+
+			$commandestatic->id=$obj->rowid;
+			$commandestatic->ref=$obj->ref;
+
+			print '<table class="nobordernopadding"><tr class="nocellnopadd">';
+			print '<td width="94" class="nobordernopadding" nowrap="nowrap">';
+			print $commandestatic->getNomUrl(1);
+			print '</td>';
+
+			print '<td width="16" class="nobordernopadding" nowrap="nowrap">';
+			print '&nbsp;';
+			print '</td>';
+
+			print '<td width="16" align="right" class="nobordernopadding">';
+			$filename=dol_sanitizeFileName($obj->ref);
+			$filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref);
+			$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
+			$formfile->show_documents('commande',$filename,$filedir,$urlsource,'','','',1,'',1);
+			print '</td></tr></table>';
+
+			print '</td>';
+
+			print '<td><a href="'.DOL_URL_ROOT.'/comm/fiche.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowCompany"),"company").' '.$obj->nom.'</a></td>';
+			print '<td>'.dol_print_date($db->jdate($obj->datec)).'</td>';
+			print '<td align="right">'.$commandestatic->LibStatut($obj->fk_statut,5).'</td>';
+			print '</tr>';
+			$i++;
+		}
+	}
+	print "</table><br>";
+}
+else dol_print_error($db);
+
+
+/*
+ * Orders to process
+ */
+/*
+$sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom, s.rowid as socid";
+$sql.=" FROM ".MAIN_DB_PREFIX."commande_fournisseur as c";
+$sql.= ", ".MAIN_DB_PREFIX."societe as s";
+if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+$sql.= " WHERE c.fk_soc = s.rowid";
+$sql.= " AND c.entity = ".$conf->entity;
+$sql.= " AND c.fk_statut = 1";
+if ($socid) $sql.= " AND c.fk_soc = ".$socid;
+if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
+$sql.= " ORDER BY c.rowid DESC";
+
+$resql=$db->query($sql);
+if ($resql)
+{
+	$num = $db->num_rows($resql);
+
+	print '<table class="noborder" width="100%">';
+	print '<tr class="liste_titre">';
+	print '<td colspan="3">'.$langs->trans("OrdersToProcess").' <a href="'.DOL_URL_ROOT.'/commande/liste.php?viewstatut=1">('.$num.')</a></td></tr>';
+
+	if ($num)
+	{
+		$i = 0;
+		$var = True;
+		while ($i < $num)
+		{
+			$var=!$var;
+			$obj = $db->fetch_object($resql);
+			print "<tr $bc[$var]>";
+			print '<td nowrap="nowrap">';
+
+			$commandestatic->id=$obj->rowid;
+			$commandestatic->ref=$obj->ref;
+
+			print '<table class="nobordernopadding"><tr class="nocellnopadd">';
+			print '<td width="94" class="nobordernopadding" nowrap="nowrap">';
+			print $commandestatic->getNomUrl(1);
+			print '</td>';
+
+			print '<td width="16" class="nobordernopadding" nowrap="nowrap">';
+			print '&nbsp;';
+			print '</td>';
+
+			print '<td width="16" align="right" class="nobordernopadding">';
+			$filename=dol_sanitizeFileName($obj->ref);
+			$filedir=$conf->commande->dir_output . '/' . dol_sanitizeFileName($obj->ref);
+			$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
+			$formfile->show_documents('commande',$filename,$filedir,$urlsource,'','','',1,'',1);
+			print '</td></tr></table>';
+
+			print '</td>';
+
+			print '<td><a href="'.DOL_URL_ROOT.'/comm/fiche.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->nom,24).'</a></td>';
+
+			print '<td align="right">'.$commandestatic->LibStatut($obj->fk_statut,$obj->facture,5).'</td>';
+
+			print '</tr>';
+			$i++;
+		}
+	}
+
+	print "</table><br>";
+}
+*/
+
 print '</td></tr></table>';
 
 $db->close();
diff --git a/htdocs/fourn/facture/fiche.php b/htdocs/fourn/facture/fiche.php
index 5a03b028cd5..eda13c50ca1 100644
--- a/htdocs/fourn/facture/fiche.php
+++ b/htdocs/fourn/facture/fiche.php
@@ -187,7 +187,9 @@ if ($_POST['action'] == 'update' && ! $_POST['cancel'])
  */
 if ($_POST['action'] == 'add' && $user->rights->fournisseur->facture->creer)
 {
-    $datefacture=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
+	$error=0;
+
+	$datefacture=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
     $datedue=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
 
     if ($datefacture == '')
@@ -219,12 +221,97 @@ if ($_POST['action'] == 'add' && $user->rights->fournisseur->facture->creer)
         $facfou->date_echeance = $datedue;
         $facfou->note_public   = $_POST['note'];
 
-        $facid = $facfou->create($user);
-
-        // Ajout des lignes de factures
-        if ($facid > 0)
-        {
-            for ($i = 1 ; $i < 9 ; $i++)
+        // If creation from another object of another module
+		if ($_POST['origin'] && $_POST['originid'])
+		{
+			// Parse element/subelement (ex: project_task)
+			$element = $subelement = $_POST['origin'];
+			/*if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs))
+			{
+				$element = $regs[1];
+				$subelement = $regs[2];
+			}*/
+
+			// For compatibility
+    		if ($element == 'order')    { $element = $subelement = 'commande'; }
+    		if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
+    		if ($element == 'contract') { $element = $subelement = 'contrat'; }
+    		if ($element == 'order_supplier') { $element = 'fourn'; $subelement = 'fournisseur.commande'; }
+
+			$facfou->origin 	= $_POST['origin'];
+			$facfou->origin_id = $_POST['originid'];
+
+			$facid = $facfou->create($user);
+
+        	// Add lines
+			if ($facid > 0)
+			{
+				require_once(DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php');
+				$classname = ucfirst($subelement);
+    			if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur';
+				$srcobject = new $classname($db);
+
+				$result=$srcobject->fetch($_POST['originid']);
+				if ($result > 0)
+				{
+					// TODO mutualiser
+					$lines = $srcobject->lignes;
+					if (sizeof($lines)) $lines = $srcobject->lines;
+					if (empty($lines) && method_exists($srcobject,'fetch_lignes')) $lines = $srcobject->fetch_lignes();
+					if (empty($lines) && method_exists($srcobject,'fetch_lines'))  $lines = $srcobject->fetch_lines();
+
+					for ($i = 0 ; $i < sizeof($lines) ; $i++)
+					{
+					    $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
+						$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
+
+						// Dates
+						// TODO mutualiser
+						$date_start=$lines[$i]->date_debut_prevue;
+						if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
+						if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
+						$date_end=$lines[$i]->date_fin_prevue;
+						if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
+						if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
+
+						$result = $facfou->addline(
+						$desc,
+						$lines[$i]->subprice,
+						$lines[$i]->tva_tx,
+						$lines[$i]->qty,
+						$lines[$i]->fk_product,
+						$lines[$i]->remise_percent,
+						$date_start,
+						$date_end,
+						0,
+						$lines[$i]->info_bits,
+						'HT',
+						$product_type
+						);
+
+						if ($result < 0)
+						{
+							$error++;
+							break;
+						}
+					}
+				}
+				else
+				{
+					$error++;
+				}
+			}
+			else
+			{
+				$error++;
+			}
+		}
+		// If some invoice's lines already known
+		else
+		{
+	        $facid = $facfou->create($user);
+
+			for ($i = 1 ; $i < 9 ; $i++)
             {
                 $label = $_POST['label'.$i];
                 $amountht  = price2num($_POST['amount'.$i]);
@@ -244,30 +331,24 @@ if ($_POST['action'] == 'add' && $user->rights->fournisseur->facture->creer)
                     }
                     $atleastoneline=1;
                     $ret=$facfou->addline($label, $amount, $tauxtva, $qty, $fk_product, $remise_percent, '', '', '', 0, $price_base);
-                    if ($ret < 0) $nberror++;
+                    if ($ret < 0) $error++;
                 }
             }
-            if ($nberror)
-            {
-                $db->rollback();
-                $mesg='<div class="error">'.$facfou->error.'</div>';
-                $_GET['action']='create';
-                $_GET['socid']=$_POST['socid'];
-            }
-            else
-            {
-                $db->commit();
-                header('Location: fiche.php?facid='.$facid);
-                exit;
-            }
         }
-        else
+
+        if ($error)
         {
             $db->rollback();
             $mesg='<div class="error">'.$facfou->error.'</div>';
             $_GET['action']='create';
             $_GET['socid']=$_POST['socid'];
         }
+        else
+        {
+            $db->commit();
+            header('Location: fiche.php?facid='.$facid);
+            exit;
+        }
     }
 }
 
@@ -761,17 +842,70 @@ if ($_GET['action'] == 'create')
         $societe->fetch($_GET['socid']);
     }
 
-    $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
-    $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0):$datetmp);
-    $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
-    $datedue=($datetmp==''?-1:$datetmp);
-
-    print '<form name="add" action="fiche.php" method="post">';
+	if (GETPOST('origin') && GETPOST('originid'))
+	{
+		// Parse element/subelement (ex: project_task)
+		$element = $subelement = GETPOST('origin');
+		/*if (preg_match('/^([^_]+)_([^_]+)/i',$_GET['origin'],$regs))
+		{
+			$element = $regs[1];
+			$subelement = $regs[2];
+		}*/
+
+		if ($element == 'project')
+		{
+            $projectid=GETPOST('originid');
+		}
+		else if (in_array($element,array('order_supplier')))
+		{
+    		// For compatibility
+    		if ($element == 'order')    { $element = $subelement = 'commande'; }
+    		if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
+    		if ($element == 'contract') { $element = $subelement = 'contrat'; }
+    		if ($element == 'order_supplier') { $element = 'fourn'; $subelement = 'fournisseur.commande'; }
+
+    		require_once(DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php');
+    		$classname = ucfirst($subelement);
+    		if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur';
+    		$objectsrc = new $classname($db);
+    		$objectsrc->fetch(GETPOST('originid'));
+    		$objectsrc->fetch_thirdparty();
+
+    		$projectid			= (!empty($objectsrc->fk_project)?$object->fk_project:'');
+    		//$ref_client			= (!empty($objectsrc->ref_client)?$object->ref_client:'');
+
+    		$soc = $objectsrc->client;
+    		$cond_reglement_id 	= (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1));
+    		$mode_reglement_id 	= (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0));
+    		$remise_percent 	= (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0));
+    		$remise_absolue 	= (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0));
+    		$dateinvoice		= empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0;
+
+			$datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
+		    $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0):$datetmp);
+	    	$datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
+		    $datedue=($datetmp==''?-1:$datetmp);
+		}
+	}
+	else
+	{
+		$datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
+	    $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0):$datetmp);
+    	$datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
+	    $datedue=($datetmp==''?-1:$datetmp);
+	}
+
+    print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">';
     print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
     print '<input type="hidden" name="action" value="add">';
+    print '<input type="hidden" name="origin" value="'.GETPOST('origin').'">';
+    print '<input type="hidden" name="originid" value="'.GETPOST('originid').'">';
     print '<table class="border" width="100%">';
 
-    // Third party
+	// Ref
+	print '<tr><td>'.$langs->trans('Ref').'</td><td>'.$langs->trans('Draft').'</td></tr>';
+
+	// Third party
     print '<tr><td class="fieldrequired">'.$langs->trans('Company').'</td>';
     print '<td>';
 
@@ -785,13 +919,96 @@ if ($_GET['action'] == 'create')
         $html->select_societes((empty($_GET['socid'])?'':$_GET['socid']),'socid','s.fournisseur = 1',1);
     }
     print '</td>';
-    print '<td width="50%">'.$langs->trans('NotePublic').'</td></tr>';
 
     // Ref supplier
     print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="facnumber" value="'.(isset($_POST['facnumber'])?$_POST['facnumber']:$fac_ori->ref).'" type="text"></td>';
-    print '<td width="50%" rowspan="4" valign="top"><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td></tr>';
-
-    // Label
+    print '</tr>';
+
+	print '<tr><td valign="top" class="fieldrequired">'.$langs->trans('Type').'</td><td colspan="2">';
+	print '<table class="nobordernopadding">'."\n";
+
+	// Standard invoice
+	print '<tr height="18"><td width="16px" valign="middle">';
+	print '<input type="radio" name="type" value="0"'.($_POST['type']==0?' checked="true"':'').'>';
+	print '</td><td valign="middle">';
+	$desc=$html->textwithpicto($langs->trans("InvoiceStandardAsk"),$langs->transnoentities("InvoiceStandardDesc"),1);
+	print $desc;
+	print '</td></tr>'."\n";
+
+	/*
+	// Deposit
+	print '<tr height="18"><td width="16px" valign="middle">';
+	print '<input type="radio" name="type" value="3"'.($_POST['type']==3?' checked="true"':'').'>';
+	print '</td><td valign="middle">';
+	$desc=$html->textwithpicto($langs->trans("InvoiceDeposit"),$langs->transnoentities("InvoiceDepositDesc"),1);
+	print $desc;
+	print '</td></tr>'."\n";
+
+	// Proforma
+	if ($conf->global->FACTURE_USE_PROFORMAT)
+	{
+		print '<tr height="18"><td width="16px" valign="middle">';
+		print '<input type="radio" name="type" value="4"'.($_POST['type']==4?' checked="true"':'').'>';
+		print '</td><td valign="middle">';
+		$desc=$html->textwithpicto($langs->trans("InvoiceProForma"),$langs->transnoentities("InvoiceProFormaDesc"),1);
+		print $desc;
+		print '</td></tr>'."\n";
+	}
+
+	// Replacement
+	print '<tr height="18"><td valign="middle">';
+	print '<input type="radio" name="type" value="1"'.($_POST['type']==1?' checked=true':'');
+	if (! $options) print ' disabled="true"';
+	print '>';
+	print '</td><td valign="middle">';
+	$text=$langs->trans("InvoiceReplacementAsk").' ';
+	$text.='<select class="flat" name="fac_replacement"';
+	if (! $options) $text.=' disabled="true"';
+	$text.='>';
+	if ($options)
+	{
+		$text.='<option value="-1">&nbsp;</option>';
+		$text.=$options;
+	}
+	else
+	{
+		$text.='<option value="-1">'.$langs->trans("NoReplacableInvoice").'</option>';
+	}
+	$text.='</select>';
+	$desc=$html->textwithpicto($text,$langs->transnoentities("InvoiceReplacementDesc"),1);
+	print $desc;
+	print '</td></tr>';
+
+		// Credit note
+	print '<tr height="18"><td valign="middle">';
+	print '<input type="radio" name="type" value="2"'.($_POST['type']==2?' checked=true':'');
+	if (! $optionsav) print ' disabled="true"';
+	print '>';
+	print '</td><td valign="middle">';
+	$text=$langs->transnoentities("InvoiceAvoirAsk").' ';
+	//	$text.='<input type="text" value="">';
+	$text.='<select class="flat" name="fac_avoir"';
+	if (! $optionsav) $text.=' disabled="true"';
+	$text.='>';
+	if ($optionsav)
+	{
+		$text.='<option value="-1">&nbsp;</option>';
+		$text.=$optionsav;
+	}
+	else
+	{
+		$text.='<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
+	}
+	$text.='</select>';
+	$desc=$html->textwithpicto($text,$langs->transnoentities("InvoiceAvoirDesc"),1);
+	//.' ('.$langs->trans("FeatureNotYetAvailable").')',$langs->transnoentities("InvoiceAvoirDesc"),1);
+	print $desc;
+	print '</td></tr>'."\n";
+*/
+	print '</table>';
+	print '</td></tr>';
+
+	// Label
     print '<tr><td>'.$langs->trans('Label').'</td><td><input size="30" name="libelle" value="'.(isset($_POST['libelle'])?$_POST['libelle']:$fac_ori->libelle).'" type="text"></td></tr>';
 
     // Date invoice
@@ -804,38 +1021,72 @@ if ($_GET['action'] == 'create')
     $html->select_date($datedue,'ech','','','',"add",1,1);
     print '</td></tr>';
 
-    print '</table><br>';
-
-    if ($conf->global->PRODUCT_SHOW_WHEN_CREATE)
+    print '<tr><td>'.$langs->trans('NotePublic').'</td>';
+    print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
+    print '</tr>';
+
+	if (is_object($objectsrc))
+	{
+		print "\n<!-- ".$classname." info -->";
+		print "\n";
+		print '<input type="hidden" name="amount"         value="'.$objectsrc->total_ht.'">'."\n";
+		print '<input type="hidden" name="total"          value="'.$objectsrc->total_ttc.'">'."\n";
+		print '<input type="hidden" name="tva"            value="'.$objectsrc->total_tva.'">'."\n";
+		print '<input type="hidden" name="origin"         value="'.$objectsrc->element.'">';
+		print '<input type="hidden" name="originid"       value="'.$objectsrc->id.'">';
+
+		$txt=$langs->trans($classname);
+		if ($classname=='CommandeFournisseur') $txt=$langs->trans("SupplierOrder");
+		print '<tr><td>'.$txt.'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>';
+		print '<tr><td>'.$langs->trans('TotalHT').'</td><td colspan="2">'.price($objectsrc->total_ht).'</td></tr>';
+		print '<tr><td>'.$langs->trans('TotalVAT').'</td><td colspan="2">'.price($objectsrc->total_tva)."</td></tr>";
+		if ($mysoc->pays_code=='ES')
+		{
+			if ($mysoc->localtax1_assuj=="1") //Localtax1 RE
+			{
+				print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->pays_code).'</td><td colspan="2">'.price($objectsrc->total_localtax1)."</td></tr>";
+			}
+
+			if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF
+			{
+				print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->pays_code).'</td><td colspan="2">'.price($objectsrc->total_localtax2)."</td></tr>";
+			}
+		}
+		print '<tr><td>'.$langs->trans('TotalTTC').'</td><td colspan="2">'.price($objectsrc->total_ttc)."</td></tr>";
+	}
+    else
     {
-        print '<table class="border" width="100%">';
-        print '<tr class="liste_titre">';
-        print '<td>&nbsp;</td><td>'.$langs->trans('Label').'</td>';
-        print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
-        print '<td align="right">'.$langs->trans('VAT').'</td>';
-        print '<td align="right">'.$langs->trans('Qty').'</td>';
-        print '<td align="right">'.$langs->trans('PriceUTTC').'</td>';
-        print '</tr>';
-
-        for ($i = 1 ; $i < 9 ; $i++)
-        {
-            $value_qty = '1';
-            $value_tauxtva = '';
-            print '<tr><td>'.$i.'</td>';
-            print '<td><input size="50" name="label'.$i.'" value="'.$value_label.'" type="text"></td>';
-            print '<td align="right"><input type="text" size="8" name="amount'.$i.'" value="'.$value_pu.'"></td>';
-            print '<td align="right">';
-            $html->select_tva('tauxtva'.$i,$value_tauxtva,$societe,$mysoc);
-            print '</td>';
-            print '<td align="right"><input type="text" size="3" name="qty'.$i.'" value="'.$value_qty.'"></td>';
-            print '<td align="right"><input type="text" size="8" name="amountttc'.$i.'" value=""></td></tr>';
-        }
-
-        print '</table>';
+	    if ($conf->global->PRODUCT_SHOW_WHEN_CREATE)
+	    {
+	        print '<tr class="liste_titre">';
+	        print '<td>&nbsp;</td><td>'.$langs->trans('Label').'</td>';
+	        print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
+	        print '<td align="right">'.$langs->trans('VAT').'</td>';
+	        print '<td align="right">'.$langs->trans('Qty').'</td>';
+	        print '<td align="right">'.$langs->trans('PriceUTTC').'</td>';
+	        print '</tr>';
+
+	        for ($i = 1 ; $i < 9 ; $i++)
+	        {
+	            $value_qty = '1';
+	            $value_tauxtva = '';
+	            print '<tr><td>'.$i.'</td>';
+	            print '<td><input size="50" name="label'.$i.'" value="'.$value_label.'" type="text"></td>';
+	            print '<td align="right"><input type="text" size="8" name="amount'.$i.'" value="'.$value_pu.'"></td>';
+	            print '<td align="right">';
+	            $html->select_tva('tauxtva'.$i,$value_tauxtva,$societe,$mysoc);
+	            print '</td>';
+	            print '<td align="right"><input type="text" size="3" name="qty'.$i.'" value="'.$value_qty.'"></td>';
+	            print '<td align="right"><input type="text" size="8" name="amountttc'.$i.'" value=""></td></tr>';
+	        }
+	    }
     }
+    	// Bouton "Create Draft"
+	print "</table>\n";
+
+	print '<br><center><input type="submit" class="button" name="bouton" value="'.$langs->trans('CreateDraft').'"></center>';
 
-    print '<center><input type="submit" class="button" value="'.$langs->trans('Save').'"></center>';
-    print '</form>';
+	print "</form>\n";
 }
 else
 {
diff --git a/htdocs/lib/company.lib.php b/htdocs/lib/company.lib.php
index 8d80509f8f4..3f94e2005f2 100644
--- a/htdocs/lib/company.lib.php
+++ b/htdocs/lib/company.lib.php
@@ -577,15 +577,15 @@ function show_actions_todo($conf,$langs,$db,$objsoc,$objcon='')
 
                     $obj = $db->fetch_object($result);
                     
-                    $datep=$obj->dp;
+                    $datep=$db->jdate($obj->dp);
                     
                     print "<tr ".$bc[$var].">";
 
-                    print '<td width="100" align="left" nowrap="nowrap">'.dol_print_date($datep,'dayhour')."</td>\n";
+                    print '<td width="120" align="left" nowrap="nowrap">'.dol_print_date($datep,'dayhour')."</td>\n";
 
                     // Picto warning
                     print '<td width="16">';
-                    if ($datep && $datep < time()) print ' '.img_warning($langs->trans("Late"));
+                    if ($datep && $datep < (time()- ($conf->global->MAIN_DELAY_ACTIONS_TODO *60*60*24)) ) print ' '.img_warning($langs->trans("Late"));
                     else print '&nbsp;';
                     print '</td>';
 
diff --git a/htdocs/lib/databases/mssql.lib.php b/htdocs/lib/databases/mssql.lib.php
index ab5f2d32d76..caf70c9f474 100644
--- a/htdocs/lib/databases/mssql.lib.php
+++ b/htdocs/lib/databases/mssql.lib.php
@@ -317,7 +317,7 @@ class DoliDb
      *  @param      type            Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
      *  @return     resource        Resultset of answer
 	 */
-	function query($query,$usesavepoint=0,$type='ddl')
+	function query($query,$usesavepoint=0,$type='auto')
 	{
 		$query = trim($query);
 
diff --git a/htdocs/lib/databases/mysql.lib.php b/htdocs/lib/databases/mysql.lib.php
index 04664a29f81..bbfe0ae9c1e 100644
--- a/htdocs/lib/databases/mysql.lib.php
+++ b/htdocs/lib/databases/mysql.lib.php
@@ -362,7 +362,7 @@ class DoliDb
      * @param       type            Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
 	 * @return	    resource    	Resultset of answer
 	 */
-	function query($query,$usesavepoint=0,$type='ddl')
+	function query($query,$usesavepoint=0,$type='auto')
 	{
 		$query = trim($query);
 
diff --git a/htdocs/lib/databases/mysqli.lib.php b/htdocs/lib/databases/mysqli.lib.php
index 699caa63dc8..bec39976c52 100644
--- a/htdocs/lib/databases/mysqli.lib.php
+++ b/htdocs/lib/databases/mysqli.lib.php
@@ -369,7 +369,7 @@ class DoliDb
      *  @param      type            Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
 	 *	@return	    resource    	Resultset of answer
 	 */
-	function query($query,$usesavepoint=0,$type='ddl')
+	function query($query,$usesavepoint=0,$type='auto')
 	{
 		$query = trim($query);
 		if (! $this->database_name)
diff --git a/htdocs/lib/databases/pgsql.lib.php b/htdocs/lib/databases/pgsql.lib.php
index c48a77197bf..1bf0087a294 100644
--- a/htdocs/lib/databases/pgsql.lib.php
+++ b/htdocs/lib/databases/pgsql.lib.php
@@ -154,7 +154,7 @@ class DoliDb
 	 *  @param     type     Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
 	 * 	@return    string	SQL request line converted
 	 */
-	function convertSQLFromMysql($line,$type='ddl')
+	function convertSQLFromMysql($line,$type='auto')
 	{
 		# Removed empty line if this is a comment line for SVN tagging
 		if (preg_match('/^--\s\$Id/i',$line)) {
@@ -167,17 +167,29 @@ class DoliDb
 		}
 		if ($line != "")
 		{
+		    if ($type == 'auto')
+		    {
+              if (preg_match('/ALTER TABLE/i',$line)) $type='dml';
+              else if (preg_match('/CREATE TABLE/i',$line)) $type='dml';
+              else if (preg_match('/DROP TABLE/i',$line)) $type='dml';
+		    }
+
 		    if ($type == 'dml')
 		    {
-    			# we are inside create table statement so lets process datatypes
+                $line=preg_replace('/\s/',' ',$line);   // Replace tabulation with space
+
+		        # we are inside create table statement so lets process datatypes
     			if (preg_match('/(ISAM|innodb)/i',$line)) { # end of create table sequence
     				$line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
     				$line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line);
     				$line=preg_replace('/,$/','',$line);
     			}
 
-    			if (preg_match('/[\s\t]*(\w*)\s*.*int.*auto_increment/i',$line,$reg)) {
-    				$line=preg_replace('/[\s\t]*([a-zA-Z_0-9]*)[\s\t]*.*int.*auto_increment[^,]*/i','\\1 SERIAL PRIMARY KEY',$line);
+    			// Process case: "CREATE TABLE llx_c_ziptown(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..."
+    			if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) {
+    				$newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 SERIAL PRIMARY KEY',$line);
+                    //$line = "-- ".$line." replaced by --\n".$newline;
+                    $line=$newline;
     			}
 
     			# tinyint type conversion
@@ -484,7 +496,7 @@ class DoliDb
      * @param       type            Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...)
 	 * @return	    resource    	Resultset of answer
 	 */
-	function query($query,$usesavepoint=0,$type='ddl')
+	function query($query,$usesavepoint=0,$type='auto')
 	{
 		$query = trim($query);
 
diff --git a/htdocs/lib/functions.lib.php b/htdocs/lib/functions.lib.php
index 30e6238b027..b0d9cc1ccae 100644
--- a/htdocs/lib/functions.lib.php
+++ b/htdocs/lib/functions.lib.php
@@ -1947,12 +1947,12 @@ function dolibarr_print_error($db='',$error='')
 }
 
 /**
- *	\brief      Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontee des bugs.
- *				On doit appeler cette fonction quand une erreur technique bloquante est rencontree.
- *				Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant
- *				renvoyer leur erreur par l'intermediaire de leur propriete "error".
- *	\param      db      Database handler
- *	\param      error	Chaine erreur ou tableau de chaines erreur complementaires a afficher
+ *	Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontee des bugs.
+ *	On doit appeler cette fonction quand une erreur technique bloquante est rencontree.
+ *	Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant
+ *	renvoyer leur erreur par l'intermediaire de leur propriete "error".
+ *	@param      db      	Database handler
+ *	@param      error		String or array of errors strings to show
  */
 function dol_print_error($db='',$error='')
 {
diff --git a/htdocs/lib/pdf.lib.php b/htdocs/lib/pdf.lib.php
index ee2e1e721b1..fa6535d56ee 100644
--- a/htdocs/lib/pdf.lib.php
+++ b/htdocs/lib/pdf.lib.php
@@ -46,6 +46,24 @@ function pdf_getPDFFont($outputlangs)
     return $font;
 }
 
+/**
+ *      Return font size to use for PDF generation
+ *      @param      outputlangs     Output langs object
+ *      @return     int             Size of font to use
+ */
+function pdf_getPDFFontSize($outputlangs)
+{
+    $size=10;                   // By default, for FPDI or ISO language on TCPDF
+    if (class_exists('TCPDF'))  // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower)
+    {
+        if ($outputlangs->trans('FONTSIZEFORPDF')!='FONTSIZEFORPDF')
+        {
+            $size = (int) $outputlangs->trans('FONTSIZEFORPDF');
+        }
+    }
+    return $size;
+}
+
 
 /**
  *      Return a formated address (part address/zip/town/state) according to country rules
@@ -741,4 +759,4 @@ function pdf_getlinetotalexcltax($object,$i,$outputlangs)
     }
 }
 
-?>
\ No newline at end of file
+?>
diff --git a/htdocs/webservices/admin/webservices.php b/htdocs/webservices/admin/webservices.php
index 6da12defe65..a545f47bdb5 100644
--- a/htdocs/webservices/admin/webservices.php
+++ b/htdocs/webservices/admin/webservices.php
@@ -33,17 +33,27 @@ if (!$user->admin)
   accessforbidden();
 
 
-if ($_POST["action"] == 'setvalue' && $user->admin)
+$actionsave=$_POST["save"];
+
+
+// Sauvegardes parametres
+if ($actionsave)
 {
-	//$result=dolibarr_set_const($db, "PAYBOX_IBS_DEVISE",$_POST["PAYBOX_IBS_DEVISE"],'chaine',0,'',$conf->entity);
-
-	if ($result >= 0)
-  	{
-  		$mesg='<div class="ok">'.$langs->trans("SetupSaved").'</div>';
-  	}
-  	else
-  	{
-		dol_print_error($db);
+    $i=0;
+
+    $db->begin();
+
+    $i+=dolibarr_set_const($db,'WEBSERVICES_KEY',trim($_POST["WEBSERVICES_KEY"]),'chaine',0,'',$conf->entity);
+
+    if ($i >= 1)
+    {
+        $db->commit();
+        $mesg = "<font class=\"ok\">".$langs->trans("SetupSaved")."</font>";
+    }
+    else
+    {
+        $db->rollback();
+        $mesg = "<font class=\"error\">".$langs->trans("SaveFailed")."</font>";
     }
 }
 
@@ -58,7 +68,32 @@ $linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToM
 print_fiche_titre($langs->trans("WebServicesSetup"),$linkback,'setup');
 
 print $langs->trans("WebServicesDesc")."<br>\n";
+print "<br>\n";
+
+print '<form name="agendasetupform" action="'.$_SERVER["PHP_SELF"].'" method="post">';
+print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+print "<table class=\"noborder\" width=\"100%\">";
+
+print "<tr class=\"liste_titre\">";
+print "<td>".$langs->trans("Parameter")."</td>";
+print "<td>".$langs->trans("Value")."</td>";
+//print "<td>".$langs->trans("Examples")."</td>";
+print "<td>&nbsp;</td>";
+print "</tr>";
+
+print "<tr class=\"impair\">";
+print '<td class="fieldrequired">'.$langs->trans("KeyForWebServicesAccess")."</td>";
+print "<td><input type=\"text\" class=\"flat\" name=\"WEBSERVICES_KEY\" value=\"". ($_POST["WEBSERVICES_KEY"]?$_POST["WEBSERVICES_KEY"]:$conf->global->WEBSERVICES_KEY) . "\" size=\"20\"></td>";
+print "<td>&nbsp;</td>";
+print "</tr>";
+
+print '</table>';
+
+print '<br><center>';
+print "<input type=\"submit\" name=\"save\" class=\"button\" value=\"".$langs->trans("Save")."\">";
+print "</center>";
 
+print '</form>';
 
 if ($mesg) print '<br>'.$mesg;
 
@@ -67,16 +102,40 @@ print '<br><br>';
 // Should work with DOL_URL_ROOT='' or DOL_URL_ROOT='/dolibarr'
 $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',$dolibarr_main_url_root);
 
+// WSDL
 print '<u>'.$langs->trans("WSDLCanBeDownloadedHere").':</u><br>';
-$url=$urlwithouturlroot.DOL_URL_ROOT.'/webservices/server.php?wsdl';
+$url=$urlwithouturlroot.DOL_URL_ROOT.'/webservices/server_other.php?wsdl';
 print img_picto('','object_globe.png').' '.'<a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
+if ($conf->societe->enabled)
+{
+	$url=$urlwithouturlroot.DOL_URL_ROOT.'/webservices/server_thirdparty.php?wsdl';
+	print img_picto('','object_globe.png').' '.'<a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
+}
+if ($conf->facture->enabled)
+{
+	$url=$urlwithouturlroot.DOL_URL_ROOT.'/webservices/server_invoice.php?wsdl';
+	print img_picto('','object_globe.png').' '.'<a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
+}
 print '<br>';
 
+
+// Endpoint
 print '<u>'.$langs->trans("EndPointIs").':</u><br>';
-$url=$urlwithouturlroot.DOL_URL_ROOT.'/webservices/server.php';
+$url=$urlwithouturlroot.DOL_URL_ROOT.'/webservices/server_other.php';
 print img_picto('','object_globe.png').' '.'<a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
+if ($conf->societe->enabled)
+{
+	$url=$urlwithouturlroot.DOL_URL_ROOT.'/webservices/server_societe.php';
+	print img_picto('','object_globe.png').' '.'<a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
+}
+if ($conf->facture->enabled)
+{
+	$url=$urlwithouturlroot.DOL_URL_ROOT.'/webservices/server_invoice.php';
+	print img_picto('','object_globe.png').' '.'<a href="'.$url.'" target="_blank">'.$url."</a><br>\n";
+}
 print '<br>';
 
+
 $db->close();
 
 llxFooter('$Date$ - $Revision$');
diff --git a/htdocs/webservices/client.php b/htdocs/webservices/client.php
index c9723d44545..e140562387f 100644
--- a/htdocs/webservices/client.php
+++ b/htdocs/webservices/client.php
@@ -32,7 +32,7 @@ $WS_DOL_URL = $dolibarr_main_url_root.'/webservices/server.php';
 $WS_METHOD  = 'getVersions';
 
 // Set the parameters to send to the WebService
-$parameters = array("param1"=>"value1");
+$parameters = array();
 
 // Set the WebService URL
 dol_syslog("Create soapclient_nusoap for URL=".$WS_DOL_URL);
@@ -45,6 +45,11 @@ if ($soapclient)
 // Call the WebService method and store its result in $result.
 dol_syslog("Call method ".$WS_METHOD);
 $result = $soapclient->call($WS_METHOD,$parameters);
+if (! $result)
+{
+	print $soapclient->error_str;
+	exit;
+}
 
 // Show page with result
 header("Content-type: text/html; charset=utf8");
diff --git a/scripts/emailings/mailing-send.php b/scripts/emailings/mailing-send.php
index c6bebcc82a0..f6f91ef3c02 100644
--- a/scripts/emailings/mailing-send.php
+++ b/scripts/emailings/mailing-send.php
@@ -76,8 +76,9 @@ if ($resql)
 		$from     = $obj->email_from;
 		$replyto  = $obj->email_replyto;
 		$errorsto = $obj->email_errorsto;
-
-		$msgishtml=-1;
+        // Le message est-il en html
+        $msgishtml=-1;  // Unknown by default
+        if (preg_match('/[\s\t]*<html>/i',$message)) $msgishtml=1;
 
 		$i++;
 	}
@@ -94,7 +95,7 @@ $nbok=0; $nbko=0;
 
 // On choisit les mails non deja envoyes pour ce mailing (statut=0)
 // ou envoyes en erreur (statut=-1)
-$sql = "SELECT mc.rowid, mc.nom, mc.prenom, mc.email, mc.other";
+$sql = "SELECT mc.rowid, mc.nom, mc.prenom, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type";
 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
 $sql .= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$id;
 
@@ -134,7 +135,7 @@ if ($resql)
 			$other4=$other[3];
 			$other5=$other[4];
 			$substitutionarray=array(
-				'__ID__' => $obj->rowid,
+				'__ID__' => $obj->source_id,
 				'__EMAIL__' => $obj->email,
 				'__LASTNAME__' => $obj->nom,
 				'__FIRSTNAME__' => $obj->prenom,
@@ -178,7 +179,7 @@ if ($resql)
 				dol_syslog("ok for #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG);
 
 				$sql="UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
-				$sql.=" SET statut=1, date_envoi=SYSDATE() WHERE rowid=".$obj->rowid;
+				$sql.=" SET statut=1, date_envoi=".$db->idate(gmmktime())." WHERE rowid=".$obj->rowid;
 				$resql2=$db->query($sql);
 				if (! $resql2)
 				{
@@ -193,7 +194,7 @@ if ($resql)
 				dol_syslog("error for #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG);
 
 				$sql="UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
-				$sql.=" SET statut=-1, date_envoi=SYSDATE() WHERE rowid=".$obj->rowid;
+				$sql.=" SET statut=-1, date_envoi=".$db->idate(gmmktime())." WHERE rowid=".$obj->rowid;
 				$resql2=$db->query($sql);
 				if (! $resql2)
 				{
-- 
GitLab