From dc790ff5866fa8099f7207f241e0a0c410a06937 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Marcos=20Garci=CC=81a=20de=20La=20Fuente?=
 <marcosgdf@gmail.com>
Date: Sat, 18 Apr 2015 18:11:01 +0200
Subject: [PATCH] NEW: Feature request: A page to merge two thirdparties into
 one #2613

---
 htdocs/adherents/class/adherent.class.php     |  17 +++
 htdocs/admin/prelevement.php                  |   4 +-
 htdocs/bookmarks/class/bookmark.class.php     |  17 +++
 htdocs/categories/class/categorie.class.php   |  21 +++-
 htdocs/comm/action/class/actioncomm.class.php |  17 +++
 htdocs/comm/list.php                          |   2 +-
 htdocs/comm/propal/class/propal.class.php     |  15 +++
 htdocs/comm/prospect/list.php                 |   2 +-
 htdocs/commande/class/commande.class.php      |  17 +++
 .../facture/class/facture-rec.class.php       |  18 ++-
 htdocs/compta/facture/class/facture.class.php |  17 +++
 .../class/ligneprelevement.class.php          |  17 +++
 htdocs/compta/salaries/index.php              |   2 +-
 htdocs/compta/stats/casoc.php                 |  12 +-
 htdocs/contact/class/contact.class.php        |  18 ++-
 htdocs/contrat/class/contrat.class.php        |  17 +++
 htdocs/core/class/commonobject.class.php      |  22 ++++
 htdocs/core/class/html.form.class.php         |   2 +-
 htdocs/core/class/html.formother.class.php    |   2 +-
 .../modules/mailings/contacts3.modules.php    |   8 +-
 .../modules/mailings/contacts4.modules.php    |   4 +-
 .../modules/mailings/thirdparties.modules.php |   4 +-
 htdocs/core/modules/modCategorie.class.php    |  16 +--
 htdocs/core/modules/modUser.class.php         |   6 +-
 htdocs/expedition/class/expedition.class.php  |  16 +++
 htdocs/fichinter/class/fichinter.class.php    |  17 +++
 .../class/fournisseur.commande.class.php      |  17 +++
 .../fourn/class/fournisseur.facture.class.php |  15 +++
 .../fourn/class/fournisseur.product.class.php |  17 +++
 htdocs/fourn/list.php                         |   2 +-
 .../install/mysql/migration/3.7.0-3.8.0.sql   |   3 +
 .../tables/llx_categorie_fournisseur.key.sql  |   6 +-
 .../tables/llx_categorie_fournisseur.sql      |   2 +-
 .../tables/llx_categorie_societe.key.sql      |   6 +-
 .../mysql/tables/llx_categorie_societe.sql    |   2 +-
 .../tables/llx_societe_remise_except.key.sql  |   4 +-
 htdocs/install/mysql/tables/llx_user.key.sql  |   2 +-
 htdocs/install/mysql/tables/llx_user.sql      |   2 +-
 htdocs/langs/en_US/companies.lang             |   7 +-
 htdocs/livraison/class/livraison.class.php    |  17 +++
 htdocs/product/class/product.class.php        |  18 +++
 htdocs/projet/class/project.class.php         |  17 +++
 htdocs/societe/class/societe.class.php        |  47 +++++++-
 htdocs/societe/soc.php                        | 107 ++++++++++++++++++
 htdocs/societe/societe.php                    |   6 +-
 htdocs/user/card.php                          |   4 +-
 htdocs/user/class/user.class.php              |  26 ++++-
 htdocs/user/home.php                          |  12 +-
 htdocs/user/index.php                         |  12 +-
 htdocs/webservices/server_thirdparty.php      |   2 +-
 50 files changed, 589 insertions(+), 74 deletions(-)

diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php
index 1f37bc27c80..941f7b300fd 100644
--- a/htdocs/adherents/class/adherent.class.php
+++ b/htdocs/adherents/class/adherent.class.php
@@ -1954,4 +1954,21 @@ class Adherent extends CommonObject
         }
     }
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty($db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'adherent'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
+
 }
diff --git a/htdocs/admin/prelevement.php b/htdocs/admin/prelevement.php
index b56ee74e10f..81ae430b371 100644
--- a/htdocs/admin/prelevement.php
+++ b/htdocs/admin/prelevement.php
@@ -180,7 +180,7 @@ if (! empty($conf->global->MAIN_MODULE_NOTIFICATION))
     $langs->load("mails");
     print_titre($langs->trans("Notifications"));
 
-    $sql = "SELECT u.rowid, u.lastname, u.firstname, u.fk_societe, u.email";
+    $sql = "SELECT u.rowid, u.lastname, u.firstname, u.fk_soc, u.email";
     $sql.= " FROM ".MAIN_DB_PREFIX."user as u";
     $sql.= " WHERE entity IN (0,".$conf->entity.")";
 
@@ -194,7 +194,7 @@ if (! empty($conf->global->MAIN_MODULE_NOTIFICATION))
         {
             $obj = $db->fetch_object($resql);
             $var=!$var;
-            if (!$obj->fk_societe)
+            if (!$obj->fk_soc)
             {
                 $username=dolGetFirstLastname($obj->firstname,$obj->lastname);
                 $internalusers[$obj->rowid] = $username;
diff --git a/htdocs/bookmarks/class/bookmark.class.php b/htdocs/bookmarks/class/bookmark.class.php
index aa92d2bedb9..68e468dd0f2 100644
--- a/htdocs/bookmarks/class/bookmark.class.php
+++ b/htdocs/bookmarks/class/bookmark.class.php
@@ -210,4 +210,21 @@ class Bookmark
 
     }
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'bookmark'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
+
 }
diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php
index 3149d9ae4e2..4303c593f1a 100644
--- a/htdocs/categories/class/categorie.class.php
+++ b/htdocs/categories/class/categorie.class.php
@@ -1166,8 +1166,8 @@ class Categorie extends CommonObject
 
 		$typeid=-1; $table='';;
 		if ($type == '0' || $type == 'product')	       { $typeid=0; $table='product';   $type='product'; }
-		else if ($type == '1' || $type == 'supplier') { $typeid=1; $table='societe';   $type='fournisseur'; }
-		else if ($type == '2' || $type == 'customer') { $typeid=2; $table='societe';   $type='societe'; }
+		else if ($type == '1' || $type == 'supplier') { $typeid=1; $table='soc';   $type='fournisseur'; }
+		else if ($type == '2' || $type == 'customer') { $typeid=2; $table='soc';   $type='societe'; }
 		else if ($type == '3' || $type == 'member')   { $typeid=3; $table='member';    $type='member'; }
         else if ($type == '4' || $type == 'contact')  { $typeid=4; $table='socpeople'; $type='contact'; }
 
@@ -1551,4 +1551,21 @@ class Categorie extends CommonObject
         $this->socid = 1;
         $this->type = 0;
     }
+
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'categorie_societe'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php
index 283d9f95856..543cf862d8f 100644
--- a/htdocs/comm/action/class/actioncomm.class.php
+++ b/htdocs/comm/action/class/actioncomm.class.php
@@ -1263,5 +1263,22 @@ class ActionComm extends CommonObject
         $this->userassigned[$user->id]=array('id'=>$user->id, 'transparency'=> 1);
     }
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'actioncomm'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
+
 }
 
