diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php
index 0fe6366ae58e6f6d1f6872ab5472ca51c807a9e4..3659f476ca0182072743164924f71433a44acc92 100644
--- a/htdocs/adherents/card.php
+++ b/htdocs/adherents/card.php
@@ -322,15 +322,15 @@ if (empty($reshook))
 			if ($result >= 0 && ! count($object->errors))
 			{
 				// Logo/Photo save
-				$dir= $conf->adherent->dir_output . '/' . get_exdir($object->id,2,0,1).'/photos';
+				$dir= $conf->adherent->dir_output . '/' . get_exdir($object->id,2,0,1,$object,'member').'/photos';
 				$file_OK = is_uploaded_file($_FILES['photo']['tmp_name']);
 				if ($file_OK)
 				{
 					if (GETPOST('deletephoto'))
 					{
 						require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
-						$fileimg=$conf->adherent->dir_output.'/'.get_exdir($object->id,2,0,1).'/photos/'.$object->photo;
-						$dirthumbs=$conf->adherent->dir_output.'/'.get_exdir($object->id,2,0,1).'/photos/thumbs';
+						$fileimg=$conf->adherent->dir_output.'/'.get_exdir($object->id,2,0,1,$object,'member').'/photos/'.$object->photo;
+						$dirthumbs=$conf->adherent->dir_output.'/'.get_exdir($object->id,2,0,1,$object,'member').'/photos/thumbs';
 						dol_delete_file($fileimg);
 						dol_delete_dir_recursive($dirthumbs);
 					}
diff --git a/htdocs/adherents/document.php b/htdocs/adherents/document.php
index 1d780eb21a5aaea0be917361be873a038ff5e8da..71f1df229379bd249f5932855fe906cbcc17bffd 100644
--- a/htdocs/adherents/document.php
+++ b/htdocs/adherents/document.php
@@ -60,7 +60,6 @@ if (! $sortorder) $sortorder="ASC";
 if (! $sortfield) $sortfield="name";
 
 
-$upload_dir = $conf->adherent->dir_output . "/" . get_exdir($id,2,0,1) . '/' . $id;
 $form = new Form($db);
 $object=new Adherent($db);
 $membert=new AdherentType($db);
@@ -70,6 +69,9 @@ if ($result < 0)
 	dol_print_error($db);
 	exit;
 }
+$upload_dir = $conf->adherent->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'member') . '/' . dol_sanitizeFileName($object->ref);
+
+
 /*
  * Actions
  */
diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php
index 20fce315153773ec0f7c5a987e615cb728995f00..96949371bae55e9e5559b42443cfd96eb77e277a 100644
--- a/htdocs/categories/class/categorie.class.php
+++ b/htdocs/categories/class/categorie.class.php
@@ -1302,7 +1302,7 @@ class Categorie extends CommonObject
 	{
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 
-		$dir = $sdir .'/'. get_exdir($this->id,2) . $this->id ."/";
+		$dir = $sdir .'/'. get_exdir($this->id,2,0,0,$this,'category') . $this->id ."/";
 		$dir .= "photos/";
 
 		if (! file_exists($dir))
diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php
index 59be328c55e6976718b4c853b61d5a3771d3dcc3..eb496db1af9817ddf8eb4d729b0f0dd41509adb7 100644
--- a/htdocs/categories/photos.php
+++ b/htdocs/categories/photos.php
@@ -224,7 +224,7 @@ if ($object->id)
 		$maxWidth = 160;
 		$maxHeight = 120;
 
-		$pdir = get_exdir($object->id,2) . $object->id ."/photos/";
+		$pdir = get_exdir($object->id,2,0,0,$object,'category') . $object->id ."/photos/";
 		$dir = $upload_dir.'/'.$pdir;
 
 		print '<br>';
diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php
index 7c08235e788005f03068ba47ad7975fce4343520..e8635ec48613fe6c0ac47a7c51025147c900028d 100644
--- a/htdocs/comm/mailing/card.php
+++ b/htdocs/comm/mailing/card.php
@@ -153,7 +153,7 @@ if (empty($reshook))
 		}
 		else
 		{
-			$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1);
+			$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
 
 			if ($object->statut == 0)
 			{
@@ -398,7 +398,7 @@ if (empty($reshook))
 	{
 		$error=0;
 
-		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1);
+		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
 
 		$object->sendto = $_POST["sendto"];
 		if (! $object->sendto)
@@ -495,7 +495,7 @@ if (empty($reshook))
 	// Action update description of emailing
 	if ($action == 'settitre' || $action == 'setemail_from' || $action == 'setreplyto' || $action == 'setemail_errorsto')
 	{
-		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1);
+		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
 
 		if ($action == 'settitre')					$object->titre          = trim(GETPOST('titre','alpha'));
 		else if ($action == 'setemail_from')		$object->email_from     = trim(GETPOST('email_from','alpha'));
@@ -527,7 +527,7 @@ if (empty($reshook))
 	 */
 	if (! empty($_POST['addfile']))
 	{
-		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1);
+		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
 
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 
@@ -540,7 +540,7 @@ if (empty($reshook))
 	// Action remove file
 	if (! empty($_POST["removedfile"]))
 	{
-		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1);
+		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
 
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 
@@ -719,7 +719,7 @@ else
 {
 	if ($object->id > 0)
 	{
-		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1);
+		$upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
 
 		$head = emailing_prepare_head($object);
 
diff --git a/htdocs/compta/paiement/cheque/card.php b/htdocs/compta/paiement/cheque/card.php
index dba17a4798c82f19a41ff981479259383e962d7f..49af748c1158111eee3c48baabcdd34f500c9d08 100644
--- a/htdocs/compta/paiement/cheque/card.php
+++ b/htdocs/compta/paiement/cheque/card.php
@@ -262,7 +262,7 @@ else if ($action == 'remove_file' && $user->rights->banque->cheque)
 
 		$langs->load("other");
 
-		$file=$dir.get_exdir($object->number,2,1) . GETPOST('file');
+		$file=$dir.get_exdir($object->number,2,1,0,$object,'cheque') . GETPOST('file');
 		$ret=dol_delete_file($file,0,0,0,$object);
 		if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('file')));
 		else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), 'errors');
@@ -322,7 +322,7 @@ else
 	if ($action == 'delete')
 	{
 		print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans("DeleteCheckReceipt"), $langs->trans("ConfirmDeleteCheckReceipt"), 'confirm_delete','','',1);