diff --git a/htdocs/comm/list.php b/htdocs/comm/list.php
index 06b26d88f48..bc3be7b3ebe 100644
--- a/htdocs/comm/list.php
+++ b/htdocs/comm/list.php
@@ -105,7 +105,7 @@ $sql = "SELECT s.rowid, s.nom as name, s.client, s.zip, s.town, st.libelle as st
 $sql.= " s.datec, s.canvas";
 if ((!$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
 $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
-if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_societe"; // We need this table joined to the select in order to filter by categ
+if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc"; // We need this table joined to the select in order to filter by categ
 if ((!$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
 $sql.= ", ".MAIN_DB_PREFIX."c_stcomm as st";
 $sql.= " WHERE s.fk_stcomm = st.id";
diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php
index d0102eb6d43..e7a7421e6ea 100644
--- a/htdocs/comm/propal/class/propal.class.php
+++ b/htdocs/comm/propal/class/propal.class.php
@@ -2868,7 +2868,22 @@ class Propal extends CommonObject
 		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
 	}
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'propal'
+		);
 
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
 
diff --git a/htdocs/comm/prospect/list.php b/htdocs/comm/prospect/list.php
index b2202a21b88..1ab843da188 100644
--- a/htdocs/comm/prospect/list.php
+++ b/htdocs/comm/prospect/list.php
@@ -201,7 +201,7 @@ if ((!$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql
 $sql .= " FROM ".MAIN_DB_PREFIX."c_stcomm as st";
 $sql.= ", ".MAIN_DB_PREFIX."societe as s";
 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as d on (d.rowid = s.fk_departement)";
-if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_societe"; // We need this table joined to the select in order to filter by categ
+if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc"; // We need this table joined to the select in order to filter by categ
 if ((!$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
 $sql.= " WHERE s.fk_stcomm = st.id";
 $sql.= " AND s.client IN (2, 3)";
diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php
index 6896c49db3e..eba8a557d25 100644
--- a/htdocs/commande/class/commande.class.php
+++ b/htdocs/commande/class/commande.class.php
@@ -3292,6 +3292,23 @@ class Commande extends CommonOrder
 		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
 	}
 
+
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'commande'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
 
diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php
index a50c1cc91fd..f90136aaa0f 100644
--- a/htdocs/compta/facture/class/facture-rec.class.php
+++ b/htdocs/compta/facture/class/facture-rec.class.php
@@ -593,5 +593,21 @@ class FactureRec extends Facture
 
 		$this->usenewprice = 1;
 	}
-		
+
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'facture_rec'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php
index c0d32275ec9..83210476a13 100644
--- a/htdocs/compta/facture/class/facture.class.php
+++ b/htdocs/compta/facture/class/facture.class.php
@@ -3636,6 +3636,23 @@ class Facture extends CommonInvoice
 			return -1;
 		}
 	}
+
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'facture'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
 /**
diff --git a/htdocs/compta/prelevement/class/ligneprelevement.class.php b/htdocs/compta/prelevement/class/ligneprelevement.class.php
index 16960b53c46..a3683e20bbb 100644
--- a/htdocs/compta/prelevement/class/ligneprelevement.class.php
+++ b/htdocs/compta/prelevement/class/ligneprelevement.class.php
@@ -156,5 +156,22 @@ class LignePrelevement
 			if ($statut==3) return $langs->trans($this->statuts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut8');
 		}
 	}
+
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'prelevement_lignes'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
diff --git a/htdocs/compta/salaries/index.php b/htdocs/compta/salaries/index.php
index 484010c9f03..81788f2d9de 100644
--- a/htdocs/compta/salaries/index.php
+++ b/htdocs/compta/salaries/index.php
@@ -83,7 +83,7 @@ $form = new Form($db);
 $salstatic = new PaymentSalary($db);
 $userstatic = new User($db);
 
-$sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.admin, u.salary as current_salary, u.fk_societe as fk_soc,";
+$sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.admin, u.salary as current_salary, u.fk_soc as fk_soc,";
 $sql.= " s.rowid, s.fk_user, s.amount, s.salary, s.label, s.datev as dm, s.fk_typepayment as type, s.num_payment,";
 $sql.= " pst.code as payment_code";
 $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s";
diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php
index a4c4663dc40..0f352defc5e 100644
--- a/htdocs/compta/stats/casoc.php
+++ b/htdocs/compta/stats/casoc.php
@@ -183,7 +183,7 @@ if ($modecompta == 'CREANCES-DETTES') {
 	$sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s";
 	if ($selected_cat === -2)	// Without any category 
 	{
-	    $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_societe";
+	    $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc";
 	}
 	else if ($selected_cat) 	// Into a specific category
 	{
@@ -201,13 +201,13 @@ if ($modecompta == 'CREANCES-DETTES') {
 	}
 	if ($selected_cat === -2)	// Without any category  
 	{
-	    $sql.=" AND cs.fk_societe is null";
+	    $sql.=" AND cs.fk_soc is null";
 	}
 	else if ($selected_cat) {	// Into a specific category
 	    $sql.= " AND (c.rowid = ".$selected_cat;
 	    if ($subcat) $sql.=" OR c.fk_parent = " . $selected_cat;
 	    $sql.= ")";
-		$sql.= " AND cs.fk_categorie = c.rowid AND cs.fk_societe = s.rowid";
+		$sql.= " AND cs.fk_categorie = c.rowid AND cs.fk_soc = s.rowid";
 	}
 } else {
 	/*
@@ -221,7 +221,7 @@ if ($modecompta == 'CREANCES-DETTES') {
 	$sql.= ", ".MAIN_DB_PREFIX."societe as s";
 	if ($selected_cat === -2)	// Without any category 
 	{
-	    $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_societe";
+	    $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc";
 	}
 	else if ($selected_cat) 	// Into a specific category
 	{
@@ -235,13 +235,13 @@ if ($modecompta == 'CREANCES-DETTES') {
 	}
 	if ($selected_cat === -2)	// Without any category  
 	{
-	    $sql.=" AND cs.fk_societe is null";
+	    $sql.=" AND cs.fk_soc is null";
 	}
 	else if ($selected_cat) {	// Into a specific category
 	    $sql.= " AND (c.rowid = ".$selected_cat;
 	    if ($subcat) $sql.=" OR c.fk_parent = " . $selected_cat;
 	    $sql.= ")";
-		$sql.= " AND cs.fk_categorie = c.rowid AND cs.fk_societe = s.rowid";
+		$sql.= " AND cs.fk_categorie = c.rowid AND cs.fk_soc = s.rowid";
 	}
 }
 $sql.= " AND f.entity = ".$conf->entity;
diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php
index 19ea13f6a39..05365da1b59 100644
--- a/htdocs/contact/class/contact.class.php
+++ b/htdocs/contact/class/contact.class.php
@@ -1084,4 +1084,20 @@ class Contact extends CommonObject
 		}
 	}
 
-}
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'socpeople'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
+}
\ No newline at end of file
diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php
index b24ee8f0d66..b6776d97916 100644
--- a/htdocs/contrat/class/contrat.class.php
+++ b/htdocs/contrat/class/contrat.class.php
@@ -2112,6 +2112,23 @@ class Contrat extends CommonObject
 
 		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
 	}
+
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'contrat'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
 
diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php
index f2e4980ea47..0b7a21416a6 100644
--- a/htdocs/core/class/commonobject.class.php
+++ b/htdocs/core/class/commonobject.class.php
@@ -3895,5 +3895,27 @@ abstract class CommonObject
 		return $user->rights->{$this->element};
 	}
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 * This function is meant to be called from replaceThirdparty with the appropiate tables
+	 * Column name fk_soc MUST be used to identify thirdparties
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @param array $tables Tables that need to be changed
+	 * @return bool
+	 */
+	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables)
+	{
+		foreach ($tables as $table) {
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
 
+			if (!$db->query($sql)) {
+				return false;
+			}
+		}
+
+		return true;
+	}
 }
diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php
index 8bdb428d26b..507dc9acb18 100644
--- a/htdocs/core/class/html.form.class.php
+++ b/htdocs/core/class/html.form.class.php
@@ -1306,7 +1306,7 @@ class Form
         		$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
         	}
         }
-        if (! empty($user->societe_id)) $sql.= " AND u.fk_societe = ".$user->societe_id;
+        if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
         if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN ('".$excludeUsers."')";
         if (is_array($include) && $includeUsers) $sql.= " AND u.rowid IN ('".$includeUsers."')";
         if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND u.statut <> 0";
diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php
index c42a673976e..3233b479b6c 100644
--- a/htdocs/core/class/html.formother.class.php
+++ b/htdocs/core/class/html.formother.class.php
@@ -391,7 +391,7 @@ class FormOther
         $sql_usr.= " FROM ".MAIN_DB_PREFIX."user as u";
         $sql_usr.= " WHERE u.entity IN (0,".$conf->entity.")";
         if (empty($user->rights->user->user->lire)) $sql_usr.=" AND u.rowid = ".$user->id;