-		
+
 	}
 
 	/*
@@ -331,7 +331,7 @@ else
 	if ($action == 'valide')
 	{
 		print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans("ValidateCheckReceipt"), $langs->trans("ConfirmValidateCheckReceipt"), 'confirm_valide','','',1);
-		
+
 	}
 }
 
@@ -704,7 +704,7 @@ if ($action != 'new')
 	if ($object->statut == 1)
 	{
 		$filename=dol_sanitizeFileName($object->ref);
-		$filedir=$dir.get_exdir($object->number,2,1) . dol_sanitizeFileName($object->ref);
+		$filedir=$dir.get_exdir($object->number,2,1,0,$object,'cheque') . dol_sanitizeFileName($object->ref);
 		$urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id;
 
 		$formfile->show_documents('remisecheque', $filename, $filedir, $urlsource, 1, 1);
diff --git a/htdocs/core/class/fileupload.class.php b/htdocs/core/class/fileupload.class.php
index 520ab7634be6bf027e0b3fa4b76411911100e6f3..cdb7f66ac5ff3e8acebe5922f9ca0330f907d205 100644
--- a/htdocs/core/class/fileupload.class.php
+++ b/htdocs/core/class/fileupload.class.php
@@ -132,7 +132,7 @@ class FileUpload
 
 		$object_ref = dol_sanitizeFileName($object->ref);
 		if ($element == 'invoice_supplier') {
-			$object_ref = get_exdir($object->id, 2) . $object_ref;
+			$object_ref = get_exdir($object->id,2,0,0,$object,'invoice_supplier') . $object_ref;
 		} else if ($element == 'project_task') {
 			$object_ref = $object->project->ref . '/' . $object_ref;
 		}
diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php
index 406ad24db4bb6b5eea4646177cd19341135a0407..39634e6af3103c09d84f4b4f0833362d291b09ee 100644
--- a/htdocs/core/class/html.form.class.php
+++ b/htdocs/core/class/html.form.class.php
@@ -4806,19 +4806,19 @@ class Form
         else if ($modulepart=='userphoto')
         {
             $dir=$conf->user->dir_output;
-            if ($object->photo) $file=get_exdir($id, 2).$object->photo;
+            if ($object->photo) $file=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;
             if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
             $email=$object->email;
         }
         else if ($modulepart=='memberphoto')
         {
             $dir=$conf->adherent->dir_output;
-            if ($object->photo) $file=get_exdir($id, 2).'photos/'.$object->photo;
+            if ($object->photo) $file=get_exdir($id, 2, 0, 0, $object, 'invoice_supplier').'photos/'.$object->photo;
             if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
             $email=$object->email;
         }else {
         	$dir=$conf->$modulepart->dir_output;
-        	if ($object->photo) $file=get_exdir($id, 2).'photos/'.$object->photo;
+        	if ($object->photo) $file=get_exdir($id, 2, 0, 0, $adherent, 'member').'photos/'.$object->photo;
         	if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
         	$email=$object->email;
         }
diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php
index 6464f653fd4379534672ae0f41aa46acf6e2b6a9..cb0fe8728b2d6c022ea383779093cecdb66f2fc0 100644
--- a/htdocs/core/class/html.formfile.class.php
+++ b/htdocs/core/class/html.formfile.class.php
@@ -581,7 +581,7 @@ class FormFile
 					$relativepath=$file["name"];								// Cas general
 					if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
 					// Autre cas
-					if ($modulepart == 'donation')            { $relativepath = get_exdir($modulesubdir,2).$file["name"]; }
+					if ($modulepart == 'donation')            { $relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"]; }
 					if ($modulepart == 'export')              { $relativepath = $file["name"]; }
 
 					$out.= "<tr ".$bc[$var].">";
@@ -700,14 +700,14 @@ class FormFile
     			if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
     			// Autre cas
     			if ($modulepart == 'donation')            {
-    				$relativepath = get_exdir($modulesubdir,2).$file["name"];
+    				$relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"];
     			}
     			if ($modulepart == 'export')              {
     				$relativepath = $file["name"];
     			}
-	                if ($modulepart == 'facture_fournisseur') {
-	                    $relativepath = get_exdir($modulesubdir, 2). $modulesubdir. "/" . $file["name"];
-	                }
+	            if ($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_fournisseur') {
+	                $relativepath = get_exdir($modulesubdir, 2,0,0,null,'invoice_supplier'). $modulesubdir. "/" . $file["name"];
+	            }
 
     			// Show file name with link to download
     			$out.= '<a data-ajax="false" href="'.DOL_URL_ROOT . '/document.php?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).'"';
@@ -801,8 +801,8 @@ class FormFile
 					if (empty($relativepath))
 					{
 						$relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/';
-						if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2).$relativepath;	// TODO Call using a defined value for $relativepath
-						if ($object->element == 'member') $relativepath=get_exdir($object->id,2).$relativepath;				// TODO Call using a defined value for $relativepath
+						if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;	// TODO Call using a defined value for $relativepath
+						if ($object->element == 'member') $relativepath=get_exdir($object->id,2,0,0,$object,'member').$relativepath;				// TODO Call using a defined value for $relativepath
 						if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
 					}
 
diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php
index 0af5e917cc56b175f905f0378b18333de3098f23..7eb6d9c5dcf2c3afe9e93c0efe366b091061a78d 100644
--- a/htdocs/core/lib/files.lib.php
+++ b/htdocs/core/lib/files.lib.php
@@ -1817,7 +1817,7 @@ function dol_check_secure_access_document($modulepart,$original_file,$entity,$fu
 			$accessallowed=1;
 		}
 
-		$original_file=$conf->banque->dir_output.'/bordereau/'.get_exdir(basename($original_file,".pdf"),2,1).$original_file;
+		$original_file=$conf->banque->dir_output.'/bordereau/'.get_exdir(basename($original_file,".pdf"),2,1,0,null,'cheque').$original_file;
 	}
 
 	// Wrapping for export module
diff --git a/htdocs/core/lib/fourn.lib.php b/htdocs/core/lib/fourn.lib.php
index 3d605d109029c280eb549f9d4aa3089c6c878e9f..d350fbce17548565ed08859420440f0b0b007d5f 100644
--- a/htdocs/core/lib/fourn.lib.php
+++ b/htdocs/core/lib/fourn.lib.php
@@ -69,7 +69,7 @@ function facturefourn_prepare_head($object)
     }
 
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-	$upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$object->ref;
+	$upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$object->ref;
 	$nbFiles = count(dol_dir_list($upload_dir,'files',0,'','(\.meta|_preview\.png)$'));
 	$head[$h][0] = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$object->id;
 	$head[$h][1] = $langs->trans('Documents');
diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php
index 5938bc07eae7775e5f61c6093024525a99d3f0f7..01615391adb85e266c96f44fd890dd9db137e413 100644
--- a/htdocs/core/lib/functions.lib.php
+++ b/htdocs/core/lib/functions.lib.php
@@ -3709,18 +3709,19 @@ function yn($yesno, $case=1, $color=0)
  *	@param  int		$level		    Level of subdirs to return (1, 2 or 3 levels)
  * 	@param	int		$alpha		    Use alpha ref
  *  @param  int		$withoutslash   0=With slash at end, 1=without slash at end (except if '/', we return '')
- *  @param	string	$ref			Not used yet. May be used to manage different option of directory path according to element.
- *  @param	string	$modulepart		Not used yet. May be used to manage different option of directory path according to element.
+ *  @param	Object	$object			Object
+ *  @param	string	$modulepart		Type of object ('invoice_supplier, 'donation', 'invoice', ...')
  *  @return	string					Dir to use ending. Example '' or '1/' or '1/2/'
  */