-        if (! empty($user->societe_id)) $sql_usr.=" AND u.fk_societe = ".$user->societe_id;
+        if (! empty($user->societe_id)) $sql_usr.=" AND u.fk_soc = ".$user->societe_id;
         // Add existing sales representatives of thirdparty of external user
         if (empty($user->rights->user->user->lire) && $user->societe_id)
         {
diff --git a/htdocs/core/modules/mailings/contacts3.modules.php b/htdocs/core/modules/mailings/contacts3.modules.php
index feeb0a2cb55..0c1ccc86d61 100644
--- a/htdocs/core/modules/mailings/contacts3.modules.php
+++ b/htdocs/core/modules/mailings/contacts3.modules.php
@@ -88,7 +88,7 @@ class mailing_contacts3 extends MailingTargets
     	$sql.= " AND sp.entity IN (".getEntity('societe', 1).")";
     	$sql.= " AND sp.email NOT IN (SELECT email FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE fk_mailing=".$mailing_id.")";
     	if ($filtersarray[0] <> 'all') $sql.= " AND cs.fk_categorie = c.rowid";
-    	if ($filtersarray[0] <> 'all') $sql.= " AND cs.fk_societe = sp.fk_soc";
+    	if ($filtersarray[0] <> 'all') $sql.= " AND cs.fk_soc = sp.fk_soc";
     	if ($filtersarray[0] <> 'all') $sql.= " AND c.label = '".$this->db->escape($filtersarray[0])."'";
     	$sql.= " ORDER BY sp.lastname, sp.firstname";
 
@@ -144,7 +144,7 @@ class mailing_contacts3 extends MailingTargets
             $statssql[$i].= " AND sp.email != ''";    // Note that null != '' is false
             $statssql[$i].= " AND sp.entity IN (".getEntity('societe', 1).")";
             $statssql[$i].= " AND cs.fk_categorie = c.rowid";
-            $statssql[$i].= " AND cs.fk_societe = sp.fk_soc";
+            $statssql[$i].= " AND cs.fk_soc = sp.fk_soc";
             $statssql[$i].= " GROUP BY c.label";
             $statssql[$i].= " ORDER BY nb DESC";
             $statssql[$i].= " LIMIT $i,1";
@@ -183,7 +183,7 @@ class mailing_contacts3 extends MailingTargets
         $sql.= " AND sp.entity IN (".getEntity('societe', 1).")";
         $sql.= " AND sp.email != ''"; // Note that null != '' is false
         $sql.= " AND cs.fk_categorie = c.rowid";
-        $sql.= " AND cs.fk_societe = sp.fk_soc";
+        $sql.= " AND cs.fk_soc = sp.fk_soc";
         */
     	// La requete doit retourner un champ "nb" pour etre comprise
     	// par parent::getNbOfRecipients
@@ -210,7 +210,7 @@ class mailing_contacts3 extends MailingTargets
         $sql.= " AND sp.no_email = 0";
         $sql.= " AND sp.entity IN (".getEntity('societe', 1).")";
         $sql.= " AND cs.fk_categorie = c.rowid";
-        $sql.= " AND cs.fk_societe = sp.fk_soc";
+        $sql.= " AND cs.fk_soc = sp.fk_soc";
         $sql.= " GROUP BY c.label";
         $sql.= " ORDER BY c.label";
 
diff --git a/htdocs/core/modules/mailings/contacts4.modules.php b/htdocs/core/modules/mailings/contacts4.modules.php
index c0a1c59c01c..56134d38932 100644
--- a/htdocs/core/modules/mailings/contacts4.modules.php
+++ b/htdocs/core/modules/mailings/contacts4.modules.php
@@ -145,7 +145,7 @@ class mailing_contacts4 extends MailingTargets
             $statssql[$i].= " AND sp.email != ''";    // Note that null != '' is false
             $statssql[$i].= " AND sp.entity IN (".getEntity('societe', 1).")";
             $statssql[$i].= " AND cs.fk_categorie = c.rowid";
-            $statssql[$i].= " AND cs.fk_societe = sp.fk_soc";
+            $statssql[$i].= " AND cs.fk_soc = sp.fk_soc";
             $statssql[$i].= " GROUP BY c.label";
             $statssql[$i].= " ORDER BY nb DESC";
             $statssql[$i].= " LIMIT $i,1";
@@ -183,7 +183,7 @@ class mailing_contacts4 extends MailingTargets
         $sql.= " AND sp.entity IN (".getEntity('societe', 1).")";
         $sql.= " AND sp.email != ''"; // Note that null != '' is false
         $sql.= " AND cs.fk_categorie = c.rowid";
-        $sql.= " AND cs.fk_societe = sp.fk_soc";
+        $sql.= " AND cs.fk_soc = sp.fk_soc";
         */
     	// La requete doit retourner un champ "nb" pour etre comprise
     	// par parent::getNbOfRecipients
diff --git a/htdocs/core/modules/mailings/thirdparties.modules.php b/htdocs/core/modules/mailings/thirdparties.modules.php
index 222711cdf65..cfccc1ff673 100644
--- a/htdocs/core/modules/mailings/thirdparties.modules.php
+++ b/htdocs/core/modules/mailings/thirdparties.modules.php
@@ -74,7 +74,7 @@ class mailing_thirdparties extends MailingTargets
 		    $sql.= " WHERE s.email <> ''";
 		    $sql.= " AND s.entity IN (".getEntity('societe', 1).")";
 		    $sql.= " AND s.email NOT IN (SELECT email FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE fk_mailing=".$mailing_id.")";
-		    $sql.= " AND cs.fk_societe = s.rowid";
+		    $sql.= " AND cs.fk_soc = s.rowid";
 		    $sql.= " AND c.rowid = cs.fk_categorie";
 		    $sql.= " AND c.rowid='".$this->db->escape($_POST['filter'])."'";
 		    $sql.= " UNION ";
@@ -83,7 +83,7 @@ class mailing_thirdparties extends MailingTargets
 		    $sql.= " WHERE s.email <> ''";
 		    $sql.= " AND s.entity IN (".getEntity('societe', 1).")";
 		    $sql.= " AND s.email NOT IN (SELECT email FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE fk_mailing=".$mailing_id.")";
-		    $sql.= " AND cs.fk_societe = s.rowid";
+		    $sql.= " AND cs.fk_soc = s.rowid";
 		    $sql.= " AND c.rowid = cs.fk_categorie";
 		    $sql.= " AND c.rowid='".$this->db->escape($_POST['filter'])."'";
 		}
diff --git a/htdocs/core/modules/modCategorie.class.php b/htdocs/core/modules/modCategorie.class.php
index 3084677c4ef..51a55d0cab0 100644
--- a/htdocs/core/modules/modCategorie.class.php
+++ b/htdocs/core/modules/modCategorie.class.php
@@ -121,7 +121,7 @@ class modCategorie extends DolibarrModules
 		$this->export_entities_array[$r]=array('s.rowid'=>'company','s.nom'=>'company','s.prefix_comm'=>"company",'s.client'=>"company",'s.datec'=>"company",'s.tms'=>"company",'s.code_client'=>"company",'s.address'=>"company",'s.zip'=>"company",'s.town'=>"company",'c.label'=>"company",'c.code'=>"company",'s.phone'=>"company",'s.fax'=>"company",'s.url'=>"company",'s.email'=>"company",'s.siret'=>"company",'s.siren'=>"company",'s.ape'=>"company",'s.idprof4'=>"company",'s.tva_intra'=>"company",'s.capital'=>"company",'s.note_public'=>"company");	// We define here only fields that use another picto
 		$this->export_sql_start[$r]='SELECT DISTINCT ';
 		$this->export_sql_end[$r]  =' FROM '.MAIN_DB_PREFIX.'categorie as u, '.MAIN_DB_PREFIX.'categorie_fournisseur as cf, '.MAIN_DB_PREFIX.'societe as s LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as t ON s.fk_typent = t.id LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as ce ON s.fk_effectif = ce.id LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as cfj ON s.fk_forme_juridique = cfj.code';
-		$this->export_sql_end[$r] .=' WHERE u.rowid = cf.fk_categorie AND cf.fk_societe = s.rowid';
+		$this->export_sql_end[$r] .=' WHERE u.rowid = cf.fk_categorie AND cf.fk_soc = s.rowid';
 		$this->export_sql_end[$r] .=' AND u.entity IN ('.getEntity('category',1).')';
 		$this->export_sql_end[$r] .=' AND u.type = 1';	// Supplier categories
 
@@ -136,7 +136,7 @@ class modCategorie extends DolibarrModules
 		$this->export_entities_array[$r]=array('s.rowid'=>'company','s.nom'=>'company','s.prefix_comm'=>"company",'s.client'=>"company",'s.datec'=>"company",'s.tms'=>"company",'s.code_client'=>"company",'s.address'=>"company",'s.zip'=>"company",'s.town'=>"company",'c.label'=>"company",'c.code'=>"company",'s.phone'=>"company",'s.fax'=>"company",'s.url'=>"company",'s.email'=>"company",'s.siret'=>"company",'s.siren'=>"company",'s.ape'=>"company",'s.idprof4'=>"company",'s.tva_intra'=>"company",'s.capital'=>"company",'s.note_public'=>"company",'s.fk_prospectlevel'=>'company','s.fk_stcomm'=>'company');	// We define here only fields that use another picto
 		$this->export_sql_start[$r]='SELECT DISTINCT ';
 		$this->export_sql_end[$r]  =' FROM '.MAIN_DB_PREFIX.'categorie as u, '.MAIN_DB_PREFIX.'categorie_societe as cf, '.MAIN_DB_PREFIX.'societe as s LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as t ON s.fk_typent = t.id LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as ce ON s.fk_effectif = ce.id LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as cfj ON s.fk_forme_juridique = cfj.code';