-function get_exdir($num,$level,$alpha=0,$withoutslash=0,$ref='',$modulepart='')
+function get_exdir($num,$level,$alpha=0,$withoutslash=0,$object=null,$modulepart='')
 {
 	global $conf;
 
 	$path = '';
 
-	if (in_array($modulepart, array('don','donation','supplier_invoice','invoice_supplier')))
+	if (! empty($level) && in_array($modulepart, array('shipment', 'member','don','donation','supplier_invoice','invoice_supplier')))
 	{
+		// This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided
 		if (empty($alpha)) $num = preg_replace('/([^0-9])/i','',$num);
 		else $num = preg_replace('/^.*\-/i','',$num);
 		$num = substr("000".$num, -$level);
diff --git a/htdocs/core/modules/askpricesupplier/doc/pdf_aurore.modules.php b/htdocs/core/modules/askpricesupplier/doc/pdf_aurore.modules.php
index 753c9ad923734778247e885b4a965dcb7d3a6516..6acbb1fc4d06ab483c0135dc8aebe01b2a472f8b 100644
--- a/htdocs/core/modules/askpricesupplier/doc/pdf_aurore.modules.php
+++ b/htdocs/core/modules/askpricesupplier/doc/pdf_aurore.modules.php
@@ -165,7 +165,7 @@ class pdf_aurore extends ModelePDFAskPriceSupplier
 				$objphoto = new Product($this->db);
 				$objphoto->fetch($object->lines[$i]->fk_product);
 
-				$pdir = get_exdir($object->lines[$i]->fk_product,2) . $object->lines[$i]->fk_product ."/photos/";
+				$pdir = get_exdir($object->lines[$i]->fk_product,2,0,0,$object,'product') . $object->lines[$i]->fk_product ."/photos/";
 				$dir = $conf->product->dir_output.'/'.$pdir;
 
 				$realpath='';
@@ -708,7 +708,7 @@ class pdf_aurore extends ModelePDFAskPriceSupplier
 
 			$pdf->SetFont('','', $default_font_size - 2);
 			$pdf->SetXY($posxval, $posy);
-			
+
 			$lib_condition_paiement=str_replace('\n',"\n",$lib_condition_paiement);
 			$pdf->MultiCell(80, 4, $lib_condition_paiement,0,'L');
 
@@ -1266,7 +1266,7 @@ class pdf_aurore extends ModelePDFAskPriceSupplier
 		$pdf->SetTextColor(0,0,60);
 		$pdf->MultiCell(100, 3, $outputlangs->transnoentities("AskPriceSupplierDate")." : " . dol_print_date($object->date_livraison,"day",false,$outputlangs,true), '', 'R');
 */
-		
+
 		if ($object->client->code_client)
 		{
 			$posy+=4;
diff --git a/htdocs/core/modules/cheque/pdf/pdf_blochet.class.php b/htdocs/core/modules/cheque/pdf/pdf_blochet.class.php
index aef8770a501394fc375882d47159cb5232403eac..d8a4823c785f5c924ba7e1e94e8f8360d89cc247 100644
--- a/htdocs/core/modules/cheque/pdf/pdf_blochet.class.php
+++ b/htdocs/core/modules/cheque/pdf/pdf_blochet.class.php
@@ -98,7 +98,7 @@ class BordereauChequeBlochet extends ModeleChequeReceipts
 		$outputlangs->load("products");
         $outputlangs->load("compta");
 
-		$dir = $_dir . "/".get_exdir($number,2,1).$number;
+		$dir = $_dir . "/".get_exdir($number,2,1,0,null,'cheque').$number;
 
 		if (! is_dir($dir))
 		{
diff --git a/htdocs/core/modules/dons/html_cerfafr.modules.php b/htdocs/core/modules/dons/html_cerfafr.modules.php
index 79e2b212f33c00aef60120e7c4efe8fb305560f1..9da0d45db502cbb018aa9f8b77c7b10f1ae5fea8 100644
--- a/htdocs/core/modules/dons/html_cerfafr.modules.php
+++ b/htdocs/core/modules/dons/html_cerfafr.modules.php
@@ -3,7 +3,7 @@
  * Copyright (C) 2005-2006	Laurent Destailleur		<eldy@users.sourceforge.net>
  * Copyright (C) 2012		Regis Houssin			<regis.houssin@capnetworks.com>
  * Copyright (C) 2012       Marcos García           <marcosgdf@gmail.com>
- * Copyright (C) 2014       Alexandre Spangaro		<alexandre.spangaro@gmail.com> 
+ * Copyright (C) 2014       Alexandre Spangaro		<alexandre.spangaro@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
@@ -105,7 +105,7 @@ class html_cerfafr extends ModeleDon
 			else
 			{
 				$donref = dol_sanitizeFileName($don->ref);
-				$dir = $conf->don->dir_output . "/" . get_exdir($donref,2);
+				$dir = $conf->don->dir_output . "/" . get_exdir($donref,2,0,0,$don,'donation');
 				$file = $dir . "/" . $donref . ".html";
 			}
 
@@ -168,18 +168,18 @@ class html_cerfafr extends ModeleDon
 		        $form = str_replace('__Message__',$outputlangs->trans("Message"),$form);
 		        $form = str_replace('__IConfirmDonationReception__',$outputlangs->trans("IConfirmDonationReception"),$form);
 		        $form = str_replace('__DonationMessage__',$conf->global->DONATION_MESSAGE,$form);
-				
+
 				$frencharticle='';
 		        if (preg_match('/fr/i',$outputlangs->defaultlang)) $frencharticle='<font size="+1">Article 200, 238 bis et 885-0 V bis A du code général des impôts (CGI)</font>';
 				$form = str_replace('__FrenchArticle__',$frencharticle,$form);
-				
+
 				$frencheligibility='';
 				if (preg_match('/fr/i',$outputlangs->defaultlang)) $frencheligibility='Le bénéficiaire certifie sur l\'honneur que les dons et versements qu\'il reçoit ouvrent droit à la réduction d\'impôt prévue à l\'article :';
 				$form = str_replace('__FrenchEligibility__',$frencheligibility,$form);
-				
+
 				$art200='';
 				if (preg_match('/fr/i',$outputlangs->defaultlang)) {
-					if ($conf->global->DONATION_ART200 >= 1) 
+					if ($conf->global->DONATION_ART200 >= 1)
 					{
 						$art200='<input type="checkbox" checked>200 du CGI';
 					}
@@ -192,7 +192,7 @@ class html_cerfafr extends ModeleDon
 
 				$art238='';
 				if (preg_match('/fr/i',$outputlangs->defaultlang)) {
-					if ($conf->global->DONATION_ART238 >= 1) 
+					if ($conf->global->DONATION_ART238 >= 1)
 					{
 						$art238='<input type="checkbox" checked>238 bis du CGI';
 					}
@@ -202,10 +202,10 @@ class html_cerfafr extends ModeleDon
 					}
 				}
 				$form = str_replace('__ARTICLE238__',$art238,$form);
-				
+
 				$art885='';
 				if (preg_match('/fr/i',$outputlangs->defaultlang)) {
-					if ($conf->global->DONATION_ART885 >= 1) 
+					if ($conf->global->DONATION_ART885 >= 1)
 					{
 						$art885='<input type="checkbox" checked>885-0 V bis du CGI';
 					}
@@ -215,7 +215,7 @@ class html_cerfafr extends ModeleDon
 					}
 				}
 				$form = str_replace('__ARTICLE885__',$art885,$form);
-				
+
 				// Save file on disk
 		        dol_syslog("html_cerfafr::write_file $file");
 		        $handle=fopen($file,"w");
diff --git a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php
index c6c290ac204b9c10b472c511a35a55d71f39b88c..16447b8f0821719948dea13f0170b7d6b63fb74d 100644
--- a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php
+++ b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php
@@ -190,7 +190,7 @@ class pdf_crabe extends ModelePDFFactures
 				$objphoto = new Product($this->db);
 				$objphoto->fetch($object->lines[$i]->fk_product);
 
-				$pdir = get_exdir($object->lines[$i]->fk_product,2) . $object->lines[$i]->fk_product ."/photos/";
+				$pdir = get_exdir($object->lines[$i]->fk_product,2,0,0,'product') . $object->lines[$i]->fk_product ."/photos/";
 				$dir = $conf->product->dir_output.'/'.$pdir;
 
 				$realpath='';
diff --git a/htdocs/core/modules/member/doc/pdf_standard.class.php b/htdocs/core/modules/member/doc/pdf_standard.class.php
index c421ae1cda4600fafb0d736c98d525d001362983..a768cfefc5349de8de8067ffe8934b80e9c347ed 100644
--- a/htdocs/core/modules/member/doc/pdf_standard.class.php
+++ b/htdocs/core/modules/member/doc/pdf_standard.class.php
@@ -45,7 +45,7 @@ class pdf_standard extends CommonStickerGenerator
 	function addSticker(&$pdf,$outputlangs,$param) {
 		// use this method in future refactoring
 	}
-	
+
 	/**
 	 * Output a sticker on page at position _COUNTX, _COUNTY (_COUNTX and _COUNTY start from 0)
 	 * - %LOGO% is replace with company logo
@@ -96,7 +96,7 @@ class pdf_standard extends CommonStickerGenerator
 		$dir=$conf->adherent->dir_output;
 		if (! empty($photo))
 		{
-			$file=get_exdir($idmember,2).'photos/'.$photo;
+			$file=get_exdir($idmember,2,0,0,null,'member').'photos/'.$photo;
 			$photo=$dir.'/'.$file;
 			if (! is_readable($photo)) $photo='';
 		}
diff --git a/htdocs/core/modules/propale/doc/pdf_azur.modules.php b/htdocs/core/modules/propale/doc/pdf_azur.modules.php
index 5463694f0e84904bacc903e922409e37fa63ea7c..ad45d1150f3ea07ae75ed6887a4c44d3a6ef6842 100644
--- a/htdocs/core/modules/propale/doc/pdf_azur.modules.php
+++ b/htdocs/core/modules/propale/doc/pdf_azur.modules.php
@@ -179,13 +179,13 @@ class pdf_azur extends ModelePDFPropales
 
 				if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
 				{
-					$pdir[0] = get_exdir($objphoto->id,2) . $objphoto->id ."/photos/";
+					$pdir[0] = get_exdir($objphoto->id,2,0,0,$objphoto,'product') . $objphoto->id ."/photos/";
 					$pdir[1] = dol_sanitizeFileName($objphoto->ref).'/';
 				}
 				else
 				{
 					$pdir[0] = dol_sanitizeFileName($objphoto->ref).'/';				// default
-					$pdir[1] = get_exdir($objphoto->id,2) . $objphoto->id ."/photos/";	// alternative
+					$pdir[1] = get_exdir($objphoto->id,2,0,0,$objphoto,'product') . $objphoto->id ."/photos/";	// alternative
 				}
 
 				$arephoto = false;
diff --git a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php
index c01dfacd1c33519c9a8922ccf537ac0ebed95d11..e00546711c89a9f135c86bbac61530e6e9bf5d31 100644
--- a/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php
+++ b/htdocs/core/modules/supplier_invoice/pdf/pdf_canelle.modules.php
@@ -173,7 +173,7 @@ class pdf_canelle extends ModelePDFSuppliersInvoices
 			{
 				$objectref = dol_sanitizeFileName($object->ref);
 				$objectrefsupplier = dol_sanitizeFileName($object->ref_supplier);
-                $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$objectref;
+                $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$objectref;
 				$file = $dir . "/" . $objectref . ".pdf";
 				if (! empty($conf->global->SUPPLIER_REF_IN_NAME)) $file = $dir . "/" . $objectref . ($objectrefsupplier?"_".$objectrefsupplier:"").".pdf";
 			}
diff --git a/htdocs/don/card.php b/htdocs/don/card.php
index cf7108070436654b4c423b138954add6b3215f8d..2047c9b5f8f294b4f351481509a008dc3467d702 100644
--- a/htdocs/don/card.php
+++ b/htdocs/don/card.php
@@ -110,7 +110,7 @@ if ($action == 'update')
 		$object->fk_projet   = GETPOST("fk_projet");
 		$object->note_private= GETPOST("note_private");
 		$object->note_public = GETPOST("note_public");
-		
+
 		// Fill array 'array_options' with data from add form
         $ret = $extrafields->setOptionalsFromPost($extralabels,$object);
 		if ($ret < 0) $error++;
@@ -163,7 +163,7 @@ if ($action == 'add')
 		$object->note_public = GETPOST("note_public");
 		$object->public      = GETPOST("public");
 		$object->fk_projet   = GETPOST("fk_projet");
-		
+
 		// Fill array 'array_options' with data from add form
         $ret = $extrafields->setOptionalsFromPost($extralabels,$object);
 		if ($ret < 0) $error++;
@@ -274,9 +274,9 @@ if ($action == 'create')
 	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">';
-	
+
 	dol_fiche_head('');
-	
+
 	print '<table class="border" width="100%">';
 
     $nbrows=11;
@@ -312,14 +312,14 @@ if ($action == 'create')
     print $form->select_country(GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id);
     if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
     print '</td></tr>';
-	
+
 	print "<tr>".'<td>'.$langs->trans("EMail").'</td><td><input type="text" name="email" value="'.GETPOST("email").'" size="40"></td></tr>';
 
 	// Public note
 	print '<tr>';
 	print '<td class="border" valign="top">' . $langs->trans('NotePublic') . '</td>';
 	print '<td valign="top" colspan="2">';
-	
+
     $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70);
 	print $doleditor->Create(1);
 	print '</td></tr>';
@@ -337,9 +337,9 @@ if ($action == 'create')
 
 	if (! empty($conf->projet->enabled))
     {
-    	
+
     	$formproject=new FormProjets($db);
-    	
+
         print "<tr><td>".$langs->trans("Project")."</td><td>";
         $formproject->select_projects(-1, GETPOST("fk_projet"),'fk_projet', 0, 0, 1, 1);
 		print "</td></tr>\n";
@@ -352,11 +352,11 @@ if ($action == 'create')
     {
 		print $object->showOptionals($extrafields,'edit',$parameters);
     }
-	
+
 	print "</table>\n";
-	
+
 	dol_fiche_end();
-	
+
 	print '<div class="center"><input type="submit" class="button" name="save" value="'.$langs->trans("Save").'"> &nbsp; &nbsp; <input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
 
 	print "</form>\n";
@@ -441,7 +441,7 @@ if (! empty($id) && $action == 'edit')
 	print $form->select_country((!empty($object->country_id)?$object->country_id:$mysoc->country_code),'country_id');
 	if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
 	print '</td></tr>';
-	
+
 	print "<tr>".'<td>'.$langs->trans("EMail").'</td><td><input type="text" name="email" size="40" value="'.$object->email.'"></td></tr>';
 
     print "<tr><td>".$langs->trans("PaymentMode")."</td><td>\n";
@@ -458,7 +458,7 @@ if (! empty($id) && $action == 'edit')
     if (! empty($conf->projet->enabled))
     {
     	$formproject=new FormProjets($db);
-    	
+
         $langs->load('projects');
         print '<tr><td>'.$langs->trans('Project').'</td><td>';
 		$formproject->select_projects(-1, $object->fk_projet,'fk_projet', 0, 1, 0, 1);
@@ -497,7 +497,7 @@ if (! empty($id) && $action != 'edit')
         $text=$langs->trans("ConfirmDeleteADonation");
         print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id,$langs->trans("DeleteADonation"),$text,"confirm_delete",'','',1);
     }
-	
+
 	$result=$object->fetch($id);
 	if ($result < 0) {
 		dol_print_error($db,$object->error); exit;
@@ -506,7 +506,7 @@ if (! empty($id) && $action != 'edit')
 	if ($result < 0) {
 		dol_print_error($db); exit;
 	}
-	
+
 	$head = donation_prepare_head($object);
 	dol_fiche_head($head, $hselected, $langs->trans("Donation"), 0, 'generic');
 
@@ -542,7 +542,7 @@ if (! empty($id) && $action != 'edit')
 	print '<tr><td>'.$langs->trans("Lastname").'</td><td colspan="2">'.$object->lastname.'</td></tr>';
 	print '<tr><td>'.$langs->trans("Firstname").'</td><td colspan="2">'.$object->firstname.'</td></tr>';
 	print '<tr><td>'.$langs->trans("Address").'</td><td>'.dol_nl2br($object->address).'</td>';
-	
+
 	$rowspan=6;
 	if (! empty($conf->projet->enabled)) $rowspan++;
 	print '<td rowspan="'.$rowspan.'" valign="top">';
@@ -584,7 +584,7 @@ if (! empty($id) && $action != 'edit')
 			print "<tr ".$bc[$var]."><td>";
 			print '<a href="'.DOL_URL_ROOT.'/don/payment/card.php?id='.$objp->rowid.'">'.img_object($langs->trans("Payment"),"payment").' '.$objp->rowid.'</a></td>';
 			print '<td>'.dol_print_date($db->jdate($objp->dp),'day')."</td>\n";
-		        $labeltype=$langs->trans("PaymentType".$object->type_code)!=("PaymentType".$object->type_code)?$langs->trans("PaymentType".$object->type_code):$object->paiement_type;				
+		        $labeltype=$langs->trans("PaymentType".$object->type_code)!=("PaymentType".$object->type_code)?$langs->trans("PaymentType".$object->type_code):$object->paiement_type;
                                print "<td>".$labeltype.' '.$object->num_paiement."</td>\n";
 			print '<td align="right">'.price($objp->amount)."</td><td>&nbsp;".$langs->trans("Currency".$conf->currency)."</td>\n";
 			print "</tr>";
@@ -628,7 +628,7 @@ if (! empty($id) && $action != 'edit')
 	else
 	{
 		print $object->country_olddata;
-	}	
+	}
 	print '</td></tr>';
 
 	// EMail
@@ -683,12 +683,12 @@ if (! empty($id) && $action != 'edit')
     }
 
 	// Create payment
-	if ($object->statut == 1 && $object->paid == 0 && $user->rights->don->creer) 
+	if ($object->statut == 1 && $object->paid == 0 && $user->rights->don->creer)
 	{
-		if ($remaintopay == 0) 
+		if ($remaintopay == 0)
 		{
 			print '<div class="inline-block divButAction"><span class="butActionRefused" title="' . $langs->trans("DisabledBecauseRemainderToPayIsZero") . '">' . $langs->trans('DoPayment') . '</span></div>';
-		} 
+		}
 		else
 		{
 			print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/don/payment/payment.php?rowid=' . $object->id . '&amp;action=create">' . $langs->trans('DoPayment') . '</a></div>';
@@ -700,7 +700,7 @@ if (! empty($id) && $action != 'edit')
 	{
 		print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?rowid='.$object->id.'&action=set_paid">'.$langs->trans("ClassifyPaid")."</a></div>";
 	}
-	
+
 	// Delete
 	if ($user->rights->don->supprimer)
 	{
@@ -720,7 +720,7 @@ if (! empty($id) && $action != 'edit')
 	 * Documents generes
 	 */
 	$filename=dol_sanitizeFileName($object->id);
-	$filedir=$conf->don->dir_output . '/' . get_exdir($filename,2);
+	$filedir=$conf->don->dir_output . '/' . get_exdir($filename,2,0,0,$object,'donation');
 	$urlsource=$_SERVER['PHP_SELF'].'?rowid='.$object->id;
 	//            $genallowed=($fac->statut == 1 && ($fac->paye == 0 || $user->admin) && $user->rights->facture->creer);
 	//            $delallowed=$user->rights->facture->supprimer;
diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php
index 41def896ac0f585351a3971acab94473e3c13a3d..e0b5b791adacf19a2da43ad4323d8837576cb3b5 100644
--- a/htdocs/expedition/class/expedition.class.php
+++ b/htdocs/expedition/class/expedition.class.php
@@ -497,7 +497,7 @@ class Expedition extends CommonObject
 
 				if ($this->statut == 0) $this->brouillon = 1;
 
-				$file = $conf->expedition->dir_output . "/" .get_exdir($this->id, 2) . "/" . $this->id.".pdf";
+				$file = $conf->expedition->dir_output . "/" .get_exdir($this->id, 2, 0, 0, $this, 'shipment') . "/" . $this->id.".pdf";
 				$this->pdf_filename = $file;
 
 				// Tracking url
diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php
index 0c5998d953cf7e1d42deebcb6821656247d09a46..994ddb28310b9b067178efb96ea2e5d39a965a4b 100644
--- a/htdocs/fourn/class/fournisseur.facture.class.php
+++ b/htdocs/fourn/class/fournisseur.facture.class.php
@@ -736,7 +736,7 @@ class FactureFournisseur extends CommonInvoice
         		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 
         		$ref = dol_sanitizeFileName($this->ref);
-        		$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2).$ref;
+        		$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref;
         		$file = $dir . "/" . $ref . ".pdf";
         		if (file_exists($file))
         		{
@@ -975,8 +975,8 @@ class FactureFournisseur extends CommonInvoice
             		$oldref = dol_sanitizeFileName($this->ref);
             		$newref = dol_sanitizeFileName($num);
 
-            		$dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2).$oldref;
-            		$dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2).$newref;
+            		$dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoive_supplier').$oldref;
+            		$dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoive_supplier').$newref;
             		if (file_exists($dirsource))
             		{
             			dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
@@ -985,7 +985,7 @@ class FactureFournisseur extends CommonInvoice
             			{
             				dol_syslog("Rename ok");
                             // Rename docs starting with $oldref with $newref
-	                        $listoffiles=dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2).$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
+	                        $listoffiles=dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2,0,0, $this, 'invoive_supplier').$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
 	                        foreach($listoffiles as $fileentry)
 	                        {
 	                        	$dirsource=$fileentry['name'];
diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php
index 73832e9f3b762e967d2a82011c01b257a47aee49..78119bdbf269fe2c4a8486c57e67c90f2c899357 100644
--- a/htdocs/fourn/facture/card.php
+++ b/htdocs/fourn/facture/card.php
@@ -926,143 +926,131 @@ if (empty($reshook))
 	    $result=$object->fetch_thirdparty();
 	    if ($result > 0)
 	    {
-	//        $ref = dol_sanitizeFileName($object->ref);
-	//        $file = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$ref.'/'.$ref.'.pdf';
-
-	//        if (is_readable($file))
-	//        {
-	            if ($_POST['sendto'])
-	            {
-	                // Le destinataire a ete fourni via le champ libre
-	                $sendto = $_POST['sendto'];
-	                $sendtoid = 0;
-	            }
-	            elseif ($_POST['receiver'] != '-1')
-	            {
-	                // Recipient was provided from combo list
-	                if ($_POST['receiver'] == 'thirdparty') // Id of third party
-	                {
-	                    $sendto = $object->client->email;
-	                    $sendtoid = 0;
-	                }
-	                else	// Id du contact
-	                {
-	                    $sendto = $object->client->contact_get_property($_POST['receiver'],'email');
-	                    $sendtoid = $_POST['receiver'];
-	                }
-	            }
-
-	            if (dol_strlen($sendto))
-	            {
-	                $langs->load("commercial");
+            if ($_POST['sendto'])
+            {
+                // Le destinataire a ete fourni via le champ libre
+                $sendto = $_POST['sendto'];
+                $sendtoid = 0;
+            }
+            elseif ($_POST['receiver'] != '-1')
+            {
+                // Recipient was provided from combo list
+                if ($_POST['receiver'] == 'thirdparty') // Id of third party
+                {
+                    $sendto = $object->client->email;
+                    $sendtoid = 0;
+                }
+                else	// Id du contact
+                {
+                    $sendto = $object->client->contact_get_property($_POST['receiver'],'email');
+                    $sendtoid = $_POST['receiver'];
+                }
+            }
 
-	                $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
-	                $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>';
-	                $message = $_POST['message'];
-	                $sendtocc = $_POST['sendtocc'];
-	                $deliveryreceipt = $_POST['deliveryreceipt'];
+            if (dol_strlen($sendto))
+            {
+                $langs->load("commercial");
 
-	                if ($action == 'send')
-	                {
-	                    if (dol_strlen($_POST['subject'])) $subject=$_POST['subject'];
-	                    else $subject = $langs->transnoentities('CustomerOrder').' '.$object->ref;
-	                    $actiontypecode='AC_SUP_INV';
-	                    $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
-	                    if ($message)
-	                    {
-							if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
-							$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
-							$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
-							$actionmsg = dol_concatdesc($actionmsg, $message);
-	                    }
-	                    $actionmsg2=$langs->transnoentities('Action'.$actiontypecode);
-	                }
+                $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
+                $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>';
+                $message = $_POST['message'];
+                $sendtocc = $_POST['sendtocc'];
+                $deliveryreceipt = $_POST['deliveryreceipt'];
 
-	                // Create form object
-	                include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
-	                $formmail = new FormMail($db);
+                if ($action == 'send')
+                {
+                    if (dol_strlen($_POST['subject'])) $subject=$_POST['subject'];
+                    else $subject = $langs->transnoentities('CustomerOrder').' '.$object->ref;
+                    $actiontypecode='AC_SUP_INV';
+                    $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
+                    if ($message)
+                    {
+						if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
+						$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
+						$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
+						$actionmsg = dol_concatdesc($actionmsg, $message);
+                    }
+                    $actionmsg2=$langs->transnoentities('Action'.$actiontypecode);
+                }
 
-	                $attachedfiles=$formmail->get_attached_files();
-	                $filepath = $attachedfiles['paths'];
-	                $filename = $attachedfiles['names'];
-	                $mimetype = $attachedfiles['mimes'];
+                // Create form object
+                include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
+                $formmail = new FormMail($db);
 
-	                // Send mail
-	                require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
-	                $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1);
-	                if ($mailfile->error)
-	                {
-	                    setEventMessage($mailfile->error,'errors');
-	                }
-	                else
-	                {
-	                    $result=$mailfile->sendfile();
-	                    if ($result)
-	                    {
-	                        $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2));		// Must not contain "
-	                        setEventMessage($mesg);
-
-	                        $error=0;
-
-	                        // Initialisation donnees
-	                        $object->sendtoid		= $sendtoid;
-	                        $object->actiontypecode	= $actiontypecode;
-	                        $object->actionmsg		= $actionmsg;
-	                        $object->actionmsg2		= $actionmsg2;
-	                        $object->fk_element		= $object->id;
-	                        $object->elementtype	= $object->element;
-
-	                        // Appel des triggers
-	                        include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
-	                        $interface=new Interfaces($db);
-	                        $result=$interface->run_triggers('BILL_SUPPLIER_SENTBYMAIL',$object,$user,$langs,$conf);
-	                        if ($result < 0) {
-	                            $error++; $object->errors=$interface->errors;
-	                        }
-	                        // Fin appel triggers
+                $attachedfiles=$formmail->get_attached_files();
+                $filepath = $attachedfiles['paths'];
+                $filename = $attachedfiles['names'];
+                $mimetype = $attachedfiles['mimes'];
 
-	                        if ($error)
-	                        {
-	                            dol_print_error($db);
-	                        }
-	                        else
-	                        {
-	                            // Redirect here
-	                            // This avoid sending mail twice if going out and then back to page
-	                            header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
-	                            exit;
-	                        }
-	                    }
-	                    else
-	                    {
-	                        $langs->load("other");
-	                        if ($mailfile->error)
-	                        {
-	                            $mesg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
-	                            $mesg.='<br>'.$mailfile->error;
-	                        }
-	                        else
-	                        {
-	                            $mesg.='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
-	                        }
-		                    setEventMessage($mesg, 'errors');
-	                    }
-	                }
-	            }
+                // Send mail
+                require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
+                $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1);
+                if ($mailfile->error)
+                {
+                    setEventMessage($mailfile->error,'errors');
+                }
+                else
+                {
+                    $result=$mailfile->sendfile();
+                    if ($result)
+                    {
+                        $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2));		// Must not contain "
+                        setEventMessage($mesg);
+
+                        $error=0;
+
+                        // Initialisation donnees
+                        $object->sendtoid		= $sendtoid;
+                        $object->actiontypecode	= $actiontypecode;
+                        $object->actionmsg		= $actionmsg;
+                        $object->actionmsg2		= $actionmsg2;
+                        $object->fk_element		= $object->id;
+                        $object->elementtype	= $object->element;
+
+                        // Appel des triggers
+                        include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
+                        $interface=new Interfaces($db);
+                        $result=$interface->run_triggers('BILL_SUPPLIER_SENTBYMAIL',$object,$user,$langs,$conf);
+                        if ($result < 0) {
+                            $error++; $object->errors=$interface->errors;
+                        }
+                        // Fin appel triggers
+
+                        if ($error)
+                        {
+                            dol_print_error($db);
+                        }
+                        else
+                        {
+                            // Redirect here
+                            // This avoid sending mail twice if going out and then back to page
+                            header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
+                            exit;
+                        }
+                    }
+                    else
+                    {
+                        $langs->load("other");
+                        if ($mailfile->error)
+                        {
+                            $mesg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
+                            $mesg.='<br>'.$mailfile->error;
+                        }
+                        else
+                        {
+                            $mesg.='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
+                        }
+	                    setEventMessage($mesg, 'errors');
+                    }
+                }
+            }
 
-	            else
-	            {
-	                $langs->load("other");
-		            setEventMessage($langs->trans('ErrorMailRecipientIsEmpty'), 'errors');
-	                dol_syslog('Recipient email is empty');
-	            }
-	/*        }
-	        else
-	        {
-	            $langs->load("errors");
-	            $mesg='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div>';
-	            dol_syslog('Failed to read file: '.$file);
-	        }*/
+            else
+            {
+                $langs->load("other");
+	            setEventMessage($langs->trans('ErrorMailRecipientIsEmpty'), 'errors');
+                dol_syslog('Recipient email is empty');
+            }
 	    }
 	    else
 	    {
@@ -1319,7 +1307,7 @@ if ($action == 'create')
     }
 
     dol_fiche_head();
-    
+
     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">';
@@ -1575,7 +1563,7 @@ if ($action == 'create')
     print "</table>\n";
 
     dol_fiche_end();
-    
+
     print '<div class="center"><input type="submit" class="button" name="bouton" value="'.$langs->trans('CreateDraft').'"></div>';
 
     print "</form>\n";
@@ -2405,8 +2393,8 @@ else
                 */
 
                 $ref=dol_sanitizeFileName($object->ref);
-                $subdir = get_exdir($object->id,2).$ref;
-                $filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$ref;
+                $subdir = get_exdir($object->id,2,0,0,$object,'invoice_supplier').$ref;
+                $filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$ref;
                 $urlsource=$_SERVER['PHP_SELF'].'?id='.$object->id;
                 $genallowed=$user->rights->fournisseur->facture->creer;
                 $delallowed=$user->rights->fournisseur->facture->supprimer;