-		$this->export_sql_end[$r] .=' WHERE u.rowid = cf.fk_categorie AND cf.fk_societe = s.rowid';
+		$this->export_sql_end[$r] .=' WHERE u.rowid = cf.fk_categorie AND cf.fk_soc = s.rowid';
 		$this->export_sql_end[$r] .=' AND u.entity IN ('.getEntity('category',1).')';
 		$this->export_sql_end[$r] .=' AND u.type = 2';	// Customer/Prospect categories
 
@@ -316,14 +316,14 @@ class modCategorie extends DolibarrModules
 			$this->import_icon[$r]=$this->picto;
 			$this->import_entities_array[$r]=array();		// We define here only fields that use another icon that the one defined into import_icon
 			$this->import_tables_array[$r]=array('cs'=>MAIN_DB_PREFIX.'categorie_societe');
-			$this->import_fields_array[$r]=array('cs.fk_categorie'=>"Category*",'cs.fk_societe'=>"ThirdParty*"
+			$this->import_fields_array[$r]=array('cs.fk_categorie'=>"Category*",'cs.fk_soc'=>"ThirdParty*"
 			);
 
 			$this->import_convertvalue_array[$r]=array(
 					'cs.fk_categorie'=>array('rule'=>'fetchidfromref','classfile'=>'/categories/class/categorie.class.php','class'=>'Categorie','method'=>'fetch','element'=>'category'),
-					'cs.fk_societe'=>array('rule'=>'fetchidfromref','classfile'=>'/societe/class/societe.class.php','class'=>'Societe','method'=>'fetch','element'=>'ThirdParty')
+					'cs.fk_soc'=>array('rule'=>'fetchidfromref','classfile'=>'/societe/class/societe.class.php','class'=>'Societe','method'=>'fetch','element'=>'ThirdParty')
 			);
-			$this->import_examplevalues_array[$r]=array('cs.fk_categorie'=>"Imported category",'cs.fk_societe'=>"MyBigCompany");
+			$this->import_examplevalues_array[$r]=array('cs.fk_categorie'=>"Imported category",'cs.fk_soc'=>"MyBigCompany");
 		}
 
 		if (! empty($conf->fournisseur->enabled))
@@ -335,14 +335,14 @@ class modCategorie extends DolibarrModules
 			$this->import_icon[$r]=$this->picto;
 			$this->import_entities_array[$r]=array();		// We define here only fields that use another icon that the one defined into import_icon
 			$this->import_tables_array[$r]=array('cs'=>MAIN_DB_PREFIX.'categorie_fournisseur');
-			$this->import_fields_array[$r]=array('cs.fk_categorie'=>"Category*",'cs.fk_societe'=>"Supplier*"
+			$this->import_fields_array[$r]=array('cs.fk_categorie'=>"Category*",'cs.fk_soc'=>"Supplier*"
 			);
 
 			$this->import_convertvalue_array[$r]=array(
 					'cs.fk_categorie'=>array('rule'=>'fetchidfromref','classfile'=>'/categories/class/categorie.class.php','class'=>'Categorie','method'=>'fetch','element'=>'category'),
-					'cs.fk_societe'=>array('rule'=>'fetchidfromref','classfile'=>'/societe/class/societe.class.php','class'=>'Societe','method'=>'fetch','element'=>'ThirdParty')
+					'cs.fk_soc'=>array('rule'=>'fetchidfromref','classfile'=>'/societe/class/societe.class.php','class'=>'Societe','method'=>'fetch','element'=>'ThirdParty')
 			);
-			$this->import_examplevalues_array[$r]=array('cs.fk_categorie'=>"Imported category",'cs.fk_societe'=>"MyBigCompany");
+			$this->import_examplevalues_array[$r]=array('cs.fk_categorie'=>"Imported category",'cs.fk_soc'=>"MyBigCompany");
 		}
 	}
 
diff --git a/htdocs/core/modules/modUser.class.php b/htdocs/core/modules/modUser.class.php
index c683c2b34cc..fd7efdae5bc 100644
--- a/htdocs/core/modules/modUser.class.php
+++ b/htdocs/core/modules/modUser.class.php
@@ -209,10 +209,10 @@ class modUser extends DolibarrModules
 		$this->export_code[$r]=$this->rights_class.'_'.$r;
 		$this->export_label[$r]='Liste des utilisateurs Dolibarr et attributs';
 		$this->export_permission[$r]=array(array("user","user","export"));
-		$this->export_fields_array[$r]=array('u.rowid'=>"Id",'u.login'=>"Login",'u.lastname'=>"Lastname",'u.firstname'=>"Firstname",'u.office_phone'=>'Phone','u.office_fax'=>'Fax','u.email'=>'EMail','u.datec'=>"DateCreation",'u.tms'=>"DateLastModification",'u.admin'=>"Administrator",'u.statut'=>'Status','u.note'=>"Note",'u.datelastlogin'=>'LastConnexion','u.datepreviouslogin'=>'PreviousConnexion','u.fk_socpeople'=>"IdContact",'u.fk_societe'=>"IdCompany",'u.fk_member'=>"MemberId");
-		$this->export_TypeFields_array[$r]=array('u.login'=>"Text",'u.lastname'=>"Text",'u.firstname'=>"Text",'u.office_phone'=>'Text','u.office_fax'=>'Text','u.email'=>'Text','u.datec'=>"Date",'u.tms'=>"Date",'u.admin'=>"Boolean",'u.statut'=>'Status','u.note'=>"Text",'u.datelastlogin'=>'Date','u.datepreviouslogin'=>'Date','u.fk_societe'=>"List:societe:nom:rowid",'u.fk_member'=>"List:adherent:nom");
+		$this->export_fields_array[$r]=array('u.rowid'=>"Id",'u.login'=>"Login",'u.lastname'=>"Lastname",'u.firstname'=>"Firstname",'u.office_phone'=>'Phone','u.office_fax'=>'Fax','u.email'=>'EMail','u.datec'=>"DateCreation",'u.tms'=>"DateLastModification",'u.admin'=>"Administrator",'u.statut'=>'Status','u.note'=>"Note",'u.datelastlogin'=>'LastConnexion','u.datepreviouslogin'=>'PreviousConnexion','u.fk_socpeople'=>"IdContact",'u.fk_soc'=>"IdCompany",'u.fk_member'=>"MemberId");
+		$this->export_TypeFields_array[$r]=array('u.login'=>"Text",'u.lastname'=>"Text",'u.firstname'=>"Text",'u.office_phone'=>'Text','u.office_fax'=>'Text','u.email'=>'Text','u.datec'=>"Date",'u.tms'=>"Date",'u.admin'=>"Boolean",'u.statut'=>'Status','u.note'=>"Text",'u.datelastlogin'=>'Date','u.datepreviouslogin'=>'Date','u.fk_soc'=>"List:societe:nom:rowid",'u.fk_member'=>"List:adherent:nom");
 
-		$this->export_entities_array[$r]=array('u.rowid'=>"user",'u.login'=>"user",'u.lastname'=>"user",'u.firstname'=>"user",'u.office_phone'=>'user','u.office_fax'=>'user','u.email'=>'user','u.datec'=>"user",'u.tms'=>"user",'u.admin'=>"user",'u.statut'=>'user','u.note'=>"user",'u.datelastlogin'=>'user','u.datepreviouslogin'=>'user','u.fk_socpeople'=>"contact",'u.fk_societe'=>"company",'u.fk_member'=>"member");
+		$this->export_entities_array[$r]=array('u.rowid'=>"user",'u.login'=>"user",'u.lastname'=>"user",'u.firstname'=>"user",'u.office_phone'=>'user','u.office_fax'=>'user','u.email'=>'user','u.datec'=>"user",'u.tms'=>"user",'u.admin'=>"user",'u.statut'=>'user','u.note'=>"user",'u.datelastlogin'=>'user','u.datepreviouslogin'=>'user','u.fk_socpeople'=>"contact",'u.fk_soc'=>"company",'u.fk_member'=>"member");
         if (empty($conf->adherent->enabled))
         {
             unset($this->export_fields_array[$r]['u.fk_member']);
diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php
index 6e8c81450ce..2dd899dce7a 100644
--- a/htdocs/expedition/class/expedition.class.php
+++ b/htdocs/expedition/class/expedition.class.php
@@ -1673,6 +1673,22 @@ class Expedition extends CommonObject
 		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, 0, 0, 0);
 	}
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'expedition'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
 
diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php
index baf2555a905..b132c74b9b9 100644
--- a/htdocs/fichinter/class/fichinter.class.php
+++ b/htdocs/fichinter/class/fichinter.class.php
@@ -1011,6 +1011,23 @@ class Fichinter extends CommonObject
 			return -1;
 		}
 	}
+
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'fichinter'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
 /**
diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php
index 440a46c1c62..5b8f42efc30 100644
--- a/htdocs/fourn/class/fournisseur.commande.class.php
+++ b/htdocs/fourn/class/fournisseur.commande.class.php
@@ -2415,6 +2415,23 @@ class CommandeFournisseur extends CommonOrder
 		return $user->rights->fournisseur->commande;
 	}
 
+
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'commande_fournisseur'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
 
diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php
index a1988b5c3ac..00eec4d536a 100644
--- a/htdocs/fourn/class/fournisseur.facture.class.php
+++ b/htdocs/fourn/class/fournisseur.facture.class.php
@@ -1852,7 +1852,22 @@ class FactureFournisseur extends CommonInvoice
 		return $user->rights->fournisseur->facture;
 	}
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'facture_fourn'
+		);
 
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
 
diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php
index 0f740a5367c..f10580d9714 100755
--- a/htdocs/fourn/class/fournisseur.product.class.php
+++ b/htdocs/fourn/class/fournisseur.product.class.php
@@ -663,5 +663,22 @@ class ProductFournisseur extends Product
         return $out;
     }
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'product_fournisseur_price'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
+
 }
 
diff --git a/htdocs/fourn/list.php b/htdocs/fourn/list.php
index 77202f989fe..c44aa39622d 100644
--- a/htdocs/fourn/list.php
+++ b/htdocs/fourn/list.php
@@ -108,7 +108,7 @@ $result=$hookmanager->executeHooks('printFieldListSelect',$parameters);    // No
 $sql.=$hookmanager->resPrint;
 $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_extrafields as ef ON ef.fk_object = s.rowid";
-if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cf ON s.rowid = cf.fk_societe"; // We need this table joined to the select in order to filter by categ
+if (! empty($search_categ) || ! empty($catid)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cf ON s.rowid = cf.fk_soc"; // We need this table joined to the select in order to filter by categ
 $sql.= ", ".MAIN_DB_PREFIX."c_stcomm as st";
 if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
 $sql.= " WHERE s.fk_stcomm = st.id AND s.fournisseur = 1";
diff --git a/htdocs/install/mysql/migration/3.7.0-3.8.0.sql b/htdocs/install/mysql/migration/3.7.0-3.8.0.sql
index 6c70b73030f..fcf5ed36563 100644
--- a/htdocs/install/mysql/migration/3.7.0-3.8.0.sql
+++ b/htdocs/install/mysql/migration/3.7.0-3.8.0.sql
@@ -520,3 +520,6 @@ create table llx_c_price_global_variable_updater
 ALTER TABLE llx_adherent CHANGE COLUMN note note_private text DEFAULT NULL;
 ALTER TABLE llx_adherent ADD COLUMN note_public text DEFAULT NULL after note_private;
 
+-- Feature request: A page to merge two thirdparties into one #2613
+ALTER TABLE llx_categorie_societe CHANGE COLUMN fk_societe fk_soc INTEGER NOT NULL;
+ALTER TABLE llx_societe CHANGE COLUMN fk_societe fk_soc INTEGER NOT NULL;
diff --git a/htdocs/install/mysql/tables/llx_categorie_fournisseur.key.sql b/htdocs/install/mysql/tables/llx_categorie_fournisseur.key.sql
index d8e84769cf0..7293c152b9a 100644
--- a/htdocs/install/mysql/tables/llx_categorie_fournisseur.key.sql
+++ b/htdocs/install/mysql/tables/llx_categorie_fournisseur.key.sql
@@ -17,9 +17,9 @@
 --
 -- ============================================================================
 
-ALTER TABLE llx_categorie_fournisseur ADD PRIMARY KEY pk_categorie_fournisseur (fk_categorie, fk_societe);
+ALTER TABLE llx_categorie_fournisseur ADD PRIMARY KEY pk_categorie_fournisseur (fk_categorie, fk_soc);
 ALTER TABLE llx_categorie_fournisseur ADD INDEX idx_categorie_fournisseur_fk_categorie (fk_categorie);
-ALTER TABLE llx_categorie_fournisseur ADD INDEX idx_categorie_fournisseur_fk_societe (fk_societe);
+ALTER TABLE llx_categorie_fournisseur ADD INDEX idx_categorie_fournisseur_fk_societe (fk_soc);
 
 ALTER TABLE llx_categorie_fournisseur ADD CONSTRAINT fk_categorie_fournisseur_categorie_rowid FOREIGN KEY (fk_categorie) REFERENCES llx_categorie (rowid);
-ALTER TABLE llx_categorie_fournisseur ADD CONSTRAINT fk_categorie_fournisseur_fk_soc   FOREIGN KEY (fk_societe) REFERENCES llx_societe (rowid);
+ALTER TABLE llx_categorie_fournisseur ADD CONSTRAINT fk_categorie_fournisseur_fk_soc   FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid);
diff --git a/htdocs/install/mysql/tables/llx_categorie_fournisseur.sql b/htdocs/install/mysql/tables/llx_categorie_fournisseur.sql
index 90df0e6f969..5a270b1fad9 100644
--- a/htdocs/install/mysql/tables/llx_categorie_fournisseur.sql
+++ b/htdocs/install/mysql/tables/llx_categorie_fournisseur.sql
@@ -22,6 +22,6 @@
 create table llx_categorie_fournisseur
 (
   fk_categorie  integer NOT NULL,
-  fk_societe    integer NOT NULL,
+  fk_soc    integer NOT NULL,
   import_key    varchar(14)
 )ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_categorie_societe.key.sql b/htdocs/install/mysql/tables/llx_categorie_societe.key.sql
index 6c912acb4c4..17605fc3520 100644
--- a/htdocs/install/mysql/tables/llx_categorie_societe.key.sql
+++ b/htdocs/install/mysql/tables/llx_categorie_societe.key.sql
@@ -16,9 +16,9 @@
 --
 -- ============================================================================
 
-ALTER TABLE llx_categorie_societe ADD PRIMARY KEY pk_categorie_societe (fk_categorie, fk_societe);
+ALTER TABLE llx_categorie_societe ADD PRIMARY KEY pk_categorie_societe (fk_categorie, fk_soc);
 ALTER TABLE llx_categorie_societe ADD INDEX idx_categorie_societe_fk_categorie (fk_categorie);
-ALTER TABLE llx_categorie_societe ADD INDEX idx_categorie_societe_fk_societe (fk_societe);
+ALTER TABLE llx_categorie_societe ADD INDEX idx_categorie_societe_fk_societe (fk_soc);
 
 ALTER TABLE llx_categorie_societe ADD CONSTRAINT fk_categorie_societe_categorie_rowid FOREIGN KEY (fk_categorie) REFERENCES llx_categorie (rowid);
-ALTER TABLE llx_categorie_societe ADD CONSTRAINT fk_categorie_societe_fk_soc   FOREIGN KEY (fk_societe) REFERENCES llx_societe (rowid);
+ALTER TABLE llx_categorie_societe ADD CONSTRAINT fk_categorie_societe_fk_soc   FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid);
diff --git a/htdocs/install/mysql/tables/llx_categorie_societe.sql b/htdocs/install/mysql/tables/llx_categorie_societe.sql
index 6543fc52bc8..c347d40c372 100644
--- a/htdocs/install/mysql/tables/llx_categorie_societe.sql
+++ b/htdocs/install/mysql/tables/llx_categorie_societe.sql
@@ -20,6 +20,6 @@
 create table llx_categorie_societe
 (
   fk_categorie  integer NOT NULL,
-  fk_societe    integer NOT NULL,
+  fk_soc    integer NOT NULL,
   import_key    varchar(14)
 )ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql b/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql
index 22f95455b31..0b66e7984d9 100644
--- a/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql
+++ b/htdocs/install/mysql/tables/llx_societe_remise_except.key.sql
@@ -29,8 +29,8 @@ ALTER TABLE llx_societe_remise_except ADD INDEX idx_societe_remise_except_fk_fac
 
 
 ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_user    FOREIGN KEY (fk_user)    REFERENCES llx_user (rowid);
-ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_soc     FOREIGN KEY (fk_soc)     REFERENCES llx_societe (rowid);
-ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_facture_line   FOREIGN KEY (fk_facture_line) REFERENCES llx_facturedet (rowid);
+ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_soc_remise_fk_soc     FOREIGN KEY (fk_soc)     REFERENCES llx_societe (rowid);
+ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_soc_remise_fk_facture_line   FOREIGN KEY (fk_facture_line) REFERENCES llx_facturedet (rowid);
 ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_facture        FOREIGN KEY (fk_facture)        REFERENCES llx_facture (rowid);
 ALTER TABLE llx_societe_remise_except ADD CONSTRAINT fk_societe_remise_fk_facture_source FOREIGN KEY (fk_facture_source) REFERENCES llx_facture (rowid);
 
diff --git a/htdocs/install/mysql/tables/llx_user.key.sql b/htdocs/install/mysql/tables/llx_user.key.sql
index 897228a9c43..8232e7cacb7 100644
--- a/htdocs/install/mysql/tables/llx_user.key.sql
+++ b/htdocs/install/mysql/tables/llx_user.key.sql
@@ -21,7 +21,7 @@
 
 ALTER TABLE llx_user ADD UNIQUE INDEX uk_user_login (login, entity);
 
-ALTER TABLE llx_user ADD INDEX uk_user_fk_societe   (fk_societe);
+ALTER TABLE llx_user ADD INDEX uk_user_fk_societe   (fk_soc);
 
 ALTER TABLE llx_user ADD UNIQUE INDEX uk_user_fk_socpeople (fk_socpeople);
 ALTER TABLE llx_user ADD UNIQUE INDEX uk_user_fk_member    (fk_member);
diff --git a/htdocs/install/mysql/tables/llx_user.sql b/htdocs/install/mysql/tables/llx_user.sql
index 28385298125..20b876b6f37 100644
--- a/htdocs/install/mysql/tables/llx_user.sql
+++ b/htdocs/install/mysql/tables/llx_user.sql
@@ -52,7 +52,7 @@ create table llx_user
   admin             smallint DEFAULT 0,
   module_comm       smallint DEFAULT 1,
   module_compta     smallint DEFAULT 1,
-  fk_societe        integer,
+  fk_soc        integer,
   fk_socpeople      integer,
   fk_member         integer,
   fk_user           integer,               -- Hierarchic parent
diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang
index 7bfaf799f3a..e700271368d 100644
--- a/htdocs/langs/en_US/companies.lang
+++ b/htdocs/langs/en_US/companies.lang
@@ -411,4 +411,9 @@ MonkeyNumRefModelDesc=Return numero with format %syymm-nnnn for customer code an
 LeopardNumRefModelDesc=The code is free. This code can be modified at any time.
 ManagingDirectors=Manager(s) name (CEO, director, president...)
 SearchThirdparty=Search thirdparty
-SearchContact=Search contact
\ No newline at end of file
+SearchContact=Search contact
+MergeOriginThirdparty=Origin thirdparty
+MergeThirdparties=Merge thirdparties
+ConfirmMergeThirdparties=Are you sure you want to merge this thirdparty? All linked objects (invoices...) will be linked with the destination thirdparty
+ThirdpartiesMergeSuccess=Thirdparties have been merged
+ErrorThirdpartiesMerge=There was an error when deleting the thirdparties. Please check the log. Changes have been reverted.
\ No newline at end of file
diff --git a/htdocs/livraison/class/livraison.class.php b/htdocs/livraison/class/livraison.class.php
index 027f7ab3b89..836f7d686ad 100644
--- a/htdocs/livraison/class/livraison.class.php
+++ b/htdocs/livraison/class/livraison.class.php
@@ -990,6 +990,23 @@ class Livraison extends CommonObject
 		return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, 0, 0, 0);
 	}
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'livraison'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
+
 }
 
 
diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php
index 1d0f3a67935..a2592f760ab 100755
--- a/htdocs/product/class/product.class.php
+++ b/htdocs/product/class/product.class.php
@@ -3847,4 +3847,22 @@ class Product extends CommonObject
 
 		return $maxpricesupplier;
 	}
+
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'product_customer_price',
+			'product_customer_price_log'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php
index e78e9de0c63..4710e2eeb45 100644
--- a/htdocs/projet/class/project.class.php
+++ b/htdocs/projet/class/project.class.php
@@ -1494,5 +1494,22 @@ class Project extends CommonObject
         }
     }
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'projet'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
+
 }
 
diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php
index a3cb5b44dc6..45dd3ba0c0d 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -2752,7 +2752,7 @@ class Societe extends CommonObject
     {
         if ($categorie_id > 0)
         {
-            $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_societe) ";
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
             $sql.= " VALUES ('".$categorie_id."','".$this->id."');";
 
             if ($resql=$this->db->query($sql)) return 0;
@@ -3253,4 +3253,49 @@ class Societe extends CommonObject
 
 	}
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 * It must be used within a transaction to avoid trouble
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		/**
+		 * Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some
+		 * Because this function is meant to be executed within a transaction, we won't take care of it.
+		 */
+		$sql = 'SELECT rowid
+FROM llx_societe_commerciaux
+WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN (
+  SELECT fk_user
+  FROM llx_societe_commerciaux
+  WHERE fk_soc = '.(int) $origin_id.'
+);';
+
+		$query = $db->query($sql);
+
+		while ($result = $db->fetch_object($query)) {
+			$db->query('DELETE FROM llx_societe_commerciaux WHERE rowid = '.$result->rowid);
+		}
+
+		/**
+		 * llx_societe_extrafields table must not be here because we don't care about the old thirdparty data
+		 * Do not include llx_societe because it will be replaced later
+		 */
+		$tables = array(
+			'societe_address',
+			'societe_commerciaux',
+			'societe_log',
+			'societe_prices',
+			'societe_remise',
+			'societe_remise_except',
+			'societe_rib'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
diff --git a/htdocs/societe/soc.php b/htdocs/societe/soc.php
index f5497aed0ac..43b04ce3a94 100644
--- a/htdocs/societe/soc.php
+++ b/htdocs/societe/soc.php
@@ -7,6 +7,7 @@
  * Copyright (C) 2008      Patrick Raguin       <patrick.raguin@auguria.net>
  * Copyright (C) 2010-2014 Juanjo Menent        <jmenent@2byte.es>
  * Copyright (C) 2011-2013 Alexandre Spangaro   <alexandre.spangaro@gmail.com>
+ * Copyright (C) 2015      Marcos GarcĂ­a        <marcosgdf@gmail.com>
  *
  * 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
@@ -93,6 +94,96 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
 
 if (empty($reshook))
 {
+	if ($action == 'confirm_merge' && $confirm == 'yes') {
+
+		$errors = 0;
+		$soc_origin_id = GETPOST('soc_origin', 'int');
+		$soc_origin = new Societe($db);
+
+		if ($soc_origin_id < 1) {
+			$langs->load('errors');
+			$langs->load('companies');
+			setEventMessage($langs->trans('ErrorProdIdIsMandatory', $langs->trans('MergeOriginThirdparty')), 'errors');
+		} else {
+
+			if (!$errors && $soc_origin->fetch($soc_origin_id) < 1) {
+				setEventMessage($langs->trans('ErrorRecordNotFound'), 'errors');
+				$errors++;
+			}
+
+			if (!$errors) {
+				$db->begin();
+
+				$objects = array(
+					'Adherent' => '/adherents/class/adherent.class.php',
+					'Societe' => '/societe/class/societe.class.php',
+					'Bookmark' => '/bookmarks/class/bookmark.class.php',
+					'Categorie' => '/categories/class/categorie.class.php',
+					'ActionComm' => '/comm/action/class/actioncomm.class.php',
+					'Propal' => '/comm/propal/class/propal.class.php',
+					'Commande' => '/commande/class/commande.class.php',
+					'Facture' => '/compta/facture/class/facture.class.php',
+					'FactureRec' => '/compta/facture/class/facture-rec.class.php',
+					'LignePrelevement' => '/compta/prelevement/class/ligneprelevement.class.php',
+					'Contact' => '/contact/class/contact.class.php',
+					'Contrat' => '/contrat/class/contrat.class.php',
+					'Expedition' => '/expedition/class/expedition.class.php',
+					'Fichinter' => '/fichinter/class/fichinter.class.php',
+					'CommandeFournisseur' => '/fourn/class/fournisseur.commande.class.php',
+					'FactureFournisseur' => '/fourn/class/fournisseur.facture.class.php',
+					'ProductFournisseur' => '/fourn/class/fournisseur.product.class.php',
+					'Livraison' => '/livraison/class/livraison.class.php',
+					'Product' => '/product/class/product.class.php',
+					'Project' => '/projet/class/project.class.php',
+					'User' => '/user/class/user.class.php',
+				);
+
+				//First, all core objects must update their tables
+				foreach ($objects as $object_name => $object_file) {
+
+					require_once DOL_DOCUMENT_ROOT.$object_file;
+
+					if (!$errors && !$object_name::replaceThirdparty($db, $soc_origin->id, $object->id)) {
+						$errors++;
+						$db->rollback();
+					}
+				}
+
+				//External modules should update their ones too
+				$hookmanager->initHooks(array(
+					'mergethirds'
+				));
+
+				if (!$errors) {
+					$reshook = $hookmanager->executeHooks('replaceThirdparty', array(
+						'soc_origin' => $soc_origin->id,
+						'soc_dest' => $object->id
+					), $soc_dest, $action);
+
+					if ($reshook < 0) {
+						setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+						$errors++;
+					}
+				}
+
+				if (!$errors) {
+					//We finally remove the old thirdparty
+					if ($soc_origin->delete($soc_origin->id) < 1) {
+						$db->rollback();
+						$errors++;
+					}
+				}
+			}
+
+			if (!$errors) {
+				setEventMessage($langs->trans('ThirdpartiesMergeSuccess'));
+				$db->commit();
+			} else {
+				setEventMessage($langs->trans('ErrorsThirdpartyMerge'), 'errors');
+			}
+		}
+	}
+
     if (GETPOST('getcustomercode'))
     {
         // We defined value code_client
@@ -1682,6 +1773,20 @@ else
             print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id,$langs->trans("DeleteACompany"),$langs->trans("ConfirmDeleteCompany"),"confirm_delete",'',0,"action-delete");
         }
 
+	    if ($action == 'merge') {
+		    $form = new Form($db);
+
+		    $options = array(
+			    array(
+				    'label' => $langs->trans('MergeOriginThirdparty'),
+				    'type' => 'other',
+				    'value' => $form->select_company('', 'soc_origin', 's.rowid != '.$object->id, 1)
+			    )
+		    );
+
+		    print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id,$langs->trans("MergeThirdparties"),$langs->trans("ConfirmMergeThirdparties"),"confirm_merge",$options,'',1);
+	    }
+
         dol_htmloutput_errors($error,$errors);
 
         $showlogo=$object->logo;