@@ -2512,7 +2500,7 @@ else
         {
             $ref = dol_sanitizeFileName($object->ref);
             include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-            $fileparams = dol_most_recent_file($conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$ref, preg_quote($ref,'/'));
+            $fileparams = dol_most_recent_file($conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$ref, preg_quote($ref,'/'));
             $file=$fileparams['fullname'];
 
             // Define output language
@@ -2539,7 +2527,7 @@ else
                     dol_print_error($db,$result);
                     exit;
                 }
-                $fileparams = dol_most_recent_file($conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$ref, preg_quote($ref,'/'));
+                $fileparams = dol_most_recent_file($conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$ref, preg_quote($ref,'/'));
                 $file=$fileparams['fullname'];
             }
 
diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php
index e6fed65342183db17a9bccf30a892cd1bd1c2582..7b36ec62c375a5c75d3a3eb414772f92993fa7bf 100644
--- a/htdocs/fourn/facture/document.php
+++ b/htdocs/fourn/facture/document.php
@@ -64,7 +64,7 @@ if ($object->fetch($id, $ref))
 {
 	$object->fetch_thirdparty();
 	$ref=dol_sanitizeFileName($object->ref);
-	$upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$ref;
+	$upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2,0,0,$object,'invoice_supplier').$ref;
 }
 
 
diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php
index 887fa7c6fab6983486818dcd0de9a59bb3a56983..d546e796fa17bcb78694cd1ff203cfeb6068b658 100644
--- a/htdocs/fourn/facture/list.php
+++ b/htdocs/fourn/facture/list.php
@@ -8,7 +8,7 @@
  * Copyright (C) 2015      Marcos García        <marcosgdf@gmail.com>
  * Copyright (C) 2015	   juanjo Menent		<jmenent@2byte.es>
  * Copyright (C) 2015 	   Abbes Bahfir 	<bafbes@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
  * the Free Software Foundation; either version 3 of the License, or
@@ -309,7 +309,7 @@ if ($resql)
 		$facturestatic->ref_supplier=$obj->ref_supplier;
 		print $facturestatic->getNomUrl(1);
 		$filename=dol_sanitizeFileName($obj->ref);
-		$filedir=$conf->fournisseur->facture->dir_output.'/'.get_exdir($obj->facid,2).dol_sanitizeFileName($object->ref?$obj->ref:$obj->facid);
+		$filedir=$conf->fournisseur->facture->dir_output.'/'.get_exdir($obj->facid,2,0,0,$object,'invoice_supplier').dol_sanitizeFileName($object->ref?$obj->ref:$obj->facid);
 		print $formfile->getDocumentsLink('facture_fournisseur', $filename, $filedir);
 		print "</td>\n";
 