@@ -2132,6 +2237,8 @@ else
 		$reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
 		if (empty($reshook))
 		{
+			print '<div class="inline-block divButAction"><a class="butAction" href="soc.php?action=merge&socid='.$object->id.'" title="'.dol_escape_htmltag($langs->trans("Merge")).'">'.$langs->trans('Merge').'</a></div>';
+
 	        if (! empty($object->email))
 	        {
 	        	$langs->load("mails");
diff --git a/htdocs/societe/societe.php b/htdocs/societe/societe.php
index 2d046a3ec16..e44954be545 100644
--- a/htdocs/societe/societe.php
+++ b/htdocs/societe/societe.php
@@ -104,7 +104,7 @@ if ($mode == 'search')
 	if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
 	if ($socid) $sql.= " AND s.rowid = ".$socid;
     if ($search_sale) $sql.= " AND s.rowid = sc.fk_soc";        // Join for the needed table to filter by sale
-    if ($search_categ) $sql.= " AND s.rowid = cs.fk_societe";   // Join for the needed table to filter by categ
+    if ($search_categ) $sql.= " AND s.rowid = cs.fk_soc";   // Join for the needed table to filter by categ
 	if (! $user->rights->societe->lire || ! $user->rights->fournisseur->lire)
 	{
 		if (! $user->rights->fournisseur->lire) $sql.=" AND s.fournisseur != 1";
@@ -193,7 +193,7 @@ $sql.= " s.siren as idprof1, s.siret as idprof2, ape as idprof3, idprof4 as idpr
 // We'll need these fields in order to filter by sale (including the case where the user can only see his prospects)
 if ($search_sale) $sql .= ", sc.fk_soc, sc.fk_user";
 // We'll need these fields in order to filter by categ
-if ($search_categ) $sql .= ", cs.fk_categorie, cs.fk_societe";
+if ($search_categ) $sql .= ", cs.fk_categorie, cs.fk_soc";
 $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,";
 $sql.= " ".MAIN_DB_PREFIX."c_stcomm as st";
 // We'll need this table joined to the select in order to filter by sale
@@ -205,7 +205,7 @@ $sql.= " AND s.entity IN (".getEntity('societe', 1).")";
 if (! $user->rights->societe->client->voir && ! $socid)	$sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
 if ($socid)	$sql.= " AND s.rowid = ".$socid;
 if ($search_sale) $sql.= " AND s.rowid = sc.fk_soc";        // Join for the needed table to filter by sale
-if ($search_categ) $sql.= " AND s.rowid = cs.fk_societe";   // Join for the needed table to filter by categ
+if ($search_categ) $sql.= " AND s.rowid = cs.fk_soc";   // Join for the needed table to filter by categ
 if (! $user->rights->fournisseur->lire) $sql.=" AND (s.fournisseur <> 1 OR s.client <> 0)";    // client=0, fournisseur=0 must be visible
 // Insert sale filter
 if ($search_sale)
diff --git a/htdocs/user/card.php b/htdocs/user/card.php
index 8a6b08401df..d444dbb9393 100644
--- a/htdocs/user/card.php
+++ b/htdocs/user/card.php
@@ -416,13 +416,13 @@ if ($action == 'update' && ! $_POST["cancel"])
 
 	            	$sql = "UPDATE ".MAIN_DB_PREFIX."user";
 	            	$sql.= " SET fk_socpeople=".$db->escape($contactid);
-	            	if ($contact->socid) $sql.=", fk_societe=".$db->escape($contact->socid);
+	            	if ($contact->socid) $sql.=", fk_soc=".$db->escape($contact->socid);
 	            	$sql.= " WHERE rowid=".$object->id;
             	}
             	else
             	{
             		$sql = "UPDATE ".MAIN_DB_PREFIX."user";
-            		$sql.= " SET fk_socpeople=NULL, fk_societe=NULL";
+            		$sql.= " SET fk_socpeople=NULL, fk_soc=NULL";
             		$sql.= " WHERE rowid=".$object->id;
             	}
 	            dol_syslog("fiche::update", LOG_DEBUG);
diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php
index d8d8a1f071c..7f3e82d1c92 100644
--- a/htdocs/user/class/user.class.php
+++ b/htdocs/user/class/user.class.php
@@ -153,7 +153,7 @@ class User extends CommonObject
 		$sql = "SELECT u.rowid, u.lastname, u.firstname, u.email, u.job, u.skype, u.signature, u.office_phone, u.office_fax, u.user_mobile,";
 		$sql.= " u.admin, u.login, u.note,";
 		$sql.= " u.pass, u.pass_crypted, u.pass_temp,";
-		$sql.= " u.fk_societe, u.fk_socpeople, u.fk_member, u.fk_user, u.ldap_sid,";
+		$sql.= " u.fk_soc, u.fk_socpeople, u.fk_member, u.fk_user, u.ldap_sid,";
 		$sql.= " u.statut, u.lang, u.entity,";
 		$sql.= " u.datec as datec,";
 		$sql.= " u.tms as datem,";
@@ -242,9 +242,9 @@ class User extends CommonObject
 				$this->datelastlogin		= $this->db->jdate($obj->datel);
 				$this->datepreviouslogin	= $this->db->jdate($obj->datep);
 
-				$this->societe_id           = $obj->fk_societe;		// deprecated
+				$this->societe_id           = $obj->fk_soc;		// deprecated
 				$this->contact_id           = $obj->fk_socpeople;	// deprecated
-				$this->socid                = $obj->fk_societe;
+				$this->socid                = $obj->fk_soc;
 				$this->contactid            = $obj->fk_socpeople;
 				$this->fk_member            = $obj->fk_member;
 				$this->fk_user        		= $obj->fk_user;
@@ -957,7 +957,7 @@ class User extends CommonObject
 		{
 			$sql = "UPDATE ".MAIN_DB_PREFIX."user";
 			$sql.= " SET fk_socpeople=".$contact->id;
-			if ($contact->socid) $sql.=", fk_societe=".$contact->socid;
+			if ($contact->socid) $sql.=", fk_soc=".$contact->socid;
 			$sql.= " WHERE rowid=".$this->id;
 			$resql=$this->db->query($sql);
 
@@ -1030,7 +1030,7 @@ class User extends CommonObject
 			if ($result > 0 && $member->fk_soc)	// If member is linked to a thirdparty
 			{
 				$sql = "UPDATE ".MAIN_DB_PREFIX."user";
-				$sql.= " SET fk_societe=".$member->fk_soc;
+				$sql.= " SET fk_soc=".$member->fk_soc;
 				$sql.= " WHERE rowid=".$this->id;
 
 				dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
@@ -2423,5 +2423,21 @@ class User extends CommonObject
 		return;
 	}
 
+	/**
+	 * Function used to replace a thirdparty id with another one.
+	 *
+	 * @param DoliDB $db Database handler
+	 * @param int $origin_id Old thirdparty id
+	 * @param int $dest_id New thirdparty id
+	 * @return bool
+	 */
+	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+	{
+		$tables = array(
+			'user'
+		);
+
+		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+	}
 }
 
diff --git a/htdocs/user/home.php b/htdocs/user/home.php
index 6288448349a..b7b60ef2c7a 100644
--- a/htdocs/user/home.php
+++ b/htdocs/user/home.php
@@ -98,7 +98,7 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
  */
 $max=10;
 
-$sql = "SELECT u.rowid, u.lastname, u.firstname, u.admin, u.login, u.fk_societe, u.datec, u.statut";
+$sql = "SELECT u.rowid, u.lastname, u.firstname, u.admin, u.login, u.fk_soc, u.datec, u.statut";
 $sql.= ", u.entity";
 $sql.= ", u.ldap_sid";
 $sql.= ", u.photo";
@@ -109,7 +109,7 @@ $sql.= ", s.nom as name";
 $sql.= ", s.code_client";
 $sql.= ", s.canvas";
 $sql.= " FROM ".MAIN_DB_PREFIX."user as u";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_societe = s.rowid";
+$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_soc = s.rowid";
 if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && ($conf->multicompany->transverse_mode || ($user->admin && ! $user->entity)))
 {
 	$sql.= " WHERE u.entity IS NOT NULL";
@@ -118,7 +118,7 @@ else
 {
 	$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
 }
-if (!empty($socid)) $sql.= " AND u.fk_societe = ".$socid;
+if (!empty($socid)) $sql.= " AND u.fk_soc = ".$socid;
 $sql.= $db->order("u.datec","DESC");
 $sql.= $db->plimit($max);
 
@@ -147,7 +147,7 @@ if ($resql)
         $fuserstatic->admin = $obj->admin;
         $fuserstatic->email = $obj->email;
         $fuserstatic->skype = $obj->skype;
-        $fuserstatic->societe_id = $obj->fk_societe;
+        $fuserstatic->societe_id = $obj->fk_soc;
         print $fuserstatic->getNomUrl(1);
 		if (! empty($conf->multicompany->enabled) && $obj->admin && ! $obj->entity)
 		{
@@ -160,9 +160,9 @@ if ($resql)
 		print "</td>";
 		print '<td align="left">'.$obj->login.'</td>';
 		print "<td>";
-		if ($obj->fk_societe)
+		if ($obj->fk_soc)
 		{
-			$companystatic->id=$obj->fk_societe;
+			$companystatic->id=$obj->fk_soc;
             $companystatic->name=$obj->name;
             $companystatic->code_client = $obj->code_client;
             $companystatic->canvas=$obj->canvas;
diff --git a/htdocs/user/index.php b/htdocs/user/index.php
index 9e3e40b2e59..57c65cbe893 100644
--- a/htdocs/user/index.php
+++ b/htdocs/user/index.php
@@ -67,7 +67,7 @@ llxHeader('',$langs->trans("ListOfUsers"));
 
 print_fiche_titre($langs->trans("ListOfUsers"), '<form action="'.DOL_URL_ROOT.'/user/hierarchy.php" method="POST"><input type="submit" class="button" style="width:120px" name="viewcal" value="'.dol_escape_htmltag($langs->trans("HierarchicView")).'"></form>');
 
-$sql = "SELECT u.rowid, u.lastname, u.firstname, u.admin, u.fk_societe, u.login,";
+$sql = "SELECT u.rowid, u.lastname, u.firstname, u.admin, u.fk_soc, u.login,";
 $sql.= " u.datec,";
 $sql.= " u.tms as datem,";
 $sql.= " u.datelastlogin,";
@@ -75,7 +75,7 @@ $sql.= " u.ldap_sid, u.statut, u.entity,";
 $sql.= " u2.login as login2, u2.firstname as firstname2, u2.lastname as lastname2,";
 $sql.= " s.nom as name, s.canvas";
 $sql.= " FROM ".MAIN_DB_PREFIX."user as u";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_societe = s.rowid";
+$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON u.fk_soc = s.rowid";
 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u2 ON u.fk_user = u2.rowid";
 if(! empty($conf->multicompany->enabled) && $conf->entity == 1 && (! empty($conf->multicompany->transverse_mode) || (! empty($user->admin) && empty($user->entity))))
 {
@@ -85,7 +85,7 @@ else
 {
 	$sql.= " WHERE u.entity IN (".getEntity('user',1).")";
 }
-if (! empty($socid)) $sql.= " AND u.fk_societe = ".$socid;
+if (! empty($socid)) $sql.= " AND u.fk_soc = ".$socid;
 if (! empty($search_user))
 {
     $sql.= " AND (u.login LIKE '%".$db->escape($search_user)."%' OR u.lastname LIKE '%".$db->escape($search_user)."%' OR u.firstname LIKE '%".$db->escape($search_user)."%')";
@@ -113,7 +113,7 @@ if ($result)
     print_liste_field_titre($langs->trans("Login"),$_SERVER['PHP_SELF'],"u.login",$param,"","",$sortfield,$sortorder);
     print_liste_field_titre($langs->trans("LastName"),$_SERVER['PHP_SELF'],"u.lastname",$param,"","",$sortfield,$sortorder);
     print_liste_field_titre($langs->trans("FirstName"),$_SERVER['PHP_SELF'],"u.firstname",$param,"","",$sortfield,$sortorder);
-    print_liste_field_titre($langs->trans("Company"),$_SERVER['PHP_SELF'],"u.fk_societe",$param,"","",$sortfield,$sortorder);
+    print_liste_field_titre($langs->trans("Company"),$_SERVER['PHP_SELF'],"u.fk_soc",$param,"","",$sortfield,$sortorder);
     if (! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode))
     {
 	    print_liste_field_titre($langs->trans("Entity"),$_SERVER['PHP_SELF'],"u.entity",$param,"","",$sortfield,$sortorder);
@@ -164,9 +164,9 @@ if ($result)
         print '<td>'.ucfirst($obj->lastname).'</td>';
         print '<td>'.ucfirst($obj->firstname).'</td>';
         print "<td>";
-        if ($obj->fk_societe)
+        if ($obj->fk_soc)
         {
-            $companystatic->id=$obj->fk_societe;
+            $companystatic->id=$obj->fk_soc;
             $companystatic->name=$obj->name;
             $companystatic->canvas=$obj->canvas;
             print $companystatic->getNomUrl(1);
diff --git a/htdocs/webservices/server_thirdparty.php b/htdocs/webservices/server_thirdparty.php
index 696723f7247..aaed36ac9d8 100644
--- a/htdocs/webservices/server_thirdparty.php
+++ b/htdocs/webservices/server_thirdparty.php
@@ -664,7 +664,7 @@ function getListOfThirdParties($authentication,$filterthirdparty)
             if ($key == 'name'     && $val != '')  $sql.=" AND s.name LIKE '%".$db->escape($val)."%'";
         	if ($key == 'client'   && $val != '')  $sql.=" AND s.client = ".$db->escape($val);
             if ($key == 'supplier' && $val != '')  $sql.=" AND s.fournisseur = ".$db->escape($val);
-            if ($key == 'category' && $val != '')  $sql.=" AND s.rowid IN (SELECT fk_societe FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_categorie=".$db->escape($val).") ";
+            if ($key == 'category' && $val != '')  $sql.=" AND s.rowid IN (SELECT fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_categorie=".$db->escape($val).") ";
         }
         dol_syslog("Function: getListOfThirdParties", LOG_DEBUG);
 
-- 
GitLab