diff --git a/htdocs/fourn/product/photos.php b/htdocs/fourn/product/photos.php
index ba5c396c42017de39f606f1965491d0fd0fc3cf5..49f2fc2b65b531e31b5bf05153995308435c7863 100644
--- a/htdocs/fourn/product/photos.php
+++ b/htdocs/fourn/product/photos.php
@@ -138,7 +138,7 @@ if ($id)
 			$nbphoto=0;
 			$nbbyrow=5;
 
-			$pdir = get_exdir($object->id,2) . $object->id ."/photos/";
+			$pdir = get_exdir($object->id,2,0,0,$object,'product') . $object->id ."/photos/";
 			$dir = $conf->product->multidir_output[$object->entity] . '/'. $pdir;
 
 			print '<br><table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php
index b9ceb7c240afbcc66ee239100783efccb82c869c..d2c3deeb2e4f08cf71dbb28700bb3d7f137831a9 100644
--- a/htdocs/product/class/product.class.php
+++ b/htdocs/product/class/product.class.php
@@ -3383,7 +3383,7 @@ class Product extends CommonObject
 		$result = 0;
 
 		$dir = $sdir;
-		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $dir .= '/'. get_exdir($this->id,2) . $this->id ."/photos";
+		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $dir .= '/'. get_exdir($this->id,2,0,0,$this,'product') . $this->id ."/photos";
 		else $dir .= '/'.dol_sanitizeFileName($this->ref);
 
 		dol_mkdir($dir);
@@ -3421,7 +3421,7 @@ class Product extends CommonObject
 		global $conf;
 
 		$dir = $sdir;
-		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $dir .= '/'. get_exdir($this->id,2) . $this->id ."/photos/";
+		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $dir .= '/'. get_exdir($this->id,2,0,0,$this,'product') . $this->id ."/photos/";
 		else $dir .= '/'.dol_sanitizeFileName($this->ref).'/';
 
 		$nbphoto=0;
@@ -3468,8 +3468,8 @@ class Product extends CommonObject
 		$pdir = '/';
 		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
 		{
-			$dir .= get_exdir($this->id,2) . $this->id ."/photos/";
-			$pdir .= get_exdir($this->id,2) . $this->id ."/photos/";
+			$dir .= get_exdir($this->id,2,0,0,$this,'product') . $this->id ."/photos/";
+			$pdir .= get_exdir($this->id,2,0,0,$this,'product') . $this->id ."/photos/";
 		}
 		else
 		{
diff --git a/htdocs/projet/element.php b/htdocs/projet/element.php
index a56de8ec84b76b4140b58a1eae0fc17cb5d93625..c5f561b2c1c970d905f4950f2cc4f2239a7431cb 100644
--- a/htdocs/projet/element.php
+++ b/htdocs/projet/element.php
@@ -434,8 +434,8 @@ foreach ($listofreferent as $key => $value)
 					}
 					else if($element_doc === 'invoice_supplier') {
 						$element_doc='facture_fournisseur';
-						$filename = get_exdir($element->id,2).dol_sanitizeFileName($element->ref);
-						$filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($element->id,2).dol_sanitizeFileName($element->ref);
+						$filename = get_exdir($element->id,2,0,0,$this,'product').dol_sanitizeFileName($element->ref);
+						$filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($element->id,2,0,0,null,'invoice_supplier').dol_sanitizeFileName($element->ref);
 					}
 
 					print $formfile->getDocumentsLink($element_doc, $filename, $filedir);
diff --git a/htdocs/societe/document.php b/htdocs/societe/document.php
index f3c217d0a54b3fc35aa03abd44e6c5581b87876c..b152e6097c6a1bd0eb169d541335a80e302dc521 100644
--- a/htdocs/societe/document.php
+++ b/htdocs/societe/document.php
@@ -65,7 +65,7 @@ if ($id > 0 || ! empty($ref))
 	$result = $object->fetch($id, $ref);
 
 	$upload_dir = $conf->societe->multidir_output[$object->entity] . "/" . $object->id ;
-	$courrier_dir = $conf->societe->multidir_output[$object->entity] . "/courrier/" . get_exdir($object->id);
+	$courrier_dir = $conf->societe->multidir_output[$object->entity] . "/courrier/" . get_exdir($object->id,0,0,0,$object,'thirdparty');
 }
 
 
diff --git a/htdocs/user/card.php b/htdocs/user/card.php
index 332684a3238747911c4bdf209346fd5349ca5d05..3a561ce8ebb531b1f6feeef4aaea8ad4caaa2a0b 100644
--- a/htdocs/user/card.php
+++ b/htdocs/user/card.php
@@ -438,15 +438,15 @@ if ($action == 'update' && ! $_POST["cancel"])
             {
                 if (GETPOST('deletephoto') && $object->photo)
                 {
-                    $fileimg=$conf->user->dir_output.'/'.get_exdir($object->id,2,0,1).'/logos/'.$object->photo;
-                    $dirthumbs=$conf->user->dir_output.'/'.get_exdir($object->id,2,0,1).'/logos/thumbs';
+                    $fileimg=$conf->user->dir_output.'/'.get_exdir($object->id,2,0,1,$object,'user').'/logos/'.$object->photo;
+                    $dirthumbs=$conf->user->dir_output.'/'.get_exdir($object->id,2,0,1,$object,'user').'/logos/thumbs';
                     dol_delete_file($fileimg);
                     dol_delete_dir_recursive($dirthumbs);
                 }
 
                 if (isset($_FILES['photo']['tmp_name']) && trim($_FILES['photo']['tmp_name']))
                 {
-                    $dir= $conf->user->dir_output . '/' . get_exdir($object->id,2,0,1);
+                    $dir= $conf->user->dir_output . '/' . get_exdir($object->id,2,0,1,$object,'user');
 
                     dol_mkdir($dir);
 
diff --git a/htdocs/webservices/server_category.php b/htdocs/webservices/server_category.php
index 345679f7c9a79fb61ea2d894e4e2a0e5038fa168..2bf914ebd384003e5ffa47a8571f2319f23ab9c8 100644
--- a/htdocs/webservices/server_category.php
+++ b/htdocs/webservices/server_category.php
@@ -124,7 +124,7 @@ $server->wsdl->addComplexType(
  				)
  		)
  );
- 
+
  /*
   * An image
  */
@@ -217,7 +217,7 @@ function getCategory($authentication,$id)
 			if ($result > 0)
 			{
 					$dir = (!empty($conf->categorie->dir_output)?$conf->categorie->dir_output:$conf->service->dir_output);
-					$pdir = get_exdir($categorie->id,2) . $categorie->id ."/photos/";
+					$pdir = get_exdir($categorie->id,2,0,0,$categorie,'category') . $categorie->id ."/photos/";
 					$dir = $dir . '/'. $pdir;
 
 					$cat = array(
@@ -238,7 +238,7 @@ function getCategory($authentication,$id)
 					 	foreach($cats as $fille)
 						{
 							$dir = (!empty($conf->categorie->dir_output)?$conf->categorie->dir_output:$conf->service->dir_output);
-							$pdir = get_exdir($fille->id,2) . $fille->id ."/photos/";
+							$pdir = get_exdir($fille->id,2,0,0,$categorie,'category') . $fille->id ."/photos/";
 							$dir = $dir . '/'. $pdir;
 							$cat['filles'][] = array(
 								'id'=>$fille->id,
diff --git a/htdocs/webservices/server_productorservice.php b/htdocs/webservices/server_productorservice.php
index b7af224ff52546e74f7e3c2d13e353d279c6cf33..86891e87595afd35086c48fccba95731aebefdb7 100644
--- a/htdocs/webservices/server_productorservice.php
+++ b/htdocs/webservices/server_productorservice.php
@@ -374,7 +374,7 @@ function getProductOrService($authentication,$id='',$ref='',$ref_ext='',$lang=''
             	$product->load_stock();
 
             	$dir = (!empty($conf->product->dir_output)?$conf->product->dir_output:$conf->service->dir_output);
-            	$pdir = get_exdir($product->id,2) . $product->id ."/photos/";
+            	$pdir = get_exdir($product->id,2,0,0,$product,'product') . $product->id ."/photos/";
             	$dir = $dir . '/'. $pdir;
 
             	if (! empty($product->multilangs[$langs->defaultlang]["label"]))     		$product->label =  $product->multilangs[$langs->defaultlang]["label"];
@@ -1055,7 +1055,7 @@ function getProductsForCategory($authentication,$id,$lang='')
 						if($obj->status > 0 )
 						{
 							$dir = (!empty($conf->product->dir_output)?$conf->product->dir_output:$conf->service->dir_output);
-							$pdir = get_exdir($obj->id,2) . $obj->id ."/photos/";
+							$pdir = get_exdir($obj->id,2,0,0,$product,'product') . $obj->id ."/photos/";
 							$dir = $dir . '/'. $pdir;
 
 							$products[] = array(